@ibgib/space-gib 0.0.22 → 0.0.24

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.
@@ -1,4 +1,4 @@
1
- import{$b as Mi,Ab as Me,B as J,Bb as Ce,C as $s,Cb as Vt,D as it,Db as zs,E as an,Eb as Ks,Ec as lt,Fb as Js,Fc as er,G as Ie,Gb as dn,Gc as tr,Hb as Ni,Hc as nr,Ic as Fe,Jb as k,Jc as ir,Kb as cn,Kc as or,La as ln,Lc as sr,Nb as $i,Ob as ki,Oc as wn,Pb as Ri,Qb as qt,Rb as Di,Sb as Le,Tb as Pe,Ub as Ge,Uc as rr,V as ks,Vb as ot,W as Rs,Wa as Ds,Wc as ar,Xa as Ms,Xc as se,Ya as Ls,Yc as Et,a as p,b as nn,bd as D,c as Pi,d as xe,e as Gs,ed as lr,fc as st,fd as Be,g as on,gb as Gi,gc as un,gd as dr,h as V,hb as Se,hc as Y,i as z,ic as Ws,id as wt,j as E,jb as H,jc as Li,jd as vt,kb as W,kc as fn,kd as It,l as nt,lc as pn,mc as Ys,n as bt,nc as rt,o as yt,ob as Q,oc as at,p as sn,pc as Ui,pd as cr,q as rn,qb as Us,qc as Xs,qd as Fi,r as Ut,rb as Fs,rc as Qs,sb as Bs,sc as hn,tb as Vs,tc as mn,u as j,ub as qs,uc as Zs,v as _,vc as js,w as B,wb as Os,wc as gn,xb as Hs,xc as bn,y as Ns,yb as Bt,yc as yn,z as Ft,zb as oe,zc as En}from"./chunk-XZM4L3U6.mjs";var Ne=Q,Bi=class n{static{p(this,"IbGibComponentService")}lc=`[${n.name}]`;_registeredComponentsMeta=[];initialized;constructor(){this.initialized=this.initialize()}async initialize(){let e=`[${this.initialize.name}]`;try{Ne&&console.log(`${e} starting... (I: 1cf04e8d768f4b5c55e7c3861e2d2225)`),console.log(`${e} does nothing atow (I: 65bb46c88c82b637ad928b8bf1a07225)`)}catch(t){throw console.error(`${e} ${E(t)}`),t}finally{Ne&&console.log(`${e} complete.`)}}registerComponentMeta(e){this._registeredComponentsMeta.push(e),Ne&&console.log(`${this.lc}[registerComponentMeta] component meta registered: ${e.constructor.name} (I: 88ddcbd0c8caa2342af0e7348f171225)`)}unregisterComponentMeta(e){this._registeredComponentsMeta=this._registeredComponentsMeta.filter(t=>t!==e),Ne&&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{Ne&&console.log(`${o} starting... (I: 684ef316cbdb4a3b1fdc96096c273b25)`);let s,a=Ot.getRegisteredComponentsMeta(),d=e?a.filter(c=>{let u=c.routeRegExp?c.routeRegExp.test(t):!1;return Ne&&console.log(`${o} ${c.componentName} ${c.routeRegExp} componentMatchesPath: ${u} (I: 3758520e6a4a57f218396c8649283425)`),u}):a.concat();for(let c of d)if(c.fnHandleRoute?await c.fnHandleRoute({path:t,ibGibAddr:i}):!0){s=await c.createInstance({path:t,ibGibAddr:i});break}return s}catch(s){throw console.error(`${o} ${E(s)}`),s}finally{Ne&&console.log(`${o} complete.`)}}async inject({parentEl:e,componentToInject:t}){let i=`${this.lc}[${this.inject.name}]`;try{if(Ne&&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} ${E(o)}`),e.innerHTML=`<p class="error">Error loading component for route. error:</p><br /><br /><p>${o.message}</p>`}finally{Ne&&console.log(`${i} complete.`)}}getRegisteredComponentsMeta(){return[...this._registeredComponentsMeta]}},Ot;async function de(){let n=`[${de.name}]`;try{return Ne&&console.log(`${n} starting... (I: 853694c88223381339103a3765129925)`),Ot||(Ot=new Bi,await Ot.initialized),Ot}catch(e){throw console.error(`${n} ${E(e)}`),e}finally{Ne&&console.log(`${n} complete.`)}}p(de,"getComponentSvc");var ur="left-panel";var fr="right-panel";var pr="left-resizer",hr="right-resizer",mr="footer-resizer",gr="btn-left-panel-toggle",br="btn-right-panel-toggle",yr="btn-create-keystone",vn="center-panel-content";var qi=class{static{p(this,"KeystoneSyncService")}lc="[KeystoneSyncService]";dispatchUpdateAvailableEvent(e){typeof window<"u"&&window.dispatchEvent(new CustomEvent(Vt,{detail:e,bubbles:!0,composed:!0}))}dispatchRenewalRequiredEvent(e){typeof window<"u"&&window.dispatchEvent(new CustomEvent(zs,{detail:e,bubbles:!0,composed:!0}))}async getDeviceDelegateSecret({primaryTjpAddr:e}){return Ui({primaryTjpAddr:e})}async checkDelegateStatus({activePrimaryAddr:e,metaspace:t,space:i}){let o=`${this.lc}[${this.checkDelegateStatus.name}]`;try{if(t||(t=await k()),!t)throw new Error(`${o} (UNEXPECTED) metaspace falsy? (E: a1b2c3d4e5f60718293a4b5c6d7e8f90)`);if(i||(i=await t.getLocalUserSpace({lock:!1})),!i)throw new Error(`${o} (UNEXPECTED) space falsy? (E: b2c3d4e5f60718293a4b5c6d7e8f90a1)`);let s=J({ibGibAddr:e}),{ib:a}=B({ibGibAddr:e}),d=s.tjpGib?`${a}^${s.tjpGib}`:e;if(!await Ui({primaryTjpAddr:d}))return this.dispatchRenewalRequiredEvent({activePrimaryAddr:e,primaryTjpAddr:d,reason:"missing_secret"}),{isValid:!1,reason:"missing_secret"};let f=await new Y().getLatestKeystone({addr:e,metaspace:t,space:i});if(!f)throw new Error(`${o} (UNEXPECTED) latest primary keystone not found for addr: ${e} (E: c3d4e5f60718293a4b5c6d7e8f90a1b2)`);return f?.data?.delegates&&Object.values(f.data.delegates).some(g=>fn({delegateInfo:g}))?(this.dispatchRenewalRequiredEvent({activePrimaryAddr:e,primaryTjpAddr:d,reason:"expired"}),{isValid:!1,reason:"expired"}):{isValid:!0}}catch(s){return console.error(`${o} ${E(s)}`),{isValid:!1}}}async checkForKeystoneUpdate({activePrimaryAddr:e,metaspace:t,space:i}){let o=`${this.lc}[${this.checkForKeystoneUpdate.name}]`;try{if(t||(t=await k()),!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}),d=a.success&&a.ibGibs&&a.ibGibs.length>0?a.ibGibs[0]:void 0,c=d?.data?.n??0,{ib:u}=B({ibGibAddr:e}),f=J({ibGibAddr:e}),h=f.tjpGib?`${u}^${f.tjpGib}`:e,m=(d?H({ibGib:d}):void 0)||h,g=await D().getKeystoneGraph(m);if(!g.success||!g.graph){let N={hasUpdate:!1,serverN:c,localN:c,serverLatestAddr:s,graph:{}};return this.dispatchUpdateAvailableEvent({activePrimaryAddr:e,hasUpdate:N.hasUpdate,serverN:N.serverN,localN:N.localN,serverLatestAddr:N.serverLatestAddr}),N}let b=g.graph,y=Object.values(b),w=Se({ibGibs:y}),v=w[m]||w[e]||w[Object.keys(w)[0]]||[];if(v.length===0){let N={hasUpdate:!1,serverN:c,localN:c,serverLatestAddr:s,graph:b};return this.dispatchUpdateAvailableEvent({activePrimaryAddr:e,hasUpdate:N.hasUpdate,serverN:N.serverN,localN:N.localN,serverLatestAddr:N.serverLatestAddr}),N}let I=[...v].sort((N,P)=>(N.data?.n??0)-(P.data?.n??0)),C=I[I.length-1],T=C.data?.n??0,x=_({ibGib:C}),S={hasUpdate:T>c,serverN:T,localN:c,serverLatestAddr:x,graph:b};return this.dispatchUpdateAvailableEvent({activePrimaryAddr:e,hasUpdate:S.hasUpdate,serverN:S.serverN,localN:S.localN,serverLatestAddr:S.serverLatestAddr}),S}catch(s){console.error(`${o} ${E(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 k()),!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 c=Object.values(s.graph);await t.put({ibGibs:c,space:i});let u=Se({ibGibs:c});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=J({ibGibAddr:e}).tjpGib??e,m=[...u[f]||u[e]||u[Object.keys(u)[0]]].sort((b,y)=>(b.data?.n??0)-(y.data?.n??0)),g=m[m.length-1];if(g)return await se({type:"keystones",rel8nInfos:[{rel8nName:"keystone",ibGibs:[W({ibGib:g})]}],metaspace:t,space:i}),g}let a=await t.getLatestAddr({addr:e,space:i})||e,d=await t.get({addrs:[a],space:i});return d.success&&d.ibGibs&&d.ibGibs.length>0?d.ibGibs[0]:void 0}catch(s){throw console.error(`${o} ${E(s)}`),s}}},Vi;function dt(){return Vi||(Vi=new qi),Vi}p(dt,"getKeystoneSyncService");var Er=`:host {
1
+ import{$b as Ui,A as Ft,Ab as zs,Ac as at,Bb as Ks,Bc as Oi,Bd as gr,C as W,Cb as Ws,Cc as nr,Cd as qi,D as Ls,Dc as ir,Dd as br,E as it,Eb as Js,Ec as yn,F as ln,Fb as Ys,Fc as En,Gb as Bt,Gc as or,H as Ie,Hb as se,Hc as sr,Ib as Me,Ic as wn,Jb as Ce,Jc as vn,Kb as Vt,Kc as In,Lb as Xs,Lc as Cn,Ma as cn,Mb as dn,Nb as un,Ob as fn,Pb as Qs,Qb as Zs,Qc as lt,Rb as js,Rc as rr,Sb as pn,Sc as ar,Tb as Di,Tc as lr,Uc as Be,Vb as k,Vc as cr,W as Us,Wb as hn,Wc as dr,X as Fs,Xa as Bs,Xc as ur,Ya as Vs,Za as Os,Zb as Mi,_b as Li,_c as Tn,a as p,ac as Ot,b as on,bc as Fi,c as ki,cc as Le,d as xe,dc as Pe,e as Ds,ec as Ne,ed as fr,fc as ot,g as sn,gd as pr,h as V,hd as re,i as z,id as Et,j as E,kb as Ri,l as nt,lb as Se,lc as Bi,n as bt,nb as H,nd as D,o as yt,ob as J,q as rn,qd as hr,r as an,rc as st,rd as Ve,s as Ut,sc as mn,sd as mr,tc as Y,uc as er,ud as wt,v as Z,vc as Vi,vd as vt,w as _,wb as Q,wc as gn,wd as It,x as B,xc as bn,yb as qs,yc as tr,z as Ms,zb as Hs,zc as rt}from"./chunk-7PVWSU7S.mjs";var Ge=Q,Hi=class n{static{p(this,"IbGibComponentService")}lc=`[${n.name}]`;_registeredComponentsMeta=[];initialized;constructor(){this.initialized=this.initialize()}async initialize(){let e=`[${this.initialize.name}]`;try{Ge&&console.log(`${e} starting... (I: 1cf04e8d768f4b5c55e7c3861e2d2225)`),console.log(`${e} does nothing atow (I: 65bb46c88c82b637ad928b8bf1a07225)`)}catch(t){throw console.error(`${e} ${E(t)}`),t}finally{Ge&&console.log(`${e} complete.`)}}registerComponentMeta(e){this._registeredComponentsMeta.push(e),Ge&&console.log(`${this.lc}[registerComponentMeta] component meta registered: ${e.constructor.name} (I: 88ddcbd0c8caa2342af0e7348f171225)`)}unregisterComponentMeta(e){this._registeredComponentsMeta=this._registeredComponentsMeta.filter(t=>t!==e),Ge&&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{Ge&&console.log(`${o} starting... (I: 684ef316cbdb4a3b1fdc96096c273b25)`);let s,a=qt.getRegisteredComponentsMeta(),c=e?a.filter(d=>{let u=d.routeRegExp?d.routeRegExp.test(t):!1;return Ge&&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} ${E(s)}`),s}finally{Ge&&console.log(`${o} complete.`)}}async inject({parentEl:e,componentToInject:t}){let i=`${this.lc}[${this.inject.name}]`;try{if(Ge&&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} ${E(o)}`),e.innerHTML=`<p class="error">Error loading component for route. error:</p><br /><br /><p>${o.message}</p>`}finally{Ge&&console.log(`${i} complete.`)}}getRegisteredComponentsMeta(){return[...this._registeredComponentsMeta]}},qt;async function ne(){let n=`[${ne.name}]`;try{return Ge&&console.log(`${n} starting... (I: 853694c88223381339103a3765129925)`),qt||(qt=new Hi,await qt.initialized),qt}catch(e){throw console.error(`${n} ${E(e)}`),e}finally{Ge&&console.log(`${n} complete.`)}}p(ne,"getComponentSvc");var yr="left-panel";var Er="right-panel";var wr="left-resizer",vr="right-resizer",Ir="footer-resizer",Cr="btn-left-panel-toggle",Tr="btn-right-panel-toggle",Sr="btn-create-keystone",Ht="center-panel-content";var Ki=class{static{p(this,"KeystoneSyncService")}lc="[KeystoneSyncService]";dispatchUpdateAvailableEvent(e){typeof window<"u"&&window.dispatchEvent(new CustomEvent(Vt,{detail:e,bubbles:!0,composed:!0}))}dispatchRenewalRequiredEvent(e){typeof window<"u"&&window.dispatchEvent(new CustomEvent(Xs,{detail:e,bubbles:!0,composed:!0}))}async getDeviceDelegateSecret({primaryTjpAddr:e}){return Oi({primaryTjpAddr:e})}async checkDelegateStatus({activePrimaryAddr:e,metaspace:t,space:i}){let o=`${this.lc}[${this.checkDelegateStatus.name}]`;try{if(t||(t=await k()),!t)throw new Error(`${o} (UNEXPECTED) metaspace falsy? (E: genuuid)`);if(i||(i=await t.getLocalUserSpace({lock:!1})),!i)throw new Error(`${o} (UNEXPECTED) space falsy? (E: genuuid)`);let s=W({ibGibAddr:e}),{ib:a}=B({ibGibAddr:e}),c=s.tjpGib?`${a}^${s.tjpGib}`:e;if(!await Oi({primaryTjpAddr:c}))return this.dispatchRenewalRequiredEvent({activePrimaryAddr:e,primaryTjpAddr:c,reason:"missing_secret"}),{isValid:!1,reason:"missing_secret"};let f=await new Y().getLatestKeystone({addr:e,metaspace:t,space:i});if(!f)throw new Error(`${o} (UNEXPECTED) latest primary keystone not found for addr: ${e} (E: genuuid)`);return f?.data?.delegates&&Object.values(f.data.delegates).some(g=>gn({delegateInfo:g}))?(this.dispatchRenewalRequiredEvent({activePrimaryAddr:e,primaryTjpAddr:c,reason:"expired"}),{isValid:!1,reason:"expired"}):{isValid:!0}}catch(s){return console.error(`${o} ${E(s)}`),{isValid:!1}}}async checkForKeystoneUpdate({activePrimaryAddr:e,metaspace:t,space:i}){let o=`${this.lc}[${this.checkForKeystoneUpdate.name}]`;try{if(t||(t=await k()),!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}=B({ibGibAddr:e}),f=W({ibGibAddr:e}),h=f.tjpGib?`${u}^${f.tjpGib}`:e,m=(c?H({ibGib:c}):void 0)||h,g=await D().getKeystoneGraph(m);if(!g.success||!g.graph){let G={hasUpdate:!1,serverN:d,localN:d,serverLatestAddr:s,graph:{}};return this.dispatchUpdateAvailableEvent({activePrimaryAddr:e,hasUpdate:G.hasUpdate,serverN:G.serverN,localN:G.localN,serverLatestAddr:G.serverLatestAddr}),G}let b=g.graph,y=Object.values(b),w=Se({ibGibs:y}),v=w[m]||w[e]||w[Object.keys(w)[0]]||[];if(v.length===0){let G={hasUpdate:!1,serverN:d,localN:d,serverLatestAddr:s,graph:b};return this.dispatchUpdateAvailableEvent({activePrimaryAddr:e,hasUpdate:G.hasUpdate,serverN:G.serverN,localN:G.localN,serverLatestAddr:G.serverLatestAddr}),G}let I=[...v].sort((G,P)=>(G.data?.n??0)-(P.data?.n??0)),C=I[I.length-1],T=C.data?.n??0,x=_({ibGib:C}),S={hasUpdate:T>d,serverN:T,localN:d,serverLatestAddr:x,graph:b};return this.dispatchUpdateAvailableEvent({activePrimaryAddr:e,hasUpdate:S.hasUpdate,serverN:S.serverN,localN:S.localN,serverLatestAddr:S.serverLatestAddr}),S}catch(s){console.error(`${o} ${E(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 k()),!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=Se({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,y)=>(b.data?.n??0)-(y.data?.n??0)),g=m[m.length-1];if(g)return await re({type:"keystones",rel8nInfos:[{rel8nName:"keystone",ibGibs:[J({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} ${E(s)}`),s}}},zi;function ct(){return zi||(zi=new Ki),zi}p(ct,"getKeystoneSyncService");var _r=`:host {
2
2
  display: inline-block;
3
3
  vertical-align: middle;
4
4
  position: relative;
@@ -315,7 +315,7 @@ import{$b as Mi,Ab as Me,B as J,Bb as Ce,C as $s,Cb as Vt,D as it,Db as zs,E as
315
315
  display: none !important;
316
316
  }
317
317
 
318
- `;var wr=`<div id="container" class="header-widget-container">
318
+ `;var Ar=`<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{$b as Mi,Ab as Me,B as J,Bb as Ce,C as $s,Cb as Vt,D as it,Db as zs,E 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 me=`/* =========================================================================
389
+ </div>`;var ue=`/* =========================================================================
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,39 +656,39 @@ import{$b as Mi,Ab as Me,B as J,Bb as Ce,C as $s,Cb as Vt,D as it,Db as zs,E as
656
656
  word-break: break-all;
657
657
  color: var(--clr-accent);
658
658
  }
659
- `;var K=!1,In=class n extends dr{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{K&&console.log(`${e} starting... (I: f0e65ab0f80046a59668ddfbf9f47a4a5)`),await super.initialize()}catch(t){console.error(`${e} ${E(t)}`)}finally{K&&console.log(`${e} complete.`)}}async loadNewerSelfIfAvailable(){let e=`${this.lc}[${this.loadNewerSelfIfAvailable.name}]`;try{if(K&&console.log(`${e} starting... (I: 94755c3131f4dfa12d20fa38e2926522)`),this.metaspace){let t=_({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: ${V(s)} (E: 0d9f0684a1ff6af44e20a57130e3ac22)`)}}else console.warn(`${e} this.metaspace undefined (W: 44cc5bf1b14b4695b8de4c589787be06)`)}catch(t){throw console.error(`${e} ${E(t)}`),t}finally{K&&console.log(`${e} complete.`)}}async rel8To({ibGibs:e,rel8nName:t,linked:i,metaspace:o}){let s=`${this.lc}[${this.rel8To.name}]`;try{if(K&&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 c=(this.rel8ns?this.rel8ns[t]??[]:[]).map(b=>J({ibGibAddr:b}).tjpGib),u=e.filter(b=>{let y=J({ibGibAddr:_({ibGib:b})}).tjpGib;return!c.includes(y)});if(u.length===0){K&&console.log(`${s} already rel8d to all incoming ibGib(s) via tjp. (I: 5e9d94a98ba262f146c0c0b765157922)`);return}let f=u.map(b=>_({ibGib:b})),h=await it({src:this.toIbGibDto(),rel8nsToAddByAddr:{[t]:f},linkedRel8ns:i?["past","ancestor",t]:["past","ancestor"],dna:!0,nCounter:!0}),m=h.newIbGib,g=await an({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} ${E(a)}`),a}finally{K&&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||_({ibGib:e}),o.forEach(u=>{a[u]=[t]});let d=await it({src:i,rel8nsToAddByAddr:a,dna:!0,nCounter:!0});await this.metaspace.persistTransformResult({resTransform:d});let{newIbGib:c}=d;await this.metaspace.registerNewIbGib({ibGib:c})}catch(a){throw console.error(`${s} ${E(a)}`),a}}async createCommentAndRel8ToContextIbGib({text:e,contextIbGib:t,rel8nName:i}){let o=`${this.lc}[${this.createCommentAndRel8ToContextIbGib.name}]`;try{if(K&&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 vt({text:e,addlMetadataText:this.getAddlMetadata(),saveInSpace:!0,space:s});s=await this.metaspace.getLocalUserSpace({lock:!0});let d=a.newIbGib;if(!d)throw new Error("(UNEXPECTED) failed to create comment? (E: 6d668f4e55198e654324622eabaac922)");await this.metaspace.registerNewIbGib({ibGib:d}),await this.rel8ToContextIbGib({ibGibToRel8:d,contextIbGib:t,rel8nNames:["comment"]}),await this.rel8To({ibGibs:[d],rel8nName:i})}catch(s){throw console.error(`${o} ${E(s)}`),s}finally{K&&console.log(`${o} complete.`)}}getThisAtom(){return bt({text:this.data?.classname??"this",length:16})}getAddlMetadata(){let e=`${this.lc}[${this.getAddlMetadata.name}]`;try{if(K&&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 K&&console.log(`${e} addlMetadataText: ${a} (I: 53c0044671dc99fb75635367d2e63c22)`),a}catch(t){throw console.error(`${e} ${E(t)}`),t}finally{K&&console.log(`${e} complete.`)}}async getContextIbGibFromArgOrAddr({arg:e,addr:t,latest:i}){let o=`${this.lc}[${this.getContextIbGibFromArgOrAddr.name}]`;try{K&&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!==_({ibGib:s})){let d=await this.metaspace.get({addr:a});if(d.success&&d.ibGibs?.length===1)s=d.ibGibs[0];else throw new Error(`unable to get resLatestAddr (${a}) (E: ce1e1297743e9a16c8f082321e52a122)`)}}return s}catch(s){throw console.error(`${o} ${E(s)}`),s}finally{K&&console.log(`${o} complete.`)}}async initializeContext({arg:e,contextIbGib:t,rel8nName:i}){let o=`${this.lc}[${this.initializeContext.name}]`;try{if(K&&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 c=H({ibGib:this._currentWorkingContextIbGib}),u=H({ibGib:s});if(c===u){K&&console.warn(`${o} initializing context but it's the same timeline (${c}). (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:_({ibGib:t}),latest:!0}):await this.getContextIbGibFromArgOrAddr({arg:e,latest:!0}),a();let d=H({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(Be({next:p(async c=>{let u=`${o}[latestObs.next]`;if(c.tjpAddr!==d)return;let f=_({ibGib:this._currentWorkingContextIbGib});if(c.latestAddr!==f){if(K&&console.warn(`${u} checking if new context is actually new...damn getLatestAddr maybe not working in ionic space... argh (W: 3d1a12154dfafb9c96d07e6f75f7a322)`),c.latestIbGib){let h=c.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: ${c.tjpAddr}) (W: 6792c9a596c44c03b262614ae79a715e)`);return}}K&&console.log(`${u} update to context.
659
+ `;var K=!1,Sn=class n extends mr{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{K&&console.log(`${e} starting... (I: f0e65ab0f80046a59668ddfbf9f47a4a5)`),await super.initialize()}catch(t){console.error(`${e} ${E(t)}`)}finally{K&&console.log(`${e} complete.`)}}async loadNewerSelfIfAvailable(){let e=`${this.lc}[${this.loadNewerSelfIfAvailable.name}]`;try{if(K&&console.log(`${e} starting... (I: 94755c3131f4dfa12d20fa38e2926522)`),this.metaspace){let t=_({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: ${V(s)} (E: 0d9f0684a1ff6af44e20a57130e3ac22)`)}}else console.warn(`${e} this.metaspace undefined (W: 44cc5bf1b14b4695b8de4c589787be06)`)}catch(t){throw console.error(`${e} ${E(t)}`),t}finally{K&&console.log(`${e} complete.`)}}async rel8To({ibGibs:e,rel8nName:t,linked:i,metaspace:o}){let s=`${this.lc}[${this.rel8To.name}]`;try{if(K&&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 y=W({ibGibAddr:_({ibGib:b})}).tjpGib;return!d.includes(y)});if(u.length===0){K&&console.log(`${s} already rel8d to all incoming ibGib(s) via tjp. (I: 5e9d94a98ba262f146c0c0b765157922)`);return}let f=u.map(b=>_({ibGib:b})),h=await it({src:this.toIbGibDto(),rel8nsToAddByAddr:{[t]:f},linkedRel8ns:i?["past","ancestor",t]:["past","ancestor"],dna:!0,nCounter:!0}),m=h.newIbGib,g=await ln({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} ${E(a)}`),a}finally{K&&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||_({ibGib:e}),o.forEach(u=>{a[u]=[t]});let c=await it({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} ${E(a)}`),a}}async createCommentAndRel8ToContextIbGib({text:e,contextIbGib:t,rel8nName:i}){let o=`${this.lc}[${this.createCommentAndRel8ToContextIbGib.name}]`;try{if(K&&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 vt({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} ${E(s)}`),s}finally{K&&console.log(`${o} complete.`)}}getThisAtom(){return bt({text:this.data?.classname??"this",length:16})}getAddlMetadata(){let e=`${this.lc}[${this.getAddlMetadata.name}]`;try{if(K&&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 K&&console.log(`${e} addlMetadataText: ${a} (I: 53c0044671dc99fb75635367d2e63c22)`),a}catch(t){throw console.error(`${e} ${E(t)}`),t}finally{K&&console.log(`${e} complete.`)}}async getContextIbGibFromArgOrAddr({arg:e,addr:t,latest:i}){let o=`${this.lc}[${this.getContextIbGibFromArgOrAddr.name}]`;try{K&&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!==_({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} ${E(s)}`),s}finally{K&&console.log(`${o} complete.`)}}async initializeContext({arg:e,contextIbGib:t,rel8nName:i}){let o=`${this.lc}[${this.initializeContext.name}]`;try{if(K&&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=H({ibGib:this._currentWorkingContextIbGib}),u=H({ibGib:s});if(d===u){K&&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:_({ibGib:t}),latest:!0}):await this.getContextIbGibFromArgOrAddr({arg:e,latest:!0}),a();let c=H({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(Ve({next:p(async d=>{let u=`${o}[latestObs.next]`;if(d.tjpAddr!==c)return;let f=_({ibGib:this._currentWorkingContextIbGib});if(d.latestAddr!==f){if(K&&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}}K&&console.log(`${u} update to context.
660
660
  currentAddr: ${f}
661
- latestAddr: ${c.latestAddr} (I: d0adcc392e6e974c9917730ebad51322)`),this._currentWorkingContextIbGib=c.latestIbGib??await this.getContextIbGibFromArgOrAddr({addr:c.latestAddr,latest:!1}),this._updatingContext?K&&console.log(`${u} already updating context (I: f856f9414627ab00418dccd285b55822)`):(await this.handleContextUpdate({update:c}),a())}},"next"),error:p(async c=>{let u=`${o}[latestObs.error]`;console.error(`${u} this.metaspace.latestObs error: ${lr({err:c})}. (E: 99df4c42195d46d0a9dbfb06ac45ae00)`)},"error")})),i&&await this.rel8To({ibGibs:[this._currentWorkingContextIbGib],rel8nName:i})}catch(s){throw console.error(`${o} ${E(s)}`),s}finally{K&&console.log(`${o} complete.`)}}async finalizeContext({arg:e}){let t=`${this.lc}[${this.finalizeContext.name}]`;try{K&&console.log(`${t} starting... (I: dd53dfc745864dd19fde5f209ceb82c8)`);let i=0,o=100;for(;this._updatingContext&&i<o;)await z(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} ${E(i)}`),i}finally{this._updatingContext=!1,K&&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 z(1e3);this._updatingContext=!0;try{if(K&&console.log(`${t} starting... (I: 3eeaa40cad49094f125f9f5cd6ff6e22)`),K&&(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{K&&console.log(`${t} no new children in context update. returning early... (I: 31397b04965351ab29bb3f78cb709122)`);return}}catch(i){throw console.error(`${t} ${E(i)}`),i}finally{this._updatingContext=!1,K&&console.log(`${t} complete.`)}}async getNewChildrenIbGibs({newContext:e}){let t=`${this.lc}[${this.getNewChildrenIbGibs.name}]`;try{K&&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 K&&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 Ls({addrs:o,space:s}),d=Object.values(a?.data?.latestAddrsMap??{});if(!a?.data?.success||d.length!==o.length)throw new Error("could not get latest addrs. (E: 2e1619e7e2e166696fe8ff78cb02cc22)");if(d.some(u=>u===null))throw new Error("some addrs were not found in the space. (E: 2216d8e5ad7fb600ceb025ed7c90f323)");let c=await this.metaspace.get({addrs:d});if(!c.success||c.ibGibs?.length!==o.length)throw new Error(`failed to get newChildren with addrs: ${o.join("|")}. Error: ${c.errorMsg??"unknown error 5737bd0996d5445b8bd80975bedc0d57"} (E: 05722e11350ec6ffffdb5c7d0caa2922)`);return c.ibGibs}catch(i){throw console.error(`${t} ${E(i)}`),i}finally{K&&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} ${E(i)}`),i}}};var ce=Q,ze=class extends In{static{p(this,"LiveProxyIbGib")}lc="";ib=this._currentWorkingContextIbGib?this._currentWorkingContextIbGib.ib:sn;gib=this._currentWorkingContextIbGib?this._currentWorkingContextIbGib.gib:rn;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{ce&&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} ${E(t)}`),t}finally{ce&&console.log(`${e} complete.`)}}async loadIbGibDto(e){let t=`${this.lc}[${this.loadIbGibDto.name}]`;try{ce&&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} ${E(i)}`),i}finally{ce&&console.log(`${t} complete.`)}}async validateThis(){let e=`${this.lc}[${this.validateThis.name}]`;return ce&&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{ce&&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} ${E(t)}`),t}finally{ce&&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(ce&&console.log(`${t} starting...`),Ds({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,ce&&console.log(`${t} spaceId set to the ${i} (I: 018724a5431ba421b71fad36924c5a25)`),Ie.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}),Ut}}catch(i){throw console.error(`${t} ${i.message}`),i}finally{ce&&console.log(`${t} complete.`)}}_contextUpdated$;contextUpdated$;_newContextChild$;newContextChild$;async handleContextUpdate({update:e}){let t=`${this.lc}[${this.handleContextUpdate.name}]`;try{if(ce&&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} ${E(i)}`),i}finally{ce&&console.log(`${t} complete.`)}}async setWrappedIbGib({ibGib:e,ibGibAddr:t,space:i}){let o=`${this.lc}[${this.setWrappedIbGib.name}]`;try{if(ce&&console.log(`${o} starting... (I: a4b0acda259c121801aa701534320125)`),this.metaspace||(this.metaspace=await k()),!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} ${E(s)}`),s}finally{ce&&console.log(`${o} complete.`)}}async handleNewContextChild({newChild:e}){let t=`[${this.handleNewContextChild.name}]`;try{if(ce&&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} ${E(i)}`),i}finally{ce&&console.log(`${t} complete.`)}}};var Ct="witness_agent",Tt=/^[a-zA-Z0-9_\-.]{1,32}$/,Hi=/.{1,255}/,vr="",Ir="Manco",Cr="This is a generic, unspecified agent.";var Cn="List of function info ibgib addresses. These contain info on both the requests you made and the resultant values.",ct="agent",Cb={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 hd="hardcoded",md="human",gd="ai",bd="function",yd="unknown",ee={HARDCODED:hd,HUMAN:md,AI:gd,FUNCTION:bd,UNKNOWN:yd},zi=Object.freeze(Object.values(ee));function Tr(n){return!!n&&zi.includes(n)}p(Tr,"isTextSource");var Sb={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: ${Tt.source}`},Sr="primaryagent";var _r=!1;async function Ki({ibGib:n,addr:e,tagIbGib:t,metaspace:i,space:o}){let s=`[${Ki.name}]`;try{if(_r&&console.log(`${s} starting... (I: b1fd25ec28bce8f1916b4ab55f48a724)`),!e&&!n)throw new Error("either addr or ibGib required (E: 3d580f8ecc251a0c81c7ea8bc3d38524)");if(e??=_({ibGib:n}),e!==_({ibGib:n}))throw new Error(`addr (${e}) differs from incoming ibGib's addr (${_({ibGib:n})}). (E: f2c14234a78c917fb9f587beaee89324)`);let a=await i.getLatestAddr({ibGib:t,space:o});if(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 d={[Rs]:[e]},c=await it({src:t,rel8nsToAddByAddr:d,dna:!0,nCounter:!0}),u=c.newIbGib;return await i.persistTransformResult({resTransform:c,space:o}),await i.registerNewIbGib({ibGib:u,space:o}),u}catch(a){throw console.error(`${s} ${E(a)}`),a}finally{_r&&console.log(`${s} complete.`)}}p(Ki,"rel8ToTag");var re=Q,Wi=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;re&&console.log(`${t} starting... (I: 0c4214b4614a43bd2825978e54aee325)`);let a=this.latestAgents.get(i);if(!a){let d=await k();a=(await Tn({metaspace:d,type:o,spaceId:s})).find(u=>u.data.uuid===i)}return a||console.warn(`${t} couldn't find any agent by id. opts: ${V(e)} (W: 70cf51ecbe68dfdcfe1e9995a7468f25)`),a}catch(i){throw console.error(`${t} ${E(i)}`),i}finally{re&&console.log(`${t} complete.`)}}async updateOrSetLatestAgent({agent:e,throwIfNewerFound:t}){let i=`${this.lc}[${this.updateOrSetLatestAgent.name}]`;try{if(re&&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.
662
- existing: ${V(W({ibGib:o}))}
663
- new: ${V(W({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} ${E(o)}`),o}finally{re&&console.log(`${i} complete.`)}}getLatestAgent({id:e}){let t=`${this.lc}[${this.getLatestAgent.name}]`;try{return re&&console.log(`${t} starting... (I: 8e85b55057760b712a913a92e88ead25)`),Promise.resolve(this.latestAgents.get(e))}catch(i){throw console.error(`${t} ${E(i)}`),i}finally{re&&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(re&&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 d=this.factoryFns[a],c=await d(e);if(c.applies){if(!c.agent)throw new Error("(UNEXPECTED) factory function for agent dto applies: true, but the resulting agent is undefined? (E: 60e97c083a668baf11efcd6adf6a3525)");o=c.agent;break}}}return o}catch(o){throw console.error(`${i} ${E(o)}`),o}finally{re&&console.log(`${i} complete.`)}}async getAgentByAddr({agentAddr:e,spaceId:t,metaspace:i}){let o=`${this.lc}[${this.getAgentByAddr.name}]`;try{if(re&&console.log(`${o} starting... (I: 42dfecbe6d6b5a3a7d392af5a66cc625)`),!e)throw new Error(`${o} agentAddr is required. (E: 389351659a2e08fa179ceede16925a25)`);let{ib:s}=B({ibGibAddr:e}),{uuid:a,type:d}=Ar({ib:s});if(!a){debugger;throw new Error(`(UNEXPECTED) agentAddr doesn't have uuid in the ib? agentAddr: ${e} (E: fedcacffed98fdc78b1e80e45c413925)`)}let c=await this.getAgentById({agentId:a,agentType:d});if(c)return re&&console.log(`${o} agent found already in agents svc so didn't need to go get it from the space. (I: ec6abaf3badd8e301d79a7476845bc25)`),c;i??=await k();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){re&&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}),re&&console.log(`${o} Cached agent witness with id ${a}. (I: b862f63147a3fac3c6e6210d5ab87c25)`),re&&console.log(`${o} complete. Retrieved and cached agent witness for address ${e}.`),m}catch(s){throw console.error(`${o} ${E(s)}`),s}}async createNewAgent(e){let t=`[${this.createNewAgent.name}]`;try{re&&console.log(`${t} starting... (I: a3e07b54bb7bf45f7739eff2d738c825)`);let{metaspace:i,superSpace:o,name:s,availableFunctions:a,initialSystemText:d,initialChatText:c,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=Xi(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 y=await m.createInitialRel8ns(),w=await Ie.firstGen({ib:Qi({data:g}),parentIbGib:Ie.primitive({ib:Ct}),data:g,rel8ns:y,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 T=await Yi({metaspace:i,space:o}),x=await Ki({ibGib:v,metaspace:i,space:o,tagIbGib:T})}await se({type:h,rel8nInfos:[{rel8nName:ct,ibGibs:[v]}],metaspace:i,space:o}),a.length>0&&await I.addAvailableFunctions(a);let C=[];return C.push({textSrc:"hardcoded",text:St({tagText:qs,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}),d&&C.push({textSrc:"hardcoded",text:d,isSystem:!0}),c&&C.push({textSrc:"hardcoded",text:c}),await I.addTexts({infos:C}),this.latestAgents.set(I.data.uuid,I),I}catch(i){throw console.error(`${t} ${E(i)}`),i}finally{re&&console.log(`${t} complete.`)}}getAgents(e){let t=`${this.lc}[${this.getAgents.name}]`;try{return re&&console.log(`${t} starting... (I: 4663f125c3a21fa3ecccc2c5a38d1225)`),Tn(e)}catch(i){throw console.error(`${t} ${E(i)}`),i}finally{re&&console.log(`${t} complete.`)}}},Ji;function Ue(){return Ji||(Ji=new Wi),Ji}p(Ue,"getAgentsSvc");var Ed="gemini-3.1-pro-preview",wd="gemini-3-flash-preview",vd="gemini-3.1-flash-lite-preview",Id="gemini-3.1-flash-live-preview",Cd="gemini-2.5-pro",Td="gemini-2.5-flash",Sd="gemini-2.5-flash-lite",_d="gemini-2.5-flash-preview-tts",Ad="gemini-2.0-flash",xd="gemini-2.0-flash-lite",Zi={GEMINI_3_1_PRO_PREVIEW:Ed,GEMINI_3_FLASH_PREVIEW:wd,GEMINI_3_1_FLASH_LITE_PREVIEW:vd,GEMINI_3_1_FLASH_LIVE_PREVIEW:Id,GEMINI_2_5_PRO:Cd,GEMINI_2_5_FLASH:Td,GEMINI_2_5_FLASH_LITE:Sd,GEMINI_2_5_FLASH_PREVIEW_TTS:_d,GEMINI_2_0_FLASH:Ad,GEMINI_2_0_FLASH_LITE:xd},Jb=Object.freeze(Object.values(Zi));var xr=Zi.GEMINI_2_5_FLASH,_t=Zi.GEMINI_2_5_FLASH_LITE,ji=5;var Pr={version:"1",uuid:vr,name:Ir,description:Cr,classname:"AgentWitness_V1",icon:"happy",persistOptsAndResultIbGibs:!1,allowPrimitiveArgs:!0,catchAllErrors:!0,trace:!1,subSpaceId:"",superSpaceId:"",availableFunctionNameOrIds:[],model:xr,api:"gemini",type:Sr,"@currentContextTjpAddr":j},eo=void 0;var Pd,Gd;function Nd(){return{geminiUrl:Pd,vertexUrl:Gd}}p(Nd,"getDefaultBaseUrls");function $d(n,e,t,i){var o,s;if(!n?.baseUrl){let a=Nd();return e?(o=a.vertexUrl)!==null&&o!==void 0?o:t:(s=a.geminiUrl)!==null&&s!==void 0?s:i}return n.baseUrl}p($d,"getBaseUrl");var Re=class{static{p(this,"BaseModule")}};function A(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(A,"formatMap");function l(n,e,t){for(let s=0;s<e.length-1;s++){let a=e[s];if(a.endsWith("[]")){let d=a.slice(0,-2);if(!(d in n))if(Array.isArray(t))n[d]=Array.from({length:t.length},()=>({}));else throw new Error(`Value must be a list given an array path ${a}`);if(Array.isArray(n[d])){let c=n[d];if(Array.isArray(t))for(let u=0;u<c.length;u++){let f=c[u];l(f,e.slice(s+1),t[u])}else for(let u of c)l(u,e.slice(s+1),t)}return}else if(a.endsWith("[0]")){let d=a.slice(0,-3);d in n||(n[d]=[{}]);let c=n[d];l(c[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(d=>r(d,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 kd(n,e){for(let[t,i]of Object.entries(e)){let o=t.split("."),s=i.split("."),a=new Set,d=-1;for(let c=0;c<o.length;c++)if(o[c]==="*"){d=c;break}if(d!==-1&&s.length>d)for(let c=d;c<s.length;c++){let u=s[c];u!=="*"&&!u.endsWith("[]")&&!u.endsWith("[0]")&&a.add(u)}oo(n,o,s,0,a)}}p(kd,"moveValueByPath");function oo(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),d=n;if(a in d&&Array.isArray(d[a]))for(let c of d[a])oo(c,e,t,i+1,o)}else if(s==="*"){if(typeof n=="object"&&n!==null&&!Array.isArray(n)){let a=n,d=Object.keys(a).filter(u=>!u.startsWith("_")&&!o.has(u)),c={};for(let u of d)c[u]=a[u];for(let[u,f]of Object.entries(c)){let h=[];for(let m of t.slice(i))m==="*"?h.push(u):h.push(m);l(a,h,f)}for(let u of d)delete a[u]}}else{let a=n;s in a&&oo(a[s],e,t,i+1,o)}}p(oo,"_moveValueRecursive");function is(n){if(typeof n!="string")throw new Error("fromImageBytes must be a string");return n}p(is,"tBytes$1");function Rd(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(Rd,"fetchPredictOperationParametersToVertex");function Dd(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"],Ld(a)),e}p(Dd,"generateVideosOperationFromMldev$1");function Md(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"],Ud(a)),e}p(Md,"generateVideosOperationFromVertex$1");function Ld(n){let e={},t=r(n,["generatedSamples"]);if(t!=null){let s=t;Array.isArray(s)&&(s=s.map(a=>Fd(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(Ld,"generateVideosResponseFromMldev$1");function Ud(n){let e={},t=r(n,["videos"]);if(t!=null){let s=t;Array.isArray(s)&&(s=s.map(a=>Bd(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(Ud,"generateVideosResponseFromVertex$1");function Fd(n){let e={},t=r(n,["video"]);return t!=null&&l(e,["video"],Kd(t)),e}p(Fd,"generatedVideoFromMldev$1");function Bd(n){let e={},t=r(n,["_self"]);return t!=null&&l(e,["video"],Jd(t)),e}p(Bd,"generatedVideoFromVertex$1");function Vd(n){let e={},t=r(n,["operationName"]);return t!=null&&l(e,["_url","operationName"],t),e}p(Vd,"getOperationParametersToMldev");function qd(n){let e={},t=r(n,["operationName"]);return t!=null&&l(e,["_url","operationName"],t),e}p(qd,"getOperationParametersToVertex");function Od(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"],Hd(a)),e}p(Od,"importFileOperationFromMldev$1");function Hd(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(Hd,"importFileResponseFromMldev$1");function Za(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"],zd(a)),e}p(Za,"uploadToFileSearchStoreOperationFromMldev");function zd(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(zd,"uploadToFileSearchStoreResponseFromMldev");function Kd(n){let e={},t=r(n,["uri"]);t!=null&&l(e,["uri"],t);let i=r(n,["encodedVideo"]);i!=null&&l(e,["videoBytes"],is(i));let o=r(n,["encoding"]);return o!=null&&l(e,["mimeType"],o),e}p(Kd,"videoFromMldev$1");function Jd(n){let e={},t=r(n,["gcsUri"]);t!=null&&l(e,["uri"],t);let i=r(n,["bytesBase64Encoded"]);i!=null&&l(e,["videoBytes"],is(i));let o=r(n,["mimeType"]);return o!=null&&l(e,["mimeType"],o),e}p(Jd,"videoFromVertex$1");var Gr;(function(n){n.OUTCOME_UNSPECIFIED="OUTCOME_UNSPECIFIED",n.OUTCOME_OK="OUTCOME_OK",n.OUTCOME_FAILED="OUTCOME_FAILED",n.OUTCOME_DEADLINE_EXCEEDED="OUTCOME_DEADLINE_EXCEEDED"})(Gr||(Gr={}));var Nr;(function(n){n.LANGUAGE_UNSPECIFIED="LANGUAGE_UNSPECIFIED",n.PYTHON="PYTHON"})(Nr||(Nr={}));var $r;(function(n){n.SCHEDULING_UNSPECIFIED="SCHEDULING_UNSPECIFIED",n.SILENT="SILENT",n.WHEN_IDLE="WHEN_IDLE",n.INTERRUPT="INTERRUPT"})($r||($r={}));var Ke;(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"})(Ke||(Ke={}));var kr;(function(n){n.MODE_UNSPECIFIED="MODE_UNSPECIFIED",n.MODE_DYNAMIC="MODE_DYNAMIC"})(kr||(kr={}));var Rr;(function(n){n.API_SPEC_UNSPECIFIED="API_SPEC_UNSPECIFIED",n.SIMPLE_SEARCH="SIMPLE_SEARCH",n.ELASTIC_SEARCH="ELASTIC_SEARCH"})(Rr||(Rr={}));var Dr;(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"})(Dr||(Dr={}));var Mr;(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"})(Mr||(Mr={}));var Lr;(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"})(Lr||(Lr={}));var Ur;(function(n){n.THINKING_LEVEL_UNSPECIFIED="THINKING_LEVEL_UNSPECIFIED",n.LOW="LOW",n.HIGH="HIGH"})(Ur||(Ur={}));var Fr;(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"})(Fr||(Fr={}));var Br;(function(n){n.HARM_BLOCK_METHOD_UNSPECIFIED="HARM_BLOCK_METHOD_UNSPECIFIED",n.SEVERITY="SEVERITY",n.PROBABILITY="PROBABILITY"})(Br||(Br={}));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 qr;(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"})(qr||(qr={}));var Or;(function(n){n.HARM_PROBABILITY_UNSPECIFIED="HARM_PROBABILITY_UNSPECIFIED",n.NEGLIGIBLE="NEGLIGIBLE",n.LOW="LOW",n.MEDIUM="MEDIUM",n.HIGH="HIGH"})(Or||(Or={}));var Hr;(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"})(Hr||(Hr={}));var zr;(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"})(zr||(zr={}));var Kr;(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"})(Kr||(Kr={}));var Jr;(function(n){n.TRAFFIC_TYPE_UNSPECIFIED="TRAFFIC_TYPE_UNSPECIFIED",n.ON_DEMAND="ON_DEMAND",n.PROVISIONED_THROUGHPUT="PROVISIONED_THROUGHPUT"})(Jr||(Jr={}));var $n;(function(n){n.MODALITY_UNSPECIFIED="MODALITY_UNSPECIFIED",n.TEXT="TEXT",n.IMAGE="IMAGE",n.AUDIO="AUDIO"})($n||($n={}));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 Yr;(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"})(Yr||(Yr={}));var Xr;(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"})(Xr||(Xr={}));var so;(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"})(so||(so={}));var Qr;(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"})(Qr||(Qr={}));var Zr;(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"})(Zr||(Zr={}));var jr;(function(n){n.FEATURE_SELECTION_PREFERENCE_UNSPECIFIED="FEATURE_SELECTION_PREFERENCE_UNSPECIFIED",n.PRIORITIZE_QUALITY="PRIORITIZE_QUALITY",n.BALANCED="BALANCED",n.PRIORITIZE_COST="PRIORITIZE_COST"})(jr||(jr={}));var ea;(function(n){n.UNSPECIFIED="UNSPECIFIED",n.BLOCKING="BLOCKING",n.NON_BLOCKING="NON_BLOCKING"})(ea||(ea={}));var ta;(function(n){n.MODE_UNSPECIFIED="MODE_UNSPECIFIED",n.MODE_DYNAMIC="MODE_DYNAMIC"})(ta||(ta={}));var na;(function(n){n.ENVIRONMENT_UNSPECIFIED="ENVIRONMENT_UNSPECIFIED",n.ENVIRONMENT_BROWSER="ENVIRONMENT_BROWSER"})(na||(na={}));var kn;(function(n){n.MODE_UNSPECIFIED="MODE_UNSPECIFIED",n.AUTO="AUTO",n.ANY="ANY",n.NONE="NONE",n.VALIDATED="VALIDATED"})(kn||(kn={}));var ia;(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"})(ia||(ia={}));var oa;(function(n){n.DONT_ALLOW="DONT_ALLOW",n.ALLOW_ADULT="ALLOW_ADULT",n.ALLOW_ALL="ALLOW_ALL"})(oa||(oa={}));var sa;(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"})(sa||(sa={}));var ra;(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"})(ra||(ra={}));var aa;(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"})(aa||(aa={}));var la;(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"})(la||(la={}));var da;(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"})(da||(da={}));var ca;(function(n){n.FOREGROUND="FOREGROUND",n.BACKGROUND="BACKGROUND",n.PROMPT="PROMPT",n.SEMANTIC="SEMANTIC",n.INTERACTIVE="INTERACTIVE"})(ca||(ca={}));var ua;(function(n){n.ASSET="ASSET",n.STYLE="STYLE"})(ua||(ua={}));var fa;(function(n){n.INSERT="INSERT",n.REMOVE="REMOVE",n.REMOVE_STATIC="REMOVE_STATIC",n.OUTPAINT="OUTPAINT"})(fa||(fa={}));var pa;(function(n){n.OPTIMIZED="OPTIMIZED",n.LOSSLESS="LOSSLESS"})(pa||(pa={}));var ha;(function(n){n.SUPERVISED_FINE_TUNING="SUPERVISED_FINE_TUNING",n.PREFERENCE_TUNING="PREFERENCE_TUNING"})(ha||(ha={}));var ma;(function(n){n.STATE_UNSPECIFIED="STATE_UNSPECIFIED",n.STATE_PENDING="STATE_PENDING",n.STATE_ACTIVE="STATE_ACTIVE",n.STATE_FAILED="STATE_FAILED"})(ma||(ma={}));var ga;(function(n){n.STATE_UNSPECIFIED="STATE_UNSPECIFIED",n.PROCESSING="PROCESSING",n.ACTIVE="ACTIVE",n.FAILED="FAILED"})(ga||(ga={}));var ba;(function(n){n.SOURCE_UNSPECIFIED="SOURCE_UNSPECIFIED",n.UPLOADED="UPLOADED",n.GENERATED="GENERATED"})(ba||(ba={}));var ya;(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"})(ya||(ya={}));var Ea;(function(n){n.MODALITY_UNSPECIFIED="MODALITY_UNSPECIFIED",n.TEXT="TEXT",n.IMAGE="IMAGE",n.VIDEO="VIDEO",n.AUDIO="AUDIO",n.DOCUMENT="DOCUMENT"})(Ea||(Ea={}));var wa;(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"})(wa||(wa={}));var va;(function(n){n.START_SENSITIVITY_UNSPECIFIED="START_SENSITIVITY_UNSPECIFIED",n.START_SENSITIVITY_HIGH="START_SENSITIVITY_HIGH",n.START_SENSITIVITY_LOW="START_SENSITIVITY_LOW"})(va||(va={}));var Ia;(function(n){n.END_SENSITIVITY_UNSPECIFIED="END_SENSITIVITY_UNSPECIFIED",n.END_SENSITIVITY_HIGH="END_SENSITIVITY_HIGH",n.END_SENSITIVITY_LOW="END_SENSITIVITY_LOW"})(Ia||(Ia={}));var Ca;(function(n){n.ACTIVITY_HANDLING_UNSPECIFIED="ACTIVITY_HANDLING_UNSPECIFIED",n.START_OF_ACTIVITY_INTERRUPTS="START_OF_ACTIVITY_INTERRUPTS",n.NO_INTERRUPTION="NO_INTERRUPTION"})(Ca||(Ca={}));var Ta;(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"})(Ta||(Ta={}));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 _a;(function(n){n.MUSIC_GENERATION_MODE_UNSPECIFIED="MUSIC_GENERATION_MODE_UNSPECIFIED",n.QUALITY="QUALITY",n.DIVERSITY="DIVERSITY",n.VOCALIZATION="VOCALIZATION"})(_a||(_a={}));var xt;(function(n){n.PLAYBACK_CONTROL_UNSPECIFIED="PLAYBACK_CONTROL_UNSPECIFIED",n.PLAY="PLAY",n.PAUSE="PAUSE",n.STOP="STOP",n.RESET_CONTEXT="RESET_CONTEXT"})(xt||(xt={}));var zt=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 ft=class{static{p(this,"GenerateContentResponse")}get text(){var e,t,i,o,s,a,d,c;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(c=(d=(a=(s=this.candidates)===null||s===void 0?void 0:s[0])===null||a===void 0?void 0:a.content)===null||d===void 0?void 0:d.parts)!==null&&c!==void 0?c:[]){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,d,c;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(c=(d=(a=(s=this.candidates)===null||s===void 0?void 0:s[0])===null||a===void 0?void 0:a.content)===null||d===void 0?void 0:d.parts)!==null&&c!==void 0?c:[]){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,d,c;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=(c=(d=(a=(s=this.candidates)===null||s===void 0?void 0:s[0])===null||a===void 0?void 0:a.content)===null||d===void 0?void 0:d.parts)===null||c===void 0?void 0:c.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,d,c,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=(c=(d=(a=(s=this.candidates)===null||s===void 0?void 0:s[0])===null||a===void 0?void 0:a.content)===null||d===void 0?void 0:d.parts)===null||c===void 0?void 0:c.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,d,c,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=(c=(d=(a=(s=this.candidates)===null||s===void 0?void 0:s[0])===null||a===void 0?void 0:a.content)===null||d===void 0?void 0:d.parts)===null||c===void 0?void 0:c.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}},Rn=class{static{p(this,"EmbedContentResponse")}},Dn=class{static{p(this,"GenerateImagesResponse")}},ro=class{static{p(this,"EditImageResponse")}},ao=class{static{p(this,"UpscaleImageResponse")}},lo=class{static{p(this,"RecontextImageResponse")}},co=class{static{p(this,"SegmentImageResponse")}},Mn=class{static{p(this,"ListModelsResponse")}},Ln=class{static{p(this,"DeleteModelResponse")}},Un=class{static{p(this,"CountTokensResponse")}},uo=class{static{p(this,"ComputeTokensResponse")}};var Fn=class n{static{p(this,"GenerateVideosOperation")}_fromAPIResponse({apiResponse:e,_isVertexAI:t}){let i=new n,o,s=e;return t?o=Md(s):o=Dd(s),Object.assign(i,o),i}},Bn=class{static{p(this,"ListTuningJobsResponse")}},Vn=class{static{p(this,"CancelTuningJobResponse")}},qn=class{static{p(this,"DeleteCachedContentResponse")}},On=class{static{p(this,"ListCachedContentsResponse")}},fo=class{static{p(this,"ListDocumentsResponse")}},po=class{static{p(this,"ListFileSearchStoresResponse")}},ho=class{static{p(this,"UploadToFileSearchStoreResumableResponse")}};var mo=class n{static{p(this,"ImportFileOperation")}_fromAPIResponse({apiResponse:e,_isVertexAI:t}){let i=new n,s=Od(e);return Object.assign(i,s),i}},go=class{static{p(this,"ListFilesResponse")}},bo=class{static{p(this,"CreateFileResponse")}},yo=class{static{p(this,"DeleteFileResponse")}};var Hn=class{static{p(this,"ListBatchJobsResponse")}};var Eo=class{static{p(this,"LiveServerMessage")}get text(){var e,t,i;let o="",s=!1,a=[];for(let d 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,u]of Object.entries(d))c!=="text"&&c!=="thought"&&u!==null&&a.push(c);if(typeof d.text=="string"){if(typeof d.thought=="boolean"&&d.thought)continue;s=!0,o+=d.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[d,c]of Object.entries(a))d!=="inlineData"&&c!==null&&s.push(d);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 wo=class{static{p(this,"LiveMusicServerMessage")}get audioChunk(){if(this.serverContent&&this.serverContent.audioChunks&&this.serverContent.audioChunks.length>0)return this.serverContent.audioChunks[0]}};var vo=class n{static{p(this,"UploadToFileSearchStoreOperation")}_fromAPIResponse({apiResponse:e,_isVertexAI:t}){let i=new n,s=Za(e);return Object.assign(i,s),i}};function q(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(q,"tModel");function ja(n,e){let t=q(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(ja,"tCachesModel");function el(n){return Array.isArray(n)?n.map(e=>zn(e)):[zn(n)]}p(el,"tBlobs");function zn(n){if(typeof n=="object"&&n!==null)return n;throw new Error(`Could not parse input as Blob. Unsupported blob type: ${typeof n}`)}p(zn,"tBlob");function tl(n){let e=zn(n);if(e.mimeType&&e.mimeType.startsWith("image/"))return e;throw new Error(`Unsupported mime type: ${e.mimeType}`)}p(tl,"tImageBlob");function nl(n){let e=zn(n);if(e.mimeType&&e.mimeType.startsWith("audio/"))return e;throw new Error(`Unsupported mime type: ${e.mimeType}`)}p(nl,"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 il(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(il,"tParts");function Io(n){return n!=null&&typeof n=="object"&&"parts"in n&&Array.isArray(n.parts)}p(Io,"_isContent");function xa(n){return n!=null&&typeof n=="object"&&"functionCall"in n}p(xa,"_isFunctionCallPart");function Pa(n){return n!=null&&typeof n=="object"&&"functionResponse"in n}p(Pa,"_isFunctionResponsePart");function ue(n){if(n==null)throw new Error("ContentUnion is required");return Io(n)?n:{role:"user",parts:il(n)}}p(ue,"tContent");function os(n,e){if(!e)return[];if(n.isVertexAI()&&Array.isArray(e))return e.flatMap(t=>{let i=ue(t);return i.parts&&i.parts.length>0&&i.parts[0].text!==void 0?[i.parts[0].text]:[]});if(n.isVertexAI()){let t=ue(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=>ue(t)):[ue(e)]}p(os,"tContentsForEmbed");function _e(n){if(n==null||Array.isArray(n)&&n.length===0)throw new Error("contents are required");if(!Array.isArray(n)){if(xa(n)||Pa(n))throw new Error("To specify functionCall or functionResponse parts, please wrap them in a Content object, specifying the role for them");return[ue(n)]}let e=[],t=[],i=Io(n[0]);for(let o of n){let s=Io(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(xa(o)||Pa(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:il(t)}),e}p(_e,"tContents");function Wd(n,e){n.includes("null")&&(e.nullable=!0);let t=n.filter(i=>i!=="null");if(t.length===1)e.type=Object.values(Ke).includes(t[0].toUpperCase())?t[0].toUpperCase():Ke.TYPE_UNSPECIFIED;else{e.anyOf=[];for(let i of t)e.anyOf.push({type:Object.values(Ke).includes(i.toUpperCase())?i.toUpperCase():Ke.TYPE_UNSPECIFIED})}}p(Wd,"flattenTypeArrayToAnyOf");function Pt(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&&Wd(n.type,e);for(let[a,d]of Object.entries(n))if(d!=null)if(a=="type"){if(d==="null")throw new Error("type: null can not be the only possible type for the field.");if(d instanceof Array)continue;e.type=Object.values(Ke).includes(d.toUpperCase())?d.toUpperCase():Ke.TYPE_UNSPECIFIED}else if(t.includes(a))e[a]=Pt(d);else if(i.includes(a)){let c=[];for(let u of d){if(u.type=="null"){e.nullable=!0;continue}c.push(Pt(u))}e[a]=c}else if(o.includes(a)){let c={};for(let[u,f]of Object.entries(d))c[u]=Pt(f);e[a]=c}else{if(a==="additionalProperties")continue;e[a]=d}return e}p(Pt,"processJsonSchema");function ss(n){return Pt(n)}p(ss,"tSchema");function rs(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(rs,"tSpeechConfig");function as(n){if("multiSpeakerVoiceConfig"in n)throw new Error("multiSpeakerVoiceConfig is not supported in the live API.");return n}p(as,"tLiveSpeechConfig");function kt(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=Pt(e.parameters)),e.response&&(Object.keys(e.response).includes("$schema")?e.responseJsonSchema||(e.responseJsonSchema=e.response,delete e.response):e.response=Pt(e.response));return n}p(kt,"tTool");function Rt(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(Rt,"tTools");function Yd(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(Yd,"resourceName");function Oe(n,e){if(typeof e!="string")throw new Error("name must be a string");return Yd(n,e,"cachedContents")}p(Oe,"tCachedContentName");function ol(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(ol,"tTuningJobStatus");function Je(n){return is(n)}p(Je,"tBytes");function Xd(n){return n!=null&&typeof n=="object"&&"name"in n}p(Xd,"_isFile");function Qd(n){return n!=null&&typeof n=="object"&&"video"in n}p(Qd,"isGeneratedVideo");function Zd(n){return n!=null&&typeof n=="object"&&"uri"in n}p(Zd,"isVideo");function sl(n){var e;let t;if(Xd(n)&&(t=n.name),!(Zd(n)&&(t=n.uri,t===void 0))&&!(Qd(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(sl,"tFileName");function rl(n,e){let t;return n.isVertexAI()?t=e?"publishers/google/models":"models":t=e?"models":"tunedModels",t}p(rl,"tModelsUrl");function al(n){for(let e of["models","tunedModels","publisherModels"])if(jd(n,e))return n[e];return[]}p(al,"tExtractModels");function jd(n,e){return n!==null&&typeof n=="object"&&e in n}p(jd,"hasField");function ec(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(ec,"mcpToGeminiTool");function tc(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=ec(o,e);a.functionDeclarations&&t.push(...a.functionDeclarations)}return{functionDeclarations:t}}p(tc,"mcpToolsToGeminiTool");function ll(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(ll,"tBatchJobSource");function nc(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(nc,"tBatchJobDestination");function dl(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 c=a.response;if(typeof c!="object"||c===null)continue;if(c.embedding!==void 0){s=!0;break}}return s&&(e.inlinedEmbedContentResponses=e.inlinedResponses,delete e.inlinedResponses),n}p(dl,"tRecvBatchJobDestination");function Dt(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(Dt,"tBatchJobName");function cl(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(cl,"tJobState");function ic(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=>Lc(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(ic,"batchJobDestinationFromMldev");function oc(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(oc,"batchJobDestinationFromVertex");function sc(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(sc,"batchJobDestinationToVertex");function Gn(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"],cl(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 d=r(n,["metadata","updateTime"]);d!=null&&l(e,["updateTime"],d);let c=r(n,["metadata","model"]);c!=null&&l(e,["model"],c);let u=r(n,["metadata","output"]);return u!=null&&l(e,["dest"],ic(dl(u))),e}p(Gn,"batchJobFromMldev");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,["state"]);o!=null&&l(e,["state"],cl(o));let s=r(n,["error"]);s!=null&&l(e,["error"],s);let a=r(n,["createTime"]);a!=null&&l(e,["createTime"],a);let d=r(n,["startTime"]);d!=null&&l(e,["startTime"],d);let c=r(n,["endTime"]);c!=null&&l(e,["endTime"],c);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"],rc(h));let m=r(n,["outputConfig"]);m!=null&&l(e,["dest"],oc(dl(m)));let g=r(n,["completionStats"]);return g!=null&&l(e,["completionStats"],g),e}p(Co,"batchJobFromVertex");function rc(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(rc,"batchJobSourceFromVertex");function ac(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=>Mc(n,a))),l(t,["requests","requests"],s)}return t}p(ac,"batchJobSourceToMldev");function lc(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(lc,"batchJobSourceToVertex");function dc(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(dc,"blobToMldev$4");function cc(n,e){let t={},i=r(e,["name"]);return i!=null&&l(t,["_url","name"],Dt(n,i)),t}p(cc,"cancelBatchJobParametersToMldev");function uc(n,e){let t={},i=r(e,["name"]);return i!=null&&l(t,["_url","name"],Dt(n,i)),t}p(uc,"cancelBatchJobParametersToVertex");function fc(n){let e={},t=r(n,["content"]);t!=null&&l(e,["content"],t);let i=r(n,["citationMetadata"]);i!=null&&l(e,["citationMetadata"],pc(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 d=r(n,["groundingMetadata"]);d!=null&&l(e,["groundingMetadata"],d);let c=r(n,["index"]);c!=null&&l(e,["index"],c);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(fc,"candidateFromMldev$1");function pc(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(pc,"citationMetadataFromMldev$1");function ul(n){let e={},t=r(n,["parts"]);if(t!=null){let o=t;Array.isArray(o)&&(o=o.map(s=>Hc(s))),l(e,["parts"],o)}let i=r(n,["role"]);return i!=null&&l(e,["role"],i),e}p(ul,"contentToMldev$4");function hc(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(hc,"createBatchJobConfigToMldev");function mc(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"],sc(nc(o))),t}p(mc,"createBatchJobConfigToVertex");function Ga(n,e){let t={},i=r(e,["model"]);i!=null&&l(t,["_url","model"],q(n,i));let o=r(e,["src"]);o!=null&&l(t,["batch","inputConfig"],ac(n,ll(n,o)));let s=r(e,["config"]);return s!=null&&hc(s,t),t}p(Ga,"createBatchJobParametersToMldev");function gc(n,e){let t={},i=r(e,["model"]);i!=null&&l(t,["model"],q(n,i));let o=r(e,["src"]);o!=null&&l(t,["inputConfig"],lc(ll(n,o)));let s=r(e,["config"]);return s!=null&&mc(s,t),t}p(gc,"createBatchJobParametersToVertex");function bc(n,e){let t={},i=r(n,["displayName"]);return e!==void 0&&i!=null&&l(e,["batch","displayName"],i),t}p(bc,"createEmbeddingsBatchJobConfigToMldev");function yc(n,e){let t={},i=r(e,["model"]);i!=null&&l(t,["_url","model"],q(n,i));let o=r(e,["src"]);o!=null&&l(t,["batch","inputConfig"],Sc(n,o));let s=r(e,["config"]);return s!=null&&bc(s,t),t}p(yc,"createEmbeddingsBatchJobParametersToMldev");function Ec(n,e){let t={},i=r(e,["name"]);return i!=null&&l(t,["_url","name"],Dt(n,i)),t}p(Ec,"deleteBatchJobParametersToMldev");function wc(n,e){let t={},i=r(e,["name"]);return i!=null&&l(t,["_url","name"],Dt(n,i)),t}p(wc,"deleteBatchJobParametersToVertex");function vc(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(vc,"deleteResourceJobFromMldev");function Ic(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(Ic,"deleteResourceJobFromVertex");function Cc(n,e){let t={},i=r(e,["contents"]);if(i!=null){let s=os(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"],Tc(o,t)),kd(t,{"requests[].*":"requests[].request.*"})),t}p(Cc,"embedContentBatchToMldev");function Tc(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(Tc,"embedContentConfigToMldev$1");function Sc(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"],Cc(n,o)),t}p(Sc,"embeddingsBatchJobSourceToMldev");function _c(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(_c,"fileDataToMldev$4");function Ac(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(Ac,"functionCallToMldev$4");function xc(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(xc,"functionCallingConfigToMldev$2");function Pc(n,e,t){let i={},o=r(e,["systemInstruction"]);t!==void 0&&o!=null&&l(t,["systemInstruction"],ul(ue(o)));let s=r(e,["temperature"]);s!=null&&l(i,["temperature"],s);let a=r(e,["topP"]);a!=null&&l(i,["topP"],a);let d=r(e,["topK"]);d!=null&&l(i,["topK"],d);let c=r(e,["candidateCount"]);c!=null&&l(i,["candidateCount"],c);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 y=r(e,["seed"]);y!=null&&l(i,["seed"],y);let w=r(e,["responseMimeType"]);w!=null&&l(i,["responseMimeType"],w);let v=r(e,["responseSchema"]);v!=null&&l(i,["responseSchema"],ss(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 C=r(e,["safetySettings"]);if(t!==void 0&&C!=null){let U=C;Array.isArray(U)&&(U=U.map(ie=>zc(ie))),l(t,["safetySettings"],U)}let T=r(e,["tools"]);if(t!==void 0&&T!=null){let U=Rt(T);Array.isArray(U)&&(U=U.map(ie=>Jc(kt(ie)))),l(t,["tools"],U)}let x=r(e,["toolConfig"]);if(t!==void 0&&x!=null&&l(t,["toolConfig"],Kc(x)),r(e,["labels"])!==void 0)throw new Error("labels parameter is not supported in Gemini API.");let G=r(e,["cachedContent"]);t!==void 0&&G!=null&&l(t,["cachedContent"],Oe(n,G));let S=r(e,["responseModalities"]);S!=null&&l(i,["responseModalities"],S);let N=r(e,["mediaResolution"]);N!=null&&l(i,["mediaResolution"],N);let P=r(e,["speechConfig"]);if(P!=null&&l(i,["speechConfig"],rs(P)),r(e,["audioTimestamp"])!==void 0)throw new Error("audioTimestamp parameter is not supported in Gemini API.");let $=r(e,["thinkingConfig"]);$!=null&&l(i,["thinkingConfig"],$);let F=r(e,["imageConfig"]);F!=null&&l(i,["imageConfig"],Dc(F));let X=r(e,["enableEnhancedCivicAnswers"]);return X!=null&&l(i,["enableEnhancedCivicAnswers"],X),i}p(Pc,"generateContentConfigToMldev$1");function Gc(n){let e={},t=r(n,["sdkHttpResponse"]);t!=null&&l(e,["sdkHttpResponse"],t);let i=r(n,["candidates"]);if(i!=null){let c=i;Array.isArray(c)&&(c=c.map(u=>fc(u))),l(e,["candidates"],c)}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 d=r(n,["usageMetadata"]);return d!=null&&l(e,["usageMetadata"],d),e}p(Gc,"generateContentResponseFromMldev$1");function Nc(n,e){let t={},i=r(e,["name"]);return i!=null&&l(t,["_url","name"],Dt(n,i)),t}p(Nc,"getBatchJobParametersToMldev");function $c(n,e){let t={},i=r(e,["name"]);return i!=null&&l(t,["_url","name"],Dt(n,i)),t}p($c,"getBatchJobParametersToVertex");function kc(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(kc,"googleMapsToMldev$4");function Rc(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(Rc,"googleSearchToMldev$4");function Dc(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(Dc,"imageConfigToMldev$1");function Mc(n,e){let t={},i=r(e,["model"]);i!=null&&l(t,["request","model"],q(n,i));let o=r(e,["contents"]);if(o!=null){let d=_e(o);Array.isArray(d)&&(d=d.map(c=>ul(c))),l(t,["request","contents"],d)}let s=r(e,["metadata"]);s!=null&&l(t,["metadata"],s);let a=r(e,["config"]);return a!=null&&l(t,["request","generationConfig"],Pc(n,a,r(t,["request"],{}))),t}p(Mc,"inlinedRequestToMldev");function Lc(n){let e={},t=r(n,["response"]);t!=null&&l(e,["response"],Gc(t));let i=r(n,["error"]);return i!=null&&l(e,["error"],i),e}p(Lc,"inlinedResponseFromMldev");function Uc(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(Uc,"listBatchJobsConfigToMldev");function Fc(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(Fc,"listBatchJobsConfigToVertex");function Bc(n){let e={},t=r(n,["config"]);return t!=null&&Uc(t,e),e}p(Bc,"listBatchJobsParametersToMldev");function Vc(n){let e={},t=r(n,["config"]);return t!=null&&Fc(t,e),e}p(Vc,"listBatchJobsParametersToVertex");function qc(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=>Gn(a))),l(e,["batchJobs"],s)}return e}p(qc,"listBatchJobsResponseFromMldev");function Oc(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=>Co(a))),l(e,["batchJobs"],s)}return e}p(Oc,"listBatchJobsResponseFromVertex");function Hc(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"],_c(s));let a=r(n,["functionCall"]);a!=null&&l(e,["functionCall"],Ac(a));let d=r(n,["functionResponse"]);d!=null&&l(e,["functionResponse"],d);let c=r(n,["inlineData"]);c!=null&&l(e,["inlineData"],dc(c));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(Hc,"partToMldev$4");function zc(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(zc,"safetySettingToMldev$1");function Kc(n){let e={},t=r(n,["functionCallingConfig"]);t!=null&&l(e,["functionCallingConfig"],xc(t));let i=r(n,["retrievalConfig"]);return i!=null&&l(e,["retrievalConfig"],i),e}p(Kc,"toolConfigToMldev$2");function Jc(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 d=r(n,["googleMaps"]);d!=null&&l(e,["googleMaps"],kc(d));let c=r(n,["googleSearch"]);c!=null&&l(e,["googleSearch"],Rc(c));let u=r(n,["urlContext"]);return u!=null&&l(e,["urlContext"],u),e}p(Jc,"toolToMldev$4");var Ve;(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"})(Ve||(Ve={}));var qe=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 To=class extends Re{static{p(this,"Batches")}constructor(e){super(),this.apiClient=e,this.list=async(t={})=>new qe(Ve.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=Ga(this.apiClient,e),i=t._url,o=A("{model}:batchGenerateContent",i),d=t.batch.inputConfig.requests,c=d.requests,u=[];for(let f of c){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 d.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,d="",c={};if(this.apiClient.isVertexAI()){let u=gc(this.apiClient,e);return d=A("batchPredictionJobs",u._url),c=u._query,delete u._url,delete u._query,a=this.apiClient.request({path:d,queryParams:c,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=>Co(f))}else{let u=Ga(this.apiClient,e);return d=A("{model}:batchGenerateContent",u._url),c=u._query,delete u._url,delete u._query,a=this.apiClient.request({path:d,queryParams:c,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=>Gn(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 d=yc(this.apiClient,e);return s=A("{model}:asyncBatchEmbedContent",d._url),a=d._query,delete d._url,delete d._query,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(c=>c.json()),o.then(c=>Gn(c))}}async get(e){var t,i,o,s;let a,d="",c={};if(this.apiClient.isVertexAI()){let u=$c(this.apiClient,e);return d=A("batchPredictionJobs/{name}",u._url),c=u._query,delete u._url,delete u._query,a=this.apiClient.request({path:d,queryParams:c,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=Nc(this.apiClient,e);return d=A("batches/{name}",u._url),c=u._query,delete u._url,delete u._query,a=this.apiClient.request({path:d,queryParams:c,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=>Gn(f))}}async cancel(e){var t,i,o,s;let a="",d={};if(this.apiClient.isVertexAI()){let c=uc(this.apiClient,e);a=A("batchPredictionJobs/{name}:cancel",c._url),d=c._query,delete c._url,delete c._query,await this.apiClient.request({path:a,queryParams:d,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})}else{let c=cc(this.apiClient,e);a=A("batches/{name}:cancel",c._url),d=c._query,delete c._url,delete c._query,await this.apiClient.request({path:a,queryParams:d,body:JSON.stringify(c),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,d="",c={};if(this.apiClient.isVertexAI()){let u=Vc(e);return d=A("batchPredictionJobs",u._url),c=u._query,delete u._url,delete u._query,a=this.apiClient.request({path:d,queryParams:c,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=Oc(f),m=new Hn;return Object.assign(m,h),m})}else{let u=Bc(e);return d=A("batches",u._url),c=u._query,delete u._url,delete u._query,a=this.apiClient.request({path:d,queryParams:c,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=qc(f),m=new Hn;return Object.assign(m,h),m})}}async delete(e){var t,i,o,s;let a,d="",c={};if(this.apiClient.isVertexAI()){let u=wc(this.apiClient,e);return d=A("batchPredictionJobs/{name}",u._url),c=u._query,delete u._url,delete u._query,a=this.apiClient.request({path:d,queryParams:c,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=>Ic(f))}else{let u=Ec(this.apiClient,e);return d=A("batches/{name}",u._url),c=u._query,delete u._url,delete u._query,a=this.apiClient.request({path:d,queryParams:c,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=>vc(f))}}};function Wc(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(Wc,"blobToMldev$3");function Na(n){let e={},t=r(n,["parts"]);if(t!=null){let o=t;Array.isArray(o)&&(o=o.map(s=>bu(s))),l(e,["parts"],o)}let i=r(n,["role"]);return i!=null&&l(e,["role"],i),e}p(Na,"contentToMldev$3");function Yc(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=_e(a);Array.isArray(f)&&(f=f.map(h=>Na(h))),l(e,["contents"],f)}let d=r(n,["systemInstruction"]);e!==void 0&&d!=null&&l(e,["systemInstruction"],Na(ue(d)));let c=r(n,["tools"]);if(e!==void 0&&c!=null){let f=c;Array.isArray(f)&&(f=f.map(h=>Eu(h))),l(e,["tools"],f)}let u=r(n,["toolConfig"]);if(e!==void 0&&u!=null&&l(e,["toolConfig"],yu(u)),r(n,["kmsKeyName"])!==void 0)throw new Error("kmsKeyName parameter is not supported in Gemini API.");return t}p(Yc,"createCachedContentConfigToMldev");function Xc(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=_e(a);Array.isArray(h)&&(h=h.map(m=>m)),l(e,["contents"],h)}let d=r(n,["systemInstruction"]);e!==void 0&&d!=null&&l(e,["systemInstruction"],ue(d));let c=r(n,["tools"]);if(e!==void 0&&c!=null){let h=c;Array.isArray(h)&&(h=h.map(m=>wu(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(Xc,"createCachedContentConfigToVertex");function Qc(n,e){let t={},i=r(e,["model"]);i!=null&&l(t,["model"],ja(n,i));let o=r(e,["config"]);return o!=null&&Yc(o,t),t}p(Qc,"createCachedContentParametersToMldev");function Zc(n,e){let t={},i=r(e,["model"]);i!=null&&l(t,["model"],ja(n,i));let o=r(e,["config"]);return o!=null&&Xc(o,t),t}p(Zc,"createCachedContentParametersToVertex");function jc(n,e){let t={},i=r(e,["name"]);return i!=null&&l(t,["_url","name"],Oe(n,i)),t}p(jc,"deleteCachedContentParametersToMldev");function eu(n,e){let t={},i=r(e,["name"]);return i!=null&&l(t,["_url","name"],Oe(n,i)),t}p(eu,"deleteCachedContentParametersToVertex");function tu(n){let e={},t=r(n,["sdkHttpResponse"]);return t!=null&&l(e,["sdkHttpResponse"],t),e}p(tu,"deleteCachedContentResponseFromMldev");function nu(n){let e={},t=r(n,["sdkHttpResponse"]);return t!=null&&l(e,["sdkHttpResponse"],t),e}p(nu,"deleteCachedContentResponseFromVertex");function iu(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(iu,"fileDataToMldev$3");function ou(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(ou,"functionCallToMldev$3");function su(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(su,"functionCallingConfigToMldev$1");function ru(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 d=r(n,["responseJsonSchema"]);return d!=null&&l(e,["responseJsonSchema"],d),e}p(ru,"functionDeclarationToVertex$2");function au(n,e){let t={},i=r(e,["name"]);return i!=null&&l(t,["_url","name"],Oe(n,i)),t}p(au,"getCachedContentParametersToMldev");function lu(n,e){let t={},i=r(e,["name"]);return i!=null&&l(t,["_url","name"],Oe(n,i)),t}p(lu,"getCachedContentParametersToVertex");function du(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(du,"googleMapsToMldev$3");function cu(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(cu,"googleSearchToMldev$3");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,"listCachedContentsConfigToMldev");function fu(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(fu,"listCachedContentsConfigToVertex");function pu(n){let e={},t=r(n,["config"]);return t!=null&&uu(t,e),e}p(pu,"listCachedContentsParametersToMldev");function hu(n){let e={},t=r(n,["config"]);return t!=null&&fu(t,e),e}p(hu,"listCachedContentsParametersToVertex");function mu(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(mu,"listCachedContentsResponseFromMldev");function gu(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(gu,"listCachedContentsResponseFromVertex");function bu(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"],iu(s));let a=r(n,["functionCall"]);a!=null&&l(e,["functionCall"],ou(a));let d=r(n,["functionResponse"]);d!=null&&l(e,["functionResponse"],d);let c=r(n,["inlineData"]);c!=null&&l(e,["inlineData"],Wc(c));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(bu,"partToMldev$3");function yu(n){let e={},t=r(n,["functionCallingConfig"]);t!=null&&l(e,["functionCallingConfig"],su(t));let i=r(n,["retrievalConfig"]);return i!=null&&l(e,["retrievalConfig"],i),e}p(yu,"toolConfigToMldev$1");function Eu(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 d=r(n,["googleMaps"]);d!=null&&l(e,["googleMaps"],du(d));let c=r(n,["googleSearch"]);c!=null&&l(e,["googleSearch"],cu(c));let u=r(n,["urlContext"]);return u!=null&&l(e,["urlContext"],u),e}p(Eu,"toolToMldev$3");function wu(n){let e={},t=r(n,["functionDeclarations"]);if(t!=null){let h=t;Array.isArray(h)&&(h=h.map(m=>ru(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 d=r(n,["enterpriseWebSearch"]);d!=null&&l(e,["enterpriseWebSearch"],d);let c=r(n,["googleMaps"]);c!=null&&l(e,["googleMaps"],c);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(wu,"toolToVertex$2");function vu(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(vu,"updateCachedContentConfigToMldev");function Iu(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(Iu,"updateCachedContentConfigToVertex");function Cu(n,e){let t={},i=r(e,["name"]);i!=null&&l(t,["_url","name"],Oe(n,i));let o=r(e,["config"]);return o!=null&&vu(o,t),t}p(Cu,"updateCachedContentParametersToMldev");function Tu(n,e){let t={},i=r(e,["name"]);i!=null&&l(t,["_url","name"],Oe(n,i));let o=r(e,["config"]);return o!=null&&Iu(o,t),t}p(Tu,"updateCachedContentParametersToVertex");var So=class extends Re{static{p(this,"Caches")}constructor(e){super(),this.apiClient=e,this.list=async(t={})=>new qe(Ve.PAGED_ITEM_CACHED_CONTENTS,i=>this.listInternal(i),await this.listInternal(t),t)}async create(e){var t,i,o,s;let a,d="",c={};if(this.apiClient.isVertexAI()){let u=Zc(this.apiClient,e);return d=A("cachedContents",u._url),c=u._query,delete u._url,delete u._query,a=this.apiClient.request({path:d,queryParams:c,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=Qc(this.apiClient,e);return d=A("cachedContents",u._url),c=u._query,delete u._url,delete u._query,a=this.apiClient.request({path:d,queryParams:c,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,d="",c={};if(this.apiClient.isVertexAI()){let u=lu(this.apiClient,e);return d=A("{name}",u._url),c=u._query,delete u._url,delete u._query,a=this.apiClient.request({path:d,queryParams:c,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=au(this.apiClient,e);return d=A("{name}",u._url),c=u._query,delete u._url,delete u._query,a=this.apiClient.request({path:d,queryParams:c,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,d="",c={};if(this.apiClient.isVertexAI()){let u=eu(this.apiClient,e);return d=A("{name}",u._url),c=u._query,delete u._url,delete u._query,a=this.apiClient.request({path:d,queryParams:c,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=nu(f),m=new qn;return Object.assign(m,h),m})}else{let u=jc(this.apiClient,e);return d=A("{name}",u._url),c=u._query,delete u._url,delete u._query,a=this.apiClient.request({path:d,queryParams:c,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=tu(f),m=new qn;return Object.assign(m,h),m})}}async update(e){var t,i,o,s;let a,d="",c={};if(this.apiClient.isVertexAI()){let u=Tu(this.apiClient,e);return d=A("{name}",u._url),c=u._query,delete u._url,delete u._query,a=this.apiClient.request({path:d,queryParams:c,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=Cu(this.apiClient,e);return d=A("{name}",u._url),c=u._query,delete u._url,delete u._query,a=this.apiClient.request({path:d,queryParams:c,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,d="",c={};if(this.apiClient.isVertexAI()){let u=hu(e);return d=A("cachedContents",u._url),c=u._query,delete u._url,delete u._query,a=this.apiClient.request({path:d,queryParams:c,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=gu(f),m=new On;return Object.assign(m,h),m})}else{let u=pu(e);return d=A("cachedContents",u._url),c=u._query,delete u._url,delete u._query,a=this.apiClient.request({path:d,queryParams:c,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=mu(f),m=new On;return Object.assign(m,h),m})}}};function Kn(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(Kn,"__rest");function $a(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($a,"__values");function M(n){return this instanceof M?(this.v=n,this):new M(n)}p(M,"__await");function $e(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),d("next"),d("throw"),d("return",a),o[Symbol.asyncIterator]=function(){return this},o;function a(g){return function(b){return Promise.resolve(b).then(g,h)}}function d(g,b){i[g]&&(o[g]=function(y){return new Promise(function(w,v){s.push([g,y,w,v])>1||c(g,y)})},b&&(o[g]=b(o[g])))}function c(g,b){try{u(i[g](b))}catch(y){m(s[0][3],y)}}function u(g){g.value instanceof M?Promise.resolve(g.value.v).then(f,h):m(s[0][2],g)}function f(g){c("next",g)}function h(g){c("throw",g)}function m(g,b){g(b),s.shift(),s.length&&c(s[0][0],s[0][1])}}p($e,"__asyncGenerator");function ke(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 $a=="function"?$a(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(d,c){a=n[s](a),o(d,c,a.done,a.value)})}}function o(s,a,d,c){Promise.resolve(c).then(function(u){s({value:u,done:d})},a)}}p(ke,"__asyncValues");function Su(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:fl(t)}p(Su,"isValidResponse");function fl(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(fl,"isValidContent");function _u(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(_u,"validateHistory");function ka(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&&!fl(n[i])&&(s=!1),i++;s?e.push(...o):e.pop()}return e}p(ka,"extractCuratedHistory");var _o=class{static{p(this,"Chats")}constructor(e,t){this.modelsModule=e,this.apiClient=t}create(e){return new Ao(this.apiClient,this.modelsModule,e.model,e.config,structuredClone(e.history))}},Ao=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(),_u(s)}async sendMessage(e){var t;await this.sendPromise;let i=ue(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,d;let c=await o,u=(a=(s=c.candidates)===null||s===void 0?void 0:s[0])===null||a===void 0?void 0:a.content,f=c.automaticFunctionCallingHistory,h=this.getHistory(!0).length,m=[];f!=null&&(m=(d=f.slice(h))!==null&&d!==void 0?d:[]);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=ue(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?ka(this.history):this.history;return structuredClone(t)}processStreamResponse(e,t){return $e(this,arguments,p(function*(){var o,s,a,d,c,u;let f=[];try{for(var h=!0,m=ke(e),g;g=yield M(m.next()),o=g.done,!o;h=!0){d=g.value,h=!1;let b=d;if(Su(b)){let y=(u=(c=b.candidates)===null||c===void 0?void 0:c[0])===null||u===void 0?void 0:u.content;y!==void 0&&f.push(y)}yield yield M(b)}}catch(b){s={error:b}}finally{try{!h&&!o&&(a=m.return)&&(yield M(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(...ka(i)):this.history.push(e),this.history.push(...o)}};var Jn=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 Au(n){let e={},t=r(n,["file"]);return t!=null&&l(e,["file"],t),e}p(Au,"createFileParametersToMldev");function xu(n){let e={},t=r(n,["sdkHttpResponse"]);return t!=null&&l(e,["sdkHttpResponse"],t),e}p(xu,"createFileResponseFromMldev");function Pu(n){let e={},t=r(n,["name"]);return t!=null&&l(e,["_url","file"],sl(t)),e}p(Pu,"deleteFileParametersToMldev");function Gu(n){let e={},t=r(n,["sdkHttpResponse"]);return t!=null&&l(e,["sdkHttpResponse"],t),e}p(Gu,"deleteFileResponseFromMldev");function Nu(n){let e={},t=r(n,["name"]);return t!=null&&l(e,["_url","file"],sl(t)),e}p(Nu,"getFileParametersToMldev");function $u(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($u,"listFilesConfigToMldev");function ku(n){let e={},t=r(n,["config"]);return t!=null&&$u(t,e),e}p(ku,"listFilesParametersToMldev");function Ru(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(Ru,"listFilesResponseFromMldev");var xo=class extends Re{static{p(this,"Files")}constructor(e){super(),this.apiClient=e,this.list=async(t={})=>new qe(Ve.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 d=ku(e);return s=A("files",d._url),a=d._query,delete d._url,delete d._query,o=this.apiClient.request({path:s,queryParams:a,body:JSON.stringify(d),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(c=>c.json().then(u=>{let f=u;return f.sdkHttpResponse={headers:c.headers},f})),o.then(c=>{let u=Ru(c),f=new go;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 d=Au(e);return s=A("upload/v1beta/files",d._url),a=d._query,delete d._url,delete d._query,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(c=>c.json()),o.then(c=>{let u=xu(c),f=new bo;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 d=Nu(e);return s=A("files/{file}",d._url),a=d._query,delete d._url,delete d._query,o=this.apiClient.request({path:s,queryParams:a,body:JSON.stringify(d),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(c=>c.json()),o.then(c=>c)}}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 d=Pu(e);return s=A("files/{file}",d._url),a=d._query,delete d._url,delete d._query,o=this.apiClient.request({path:s,queryParams:a,body:JSON.stringify(d),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(c=>c.json().then(u=>{let f=u;return f.sdkHttpResponse={headers:c.headers},f})),o.then(c=>{let u=Gu(c),f=new yo;return Object.assign(f,u),f})}}};function Nn(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(Nn,"blobToMldev$2");function Du(n){let e={},t=r(n,["parts"]);if(t!=null){let o=t;Array.isArray(o)&&(o=o.map(s=>Qu(s))),l(e,["parts"],o)}let i=r(n,["role"]);return i!=null&&l(e,["role"],i),e}p(Du,"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 Lu(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(Lu,"functionCallToMldev$2");function Uu(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 d=r(n,["responseJsonSchema"]);return d!=null&&l(e,["responseJsonSchema"],d),e}p(Uu,"functionDeclarationToVertex$1");function Fu(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 d=r(n,["frequencyPenalty"]);d!=null&&l(e,["frequencyPenalty"],d);let c=r(n,["logprobs"]);c!=null&&l(e,["logprobs"],c);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 y=r(n,["responseSchema"]);y!=null&&l(e,["responseSchema"],y);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"],pl(I));let C=r(n,["stopSequences"]);C!=null&&l(e,["stopSequences"],C);let T=r(n,["temperature"]);T!=null&&l(e,["temperature"],T);let x=r(n,["thinkingConfig"]);x!=null&&l(e,["thinkingConfig"],x);let G=r(n,["topK"]);G!=null&&l(e,["topK"],G);let S=r(n,["topP"]);if(S!=null&&l(e,["topP"],S),r(n,["enableEnhancedCivicAnswers"])!==void 0)throw new Error("enableEnhancedCivicAnswers parameter is not supported in Vertex AI.");return e}p(Fu,"generationConfigToVertex$1");function Bu(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(Bu,"googleMapsToMldev$2");function Vu(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(Vu,"googleSearchToMldev$2");function qu(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 d=r(n,["topK"]);e!==void 0&&d!=null&&l(e,["setup","generationConfig","topK"],d);let c=r(n,["maxOutputTokens"]);e!==void 0&&c!=null&&l(e,["setup","generationConfig","maxOutputTokens"],c);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"],as(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"],Du(ue(b)));let y=r(n,["tools"]);if(e!==void 0&&y!=null){let G=Rt(y);Array.isArray(G)&&(G=G.map(S=>ju(kt(S)))),l(e,["setup","tools"],G)}let w=r(n,["sessionResumption"]);e!==void 0&&w!=null&&l(e,["setup","sessionResumption"],Zu(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 C=r(n,["realtimeInputConfig"]);e!==void 0&&C!=null&&l(e,["setup","realtimeInputConfig"],C);let T=r(n,["contextWindowCompression"]);e!==void 0&&T!=null&&l(e,["setup","contextWindowCompression"],T);let x=r(n,["proactivity"]);if(e!==void 0&&x!=null&&l(e,["setup","proactivity"],x),r(n,["explicitVadSignal"])!==void 0)throw new Error("explicitVadSignal parameter is not supported in Gemini API.");return t}p(qu,"liveConnectConfigToMldev$1");function Ou(n,e){let t={},i=r(n,["generationConfig"]);e!==void 0&&i!=null&&l(e,["setup","generationConfig"],Fu(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 d=r(n,["topK"]);e!==void 0&&d!=null&&l(e,["setup","generationConfig","topK"],d);let c=r(n,["maxOutputTokens"]);e!==void 0&&c!=null&&l(e,["setup","generationConfig","maxOutputTokens"],c);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"],pl(as(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"],ue(b));let y=r(n,["tools"]);if(e!==void 0&&y!=null){let S=Rt(y);Array.isArray(S)&&(S=S.map(N=>ef(kt(N)))),l(e,["setup","tools"],S)}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 C=r(n,["realtimeInputConfig"]);e!==void 0&&C!=null&&l(e,["setup","realtimeInputConfig"],C);let T=r(n,["contextWindowCompression"]);e!==void 0&&T!=null&&l(e,["setup","contextWindowCompression"],T);let x=r(n,["proactivity"]);e!==void 0&&x!=null&&l(e,["setup","proactivity"],x);let G=r(n,["explicitVadSignal"]);return e!==void 0&&G!=null&&l(e,["setup","explicitVadSignal"],G),t}p(Ou,"liveConnectConfigToVertex");function Hu(n,e){let t={},i=r(e,["model"]);i!=null&&l(t,["setup","model"],q(n,i));let o=r(e,["config"]);return o!=null&&l(t,["config"],qu(o,t)),t}p(Hu,"liveConnectParametersToMldev");function zu(n,e){let t={},i=r(e,["model"]);i!=null&&l(t,["setup","model"],q(n,i));let o=r(e,["config"]);return o!=null&&l(t,["config"],Ou(o,t)),t}p(zu,"liveConnectParametersToVertex");function Ku(n){let e={},t=r(n,["musicGenerationConfig"]);return t!=null&&l(e,["musicGenerationConfig"],t),e}p(Ku,"liveMusicSetConfigParametersToMldev");function Ju(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(Ju,"liveMusicSetWeightedPromptsParametersToMldev");function Wu(n){let e={},t=r(n,["media"]);if(t!=null){let u=el(t);Array.isArray(u)&&(u=u.map(f=>Nn(f))),l(e,["mediaChunks"],u)}let i=r(n,["audio"]);i!=null&&l(e,["audio"],Nn(nl(i)));let o=r(n,["audioStreamEnd"]);o!=null&&l(e,["audioStreamEnd"],o);let s=r(n,["video"]);s!=null&&l(e,["video"],Nn(tl(s)));let a=r(n,["text"]);a!=null&&l(e,["text"],a);let d=r(n,["activityStart"]);d!=null&&l(e,["activityStart"],d);let c=r(n,["activityEnd"]);return c!=null&&l(e,["activityEnd"],c),e}p(Wu,"liveSendRealtimeInputParametersToMldev");function Yu(n){let e={},t=r(n,["media"]);if(t!=null){let u=el(t);Array.isArray(u)&&(u=u.map(f=>f)),l(e,["mediaChunks"],u)}let i=r(n,["audio"]);i!=null&&l(e,["audio"],nl(i));let o=r(n,["audioStreamEnd"]);o!=null&&l(e,["audioStreamEnd"],o);let s=r(n,["video"]);s!=null&&l(e,["video"],tl(s));let a=r(n,["text"]);a!=null&&l(e,["text"],a);let d=r(n,["activityStart"]);d!=null&&l(e,["activityStart"],d);let c=r(n,["activityEnd"]);return c!=null&&l(e,["activityEnd"],c),e}p(Yu,"liveSendRealtimeInputParametersToVertex");function Xu(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"],tf(a));let d=r(n,["goAway"]);d!=null&&l(e,["goAway"],d);let c=r(n,["sessionResumptionUpdate"]);c!=null&&l(e,["sessionResumptionUpdate"],c);let u=r(n,["voiceActivityDetectionSignal"]);return u!=null&&l(e,["voiceActivityDetectionSignal"],u),e}p(Xu,"liveServerMessageFromVertex");function Qu(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"],Lu(a));let d=r(n,["functionResponse"]);d!=null&&l(e,["functionResponse"],d);let c=r(n,["inlineData"]);c!=null&&l(e,["inlineData"],Nn(c));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(Qu,"partToMldev$2");function Zu(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(Zu,"sessionResumptionConfigToMldev$1");function pl(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(pl,"speechConfigToVertex$1");function ju(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 d=r(n,["googleMaps"]);d!=null&&l(e,["googleMaps"],Bu(d));let c=r(n,["googleSearch"]);c!=null&&l(e,["googleSearch"],Vu(c));let u=r(n,["urlContext"]);return u!=null&&l(e,["urlContext"],u),e}p(ju,"toolToMldev$2");function ef(n){let e={},t=r(n,["functionDeclarations"]);if(t!=null){let h=t;Array.isArray(h)&&(h=h.map(m=>Uu(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 d=r(n,["enterpriseWebSearch"]);d!=null&&l(e,["enterpriseWebSearch"],d);let c=r(n,["googleMaps"]);c!=null&&l(e,["googleMaps"],c);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(ef,"toolToVertex$1");function tf(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 d=r(n,["totalTokenCount"]);d!=null&&l(e,["totalTokenCount"],d);let c=r(n,["promptTokensDetails"]);if(c!=null){let g=c;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(tf,"usageMetadataFromVertex");function nf(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(nf,"blobToMldev$1");function of(n){let e={},t=r(n,["content"]);t!=null&&l(e,["content"],t);let i=r(n,["citationMetadata"]);i!=null&&l(e,["citationMetadata"],sf(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 d=r(n,["groundingMetadata"]);d!=null&&l(e,["groundingMetadata"],d);let c=r(n,["index"]);c!=null&&l(e,["index"],c);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(of,"candidateFromMldev");function sf(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(sf,"citationMetadataFromMldev");function rf(n,e){let t={},i=r(e,["model"]);i!=null&&l(t,["_url","model"],q(n,i));let o=r(e,["contents"]);if(o!=null){let s=_e(o);Array.isArray(s)&&(s=s.map(a=>a)),l(t,["contents"],s)}return t}p(rf,"computeTokensParametersToVertex");function af(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(af,"computeTokensResponseFromVertex");function lf(n){let e={},t=r(n,["values"]);t!=null&&l(e,["values"],t);let i=r(n,["statistics"]);return i!=null&&l(e,["statistics"],df(i)),e}p(lf,"contentEmbeddingFromVertex");function df(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(df,"contentEmbeddingStatisticsFromVertex");function di(n){let e={},t=r(n,["parts"]);if(t!=null){let o=t;Array.isArray(o)&&(o=o.map(s=>yp(s))),l(e,["parts"],o)}let i=r(n,["role"]);return i!=null&&l(e,["role"],i),e}p(di,"contentToMldev$1");function cf(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(cf,"controlReferenceConfigToVertex");function uf(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(uf,"countTokensConfigToMldev");function ff(n,e){let t={},i=r(n,["systemInstruction"]);e!==void 0&&i!=null&&l(e,["systemInstruction"],ue(i));let o=r(n,["tools"]);if(e!==void 0&&o!=null){let a=o;Array.isArray(a)&&(a=a.map(d=>yl(d))),l(e,["tools"],a)}let s=r(n,["generationConfig"]);return e!==void 0&&s!=null&&l(e,["generationConfig"],ip(s)),t}p(ff,"countTokensConfigToVertex");function pf(n,e){let t={},i=r(e,["model"]);i!=null&&l(t,["_url","model"],q(n,i));let o=r(e,["contents"]);if(o!=null){let a=_e(o);Array.isArray(a)&&(a=a.map(d=>di(d))),l(t,["contents"],a)}let s=r(e,["config"]);return s!=null&&uf(s),t}p(pf,"countTokensParametersToMldev");function hf(n,e){let t={},i=r(e,["model"]);i!=null&&l(t,["_url","model"],q(n,i));let o=r(e,["contents"]);if(o!=null){let a=_e(o);Array.isArray(a)&&(a=a.map(d=>d)),l(t,["contents"],a)}let s=r(e,["config"]);return s!=null&&ff(s,t),t}p(hf,"countTokensParametersToVertex");function mf(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(mf,"countTokensResponseFromMldev");function gf(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(gf,"countTokensResponseFromVertex");function bf(n,e){let t={},i=r(e,["model"]);return i!=null&&l(t,["_url","name"],q(n,i)),t}p(bf,"deleteModelParametersToMldev");function yf(n,e){let t={},i=r(e,["model"]);return i!=null&&l(t,["_url","name"],q(n,i)),t}p(yf,"deleteModelParametersToVertex");function Ef(n){let e={},t=r(n,["sdkHttpResponse"]);return t!=null&&l(e,["sdkHttpResponse"],t),e}p(Ef,"deleteModelResponseFromMldev");function wf(n){let e={},t=r(n,["sdkHttpResponse"]);return t!=null&&l(e,["sdkHttpResponse"],t),e}p(wf,"deleteModelResponseFromVertex");function vf(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 d=r(n,["guidanceScale"]);e!==void 0&&d!=null&&l(e,["parameters","guidanceScale"],d);let c=r(n,["seed"]);e!==void 0&&c!=null&&l(e,["parameters","seed"],c);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 y=r(n,["outputCompressionQuality"]);e!==void 0&&y!=null&&l(e,["parameters","outputOptions","compressionQuality"],y);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 C=r(n,["baseSteps"]);return e!==void 0&&C!=null&&l(e,["parameters","editConfig","baseSteps"],C),t}p(vf,"editImageConfigToVertex");function If(n,e){let t={},i=r(e,["model"]);i!=null&&l(t,["_url","model"],q(n,i));let o=r(e,["prompt"]);o!=null&&l(t,["instances[0]","prompt"],o);let s=r(e,["referenceImages"]);if(s!=null){let d=s;Array.isArray(d)&&(d=d.map(c=>Tp(c))),l(t,["instances[0]","referenceImages"],d)}let a=r(e,["config"]);return a!=null&&vf(a,t),t}p(If,"editImageParametersInternalToVertex");function Cf(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=>ci(s))),l(e,["generatedImages"],o)}return e}p(Cf,"editImageResponseFromVertex");function Tf(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(Tf,"embedContentConfigToMldev");function Sf(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 d=r(n,["autoTruncate"]);return e!==void 0&&d!=null&&l(e,["parameters","autoTruncate"],d),t}p(Sf,"embedContentConfigToVertex");function _f(n,e){let t={},i=r(e,["model"]);i!=null&&l(t,["_url","model"],q(n,i));let o=r(e,["contents"]);if(o!=null){let d=os(n,o);Array.isArray(d)&&(d=d.map(c=>c)),l(t,["requests[]","content"],d)}let s=r(e,["config"]);s!=null&&Tf(s,t);let a=r(e,["model"]);return a!==void 0&&l(t,["requests[]","model"],q(n,a)),t}p(_f,"embedContentParametersToMldev");function Af(n,e){let t={},i=r(e,["model"]);i!=null&&l(t,["_url","model"],q(n,i));let o=r(e,["contents"]);if(o!=null){let a=os(n,o);Array.isArray(a)&&(a=a.map(d=>d)),l(t,["instances[]","content"],a)}let s=r(e,["config"]);return s!=null&&Sf(s,t),t}p(Af,"embedContentParametersToVertex");function xf(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(xf,"embedContentResponseFromMldev");function Pf(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=>lf(a))),l(e,["embeddings"],s)}let o=r(n,["metadata"]);return o!=null&&l(e,["metadata"],o),e}p(Pf,"embedContentResponseFromVertex");function Gf(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(Gf,"endpointFromVertex");function Nf(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(Nf,"fileDataToMldev$1");function $f(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($f,"functionCallToMldev$1");function kf(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(kf,"functionCallingConfigToMldev");function Rf(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 d=r(n,["responseJsonSchema"]);return d!=null&&l(e,["responseJsonSchema"],d),e}p(Rf,"functionDeclarationToVertex");function Df(n,e,t){let i={},o=r(e,["systemInstruction"]);t!==void 0&&o!=null&&l(t,["systemInstruction"],di(ue(o)));let s=r(e,["temperature"]);s!=null&&l(i,["temperature"],s);let a=r(e,["topP"]);a!=null&&l(i,["topP"],a);let d=r(e,["topK"]);d!=null&&l(i,["topK"],d);let c=r(e,["candidateCount"]);c!=null&&l(i,["candidateCount"],c);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 y=r(e,["seed"]);y!=null&&l(i,["seed"],y);let w=r(e,["responseMimeType"]);w!=null&&l(i,["responseMimeType"],w);let v=r(e,["responseSchema"]);v!=null&&l(i,["responseSchema"],ss(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 C=r(e,["safetySettings"]);if(t!==void 0&&C!=null){let U=C;Array.isArray(U)&&(U=U.map(ie=>Sp(ie))),l(t,["safetySettings"],U)}let T=r(e,["tools"]);if(t!==void 0&&T!=null){let U=Rt(T);Array.isArray(U)&&(U=U.map(ie=>$p(kt(ie)))),l(t,["tools"],U)}let x=r(e,["toolConfig"]);if(t!==void 0&&x!=null&&l(t,["toolConfig"],Np(x)),r(e,["labels"])!==void 0)throw new Error("labels parameter is not supported in Gemini API.");let G=r(e,["cachedContent"]);t!==void 0&&G!=null&&l(t,["cachedContent"],Oe(n,G));let S=r(e,["responseModalities"]);S!=null&&l(i,["responseModalities"],S);let N=r(e,["mediaResolution"]);N!=null&&l(i,["mediaResolution"],N);let P=r(e,["speechConfig"]);if(P!=null&&l(i,["speechConfig"],rs(P)),r(e,["audioTimestamp"])!==void 0)throw new Error("audioTimestamp parameter is not supported in Gemini API.");let $=r(e,["thinkingConfig"]);$!=null&&l(i,["thinkingConfig"],$);let F=r(e,["imageConfig"]);F!=null&&l(i,["imageConfig"],lp(F));let X=r(e,["enableEnhancedCivicAnswers"]);return X!=null&&l(i,["enableEnhancedCivicAnswers"],X),i}p(Df,"generateContentConfigToMldev");function Mf(n,e,t){let i={},o=r(e,["systemInstruction"]);t!==void 0&&o!=null&&l(t,["systemInstruction"],ue(o));let s=r(e,["temperature"]);s!=null&&l(i,["temperature"],s);let a=r(e,["topP"]);a!=null&&l(i,["topP"],a);let d=r(e,["topK"]);d!=null&&l(i,["topK"],d);let c=r(e,["candidateCount"]);c!=null&&l(i,["candidateCount"],c);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 y=r(e,["seed"]);y!=null&&l(i,["seed"],y);let w=r(e,["responseMimeType"]);w!=null&&l(i,["responseMimeType"],w);let v=r(e,["responseSchema"]);v!=null&&l(i,["responseSchema"],ss(v));let I=r(e,["responseJsonSchema"]);I!=null&&l(i,["responseJsonSchema"],I);let C=r(e,["routingConfig"]);C!=null&&l(i,["routingConfig"],C);let T=r(e,["modelSelectionConfig"]);T!=null&&l(i,["modelConfig"],T);let x=r(e,["safetySettings"]);if(t!==void 0&&x!=null){let Z=x;Array.isArray(Z)&&(Z=Z.map(he=>he)),l(t,["safetySettings"],Z)}let G=r(e,["tools"]);if(t!==void 0&&G!=null){let Z=Rt(G);Array.isArray(Z)&&(Z=Z.map(he=>yl(kt(he)))),l(t,["tools"],Z)}let S=r(e,["toolConfig"]);t!==void 0&&S!=null&&l(t,["toolConfig"],S);let N=r(e,["labels"]);t!==void 0&&N!=null&&l(t,["labels"],N);let P=r(e,["cachedContent"]);t!==void 0&&P!=null&&l(t,["cachedContent"],Oe(n,P));let $=r(e,["responseModalities"]);$!=null&&l(i,["responseModalities"],$);let F=r(e,["mediaResolution"]);F!=null&&l(i,["mediaResolution"],F);let X=r(e,["speechConfig"]);X!=null&&l(i,["speechConfig"],bl(rs(X)));let U=r(e,["audioTimestamp"]);U!=null&&l(i,["audioTimestamp"],U);let ie=r(e,["thinkingConfig"]);ie!=null&&l(i,["thinkingConfig"],ie);let ve=r(e,["imageConfig"]);if(ve!=null&&l(i,["imageConfig"],dp(ve)),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"],q(n,i));let o=r(e,["contents"]);if(o!=null){let a=_e(o);Array.isArray(a)&&(a=a.map(d=>di(d))),l(t,["contents"],a)}let s=r(e,["config"]);return s!=null&&l(t,["generationConfig"],Df(n,s,t)),t}p(Ra,"generateContentParametersToMldev");function Da(n,e){let t={},i=r(e,["model"]);i!=null&&l(t,["_url","model"],q(n,i));let o=r(e,["contents"]);if(o!=null){let a=_e(o);Array.isArray(a)&&(a=a.map(d=>d)),l(t,["contents"],a)}let s=r(e,["config"]);return s!=null&&l(t,["generationConfig"],Mf(n,s,t)),t}p(Da,"generateContentParametersToVertex");function Ma(n){let e={},t=r(n,["sdkHttpResponse"]);t!=null&&l(e,["sdkHttpResponse"],t);let i=r(n,["candidates"]);if(i!=null){let c=i;Array.isArray(c)&&(c=c.map(u=>of(u))),l(e,["candidates"],c)}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 d=r(n,["usageMetadata"]);return d!=null&&l(e,["usageMetadata"],d),e}p(Ma,"generateContentResponseFromMldev");function La(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 d=r(n,["responseId"]);d!=null&&l(e,["responseId"],d);let c=r(n,["usageMetadata"]);return c!=null&&l(e,["usageMetadata"],c),e}p(La,"generateContentResponseFromVertex");function Lf(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 d=r(n,["personGeneration"]);e!==void 0&&d!=null&&l(e,["parameters","personGeneration"],d);let c=r(n,["includeSafetyAttributes"]);e!==void 0&&c!=null&&l(e,["parameters","includeSafetyAttributes"],c);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(Lf,"generateImagesConfigToMldev");function Uf(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 d=r(n,["guidanceScale"]);e!==void 0&&d!=null&&l(e,["parameters","guidanceScale"],d);let c=r(n,["seed"]);e!==void 0&&c!=null&&l(e,["parameters","seed"],c);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 y=r(n,["outputCompressionQuality"]);e!==void 0&&y!=null&&l(e,["parameters","outputOptions","compressionQuality"],y);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 C=r(n,["enhancePrompt"]);return e!==void 0&&C!=null&&l(e,["parameters","enhancePrompt"],C),t}p(Uf,"generateImagesConfigToVertex");function Ff(n,e){let t={},i=r(e,["model"]);i!=null&&l(t,["_url","model"],q(n,i));let o=r(e,["prompt"]);o!=null&&l(t,["instances[0]","prompt"],o);let s=r(e,["config"]);return s!=null&&Lf(s,t),t}p(Ff,"generateImagesParametersToMldev");function Bf(n,e){let t={},i=r(e,["model"]);i!=null&&l(t,["_url","model"],q(n,i));let o=r(e,["prompt"]);o!=null&&l(t,["instances[0]","prompt"],o);let s=r(e,["config"]);return s!=null&&Uf(s,t),t}p(Bf,"generateImagesParametersToVertex");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=>jf(a))),l(e,["generatedImages"],s)}let o=r(n,["positivePromptSafetyAttributes"]);return o!=null&&l(e,["positivePromptSafetyAttributes"],ml(o)),e}p(Vf,"generateImagesResponseFromMldev");function qf(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=>ci(a))),l(e,["generatedImages"],s)}let o=r(n,["positivePromptSafetyAttributes"]);return o!=null&&l(e,["positivePromptSafetyAttributes"],gl(o)),e}p(qf,"generateImagesResponseFromVertex");function Of(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 d=r(n,["personGeneration"]);if(e!==void 0&&d!=null&&l(e,["parameters","personGeneration"],d),r(n,["pubsubTopic"])!==void 0)throw new Error("pubsubTopic parameter is not supported in Gemini API.");let c=r(n,["negativePrompt"]);e!==void 0&&c!=null&&l(e,["parameters","negativePrompt"],c);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"],ui(f));let h=r(n,["referenceImages"]);if(e!==void 0&&h!=null){let m=h;Array.isArray(m)&&(m=m.map(g=>zp(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(Of,"generateVideosConfigToMldev");function Hf(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 d=r(n,["seed"]);e!==void 0&&d!=null&&l(e,["parameters","seed"],d);let c=r(n,["aspectRatio"]);e!==void 0&&c!=null&&l(e,["parameters","aspectRatio"],c);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 y=r(n,["lastFrame"]);e!==void 0&&y!=null&&l(e,["instances[0]","lastFrame"],De(y));let w=r(n,["referenceImages"]);if(e!==void 0&&w!=null){let C=w;Array.isArray(C)&&(C=C.map(T=>Kp(T))),l(e,["instances[0]","referenceImages"],C)}let v=r(n,["mask"]);e!==void 0&&v!=null&&l(e,["instances[0]","mask"],Hp(v));let I=r(n,["compressionQuality"]);return e!==void 0&&I!=null&&l(e,["parameters","compressionQuality"],I),t}p(Hf,"generateVideosConfigToVertex");function zf(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"],Yf(a)),e}p(zf,"generateVideosOperationFromMldev");function Kf(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"],Xf(a)),e}p(Kf,"generateVideosOperationFromVertex");function Jf(n,e){let t={},i=r(e,["model"]);i!=null&&l(t,["_url","model"],q(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"],ui(s));let a=r(e,["video"]);a!=null&&l(t,["instances[0]","video"],El(a));let d=r(e,["source"]);d!=null&&Qf(d,t);let c=r(e,["config"]);return c!=null&&Of(c,t),t}p(Jf,"generateVideosParametersToMldev");function Wf(n,e){let t={},i=r(e,["model"]);i!=null&&l(t,["_url","model"],q(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"],De(s));let a=r(e,["video"]);a!=null&&l(t,["instances[0]","video"],wl(a));let d=r(e,["source"]);d!=null&&Zf(d,t);let c=r(e,["config"]);return c!=null&&Hf(c,t),t}p(Wf,"generateVideosParametersToVertex");function Yf(n){let e={},t=r(n,["generatedSamples"]);if(t!=null){let s=t;Array.isArray(s)&&(s=s.map(a=>tp(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(Yf,"generateVideosResponseFromMldev");function Xf(n){let e={},t=r(n,["videos"]);if(t!=null){let s=t;Array.isArray(s)&&(s=s.map(a=>np(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,"generateVideosResponseFromVertex");function Qf(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"],ui(o));let s=r(n,["video"]);return e!==void 0&&s!=null&&l(e,["instances[0]","video"],El(s)),t}p(Qf,"generateVideosSourceToMldev");function Zf(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"],De(o));let s=r(n,["video"]);return e!==void 0&&s!=null&&l(e,["instances[0]","video"],wl(s)),t}p(Zf,"generateVideosSourceToVertex");function jf(n){let e={},t=r(n,["_self"]);t!=null&&l(e,["image"],cp(t));let i=r(n,["raiFilteredReason"]);i!=null&&l(e,["raiFilteredReason"],i);let o=r(n,["_self"]);return o!=null&&l(e,["safetyAttributes"],ml(o)),e}p(jf,"generatedImageFromMldev");function ci(n){let e={},t=r(n,["_self"]);t!=null&&l(e,["image"],hl(t));let i=r(n,["raiFilteredReason"]);i!=null&&l(e,["raiFilteredReason"],i);let o=r(n,["_self"]);o!=null&&l(e,["safetyAttributes"],gl(o));let s=r(n,["prompt"]);return s!=null&&l(e,["enhancedPrompt"],s),e}p(ci,"generatedImageFromVertex");function ep(n){let e={},t=r(n,["_self"]);t!=null&&l(e,["mask"],hl(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(ep,"generatedImageMaskFromVertex");function tp(n){let e={},t=r(n,["video"]);return t!=null&&l(e,["video"],qp(t)),e}p(tp,"generatedVideoFromMldev");function np(n){let e={},t=r(n,["_self"]);return t!=null&&l(e,["video"],Op(t)),e}p(np,"generatedVideoFromVertex");function ip(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 d=r(n,["frequencyPenalty"]);d!=null&&l(e,["frequencyPenalty"],d);let c=r(n,["logprobs"]);c!=null&&l(e,["logprobs"],c);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 y=r(n,["responseSchema"]);y!=null&&l(e,["responseSchema"],y);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"],bl(I));let C=r(n,["stopSequences"]);C!=null&&l(e,["stopSequences"],C);let T=r(n,["temperature"]);T!=null&&l(e,["temperature"],T);let x=r(n,["thinkingConfig"]);x!=null&&l(e,["thinkingConfig"],x);let G=r(n,["topK"]);G!=null&&l(e,["topK"],G);let S=r(n,["topP"]);if(S!=null&&l(e,["topP"],S),r(n,["enableEnhancedCivicAnswers"])!==void 0)throw new Error("enableEnhancedCivicAnswers parameter is not supported in Vertex AI.");return e}p(ip,"generationConfigToVertex");function op(n,e){let t={},i=r(e,["model"]);return i!=null&&l(t,["_url","name"],q(n,i)),t}p(op,"getModelParametersToMldev");function sp(n,e){let t={},i=r(e,["model"]);return i!=null&&l(t,["_url","name"],q(n,i)),t}p(sp,"getModelParametersToVertex");function rp(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(rp,"googleMapsToMldev$1");function ap(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(ap,"googleSearchToMldev$1");function lp(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(lp,"imageConfigToMldev");function dp(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(dp,"imageConfigToVertex");function cp(n){let e={},t=r(n,["bytesBase64Encoded"]);t!=null&&l(e,["imageBytes"],Je(t));let i=r(n,["mimeType"]);return i!=null&&l(e,["mimeType"],i),e}p(cp,"imageFromMldev");function hl(n){let e={},t=r(n,["gcsUri"]);t!=null&&l(e,["gcsUri"],t);let i=r(n,["bytesBase64Encoded"]);i!=null&&l(e,["imageBytes"],Je(i));let o=r(n,["mimeType"]);return o!=null&&l(e,["mimeType"],o),e}p(hl,"imageFromVertex");function ui(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"],Je(t));let i=r(n,["mimeType"]);return i!=null&&l(e,["mimeType"],i),e}p(ui,"imageToMldev");function De(n){let e={},t=r(n,["gcsUri"]);t!=null&&l(e,["gcsUri"],t);let i=r(n,["imageBytes"]);i!=null&&l(e,["bytesBase64Encoded"],Je(i));let o=r(n,["mimeType"]);return o!=null&&l(e,["mimeType"],o),e}p(De,"imageToVertex");function up(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 d=r(e,["queryBase"]);return t!==void 0&&d!=null&&l(t,["_url","models_url"],rl(n,d)),i}p(up,"listModelsConfigToMldev");function fp(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 d=r(e,["queryBase"]);return t!==void 0&&d!=null&&l(t,["_url","models_url"],rl(n,d)),i}p(fp,"listModelsConfigToVertex");function pp(n,e){let t={},i=r(e,["config"]);return i!=null&&up(n,i,t),t}p(pp,"listModelsParametersToMldev");function hp(n,e){let t={},i=r(e,["config"]);return i!=null&&fp(n,i,t),t}p(hp,"listModelsParametersToVertex");function mp(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=al(o);Array.isArray(s)&&(s=s.map(a=>Po(a))),l(e,["models"],s)}return e}p(mp,"listModelsResponseFromMldev");function gp(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=al(o);Array.isArray(s)&&(s=s.map(a=>Go(a))),l(e,["models"],s)}return e}p(gp,"listModelsResponseFromVertex");function bp(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(bp,"maskReferenceConfigToVertex");function Po(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"],kp(a));let d=r(n,["inputTokenLimit"]);d!=null&&l(e,["inputTokenLimit"],d);let c=r(n,["outputTokenLimit"]);c!=null&&l(e,["outputTokenLimit"],c);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(Po,"modelFromMldev");function Go(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=>Gf(m))),l(e,["endpoints"],h)}let d=r(n,["labels"]);d!=null&&l(e,["labels"],d);let c=r(n,["_self"]);c!=null&&l(e,["tunedModelInfo"],Rp(c));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(Go,"modelFromVertex");function yp(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"],Nf(s));let a=r(n,["functionCall"]);a!=null&&l(e,["functionCall"],$f(a));let d=r(n,["functionResponse"]);d!=null&&l(e,["functionResponse"],d);let c=r(n,["inlineData"]);c!=null&&l(e,["inlineData"],nf(c));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(yp,"partToMldev$1");function Ep(n){let e={},t=r(n,["productImage"]);return t!=null&&l(e,["image"],De(t)),e}p(Ep,"productImageToVertex");function wp(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 d=r(n,["safetyFilterLevel"]);e!==void 0&&d!=null&&l(e,["parameters","safetySetting"],d);let c=r(n,["personGeneration"]);e!==void 0&&c!=null&&l(e,["parameters","personGeneration"],c);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(wp,"recontextImageConfigToVertex");function vp(n,e){let t={},i=r(e,["model"]);i!=null&&l(t,["_url","model"],q(n,i));let o=r(e,["source"]);o!=null&&Cp(o,t);let s=r(e,["config"]);return s!=null&&wp(s,t),t}p(vp,"recontextImageParametersToVertex");function Ip(n){let e={},t=r(n,["predictions"]);if(t!=null){let i=t;Array.isArray(i)&&(i=i.map(o=>ci(o))),l(e,["generatedImages"],i)}return e}p(Ip,"recontextImageResponseFromVertex");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,["personImage"]);e!==void 0&&o!=null&&l(e,["instances[0]","personImage","image"],De(o));let s=r(n,["productImages"]);if(e!==void 0&&s!=null){let a=s;Array.isArray(a)&&(a=a.map(d=>Ep(d))),l(e,["instances[0]","productImages"],a)}return t}p(Cp,"recontextImageSourceToVertex");function Tp(n){let e={},t=r(n,["referenceImage"]);t!=null&&l(e,["referenceImage"],De(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"],bp(s));let a=r(n,["controlImageConfig"]);a!=null&&l(e,["controlImageConfig"],cf(a));let d=r(n,["styleImageConfig"]);d!=null&&l(e,["styleImageConfig"],d);let c=r(n,["subjectImageConfig"]);return c!=null&&l(e,["subjectImageConfig"],c),e}p(Tp,"referenceImageAPIInternalToVertex");function ml(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(ml,"safetyAttributesFromMldev");function gl(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(gl,"safetyAttributesFromVertex");function Sp(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(Sp,"safetySettingToMldev");function _p(n){let e={},t=r(n,["image"]);return t!=null&&l(e,["image"],De(t)),e}p(_p,"scribbleImageToVertex");function Ap(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 d=r(n,["binaryColorThreshold"]);e!==void 0&&d!=null&&l(e,["parameters","binaryColorThreshold"],d);let c=r(n,["labels"]);return e!==void 0&&c!=null&&l(e,["labels"],c),t}p(Ap,"segmentImageConfigToVertex");function xp(n,e){let t={},i=r(e,["model"]);i!=null&&l(t,["_url","model"],q(n,i));let o=r(e,["source"]);o!=null&&Gp(o,t);let s=r(e,["config"]);return s!=null&&Ap(s,t),t}p(xp,"segmentImageParametersToVertex");function Pp(n){let e={},t=r(n,["predictions"]);if(t!=null){let i=t;Array.isArray(i)&&(i=i.map(o=>ep(o))),l(e,["generatedMasks"],i)}return e}p(Pp,"segmentImageResponseFromVertex");function Gp(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"],De(o));let s=r(n,["scribbleImage"]);return e!==void 0&&s!=null&&l(e,["instances[0]","scribble"],_p(s)),t}p(Gp,"segmentImageSourceToVertex");function bl(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(bl,"speechConfigToVertex");function Np(n){let e={},t=r(n,["functionCallingConfig"]);t!=null&&l(e,["functionCallingConfig"],kf(t));let i=r(n,["retrievalConfig"]);return i!=null&&l(e,["retrievalConfig"],i),e}p(Np,"toolConfigToMldev");function $p(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 d=r(n,["googleMaps"]);d!=null&&l(e,["googleMaps"],rp(d));let c=r(n,["googleSearch"]);c!=null&&l(e,["googleSearch"],ap(c));let u=r(n,["urlContext"]);return u!=null&&l(e,["urlContext"],u),e}p($p,"toolToMldev$1");function yl(n){let e={},t=r(n,["functionDeclarations"]);if(t!=null){let h=t;Array.isArray(h)&&(h=h.map(m=>Rf(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 d=r(n,["enterpriseWebSearch"]);d!=null&&l(e,["enterpriseWebSearch"],d);let c=r(n,["googleMaps"]);c!=null&&l(e,["googleMaps"],c);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(yl,"toolToVertex");function kp(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(kp,"tunedModelInfoFromMldev");function Rp(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(Rp,"tunedModelInfoFromVertex");function Dp(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(Dp,"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 Lp(n,e){let t={},i=r(e,["model"]);i!=null&&l(t,["_url","name"],q(n,i));let o=r(e,["config"]);return o!=null&&Dp(o,t),t}p(Lp,"updateModelParametersToMldev");function Up(n,e){let t={},i=r(e,["model"]);i!=null&&l(t,["_url","model"],q(n,i));let o=r(e,["config"]);return o!=null&&Mp(o,t),t}p(Up,"updateModelParametersToVertex");function Fp(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 d=r(n,["outputMimeType"]);e!==void 0&&d!=null&&l(e,["parameters","outputOptions","mimeType"],d);let c=r(n,["outputCompressionQuality"]);e!==void 0&&c!=null&&l(e,["parameters","outputOptions","compressionQuality"],c);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(Fp,"upscaleImageAPIConfigInternalToVertex");function Bp(n,e){let t={},i=r(e,["model"]);i!=null&&l(t,["_url","model"],q(n,i));let o=r(e,["image"]);o!=null&&l(t,["instances[0]","image"],De(o));let s=r(e,["upscaleFactor"]);s!=null&&l(t,["parameters","upscaleConfig","upscaleFactor"],s);let a=r(e,["config"]);return a!=null&&Fp(a,t),t}p(Bp,"upscaleImageAPIParametersInternalToVertex");function Vp(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=>ci(s))),l(e,["generatedImages"],o)}return e}p(Vp,"upscaleImageResponseFromVertex");function qp(n){let e={},t=r(n,["uri"]);t!=null&&l(e,["uri"],t);let i=r(n,["encodedVideo"]);i!=null&&l(e,["videoBytes"],Je(i));let o=r(n,["encoding"]);return o!=null&&l(e,["mimeType"],o),e}p(qp,"videoFromMldev");function Op(n){let e={},t=r(n,["gcsUri"]);t!=null&&l(e,["uri"],t);let i=r(n,["bytesBase64Encoded"]);i!=null&&l(e,["videoBytes"],Je(i));let o=r(n,["mimeType"]);return o!=null&&l(e,["mimeType"],o),e}p(Op,"videoFromVertex");function Hp(n){let e={},t=r(n,["image"]);t!=null&&l(e,["_self"],De(t));let i=r(n,["maskMode"]);return i!=null&&l(e,["maskMode"],i),e}p(Hp,"videoGenerationMaskToVertex");function zp(n){let e={},t=r(n,["image"]);t!=null&&l(e,["image"],ui(t));let i=r(n,["referenceType"]);return i!=null&&l(e,["referenceType"],i),e}p(zp,"videoGenerationReferenceImageToMldev");function Kp(n){let e={},t=r(n,["image"]);t!=null&&l(e,["image"],De(t));let i=r(n,["referenceType"]);return i!=null&&l(e,["referenceType"],i),e}p(Kp,"videoGenerationReferenceImageToVertex");function El(n){let e={},t=r(n,["uri"]);t!=null&&l(e,["uri"],t);let i=r(n,["videoBytes"]);i!=null&&l(e,["encodedVideo"],Je(i));let o=r(n,["mimeType"]);return o!=null&&l(e,["encoding"],o),e}p(El,"videoToMldev");function wl(n){let e={},t=r(n,["uri"]);t!=null&&l(e,["gcsUri"],t);let i=r(n,["videoBytes"]);i!=null&&l(e,["bytesBase64Encoded"],Je(i));let o=r(n,["mimeType"]);return o!=null&&l(e,["mimeType"],o),e}p(wl,"videoToVertex");function Jp(n,e){let t={},i=r(n,["displayName"]);return e!==void 0&&i!=null&&l(e,["displayName"],i),t}p(Jp,"createFileSearchStoreConfigToMldev");function Wp(n){let e={},t=r(n,["config"]);return t!=null&&Jp(t,e),e}p(Wp,"createFileSearchStoreParametersToMldev");function Yp(n,e){let t={},i=r(n,["force"]);return e!==void 0&&i!=null&&l(e,["_query","force"],i),t}p(Yp,"deleteFileSearchStoreConfigToMldev");function Xp(n){let e={},t=r(n,["name"]);t!=null&&l(e,["_url","name"],t);let i=r(n,["config"]);return i!=null&&Yp(i,e),e}p(Xp,"deleteFileSearchStoreParametersToMldev");function Qp(n){let e={},t=r(n,["name"]);return t!=null&&l(e,["_url","name"],t),e}p(Qp,"getFileSearchStoreParametersToMldev");function Zp(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(Zp,"importFileConfigToMldev");function jp(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"],th(a)),e}p(jp,"importFileOperationFromMldev");function eh(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&&Zp(o,e),e}p(eh,"importFileParametersToMldev");function th(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(th,"importFileResponseFromMldev");function nh(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(nh,"listFileSearchStoresConfigToMldev");function ih(n){let e={},t=r(n,["config"]);return t!=null&&nh(t,e),e}p(ih,"listFileSearchStoresParametersToMldev");function oh(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(oh,"listFileSearchStoresResponseFromMldev");function vl(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 d=s;Array.isArray(d)&&(d=d.map(c=>c)),l(e,["customMetadata"],d)}let a=r(n,["chunkingConfig"]);return e!==void 0&&a!=null&&l(e,["chunkingConfig"],a),t}p(vl,"uploadToFileSearchStoreConfigToMldev");function sh(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&&vl(i,e),e}p(sh,"uploadToFileSearchStoreParametersToMldev");function rh(n){let e={},t=r(n,["sdkHttpResponse"]);return t!=null&&l(e,["sdkHttpResponse"],t),e}p(rh,"uploadToFileSearchStoreResumableResponseFromMldev");var ah="Content-Type",lh="X-Server-Timeout",dh="User-Agent",No="x-goog-api-client",ch="1.33.0",uh=`google-genai-sdk/${ch}`,fh="v1beta1",ph="v1beta",$o=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:fh,o.baseUrl=this.baseUrlFromProjectLocation(),this.normalizeAuthParameters()):(o.apiVersion=(i=this.clientOptions.apiVersion)!==null&&i!==void 0?i:ph,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,d]of Object.entries(e.queryParams))o.searchParams.append(a,String(d));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 d=setTimeout(()=>s.abort(),t.timeout);d&&typeof d.unref=="function"&&d.unref()}o&&o.addEventListener("abort",()=>{s.abort()}),e.signal=a}return t&&t.extraBody!==null&&hh(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 Ua(o),new zt(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 Ua(o),this.processStreamResponse(o))).catch(o=>{throw o instanceof Error?o:new Error(JSON.stringify(o))})}processStreamResponse(e){return $e(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="",d="data:",c=[`
661
+ latestAddr: ${d.latestAddr} (I: d0adcc392e6e974c9917730ebad51322)`),this._currentWorkingContextIbGib=d.latestIbGib??await this.getContextIbGibFromArgOrAddr({addr:d.latestAddr,latest:!1}),this._updatingContext?K&&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: ${hr({err:d})}. (E: 99df4c42195d46d0a9dbfb06ac45ae00)`)},"error")})),i&&await this.rel8To({ibGibs:[this._currentWorkingContextIbGib],rel8nName:i})}catch(s){throw console.error(`${o} ${E(s)}`),s}finally{K&&console.log(`${o} complete.`)}}async finalizeContext({arg:e}){let t=`${this.lc}[${this.finalizeContext.name}]`;try{K&&console.log(`${t} starting... (I: dd53dfc745864dd19fde5f209ceb82c8)`);let i=0,o=100;for(;this._updatingContext&&i<o;)await z(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} ${E(i)}`),i}finally{this._updatingContext=!1,K&&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 z(1e3);this._updatingContext=!0;try{if(K&&console.log(`${t} starting... (I: 3eeaa40cad49094f125f9f5cd6ff6e22)`),K&&(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{K&&console.log(`${t} no new children in context update. returning early... (I: 31397b04965351ab29bb3f78cb709122)`);return}}catch(i){throw console.error(`${t} ${E(i)}`),i}finally{this._updatingContext=!1,K&&console.log(`${t} complete.`)}}async getNewChildrenIbGibs({newContext:e}){let t=`${this.lc}[${this.getNewChildrenIbGibs.name}]`;try{K&&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 K&&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 Os({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} ${E(i)}`),i}finally{K&&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} ${E(i)}`),i}}};var fe=Q,Ke=class extends Sn{static{p(this,"LiveProxyIbGib")}lc="";ib=this._currentWorkingContextIbGib?this._currentWorkingContextIbGib.ib:rn;gib=this._currentWorkingContextIbGib?this._currentWorkingContextIbGib.gib:an;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{fe&&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} ${E(t)}`),t}finally{fe&&console.log(`${e} complete.`)}}async loadIbGibDto(e){let t=`${this.lc}[${this.loadIbGibDto.name}]`;try{fe&&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} ${E(i)}`),i}finally{fe&&console.log(`${t} complete.`)}}async validateThis(){let e=`${this.lc}[${this.validateThis.name}]`;return fe&&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{fe&&console.log(`${e} starting... (I: 1bd72217a5f334effc63f8d51e7b2225)`),await super.initialize(),this._contextUpdated$=await qi(),this.contextUpdated$=this._contextUpdated$.asObservable(),this._newContextChild$=await qi(),this.newContextChild$=this._newContextChild$.asObservable()}catch(t){throw console.error(`${e} ${E(t)}`),t}finally{fe&&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(fe&&console.log(`${t} starting...`),Bs({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,fe&&console.log(`${t} spaceId set to the ${i} (I: 018724a5431ba421b71fad36924c5a25)`),Ie.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}),Ut}}catch(i){throw console.error(`${t} ${i.message}`),i}finally{fe&&console.log(`${t} complete.`)}}_contextUpdated$;contextUpdated$;_newContextChild$;newContextChild$;async handleContextUpdate({update:e}){let t=`${this.lc}[${this.handleContextUpdate.name}]`;try{if(fe&&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} ${E(i)}`),i}finally{fe&&console.log(`${t} complete.`)}}async setWrappedIbGib({ibGib:e,ibGibAddr:t,space:i}){let o=`${this.lc}[${this.setWrappedIbGib.name}]`;try{if(fe&&console.log(`${o} starting... (I: a4b0acda259c121801aa701534320125)`),this.metaspace||(this.metaspace=await k()),!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} ${E(s)}`),s}finally{fe&&console.log(`${o} complete.`)}}async handleNewContextChild({newChild:e}){let t=`[${this.handleNewContextChild.name}]`;try{if(fe&&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} ${E(i)}`),i}finally{fe&&console.log(`${t} complete.`)}}};var Ct="witness_agent",Tt=/^[a-zA-Z0-9_\-.]{1,32}$/,Ji=/.{1,255}/,xr="",Pr="Manco",Nr="This is a generic, unspecified agent.";var _n="List of function info ibgib addresses. These contain info on both the requests you made and the resultant values.",dt="agent",Mb={type:"string",description:"unique identifier for the agent. Should be provided to the agent in system instructions upon creation."},Lb={type:"string",description:"type of the agent that governs basic responsibilities. Should be provided to the agent in system instructions upon creation."};var Sc="hardcoded",_c="human",Ac="ai",xc="function",Pc="unknown",ee={HARDCODED:Sc,HUMAN:_c,AI:Ac,FUNCTION:xc,UNKNOWN:Pc},Yi=Object.freeze(Object.values(ee));function Gr(n){return!!n&&Yi.includes(n)}p(Gr,"isTextSource");var Ub={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: ${Tt.source}`},$r="primaryagent";var kr=!1;async function Xi({ibGib:n,addr:e,tagIbGib:t,metaspace:i,space:o}){let s=`[${Xi.name}]`;try{if(kr&&console.log(`${s} starting... (I: b1fd25ec28bce8f1916b4ab55f48a724)`),!e&&!n)throw new Error("either addr or ibGib required (E: 3d580f8ecc251a0c81c7ea8bc3d38524)");if(e??=_({ibGib:n}),e!==_({ibGib:n}))throw new Error(`addr (${e}) differs from incoming ibGib's addr (${_({ibGib:n})}). (E: f2c14234a78c917fb9f587beaee89324)`);let a=await i.getLatestAddr({ibGib:t,space:o});if(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={[Fs]:[e]},d=await it({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} ${E(a)}`),a}finally{kr&&console.log(`${s} complete.`)}}p(Xi,"rel8ToTag");var le=Q,Zi=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;le&&console.log(`${t} starting... (I: 0c4214b4614a43bd2825978e54aee325)`);let a=this.latestAgents.get(i);if(!a){let c=await k();a=(await An({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: ${V(e)} (W: 70cf51ecbe68dfdcfe1e9995a7468f25)`),a}catch(i){throw console.error(`${t} ${E(i)}`),i}finally{le&&console.log(`${t} complete.`)}}async updateOrSetLatestAgent({agent:e,throwIfNewerFound:t}){let i=`${this.lc}[${this.updateOrSetLatestAgent.name}]`;try{if(le&&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.
662
+ existing: ${V(J({ibGib:o}))}
663
+ new: ${V(J({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} ${E(o)}`),o}finally{le&&console.log(`${i} complete.`)}}getLatestAgent({id:e}){let t=`${this.lc}[${this.getLatestAgent.name}]`;try{return le&&console.log(`${t} starting... (I: 8e85b55057760b712a913a92e88ead25)`),Promise.resolve(this.latestAgents.get(e))}catch(i){throw console.error(`${t} ${E(i)}`),i}finally{le&&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(le&&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} ${E(o)}`),o}finally{le&&console.log(`${i} complete.`)}}async getAgentByAddr({agentAddr:e,spaceId:t,metaspace:i}){let o=`${this.lc}[${this.getAgentByAddr.name}]`;try{if(le&&console.log(`${o} starting... (I: 42dfecbe6d6b5a3a7d392af5a66cc625)`),!e)throw new Error(`${o} agentAddr is required. (E: 389351659a2e08fa179ceede16925a25)`);let{ib:s}=B({ibGibAddr:e}),{uuid:a,type:c}=Rr({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 le&&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 k();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){le&&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}),le&&console.log(`${o} Cached agent witness with id ${a}. (I: b862f63147a3fac3c6e6210d5ab87c25)`),le&&console.log(`${o} complete. Retrieved and cached agent witness for address ${e}.`),m}catch(s){throw console.error(`${o} ${E(s)}`),s}}async createNewAgent(e){let t=`[${this.createNewAgent.name}]`;try{le&&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=eo(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 y=await m.createInitialRel8ns(),w=await Ie.firstGen({ib:to({data:g}),parentIbGib:Ie.primitive({ib:Ct}),data:g,rel8ns:y,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 T=await ji({metaspace:i,space:o}),x=await Xi({ibGib:v,metaspace:i,space:o,tagIbGib:T})}await re({type:h,rel8nInfos:[{rel8nName:dt,ibGibs:[v]}],metaspace:i,space:o}),a.length>0&&await I.addAvailableFunctions(a);let C=[];return C.push({textSrc:"hardcoded",text:St({tagText:Ws,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&&C.push({textSrc:"hardcoded",text:c,isSystem:!0}),d&&C.push({textSrc:"hardcoded",text:d}),await I.addTexts({infos:C}),this.latestAgents.set(I.data.uuid,I),I}catch(i){throw console.error(`${t} ${E(i)}`),i}finally{le&&console.log(`${t} complete.`)}}getAgents(e){let t=`${this.lc}[${this.getAgents.name}]`;try{return le&&console.log(`${t} starting... (I: 4663f125c3a21fa3ecccc2c5a38d1225)`),An(e)}catch(i){throw console.error(`${t} ${E(i)}`),i}finally{le&&console.log(`${t} complete.`)}}},Qi;function Ue(){return Qi||(Qi=new Zi),Qi}p(Ue,"getAgentsSvc");var Nc="gemini-3.1-pro-preview",Gc="gemini-3-flash-preview",$c="gemini-3.1-flash-lite-preview",kc="gemini-3.1-flash-live-preview",Rc="gemini-2.5-pro",Dc="gemini-2.5-flash",Mc="gemini-2.5-flash-lite",Lc="gemini-2.5-flash-preview-tts",Uc="gemini-2.0-flash",Fc="gemini-2.0-flash-lite",no={GEMINI_3_1_PRO_PREVIEW:Nc,GEMINI_3_FLASH_PREVIEW:Gc,GEMINI_3_1_FLASH_LITE_PREVIEW:$c,GEMINI_3_1_FLASH_LIVE_PREVIEW:kc,GEMINI_2_5_PRO:Rc,GEMINI_2_5_FLASH:Dc,GEMINI_2_5_FLASH_LITE:Mc,GEMINI_2_5_FLASH_PREVIEW_TTS:Lc,GEMINI_2_0_FLASH:Uc,GEMINI_2_0_FLASH_LITE:Fc},ry=Object.freeze(Object.values(no));var Dr=no.GEMINI_2_5_FLASH,_t=no.GEMINI_2_5_FLASH_LITE,io=5;var Mr={version:"1",uuid:xr,name:Pr,description:Nr,classname:"AgentWitness_V1",icon:"happy",persistOptsAndResultIbGibs:!1,allowPrimitiveArgs:!0,catchAllErrors:!0,trace:!1,subSpaceId:"",superSpaceId:"",availableFunctionNameOrIds:[],model:Dr,api:"gemini",type:$r,"@currentContextTjpAddr":Z},oo=void 0;var Bc,Vc;function Oc(){return{geminiUrl:Bc,vertexUrl:Vc}}p(Oc,"getDefaultBaseUrls");function qc(n,e,t,i){var o,s;if(!n?.baseUrl){let a=Oc();return e?(o=a.vertexUrl)!==null&&o!==void 0?o:t:(s=a.geminiUrl)!==null&&s!==void 0?s:i}return n.baseUrl}p(qc,"getBaseUrl");var Re=class{static{p(this,"BaseModule")}};function A(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(A,"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 Hc(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)}lo(n,o,s,0,a)}}p(Hc,"moveValueByPath");function lo(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])lo(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&&lo(a[s],e,t,i+1,o)}}p(lo,"_moveValueRecursive");function as(n){if(typeof n!="string")throw new Error("fromImageBytes must be a string");return n}p(as,"tBytes$1");function zc(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(zc,"fetchPredictOperationParametersToVertex");function Kc(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"],Jc(a)),e}p(Kc,"generateVideosOperationFromMldev$1");function Wc(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"],Yc(a)),e}p(Wc,"generateVideosOperationFromVertex$1");function Jc(n){let e={},t=r(n,["generatedSamples"]);if(t!=null){let s=t;Array.isArray(s)&&(s=s.map(a=>Xc(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(Jc,"generateVideosResponseFromMldev$1");function Yc(n){let e={},t=r(n,["videos"]);if(t!=null){let s=t;Array.isArray(s)&&(s=s.map(a=>Qc(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(Yc,"generateVideosResponseFromVertex$1");function Xc(n){let e={},t=r(n,["video"]);return t!=null&&l(e,["video"],id(t)),e}p(Xc,"generatedVideoFromMldev$1");function Qc(n){let e={},t=r(n,["_self"]);return t!=null&&l(e,["video"],od(t)),e}p(Qc,"generatedVideoFromVertex$1");function Zc(n){let e={},t=r(n,["operationName"]);return t!=null&&l(e,["_url","operationName"],t),e}p(Zc,"getOperationParametersToMldev");function jc(n){let e={},t=r(n,["operationName"]);return t!=null&&l(e,["_url","operationName"],t),e}p(jc,"getOperationParametersToVertex");function ed(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"],td(a)),e}p(ed,"importFileOperationFromMldev$1");function td(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(td,"importFileResponseFromMldev$1");function sl(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"],nd(a)),e}p(sl,"uploadToFileSearchStoreOperationFromMldev");function nd(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(nd,"uploadToFileSearchStoreResponseFromMldev");function id(n){let e={},t=r(n,["uri"]);t!=null&&l(e,["uri"],t);let i=r(n,["encodedVideo"]);i!=null&&l(e,["videoBytes"],as(i));let o=r(n,["encoding"]);return o!=null&&l(e,["mimeType"],o),e}p(id,"videoFromMldev$1");function od(n){let e={},t=r(n,["gcsUri"]);t!=null&&l(e,["uri"],t);let i=r(n,["bytesBase64Encoded"]);i!=null&&l(e,["videoBytes"],as(i));let o=r(n,["mimeType"]);return o!=null&&l(e,["mimeType"],o),e}p(od,"videoFromVertex$1");var Lr;(function(n){n.OUTCOME_UNSPECIFIED="OUTCOME_UNSPECIFIED",n.OUTCOME_OK="OUTCOME_OK",n.OUTCOME_FAILED="OUTCOME_FAILED",n.OUTCOME_DEADLINE_EXCEEDED="OUTCOME_DEADLINE_EXCEEDED"})(Lr||(Lr={}));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 We;(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"})(We||(We={}));var Br;(function(n){n.MODE_UNSPECIFIED="MODE_UNSPECIFIED",n.MODE_DYNAMIC="MODE_DYNAMIC"})(Br||(Br={}));var Vr;(function(n){n.API_SPEC_UNSPECIFIED="API_SPEC_UNSPECIFIED",n.SIMPLE_SEARCH="SIMPLE_SEARCH",n.ELASTIC_SEARCH="ELASTIC_SEARCH"})(Vr||(Vr={}));var Or;(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"})(Or||(Or={}));var qr;(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"})(qr||(qr={}));var Hr;(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"})(Hr||(Hr={}));var zr;(function(n){n.THINKING_LEVEL_UNSPECIFIED="THINKING_LEVEL_UNSPECIFIED",n.LOW="LOW",n.HIGH="HIGH"})(zr||(zr={}));var Kr;(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"})(Kr||(Kr={}));var Wr;(function(n){n.HARM_BLOCK_METHOD_UNSPECIFIED="HARM_BLOCK_METHOD_UNSPECIFIED",n.SEVERITY="SEVERITY",n.PROBABILITY="PROBABILITY"})(Wr||(Wr={}));var Jr;(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"})(Jr||(Jr={}));var Yr;(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"})(Yr||(Yr={}));var Xr;(function(n){n.HARM_PROBABILITY_UNSPECIFIED="HARM_PROBABILITY_UNSPECIFIED",n.NEGLIGIBLE="NEGLIGIBLE",n.LOW="LOW",n.MEDIUM="MEDIUM",n.HIGH="HIGH"})(Xr||(Xr={}));var Qr;(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"})(Qr||(Qr={}));var Zr;(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"})(Zr||(Zr={}));var jr;(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"})(jr||(jr={}));var ea;(function(n){n.TRAFFIC_TYPE_UNSPECIFIED="TRAFFIC_TYPE_UNSPECIFIED",n.ON_DEMAND="ON_DEMAND",n.PROVISIONED_THROUGHPUT="PROVISIONED_THROUGHPUT"})(ea||(ea={}));var Dn;(function(n){n.MODALITY_UNSPECIFIED="MODALITY_UNSPECIFIED",n.TEXT="TEXT",n.IMAGE="IMAGE",n.AUDIO="AUDIO"})(Dn||(Dn={}));var ta;(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"})(ta||(ta={}));var na;(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"})(na||(na={}));var ia;(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"})(ia||(ia={}));var co;(function(n){n.JOB_STATE_UNSPECIFIED="JOB_STATE_UNSPECIFIED",n.JOB_STATE_QUEUED="JOB_STATE_QUEUED",n.JOB_STATE_PENDING="JOB_STATE_PENDING",n.JOB_STATE_RUNNING="JOB_STATE_RUNNING",n.JOB_STATE_SUCCEEDED="JOB_STATE_SUCCEEDED",n.JOB_STATE_FAILED="JOB_STATE_FAILED",n.JOB_STATE_CANCELLING="JOB_STATE_CANCELLING",n.JOB_STATE_CANCELLED="JOB_STATE_CANCELLED",n.JOB_STATE_PAUSED="JOB_STATE_PAUSED",n.JOB_STATE_EXPIRED="JOB_STATE_EXPIRED",n.JOB_STATE_UPDATING="JOB_STATE_UPDATING",n.JOB_STATE_PARTIALLY_SUCCEEDED="JOB_STATE_PARTIALLY_SUCCEEDED"})(co||(co={}));var oa;(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"})(oa||(oa={}));var sa;(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"})(sa||(sa={}));var ra;(function(n){n.FEATURE_SELECTION_PREFERENCE_UNSPECIFIED="FEATURE_SELECTION_PREFERENCE_UNSPECIFIED",n.PRIORITIZE_QUALITY="PRIORITIZE_QUALITY",n.BALANCED="BALANCED",n.PRIORITIZE_COST="PRIORITIZE_COST"})(ra||(ra={}));var aa;(function(n){n.UNSPECIFIED="UNSPECIFIED",n.BLOCKING="BLOCKING",n.NON_BLOCKING="NON_BLOCKING"})(aa||(aa={}));var la;(function(n){n.MODE_UNSPECIFIED="MODE_UNSPECIFIED",n.MODE_DYNAMIC="MODE_DYNAMIC"})(la||(la={}));var ca;(function(n){n.ENVIRONMENT_UNSPECIFIED="ENVIRONMENT_UNSPECIFIED",n.ENVIRONMENT_BROWSER="ENVIRONMENT_BROWSER"})(ca||(ca={}));var Mn;(function(n){n.MODE_UNSPECIFIED="MODE_UNSPECIFIED",n.AUTO="AUTO",n.ANY="ANY",n.NONE="NONE",n.VALIDATED="VALIDATED"})(Mn||(Mn={}));var da;(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"})(da||(da={}));var ua;(function(n){n.DONT_ALLOW="DONT_ALLOW",n.ALLOW_ADULT="ALLOW_ADULT",n.ALLOW_ALL="ALLOW_ALL"})(ua||(ua={}));var fa;(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"})(fa||(fa={}));var pa;(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"})(pa||(pa={}));var ha;(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"})(ha||(ha={}));var ma;(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"})(ma||(ma={}));var ga;(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"})(ga||(ga={}));var ba;(function(n){n.FOREGROUND="FOREGROUND",n.BACKGROUND="BACKGROUND",n.PROMPT="PROMPT",n.SEMANTIC="SEMANTIC",n.INTERACTIVE="INTERACTIVE"})(ba||(ba={}));var ya;(function(n){n.ASSET="ASSET",n.STYLE="STYLE"})(ya||(ya={}));var Ea;(function(n){n.INSERT="INSERT",n.REMOVE="REMOVE",n.REMOVE_STATIC="REMOVE_STATIC",n.OUTPAINT="OUTPAINT"})(Ea||(Ea={}));var wa;(function(n){n.OPTIMIZED="OPTIMIZED",n.LOSSLESS="LOSSLESS"})(wa||(wa={}));var va;(function(n){n.SUPERVISED_FINE_TUNING="SUPERVISED_FINE_TUNING",n.PREFERENCE_TUNING="PREFERENCE_TUNING"})(va||(va={}));var Ia;(function(n){n.STATE_UNSPECIFIED="STATE_UNSPECIFIED",n.STATE_PENDING="STATE_PENDING",n.STATE_ACTIVE="STATE_ACTIVE",n.STATE_FAILED="STATE_FAILED"})(Ia||(Ia={}));var Ca;(function(n){n.STATE_UNSPECIFIED="STATE_UNSPECIFIED",n.PROCESSING="PROCESSING",n.ACTIVE="ACTIVE",n.FAILED="FAILED"})(Ca||(Ca={}));var Ta;(function(n){n.SOURCE_UNSPECIFIED="SOURCE_UNSPECIFIED",n.UPLOADED="UPLOADED",n.GENERATED="GENERATED"})(Ta||(Ta={}));var Sa;(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"})(Sa||(Sa={}));var _a;(function(n){n.MODALITY_UNSPECIFIED="MODALITY_UNSPECIFIED",n.TEXT="TEXT",n.IMAGE="IMAGE",n.VIDEO="VIDEO",n.AUDIO="AUDIO",n.DOCUMENT="DOCUMENT"})(_a||(_a={}));var Aa;(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"})(Aa||(Aa={}));var xa;(function(n){n.START_SENSITIVITY_UNSPECIFIED="START_SENSITIVITY_UNSPECIFIED",n.START_SENSITIVITY_HIGH="START_SENSITIVITY_HIGH",n.START_SENSITIVITY_LOW="START_SENSITIVITY_LOW"})(xa||(xa={}));var Pa;(function(n){n.END_SENSITIVITY_UNSPECIFIED="END_SENSITIVITY_UNSPECIFIED",n.END_SENSITIVITY_HIGH="END_SENSITIVITY_HIGH",n.END_SENSITIVITY_LOW="END_SENSITIVITY_LOW"})(Pa||(Pa={}));var Na;(function(n){n.ACTIVITY_HANDLING_UNSPECIFIED="ACTIVITY_HANDLING_UNSPECIFIED",n.START_OF_ACTIVITY_INTERRUPTS="START_OF_ACTIVITY_INTERRUPTS",n.NO_INTERRUPTION="NO_INTERRUPTION"})(Na||(Na={}));var Ga;(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"})(Ga||(Ga={}));var $a;(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"})($a||($a={}));var ka;(function(n){n.MUSIC_GENERATION_MODE_UNSPECIFIED="MUSIC_GENERATION_MODE_UNSPECIFIED",n.QUALITY="QUALITY",n.DIVERSITY="DIVERSITY",n.VOCALIZATION="VOCALIZATION"})(ka||(ka={}));var xt;(function(n){n.PLAYBACK_CONTROL_UNSPECIFIED="PLAYBACK_CONTROL_UNSPECIFIED",n.PLAY="PLAY",n.PAUSE="PAUSE",n.STOP="STOP",n.RESET_CONTEXT="RESET_CONTEXT"})(xt||(xt={}));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 ft=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}},Ln=class{static{p(this,"EmbedContentResponse")}},Un=class{static{p(this,"GenerateImagesResponse")}},uo=class{static{p(this,"EditImageResponse")}},fo=class{static{p(this,"UpscaleImageResponse")}},po=class{static{p(this,"RecontextImageResponse")}},ho=class{static{p(this,"SegmentImageResponse")}},Fn=class{static{p(this,"ListModelsResponse")}},Bn=class{static{p(this,"DeleteModelResponse")}},Vn=class{static{p(this,"CountTokensResponse")}},mo=class{static{p(this,"ComputeTokensResponse")}};var On=class n{static{p(this,"GenerateVideosOperation")}_fromAPIResponse({apiResponse:e,_isVertexAI:t}){let i=new n,o,s=e;return t?o=Wc(s):o=Kc(s),Object.assign(i,o),i}},qn=class{static{p(this,"ListTuningJobsResponse")}},Hn=class{static{p(this,"CancelTuningJobResponse")}},zn=class{static{p(this,"DeleteCachedContentResponse")}},Kn=class{static{p(this,"ListCachedContentsResponse")}},go=class{static{p(this,"ListDocumentsResponse")}},bo=class{static{p(this,"ListFileSearchStoresResponse")}},yo=class{static{p(this,"UploadToFileSearchStoreResumableResponse")}};var Eo=class n{static{p(this,"ImportFileOperation")}_fromAPIResponse({apiResponse:e,_isVertexAI:t}){let i=new n,s=ed(e);return Object.assign(i,s),i}},wo=class{static{p(this,"ListFilesResponse")}},vo=class{static{p(this,"CreateFileResponse")}},Io=class{static{p(this,"DeleteFileResponse")}};var Wn=class{static{p(this,"ListBatchJobsResponse")}};var Co=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 To=class{static{p(this,"LiveMusicServerMessage")}get audioChunk(){if(this.serverContent&&this.serverContent.audioChunks&&this.serverContent.audioChunks.length>0)return this.serverContent.audioChunks[0]}};var So=class n{static{p(this,"UploadToFileSearchStoreOperation")}_fromAPIResponse({apiResponse:e,_isVertexAI:t}){let i=new n,s=sl(e);return Object.assign(i,s),i}};function O(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(O,"tModel");function rl(n,e){let t=O(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(rl,"tCachesModel");function al(n){return Array.isArray(n)?n.map(e=>Jn(e)):[Jn(n)]}p(al,"tBlobs");function Jn(n){if(typeof n=="object"&&n!==null)return n;throw new Error(`Could not parse input as Blob. Unsupported blob type: ${typeof n}`)}p(Jn,"tBlob");function ll(n){let e=Jn(n);if(e.mimeType&&e.mimeType.startsWith("image/"))return e;throw new Error(`Unsupported mime type: ${e.mimeType}`)}p(ll,"tImageBlob");function cl(n){let e=Jn(n);if(e.mimeType&&e.mimeType.startsWith("audio/"))return e;throw new Error(`Unsupported mime type: ${e.mimeType}`)}p(cl,"tAudioBlob");function Ra(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(Ra,"tPart");function dl(n){if(n==null||Array.isArray(n)&&n.length===0)throw new Error("PartListUnion is required");return Array.isArray(n)?n.map(e=>Ra(e)):[Ra(n)]}p(dl,"tParts");function _o(n){return n!=null&&typeof n=="object"&&"parts"in n&&Array.isArray(n.parts)}p(_o,"_isContent");function Da(n){return n!=null&&typeof n=="object"&&"functionCall"in n}p(Da,"_isFunctionCallPart");function Ma(n){return n!=null&&typeof n=="object"&&"functionResponse"in n}p(Ma,"_isFunctionResponsePart");function pe(n){if(n==null)throw new Error("ContentUnion is required");return _o(n)?n:{role:"user",parts:dl(n)}}p(pe,"tContent");function ls(n,e){if(!e)return[];if(n.isVertexAI()&&Array.isArray(e))return e.flatMap(t=>{let i=pe(t);return i.parts&&i.parts.length>0&&i.parts[0].text!==void 0?[i.parts[0].text]:[]});if(n.isVertexAI()){let t=pe(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=>pe(t)):[pe(e)]}p(ls,"tContentsForEmbed");function _e(n){if(n==null||Array.isArray(n)&&n.length===0)throw new Error("contents are required");if(!Array.isArray(n)){if(Da(n)||Ma(n))throw new Error("To specify functionCall or functionResponse parts, please wrap them in a Content object, specifying the role for them");return[pe(n)]}let e=[],t=[],i=_o(n[0]);for(let o of n){let s=_o(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(Da(o)||Ma(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:dl(t)}),e}p(_e,"tContents");function sd(n,e){n.includes("null")&&(e.nullable=!0);let t=n.filter(i=>i!=="null");if(t.length===1)e.type=Object.values(We).includes(t[0].toUpperCase())?t[0].toUpperCase():We.TYPE_UNSPECIFIED;else{e.anyOf=[];for(let i of t)e.anyOf.push({type:Object.values(We).includes(i.toUpperCase())?i.toUpperCase():We.TYPE_UNSPECIFIED})}}p(sd,"flattenTypeArrayToAnyOf");function Pt(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&&sd(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(We).includes(c.toUpperCase())?c.toUpperCase():We.TYPE_UNSPECIFIED}else if(t.includes(a))e[a]=Pt(c);else if(i.includes(a)){let d=[];for(let u of c){if(u.type=="null"){e.nullable=!0;continue}d.push(Pt(u))}e[a]=d}else if(o.includes(a)){let d={};for(let[u,f]of Object.entries(c))d[u]=Pt(f);e[a]=d}else{if(a==="additionalProperties")continue;e[a]=c}return e}p(Pt,"processJsonSchema");function cs(n){return Pt(n)}p(cs,"tSchema");function ds(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(ds,"tSpeechConfig");function us(n){if("multiSpeakerVoiceConfig"in n)throw new Error("multiSpeakerVoiceConfig is not supported in the live API.");return n}p(us,"tLiveSpeechConfig");function kt(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=Pt(e.parameters)),e.response&&(Object.keys(e.response).includes("$schema")?e.responseJsonSchema||(e.responseJsonSchema=e.response,delete e.response):e.response=Pt(e.response));return n}p(kt,"tTool");function Rt(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(Rt,"tTools");function rd(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(rd,"resourceName");function He(n,e){if(typeof e!="string")throw new Error("name must be a string");return rd(n,e,"cachedContents")}p(He,"tCachedContentName");function ul(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(ul,"tTuningJobStatus");function Je(n){return as(n)}p(Je,"tBytes");function ad(n){return n!=null&&typeof n=="object"&&"name"in n}p(ad,"_isFile");function ld(n){return n!=null&&typeof n=="object"&&"video"in n}p(ld,"isGeneratedVideo");function cd(n){return n!=null&&typeof n=="object"&&"uri"in n}p(cd,"isVideo");function fl(n){var e;let t;if(ad(n)&&(t=n.name),!(cd(n)&&(t=n.uri,t===void 0))&&!(ld(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(fl,"tFileName");function pl(n,e){let t;return n.isVertexAI()?t=e?"publishers/google/models":"models":t=e?"models":"tunedModels",t}p(pl,"tModelsUrl");function hl(n){for(let e of["models","tunedModels","publisherModels"])if(dd(n,e))return n[e];return[]}p(hl,"tExtractModels");function dd(n,e){return n!==null&&typeof n=="object"&&e in n}p(dd,"hasField");function ud(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(ud,"mcpToGeminiTool");function fd(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=ud(o,e);a.functionDeclarations&&t.push(...a.functionDeclarations)}return{functionDeclarations:t}}p(fd,"mcpToolsToGeminiTool");function ml(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(ml,"tBatchJobSource");function pd(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(pd,"tBatchJobDestination");function gl(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(gl,"tRecvBatchJobDestination");function Dt(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(Dt,"tBatchJobName");function bl(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(bl,"tJobState");function hd(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=>Jd(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(hd,"batchJobDestinationFromMldev");function md(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(md,"batchJobDestinationFromVertex");function gd(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(gd,"batchJobDestinationToVertex");function kn(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"],bl(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"],hd(gl(u))),e}p(kn,"batchJobFromMldev");function Ao(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"],bl(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"],bd(h));let m=r(n,["outputConfig"]);m!=null&&l(e,["dest"],md(gl(m)));let g=r(n,["completionStats"]);return g!=null&&l(e,["completionStats"],g),e}p(Ao,"batchJobFromVertex");function bd(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(bd,"batchJobSourceFromVertex");function yd(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=>Wd(n,a))),l(t,["requests","requests"],s)}return t}p(yd,"batchJobSourceToMldev");function Ed(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(Ed,"batchJobSourceToVertex");function wd(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(wd,"blobToMldev$4");function vd(n,e){let t={},i=r(e,["name"]);return i!=null&&l(t,["_url","name"],Dt(n,i)),t}p(vd,"cancelBatchJobParametersToMldev");function Id(n,e){let t={},i=r(e,["name"]);return i!=null&&l(t,["_url","name"],Dt(n,i)),t}p(Id,"cancelBatchJobParametersToVertex");function Cd(n){let e={},t=r(n,["content"]);t!=null&&l(e,["content"],t);let i=r(n,["citationMetadata"]);i!=null&&l(e,["citationMetadata"],Td(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(Cd,"candidateFromMldev$1");function Td(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(Td,"citationMetadataFromMldev$1");function yl(n){let e={},t=r(n,["parts"]);if(t!=null){let o=t;Array.isArray(o)&&(o=o.map(s=>tu(s))),l(e,["parts"],o)}let i=r(n,["role"]);return i!=null&&l(e,["role"],i),e}p(yl,"contentToMldev$4");function Sd(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(Sd,"createBatchJobConfigToMldev");function _d(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"],gd(pd(o))),t}p(_d,"createBatchJobConfigToVertex");function La(n,e){let t={},i=r(e,["model"]);i!=null&&l(t,["_url","model"],O(n,i));let o=r(e,["src"]);o!=null&&l(t,["batch","inputConfig"],yd(n,ml(n,o)));let s=r(e,["config"]);return s!=null&&Sd(s,t),t}p(La,"createBatchJobParametersToMldev");function Ad(n,e){let t={},i=r(e,["model"]);i!=null&&l(t,["model"],O(n,i));let o=r(e,["src"]);o!=null&&l(t,["inputConfig"],Ed(ml(n,o)));let s=r(e,["config"]);return s!=null&&_d(s,t),t}p(Ad,"createBatchJobParametersToVertex");function xd(n,e){let t={},i=r(n,["displayName"]);return e!==void 0&&i!=null&&l(e,["batch","displayName"],i),t}p(xd,"createEmbeddingsBatchJobConfigToMldev");function Pd(n,e){let t={},i=r(e,["model"]);i!=null&&l(t,["_url","model"],O(n,i));let o=r(e,["src"]);o!=null&&l(t,["batch","inputConfig"],Md(n,o));let s=r(e,["config"]);return s!=null&&xd(s,t),t}p(Pd,"createEmbeddingsBatchJobParametersToMldev");function Nd(n,e){let t={},i=r(e,["name"]);return i!=null&&l(t,["_url","name"],Dt(n,i)),t}p(Nd,"deleteBatchJobParametersToMldev");function Gd(n,e){let t={},i=r(e,["name"]);return i!=null&&l(t,["_url","name"],Dt(n,i)),t}p(Gd,"deleteBatchJobParametersToVertex");function $d(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($d,"deleteResourceJobFromMldev");function kd(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(kd,"deleteResourceJobFromVertex");function Rd(n,e){let t={},i=r(e,["contents"]);if(i!=null){let s=ls(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"],Dd(o,t)),Hc(t,{"requests[].*":"requests[].request.*"})),t}p(Rd,"embedContentBatchToMldev");function Dd(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(Dd,"embedContentConfigToMldev$1");function Md(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"],Rd(n,o)),t}p(Md,"embeddingsBatchJobSourceToMldev");function Ld(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(Ld,"fileDataToMldev$4");function Ud(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(Ud,"functionCallToMldev$4");function Fd(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(Fd,"functionCallingConfigToMldev$2");function Bd(n,e,t){let i={},o=r(e,["systemInstruction"]);t!==void 0&&o!=null&&l(t,["systemInstruction"],yl(pe(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 y=r(e,["seed"]);y!=null&&l(i,["seed"],y);let w=r(e,["responseMimeType"]);w!=null&&l(i,["responseMimeType"],w);let v=r(e,["responseSchema"]);v!=null&&l(i,["responseSchema"],cs(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 C=r(e,["safetySettings"]);if(t!==void 0&&C!=null){let U=C;Array.isArray(U)&&(U=U.map(oe=>nu(oe))),l(t,["safetySettings"],U)}let T=r(e,["tools"]);if(t!==void 0&&T!=null){let U=Rt(T);Array.isArray(U)&&(U=U.map(oe=>ou(kt(oe)))),l(t,["tools"],U)}let x=r(e,["toolConfig"]);if(t!==void 0&&x!=null&&l(t,["toolConfig"],iu(x)),r(e,["labels"])!==void 0)throw new Error("labels parameter is not supported in Gemini API.");let N=r(e,["cachedContent"]);t!==void 0&&N!=null&&l(t,["cachedContent"],He(n,N));let S=r(e,["responseModalities"]);S!=null&&l(i,["responseModalities"],S);let G=r(e,["mediaResolution"]);G!=null&&l(i,["mediaResolution"],G);let P=r(e,["speechConfig"]);if(P!=null&&l(i,["speechConfig"],ds(P)),r(e,["audioTimestamp"])!==void 0)throw new Error("audioTimestamp parameter is not supported in Gemini API.");let $=r(e,["thinkingConfig"]);$!=null&&l(i,["thinkingConfig"],$);let F=r(e,["imageConfig"]);F!=null&&l(i,["imageConfig"],Kd(F));let X=r(e,["enableEnhancedCivicAnswers"]);return X!=null&&l(i,["enableEnhancedCivicAnswers"],X),i}p(Bd,"generateContentConfigToMldev$1");function Vd(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=>Cd(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(Vd,"generateContentResponseFromMldev$1");function Od(n,e){let t={},i=r(e,["name"]);return i!=null&&l(t,["_url","name"],Dt(n,i)),t}p(Od,"getBatchJobParametersToMldev");function qd(n,e){let t={},i=r(e,["name"]);return i!=null&&l(t,["_url","name"],Dt(n,i)),t}p(qd,"getBatchJobParametersToVertex");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$4");function zd(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(zd,"googleSearchToMldev$4");function Kd(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(Kd,"imageConfigToMldev$1");function Wd(n,e){let t={},i=r(e,["model"]);i!=null&&l(t,["request","model"],O(n,i));let o=r(e,["contents"]);if(o!=null){let c=_e(o);Array.isArray(c)&&(c=c.map(d=>yl(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"],Bd(n,a,r(t,["request"],{}))),t}p(Wd,"inlinedRequestToMldev");function Jd(n){let e={},t=r(n,["response"]);t!=null&&l(e,["response"],Vd(t));let i=r(n,["error"]);return i!=null&&l(e,["error"],i),e}p(Jd,"inlinedResponseFromMldev");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"]);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(Yd,"listBatchJobsConfigToMldev");function Xd(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(Xd,"listBatchJobsConfigToVertex");function Qd(n){let e={},t=r(n,["config"]);return t!=null&&Yd(t,e),e}p(Qd,"listBatchJobsParametersToMldev");function Zd(n){let e={},t=r(n,["config"]);return t!=null&&Xd(t,e),e}p(Zd,"listBatchJobsParametersToVertex");function jd(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=>kn(a))),l(e,["batchJobs"],s)}return e}p(jd,"listBatchJobsResponseFromMldev");function eu(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=>Ao(a))),l(e,["batchJobs"],s)}return e}p(eu,"listBatchJobsResponseFromVertex");function tu(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"],Ld(s));let a=r(n,["functionCall"]);a!=null&&l(e,["functionCall"],Ud(a));let c=r(n,["functionResponse"]);c!=null&&l(e,["functionResponse"],c);let d=r(n,["inlineData"]);d!=null&&l(e,["inlineData"],wd(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(tu,"partToMldev$4");function nu(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(nu,"safetySettingToMldev$1");function iu(n){let e={},t=r(n,["functionCallingConfig"]);t!=null&&l(e,["functionCallingConfig"],Fd(t));let i=r(n,["retrievalConfig"]);return i!=null&&l(e,["retrievalConfig"],i),e}p(iu,"toolConfigToMldev$2");function ou(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"],zd(d));let u=r(n,["urlContext"]);return u!=null&&l(e,["urlContext"],u),e}p(ou,"toolToMldev$4");var Oe;(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"})(Oe||(Oe={}));var qe=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 xo=class extends Re{static{p(this,"Batches")}constructor(e){super(),this.apiClient=e,this.list=async(t={})=>new qe(Oe.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=La(this.apiClient,e),i=t._url,o=A("{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=Ad(this.apiClient,e);return c=A("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=>Ao(f))}else{let u=La(this.apiClient,e);return c=A("{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=>kn(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=Pd(this.apiClient,e);return s=A("{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=>kn(d))}}async get(e){var t,i,o,s;let a,c="",d={};if(this.apiClient.isVertexAI()){let u=qd(this.apiClient,e);return c=A("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=>Ao(f))}else{let u=Od(this.apiClient,e);return c=A("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=>kn(f))}}async cancel(e){var t,i,o,s;let a="",c={};if(this.apiClient.isVertexAI()){let d=Id(this.apiClient,e);a=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=vd(this.apiClient,e);a=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=Zd(e);return c=A("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=eu(f),m=new Wn;return Object.assign(m,h),m})}else{let u=Qd(e);return c=A("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=jd(f),m=new Wn;return Object.assign(m,h),m})}}async delete(e){var t,i,o,s;let a,c="",d={};if(this.apiClient.isVertexAI()){let u=Gd(this.apiClient,e);return c=A("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=>kd(f))}else{let u=Nd(this.apiClient,e);return c=A("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=>$d(f))}}};function su(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(su,"blobToMldev$3");function Ua(n){let e={},t=r(n,["parts"]);if(t!=null){let o=t;Array.isArray(o)&&(o=o.map(s=>xu(s))),l(e,["parts"],o)}let i=r(n,["role"]);return i!=null&&l(e,["role"],i),e}p(Ua,"contentToMldev$3");function ru(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=_e(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(pe(c)));let d=r(n,["tools"]);if(e!==void 0&&d!=null){let f=d;Array.isArray(f)&&(f=f.map(h=>Nu(h))),l(e,["tools"],f)}let u=r(n,["toolConfig"]);if(e!==void 0&&u!=null&&l(e,["toolConfig"],Pu(u)),r(n,["kmsKeyName"])!==void 0)throw new Error("kmsKeyName parameter is not supported in Gemini API.");return t}p(ru,"createCachedContentConfigToMldev");function au(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=_e(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"],pe(c));let d=r(n,["tools"]);if(e!==void 0&&d!=null){let h=d;Array.isArray(h)&&(h=h.map(m=>Gu(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(au,"createCachedContentConfigToVertex");function lu(n,e){let t={},i=r(e,["model"]);i!=null&&l(t,["model"],rl(n,i));let o=r(e,["config"]);return o!=null&&ru(o,t),t}p(lu,"createCachedContentParametersToMldev");function cu(n,e){let t={},i=r(e,["model"]);i!=null&&l(t,["model"],rl(n,i));let o=r(e,["config"]);return o!=null&&au(o,t),t}p(cu,"createCachedContentParametersToVertex");function du(n,e){let t={},i=r(e,["name"]);return i!=null&&l(t,["_url","name"],He(n,i)),t}p(du,"deleteCachedContentParametersToMldev");function uu(n,e){let t={},i=r(e,["name"]);return i!=null&&l(t,["_url","name"],He(n,i)),t}p(uu,"deleteCachedContentParametersToVertex");function fu(n){let e={},t=r(n,["sdkHttpResponse"]);return t!=null&&l(e,["sdkHttpResponse"],t),e}p(fu,"deleteCachedContentResponseFromMldev");function pu(n){let e={},t=r(n,["sdkHttpResponse"]);return t!=null&&l(e,["sdkHttpResponse"],t),e}p(pu,"deleteCachedContentResponseFromVertex");function hu(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(hu,"fileDataToMldev$3");function mu(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(mu,"functionCallToMldev$3");function gu(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(gu,"functionCallingConfigToMldev$1");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$2");function yu(n,e){let t={},i=r(e,["name"]);return i!=null&&l(t,["_url","name"],He(n,i)),t}p(yu,"getCachedContentParametersToMldev");function Eu(n,e){let t={},i=r(e,["name"]);return i!=null&&l(t,["_url","name"],He(n,i)),t}p(Eu,"getCachedContentParametersToVertex");function wu(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(wu,"googleMapsToMldev$3");function vu(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(vu,"googleSearchToMldev$3");function Iu(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(Iu,"listCachedContentsConfigToMldev");function Cu(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(Cu,"listCachedContentsConfigToVertex");function Tu(n){let e={},t=r(n,["config"]);return t!=null&&Iu(t,e),e}p(Tu,"listCachedContentsParametersToMldev");function Su(n){let e={},t=r(n,["config"]);return t!=null&&Cu(t,e),e}p(Su,"listCachedContentsParametersToVertex");function _u(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(_u,"listCachedContentsResponseFromMldev");function Au(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(Au,"listCachedContentsResponseFromVertex");function xu(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"],hu(s));let a=r(n,["functionCall"]);a!=null&&l(e,["functionCall"],mu(a));let c=r(n,["functionResponse"]);c!=null&&l(e,["functionResponse"],c);let d=r(n,["inlineData"]);d!=null&&l(e,["inlineData"],su(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(xu,"partToMldev$3");function Pu(n){let e={},t=r(n,["functionCallingConfig"]);t!=null&&l(e,["functionCallingConfig"],gu(t));let i=r(n,["retrievalConfig"]);return i!=null&&l(e,["retrievalConfig"],i),e}p(Pu,"toolConfigToMldev$1");function Nu(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"],wu(c));let d=r(n,["googleSearch"]);d!=null&&l(e,["googleSearch"],vu(d));let u=r(n,["urlContext"]);return u!=null&&l(e,["urlContext"],u),e}p(Nu,"toolToMldev$3");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$2");function $u(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($u,"updateCachedContentConfigToMldev");function ku(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(ku,"updateCachedContentConfigToVertex");function Ru(n,e){let t={},i=r(e,["name"]);i!=null&&l(t,["_url","name"],He(n,i));let o=r(e,["config"]);return o!=null&&$u(o,t),t}p(Ru,"updateCachedContentParametersToMldev");function Du(n,e){let t={},i=r(e,["name"]);i!=null&&l(t,["_url","name"],He(n,i));let o=r(e,["config"]);return o!=null&&ku(o,t),t}p(Du,"updateCachedContentParametersToVertex");var Po=class extends Re{static{p(this,"Caches")}constructor(e){super(),this.apiClient=e,this.list=async(t={})=>new qe(Oe.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=cu(this.apiClient,e);return c=A("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=lu(this.apiClient,e);return c=A("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=Eu(this.apiClient,e);return c=A("{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=yu(this.apiClient,e);return c=A("{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=uu(this.apiClient,e);return c=A("{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=pu(f),m=new zn;return Object.assign(m,h),m})}else{let u=du(this.apiClient,e);return c=A("{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=fu(f),m=new zn;return Object.assign(m,h),m})}}async update(e){var t,i,o,s;let a,c="",d={};if(this.apiClient.isVertexAI()){let u=Du(this.apiClient,e);return c=A("{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=Ru(this.apiClient,e);return c=A("{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=Su(e);return c=A("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=Au(f),m=new Kn;return Object.assign(m,h),m})}else{let u=Tu(e);return c=A("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=_u(f),m=new Kn;return Object.assign(m,h),m})}}};function Yn(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(Yn,"__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 M(n){return this instanceof M?(this.v=n,this):new M(n)}p(M,"__await");function $e(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(y){return new Promise(function(w,v){s.push([g,y,w,v])>1||d(g,y)})},b&&(o[g]=b(o[g])))}function d(g,b){try{u(i[g](b))}catch(y){m(s[0][3],y)}}function u(g){g.value instanceof M?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($e,"__asyncGenerator");function ke(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(ke,"__asyncValues");function Mu(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:El(t)}p(Mu,"isValidResponse");function El(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(El,"isValidContent");function Lu(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(Lu,"validateHistory");function Ba(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&&!El(n[i])&&(s=!1),i++;s?e.push(...o):e.pop()}return e}p(Ba,"extractCuratedHistory");var No=class{static{p(this,"Chats")}constructor(e,t){this.modelsModule=e,this.apiClient=t}create(e){return new Go(this.apiClient,this.modelsModule,e.model,e.config,structuredClone(e.history))}},Go=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(),Lu(s)}async sendMessage(e){var t;await this.sendPromise;let i=pe(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=pe(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?Ba(this.history):this.history;return structuredClone(t)}processStreamResponse(e,t){return $e(this,arguments,p(function*(){var o,s,a,c,d,u;let f=[];try{for(var h=!0,m=ke(e),g;g=yield M(m.next()),o=g.done,!o;h=!0){c=g.value,h=!1;let b=c;if(Mu(b)){let y=(u=(d=b.candidates)===null||d===void 0?void 0:d[0])===null||u===void 0?void 0:u.content;y!==void 0&&f.push(y)}yield yield M(b)}}catch(b){s={error:b}}finally{try{!h&&!o&&(a=m.return)&&(yield M(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(...Ba(i)):this.history.push(e),this.history.push(...o)}};var Xn=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 Uu(n){let e={},t=r(n,["file"]);return t!=null&&l(e,["file"],t),e}p(Uu,"createFileParametersToMldev");function Fu(n){let e={},t=r(n,["sdkHttpResponse"]);return t!=null&&l(e,["sdkHttpResponse"],t),e}p(Fu,"createFileResponseFromMldev");function Bu(n){let e={},t=r(n,["name"]);return t!=null&&l(e,["_url","file"],fl(t)),e}p(Bu,"deleteFileParametersToMldev");function Vu(n){let e={},t=r(n,["sdkHttpResponse"]);return t!=null&&l(e,["sdkHttpResponse"],t),e}p(Vu,"deleteFileResponseFromMldev");function Ou(n){let e={},t=r(n,["name"]);return t!=null&&l(e,["_url","file"],fl(t)),e}p(Ou,"getFileParametersToMldev");function qu(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(qu,"listFilesConfigToMldev");function Hu(n){let e={},t=r(n,["config"]);return t!=null&&qu(t,e),e}p(Hu,"listFilesParametersToMldev");function zu(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(zu,"listFilesResponseFromMldev");var $o=class extends Re{static{p(this,"Files")}constructor(e){super(),this.apiClient=e,this.list=async(t={})=>new qe(Oe.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=Hu(e);return s=A("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=zu(d),f=new wo;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=Uu(e);return s=A("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=Fu(d),f=new vo;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=Ou(e);return s=A("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=Bu(e);return s=A("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=Vu(d),f=new Io;return Object.assign(f,u),f})}}};function Rn(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(Rn,"blobToMldev$2");function Ku(n){let e={},t=r(n,["parts"]);if(t!=null){let o=t;Array.isArray(o)&&(o=o.map(s=>cf(s))),l(e,["parts"],o)}let i=r(n,["role"]);return i!=null&&l(e,["role"],i),e}p(Ku,"contentToMldev$2");function Wu(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(Wu,"fileDataToMldev$2");function Ju(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(Ju,"functionCallToMldev$2");function Yu(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(Yu,"functionDeclarationToVertex$1");function Xu(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 y=r(n,["responseSchema"]);y!=null&&l(e,["responseSchema"],y);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"],wl(I));let C=r(n,["stopSequences"]);C!=null&&l(e,["stopSequences"],C);let T=r(n,["temperature"]);T!=null&&l(e,["temperature"],T);let x=r(n,["thinkingConfig"]);x!=null&&l(e,["thinkingConfig"],x);let N=r(n,["topK"]);N!=null&&l(e,["topK"],N);let S=r(n,["topP"]);if(S!=null&&l(e,["topP"],S),r(n,["enableEnhancedCivicAnswers"])!==void 0)throw new Error("enableEnhancedCivicAnswers parameter is not supported in Vertex AI.");return e}p(Xu,"generationConfigToVertex$1");function Qu(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(Qu,"googleMapsToMldev$2");function Zu(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(Zu,"googleSearchToMldev$2");function ju(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"],us(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"],Ku(pe(b)));let y=r(n,["tools"]);if(e!==void 0&&y!=null){let N=Rt(y);Array.isArray(N)&&(N=N.map(S=>uf(kt(S)))),l(e,["setup","tools"],N)}let w=r(n,["sessionResumption"]);e!==void 0&&w!=null&&l(e,["setup","sessionResumption"],df(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 C=r(n,["realtimeInputConfig"]);e!==void 0&&C!=null&&l(e,["setup","realtimeInputConfig"],C);let T=r(n,["contextWindowCompression"]);e!==void 0&&T!=null&&l(e,["setup","contextWindowCompression"],T);let x=r(n,["proactivity"]);if(e!==void 0&&x!=null&&l(e,["setup","proactivity"],x),r(n,["explicitVadSignal"])!==void 0)throw new Error("explicitVadSignal parameter is not supported in Gemini API.");return t}p(ju,"liveConnectConfigToMldev$1");function ef(n,e){let t={},i=r(n,["generationConfig"]);e!==void 0&&i!=null&&l(e,["setup","generationConfig"],Xu(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"],wl(us(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"],pe(b));let y=r(n,["tools"]);if(e!==void 0&&y!=null){let S=Rt(y);Array.isArray(S)&&(S=S.map(G=>ff(kt(G)))),l(e,["setup","tools"],S)}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 C=r(n,["realtimeInputConfig"]);e!==void 0&&C!=null&&l(e,["setup","realtimeInputConfig"],C);let T=r(n,["contextWindowCompression"]);e!==void 0&&T!=null&&l(e,["setup","contextWindowCompression"],T);let x=r(n,["proactivity"]);e!==void 0&&x!=null&&l(e,["setup","proactivity"],x);let N=r(n,["explicitVadSignal"]);return e!==void 0&&N!=null&&l(e,["setup","explicitVadSignal"],N),t}p(ef,"liveConnectConfigToVertex");function tf(n,e){let t={},i=r(e,["model"]);i!=null&&l(t,["setup","model"],O(n,i));let o=r(e,["config"]);return o!=null&&l(t,["config"],ju(o,t)),t}p(tf,"liveConnectParametersToMldev");function nf(n,e){let t={},i=r(e,["model"]);i!=null&&l(t,["setup","model"],O(n,i));let o=r(e,["config"]);return o!=null&&l(t,["config"],ef(o,t)),t}p(nf,"liveConnectParametersToVertex");function of(n){let e={},t=r(n,["musicGenerationConfig"]);return t!=null&&l(e,["musicGenerationConfig"],t),e}p(of,"liveMusicSetConfigParametersToMldev");function sf(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(sf,"liveMusicSetWeightedPromptsParametersToMldev");function rf(n){let e={},t=r(n,["media"]);if(t!=null){let u=al(t);Array.isArray(u)&&(u=u.map(f=>Rn(f))),l(e,["mediaChunks"],u)}let i=r(n,["audio"]);i!=null&&l(e,["audio"],Rn(cl(i)));let o=r(n,["audioStreamEnd"]);o!=null&&l(e,["audioStreamEnd"],o);let s=r(n,["video"]);s!=null&&l(e,["video"],Rn(ll(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(rf,"liveSendRealtimeInputParametersToMldev");function af(n){let e={},t=r(n,["media"]);if(t!=null){let u=al(t);Array.isArray(u)&&(u=u.map(f=>f)),l(e,["mediaChunks"],u)}let i=r(n,["audio"]);i!=null&&l(e,["audio"],cl(i));let o=r(n,["audioStreamEnd"]);o!=null&&l(e,["audioStreamEnd"],o);let s=r(n,["video"]);s!=null&&l(e,["video"],ll(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(af,"liveSendRealtimeInputParametersToVertex");function lf(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"],pf(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(lf,"liveServerMessageFromVertex");function cf(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"],Wu(s));let a=r(n,["functionCall"]);a!=null&&l(e,["functionCall"],Ju(a));let c=r(n,["functionResponse"]);c!=null&&l(e,["functionResponse"],c);let d=r(n,["inlineData"]);d!=null&&l(e,["inlineData"],Rn(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(cf,"partToMldev$2");function df(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(df,"sessionResumptionConfigToMldev$1");function wl(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(wl,"speechConfigToVertex$1");function uf(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"],Qu(c));let d=r(n,["googleSearch"]);d!=null&&l(e,["googleSearch"],Zu(d));let u=r(n,["urlContext"]);return u!=null&&l(e,["urlContext"],u),e}p(uf,"toolToMldev$2");function ff(n){let e={},t=r(n,["functionDeclarations"]);if(t!=null){let h=t;Array.isArray(h)&&(h=h.map(m=>Yu(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(ff,"toolToVertex$1");function pf(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(pf,"usageMetadataFromVertex");function hf(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(hf,"blobToMldev$1");function mf(n){let e={},t=r(n,["content"]);t!=null&&l(e,["content"],t);let i=r(n,["citationMetadata"]);i!=null&&l(e,["citationMetadata"],gf(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(mf,"candidateFromMldev");function gf(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(gf,"citationMetadataFromMldev");function bf(n,e){let t={},i=r(e,["model"]);i!=null&&l(t,["_url","model"],O(n,i));let o=r(e,["contents"]);if(o!=null){let s=_e(o);Array.isArray(s)&&(s=s.map(a=>a)),l(t,["contents"],s)}return t}p(bf,"computeTokensParametersToVertex");function yf(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(yf,"computeTokensResponseFromVertex");function Ef(n){let e={},t=r(n,["values"]);t!=null&&l(e,["values"],t);let i=r(n,["statistics"]);return i!=null&&l(e,["statistics"],wf(i)),e}p(Ef,"contentEmbeddingFromVertex");function wf(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(wf,"contentEmbeddingStatisticsFromVertex");function fi(n){let e={},t=r(n,["parts"]);if(t!=null){let o=t;Array.isArray(o)&&(o=o.map(s=>Pp(s))),l(e,["parts"],o)}let i=r(n,["role"]);return i!=null&&l(e,["role"],i),e}p(fi,"contentToMldev$1");function vf(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(vf,"controlReferenceConfigToVertex");function If(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(If,"countTokensConfigToMldev");function Cf(n,e){let t={},i=r(n,["systemInstruction"]);e!==void 0&&i!=null&&l(e,["systemInstruction"],pe(i));let o=r(n,["tools"]);if(e!==void 0&&o!=null){let a=o;Array.isArray(a)&&(a=a.map(c=>Sl(c))),l(e,["tools"],a)}let s=r(n,["generationConfig"]);return e!==void 0&&s!=null&&l(e,["generationConfig"],hp(s)),t}p(Cf,"countTokensConfigToVertex");function Tf(n,e){let t={},i=r(e,["model"]);i!=null&&l(t,["_url","model"],O(n,i));let o=r(e,["contents"]);if(o!=null){let a=_e(o);Array.isArray(a)&&(a=a.map(c=>fi(c))),l(t,["contents"],a)}let s=r(e,["config"]);return s!=null&&If(s),t}p(Tf,"countTokensParametersToMldev");function Sf(n,e){let t={},i=r(e,["model"]);i!=null&&l(t,["_url","model"],O(n,i));let o=r(e,["contents"]);if(o!=null){let a=_e(o);Array.isArray(a)&&(a=a.map(c=>c)),l(t,["contents"],a)}let s=r(e,["config"]);return s!=null&&Cf(s,t),t}p(Sf,"countTokensParametersToVertex");function _f(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(_f,"countTokensResponseFromMldev");function Af(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(Af,"countTokensResponseFromVertex");function xf(n,e){let t={},i=r(e,["model"]);return i!=null&&l(t,["_url","name"],O(n,i)),t}p(xf,"deleteModelParametersToMldev");function Pf(n,e){let t={},i=r(e,["model"]);return i!=null&&l(t,["_url","name"],O(n,i)),t}p(Pf,"deleteModelParametersToVertex");function Nf(n){let e={},t=r(n,["sdkHttpResponse"]);return t!=null&&l(e,["sdkHttpResponse"],t),e}p(Nf,"deleteModelResponseFromMldev");function Gf(n){let e={},t=r(n,["sdkHttpResponse"]);return t!=null&&l(e,["sdkHttpResponse"],t),e}p(Gf,"deleteModelResponseFromVertex");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 y=r(n,["outputCompressionQuality"]);e!==void 0&&y!=null&&l(e,["parameters","outputOptions","compressionQuality"],y);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 C=r(n,["baseSteps"]);return e!==void 0&&C!=null&&l(e,["parameters","editConfig","baseSteps"],C),t}p($f,"editImageConfigToVertex");function kf(n,e){let t={},i=r(e,["model"]);i!=null&&l(t,["_url","model"],O(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=>Dp(d))),l(t,["instances[0]","referenceImages"],c)}let a=r(e,["config"]);return a!=null&&$f(a,t),t}p(kf,"editImageParametersInternalToVertex");function Rf(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=>pi(s))),l(e,["generatedImages"],o)}return e}p(Rf,"editImageResponseFromVertex");function Df(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(Df,"embedContentConfigToMldev");function Mf(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(Mf,"embedContentConfigToVertex");function Lf(n,e){let t={},i=r(e,["model"]);i!=null&&l(t,["_url","model"],O(n,i));let o=r(e,["contents"]);if(o!=null){let c=ls(n,o);Array.isArray(c)&&(c=c.map(d=>d)),l(t,["requests[]","content"],c)}let s=r(e,["config"]);s!=null&&Df(s,t);let a=r(e,["model"]);return a!==void 0&&l(t,["requests[]","model"],O(n,a)),t}p(Lf,"embedContentParametersToMldev");function Uf(n,e){let t={},i=r(e,["model"]);i!=null&&l(t,["_url","model"],O(n,i));let o=r(e,["contents"]);if(o!=null){let a=ls(n,o);Array.isArray(a)&&(a=a.map(c=>c)),l(t,["instances[]","content"],a)}let s=r(e,["config"]);return s!=null&&Mf(s,t),t}p(Uf,"embedContentParametersToVertex");function Ff(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(Ff,"embedContentResponseFromMldev");function Bf(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=>Ef(a))),l(e,["embeddings"],s)}let o=r(n,["metadata"]);return o!=null&&l(e,["metadata"],o),e}p(Bf,"embedContentResponseFromVertex");function Vf(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(Vf,"endpointFromVertex");function Of(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(Of,"fileDataToMldev$1");function qf(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(qf,"functionCallToMldev$1");function Hf(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(Hf,"functionCallingConfigToMldev");function zf(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(zf,"functionDeclarationToVertex");function Kf(n,e,t){let i={},o=r(e,["systemInstruction"]);t!==void 0&&o!=null&&l(t,["systemInstruction"],fi(pe(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 y=r(e,["seed"]);y!=null&&l(i,["seed"],y);let w=r(e,["responseMimeType"]);w!=null&&l(i,["responseMimeType"],w);let v=r(e,["responseSchema"]);v!=null&&l(i,["responseSchema"],cs(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 C=r(e,["safetySettings"]);if(t!==void 0&&C!=null){let U=C;Array.isArray(U)&&(U=U.map(oe=>Mp(oe))),l(t,["safetySettings"],U)}let T=r(e,["tools"]);if(t!==void 0&&T!=null){let U=Rt(T);Array.isArray(U)&&(U=U.map(oe=>qp(kt(oe)))),l(t,["tools"],U)}let x=r(e,["toolConfig"]);if(t!==void 0&&x!=null&&l(t,["toolConfig"],Op(x)),r(e,["labels"])!==void 0)throw new Error("labels parameter is not supported in Gemini API.");let N=r(e,["cachedContent"]);t!==void 0&&N!=null&&l(t,["cachedContent"],He(n,N));let S=r(e,["responseModalities"]);S!=null&&l(i,["responseModalities"],S);let G=r(e,["mediaResolution"]);G!=null&&l(i,["mediaResolution"],G);let P=r(e,["speechConfig"]);if(P!=null&&l(i,["speechConfig"],ds(P)),r(e,["audioTimestamp"])!==void 0)throw new Error("audioTimestamp parameter is not supported in Gemini API.");let $=r(e,["thinkingConfig"]);$!=null&&l(i,["thinkingConfig"],$);let F=r(e,["imageConfig"]);F!=null&&l(i,["imageConfig"],Ep(F));let X=r(e,["enableEnhancedCivicAnswers"]);return X!=null&&l(i,["enableEnhancedCivicAnswers"],X),i}p(Kf,"generateContentConfigToMldev");function Wf(n,e,t){let i={},o=r(e,["systemInstruction"]);t!==void 0&&o!=null&&l(t,["systemInstruction"],pe(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 y=r(e,["seed"]);y!=null&&l(i,["seed"],y);let w=r(e,["responseMimeType"]);w!=null&&l(i,["responseMimeType"],w);let v=r(e,["responseSchema"]);v!=null&&l(i,["responseSchema"],cs(v));let I=r(e,["responseJsonSchema"]);I!=null&&l(i,["responseJsonSchema"],I);let C=r(e,["routingConfig"]);C!=null&&l(i,["routingConfig"],C);let T=r(e,["modelSelectionConfig"]);T!=null&&l(i,["modelConfig"],T);let x=r(e,["safetySettings"]);if(t!==void 0&&x!=null){let j=x;Array.isArray(j)&&(j=j.map(ge=>ge)),l(t,["safetySettings"],j)}let N=r(e,["tools"]);if(t!==void 0&&N!=null){let j=Rt(N);Array.isArray(j)&&(j=j.map(ge=>Sl(kt(ge)))),l(t,["tools"],j)}let S=r(e,["toolConfig"]);t!==void 0&&S!=null&&l(t,["toolConfig"],S);let G=r(e,["labels"]);t!==void 0&&G!=null&&l(t,["labels"],G);let P=r(e,["cachedContent"]);t!==void 0&&P!=null&&l(t,["cachedContent"],He(n,P));let $=r(e,["responseModalities"]);$!=null&&l(i,["responseModalities"],$);let F=r(e,["mediaResolution"]);F!=null&&l(i,["mediaResolution"],F);let X=r(e,["speechConfig"]);X!=null&&l(i,["speechConfig"],Tl(ds(X)));let U=r(e,["audioTimestamp"]);U!=null&&l(i,["audioTimestamp"],U);let oe=r(e,["thinkingConfig"]);oe!=null&&l(i,["thinkingConfig"],oe);let ve=r(e,["imageConfig"]);if(ve!=null&&l(i,["imageConfig"],wp(ve)),r(e,["enableEnhancedCivicAnswers"])!==void 0)throw new Error("enableEnhancedCivicAnswers parameter is not supported in Vertex AI.");return i}p(Wf,"generateContentConfigToVertex");function Va(n,e){let t={},i=r(e,["model"]);i!=null&&l(t,["_url","model"],O(n,i));let o=r(e,["contents"]);if(o!=null){let a=_e(o);Array.isArray(a)&&(a=a.map(c=>fi(c))),l(t,["contents"],a)}let s=r(e,["config"]);return s!=null&&l(t,["generationConfig"],Kf(n,s,t)),t}p(Va,"generateContentParametersToMldev");function Oa(n,e){let t={},i=r(e,["model"]);i!=null&&l(t,["_url","model"],O(n,i));let o=r(e,["contents"]);if(o!=null){let a=_e(o);Array.isArray(a)&&(a=a.map(c=>c)),l(t,["contents"],a)}let s=r(e,["config"]);return s!=null&&l(t,["generationConfig"],Wf(n,s,t)),t}p(Oa,"generateContentParametersToVertex");function qa(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=>mf(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(qa,"generateContentResponseFromMldev");function Ha(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(Ha,"generateContentResponseFromVertex");function Jf(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(Jf,"generateImagesConfigToMldev");function Yf(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 y=r(n,["outputCompressionQuality"]);e!==void 0&&y!=null&&l(e,["parameters","outputOptions","compressionQuality"],y);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 C=r(n,["enhancePrompt"]);return e!==void 0&&C!=null&&l(e,["parameters","enhancePrompt"],C),t}p(Yf,"generateImagesConfigToVertex");function Xf(n,e){let t={},i=r(e,["model"]);i!=null&&l(t,["_url","model"],O(n,i));let o=r(e,["prompt"]);o!=null&&l(t,["instances[0]","prompt"],o);let s=r(e,["config"]);return s!=null&&Jf(s,t),t}p(Xf,"generateImagesParametersToMldev");function Qf(n,e){let t={},i=r(e,["model"]);i!=null&&l(t,["_url","model"],O(n,i));let o=r(e,["prompt"]);o!=null&&l(t,["instances[0]","prompt"],o);let s=r(e,["config"]);return s!=null&&Yf(s,t),t}p(Qf,"generateImagesParametersToVertex");function Zf(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=>dp(a))),l(e,["generatedImages"],s)}let o=r(n,["positivePromptSafetyAttributes"]);return o!=null&&l(e,["positivePromptSafetyAttributes"],Il(o)),e}p(Zf,"generateImagesResponseFromMldev");function jf(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=>pi(a))),l(e,["generatedImages"],s)}let o=r(n,["positivePromptSafetyAttributes"]);return o!=null&&l(e,["positivePromptSafetyAttributes"],Cl(o)),e}p(jf,"generateImagesResponseFromVertex");function ep(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"],hi(f));let h=r(n,["referenceImages"]);if(e!==void 0&&h!=null){let m=h;Array.isArray(m)&&(m=m.map(g=>nh(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(ep,"generateVideosConfigToMldev");function tp(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 y=r(n,["lastFrame"]);e!==void 0&&y!=null&&l(e,["instances[0]","lastFrame"],De(y));let w=r(n,["referenceImages"]);if(e!==void 0&&w!=null){let C=w;Array.isArray(C)&&(C=C.map(T=>ih(T))),l(e,["instances[0]","referenceImages"],C)}let v=r(n,["mask"]);e!==void 0&&v!=null&&l(e,["instances[0]","mask"],th(v));let I=r(n,["compressionQuality"]);return e!==void 0&&I!=null&&l(e,["parameters","compressionQuality"],I),t}p(tp,"generateVideosConfigToVertex");function np(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"],rp(a)),e}p(np,"generateVideosOperationFromMldev");function ip(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"],ap(a)),e}p(ip,"generateVideosOperationFromVertex");function op(n,e){let t={},i=r(e,["model"]);i!=null&&l(t,["_url","model"],O(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"],hi(s));let a=r(e,["video"]);a!=null&&l(t,["instances[0]","video"],_l(a));let c=r(e,["source"]);c!=null&&lp(c,t);let d=r(e,["config"]);return d!=null&&ep(d,t),t}p(op,"generateVideosParametersToMldev");function sp(n,e){let t={},i=r(e,["model"]);i!=null&&l(t,["_url","model"],O(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"],De(s));let a=r(e,["video"]);a!=null&&l(t,["instances[0]","video"],Al(a));let c=r(e,["source"]);c!=null&&cp(c,t);let d=r(e,["config"]);return d!=null&&tp(d,t),t}p(sp,"generateVideosParametersToVertex");function rp(n){let e={},t=r(n,["generatedSamples"]);if(t!=null){let s=t;Array.isArray(s)&&(s=s.map(a=>fp(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(rp,"generateVideosResponseFromMldev");function ap(n){let e={},t=r(n,["videos"]);if(t!=null){let s=t;Array.isArray(s)&&(s=s.map(a=>pp(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(ap,"generateVideosResponseFromVertex");function lp(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"],hi(o));let s=r(n,["video"]);return e!==void 0&&s!=null&&l(e,["instances[0]","video"],_l(s)),t}p(lp,"generateVideosSourceToMldev");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"],De(o));let s=r(n,["video"]);return e!==void 0&&s!=null&&l(e,["instances[0]","video"],Al(s)),t}p(cp,"generateVideosSourceToVertex");function dp(n){let e={},t=r(n,["_self"]);t!=null&&l(e,["image"],vp(t));let i=r(n,["raiFilteredReason"]);i!=null&&l(e,["raiFilteredReason"],i);let o=r(n,["_self"]);return o!=null&&l(e,["safetyAttributes"],Il(o)),e}p(dp,"generatedImageFromMldev");function pi(n){let e={},t=r(n,["_self"]);t!=null&&l(e,["image"],vl(t));let i=r(n,["raiFilteredReason"]);i!=null&&l(e,["raiFilteredReason"],i);let o=r(n,["_self"]);o!=null&&l(e,["safetyAttributes"],Cl(o));let s=r(n,["prompt"]);return s!=null&&l(e,["enhancedPrompt"],s),e}p(pi,"generatedImageFromVertex");function up(n){let e={},t=r(n,["_self"]);t!=null&&l(e,["mask"],vl(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(up,"generatedImageMaskFromVertex");function fp(n){let e={},t=r(n,["video"]);return t!=null&&l(e,["video"],jp(t)),e}p(fp,"generatedVideoFromMldev");function pp(n){let e={},t=r(n,["_self"]);return t!=null&&l(e,["video"],eh(t)),e}p(pp,"generatedVideoFromVertex");function hp(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 y=r(n,["responseSchema"]);y!=null&&l(e,["responseSchema"],y);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"],Tl(I));let C=r(n,["stopSequences"]);C!=null&&l(e,["stopSequences"],C);let T=r(n,["temperature"]);T!=null&&l(e,["temperature"],T);let x=r(n,["thinkingConfig"]);x!=null&&l(e,["thinkingConfig"],x);let N=r(n,["topK"]);N!=null&&l(e,["topK"],N);let S=r(n,["topP"]);if(S!=null&&l(e,["topP"],S),r(n,["enableEnhancedCivicAnswers"])!==void 0)throw new Error("enableEnhancedCivicAnswers parameter is not supported in Vertex AI.");return e}p(hp,"generationConfigToVertex");function mp(n,e){let t={},i=r(e,["model"]);return i!=null&&l(t,["_url","name"],O(n,i)),t}p(mp,"getModelParametersToMldev");function gp(n,e){let t={},i=r(e,["model"]);return i!=null&&l(t,["_url","name"],O(n,i)),t}p(gp,"getModelParametersToVertex");function bp(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(bp,"googleMapsToMldev$1");function yp(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(yp,"googleSearchToMldev$1");function Ep(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(Ep,"imageConfigToMldev");function wp(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(wp,"imageConfigToVertex");function vp(n){let e={},t=r(n,["bytesBase64Encoded"]);t!=null&&l(e,["imageBytes"],Je(t));let i=r(n,["mimeType"]);return i!=null&&l(e,["mimeType"],i),e}p(vp,"imageFromMldev");function vl(n){let e={},t=r(n,["gcsUri"]);t!=null&&l(e,["gcsUri"],t);let i=r(n,["bytesBase64Encoded"]);i!=null&&l(e,["imageBytes"],Je(i));let o=r(n,["mimeType"]);return o!=null&&l(e,["mimeType"],o),e}p(vl,"imageFromVertex");function hi(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"],Je(t));let i=r(n,["mimeType"]);return i!=null&&l(e,["mimeType"],i),e}p(hi,"imageToMldev");function De(n){let e={},t=r(n,["gcsUri"]);t!=null&&l(e,["gcsUri"],t);let i=r(n,["imageBytes"]);i!=null&&l(e,["bytesBase64Encoded"],Je(i));let o=r(n,["mimeType"]);return o!=null&&l(e,["mimeType"],o),e}p(De,"imageToVertex");function Ip(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"],pl(n,c)),i}p(Ip,"listModelsConfigToMldev");function Cp(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"],pl(n,c)),i}p(Cp,"listModelsConfigToVertex");function Tp(n,e){let t={},i=r(e,["config"]);return i!=null&&Ip(n,i,t),t}p(Tp,"listModelsParametersToMldev");function Sp(n,e){let t={},i=r(e,["config"]);return i!=null&&Cp(n,i,t),t}p(Sp,"listModelsParametersToVertex");function _p(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=hl(o);Array.isArray(s)&&(s=s.map(a=>ko(a))),l(e,["models"],s)}return e}p(_p,"listModelsResponseFromMldev");function Ap(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=hl(o);Array.isArray(s)&&(s=s.map(a=>Ro(a))),l(e,["models"],s)}return e}p(Ap,"listModelsResponseFromVertex");function xp(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(xp,"maskReferenceConfigToVertex");function ko(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"],Hp(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(ko,"modelFromMldev");function Ro(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=>Vf(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"],zp(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(Ro,"modelFromVertex");function Pp(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"],Of(s));let a=r(n,["functionCall"]);a!=null&&l(e,["functionCall"],qf(a));let c=r(n,["functionResponse"]);c!=null&&l(e,["functionResponse"],c);let d=r(n,["inlineData"]);d!=null&&l(e,["inlineData"],hf(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(Pp,"partToMldev$1");function Np(n){let e={},t=r(n,["productImage"]);return t!=null&&l(e,["image"],De(t)),e}p(Np,"productImageToVertex");function Gp(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(Gp,"recontextImageConfigToVertex");function $p(n,e){let t={},i=r(e,["model"]);i!=null&&l(t,["_url","model"],O(n,i));let o=r(e,["source"]);o!=null&&Rp(o,t);let s=r(e,["config"]);return s!=null&&Gp(s,t),t}p($p,"recontextImageParametersToVertex");function kp(n){let e={},t=r(n,["predictions"]);if(t!=null){let i=t;Array.isArray(i)&&(i=i.map(o=>pi(o))),l(e,["generatedImages"],i)}return e}p(kp,"recontextImageResponseFromVertex");function Rp(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"],De(o));let s=r(n,["productImages"]);if(e!==void 0&&s!=null){let a=s;Array.isArray(a)&&(a=a.map(c=>Np(c))),l(e,["instances[0]","productImages"],a)}return t}p(Rp,"recontextImageSourceToVertex");function Dp(n){let e={},t=r(n,["referenceImage"]);t!=null&&l(e,["referenceImage"],De(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"],xp(s));let a=r(n,["controlImageConfig"]);a!=null&&l(e,["controlImageConfig"],vf(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(Dp,"referenceImageAPIInternalToVertex");function Il(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(Il,"safetyAttributesFromMldev");function Cl(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(Cl,"safetyAttributesFromVertex");function Mp(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(Mp,"safetySettingToMldev");function Lp(n){let e={},t=r(n,["image"]);return t!=null&&l(e,["image"],De(t)),e}p(Lp,"scribbleImageToVertex");function Up(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(Up,"segmentImageConfigToVertex");function Fp(n,e){let t={},i=r(e,["model"]);i!=null&&l(t,["_url","model"],O(n,i));let o=r(e,["source"]);o!=null&&Vp(o,t);let s=r(e,["config"]);return s!=null&&Up(s,t),t}p(Fp,"segmentImageParametersToVertex");function Bp(n){let e={},t=r(n,["predictions"]);if(t!=null){let i=t;Array.isArray(i)&&(i=i.map(o=>up(o))),l(e,["generatedMasks"],i)}return e}p(Bp,"segmentImageResponseFromVertex");function Vp(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"],De(o));let s=r(n,["scribbleImage"]);return e!==void 0&&s!=null&&l(e,["instances[0]","scribble"],Lp(s)),t}p(Vp,"segmentImageSourceToVertex");function Tl(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(Tl,"speechConfigToVertex");function Op(n){let e={},t=r(n,["functionCallingConfig"]);t!=null&&l(e,["functionCallingConfig"],Hf(t));let i=r(n,["retrievalConfig"]);return i!=null&&l(e,["retrievalConfig"],i),e}p(Op,"toolConfigToMldev");function qp(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"],bp(c));let d=r(n,["googleSearch"]);d!=null&&l(e,["googleSearch"],yp(d));let u=r(n,["urlContext"]);return u!=null&&l(e,["urlContext"],u),e}p(qp,"toolToMldev$1");function Sl(n){let e={},t=r(n,["functionDeclarations"]);if(t!=null){let h=t;Array.isArray(h)&&(h=h.map(m=>zf(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(Sl,"toolToVertex");function Hp(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(Hp,"tunedModelInfoFromMldev");function zp(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(zp,"tunedModelInfoFromVertex");function Kp(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(Kp,"updateModelConfigToMldev");function Wp(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(Wp,"updateModelConfigToVertex");function Jp(n,e){let t={},i=r(e,["model"]);i!=null&&l(t,["_url","name"],O(n,i));let o=r(e,["config"]);return o!=null&&Kp(o,t),t}p(Jp,"updateModelParametersToMldev");function Yp(n,e){let t={},i=r(e,["model"]);i!=null&&l(t,["_url","model"],O(n,i));let o=r(e,["config"]);return o!=null&&Wp(o,t),t}p(Yp,"updateModelParametersToVertex");function Xp(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(Xp,"upscaleImageAPIConfigInternalToVertex");function Qp(n,e){let t={},i=r(e,["model"]);i!=null&&l(t,["_url","model"],O(n,i));let o=r(e,["image"]);o!=null&&l(t,["instances[0]","image"],De(o));let s=r(e,["upscaleFactor"]);s!=null&&l(t,["parameters","upscaleConfig","upscaleFactor"],s);let a=r(e,["config"]);return a!=null&&Xp(a,t),t}p(Qp,"upscaleImageAPIParametersInternalToVertex");function Zp(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=>pi(s))),l(e,["generatedImages"],o)}return e}p(Zp,"upscaleImageResponseFromVertex");function jp(n){let e={},t=r(n,["uri"]);t!=null&&l(e,["uri"],t);let i=r(n,["encodedVideo"]);i!=null&&l(e,["videoBytes"],Je(i));let o=r(n,["encoding"]);return o!=null&&l(e,["mimeType"],o),e}p(jp,"videoFromMldev");function eh(n){let e={},t=r(n,["gcsUri"]);t!=null&&l(e,["uri"],t);let i=r(n,["bytesBase64Encoded"]);i!=null&&l(e,["videoBytes"],Je(i));let o=r(n,["mimeType"]);return o!=null&&l(e,["mimeType"],o),e}p(eh,"videoFromVertex");function th(n){let e={},t=r(n,["image"]);t!=null&&l(e,["_self"],De(t));let i=r(n,["maskMode"]);return i!=null&&l(e,["maskMode"],i),e}p(th,"videoGenerationMaskToVertex");function nh(n){let e={},t=r(n,["image"]);t!=null&&l(e,["image"],hi(t));let i=r(n,["referenceType"]);return i!=null&&l(e,["referenceType"],i),e}p(nh,"videoGenerationReferenceImageToMldev");function ih(n){let e={},t=r(n,["image"]);t!=null&&l(e,["image"],De(t));let i=r(n,["referenceType"]);return i!=null&&l(e,["referenceType"],i),e}p(ih,"videoGenerationReferenceImageToVertex");function _l(n){let e={},t=r(n,["uri"]);t!=null&&l(e,["uri"],t);let i=r(n,["videoBytes"]);i!=null&&l(e,["encodedVideo"],Je(i));let o=r(n,["mimeType"]);return o!=null&&l(e,["encoding"],o),e}p(_l,"videoToMldev");function Al(n){let e={},t=r(n,["uri"]);t!=null&&l(e,["gcsUri"],t);let i=r(n,["videoBytes"]);i!=null&&l(e,["bytesBase64Encoded"],Je(i));let o=r(n,["mimeType"]);return o!=null&&l(e,["mimeType"],o),e}p(Al,"videoToVertex");function oh(n,e){let t={},i=r(n,["displayName"]);return e!==void 0&&i!=null&&l(e,["displayName"],i),t}p(oh,"createFileSearchStoreConfigToMldev");function sh(n){let e={},t=r(n,["config"]);return t!=null&&oh(t,e),e}p(sh,"createFileSearchStoreParametersToMldev");function rh(n,e){let t={},i=r(n,["force"]);return e!==void 0&&i!=null&&l(e,["_query","force"],i),t}p(rh,"deleteFileSearchStoreConfigToMldev");function ah(n){let e={},t=r(n,["name"]);t!=null&&l(e,["_url","name"],t);let i=r(n,["config"]);return i!=null&&rh(i,e),e}p(ah,"deleteFileSearchStoreParametersToMldev");function lh(n){let e={},t=r(n,["name"]);return t!=null&&l(e,["_url","name"],t),e}p(lh,"getFileSearchStoreParametersToMldev");function ch(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(ch,"importFileConfigToMldev");function dh(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"],fh(a)),e}p(dh,"importFileOperationFromMldev");function uh(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&&ch(o,e),e}p(uh,"importFileParametersToMldev");function fh(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(fh,"importFileResponseFromMldev");function ph(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(ph,"listFileSearchStoresConfigToMldev");function hh(n){let e={},t=r(n,["config"]);return t!=null&&ph(t,e),e}p(hh,"listFileSearchStoresParametersToMldev");function mh(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(mh,"listFileSearchStoresResponseFromMldev");function xl(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(xl,"uploadToFileSearchStoreConfigToMldev");function gh(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&&xl(i,e),e}p(gh,"uploadToFileSearchStoreParametersToMldev");function bh(n){let e={},t=r(n,["sdkHttpResponse"]);return t!=null&&l(e,["sdkHttpResponse"],t),e}p(bh,"uploadToFileSearchStoreResumableResponseFromMldev");var yh="Content-Type",Eh="X-Server-Timeout",wh="User-Agent",Do="x-goog-api-client",vh="1.33.0",Ih=`google-genai-sdk/${vh}`,Ch="v1beta1",Th="v1beta",Mo=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:Ch,o.baseUrl=this.baseUrlFromProjectLocation(),this.normalizeAuthParameters()):(o.apiVersion=(i=this.clientOptions.apiVersion)!==null&&i!==void 0?i:Th,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&&Sh(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 za(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 za(o),this.processStreamResponse(o))).catch(o=>{throw o instanceof Error?o:new Error(JSON.stringify(o))})}processStreamResponse(e){return $e(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
664
 
665
665
  `,"\r\r",`\r
666
666
  \r
667
- `];for(;;){let{done:u,value:f}=yield M(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 y=JSON.parse(JSON.stringify(b.error)),w=y.status,v=y.code,I=`got status: ${w}. ${JSON.stringify(b)}`;if(v>=400&&v<600)throw new Jn({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 c){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 y=b.trim();if(y.startsWith(d)){let w=y.substring(d.length).trim();try{let v=new Response(w,{headers:e?.headers,status:e?.status,statusText:e?.statusText});yield yield M(new zt(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=uh+" "+this.clientOptions.userAgentExtra;return e[dh]=t,e[No]=t,e[ah]="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(lh,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 d=(i=t?.mimeType)!==null&&i!==void 0?i:a.type;if(d===void 0||d==="")throw new Error("Can not determine mimeType. Please provide mimeType in the config.");o.mimeType=d;let c={file:o},u=this.getFileName(e),f=A("upload/v1beta/files",c._url),h=await this.fetchUploadUrl(f,o.sizeBytes,o.mimeType,u,c,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),d=String(a.size),c=(o=i?.mimeType)!==null&&o!==void 0?o:a.type;if(c===void 0||c==="")throw new Error("Can not determine mimeType. Please provide mimeType in the config.");let u=`upload/v1beta/${e}:uploadToFileSearchStore`,f=this.getFileName(t),h={};i!=null&&vl(i,h);let m=await this.fetchUploadUrl(u,d,c,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 d;let c={};a?c=a:c={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:c});if(!u||!u?.headers)throw new Error("Server did not return an HttpResponse or the returned HttpResponse did not have headers.");let f=(d=u?.headers)===null||d===void 0?void 0:d["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 Ua(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 Jn({message:o,status:t}):new Error(o)}}p(Ua,"throwErrorIfNotOK");function hh(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 d=Object.assign({},s);for(let c in a)if(Object.prototype.hasOwnProperty.call(a,c)){let u=a[c],f=d[c];u&&typeof u=="object"&&!Array.isArray(u)&&f&&typeof f=="object"&&!Array.isArray(f)?d[c]=i(f,u):(f&&u&&typeof f!=typeof u&&console.warn(`includeExtraBodyToRequestInit:deepMerge: Type mismatch for key "${c}". Original type: ${typeof f}, New type: ${typeof u}. Overwriting.`),d[c]=u)}return d}p(i,"deepMerge");let o=i(t,e);n.body=JSON.stringify(o)}p(hh,"includeExtraBodyToRequestInit");var mh="mcp_used/unknown",gh=!1;function Il(n){for(let e of n)if(bh(e)||typeof e=="object"&&"inputSchema"in e)return!0;return gh}p(Il,"hasMcpToolUsage");function Cl(n){var e;let t=(e=n[No])!==null&&e!==void 0?e:"";n[No]=(t+` ${mh}`).trimStart()}p(Cl,"setMcpUsageHeader");function bh(n){return n!==null&&typeof n=="object"&&n instanceof ko}p(bh,"isMcpCallableTool");function yh(n){return $e(this,arguments,p(function*(t,i=100){let o,s=0;for(;s<i;){let a=yield M(t.listTools({cursor:o}));for(let d of a.tools)yield yield M(d),s++;if(!a.nextCursor)break;o=a.nextCursor}},"listAllTools_1"))}p(yh,"listAllTools");var ko=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 d=!0,c=(t=void 0,ke(yh(f))),u;u=await c.next(),e=u.done,!e;d=!0){o=u.value,d=!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{!d&&!e&&(i=c.return)&&await i.call(c)}finally{if(t)throw t.error}}this.mcpTools=a,this.functionNameToMcpClient=s}async tool(){return await this.initialize(),tc(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 Eh(n,e,t){let i=new wo,o;t.data instanceof Blob?o=JSON.parse(await t.data.text()):o=JSON.parse(t.data),Object.assign(i,o),e(i)}p(Eh,"handleWebSocketMessage$1");var Ro=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=vh(this.apiClient.getDefaultHeaders()),d=this.apiClient.getApiKey(),c=`${o}/ws/google.ai.generativelanguage.${s}.GenerativeService.BidiGenerateMusic?key=${d}`,u=p(()=>{},"onopenResolve"),f=new Promise(C=>{u=C}),h=e.callbacks,m=p(function(){u({})},"onopenAwaitedCallback"),g=this.apiClient,b={onopen:m,onmessage:p(C=>{Eh(g,h.onmessage,C)},"onmessage"),onerror:(t=h?.onerror)!==null&&t!==void 0?t:function(C){},onclose:(i=h?.onclose)!==null&&i!==void 0?i:function(C){}},y=this.webSocketFactory.create(c,wh(a),b);y.connect(),await f;let I={setup:{model:q(this.apiClient,e.model)}};return y.send(JSON.stringify(I)),new Do(y,this.apiClient)}},Do=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=Ju(e);this.conn.send(JSON.stringify({clientContent:t}))}async setMusicGenerationConfig(e){e.musicGenerationConfig||(e.musicGenerationConfig={});let t=Ku(e);this.conn.send(JSON.stringify(t))}sendPlaybackControl(e){let t={playbackControl:e};this.conn.send(JSON.stringify(t))}play(){this.sendPlaybackControl(xt.PLAY)}pause(){this.sendPlaybackControl(xt.PAUSE)}stop(){this.sendPlaybackControl(xt.STOP)}resetContext(){this.sendPlaybackControl(xt.RESET_CONTEXT)}close(){this.conn.close()}};function wh(n){let e={};return n.forEach((t,i)=>{e[i]=t}),e}p(wh,"headersToMap$1");function vh(n){let e=new Headers;for(let[t,i]of Object.entries(n))e.append(t,i);return e}p(vh,"mapToHeaders$1");var Ih="FunctionResponse request must have an `id` field from the response of a ToolCall.FunctionalCalls in Google AI.";async function Ch(n,e,t){let i=new Eo,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=Xu(s);Object.assign(i,a)}else Object.assign(i,s);e(i)}p(Ch,"handleWebSocketMessage");var Mo=class{static{p(this,"Live")}constructor(e,t,i){this.apiClient=e,this.auth=t,this.webSocketFactory=i,this.music=new Ro(this.apiClient,this.auth,this.webSocketFactory)}async connect(e){var t,i,o,s,a,d;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 c=this.apiClient.getWebsocketBaseUrl(),u=this.apiClient.getApiVersion(),f,h=this.apiClient.getHeaders();e.config&&e.config.tools&&Il(e.config.tools)&&Cl(h);let m=_h(h);if(this.apiClient.isVertexAI())f=`${c}/ws/google.cloud.aiplatform.${u}.LlmBidiService/BidiGenerateContent`,await this.auth.addAuthHeaders(m,f);else{let P=this.apiClient.getApiKey(),$="BidiGenerateContent",F="key";P?.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."),$="BidiGenerateContentConstrained",F="access_token"),f=`${c}/ws/google.ai.generativelanguage.${u}.GenerativeService.${$}?${F}=${P}`}let g=p(()=>{},"onopenResolve"),b=new Promise(P=>{g=P}),y=e.callbacks,w=p(function(){var P;(P=y?.onopen)===null||P===void 0||P.call(y),g({})},"onopenAwaitedCallback"),v=this.apiClient,I={onopen:w,onmessage:p(P=>{Ch(v,y.onmessage,P)},"onmessage"),onerror:(t=y?.onerror)!==null&&t!==void 0?t:function(P){},onclose:(i=y?.onclose)!==null&&i!==void 0?i:function(P){}},C=this.webSocketFactory.create(f,Sh(m),I);C.connect(),await b;let T=q(this.apiClient,e.model);if(this.apiClient.isVertexAI()&&T.startsWith("publishers/")){let P=this.apiClient.getProject(),$=this.apiClient.getLocation();T=`projects/${P}/locations/${$}/`+T}let x={};this.apiClient.isVertexAI()&&((o=e.config)===null||o===void 0?void 0:o.responseModalities)===void 0&&(e.config===void 0?e.config={responseModalities:[$n.AUDIO]}:e.config.responseModalities=[$n.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 G=(d=(a=e.config)===null||a===void 0?void 0:a.tools)!==null&&d!==void 0?d:[],S=[];for(let P of G)if(this.isCallableTool(P)){let $=P;S.push(await $.tool())}else S.push(P);S.length>0&&(e.config.tools=S);let N={model:T,config:e.config,callbacks:e.callbacks};return this.apiClient.isVertexAI()?x=zu(this.apiClient,N):x=Hu(this.apiClient,N),delete x.config,C.send(JSON.stringify(x)),new Lo(C,this.apiClient)}isCallableTool(e){return"callTool"in e&&typeof e.callTool=="function"}},Th={turnComplete:!0},Lo=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=_e(t.turns),e.isVertexAI()||(i=i.map(o=>di(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(Ih)}return{toolResponse:{functionResponses:i}}}sendClientContent(e){e=Object.assign(Object.assign({},Th),e);let t=this.tLiveClientContent(this.apiClient,e);this.conn.send(JSON.stringify(t))}sendRealtimeInput(e){let t={};this.apiClient.isVertexAI()?t={realtimeInput:Yu(e)}:t={realtimeInput:Wu(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 Sh(n){let e={};return n.forEach((t,i)=>{e[i]=t}),e}p(Sh,"headersToMap");function _h(n){let e=new Headers;for(let[t,i]of Object.entries(n))e.append(t,i);return e}p(_h,"mapToHeaders");var Fa=10;function Ba(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(Gt(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(Ba,"shouldDisableAfc");function Gt(n){return"callTool"in n&&typeof n.callTool=="function"}p(Gt,"isCallableTool");function Ah(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=>Gt(o)))!==null&&i!==void 0?i:!1}p(Ah,"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(Gt(i))return;let s=i;s.functionDeclarations&&s.functionDeclarations.length>0&&t.push(o)}),t}p(Va,"findAfcIncompatibleToolIndexes");function qa(n){var e;return!(!((e=n?.automaticFunctionCalling)===null||e===void 0)&&e.ignoreCallHistory)}p(qa,"shouldAppendAfcHistory");var Uo=class extends Re{static{p(this,"Models")}constructor(e){super(),this.apiClient=e,this.generateContent=async t=>{var i,o,s,a,d;let c=await this.processParamsMaybeAddMcpUsage(t);if(this.maybeMoveToResponseJsonSchem(t),!Ah(t)||Ba(t.config))return await this.generateContentInternal(c);let u=Va(t);if(u.length>0){let y=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 ${y}.`)}let f,h,m=_e(c.contents),g=(s=(o=(i=c.config)===null||i===void 0?void 0:i.automaticFunctionCalling)===null||o===void 0?void 0:o.maximumRemoteCalls)!==null&&s!==void 0?s:Fa,b=0;for(;b<g&&(f=await this.generateContentInternal(c),!(!f.functionCalls||f.functionCalls.length===0));){let y=f.candidates[0].content,w=[];for(let v of(d=(a=t.config)===null||a===void 0?void 0:a.tools)!==null&&d!==void 0?d:[])if(Gt(v)){let C=await v.callTool(f.functionCalls);w.push(...C)}b++,h={role:"user",parts:w},c.contents=_e(c.contents),c.contents.push(y),c.contents.push(h),qa(c.config)&&(m.push(y),m.push(h))}return qa(c.config)&&(f.automaticFunctionCallingHistory=m),f},this.generateContentStream=async t=>{var i,o,s,a,d;if(this.maybeMoveToResponseJsonSchem(t),Ba(t.config)){let h=await this.processParamsMaybeAddMcpUsage(t);return await this.generateContentStreamInternal(h)}let c=Va(t);if(c.length>0){let h=c.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=(d=(a=t?.config)===null||a===void 0?void 0:a.automaticFunctionCalling)===null||d===void 0?void 0:d.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 c of i.generatedImages)c&&c?.safetyAttributes&&((o=c?.safetyAttributes)===null||o===void 0?void 0:o.contentType)==="Positive Prompt"?s=c?.safetyAttributes:a.push(c);let d;return s?d={generatedImages:a,positivePromptSafetyAttributes:s,sdkHttpResponse:i.sdkHttpResponse}:d={generatedImages:a,sdkHttpResponse:i.sdkHttpResponse},d}),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 qe(Ve.PAGED_ITEM_MODELS,d=>this.listInternal(d),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,d,c;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&&(!((c=(d=t.source)===null||d===void 0?void 0:d.video)===null||c===void 0)&&c.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 c=>Gt(c)?await c.tool():c)),d={model:e.model,contents:e.contents,config:Object.assign(Object.assign({},e.config),{tools:a})};if(d.config.tools=a,e.config&&e.config.tools&&Il(e.config.tools)){let c=(o=(i=e.config.httpOptions)===null||i===void 0?void 0:i.headers)!==null&&o!==void 0?o:{},u=Object.assign({},c);Object.keys(u).length===0&&(u=this.apiClient.getDefaultHeaders()),Cl(u),d.config.httpOptions=Object.assign(Object.assign({},e.config.httpOptions),{headers:u})}return d}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(Gt(a)){let d=a,c=await d.tool();for(let u of(o=c.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,d)}}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:Fa,a=!1,d=0,c=await this.initAfcToolsMap(e);return function(u,f,h){return $e(this,arguments,function*(){for(var m,g,b,y,w,v;d<s;){a&&(d++,a=!1);let x=yield M(u.processParamsMaybeAddMcpUsage(h)),G=yield M(u.generateContentStreamInternal(x)),S=[],N=[];try{for(var I=!0,C=(g=void 0,ke(G)),T;T=yield M(C.next()),m=T.done,!m;I=!0){y=T.value,I=!1;let P=y;if(yield yield M(P),P.candidates&&(!((w=P.candidates[0])===null||w===void 0)&&w.content)){N.push(P.candidates[0].content);for(let $ of(v=P.candidates[0].content.parts)!==null&&v!==void 0?v:[])if(d<s&&$.functionCall){if(!$.functionCall.name)throw new Error("Function call name was not returned by the model.");if(f.has($.functionCall.name)){let F=yield M(f.get($.functionCall.name).callTool([$.functionCall]));S.push(...F)}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: ${$.functionCall.name}`)}}}}catch(P){g={error:P}}finally{try{!I&&!m&&(b=C.return)&&(yield M(b.call(C)))}finally{if(g)throw g.error}}if(S.length>0){a=!0;let P=new ft;P.candidates=[{content:{role:"user",parts:S}}],yield yield M(P);let $=[];$.push(...N),$.push({role:"user",parts:S});let F=_e(h.contents).concat($);h.contents=F}else break}})}(this,c,e)}async generateContentInternal(e){var t,i,o,s;let a,d="",c={};if(this.apiClient.isVertexAI()){let u=Da(this.apiClient,e);return d=A("{model}:generateContent",u._url),c=u._query,delete u._url,delete u._query,a=this.apiClient.request({path:d,queryParams:c,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=La(f),m=new ft;return Object.assign(m,h),m})}else{let u=Ra(this.apiClient,e);return d=A("{model}:generateContent",u._url),c=u._query,delete u._url,delete u._query,a=this.apiClient.request({path:d,queryParams:c,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=Ma(f),m=new ft;return Object.assign(m,h),m})}}async generateContentStreamInternal(e){var t,i,o,s;let a,d="",c={};if(this.apiClient.isVertexAI()){let u=Da(this.apiClient,e);return d=A("{model}:streamGenerateContent?alt=sse",u._url),c=u._query,delete u._url,delete u._query,a=this.apiClient.requestStream({path:d,queryParams:c,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 $e(this,arguments,function*(){var m,g,b,y;try{for(var w=!0,v=ke(h),I;I=yield M(v.next()),m=I.done,!m;w=!0){y=I.value,w=!1;let C=y,T=La(yield M(C.json()));T.sdkHttpResponse={headers:C.headers};let x=new ft;Object.assign(x,T),yield yield M(x)}}catch(C){g={error:C}}finally{try{!w&&!m&&(b=v.return)&&(yield M(b.call(v)))}finally{if(g)throw g.error}}})})}else{let u=Ra(this.apiClient,e);return d=A("{model}:streamGenerateContent?alt=sse",u._url),c=u._query,delete u._url,delete u._query,a=this.apiClient.requestStream({path:d,queryParams:c,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 $e(this,arguments,function*(){var m,g,b,y;try{for(var w=!0,v=ke(h),I;I=yield M(v.next()),m=I.done,!m;w=!0){y=I.value,w=!1;let C=y,T=Ma(yield M(C.json()));T.sdkHttpResponse={headers:C.headers};let x=new ft;Object.assign(x,T),yield yield M(x)}}catch(C){g={error:C}}finally{try{!w&&!m&&(b=v.return)&&(yield M(b.call(v)))}finally{if(g)throw g.error}}})})}}async embedContent(e){var t,i,o,s;let a,d="",c={};if(this.apiClient.isVertexAI()){let u=Af(this.apiClient,e);return d=A("{model}:predict",u._url),c=u._query,delete u._url,delete u._query,a=this.apiClient.request({path:d,queryParams:c,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=Pf(f),m=new Rn;return Object.assign(m,h),m})}else{let u=_f(this.apiClient,e);return d=A("{model}:batchEmbedContents",u._url),c=u._query,delete u._url,delete u._query,a=this.apiClient.request({path:d,queryParams:c,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 Rn;return Object.assign(m,h),m})}}async generateImagesInternal(e){var t,i,o,s;let a,d="",c={};if(this.apiClient.isVertexAI()){let u=Bf(this.apiClient,e);return d=A("{model}:predict",u._url),c=u._query,delete u._url,delete u._query,a=this.apiClient.request({path:d,queryParams:c,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=qf(f),m=new Dn;return Object.assign(m,h),m})}else{let u=Ff(this.apiClient,e);return d=A("{model}:predict",u._url),c=u._query,delete u._url,delete u._query,a=this.apiClient.request({path:d,queryParams:c,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=Vf(f),m=new Dn;return Object.assign(m,h),m})}}async editImageInternal(e){var t,i;let o,s="",a={};if(this.apiClient.isVertexAI()){let d=If(this.apiClient,e);return s=A("{model}:predict",d._url),a=d._query,delete d._url,delete d._query,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(c=>c.json().then(u=>{let f=u;return f.sdkHttpResponse={headers:c.headers},f})),o.then(c=>{let u=Cf(c),f=new ro;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 d=Bp(this.apiClient,e);return s=A("{model}:predict",d._url),a=d._query,delete d._url,delete d._query,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(c=>c.json().then(u=>{let f=u;return f.sdkHttpResponse={headers:c.headers},f})),o.then(c=>{let u=Vp(c),f=new ao;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 d=vp(this.apiClient,e);return s=A("{model}:predict",d._url),a=d._query,delete d._url,delete d._query,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(c=>c.json()),o.then(c=>{let u=Ip(c),f=new lo;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 d=xp(this.apiClient,e);return s=A("{model}:predict",d._url),a=d._query,delete d._url,delete d._query,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(c=>c.json()),o.then(c=>{let u=Pp(c),f=new co;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,d="",c={};if(this.apiClient.isVertexAI()){let u=sp(this.apiClient,e);return d=A("{name}",u._url),c=u._query,delete u._url,delete u._query,a=this.apiClient.request({path:d,queryParams:c,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=>Go(f))}else{let u=op(this.apiClient,e);return d=A("{name}",u._url),c=u._query,delete u._url,delete u._query,a=this.apiClient.request({path:d,queryParams:c,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=>Po(f))}}async listInternal(e){var t,i,o,s;let a,d="",c={};if(this.apiClient.isVertexAI()){let u=hp(this.apiClient,e);return d=A("{models_url}",u._url),c=u._query,delete u._url,delete u._query,a=this.apiClient.request({path:d,queryParams:c,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=gp(f),m=new Mn;return Object.assign(m,h),m})}else{let u=pp(this.apiClient,e);return d=A("{models_url}",u._url),c=u._query,delete u._url,delete u._query,a=this.apiClient.request({path:d,queryParams:c,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=mp(f),m=new Mn;return Object.assign(m,h),m})}}async update(e){var t,i,o,s;let a,d="",c={};if(this.apiClient.isVertexAI()){let u=Up(this.apiClient,e);return d=A("{model}",u._url),c=u._query,delete u._url,delete u._query,a=this.apiClient.request({path:d,queryParams:c,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=>Go(f))}else{let u=Lp(this.apiClient,e);return d=A("{name}",u._url),c=u._query,delete u._url,delete u._query,a=this.apiClient.request({path:d,queryParams:c,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=>Po(f))}}async delete(e){var t,i,o,s;let a,d="",c={};if(this.apiClient.isVertexAI()){let u=yf(this.apiClient,e);return d=A("{name}",u._url),c=u._query,delete u._url,delete u._query,a=this.apiClient.request({path:d,queryParams:c,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=wf(f),m=new Ln;return Object.assign(m,h),m})}else{let u=bf(this.apiClient,e);return d=A("{name}",u._url),c=u._query,delete u._url,delete u._query,a=this.apiClient.request({path:d,queryParams:c,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=Ef(f),m=new Ln;return Object.assign(m,h),m})}}async countTokens(e){var t,i,o,s;let a,d="",c={};if(this.apiClient.isVertexAI()){let u=hf(this.apiClient,e);return d=A("{model}:countTokens",u._url),c=u._query,delete u._url,delete u._query,a=this.apiClient.request({path:d,queryParams:c,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 Un;return Object.assign(m,h),m})}else{let u=pf(this.apiClient,e);return d=A("{model}:countTokens",u._url),c=u._query,delete u._url,delete u._query,a=this.apiClient.request({path:d,queryParams:c,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 Un;return Object.assign(m,h),m})}}async computeTokens(e){var t,i;let o,s="",a={};if(this.apiClient.isVertexAI()){let d=rf(this.apiClient,e);return s=A("{model}:computeTokens",d._url),a=d._query,delete d._url,delete d._query,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(c=>c.json().then(u=>{let f=u;return f.sdkHttpResponse={headers:c.headers},f})),o.then(c=>{let u=af(c),f=new uo;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,d="",c={};if(this.apiClient.isVertexAI()){let u=Wf(this.apiClient,e);return d=A("{model}:predictLongRunning",u._url),c=u._query,delete u._url,delete u._query,a=this.apiClient.request({path:d,queryParams:c,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=Kf(f),m=new Fn;return Object.assign(m,h),m})}else{let u=Jf(this.apiClient,e);return d=A("{model}:predictLongRunning",u._url),c=u._query,delete u._url,delete u._query,a=this.apiClient.request({path:d,queryParams:c,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=zf(f),m=new Fn;return Object.assign(m,h),m})}}};var Fo=class extends Re{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,d="",c={};if(this.apiClient.isVertexAI()){let u=qd(e);return d=A("{operationName}",u._url),c=u._query,delete u._url,delete u._query,a=this.apiClient.request({path:d,queryParams:c,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=Vd(e);return d=A("{operationName}",u._url),c=u._query,delete u._url,delete u._query,a=this.apiClient.request({path:d,queryParams:c,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 d=Rd(e);return s=A("{resourceName}:fetchPredictOperation",d._url),a=d._query,delete d._url,delete d._query,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(c=>c.json()),o}else throw new Error("This method is only supported by the Vertex AI.")}};function xh(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(xh,"blobToMldev");function Ph(n){let e={},t=r(n,["parts"]);if(t!=null){let o=t;Array.isArray(o)&&(o=o.map(s=>Uh(s))),l(e,["parts"],o)}let i=r(n,["role"]);return i!=null&&l(e,["role"],i),e}p(Ph,"contentToMldev");function Gh(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 d=r(e,["liveConnectConstraints"]);t!==void 0&&d!=null&&l(t,["bidiGenerateContentSetup"],Lh(n,d));let c=r(e,["lockAdditionalFields"]);return t!==void 0&&c!=null&&l(t,["fieldMask"],c),i}p(Gh,"createAuthTokenConfigToMldev");function Nh(n,e){let t={},i=r(e,["config"]);return i!=null&&l(t,["config"],Gh(n,i,t)),t}p(Nh,"createAuthTokenParametersToMldev");function $h(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($h,"fileDataToMldev");function kh(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(kh,"functionCallToMldev");function Rh(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(Rh,"googleMapsToMldev");function Dh(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(Dh,"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 d=r(n,["topK"]);e!==void 0&&d!=null&&l(e,["setup","generationConfig","topK"],d);let c=r(n,["maxOutputTokens"]);e!==void 0&&c!=null&&l(e,["setup","generationConfig","maxOutputTokens"],c);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"],as(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"],Ph(ue(b)));let y=r(n,["tools"]);if(e!==void 0&&y!=null){let G=Rt(y);Array.isArray(G)&&(G=G.map(S=>Bh(kt(S)))),l(e,["setup","tools"],G)}let w=r(n,["sessionResumption"]);e!==void 0&&w!=null&&l(e,["setup","sessionResumption"],Fh(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 C=r(n,["realtimeInputConfig"]);e!==void 0&&C!=null&&l(e,["setup","realtimeInputConfig"],C);let T=r(n,["contextWindowCompression"]);e!==void 0&&T!=null&&l(e,["setup","contextWindowCompression"],T);let x=r(n,["proactivity"]);if(e!==void 0&&x!=null&&l(e,["setup","proactivity"],x),r(n,["explicitVadSignal"])!==void 0)throw new Error("explicitVadSignal parameter is not supported in Gemini API.");return t}p(Mh,"liveConnectConfigToMldev");function Lh(n,e){let t={},i=r(e,["model"]);i!=null&&l(t,["setup","model"],q(n,i));let o=r(e,["config"]);return o!=null&&l(t,["config"],Mh(o,t)),t}p(Lh,"liveConnectConstraintsToMldev");function Uh(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"],$h(s));let a=r(n,["functionCall"]);a!=null&&l(e,["functionCall"],kh(a));let d=r(n,["functionResponse"]);d!=null&&l(e,["functionResponse"],d);let c=r(n,["inlineData"]);c!=null&&l(e,["inlineData"],xh(c));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(Uh,"partToMldev");function Fh(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(Fh,"sessionResumptionConfigToMldev");function Bh(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 d=r(n,["googleMaps"]);d!=null&&l(e,["googleMaps"],Rh(d));let c=r(n,["googleSearch"]);c!=null&&l(e,["googleSearch"],Dh(c));let u=r(n,["urlContext"]);return u!=null&&l(e,["urlContext"],u),e}p(Bh,"toolToMldev");function Vh(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(Vh,"getFieldMasks");function qh(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=Vh(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"],d=[];o.length>0&&(d=o.map(u=>a.includes(u)?`generationConfig.${u}`:u));let c=[];s&&c.push(s),d.length>0&&c.push(...d),c.length>0?n.fieldMask=c.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(qh,"convertBidiSetupToTokenSetup");var Bo=class extends Re{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 d=Nh(this.apiClient,e);s=A("auth_tokens",d._url),a=d._query,delete d.config,delete d._url,delete d._query;let c=qh(d,e.config);return 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(u=>u.json()),o.then(u=>u)}}};function Oh(n,e){let t={},i=r(n,["force"]);return e!==void 0&&i!=null&&l(e,["_query","force"],i),t}p(Oh,"deleteDocumentConfigToMldev");function Hh(n){let e={},t=r(n,["name"]);t!=null&&l(e,["_url","name"],t);let i=r(n,["config"]);return i!=null&&Oh(i,e),e}p(Hh,"deleteDocumentParametersToMldev");function zh(n){let e={},t=r(n,["name"]);return t!=null&&l(e,["_url","name"],t),e}p(zh,"getDocumentParametersToMldev");function Kh(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(Kh,"listDocumentsConfigToMldev");function Jh(n){let e={},t=r(n,["parent"]);t!=null&&l(e,["_url","parent"],t);let i=r(n,["config"]);return i!=null&&Kh(i,e),e}p(Jh,"listDocumentsParametersToMldev");function Wh(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(Wh,"listDocumentsResponseFromMldev");var Vo=class extends Re{static{p(this,"Documents")}constructor(e){super(),this.apiClient=e,this.list=async t=>new qe(Ve.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 d=zh(e);return s=A("{name}",d._url),a=d._query,delete d._url,delete d._query,o=this.apiClient.request({path:s,queryParams:a,body:JSON.stringify(d),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(c=>c.json()),o.then(c=>c)}}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=Hh(e);o=A("{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 d=Jh(e);return s=A("{parent}/documents",d._url),a=d._query,delete d._url,delete d._query,o=this.apiClient.request({path:s,queryParams:a,body:JSON.stringify(d),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(c=>c.json()),o.then(c=>{let u=Wh(c),f=new fo;return Object.assign(f,u),f})}}};var qo=class extends Re{static{p(this,"FileSearchStores")}constructor(e,t=new Vo(e)){super(),this.apiClient=e,this.documents=t,this.list=async(i={})=>new qe(Ve.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 d=Wp(e);return s=A("fileSearchStores",d._url),a=d._query,delete d._url,delete d._query,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(c=>c.json()),o.then(c=>c)}}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 d=Qp(e);return s=A("{name}",d._url),a=d._query,delete d._url,delete d._query,o=this.apiClient.request({path:s,queryParams:a,body:JSON.stringify(d),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(c=>c.json()),o.then(c=>c)}}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=Xp(e);o=A("{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 d=ih(e);return s=A("fileSearchStores",d._url),a=d._query,delete d._url,delete d._query,o=this.apiClient.request({path:s,queryParams:a,body:JSON.stringify(d),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(c=>c.json()),o.then(c=>{let u=oh(c),f=new po;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 d=sh(e);return s=A("upload/v1beta/{file_search_store_name}:uploadToFileSearchStore",d._url),a=d._query,delete d._url,delete d._query,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(c=>c.json()),o.then(c=>{let u=rh(c),f=new ho;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 d=eh(e);return s=A("{file_search_store_name}:importFile",d._url),a=d._query,delete d._url,delete d._query,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(c=>c.json()),o.then(c=>{let u=jp(c),f=new mo;return Object.assign(f,u),f})}}};var Tl=p(function(){let{crypto:n}=globalThis;if(n?.randomUUID)return Tl=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"),Yh=p(()=>Tl(),"uuid4");function Oo(n){return typeof n=="object"&&n!==null&&("name"in n&&n.name==="AbortError"||"message"in n&&String(n.message).includes("FetchRequestCanceledException"))}p(Oo,"isAbortError");var Ho=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 Nt({message:i,cause:Ho(t)});let s=t;return e===400?new Yn(e,s,i,o):e===401?new Xn(e,s,i,o):e===403?new Qn(e,s,i,o):e===404?new Zn(e,s,i,o):e===409?new jn(e,s,i,o):e===422?new ei(e,s,i,o):e===429?new ti(e,s,i,o):e>=500?new ni(e,s,i,o):new n(e,s,i,o)}},Kt=class extends be{static{p(this,"APIUserAbortError")}constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}},Nt=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)}},Wn=class extends Nt{static{p(this,"APIConnectionTimeoutError")}constructor({message:e}={}){super({message:e??"Request timed out."})}},Yn=class extends be{static{p(this,"BadRequestError")}},Xn=class extends be{static{p(this,"AuthenticationError")}},Qn=class extends be{static{p(this,"PermissionDeniedError")}},Zn=class extends be{static{p(this,"NotFoundError")}},jn=class extends be{static{p(this,"ConflictError")}},ei=class extends be{static{p(this,"UnprocessableEntityError")}},ti=class extends be{static{p(this,"RateLimitError")}},ni=class extends be{static{p(this,"InternalServerError")}};var Xh=/^[a-z][a-z0-9+.-]*:/i,Qh=p(n=>Xh.test(n),"isAbsoluteURL"),zo=p(n=>(zo=Array.isArray,zo(n)),"isArrayInternal"),Zh=zo,jh=Zh,Oa=jh;function em(n){if(!n)return!0;for(let e in n)return!1;return!0}p(em,"isEmptyObj");function tm(n,e){return Object.prototype.hasOwnProperty.call(n,e)}p(tm,"hasOwn");var nm=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"),im=p(n=>{try{return JSON.parse(n)}catch{return}},"safeJSON");var om=p(n=>new Promise(e=>setTimeout(e,n)),"sleep$1");var At="0.0.1";function sm(){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(sm,"getDetectedPlatform");var rm=p(()=>{var n,e,t,i,o;let s=sm();if(s==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":At,"X-Stainless-OS":za(Deno.build.os),"X-Stainless-Arch":Ha(Deno.build.arch),"X-Stainless-Runtime":"deno","X-Stainless-Runtime-Version":typeof Deno.version=="string"?Deno.version:(e=(n=Deno.version)===null||n===void 0?void 0:n.deno)!==null&&e!==void 0?e:"unknown"};if(typeof EdgeRuntime<"u")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":At,"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":At,"X-Stainless-OS":za((t=globalThis.process.platform)!==null&&t!==void 0?t:"unknown"),"X-Stainless-Arch":Ha((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=am();return a?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":At,"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":At,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}},"getPlatformProperties");function am(){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(am,"getBrowserInfo");var Ha=p(n=>n==="x32"?"x32":n==="x86_64"||n==="x64"?"x64":n==="arm"?"arm":n==="aarch64"||n==="arm64"?"arm64":n?`other:${n}`:"unknown","normalizeArch"),za=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"),Sn,lm=p(()=>Sn??(Sn=rm()),"getPlatformHeaders");function dm(){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(dm,"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 cm(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(cm,"ReadableStreamFrom");function _l(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(_l,"ReadableStreamToAsyncIterable");async function um(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(um,"CancelReadableStream");var fm=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 to(n,e,t){return Al(),new File(n,e??"unknown_file",t)}p(to,"makeFile");function pm(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(pm,"getName");var hm=p(n=>n!=null&&typeof n=="object"&&typeof n[Symbol.asyncIterator]=="function","isAsyncIterable");var xl=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"),mm=p(n=>n!=null&&typeof n=="object"&&typeof n.name=="string"&&typeof n.lastModified=="number"&&xl(n),"isFileLike"),gm=p(n=>n!=null&&typeof n=="object"&&typeof n.url=="string"&&typeof n.blob=="function","isResponseLike");async function bm(n,e,t){if(Al(),n=await n,mm(n))return n instanceof File?n:to([await n.arrayBuffer()],n.name);if(gm(n)){let o=await n.blob();return e||(e=new URL(n.url).pathname.split(/[\\/]/).pop()),to(await Ko(o),e,t)}let i=await Ko(n);if(e||(e=pm(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 to(i,e,t)}p(bm,"toFile");async function Ko(n){var e,t,i,o,s;let a=[];if(typeof n=="string"||ArrayBuffer.isView(n)||n instanceof ArrayBuffer)a.push(n);else if(xl(n))a.push(n instanceof Blob?n:await n.arrayBuffer());else if(hm(n))try{for(var d=!0,c=ke(n),u;u=await c.next(),e=u.done,!e;d=!0){o=u.value,d=!1;let f=o;a.push(...await Ko(f))}}catch(f){t={error:f}}finally{try{!d&&!e&&(i=c.return)&&await i.call(c)}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}`:""}${ym(n)}`)}return a}p(Ko,"getBytes");function ym(n){return typeof n!="object"||n===null?"":`; props: [${Object.getOwnPropertyNames(n).map(t=>`"${t}"`).join(", ")}]`}p(ym,"propsForError");var ii=class{static{p(this,"APIResource")}constructor(e){this._client=e}};ii._key=[];function Pl(n){return n.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}p(Pl,"encodeURIPath");var Ka=Object.freeze(Object.create(null)),Em=p((n=Pl)=>p(function(t,...i){if(t.length===1)return t[0];let o=!1,s=[],a=t.reduce((f,h,m)=>{var g,b,y;/[?#]/.test(h)&&(o=!0);let w=i[m],v=(o?encodeURIComponent:n)(""+w);return m!==i.length&&(w==null||typeof w=="object"&&w.toString===((y=Object.getPrototypeOf((b=Object.getPrototypeOf((g=w.hasOwnProperty)!==null&&g!==void 0?g:Ka))!==null&&b!==void 0?b:Ka))===null||y===void 0?void 0:y.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)},""),d=a.split(/[?#]/,1)[0],c=/(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi,u;for(;(u=c.exec(d))!==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),y="^".repeat(g.length);return f=g.start+g.length,m+b+y},"");throw new ge(`Path parameters result in path with invalid segments:
667
+ `];for(;;){let{done:u,value:f}=yield M(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 y=JSON.parse(JSON.stringify(b.error)),w=y.status,v=y.code,I=`got status: ${w}. ${JSON.stringify(b)}`;if(v>=400&&v<600)throw new Xn({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 y=b.trim();if(y.startsWith(c)){let w=y.substring(c.length).trim();try{let v=new Response(w,{headers:e?.headers,status:e?.status,statusText:e?.statusText});yield yield M(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=Ih+" "+this.clientOptions.userAgentExtra;return e[wh]=t,e[Do]=t,e[yh]="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(Eh,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=A("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&&xl(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 za(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 Xn({message:o,status:t}):new Error(o)}}p(za,"throwErrorIfNotOK");function Sh(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(Sh,"includeExtraBodyToRequestInit");var _h="mcp_used/unknown",Ah=!1;function Pl(n){for(let e of n)if(xh(e)||typeof e=="object"&&"inputSchema"in e)return!0;return Ah}p(Pl,"hasMcpToolUsage");function Nl(n){var e;let t=(e=n[Do])!==null&&e!==void 0?e:"";n[Do]=(t+` ${_h}`).trimStart()}p(Nl,"setMcpUsageHeader");function xh(n){return n!==null&&typeof n=="object"&&n instanceof Lo}p(xh,"isMcpCallableTool");function Ph(n){return $e(this,arguments,p(function*(t,i=100){let o,s=0;for(;s<i;){let a=yield M(t.listTools({cursor:o}));for(let c of a.tools)yield yield M(c),s++;if(!a.nextCursor)break;o=a.nextCursor}},"listAllTools_1"))}p(Ph,"listAllTools");var Lo=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,ke(Ph(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(),fd(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 Nh(n,e,t){let i=new To,o;t.data instanceof Blob?o=JSON.parse(await t.data.text()):o=JSON.parse(t.data),Object.assign(i,o),e(i)}p(Nh,"handleWebSocketMessage$1");var Uo=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=$h(this.apiClient.getDefaultHeaders()),c=this.apiClient.getApiKey(),d=`${o}/ws/google.ai.generativelanguage.${s}.GenerativeService.BidiGenerateMusic?key=${c}`,u=p(()=>{},"onopenResolve"),f=new Promise(C=>{u=C}),h=e.callbacks,m=p(function(){u({})},"onopenAwaitedCallback"),g=this.apiClient,b={onopen:m,onmessage:p(C=>{Nh(g,h.onmessage,C)},"onmessage"),onerror:(t=h?.onerror)!==null&&t!==void 0?t:function(C){},onclose:(i=h?.onclose)!==null&&i!==void 0?i:function(C){}},y=this.webSocketFactory.create(d,Gh(a),b);y.connect(),await f;let I={setup:{model:O(this.apiClient,e.model)}};return y.send(JSON.stringify(I)),new Fo(y,this.apiClient)}},Fo=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=sf(e);this.conn.send(JSON.stringify({clientContent:t}))}async setMusicGenerationConfig(e){e.musicGenerationConfig||(e.musicGenerationConfig={});let t=of(e);this.conn.send(JSON.stringify(t))}sendPlaybackControl(e){let t={playbackControl:e};this.conn.send(JSON.stringify(t))}play(){this.sendPlaybackControl(xt.PLAY)}pause(){this.sendPlaybackControl(xt.PAUSE)}stop(){this.sendPlaybackControl(xt.STOP)}resetContext(){this.sendPlaybackControl(xt.RESET_CONTEXT)}close(){this.conn.close()}};function Gh(n){let e={};return n.forEach((t,i)=>{e[i]=t}),e}p(Gh,"headersToMap$1");function $h(n){let e=new Headers;for(let[t,i]of Object.entries(n))e.append(t,i);return e}p($h,"mapToHeaders$1");var kh="FunctionResponse request must have an `id` field from the response of a ToolCall.FunctionalCalls in Google AI.";async function Rh(n,e,t){let i=new Co,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=lf(s);Object.assign(i,a)}else Object.assign(i,s);e(i)}p(Rh,"handleWebSocketMessage");var Bo=class{static{p(this,"Live")}constructor(e,t,i){this.apiClient=e,this.auth=t,this.webSocketFactory=i,this.music=new Uo(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&&Pl(e.config.tools)&&Nl(h);let m=Lh(h);if(this.apiClient.isVertexAI())f=`${d}/ws/google.cloud.aiplatform.${u}.LlmBidiService/BidiGenerateContent`,await this.auth.addAuthHeaders(m,f);else{let P=this.apiClient.getApiKey(),$="BidiGenerateContent",F="key";P?.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."),$="BidiGenerateContentConstrained",F="access_token"),f=`${d}/ws/google.ai.generativelanguage.${u}.GenerativeService.${$}?${F}=${P}`}let g=p(()=>{},"onopenResolve"),b=new Promise(P=>{g=P}),y=e.callbacks,w=p(function(){var P;(P=y?.onopen)===null||P===void 0||P.call(y),g({})},"onopenAwaitedCallback"),v=this.apiClient,I={onopen:w,onmessage:p(P=>{Rh(v,y.onmessage,P)},"onmessage"),onerror:(t=y?.onerror)!==null&&t!==void 0?t:function(P){},onclose:(i=y?.onclose)!==null&&i!==void 0?i:function(P){}},C=this.webSocketFactory.create(f,Mh(m),I);C.connect(),await b;let T=O(this.apiClient,e.model);if(this.apiClient.isVertexAI()&&T.startsWith("publishers/")){let P=this.apiClient.getProject(),$=this.apiClient.getLocation();T=`projects/${P}/locations/${$}/`+T}let x={};this.apiClient.isVertexAI()&&((o=e.config)===null||o===void 0?void 0:o.responseModalities)===void 0&&(e.config===void 0?e.config={responseModalities:[Dn.AUDIO]}:e.config.responseModalities=[Dn.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 N=(c=(a=e.config)===null||a===void 0?void 0:a.tools)!==null&&c!==void 0?c:[],S=[];for(let P of N)if(this.isCallableTool(P)){let $=P;S.push(await $.tool())}else S.push(P);S.length>0&&(e.config.tools=S);let G={model:T,config:e.config,callbacks:e.callbacks};return this.apiClient.isVertexAI()?x=nf(this.apiClient,G):x=tf(this.apiClient,G),delete x.config,C.send(JSON.stringify(x)),new Vo(C,this.apiClient)}isCallableTool(e){return"callTool"in e&&typeof e.callTool=="function"}},Dh={turnComplete:!0},Vo=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=_e(t.turns),e.isVertexAI()||(i=i.map(o=>fi(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(kh)}return{toolResponse:{functionResponses:i}}}sendClientContent(e){e=Object.assign(Object.assign({},Dh),e);let t=this.tLiveClientContent(this.apiClient,e);this.conn.send(JSON.stringify(t))}sendRealtimeInput(e){let t={};this.apiClient.isVertexAI()?t={realtimeInput:af(e)}:t={realtimeInput:rf(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 Mh(n){let e={};return n.forEach((t,i)=>{e[i]=t}),e}p(Mh,"headersToMap");function Lh(n){let e=new Headers;for(let[t,i]of Object.entries(n))e.append(t,i);return e}p(Lh,"mapToHeaders");var Ka=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(Nt(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 Nt(n){return"callTool"in n&&typeof n.callTool=="function"}p(Nt,"isCallableTool");function Uh(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=>Nt(o)))!==null&&i!==void 0?i:!1}p(Uh,"hasCallableTools");function Ja(n){var e;let t=[];return!((e=n?.config)===null||e===void 0)&&e.tools&&n.config.tools.forEach((i,o)=>{if(Nt(i))return;let s=i;s.functionDeclarations&&s.functionDeclarations.length>0&&t.push(o)}),t}p(Ja,"findAfcIncompatibleToolIndexes");function Ya(n){var e;return!(!((e=n?.automaticFunctionCalling)===null||e===void 0)&&e.ignoreCallHistory)}p(Ya,"shouldAppendAfcHistory");var Oo=class extends Re{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),!Uh(t)||Wa(t.config))return await this.generateContentInternal(d);let u=Ja(t);if(u.length>0){let y=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 ${y}.`)}let f,h,m=_e(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:Ka,b=0;for(;b<g&&(f=await this.generateContentInternal(d),!(!f.functionCalls||f.functionCalls.length===0));){let y=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(Nt(v)){let C=await v.callTool(f.functionCalls);w.push(...C)}b++,h={role:"user",parts:w},d.contents=_e(d.contents),d.contents.push(y),d.contents.push(h),Ya(d.config)&&(m.push(y),m.push(h))}return Ya(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=Ja(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 qe(Oe.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=>Nt(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&&Pl(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()),Nl(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(Nt(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:Ka,a=!1,c=0,d=await this.initAfcToolsMap(e);return function(u,f,h){return $e(this,arguments,function*(){for(var m,g,b,y,w,v;c<s;){a&&(c++,a=!1);let x=yield M(u.processParamsMaybeAddMcpUsage(h)),N=yield M(u.generateContentStreamInternal(x)),S=[],G=[];try{for(var I=!0,C=(g=void 0,ke(N)),T;T=yield M(C.next()),m=T.done,!m;I=!0){y=T.value,I=!1;let P=y;if(yield yield M(P),P.candidates&&(!((w=P.candidates[0])===null||w===void 0)&&w.content)){G.push(P.candidates[0].content);for(let $ of(v=P.candidates[0].content.parts)!==null&&v!==void 0?v:[])if(c<s&&$.functionCall){if(!$.functionCall.name)throw new Error("Function call name was not returned by the model.");if(f.has($.functionCall.name)){let F=yield M(f.get($.functionCall.name).callTool([$.functionCall]));S.push(...F)}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: ${$.functionCall.name}`)}}}}catch(P){g={error:P}}finally{try{!I&&!m&&(b=C.return)&&(yield M(b.call(C)))}finally{if(g)throw g.error}}if(S.length>0){a=!0;let P=new ft;P.candidates=[{content:{role:"user",parts:S}}],yield yield M(P);let $=[];$.push(...G),$.push({role:"user",parts:S});let F=_e(h.contents).concat($);h.contents=F}else break}})}(this,d,e)}async generateContentInternal(e){var t,i,o,s;let a,c="",d={};if(this.apiClient.isVertexAI()){let u=Oa(this.apiClient,e);return c=A("{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=Ha(f),m=new ft;return Object.assign(m,h),m})}else{let u=Va(this.apiClient,e);return c=A("{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=qa(f),m=new ft;return Object.assign(m,h),m})}}async generateContentStreamInternal(e){var t,i,o,s;let a,c="",d={};if(this.apiClient.isVertexAI()){let u=Oa(this.apiClient,e);return c=A("{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 $e(this,arguments,function*(){var m,g,b,y;try{for(var w=!0,v=ke(h),I;I=yield M(v.next()),m=I.done,!m;w=!0){y=I.value,w=!1;let C=y,T=Ha(yield M(C.json()));T.sdkHttpResponse={headers:C.headers};let x=new ft;Object.assign(x,T),yield yield M(x)}}catch(C){g={error:C}}finally{try{!w&&!m&&(b=v.return)&&(yield M(b.call(v)))}finally{if(g)throw g.error}}})})}else{let u=Va(this.apiClient,e);return c=A("{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 $e(this,arguments,function*(){var m,g,b,y;try{for(var w=!0,v=ke(h),I;I=yield M(v.next()),m=I.done,!m;w=!0){y=I.value,w=!1;let C=y,T=qa(yield M(C.json()));T.sdkHttpResponse={headers:C.headers};let x=new ft;Object.assign(x,T),yield yield M(x)}}catch(C){g={error:C}}finally{try{!w&&!m&&(b=v.return)&&(yield M(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=Uf(this.apiClient,e);return c=A("{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=Bf(f),m=new Ln;return Object.assign(m,h),m})}else{let u=Lf(this.apiClient,e);return c=A("{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=Ff(f),m=new Ln;return Object.assign(m,h),m})}}async generateImagesInternal(e){var t,i,o,s;let a,c="",d={};if(this.apiClient.isVertexAI()){let u=Qf(this.apiClient,e);return c=A("{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=jf(f),m=new Un;return Object.assign(m,h),m})}else{let u=Xf(this.apiClient,e);return c=A("{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=Zf(f),m=new Un;return Object.assign(m,h),m})}}async editImageInternal(e){var t,i;let o,s="",a={};if(this.apiClient.isVertexAI()){let c=kf(this.apiClient,e);return s=A("{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=Rf(d),f=new uo;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=Qp(this.apiClient,e);return s=A("{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=Zp(d),f=new fo;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=$p(this.apiClient,e);return s=A("{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=kp(d),f=new po;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=Fp(this.apiClient,e);return s=A("{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=Bp(d),f=new ho;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=gp(this.apiClient,e);return c=A("{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=>Ro(f))}else{let u=mp(this.apiClient,e);return c=A("{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=>ko(f))}}async listInternal(e){var t,i,o,s;let a,c="",d={};if(this.apiClient.isVertexAI()){let u=Sp(this.apiClient,e);return c=A("{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=Ap(f),m=new Fn;return Object.assign(m,h),m})}else{let u=Tp(this.apiClient,e);return c=A("{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=_p(f),m=new Fn;return Object.assign(m,h),m})}}async update(e){var t,i,o,s;let a,c="",d={};if(this.apiClient.isVertexAI()){let u=Yp(this.apiClient,e);return c=A("{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=>Ro(f))}else{let u=Jp(this.apiClient,e);return c=A("{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=>ko(f))}}async delete(e){var t,i,o,s;let a,c="",d={};if(this.apiClient.isVertexAI()){let u=Pf(this.apiClient,e);return c=A("{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=Gf(f),m=new Bn;return Object.assign(m,h),m})}else{let u=xf(this.apiClient,e);return c=A("{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=Nf(f),m=new Bn;return Object.assign(m,h),m})}}async countTokens(e){var t,i,o,s;let a,c="",d={};if(this.apiClient.isVertexAI()){let u=Sf(this.apiClient,e);return c=A("{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=Af(f),m=new Vn;return Object.assign(m,h),m})}else{let u=Tf(this.apiClient,e);return c=A("{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=_f(f),m=new Vn;return Object.assign(m,h),m})}}async computeTokens(e){var t,i;let o,s="",a={};if(this.apiClient.isVertexAI()){let c=bf(this.apiClient,e);return s=A("{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=yf(d),f=new mo;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=sp(this.apiClient,e);return c=A("{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=ip(f),m=new On;return Object.assign(m,h),m})}else{let u=op(this.apiClient,e);return c=A("{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=np(f),m=new On;return Object.assign(m,h),m})}}};var qo=class extends Re{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=jc(e);return c=A("{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=Zc(e);return c=A("{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=zc(e);return s=A("{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 Fh(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(Fh,"blobToMldev");function Bh(n){let e={},t=r(n,["parts"]);if(t!=null){let o=t;Array.isArray(o)&&(o=o.map(s=>Yh(s))),l(e,["parts"],o)}let i=r(n,["role"]);return i!=null&&l(e,["role"],i),e}p(Bh,"contentToMldev");function Vh(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"],Jh(n,c));let d=r(e,["lockAdditionalFields"]);return t!==void 0&&d!=null&&l(t,["fieldMask"],d),i}p(Vh,"createAuthTokenConfigToMldev");function Oh(n,e){let t={},i=r(e,["config"]);return i!=null&&l(t,["config"],Vh(n,i,t)),t}p(Oh,"createAuthTokenParametersToMldev");function qh(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(qh,"fileDataToMldev");function Hh(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(Hh,"functionCallToMldev");function zh(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(zh,"googleMapsToMldev");function Kh(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(Kh,"googleSearchToMldev");function Wh(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"],us(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"],Bh(pe(b)));let y=r(n,["tools"]);if(e!==void 0&&y!=null){let N=Rt(y);Array.isArray(N)&&(N=N.map(S=>Qh(kt(S)))),l(e,["setup","tools"],N)}let w=r(n,["sessionResumption"]);e!==void 0&&w!=null&&l(e,["setup","sessionResumption"],Xh(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 C=r(n,["realtimeInputConfig"]);e!==void 0&&C!=null&&l(e,["setup","realtimeInputConfig"],C);let T=r(n,["contextWindowCompression"]);e!==void 0&&T!=null&&l(e,["setup","contextWindowCompression"],T);let x=r(n,["proactivity"]);if(e!==void 0&&x!=null&&l(e,["setup","proactivity"],x),r(n,["explicitVadSignal"])!==void 0)throw new Error("explicitVadSignal parameter is not supported in Gemini API.");return t}p(Wh,"liveConnectConfigToMldev");function Jh(n,e){let t={},i=r(e,["model"]);i!=null&&l(t,["setup","model"],O(n,i));let o=r(e,["config"]);return o!=null&&l(t,["config"],Wh(o,t)),t}p(Jh,"liveConnectConstraintsToMldev");function Yh(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"],qh(s));let a=r(n,["functionCall"]);a!=null&&l(e,["functionCall"],Hh(a));let c=r(n,["functionResponse"]);c!=null&&l(e,["functionResponse"],c);let d=r(n,["inlineData"]);d!=null&&l(e,["inlineData"],Fh(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(Yh,"partToMldev");function Xh(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(Xh,"sessionResumptionConfigToMldev");function Qh(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"],zh(c));let d=r(n,["googleSearch"]);d!=null&&l(e,["googleSearch"],Kh(d));let u=r(n,["urlContext"]);return u!=null&&l(e,["urlContext"],u),e}p(Qh,"toolToMldev");function Zh(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(Zh,"getFieldMasks");function jh(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=Zh(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(jh,"convertBidiSetupToTokenSetup");var Ho=class extends Re{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=Oh(this.apiClient,e);s=A("auth_tokens",c._url),a=c._query,delete c.config,delete c._url,delete c._query;let d=jh(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 em(n,e){let t={},i=r(n,["force"]);return e!==void 0&&i!=null&&l(e,["_query","force"],i),t}p(em,"deleteDocumentConfigToMldev");function tm(n){let e={},t=r(n,["name"]);t!=null&&l(e,["_url","name"],t);let i=r(n,["config"]);return i!=null&&em(i,e),e}p(tm,"deleteDocumentParametersToMldev");function nm(n){let e={},t=r(n,["name"]);return t!=null&&l(e,["_url","name"],t),e}p(nm,"getDocumentParametersToMldev");function im(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(im,"listDocumentsConfigToMldev");function om(n){let e={},t=r(n,["parent"]);t!=null&&l(e,["_url","parent"],t);let i=r(n,["config"]);return i!=null&&im(i,e),e}p(om,"listDocumentsParametersToMldev");function sm(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(sm,"listDocumentsResponseFromMldev");var zo=class extends Re{static{p(this,"Documents")}constructor(e){super(),this.apiClient=e,this.list=async t=>new qe(Oe.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=nm(e);return s=A("{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=tm(e);o=A("{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=om(e);return s=A("{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=sm(d),f=new go;return Object.assign(f,u),f})}}};var Ko=class extends Re{static{p(this,"FileSearchStores")}constructor(e,t=new zo(e)){super(),this.apiClient=e,this.documents=t,this.list=async(i={})=>new qe(Oe.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=sh(e);return s=A("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=lh(e);return s=A("{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=ah(e);o=A("{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=hh(e);return s=A("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=mh(d),f=new bo;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=gh(e);return s=A("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=bh(d),f=new yo;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=uh(e);return s=A("{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=dh(d),f=new Eo;return Object.assign(f,u),f})}}};var Gl=p(function(){let{crypto:n}=globalThis;if(n?.randomUUID)return Gl=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"),rm=p(()=>Gl(),"uuid4");function Wo(n){return typeof n=="object"&&n!==null&&("name"in n&&n.name==="AbortError"||"message"in n&&String(n.message).includes("FetchRequestCanceledException"))}p(Wo,"isAbortError");var Jo=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 be=class extends Error{static{p(this,"GeminiNextGenAPIClientError")}},ye=class n extends be{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:Jo(t)});let s=t;return e===400?new Zn(e,s,i,o):e===401?new jn(e,s,i,o):e===403?new ei(e,s,i,o):e===404?new ti(e,s,i,o):e===409?new ni(e,s,i,o):e===422?new ii(e,s,i,o):e===429?new oi(e,s,i,o):e>=500?new si(e,s,i,o):new n(e,s,i,o)}},Wt=class extends ye{static{p(this,"APIUserAbortError")}constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}},Gt=class extends ye{static{p(this,"APIConnectionError")}constructor({message:e,cause:t}){super(void 0,void 0,e||"Connection error.",void 0),t&&(this.cause=t)}},Qn=class extends Gt{static{p(this,"APIConnectionTimeoutError")}constructor({message:e}={}){super({message:e??"Request timed out."})}},Zn=class extends ye{static{p(this,"BadRequestError")}},jn=class extends ye{static{p(this,"AuthenticationError")}},ei=class extends ye{static{p(this,"PermissionDeniedError")}},ti=class extends ye{static{p(this,"NotFoundError")}},ni=class extends ye{static{p(this,"ConflictError")}},ii=class extends ye{static{p(this,"UnprocessableEntityError")}},oi=class extends ye{static{p(this,"RateLimitError")}},si=class extends ye{static{p(this,"InternalServerError")}};var am=/^[a-z][a-z0-9+.-]*:/i,lm=p(n=>am.test(n),"isAbsoluteURL"),Yo=p(n=>(Yo=Array.isArray,Yo(n)),"isArrayInternal"),cm=Yo,dm=cm,Xa=dm;function um(n){if(!n)return!0;for(let e in n)return!1;return!0}p(um,"isEmptyObj");function fm(n,e){return Object.prototype.hasOwnProperty.call(n,e)}p(fm,"hasOwn");var pm=p((n,e)=>{if(typeof e!="number"||!Number.isInteger(e))throw new be(`${n} must be an integer`);if(e<0)throw new be(`${n} must be a positive integer`);return e},"validatePositiveInteger"),hm=p(n=>{try{return JSON.parse(n)}catch{return}},"safeJSON");var mm=p(n=>new Promise(e=>setTimeout(e,n)),"sleep$1");var At="0.0.1";function gm(){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(gm,"getDetectedPlatform");var bm=p(()=>{var n,e,t,i,o;let s=gm();if(s==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":At,"X-Stainless-OS":Za(Deno.build.os),"X-Stainless-Arch":Qa(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":At,"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":At,"X-Stainless-OS":Za((t=globalThis.process.platform)!==null&&t!==void 0?t:"unknown"),"X-Stainless-Arch":Qa((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=ym();return a?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":At,"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":At,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}},"getPlatformProperties");function ym(){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(ym,"getBrowserInfo");var Qa=p(n=>n==="x32"?"x32":n==="x86_64"||n==="x64"?"x64":n==="arm"?"arm":n==="aarch64"||n==="arm64"?"arm64":n?`other:${n}`:"unknown","normalizeArch"),Za=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"),xn,Em=p(()=>xn??(xn=bm()),"getPlatformHeaders");function wm(){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(wm,"getDefaultFetch");function $l(...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($l,"makeReadableStream");function vm(n){let e=Symbol.asyncIterator in n?n[Symbol.asyncIterator]():n[Symbol.iterator]();return $l({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(vm,"ReadableStreamFrom");function kl(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(kl,"ReadableStreamToAsyncIterable");async function Im(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(Im,"CancelReadableStream");var Cm=p(({headers:n,body:e})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(e)}),"FallbackEncoder");var Rl=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 so(n,e,t){return Rl(),new File(n,e??"unknown_file",t)}p(so,"makeFile");function Tm(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(Tm,"getName");var Sm=p(n=>n!=null&&typeof n=="object"&&typeof n[Symbol.asyncIterator]=="function","isAsyncIterable");var Dl=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"),_m=p(n=>n!=null&&typeof n=="object"&&typeof n.name=="string"&&typeof n.lastModified=="number"&&Dl(n),"isFileLike"),Am=p(n=>n!=null&&typeof n=="object"&&typeof n.url=="string"&&typeof n.blob=="function","isResponseLike");async function xm(n,e,t){if(Rl(),n=await n,_m(n))return n instanceof File?n:so([await n.arrayBuffer()],n.name);if(Am(n)){let o=await n.blob();return e||(e=new URL(n.url).pathname.split(/[\\/]/).pop()),so(await Xo(o),e,t)}let i=await Xo(n);if(e||(e=Tm(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 so(i,e,t)}p(xm,"toFile");async function Xo(n){var e,t,i,o,s;let a=[];if(typeof n=="string"||ArrayBuffer.isView(n)||n instanceof ArrayBuffer)a.push(n);else if(Dl(n))a.push(n instanceof Blob?n:await n.arrayBuffer());else if(Sm(n))try{for(var c=!0,d=ke(n),u;u=await d.next(),e=u.done,!e;c=!0){o=u.value,c=!1;let f=o;a.push(...await Xo(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}`:""}${Pm(n)}`)}return a}p(Xo,"getBytes");function Pm(n){return typeof n!="object"||n===null?"":`; props: [${Object.getOwnPropertyNames(n).map(t=>`"${t}"`).join(", ")}]`}p(Pm,"propsForError");var ri=class{static{p(this,"APIResource")}constructor(e){this._client=e}};ri._key=[];function Ml(n){return n.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}p(Ml,"encodeURIPath");var ja=Object.freeze(Object.create(null)),Nm=p((n=Ml)=>p(function(t,...i){if(t.length===1)return t[0];let o=!1,s=[],a=t.reduce((f,h,m)=>{var g,b,y;/[?#]/.test(h)&&(o=!0);let w=i[m],v=(o?encodeURIComponent:n)(""+w);return m!==i.length&&(w==null||typeof w=="object"&&w.toString===((y=Object.getPrototypeOf((b=Object.getPrototypeOf((g=w.hasOwnProperty)!==null&&g!==void 0?g:ja))!==null&&b!==void 0?b:ja))===null||y===void 0?void 0:y.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),y="^".repeat(g.length);return f=g.start+g.length,m+b+y},"");throw new be(`Path parameters result in path with invalid segments:
668
668
  ${s.map(m=>m.error).join(`
669
669
  `)}
670
670
  ${a}
671
- ${h}`)}return a},"path"),"createPathTagFunction"),_n=Em(Pl);var oi=class extends ii{static{p(this,"BaseInteractions")}create(e,t){var i;let{api_version:o=this._client.apiVersion}=e,s=Kn(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(_n`/${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(_n`/${o}/interactions/${e}`,i)}cancel(e,t={},i){let{api_version:o=this._client.apiVersion}=t??{};return this._client.post(_n`/${o}/interactions/${e}/cancel`,i)}get(e,t={},i){var o;let s=t??{},{api_version:a=this._client.apiVersion}=s,d=Kn(s,["api_version"]);return this._client.get(_n`/${a}/interactions/${e}`,Object.assign(Object.assign({query:d},i),{stream:(o=t?.stream)!==null&&o!==void 0?o:!1}))}};oi._key=Object.freeze(["interactions"]);var si=class extends oi{static{p(this,"Interactions")}};function wm(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(wm,"concatBytes");var An;function ls(n){let e;return(An??(e=new globalThis.TextEncoder,An=e.encode.bind(e)))(n)}p(ls,"encodeUTF8");var xn;function Ja(n){let e;return(xn??(e=new globalThis.TextDecoder,xn=e.decode.bind(e)))(n)}p(Ja,"decodeUTF8");var $t=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"?ls(e):e;this.buffer=wm([this.buffer,t]);let i=[],o;for(;(o=vm(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(Ja(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=Ja(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(`
671
+ ${h}`)}return a},"path"),"createPathTagFunction"),Pn=Nm(Ml);var ai=class extends ri{static{p(this,"BaseInteractions")}create(e,t){var i;let{api_version:o=this._client.apiVersion}=e,s=Yn(e,["api_version"]);if("model"in s&&"agent_config"in s)throw new be("Invalid request: specified `model` and `agent_config`. If specifying `model`, use `generation_config`.");if("agent"in s&&"generation_config"in s)throw new be("Invalid request: specified `agent` and `generation_config`. If specifying `agent`, use `agent_config`.");return this._client.post(Pn`/${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(Pn`/${o}/interactions/${e}`,i)}cancel(e,t={},i){let{api_version:o=this._client.apiVersion}=t??{};return this._client.post(Pn`/${o}/interactions/${e}/cancel`,i)}get(e,t={},i){var o;let s=t??{},{api_version:a=this._client.apiVersion}=s,c=Yn(s,["api_version"]);return this._client.get(Pn`/${a}/interactions/${e}`,Object.assign(Object.assign({query:c},i),{stream:(o=t?.stream)!==null&&o!==void 0?o:!1}))}};ai._key=Object.freeze(["interactions"]);var li=class extends ai{static{p(this,"Interactions")}};function Gm(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(Gm,"concatBytes");var Nn;function fs(n){let e;return(Nn??(e=new globalThis.TextEncoder,Nn=e.encode.bind(e)))(n)}p(fs,"encodeUTF8");var Gn;function el(n){let e;return(Gn??(e=new globalThis.TextDecoder,Gn=e.decode.bind(e)))(n)}p(el,"decodeUTF8");var $t=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"?fs(e):e;this.buffer=Gm([this.buffer,t]);let i=[],o;for(;(o=$m(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(el(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=el(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(`
672
672
  `):[]}};$t.NEWLINE_CHARS=new Set([`
673
- `,"\r"]);$t.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function vm(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(vm,"findNewlineIndex");function Im(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(Im,"findDoubleNewlineIndex");var ri={off:0,error:200,warn:300,info:400,debug:500},Wa=p((n,e,t)=>{if(n){if(tm(ri,n))return n;pe(t).warn(`${e} was set to ${JSON.stringify(n)}, expected one of ${JSON.stringify(Object.keys(ri))}`)}},"parseLogLevel");function Ht(){}p(Ht,"noop");function Pn(n,e,t){return!e||ri[n]>ri[t]?Ht:e[n].bind(e)}p(Pn,"makeLogFn");var Cm={error:Ht,warn:Ht,info:Ht,debug:Ht},Ya=new WeakMap;function pe(n){var e;let t=n.logger,i=(e=n.logLevel)!==null&&e!==void 0?e:"off";if(!t)return Cm;let o=Ya.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 Ya.set(t,[i,s]),s}p(pe,"loggerFor");var ut=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 Jo=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?pe(i):console;function a(){return $e(this,arguments,p(function*(){var c,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=ke(Tm(e,t)),y;y=yield M(b.next()),c=y.done,!c;g=!0){h=y.value,g=!1;let w=h;if(!m)if(w.data.startsWith("[DONE]")){m=!0;continue}else try{yield yield M(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&&!c&&(f=b.return)&&(yield M(f.call(b)))}finally{if(u)throw u.error}}m=!0}catch(w){if(Oo(w))return yield M(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 $e(this,arguments,p(function*(){var c,u,f,h;let m=new $t,g=_l(e);try{for(var b=!0,y=ke(g),w;w=yield M(y.next()),c=w.done,!c;b=!0){h=w.value,b=!1;let v=h;for(let I of m.decode(v))yield yield M(I)}}catch(v){u={error:v}}finally{try{!b&&!c&&(f=y.return)&&(yield M(f.call(y)))}finally{if(u)throw u.error}}for(let v of m.flush())yield yield M(v)},"iterLines_1"))}p(s,"iterLines");function a(){return $e(this,arguments,p(function*(){var c,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=ke(s()),y;y=yield M(b.next()),c=y.done,!c;g=!0){h=y.value,g=!1;let w=h;m||w&&(yield yield M(JSON.parse(w)))}}catch(w){u={error:w}}finally{try{!g&&!c&&(f=b.return)&&(yield M(f.call(b)))}finally{if(u)throw u.error}}m=!0}catch(w){if(Oo(w))return yield M(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=ls(JSON.stringify(o)+`
674
- `);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 Tm(n,e){return $e(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 d=new Wo,c=new $t,u=_l(n.body);try{for(var f=!0,h=ke(Sm(u)),m;m=yield M(h.next()),i=m.done,!i;f=!0){a=m.value,f=!1;let g=a;for(let b of c.decode(g)){let y=d.decode(b);y&&(yield yield M(y))}}}catch(g){o={error:g}}finally{try{!f&&!i&&(s=h.return)&&(yield M(s.call(h)))}finally{if(o)throw o.error}}for(let g of c.flush()){let b=d.decode(g);b&&(yield yield M(b))}},"_iterSSEMessages_1"))}p(Tm,"_iterSSEMessages");function Sm(n){return $e(this,arguments,p(function*(){var t,i,o,s;let a=new Uint8Array;try{for(var d=!0,c=ke(n),u;u=yield M(c.next()),t=u.done,!t;d=!0){s=u.value,d=!1;let f=s;if(f==null)continue;let h=f instanceof ArrayBuffer?new Uint8Array(f):typeof f=="string"?ls(f):f,m=new Uint8Array(a.length+h.length);m.set(a),m.set(h,a.length),a=m;let g;for(;(g=Im(a))!==-1;)yield yield M(a.slice(0,g)),a=a.slice(g)}}catch(f){i={error:f}}finally{try{!d&&!t&&(o=c.return)&&(yield M(o.call(c)))}finally{if(i)throw i.error}}a.length>0&&(yield yield M(a))},"iterSSEChunks_1"))}p(Sm,"iterSSEChunks");var Wo=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(`
675
- `),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]=_m(e,":");return o.startsWith(" ")&&(o=o.substring(1)),t==="event"?this.event=o:t==="data"&&this.data.push(o),null}};function _m(n,e){let t=n.indexOf(e);return t!==-1?[n.substring(0,t),e,n.substring(t+e.length)]:[n,"",""]}p(_m,"partition");async function Am(n,e){let{response:t,requestLogID:i,retryOfRequestLogID:o,startTime:s}=e,a=await(async()=>{var d;if(e.options.stream)return pe(n).debug("response",t.status,t.url,t.headers,t.body),e.options.__streamClass?e.options.__streamClass.fromSSEResponse(t,e.controller,n):Jo.fromSSEResponse(t,e.controller,n);if(t.status===204)return null;if(e.options.__binaryResponse)return t;let c=t.headers.get("content-type"),u=(d=c?.split(";")[0])===null||d===void 0?void 0:d.trim();return u?.includes("application/json")||u?.endsWith("+json")?await t.json():await t.text()})();return pe(n).debug(`[${i}] response parsed`,ut({retryOfRequestLogID:o,url:t.url,status:t.status,body:a,durationMs:Date.now()-s})),a}p(Am,"defaultParseResponse");var Yo=class n extends Promise{static{p(this,"APIPromise")}constructor(e,t,i=Am){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 Gl=Symbol("brand.privateNullableHeaders");function*xm(n){if(!n)return;if(Gl 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():Oa(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=Oa(i[1])?i[1]:[i[1]],a=!1;for(let d of s)d!==void 0&&(e&&!a&&(a=!0,yield[o,null]),yield[o,d])}}p(xm,"iterateHeaders");var no=p(n=>{let e=new Headers,t=new Set;for(let i of n){let o=new Set;for(let[s,a]of xm(i)){let d=s.toLowerCase();o.has(d)||(e.delete(s),o.add(d)),a===null?(e.delete(s),t.add(d)):(e.append(s,a),t.delete(d))}}return{[Gl]:!0,values:e,nulls:t}},"buildHeaders");var io=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 Nl,ai=class n{static{p(this,"BaseGeminiNextGenAPIClient")}constructor(e){var t,i,o,s,a,d,c,u=e===void 0?{}:e,{baseURL:f=io("GEMINI_NEXT_GEN_API_BASE_URL"),apiKey:h=(t=io("GEMINI_API_KEY"))!==null&&t!==void 0?t:null,apiVersion:m="v1beta"}=u,g=Kn(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 y="warn";this.logLevel=y,this.logLevel=(a=(s=Wa(b.logLevel,"ClientOptions.logLevel",this))!==null&&s!==void 0?s:Wa(io("GEMINI_NEXT_GEN_API_LOG"),"process.env['GEMINI_NEXT_GEN_API_LOG']",this))!==null&&a!==void 0?a:y,this.fetchOptions=b.fetchOptions,this.maxRetries=(d=b.maxRetries)!==null&&d!==void 0?d:2,this.fetch=(c=b.fetch)!==null&&c!==void 0?c:dm(),this.encoder=fm,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 no([{"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 ${At}`}defaultIdempotencyKey(){return`stainless-node-retry-${Yh()}`}makeStatusError(e,t,i,o){return be.generate(e,t,i,o)}buildURL(e,t,i){let o=!this.baseURLOverridden()&&i||this.baseURL,s=Qh(e)?new URL(e):new URL(o+(o.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),a=this.defaultQuery();return em(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 Yo(this,this.makeRequest(e,t,void 0))}async makeRequest(e,t,i){var o,s,a;let d=await e,c=(o=d.maxRetries)!==null&&o!==void 0?o:this.maxRetries;t==null&&(t=c),await this.prepareOptions(d);let{req:u,url:f,timeout:h}=await this.buildRequest(d,{retryCount:c-t});await this.prepareRequest(u,{url:f,options:d});let m="log_"+(Math.random()*(1<<24)|0).toString(16).padStart(6,"0"),g=i===void 0?"":`, retryOf: ${i}`,b=Date.now();if(pe(this).debug(`[${m}] sending request`,ut({retryOfRequestLogID:i,method:d.method,url:f,options:d,headers:u.headers})),!((s=d.signal)===null||s===void 0)&&s.aborted)throw new Kt;let y=new AbortController,w=await this.fetchWithTimeout(f,u,h,y).catch(Ho),v=Date.now();if(w instanceof globalThis.Error){let C=`retrying, ${t} attempts remaining`;if(!((a=d.signal)===null||a===void 0)&&a.aborted)throw new Kt;let T=Oo(w)||/timed? ?out/i.test(String(w)+("cause"in w?String(w.cause):""));if(t)return pe(this).info(`[${m}] connection ${T?"timed out":"failed"} - ${C}`),pe(this).debug(`[${m}] connection ${T?"timed out":"failed"} (${C})`,ut({retryOfRequestLogID:i,url:f,durationMs:v-b,message:w.message})),this.retryRequest(d,t,i??m);throw pe(this).info(`[${m}] connection ${T?"timed out":"failed"} - error; no more retries left`),pe(this).debug(`[${m}] connection ${T?"timed out":"failed"} (error; no more retries left)`,ut({retryOfRequestLogID:i,url:f,durationMs:v-b,message:w.message})),T?new Wn:new Nt({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 C=await this.shouldRetry(w);if(t&&C){let P=`retrying, ${t} attempts remaining`;return await um(w.body),pe(this).info(`${I} - ${P}`),pe(this).debug(`[${m}] response error (${P})`,ut({retryOfRequestLogID:i,url:w.url,status:w.status,headers:w.headers,durationMs:v-b})),this.retryRequest(d,t,i??m,w.headers)}let T=C?"error; no more retries left":"error; not retryable";pe(this).info(`${I} - ${T}`);let x=await w.text().catch(P=>Ho(P).message),G=im(x),S=G?void 0:x;throw pe(this).debug(`[${m}] response error (${T})`,ut({retryOfRequestLogID:i,url:w.url,status:w.status,headers:w.headers,message:S,durationMs:Date.now()-b})),this.makeStatusError(w.status,G,S,w.headers)}return pe(this).info(I),pe(this).debug(`[${m}] response start`,ut({retryOfRequestLogID:i,url:w.url,status:w.status,headers:w.headers,durationMs:v-b})),{response:w,options:d,controller:y,requestLogID:m,retryOfRequestLogID:i,startTime:b}}async fetchWithTimeout(e,t,i,o){let s=t||{},{signal:a,method:d}=s,c=Kn(s,["signal","method"]);a&&a.addEventListener("abort",()=>o.abort());let u=setTimeout(()=>o.abort(),i),f=globalThis.ReadableStream&&c.body instanceof globalThis.ReadableStream||typeof c.body=="object"&&c.body!==null&&Symbol.asyncIterator in c.body,h=Object.assign(Object.assign(Object.assign({signal:o.signal},f?{duplex:"half"}:{}),{method:"GET"}),c);d&&(h.method=d.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,d=o?.get("retry-after-ms");if(d){let u=parseFloat(d);Number.isNaN(u)||(a=u)}let c=o?.get("retry-after");if(c&&!a){let u=parseFloat(c);Number.isNaN(u)?a=Date.parse(c)-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 om(a),this.makeRequest(e,t-1,i)}calculateDefaultRetryTimeoutMillis(e,t){let s=t-e,a=Math.min(.5*Math.pow(2,s),8),d=1-Math.random()*.25;return a*d*1e3}async buildRequest(e,{retryCount:t=0}={}){var i,o,s;let a=Object.assign({},e),{method:d,path:c,query:u,defaultBaseURL:f}=a,h=this.buildURL(c,u,f);"timeout"in a&&nm("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:d,bodyHeaders:m,retryCount:t});return{req:Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({method:d,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=no([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))}:{}),lm()),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=no([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:cm(e)}:this.encoder({body:e,headers:i})}};ai.DEFAULT_TIMEOUT=6e4;var te=class extends ai{static{p(this,"GeminiNextGenAPIClient")}constructor(){super(...arguments),this.interactions=new si(this)}};Nl=te;te.GeminiNextGenAPIClient=Nl;te.GeminiNextGenAPIClientError=ge;te.APIError=be;te.APIConnectionError=Nt;te.APIConnectionTimeoutError=Wn;te.APIUserAbortError=Kt;te.NotFoundError=Zn;te.ConflictError=jn;te.RateLimitError=ti;te.BadRequestError=Yn;te.AuthenticationError=Xn;te.InternalServerError=ni;te.PermissionDeniedError=Qn;te.UnprocessableEntityError=ei;te.toFile=bm;te.Interactions=si;function Pm(n,e){let t={},i=r(n,["name"]);return i!=null&&l(t,["_url","name"],i),t}p(Pm,"cancelTuningJobParametersToMldev");function Gm(n,e){let t={},i=r(n,["name"]);return i!=null&&l(t,["_url","name"],i),t}p(Gm,"cancelTuningJobParametersToVertex");function Nm(n,e){let t={},i=r(n,["sdkHttpResponse"]);return i!=null&&l(t,["sdkHttpResponse"],i),t}p(Nm,"cancelTuningJobResponseFromMldev");function $m(n,e){let t={},i=r(n,["sdkHttpResponse"]);return i!=null&&l(t,["sdkHttpResponse"],i),t}p($m,"cancelTuningJobResponseFromVertex");function km(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 d=r(n,["batchSize"]);e!==void 0&&d!=null&&l(e,["tuningTask","hyperparameters","batchSize"],d);let c=r(n,["learningRate"]);if(e!==void 0&&c!=null&&l(e,["tuningTask","hyperparameters","learningRate"],c),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(km,"createTuningJobConfigToMldev");function Rm(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"],Xa(g))}else if(o==="PREFERENCE_TUNING"){let g=r(n,["validationDataset"]);e!==void 0&&g!=null&&l(e,["preferenceOptimizationSpec"],Xa(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 d=r(t,["config","method"]);if(d===void 0&&(d="SUPERVISED_FINE_TUNING"),d==="SUPERVISED_FINE_TUNING"){let g=r(n,["epochCount"]);e!==void 0&&g!=null&&l(e,["supervisedTuningSpec","hyperParameters","epochCount"],g)}else if(d==="PREFERENCE_TUNING"){let g=r(n,["epochCount"]);e!==void 0&&g!=null&&l(e,["preferenceOptimizationSpec","hyperParameters","epochCount"],g)}let c=r(t,["config","method"]);if(c===void 0&&(c="SUPERVISED_FINE_TUNING"),c==="SUPERVISED_FINE_TUNING"){let g=r(n,["learningRateMultiplier"]);e!==void 0&&g!=null&&l(e,["supervisedTuningSpec","hyperParameters","learningRateMultiplier"],g)}else if(c==="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(Rm,"createTuningJobConfigToVertex");function Dm(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&&Km(s);let a=r(n,["config"]);return a!=null&&km(a,t),t}p(Dm,"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&&Jm(s,t,e);let a=r(n,["config"]);return a!=null&&Rm(a,t,e),t}p(Mm,"createTuningJobParametersPrivateToVertex");function Lm(n,e){let t={},i=r(n,["name"]);return i!=null&&l(t,["_url","name"],i),t}p(Lm,"getTuningJobParametersToMldev");function Um(n,e){let t={},i=r(n,["name"]);return i!=null&&l(t,["_url","name"],i),t}p(Um,"getTuningJobParametersToVertex");function Fm(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(Fm,"listTuningJobsConfigToMldev");function Bm(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(Bm,"listTuningJobsConfigToVertex");function Vm(n,e){let t={},i=r(n,["config"]);return i!=null&&Fm(i,t),t}p(Vm,"listTuningJobsParametersToMldev");function qm(n,e){let t={},i=r(n,["config"]);return i!=null&&Bm(i,t),t}p(qm,"listTuningJobsParametersToVertex");function Om(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(d=>$l(d))),l(t,["tuningJobs"],a)}return t}p(Om,"listTuningJobsResponseFromMldev");function Hm(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(d=>Xo(d))),l(t,["tuningJobs"],a)}return t}p(Hm,"listTuningJobsResponseFromVertex");function zm(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(zm,"tunedModelFromMldev");function Km(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(Km,"tuningDatasetToMldev");function Jm(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(Jm,"tuningDatasetToVertex");function $l(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"],ol(s));let a=r(n,["createTime"]);a!=null&&l(t,["createTime"],a);let d=r(n,["tuningTask","startTime"]);d!=null&&l(t,["startTime"],d);let c=r(n,["tuningTask","completeTime"]);c!=null&&l(t,["endTime"],c);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"],zm(m)),t}p($l,"tuningJobFromMldev");function Xo(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"],ol(s));let a=r(n,["createTime"]);a!=null&&l(t,["createTime"],a);let d=r(n,["startTime"]);d!=null&&l(t,["startTime"],d);let c=r(n,["endTime"]);c!=null&&l(t,["endTime"],c);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 y=r(n,["supervisedTuningSpec"]);y!=null&&l(t,["supervisedTuningSpec"],y);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 C=r(n,["partnerModelTuningSpec"]);C!=null&&l(t,["partnerModelTuningSpec"],C);let T=r(n,["customBaseModel"]);T!=null&&l(t,["customBaseModel"],T);let x=r(n,["experiment"]);x!=null&&l(t,["experiment"],x);let G=r(n,["labels"]);G!=null&&l(t,["labels"],G);let S=r(n,["outputUri"]);S!=null&&l(t,["outputUri"],S);let N=r(n,["pipelineJob"]);N!=null&&l(t,["pipelineJob"],N);let P=r(n,["serviceAccount"]);P!=null&&l(t,["serviceAccount"],P);let $=r(n,["tunedModelDisplayName"]);$!=null&&l(t,["tunedModelDisplayName"],$);let F=r(n,["veoTuningSpec"]);return F!=null&&l(t,["veoTuningSpec"],F),t}p(Xo,"tuningJobFromVertex");function Wm(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 d=r(n,["error"]);return d!=null&&l(t,["error"],d),t}p(Wm,"tuningOperationFromMldev");function Xa(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(Xa,"tuningValidationDatasetToVertex");var Qo=class extends Re{static{p(this,"Tunings")}constructor(e){super(),this.apiClient=e,this.list=async(t={})=>new qe(Ve.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:so.JOB_STATE_QUEUED}}}}async getInternal(e){var t,i,o,s;let a,d="",c={};if(this.apiClient.isVertexAI()){let u=Um(e);return d=A("{name}",u._url),c=u._query,delete u._url,delete u._query,a=this.apiClient.request({path:d,queryParams:c,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=>Xo(f))}else{let u=Lm(e);return d=A("{name}",u._url),c=u._query,delete u._url,delete u._query,a=this.apiClient.request({path:d,queryParams:c,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=>$l(f))}}async listInternal(e){var t,i,o,s;let a,d="",c={};if(this.apiClient.isVertexAI()){let u=qm(e);return d=A("tuningJobs",u._url),c=u._query,delete u._url,delete u._query,a=this.apiClient.request({path:d,queryParams:c,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=Hm(f),m=new Bn;return Object.assign(m,h),m})}else{let u=Vm(e);return d=A("tunedModels",u._url),c=u._query,delete u._url,delete u._query,a=this.apiClient.request({path:d,queryParams:c,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=Om(f),m=new Bn;return Object.assign(m,h),m})}}async cancel(e){var t,i,o,s;let a,d="",c={};if(this.apiClient.isVertexAI()){let u=Gm(e);return d=A("{name}:cancel",u._url),c=u._query,delete u._url,delete u._query,a=this.apiClient.request({path:d,queryParams:c,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=$m(f),m=new Vn;return Object.assign(m,h),m})}else{let u=Pm(e);return d=A("{name}:cancel",u._url),c=u._query,delete u._url,delete u._query,a=this.apiClient.request({path:d,queryParams:c,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=Nm(f),m=new Vn;return Object.assign(m,h),m})}}async tuneInternal(e){var t,i;let o,s="",a={};if(this.apiClient.isVertexAI()){let d=Mm(e,e);return s=A("tuningJobs",d._url),a=d._query,delete d._url,delete d._query,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(c=>c.json().then(u=>{let f=u;return f.sdkHttpResponse={headers:c.headers},f})),o.then(c=>Xo(c))}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 d=Dm(e);return s=A("tunedModels",d._url),a=d._query,delete d._url,delete d._query,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(c=>c.json().then(u=>{let f=u;return f.sdkHttpResponse={headers:c.headers},f})),o.then(c=>Wm(c))}}};var Zo=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.")}},Ym=1024*1024*8,Xm=3,Qm=1e3,Zm=2,li="x-goog-upload-status";async function jm(n,e,t){var i;let o=await kl(n,e,t),s=await o?.json();if(((i=o?.headers)===null||i===void 0?void 0:i[li])!=="final")throw new Error("Failed to upload file: Upload status is not finalized.");return s.file}p(jm,"uploadBlob");async function eg(n,e,t){var i;let o=await kl(n,e,t),s=await o?.json();if(((i=o?.headers)===null||i===void 0?void 0:i[li])!=="final")throw new Error("Failed to upload file: Upload status is not finalized.");let a=Za(s),d=new vo;return Object.assign(d,a),d}p(eg,"uploadBlobToFileSearchStore");async function kl(n,e,t){var i,o;let s=0,a=0,d=new zt(new Response),c="upload";for(s=n.size;a<s;){let u=Math.min(Ym,s-a),f=n.slice(a,a+u);a+u>=s&&(c+=", finalize");let h=0,m=Qm;for(;h<Xm&&(d=await t.request({path:"",body:f,httpMethod:"POST",httpOptions:{apiVersion:"",baseUrl:e,headers:{"X-Goog-Upload-Command":c,"X-Goog-Upload-Offset":String(a),"Content-Length":String(u)}}}),!(!((i=d?.headers)===null||i===void 0)&&i[li]));)h++,await ng(m),m=m*Zm;if(a+=u,((o=d?.headers)===null||o===void 0?void 0:o[li])!=="active")break;if(s<=a)throw new Error("All content has been uploaded, but the upload status is not finalized.")}return d}p(kl,"uploadBlobInternal");async function tg(n){return{size:n.size,type:n.type}}p(tg,"getBlobStat");function ng(n){return new Promise(e=>setTimeout(e,n))}p(ng,"sleep");var jo=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 jm(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 eg(e,t,i)}async stat(e){if(typeof e=="string")throw new Error("File path is not supported in browser uploader.");return await tg(e)}};var es=class{static{p(this,"BrowserWebSocketFactory")}create(e,t,i){return new ts(e,t,i)}},ts=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 Qa="x-goog-api-key",ns=class{static{p(this,"WebAuth")}constructor(e){this.apiKey=e}async addAuthHeaders(e,t){if(e.get(Qa)===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(Qa,this.apiKey)}}};var ig="gl-node/",Jt=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 te({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=$d(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 ns(this.apiKey);this.apiClient=new $o({auth:o,apiVersion:this.apiVersion,apiKey:this.apiKey,vertexai:this.vertexai,httpOptions:this.httpOptions,userAgentExtra:ig+"web",uploader:new jo,downloader:new Zo}),this.models=new Uo(this.apiClient),this.live=new Mo(this.apiClient,o,new es),this.batches=new To(this.apiClient),this.chats=new _o(this.models,this.apiClient),this.caches=new So(this.apiClient),this.files=new xo(this.apiClient),this.operations=new Fo(this.apiClient),this.authTokens=new Bo(this.apiClient),this.tunings=new Qo(this.apiClient),this.fileSearchStores=new qo(this.apiClient)}};var pt=Q,Rl=new Map,Dl=[];function ht(){let n=`[${ht.name}]`;try{return pt&&console.log(`${n} starting... (I: a5cf5821b42e1c71182dd61431977e25)`),Rl}catch(e){throw console.error(`${n} ${E(e)}`),e}finally{pt&&console.log(`${n} complete.`)}}p(ht,"getAllFunctionInfos");function ds(){let n=`[${ds.name}]`;try{return pt&&console.log(`${n} starting... (I: 82c9a8fc91d8121fb843af32e76c2e25)`),Dl}catch(e){throw console.error(`${n} ${E(e)}`),e}finally{pt&&console.log(`${n} complete.`)}}p(ds,"getDeprecatedFunctionInfoNames");function og({functionInfos:n}){let e=`[${og.name}]`;try{pt&&console.log(`${e} starting... (I: 14fee8e27384a040494542182031ae25)`),n.size===0&&console.warn(`${e} empty functionInfos? (W: 97fcb8fc47689bc418893c09a16a2525)`);for(let[t,i]of n)Dl.includes(t)?pt&&console.log(`${e} functionInfo.nameOrId (${t}) is deprecated. Skipping add. (I: 3256eadf54f8087088a704798e2fd825)`):Rl.set(t,i)}catch(t){throw console.error(`${e} ${E(t)}`),t}finally{pt&&console.log(`${e} complete.`)}}p(og,"registerFunctionInfos");var ye=Q;function Wt(n){switch(n){case ee.HUMAN:return"user";case ee.AI:return"model";case ee.FUNCTION:return"user";case ee.HARDCODED:return"user";case ee.UNKNOWN:return"user";default:throw new Error(`(UNEXPECTED) src is not a valid TextSource? src: ${n} (E: 9d954fe0bc49cf4572a65b19b6173925)`)}}p(Wt,"textSourceToGeminiRole");function Ml(n){return n.api==="gemini"}p(Ml,"isPromptInfoGemini");function cs({systemPromptEntries:n}){let e=`[${cs.name}]`;try{if(ye&&console.log(`${e} starting... (I: 18693a97427939699285ef8c1a9cc425)`),n.length===0)return;n.every(i=>i.src===ee.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: ${V(t)} (I: 011e5b865c23eb0b640df3f464ac2525)`),t}catch(t){throw console.error(`${e} ${E(t)}`),t}finally{ye&&console.log(`${e} complete.`)}}p(cs,"systemPromptEntriesToSystemInstructionContent");function us({ibGib:n}){let e=`[${us.name}]`;try{if(ye&&console.log(`${e} starting... (I: 986d3edcd4f3aaf1d7eb0f8b59206b25)`),!n)return ye&&console.warn(`${e} ibGib falsy. (W: a70390e8bc3f420a92d3a84f4c78f12a)`),!1;if(!It({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(Cn)?(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} ${E(t)}`),t}finally{ye&&console.log(`${e} complete.`)}}p(us,"isFunctionCallRequestComment");function fs({functionInfoIbGib:n}){let e=`[${fs.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: ${E(t)}`),t}finally{ye&&console.log(`${e} complete.`)}}p(fs,"getFunctionCallAndResponseParts");var Yt=Q,fi="function_info",Ll="function_info";function Ul({data:n}){let e=`[${Ul.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=nt(s);if([t,i,o,a].some(c=>c.includes(" ")))throw new Error("invalid data. ib must not contain spaces (E: 36a56e4685163848458be06f51d4ad25)");return[Ll,a,t,i,o].join(" ")}p(Ul,"getFunctionInfoIb");async function pi(n){let e=`[${pi.name}]`;try{Yt&&console.log(`${e} starting... (I: f4c9f0810a4d877f676297f6e6a96825)`);let{fnRawRequest:t,api:i,model:o,agentId:s,fnName:a,fnArgs:d,fnResult:c,fnComplete:u,parseErrorMsg:f,execErrorMsg:h,repromptWithResult:m,saveInSpace:g,metaspace:b,space:y}=n,w=new Date,v={name:o,timestamp:Gs(w),timestampMs:w.getMilliseconds(),agentId:s,api:i,model:o,fnRawRequest:t,fnName:a,fnArgs:d,fnResult:c,fnComplete:u,repromptWithResult:m};f&&(v.parseErrorMsg=f),h&&(v.execErrorMsg=h);let I=Ul({data:v}),C=await Ie.firstGen({ib:I,parentIbGib:Ie.primitive({ib:Ll}),data:v,nCounter:!0,dna:!0,tjp:{uuid:!0}});if(Yt&&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(!y)throw new Error(`${e} space must be provided if saveInSpace is set to true (E: f3d5f1695a52707114117f72d932a025)`);await b.persistTransformResult({resTransform:C,space:y}),Yt&&console.log(`${e} persisted resFunctionInfo (${_({ibGib:C.newIbGib})}) to space ${y.data?.uuid} (I: aa98e877d3b34e0d2a3b7711f8f27e25)`),await b.registerNewIbGib({ibGib:C.newIbGib,space:y}),Yt&&console.log(`${e} registered new function info ibgib (${_({ibGib:C.newIbGib})}) with metaspace (I: aa98e877d3b34e0d2a3b7711f8f27e25)`)}return C}catch(t){throw console.error(`${e} ${E(t)}`),t}finally{Yt&&console.log(`${e} complete.`)}}p(pi,"createFunctionInfoIbGib");var L=Q,hi=class n extends cr{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=yt({count:32})}async validateThis(){let e=`${this.lc}[${this.validateThis.name}]`;try{L&&console.log(`${e} starting... (I: 641e211473fc54d5a9ebb4ea44944d25)`);let t=await super.validateThis();return this.data?(this.data?.subSpaceId||t.push("agent.data.subSpaceId falsy (E: d4ea57fd6b1c5cbc1e18a084de2f7725)"),this.data?.subSpaceId.match(nn)||t.push(`agent.data.subSpaceId must match regexp: ${nn}. (E: f381eff533aa3f4713316f93f7f1dc25)`),this.data.name?this.data.name.match(Tt)||t.push(`agent name must match regexp: ${Tt}`):t.push("agent name falsy (E: 1351325107e5ac5ea6b7b789b73de125)"),this.data.description&&(this.data.description.match(Hi)||t.push(`agent description must match regexp: ${Hi}`))):t.push("this.data falsy (E: f5f151e11b12cad814b37ecad7c74a25)"),t}catch(t){throw console.error(`${e} ${E(t)}`),t}finally{L&&console.log(`${e} complete.`)}}async initialize(){let e=`${this.lc}[${this.initialize.name}]`;try{L&&console.log(`${e} starting... (I: ce38519ac4bef52844a558fe31cda825)`),await super.initialize(),this._metaspace=await k();let t=new ze;if(await t.initialized,!t.contextUpdated$)throw new Error("(UNEXPECTED) ibGibProxy.contextUpdated$ falsy? (E: e8840870af18091e6e4d52490ddca825)");if(t.contextUpdated$.subscribe(Be({next:p(async i=>{let o=`${e}[ibGibProxy.contextUpdated$][next]`;L&&console.log(`${o} nextIbGib: ${V(i)} (I: 96c846357b94fda2cefa615aed88c325)`),await this.handleContextUpdated()},"next"),error:p(async i=>{debugger;console.error(`${e}[ibGibProxy.contextUpdated$][error] what up? ${E(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 L&&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} ${E(t)}`),t}finally{L&&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(_({ibGib:this})!==_({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 z(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} ${E(t)}`),t}}async getSubSpace(){let e=`[${this.getSubSpace.name}]`;try{L&&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} ${E(t)}`),t}finally{L&&console.log(`${e} complete.`)}}async getSuperSpace(){let e=`[${this.getSuperSpace.name}]`;try{L&&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} ${E(t)}`),t}finally{L&&console.log(`${e} complete.`)}}_activeContext=void 0;async setActiveContext(e){let t=`${this.lc}[${this.setActiveContext.name}]`;try{L&&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=_({ibGib:i}),a=H({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?L&&console.log(`${t} this.data.@currentContextTjpAddr already set to the same addr. (I: 9f0d58ec65eee3ca2aec528f1328c325)`):await this.mut8Self({dataToAddOrPatch:{"@currentContextTjpAddr":a}}),!this._activeContext){let d=new ze;await d.initialized;let c=`${t}[contextUpdated]`;if(!d.contextUpdated$)throw new Error("(UNEXPECTED) proxy.contextUpdated$ falsy? (E: 868c5e3bf025baa6d1ae727ab1160c25)");d.contextUpdated$.subscribe(Be({next:p(async f=>{console.log(`${c}[next] nextIbGib: ${V(f)}`)},"next"),complete:p(async()=>{debugger;throw new Error(`${c}[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(`${c}[error] ${E(f)}`)},"error")}));let u=`${t}[newContextChild]`;if(!d.newContextChild$)throw new Error("(UNEXPECTED) proxy.newContextChild$ falsy? (E: 123cf5624c3d2a6308aafc0c41f8a925)");d.newContextChild$.subscribe(Be({next:p(async f=>{if(console.log(`${u}[next] newChild: ${V(f)}`),!f.data)throw new Error("newChild.data falsy? (E: a654134a2695c176971b0cd1426ced25)");if(It({ibGib:f})){let h=this.commentIbGibs_chat.map(w=>H({ibGib:w})??_({ibGib:w})),m=H({ibGib:f})??_({ibGib:f});if(h.includes(m)){console.log(`${t} already did this comment (${m}) (I: bce18642bb9babeb553e6188d7ae2825)`);return}let{safeIbCommentMetadataText:g}=wt({ib:f.ib}),{textSrc:b}=Xt({addlMetadataText:g??"",ifError:"warn"}),y=f.data.text.startsWith("system: ");await this.addTexts({infos:[{textSrc:b??ee.UNKNOWN,commentIbGib:f,isSystem:y}]}),b===ee.HUMAN&&(y?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] ${E(f)}`)},"error")})),this._activeContext=d}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} ${E(i)}`),i}finally{L&&console.log(`${t} complete.`)}}async updateName({name:e}){let t=`${this.lc}[${this.updateName.name}]`;try{if(L&&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(Tt.test(e))await this.mut8Self({dataToAddOrPatch:{name:e}});else throw new Error(`invalid name ${e}. must match regexp: ${Tt.source} (E: 507a2bfc0aaa60bd7bb608d253239e25)`)}catch(i){throw console.error(`${t} ${E(i)}`),i}finally{L&&console.log(`${t} complete.`)}}async updateAvailableFunctions({availableFunctions:e}){let t=`${this.lc}[${this.updateAvailableFunctions.name}]`;try{L&&console.log(`${t} starting... (I: 68f1bfa343925a657f8c0545b191c725)`);let i=[];for(let o of e)if(!this.availableFunctions.has(o.nameOrId)){let s=ht().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} ${E(i)}`),i}finally{L&&console.log(`${t} complete.`)}}async mut8Self({dataToAddOrPatch:e}){let t=`${this.lc}[${this.mut8Self.name}]`;try{L&&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}=J({gib:this.gib});if(!s)throw new Error(`(UNEXPECTED) this.gib (${this.gib}) has no tjpGib? (E: 75b8dcb82b58d3b0db40b39149023e25)`);await ln({fn:p(async()=>{let a=Ue();await a.updateOrSetLatestAgent({agent:this,throwIfNewerFound:!1});let d=await $s({type:"mut8",src:this.toIbGibDto(),dataToAddOrPatch:e,dna:!0,nCounter:!0});await i.persistTransformResult({resTransform:d,space:o});let c=d.newIbGib;await this.loadIbGibDto(c),await a.updateOrSetLatestAgent({agent:this,throwIfNewerFound:!0}),await i.registerNewIbGib({ibGib:c,space:o}),await ps({newAgentIbGib:c,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} ${E(i)}`),i}finally{L&&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(L&&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 Ue().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} ${E(i)}`),i}finally{L&&console.log(`${t} complete.`)}}async doPrompt(){let e=`[${this.doPrompt.name}]`;try{if(L&&console.log(`${e} starting... (I: e7f1a7845cdf1bdce1f12d74c71a6425)`),!this.data)throw new Error("(UNEXPECTED) this.data falsy? (E: 3c528e2376a2f2600b347b2c183a5225)");let t=await this.composePromptInfo();L&&console.log(`${e} promptTextInfo: ${V(t)} (I: b769b5f2a47623a99f78210994d90525)`);let i=await this.callTextAPI(t);if(L&&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} ${E(t)}`),t}finally{L&&console.log(`${e} complete.`)}}async doPrompt_text(e){let t=`${this.lc}[${this.doPrompt_text.name}]`;try{L&&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} ${E(i)}`),i}finally{L&&console.log(`${t} complete.`)}}async doPrompt_functionCalls({functionCalls:e}){let t=`${this.lc}[${this.doPrompt_functionCalls.name}]`;try{if(L&&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 L&&console.log(`${t} no repromptWithResult. returning early. (I: 9c0113c958c7404534291f6700325925)`)}catch(i){throw console.error(`${t} ${E(i)}`),i}finally{L&&console.log(`${t} complete.`)}}async doPrompt_functionCalls_createFunctionInfoIbGibsAndExecFunctionCalls({functionCalls:e}){let t=`${this.lc}[${this.doPrompt_functionCalls_createFunctionInfoIbGibsAndExecFunctionCalls.name}]`;try{if(L&&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{L&&console.log(`${t} processing functionCall: ${s} (I: a0c0b22b3c6b6c4b674a5a9c8c8b9e25)`);let a,d,c,u,f,h="";try{if(d=JSON.parse(s),h=d?.name??"",!h)throw new Error("functionName (functionCallParsedObj.name) falsy (E: e2397d675863a12b7609495b0007a025)");if(L&&console.log(`${t} functionCallParsedObj:`,V(d),"(I: 750f097243b85644d111971e0f929c25)"),u=ht().get(d.name),!u)throw new Error(`no APIFunctionInfo found that matches functionName (${h}) (E: 9d36b6472ec5cdf95e4f498292449925)`);f=d.args,L&&console.log(`${t} valid params (I: a4d5c13c79a2405c8d20464b42083325)`)}catch(m){c=`${t} invalid functionCallParsedObj. error: ${E(m)}. functionCallStr: ${s}. (E: 1687a24c5a3667d34689a09f8f753125)`,console.error(c),d=void 0}if(u){L&&console.log(`${t} found functionInfo: ${u.nameOrId} (I: 837c7a8200689a0b2314b73057812b25)`);let m,g=!1,b;try{L&&console.log(`${t} calling function impl for ${u.nameOrId} (I: b145d08186782089c18564305f0f1125)`),m=await u.fnViaCmd(f),g=!0,L&&console.log(`${t} functionImpl complete for ${u.nameOrId}. result:`,V(m),"(I: e19d476f489261263165914750472d25)")}catch(w){b=`${t} could not call functionImpl for ${u.nameOrId}: ${E(w)} (E: 9c0e97f29a9290f9d57637b7053f0c25)`,console.error(b)}a=(await pi({api:this.data.api,model:this.data.model,agentId:this.data.uuid,fnRawRequest:s,fnName:h,fnArgs:d.args,repromptWithResult:d.args?.repromptWithResult??!1,fnResult:m,fnComplete:g,execErrorMsg:b,parseErrorMsg:void 0,saveInSpace:!0,metaspace:i,space:await this.getSuperSpace()})).newIbGib}else a=(await pi({api:this.data.api,model:this.data.model,agentId:this.data.uuid,fnRawRequest:s,fnName:h,fnArgs:d.args,repromptWithResult:d.args?.repromptWithResult??!1,fnResult:void 0,fnComplete:void 0,execErrorMsg:void 0,parseErrorMsg:c,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} ${E(a)}`),a}finally{L&&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} ${E(i)}`),i}finally{L&&console.log(`${t} complete.`)}}async doPrompt_functionCalls_addFunctionCallRequestComment({functionInfoIbGibs:e}){let t=`${this.lc}[${this.doPrompt_functionCalls_addFunctionCallRequestComment.name}]`;try{L&&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=St({tagText:Cn,contentText:e.map(f=>_({ibGib:f})).join(`
676
- `),randomIdLength:4}),a=Mt({textSrc:"ai",other:"functionCallRequest"}),d=await vt({text:s,addlMetadataText:a,saveInSpace:!0,space:o}),c=await it({type:"rel8",src:d.newIbGib,rel8nsToAddByAddr:{[fi]:e.map(f=>_({ibGib:f}))},dna:!0,nCounter:!0}),u=c.newIbGib;await i.persistTransformResult({resTransform:c,space:o}),await i.registerNewIbGib({ibGib:u,space:o}),await this.addTexts({infos:[{textSrc:"ai",commentIbGib:u}]})}catch(i){throw console.error(`${t} ${E(i)}`),i}finally{L&&console.log(`${t} complete.`)}}async doPrompt_functionCalls_getTransientDecompressionPromptForNextPrompt({functionInfoIbGibs:e}){let t=`${this.lc}[${this.doPrompt_functionCalls_getTransientDecompressionPromptForNextPrompt.name}]`;try{L&&console.log(`${t} starting... (I: c245f78f6c78a98d62375a9f14b3d625)`);let i=[];for(let o of e)try{let s=_({ibGib:o});if(!o.data)throw new Error(`(UNEXPECTED) !functionInfoIbGib.data? functionInfoAddr: ${s} (E: 7815e4854513c26b889517a9bd7e0d25)`);let{fnRawRequest:a,fnComplete:d,fnResult:c}=o.data,f=St({tagText:s,contentText:V({fnRawRequest:a,fnComplete:d,fnResult:c}),randomIdLength:void 0});i.push(f)}catch(s){console.error(`${t} could not call functionImpl: ${E(s)} (E: 2a3b8b37e146c524b67119e3a74e3d25)`)}return i.join(`
677
- `)}catch(i){throw console.error(`${t} ${E(i)}`),i}finally{L&&console.log(`${t} complete.`)}}repromptCount=0;repromptMax=12;async rePrompt(){let e=`${this.lc}[${this.rePrompt.name}]`;try{L&&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} ${E(t)}`),t}finally{L&&console.log(`${e} complete.`)}}async witness(e){if(e.ib===sn&&e.gib===rn)return this.getComments_Chat().length>0&&await this.doPrompt(),Ut;throw new Error(`arg (${V(e)}) not implemented. only expect ${Ut} right now to trigger doPrompt. (E: 24da0ad7333b6bbb359d1be425db3c25)`)}};var O=Q,We=class n extends hi{static{p(this,"AgentWitnessGemini_V1")}lc=`[${n.name}]`;async validateThis(){let e=`${this.lc}[${this.validateThis.name}]`;try{O&&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} ${E(t)}`),t}finally{O&&console.log(`${e} complete.`)}}parseAddlMetadataString({ib:e}){let t=`${this.lc}[${this.parseAddlMetadataString.name}]`;try{throw O&&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} ${E(i)}`),i}finally{O&&console.log(`${t} complete.`)}}async addTexts(e){let t=`${this.lc}[${this.addTexts.name}]`;try{let i=Ue();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=[],d=[],c=await this.getSuperSpace();for(let h of e.infos){let{textSrc:m,isSystem:g}=h,{text:b,commentIbGib:y}=h;if(b&&y)throw new Error("(UNEXPECTED) both text and commentIbGib provided? (E: a3fd590db1a5efc301f3c7e66b322f25)");if(!b&&!y)throw new Error("(UNEXPECTED) both text and commentIbGib falsy? one or the other is required (E: e08c7c694a17319085adfb75914b2725)");let w=Mt({textSrc:m});if(y)O&&console.log(`${t} adding existing commentIbGib (I: 72a3f7aafde92f65b168d27605f94625)`);else{if(O&&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)");y=(await vt({text:b,addlMetadataText:w,saveInSpace:!0,space:c})).newIbGib,await o.registerNewIbGib({ibGib:y,space:c})}if(!y)throw new Error("(UNEXPECTED) commentIbGib still falsy? we should have just created one if it didn't exist (E: 9370b19aa207234db185cd74b57be525)");let v=await bi({ibGib:y});if(v.length>0)throw new Error(`validation errors with trying to add a commentIbGib. errors: ${v} (E: beee1893050f9bcf9842c66831595225)`);s.push(y),g?a.push(y):d.push(y)}let u=[];a.length>0&&u.push({rel8nName:"system",ibGibs:a}),d.length>0&&u.push({rel8nName:"chat",ibGibs:d});let f=await ar({timeline:this.toIbGibDto(),rel8nInfos:u,timelineIndexInfo:{rel8nName:ct,type:this.data.type},metaspace:o,space:c});return await this.loadIbGibDto(f),await i.updateOrSetLatestAgent({agent:this,throwIfNewerFound:!0}),s}catch(i){throw console.error(`${t} ${E(i)}`),i}}async composePromptInfo(){let e=`${this.lc}[${this.composePromptInfo.name}]`;try{if(O&&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"]??j;if(i!==j&&t.push({src:ee.HARDCODED,content:{role:Wt(ee.HARDCODED),parts:[{text:Fl({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,d=this.commentIbGibs_chat.at(-1),c=await this.createPromptInfoEntriesFromGeminiComment({commentIbGib:d});if(c.length===1)a=c.at(0);else if(c.length===2)o.push(c.at(0)),a=c.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 O&&console.log(`${e} resPromptInfo:`,V(u),"(I: 8f17a8c45b9a91e20a5c5064d9114a25)"),u}catch(t){throw console.error(`${e} ${E(t)}`),t}finally{O&&console.log(`${e} complete.`)}}async callTextAPI(e){let t=`${this.lc}[${this.callTextAPI.name}]`;try{if(O&&console.log(`${t} starting... (I: 27885f5b14682646542e9658417b2f25)`),!Ml(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)`);O&&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 Jt({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)`),O&&(console.log(`${t} Gemini functionDeclarations:`),console.dir(a));let{systemPromptEntries:d,chatPromptHistoryParts:c,chatPromptCurrent:u}=e,f=xe(u);O&&console.log(`chatPromptCurrent_final (before decompression): ${V(f)} (I: bbd4c7b9f3225afe9da1761918d0ac25)`),O&&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 C=c.map(N=>N.content),T={model:I,history:C,config:{systemInstruction:cs({systemPromptEntries:d}),tools:[{functionDeclarations:a}],toolConfig:{functionCallingConfig:{mode:e.overrideFunctionCallingMode??kn.ANY}}}},x=this._genAI.chats.create(T),G={message:u.content.parts};return await x.sendMessage(G)},"fnGoModel"),g=0,b=o;do{g++;try{h=await m(b);break}catch(I){let C=I.message,T=I.status??"[STATUS?]";C.includes(`${503}`)?(console.error(`${t}[fnGoModel][${b}] error trying to get result from model. will try using backup model (${_t}) for this next call. error (${I.status}): ${E(I)} (E: a5cd7d174183518058da57cc6d0d8a25)`),b=_t):C.includes(`${429}`)?(console.error(`${t}[fnGoModel][${b}] error trying to get result from model. will try using backup model (${_t}) for this next call. error (${I.status}): ${E(I)} (E: a5cd7d174183518058da57cc6d0d8a25)`),b=_t):console.error(`${t}[fnGoModel][${b}] error trying to get result from model. error (${I.status}): ${E(I)} (E: a67d595c8ed313d458369d4d0b3e7f25)`)}await z(2e3)}while(!h&&g<ji);if(!h)throw new Error("couldn't get result from model (E: ede013a53f875d99a96a2e257c7e7125)");let y=h,w=[],v=y.candidates?.[0]?.content?.parts||[];for(let I of v)I.functionCall&&w.push(I.functionCall);if(!w||w.length===0){if(O&&console.warn(`${t} no function calls in response, returning text. (W: 3a4b8c940983b9e28e3f04c01a09bb25)`),!y.text)throw new Error("response generated no function calls and no response.text (E: 6123b8cacfb834105ad3160cfc4ef825)");return{text:y.text}}return O&&(console.log(`${t} Gemini function calls:`),console.dir(w)),{functionCalls:w.map(I=>JSON.stringify(I,null,2))}}catch(i){throw console.error(`${t} ${E(i)}`),i}finally{O&&console.log(`${t} complete.`)}}async createPromptInfoEntriesFromGeminiComment({commentIbGib:e}){let t=`[${this.createPromptInfoEntriesFromGeminiComment.name}]`;try{O&&console.log(`${t} starting... (I: 826a9d6b120d96532afbe1f7a22e8d25)`);let i=await bi({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}=wt({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:d,other:c}=Xt({addlMetadataText:o,ifError:"warn"});if(d)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(us({ibGib:e})){let f=await this.getFunctionInfoIbGibs({fcrCommentIbGib:e}),h=[],m=[];for(let y of f){let{call:w,response:v}=fs({functionInfoIbGib:y});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:ee.AI,content:{role:Wt("ai"),parts:h}},b={src:ee.FUNCTION,content:{role:Wt(ee.FUNCTION),parts:m}};return[g,b]}else return[{src:s,content:{role:Wt(s),parts:[{text:e.data.text}]}}]}catch(i){throw console.error(`${t} ${E(i)}`),i}finally{O&&console.log(`${t} complete.`)}}async promptOneOff(e){let t=`${this.lc}[${this.promptOneOff.name}]`;try{O&&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)`);O&&console.log(`${t} calling gemini api with model: ${a} (I: genuuid)`);let d=await this.fnGetAPIKey();if(!d){console.error(`${t} apiKey falsy. did you set this.fnGetAPIKey (E: genuuid)`);return}this._genAI??=new Jt({apiKey:d});let c=p(async b=>{if(!this._genAI)throw new Error("(UNEXPECTED) this._genAI falsy? (E: fbe235713d48f0d8e87cd0b88ec54825)");let y={model:b,config:{systemInstruction:o}},v=await this._genAI.chats.create(y).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(_t);let m=0,g=1;do{f++,g++;let b=h[m];try{u=await c(b);break}catch(y){if(y instanceof Error){let w=y.message,v=y.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}): ${E(y)} (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}): ${E(y)} (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}): ${E(y)} (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}): ${E(y)} (E: a9869883fc72bf156f1691183e27ee25)`)}else console.error(`${t}[fnGoModel][${b}] error trying to get result from model. error (${v}): ${E(y)} (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 z(g*1e3)}while(!u&&f<ji);return u}catch(i){throw console.error(`${t} ${E(i)}`),i}finally{O&&console.log(`${t} complete.`)}}async getFunctionInfoIbGibs({fcrCommentIbGib:e}){let t=`[${this.getFunctionInfoIbGibs.name}]`;try{O&&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?.[fi]??[];if(a.length===0)return O&&console.warn(`${t} no functionInfoAddrs (I: 5f8965e92c305689c11677a1148b7425)`),[];O&&console.log(`${t} functionInfoAddrs: ${a} (I: e7b1f5a4576c493326b913e48a505e25)`);let d=await o.get({addrs:a,space:s});if(!d.success||!d.ibGibs||d.ibGibs.length!==a.length)throw new Error(`${t} could not retrieve function info ibgibs. errorMsg: ${d.errorMsg??"unknown error (E: 164246a6661d49f2b21d1b6769139625)"} (E: 0736d824876e420f91c089925191d425)`);return i=d.ibGibs,O&&console.log(`${t} resFunctionInfoIbGibs: ${V(i.map(c=>_({ibGib:c})))} (I: a5661b5c449608f0e8d773135a599a25)`),i}catch(i){throw console.error(`${t} ${E(i)}`),i}finally{O&&console.log(`${t} complete.`)}}async loadIbGibDto(e){let t=`[${this.loadIbGibDto.name}]`;try{if(O&&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 c of this.data.availableFunctionNameOrIds){if(!c)throw new Error("(UNEXPECTED) nameOrId falsy, driven by this.data.availableFunctionNameOrIds? somehow a falsy nameOrId saved? (E: 7b63f177624de2415e1569e96ef8d125)");let u=ht().get(c);u?this.availableFunctions.set(c,u):ds().includes(c)?O&&console.log(`${t} function nameOrId (${c}) found as deprecated. not adding to available functions on agent. (I: 983864ad5cd8af915fb135580e455425)`):console.error(`no function info in getAllFunctionInfos() found corresponding to nameOrId (${c}) 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 c=await i.get({addrs:a,space:o});if(!c.success||c.errorMsg)throw new Error(`couldn't get system comments. error: ${E(c.errorMsg??"unknown error (E: c0b4d7aab724bcf58e88ffd496de8825)")} (E: 7925d4b5ec3a8f7a648c109941c38a25)`);if((c.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=c.ibGibs}let d=this.rel8ns?.chat??[];if(d.length>0){let c=await i.get({addrs:d,space:o});if(!c.success||c.errorMsg)throw new Error(`couldn't get chat comments. error: ${E(c.errorMsg??"unknown error (E: c0b4d7aab724bcf58e88ffd496de8825)")} (E: 7925d4b5ec3a8f7a648c109941c38a25)`);if((c.ibGibs??[]).length!==d.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=c.ibGibs}},"fn");await ln({scope:"prune",secondsValid:60,maxDelayMs:100,maxLockAttempts:1800,space:o,callerInstanceId:nt(),fn:s})}catch(i){throw console.error(`${t} ${E(i)}`),i}finally{O&&console.log(`${t} complete.`)}}};setTimeout(()=>{Ue().registerFactory({classname:We.name,fnDtoToAgentWitness:p(async e=>e.data?e.data.classname?e.data.classname===We.name?{applies:!0,agent:await hs({agentIbGib:e})}:{applies:!1}:{applies:!1}:{applies:!1},"fnDtoToAgentWitness")})});function Fl({currentContextTjpAddr:n}){let e=`[${Fl.name}]`;try{O&&console.log(`${e} starting... (I: 7edafbba277d57eae51af325cf7eb225)`);let t=J({ibGibAddr:n});return`Your current context ibGibAddr is ${n}
678
- 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} ${E(t)}`),t}finally{O&&console.log(`${e} complete.`)}}p(Fl,"getTextPartForCurrentContextTjpAddr");var Ye=Q,yi=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{Ye&&console.log(`${t} starting... (I: f4c8ac488804666077cfc2237972d625)`);let{name:i,api:o,model:s,type:a,availableFunctions:d}=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 c=xe(Pr);return i&&(c.name=i),c.uuid=await on(),c.superSpaceId=e.data.uuid,c.api=o,c.model=s,c.type=a,c.availableFunctionNameOrIds=d.map(u=>u.nameOrId),c.classname=We.name,c}catch(i){throw console.error(`${t} ${E(i)}`),i}finally{Ye&&console.log(`${t} complete.`)}}async createInitialRel8ns(){let e=`${this.lc}[${this.createInitialRel8ns.name}]`;try{return Ye&&console.log(`${e} starting... (I: 2d4933ea3761bd7df701d8d306fb2825)`),eo?xe(eo):void 0}catch(t){throw console.error(`${e} ${E(t)}`),t}finally{Ye&&console.log(`${e} complete.`)}}async createWitness(){let e=`[${this.createWitness.name}]`;try{Ye&&console.log(`${e} starting... (I: 36709dfa0c398d63d64c4f6ba9055625)`);let{api:t,model:i}=this.arg;if(t==="gemini"){let o=new We;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} ${E(t)}`),t}finally{Ye&&console.log(`${e} complete.`)}}};async function hs({agentIbGib:n}){let e=`[${hs.name}]`;try{Ye&&console.log(`${e} starting... (I: 5a4efefba9e4bdfb942afbe7919fff25)`);let t=new We;return await t.initialized,await t.loadIbGibDto(n),t.fnGetAPIKey=async()=>await wn({dbName:or(),storeName:await ir(),key:await sr()})??"",t}catch(t){throw console.error(`${e} ${E(t)}`),t}finally{Ye&&console.log(`${e} complete.`)}}p(hs,"agentIbGibDtoToWitness");var ne=Q;async function Yi({metaspace:n,space:e,createIfNone:t}){let i=`[${Yi.name}]`;try{if(ne&&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 Js({metaspace:n,space:e});if(!o.rel8ns)throw new Error("(UNEXPECTED) tagsIbGib.rel8ns falsy? (E: dc50e8d218fe5e30bbaec7f37d484525)");let a=(o.rel8ns[ks]??[]).filter(u=>{let{ib:f}=B({ibGibAddr:u});return f===Vs}),d,c;if(a.length===0){if(t){ne&&console.log(`${i} creating new agents tag... (I: 47f4f4fa89f1a1bba960e0a6ff5f5225)`);let{newTagIbGib:u}=await n.createTagIbGib({text:Us,icon:Fs,description:Bs,space:e});return c=u,ne&&console.log(`${i} creating new agents tag complete. (I: 5f41d644f2b692348377f918057cf225)`),u}}else a.length===1?(d=a.at(0),ne&&console.log(`${i} exactly one agent tag addr found (${d}) in space (${e.ib}) (I: 7ef995963313c966216097760d0cdb25)`)):(d=a.at(0),console.error(`${i} more than one agent tag found in space (${e.ib})? Well, we're returning just the first one (${d}), but really we've not coded for this edge/future case. (E: 52a4e2e49d3c0d644df483119b46f125)`));if(d){let u=await n.get({addrs:[d],space:e});if(u.success&&u.ibGibs?.length===1)return c=u.ibGibs.at(0),c;throw new Error(`couldn't get agentTagAddr (${d}) 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} ${E(o)}`),o}finally{ne&&console.log(`${i} complete.`)}}p(Yi,"getTag_Agents");async function Tn({metaspace:n,type:e,spaceId:t,space:i}){let o=`[${Tn.name}]`;try{if(ne&&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:ct,type:e,space:i})??[],d=[];for(let c of a){if(c.data?.api!=="gemini")throw new Error("(UNEXPECTED) agentIbGib.data.api !== gemini? only gemini is implemented right now. (E: 7348fe8c68565bcf88a4052458f42d25)");let u=Ue(),f=await u.getLatestAgent({id:c.data.uuid});if(!f){if(f=await u.getAgentWitnessFromDto({dto:c}),!f){debugger;throw new Error(`(UNEXPECTED) couldn't get actual agent witness from agent dto? have we registered classname (${c.data?.classname}) and factory fn with agents service? (E: bcbfdf6446793ac34d6f6118e050d325)`)}await u.updateOrSetLatestAgent({agent:f,throwIfNewerFound:!1})}d.push(f)}return d}catch(s){throw console.error(`${o} ${E(s)}`),s}finally{ne&&console.log(`${o} complete.`)}}p(Tn,"getAgents");async function ps({metaspace:n,type:e,space:t,newAgentIbGib:i}){await p(async()=>{let s=`[${ps.name}]`;try{if(ne&&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 d=await Ue().getLatestAgent({id:i.data.uuid});if(d&&d.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 c=_({ibGib:i});await se({type:i.data.type,rel8nInfos:[{rel8nName:ct,ibGibs:[W({ibGib:i})]}],metaspace:n,space:t})}catch(a){throw console.error(`${s} ${E(a)}`),a}finally{ne&&console.log(`${s} complete.`)}},"fn")()}p(ps,"updateAgentIndex");async function ms({ibGib:n,metaspace:e,space:t}){let i=`[${ms.name}]`;try{if(ne&&console.log(`${i} starting...`),!n)throw new Error("ibGib required (E: 753a0aa13e4e5ea20d7f6bb92d963625)");let o=await dn({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=H({ibGib:n,defaultIfNone:"incomingAddr"}),a=_({ibGib:o}),c=await Ue().getAgentByAddr({agentAddr:a,metaspace:e,spaceId:t.data.uuid});return ne&&console.log(c?`${i} complete. Found agent ${_({ibGib:c})} for domain ${s}`:`${i} complete. No agent found for ibgib tjp ${s}`),c}catch(o){throw console.error(`${i} ${E(o)}`),o}}p(ms,"getAgentForDomainIbGib");function Xi(n){let e=`[${Xi.name}]`;try{ne&&console.log(`${e} starting... (I: 2a9899514ac6e478eb55819a57fd9725)`);let{api:t}=n;switch(t){case"gemini":return new yi(n);default:throw new Error(`(UNEXPECTED) api: ${t}? only 'gemini' currently implemented? (E: 071fedab181fda80666858c14ea73625)`)}}catch(t){throw console.error(`${e} ${E(t)}`),t}finally{ne&&console.log(`${e} complete.`)}}p(Xi,"getConcreteAgentFactory");function St({tagText:n,contentText:e,randomIdLength:t}){let i=`[${St.name}]`;try{ne&&console.log(`${i} starting... (I: 94104ec059c89d4ba458d96580791d25)`);let o=t?`${n}|${yt({count:t})}`:n;return[`[${o} begin]`,e,`[${o} end]`].join(`
679
- `)}catch(o){throw console.error(`${i} ${E(o)}`),o}finally{ne&&console.log(`${i} complete.`)}}p(St,"taggifyForPrompt");function Mt({textSrc:n,other:e}){let t=`[${Mt.name}]`;return e?[n,nt(),e].join("_"):[n,nt()].join("_")}p(Mt,"getAddlMetadataTextForAgentText");function Xt({addlMetadataText:n,ifError:e="warn"}){let t=`[${Mt.name}]`;try{ne&&console.log(`${t} starting... (I: 89b8b19a8d785b945fe0f816df762d25)`);let[i,o,...s]=n.split("_");if(!i)throw new Error("addlMetadataText.textSrc falsy (E: 40bbec4269c1688ab1390fa5d5440325)");if(!Tr(i))throw new Error(`addlMetadataText.textSrc (${i}) is unexpected value. Expected one of ${zi} (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} ${E(i)}`;switch(e){case"ignore":return{textSrc:ee.UNKNOWN,timestampInTicks:0,errorMsg:E(i)};case"warn":return console.warn(`${t} ${o} (W: 3e1f4a98ad6461c9bd96462841c31b25)`),{textSrc:ee.UNKNOWN,timestampInTicks:0,errorMsg:E(i)};default:throw console.error(`${t} ${o} (E: 6396ed44947c52adf85788e1adc22825)`),new Error(o)}}finally{ne&&console.log(`${t} complete.`)}}p(Xt,"parseAddlMetadataTextForAgentText");function Qi({data:n}){let e=`[${Qi.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[Ct,t,i,o].join(" ")}p(Qi,"getAgentIb");function Ar({ib:n}){let[e,t,i,o]=n.split(" ");if(e!==Ct)throw new Error(`invalid ib. first term expected to e an atom: ${Ct} (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 bi({ibGib:n}){let e=`[${bi.name}]`;try{ne&&console.log(`${e} starting... (I: f9a733a5a05b7f7494836d86a79e2d25)`);let t=await an({ibGib:n})??[];if(!It({ibGib:n}))return t.push(`${e} not a comment ibgib (E: 08676d94c698c6e42e6c35e94a58f125)`),t;let{safeIbCommentMetadataText:i}=wt({ib:n.ib});if(i){let o=Xt({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} ${E(t)}`),t}finally{ne&&console.log(`${e} complete.`)}}p(bi,"validateAgentWitnessCommentIbGib");var Ei="settings",sg="general",rg="text-editor",ag="projects",lg="projects-explorer",dg="projects-dropdown",cg="project",ug="minigame",fg="chronologys",pg="identity-manager",ae={general:sg,textEditor:rg,projects:ag,projectsExplorer:lg,projectsDropdown:dg,project:cg,minigame:ug,chronologys:fg,identityManager:pg},hg=Object.values(ae);var gs={type:ae.general,editor:void 0,readonly:!0,viewer:"ibgib-raw-viewer"},bs={type:ae.textEditor,wrap:"wrap"},mg={type:ae.project,openChildTjpAddrs:[],activeChildTjpAddr:void 0,lensMode:"raw"},gg={type:ae.minigame},bg={type:ae.chronologys,openChildTjpAddrs:[],activeChildTjpAddr:void 0},yg={type:ae.identityManager,openChildTjpAddrs:[],activeChildTjpAddr:void 0},Bl={sections:{},children:{}};var Xe=Q;async function ys({ibGib:n}){let e=`[${ys.name}]`;try{Xe&&console.log(`${e} starting... (I: 57ac4c0a3448bc5e98ecf5bfb02ce825)`);let{ib:t}=B({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`${Ei}_${i}`}catch(t){throw console.error(`${e} ${E(t)}`),t}finally{Xe&&console.log(`${e} complete.`)}}p(ys,"getSettingsScope");async function Te({settingsType:n,useCase:e}){let t=`[${Te.name}]`;try{if(Xe&&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} ${E(i)}`),i}finally{Xe&&console.log(`${t} complete.`)}}p(Te,"getSectionName");async function wi({sectionName:n,settingsIbGib:e}){let t=`[${wi.name}]`;try{if(Xe&&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} ${E(i)}`),i}finally{Xe&&console.log(`${t} complete.`)}}p(wi,"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,"__")),`${Ei} ${n}`}catch(t){throw console.error(`${e} ${E(t)}`),t}}p(Vl,"getSettingsIb");async function Es({scope:n,metaspace:e,space:t,saveInSpace:i}){let o=`[${Es.name}]`;try{let s=Vl({scope:n}),a=await ql(),c=await Ie.firstGen({parentIbGib:Ie.primitive({ib:Ei}),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:c,space:t}),await e.registerNewIbGib({ibGib:c.newIbGib,space:t})}return c}catch(s){throw console.error(`${o} ${E(s)}`),s}}p(Es,"createSettings");async function ql(){let n=`[${ql.name}]`;try{Xe&&console.log(`${n} starting... (I: 3d7cc3f242cc88ad28dafaf85d646a25)`);let e=xe(Bl),t=await Te({settingsType:"general",useCase:"default"}),i=await Te({settingsType:"general",useCase:"current"});e.sections[t]=xe(gs),e.sections[i]=xe(gs);let o=await Te({settingsType:"text-editor",useCase:"default"}),s=await Te({settingsType:"text-editor",useCase:"current"});return e.sections[o]=xe(bs),e.sections[s]=xe(bs),e}catch(e){throw console.error(`${n} ${E(e)}`),e}finally{Xe&&console.log(`${n} complete.`)}}p(ql,"getDefaultSettingsData");var R=Q,fe=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}},Qe=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}=B({ibGibAddr:this.ibGibAddr??j});return e}get gib(){let{gib:e}=B({ibGibAddr:this.ibGibAddr??j});return e}ibGibAddr=j;ibGibProxy;get ibGib(){let e=this.ibGibAddr??j,{ib:t,gib:i}=B({ibGibAddr:e});return this.ibGibAddr&&!Ft({gib:i})?this.ibGibProxy?.ibGib:Ie.primitive({ib:t})}get tjpAddr(){return this.ibGib?H({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(Bt,{detail:{isBusy:e,title:t,msg:i,animationEmoji:s},bubbles:!0,composed:!0})):window.dispatchEvent(new CustomEvent(Bt,{detail:{isBusy:e,title:t,msg:i,animationEmoji:s}}))}catch(d){throw console.error(`${a} ${E(d)}`),d}}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} ${E(t)}`),t}finally{R&&console.log(`${e} complete.`)}}constructor(){super(),this._instanceId=yt({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(d){throw console.error(`${a} ${E(d)}`),d}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} ${E(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?`
673
+ `,"\r"]);$t.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function $m(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($m,"findNewlineIndex");function km(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(km,"findDoubleNewlineIndex");var ci={off:0,error:200,warn:300,info:400,debug:500},tl=p((n,e,t)=>{if(n){if(fm(ci,n))return n;me(t).warn(`${e} was set to ${JSON.stringify(n)}, expected one of ${JSON.stringify(Object.keys(ci))}`)}},"parseLogLevel");function zt(){}p(zt,"noop");function $n(n,e,t){return!e||ci[n]>ci[t]?zt:e[n].bind(e)}p($n,"makeLogFn");var Rm={error:zt,warn:zt,info:zt,debug:zt},nl=new WeakMap;function me(n){var e;let t=n.logger,i=(e=n.logLevel)!==null&&e!==void 0?e:"off";if(!t)return Rm;let o=nl.get(t);if(o&&o[0]===i)return o[1];let s={error:$n("error",t,i),warn:$n("warn",t,i),info:$n("info",t,i),debug:$n("debug",t,i)};return nl.set(t,[i,s]),s}p(me,"loggerFor");var ut=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 Qo=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?me(i):console;function a(){return $e(this,arguments,p(function*(){var d,u,f,h;if(o)throw new be("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");o=!0;let m=!1;try{try{for(var g=!0,b=ke(Dm(e,t)),y;y=yield M(b.next()),d=y.done,!d;g=!0){h=y.value,g=!1;let w=h;if(!m)if(w.data.startsWith("[DONE]")){m=!0;continue}else try{yield yield M(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 M(f.call(b)))}finally{if(u)throw u.error}}m=!0}catch(w){if(Wo(w))return yield M(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 $e(this,arguments,p(function*(){var d,u,f,h;let m=new $t,g=kl(e);try{for(var b=!0,y=ke(g),w;w=yield M(y.next()),d=w.done,!d;b=!0){h=w.value,b=!1;let v=h;for(let I of m.decode(v))yield yield M(I)}}catch(v){u={error:v}}finally{try{!b&&!d&&(f=y.return)&&(yield M(f.call(y)))}finally{if(u)throw u.error}}for(let v of m.flush())yield yield M(v)},"iterLines_1"))}p(s,"iterLines");function a(){return $e(this,arguments,p(function*(){var d,u,f,h;if(o)throw new be("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");o=!0;let m=!1;try{try{for(var g=!0,b=ke(s()),y;y=yield M(b.next()),d=y.done,!d;g=!0){h=y.value,g=!1;let w=h;m||w&&(yield yield M(JSON.parse(w)))}}catch(w){u={error:w}}finally{try{!g&&!d&&(f=b.return)&&(yield M(f.call(b)))}finally{if(u)throw u.error}}m=!0}catch(w){if(Wo(w))return yield M(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 $l({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=fs(JSON.stringify(o)+`
674
+ `);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 Dm(n,e){return $e(this,arguments,p(function*(){var i,o,s,a;if(!n.body)throw e.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative"?new be("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 be("Attempted to iterate over a response with no body");let c=new Zo,d=new $t,u=kl(n.body);try{for(var f=!0,h=ke(Mm(u)),m;m=yield M(h.next()),i=m.done,!i;f=!0){a=m.value,f=!1;let g=a;for(let b of d.decode(g)){let y=c.decode(b);y&&(yield yield M(y))}}}catch(g){o={error:g}}finally{try{!f&&!i&&(s=h.return)&&(yield M(s.call(h)))}finally{if(o)throw o.error}}for(let g of d.flush()){let b=c.decode(g);b&&(yield yield M(b))}},"_iterSSEMessages_1"))}p(Dm,"_iterSSEMessages");function Mm(n){return $e(this,arguments,p(function*(){var t,i,o,s;let a=new Uint8Array;try{for(var c=!0,d=ke(n),u;u=yield M(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"?fs(f):f,m=new Uint8Array(a.length+h.length);m.set(a),m.set(h,a.length),a=m;let g;for(;(g=km(a))!==-1;)yield yield M(a.slice(0,g)),a=a.slice(g)}}catch(f){i={error:f}}finally{try{!c&&!t&&(o=d.return)&&(yield M(o.call(d)))}finally{if(i)throw i.error}}a.length>0&&(yield yield M(a))},"iterSSEChunks_1"))}p(Mm,"iterSSEChunks");var Zo=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(`
675
+ `),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]=Lm(e,":");return o.startsWith(" ")&&(o=o.substring(1)),t==="event"?this.event=o:t==="data"&&this.data.push(o),null}};function Lm(n,e){let t=n.indexOf(e);return t!==-1?[n.substring(0,t),e,n.substring(t+e.length)]:[n,"",""]}p(Lm,"partition");async function Um(n,e){let{response:t,requestLogID:i,retryOfRequestLogID:o,startTime:s}=e,a=await(async()=>{var c;if(e.options.stream)return me(n).debug("response",t.status,t.url,t.headers,t.body),e.options.__streamClass?e.options.__streamClass.fromSSEResponse(t,e.controller,n):Qo.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 me(n).debug(`[${i}] response parsed`,ut({retryOfRequestLogID:o,url:t.url,status:t.status,body:a,durationMs:Date.now()-s})),a}p(Um,"defaultParseResponse");var jo=class n extends Promise{static{p(this,"APIPromise")}constructor(e,t,i=Um){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 Ll=Symbol("brand.privateNullableHeaders");function*Fm(n){if(!n)return;if(Ll 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():Xa(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=Xa(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(Fm,"iterateHeaders");var ro=p(n=>{let e=new Headers,t=new Set;for(let i of n){let o=new Set;for(let[s,a]of Fm(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{[Ll]:!0,values:e,nulls:t}},"buildHeaders");var ao=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,di=class n{static{p(this,"BaseGeminiNextGenAPIClient")}constructor(e){var t,i,o,s,a,c,d,u=e===void 0?{}:e,{baseURL:f=ao("GEMINI_NEXT_GEN_API_BASE_URL"),apiKey:h=(t=ao("GEMINI_API_KEY"))!==null&&t!==void 0?t:null,apiVersion:m="v1beta"}=u,g=Yn(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 y="warn";this.logLevel=y,this.logLevel=(a=(s=tl(b.logLevel,"ClientOptions.logLevel",this))!==null&&s!==void 0?s:tl(ao("GEMINI_NEXT_GEN_API_LOG"),"process.env['GEMINI_NEXT_GEN_API_LOG']",this))!==null&&a!==void 0?a:y,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:wm(),this.encoder=Cm,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 ro([{"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 be(`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 ${At}`}defaultIdempotencyKey(){return`stainless-node-retry-${rm()}`}makeStatusError(e,t,i,o){return ye.generate(e,t,i,o)}buildURL(e,t,i){let o=!this.baseURLOverridden()&&i||this.baseURL,s=lm(e)?new URL(e):new URL(o+(o.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),a=this.defaultQuery();return um(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 jo(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(me(this).debug(`[${m}] sending request`,ut({retryOfRequestLogID:i,method:c.method,url:f,options:c,headers:u.headers})),!((s=c.signal)===null||s===void 0)&&s.aborted)throw new Wt;let y=new AbortController,w=await this.fetchWithTimeout(f,u,h,y).catch(Jo),v=Date.now();if(w instanceof globalThis.Error){let C=`retrying, ${t} attempts remaining`;if(!((a=c.signal)===null||a===void 0)&&a.aborted)throw new Wt;let T=Wo(w)||/timed? ?out/i.test(String(w)+("cause"in w?String(w.cause):""));if(t)return me(this).info(`[${m}] connection ${T?"timed out":"failed"} - ${C}`),me(this).debug(`[${m}] connection ${T?"timed out":"failed"} (${C})`,ut({retryOfRequestLogID:i,url:f,durationMs:v-b,message:w.message})),this.retryRequest(c,t,i??m);throw me(this).info(`[${m}] connection ${T?"timed out":"failed"} - error; no more retries left`),me(this).debug(`[${m}] connection ${T?"timed out":"failed"} (error; no more retries left)`,ut({retryOfRequestLogID:i,url:f,durationMs:v-b,message:w.message})),T?new Qn: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 C=await this.shouldRetry(w);if(t&&C){let P=`retrying, ${t} attempts remaining`;return await Im(w.body),me(this).info(`${I} - ${P}`),me(this).debug(`[${m}] response error (${P})`,ut({retryOfRequestLogID:i,url:w.url,status:w.status,headers:w.headers,durationMs:v-b})),this.retryRequest(c,t,i??m,w.headers)}let T=C?"error; no more retries left":"error; not retryable";me(this).info(`${I} - ${T}`);let x=await w.text().catch(P=>Jo(P).message),N=hm(x),S=N?void 0:x;throw me(this).debug(`[${m}] response error (${T})`,ut({retryOfRequestLogID:i,url:w.url,status:w.status,headers:w.headers,message:S,durationMs:Date.now()-b})),this.makeStatusError(w.status,N,S,w.headers)}return me(this).info(I),me(this).debug(`[${m}] response start`,ut({retryOfRequestLogID:i,url:w.url,status:w.status,headers:w.headers,durationMs:v-b})),{response:w,options:c,controller:y,requestLogID:m,retryOfRequestLogID:i,startTime:b}}async fetchWithTimeout(e,t,i,o){let s=t||{},{signal:a,method:c}=s,d=Yn(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 mm(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&&pm("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=ro([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))}:{}),Em()),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=ro([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:vm(e)}:this.encoder({body:e,headers:i})}};di.DEFAULT_TIMEOUT=6e4;var te=class extends di{static{p(this,"GeminiNextGenAPIClient")}constructor(){super(...arguments),this.interactions=new li(this)}};Ul=te;te.GeminiNextGenAPIClient=Ul;te.GeminiNextGenAPIClientError=be;te.APIError=ye;te.APIConnectionError=Gt;te.APIConnectionTimeoutError=Qn;te.APIUserAbortError=Wt;te.NotFoundError=ti;te.ConflictError=ni;te.RateLimitError=oi;te.BadRequestError=Zn;te.AuthenticationError=jn;te.InternalServerError=si;te.PermissionDeniedError=ei;te.UnprocessableEntityError=ii;te.toFile=xm;te.Interactions=li;function Bm(n,e){let t={},i=r(n,["name"]);return i!=null&&l(t,["_url","name"],i),t}p(Bm,"cancelTuningJobParametersToMldev");function Vm(n,e){let t={},i=r(n,["name"]);return i!=null&&l(t,["_url","name"],i),t}p(Vm,"cancelTuningJobParametersToVertex");function Om(n,e){let t={},i=r(n,["sdkHttpResponse"]);return i!=null&&l(t,["sdkHttpResponse"],i),t}p(Om,"cancelTuningJobResponseFromMldev");function qm(n,e){let t={},i=r(n,["sdkHttpResponse"]);return i!=null&&l(t,["sdkHttpResponse"],i),t}p(qm,"cancelTuningJobResponseFromVertex");function Hm(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(Hm,"createTuningJobConfigToMldev");function zm(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"],il(g))}else if(o==="PREFERENCE_TUNING"){let g=r(n,["validationDataset"]);e!==void 0&&g!=null&&l(e,["preferenceOptimizationSpec"],il(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(zm,"createTuningJobConfigToVertex");function Km(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&&ig(s);let a=r(n,["config"]);return a!=null&&Hm(a,t),t}p(Km,"createTuningJobParametersPrivateToMldev");function Wm(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&&og(s,t,e);let a=r(n,["config"]);return a!=null&&zm(a,t,e),t}p(Wm,"createTuningJobParametersPrivateToVertex");function Jm(n,e){let t={},i=r(n,["name"]);return i!=null&&l(t,["_url","name"],i),t}p(Jm,"getTuningJobParametersToMldev");function Ym(n,e){let t={},i=r(n,["name"]);return i!=null&&l(t,["_url","name"],i),t}p(Ym,"getTuningJobParametersToVertex");function Xm(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(Xm,"listTuningJobsConfigToMldev");function Qm(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(Qm,"listTuningJobsConfigToVertex");function Zm(n,e){let t={},i=r(n,["config"]);return i!=null&&Xm(i,t),t}p(Zm,"listTuningJobsParametersToMldev");function jm(n,e){let t={},i=r(n,["config"]);return i!=null&&Qm(i,t),t}p(jm,"listTuningJobsParametersToVertex");function eg(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(eg,"listTuningJobsResponseFromMldev");function tg(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=>es(c))),l(t,["tuningJobs"],a)}return t}p(tg,"listTuningJobsResponseFromVertex");function ng(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(ng,"tunedModelFromMldev");function ig(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(ig,"tuningDatasetToMldev");function og(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(og,"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"],ul(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"],ng(m)),t}p(Fl,"tuningJobFromMldev");function es(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"],ul(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 y=r(n,["supervisedTuningSpec"]);y!=null&&l(t,["supervisedTuningSpec"],y);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 C=r(n,["partnerModelTuningSpec"]);C!=null&&l(t,["partnerModelTuningSpec"],C);let T=r(n,["customBaseModel"]);T!=null&&l(t,["customBaseModel"],T);let x=r(n,["experiment"]);x!=null&&l(t,["experiment"],x);let N=r(n,["labels"]);N!=null&&l(t,["labels"],N);let S=r(n,["outputUri"]);S!=null&&l(t,["outputUri"],S);let G=r(n,["pipelineJob"]);G!=null&&l(t,["pipelineJob"],G);let P=r(n,["serviceAccount"]);P!=null&&l(t,["serviceAccount"],P);let $=r(n,["tunedModelDisplayName"]);$!=null&&l(t,["tunedModelDisplayName"],$);let F=r(n,["veoTuningSpec"]);return F!=null&&l(t,["veoTuningSpec"],F),t}p(es,"tuningJobFromVertex");function sg(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(sg,"tuningOperationFromMldev");function il(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(il,"tuningValidationDatasetToVertex");var ts=class extends Re{static{p(this,"Tunings")}constructor(e){super(),this.apiClient=e,this.list=async(t={})=>new qe(Oe.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:co.JOB_STATE_QUEUED}}}}async getInternal(e){var t,i,o,s;let a,c="",d={};if(this.apiClient.isVertexAI()){let u=Ym(e);return c=A("{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=>es(f))}else{let u=Jm(e);return c=A("{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=jm(e);return c=A("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=tg(f),m=new qn;return Object.assign(m,h),m})}else{let u=Zm(e);return c=A("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=eg(f),m=new qn;return Object.assign(m,h),m})}}async cancel(e){var t,i,o,s;let a,c="",d={};if(this.apiClient.isVertexAI()){let u=Vm(e);return c=A("{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=qm(f),m=new Hn;return Object.assign(m,h),m})}else{let u=Bm(e);return c=A("{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=Om(f),m=new Hn;return Object.assign(m,h),m})}}async tuneInternal(e){var t,i;let o,s="",a={};if(this.apiClient.isVertexAI()){let c=Wm(e,e);return s=A("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=>es(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=Km(e);return s=A("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=>sg(d))}}};var ns=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.")}},rg=1024*1024*8,ag=3,lg=1e3,cg=2,ui="x-goog-upload-status";async function dg(n,e,t){var i;let o=await Bl(n,e,t),s=await o?.json();if(((i=o?.headers)===null||i===void 0?void 0:i[ui])!=="final")throw new Error("Failed to upload file: Upload status is not finalized.");return s.file}p(dg,"uploadBlob");async function ug(n,e,t){var i;let o=await Bl(n,e,t),s=await o?.json();if(((i=o?.headers)===null||i===void 0?void 0:i[ui])!=="final")throw new Error("Failed to upload file: Upload status is not finalized.");let a=sl(s),c=new So;return Object.assign(c,a),c}p(ug,"uploadBlobToFileSearchStore");async function Bl(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(rg,s-a),f=n.slice(a,a+u);a+u>=s&&(d+=", finalize");let h=0,m=lg;for(;h<ag&&(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[ui]));)h++,await pg(m),m=m*cg;if(a+=u,((o=c?.headers)===null||o===void 0?void 0:o[ui])!=="active")break;if(s<=a)throw new Error("All content has been uploaded, but the upload status is not finalized.")}return c}p(Bl,"uploadBlobInternal");async function fg(n){return{size:n.size,type:n.type}}p(fg,"getBlobStat");function pg(n){return new Promise(e=>setTimeout(e,n))}p(pg,"sleep");var is=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 dg(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 ug(e,t,i)}async stat(e){if(typeof e=="string")throw new Error("File path is not supported in browser uploader.");return await fg(e)}};var os=class{static{p(this,"BrowserWebSocketFactory")}create(e,t,i){return new ss(e,t,i)}},ss=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 ol="x-goog-api-key",rs=class{static{p(this,"WebAuth")}constructor(e){this.apiKey=e}async addAuthHeaders(e,t){if(e.get(ol)===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(ol,this.apiKey)}}};var hg="gl-node/",Jt=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 te({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=qc(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 rs(this.apiKey);this.apiClient=new Mo({auth:o,apiVersion:this.apiVersion,apiKey:this.apiKey,vertexai:this.vertexai,httpOptions:this.httpOptions,userAgentExtra:hg+"web",uploader:new is,downloader:new ns}),this.models=new Oo(this.apiClient),this.live=new Bo(this.apiClient,o,new os),this.batches=new xo(this.apiClient),this.chats=new No(this.models,this.apiClient),this.caches=new Po(this.apiClient),this.files=new $o(this.apiClient),this.operations=new qo(this.apiClient),this.authTokens=new Ho(this.apiClient),this.tunings=new ts(this.apiClient),this.fileSearchStores=new Ko(this.apiClient)}};var pt=Q,Vl=new Map,Ol=[];function ht(){let n=`[${ht.name}]`;try{return pt&&console.log(`${n} starting... (I: a5cf5821b42e1c71182dd61431977e25)`),Vl}catch(e){throw console.error(`${n} ${E(e)}`),e}finally{pt&&console.log(`${n} complete.`)}}p(ht,"getAllFunctionInfos");function ps(){let n=`[${ps.name}]`;try{return pt&&console.log(`${n} starting... (I: 82c9a8fc91d8121fb843af32e76c2e25)`),Ol}catch(e){throw console.error(`${n} ${E(e)}`),e}finally{pt&&console.log(`${n} complete.`)}}p(ps,"getDeprecatedFunctionInfoNames");function mg({functionInfos:n}){let e=`[${mg.name}]`;try{pt&&console.log(`${e} starting... (I: 14fee8e27384a040494542182031ae25)`),n.size===0&&console.warn(`${e} empty functionInfos? (W: 97fcb8fc47689bc418893c09a16a2525)`);for(let[t,i]of n)Ol.includes(t)?pt&&console.log(`${e} functionInfo.nameOrId (${t}) is deprecated. Skipping add. (I: 3256eadf54f8087088a704798e2fd825)`):Vl.set(t,i)}catch(t){throw console.error(`${e} ${E(t)}`),t}finally{pt&&console.log(`${e} complete.`)}}p(mg,"registerFunctionInfos");var Ee=Q;function Yt(n){switch(n){case ee.HUMAN:return"user";case ee.AI:return"model";case ee.FUNCTION:return"user";case ee.HARDCODED:return"user";case ee.UNKNOWN:return"user";default:throw new Error(`(UNEXPECTED) src is not a valid TextSource? src: ${n} (E: 9d954fe0bc49cf4572a65b19b6173925)`)}}p(Yt,"textSourceToGeminiRole");function ql(n){return n.api==="gemini"}p(ql,"isPromptInfoGemini");function hs({systemPromptEntries:n}){let e=`[${hs.name}]`;try{if(Ee&&console.log(`${e} starting... (I: 18693a97427939699285ef8c1a9cc425)`),n.length===0)return;n.every(i=>i.src===ee.HUMAN)||Ee&&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 Ee&&console.log(`${e} sysInstructionContent: ${V(t)} (I: 011e5b865c23eb0b640df3f464ac2525)`),t}catch(t){throw console.error(`${e} ${E(t)}`),t}finally{Ee&&console.log(`${e} complete.`)}}p(hs,"systemPromptEntriesToSystemInstructionContent");function ms({ibGib:n}){let e=`[${ms.name}]`;try{if(Ee&&console.log(`${e} starting... (I: 986d3edcd4f3aaf1d7eb0f8b59206b25)`),!n)return Ee&&console.warn(`${e} ibGib falsy. (W: a70390e8bc3f420a92d3a84f4c78f12a)`),!1;if(!It({ibGib:n}))return Ee&&console.log(`${e} not a comment ibgib (I: 6a62c4f6e13776616855c4f237a5206b)`),!1;if(!n.data)return Ee&&console.log(`${e} ibGib.data falsy (I: 69eb86975640475395bb74944141a46d)`),!1;let{text:t}=n.data;return t?t.includes(_n)?(Ee&&console.log(`${e} has tag. returning true. (I: 6d76b27d558d44f696582f41af561f29)`),!0):(Ee&&console.log(`${e} no indicator found. returning false. (I: 815f181a0a08058362f76b08a8964674)`),!1):(Ee&&console.log(`${e} text falsy (I: e348e38c841b4443b3f09e75c0215b24)`),!1)}catch(t){throw console.error(`${e} ${E(t)}`),t}finally{Ee&&console.log(`${e} complete.`)}}p(ms,"isFunctionCallRequestComment");function gs({functionInfoIbGib:n}){let e=`[${gs.name}]`;try{if(Ee&&console.log(`${e} starting... (I: genuuid)`),!n)throw new Error(`${e} functionInfoIbGib parameter is required. (E: genuuid)`);if(!n.data)throw new Error(`${e} functionInfoIbGib.data is required. (E: genuuid)`);let{fnName:t,fnArgs:i,fnResult:o}=n.data;if(!t)throw new Error(`${e} functionInfoIbGib.data.fnName is required. (E: genuuid)`);return{call:{functionCall:{name:t,args:i??{}}},response:{functionResponse:{name:t,response:{value:o}}}}}catch(t){throw console.error(`${e} Error: ${E(t)}`),t}finally{Ee&&console.log(`${e} complete.`)}}p(gs,"getFunctionCallAndResponseParts");var Xt=Q,mi="function_info",Hl="function_info";function zl({data:n}){let e=`[${zl.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=nt(s);if([t,i,o,a].some(d=>d.includes(" ")))throw new Error("invalid data. ib must not contain spaces (E: 36a56e4685163848458be06f51d4ad25)");return[Hl,a,t,i,o].join(" ")}p(zl,"getFunctionInfoIb");async function gi(n){let e=`[${gi.name}]`;try{Xt&&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:y}=n,w=new Date,v={name:o,timestamp:Ds(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=zl({data:v}),C=await Ie.firstGen({ib:I,parentIbGib:Ie.primitive({ib:Hl}),data:v,nCounter:!0,dna:!0,tjp:{uuid:!0}});if(Xt&&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(!y)throw new Error(`${e} space must be provided if saveInSpace is set to true (E: f3d5f1695a52707114117f72d932a025)`);await b.persistTransformResult({resTransform:C,space:y}),Xt&&console.log(`${e} persisted resFunctionInfo (${_({ibGib:C.newIbGib})}) to space ${y.data?.uuid} (I: aa98e877d3b34e0d2a3b7711f8f27e25)`),await b.registerNewIbGib({ibGib:C.newIbGib,space:y}),Xt&&console.log(`${e} registered new function info ibgib (${_({ibGib:C.newIbGib})}) with metaspace (I: aa98e877d3b34e0d2a3b7711f8f27e25)`)}return C}catch(t){throw console.error(`${e} ${E(t)}`),t}finally{Xt&&console.log(`${e} complete.`)}}p(gi,"createFunctionInfoIbGib");var L=Q,bi=class n extends gr{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=yt({count:32})}async validateThis(){let e=`${this.lc}[${this.validateThis.name}]`;try{L&&console.log(`${e} starting... (I: 641e211473fc54d5a9ebb4ea44944d25)`);let t=await super.validateThis();return this.data?(this.data?.subSpaceId||t.push("agent.data.subSpaceId falsy (E: d4ea57fd6b1c5cbc1e18a084de2f7725)"),this.data?.subSpaceId.match(on)||t.push(`agent.data.subSpaceId must match regexp: ${on}. (E: f381eff533aa3f4713316f93f7f1dc25)`),this.data.name?this.data.name.match(Tt)||t.push(`agent name must match regexp: ${Tt}`):t.push("agent name falsy (E: 1351325107e5ac5ea6b7b789b73de125)"),this.data.description&&(this.data.description.match(Ji)||t.push(`agent description must match regexp: ${Ji}`))):t.push("this.data falsy (E: f5f151e11b12cad814b37ecad7c74a25)"),t}catch(t){throw console.error(`${e} ${E(t)}`),t}finally{L&&console.log(`${e} complete.`)}}async initialize(){let e=`${this.lc}[${this.initialize.name}]`;try{L&&console.log(`${e} starting... (I: ce38519ac4bef52844a558fe31cda825)`),await super.initialize(),this._metaspace=await k();let t=new Ke;if(await t.initialized,!t.contextUpdated$)throw new Error("(UNEXPECTED) ibGibProxy.contextUpdated$ falsy? (E: e8840870af18091e6e4d52490ddca825)");if(t.contextUpdated$.subscribe(Ve({next:p(async i=>{let o=`${e}[ibGibProxy.contextUpdated$][next]`;L&&console.log(`${o} nextIbGib: ${V(i)} (I: 96c846357b94fda2cefa615aed88c325)`),await this.handleContextUpdated()},"next"),error:p(async i=>{debugger;console.error(`${e}[ibGibProxy.contextUpdated$][error] what up? ${E(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 L&&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} ${E(t)}`),t}finally{L&&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(_({ibGib:this})!==_({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 z(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} ${E(t)}`),t}}async getSubSpace(){let e=`[${this.getSubSpace.name}]`;try{L&&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} ${E(t)}`),t}finally{L&&console.log(`${e} complete.`)}}async getSuperSpace(){let e=`[${this.getSuperSpace.name}]`;try{L&&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} ${E(t)}`),t}finally{L&&console.log(`${e} complete.`)}}_activeContext=void 0;async setActiveContext(e){let t=`${this.lc}[${this.setActiveContext.name}]`;try{L&&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=_({ibGib:i}),a=H({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?L&&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 Ke;await c.initialized;let d=`${t}[contextUpdated]`;if(!c.contextUpdated$)throw new Error("(UNEXPECTED) proxy.contextUpdated$ falsy? (E: 868c5e3bf025baa6d1ae727ab1160c25)");c.contextUpdated$.subscribe(Ve({next:p(async f=>{console.log(`${d}[next] nextIbGib: ${V(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] ${E(f)}`)},"error")}));let u=`${t}[newContextChild]`;if(!c.newContextChild$)throw new Error("(UNEXPECTED) proxy.newContextChild$ falsy? (E: 123cf5624c3d2a6308aafc0c41f8a925)");c.newContextChild$.subscribe(Ve({next:p(async f=>{if(console.log(`${u}[next] newChild: ${V(f)}`),!f.data)throw new Error("newChild.data falsy? (E: a654134a2695c176971b0cd1426ced25)");if(It({ibGib:f})){let h=this.commentIbGibs_chat.map(w=>H({ibGib:w})??_({ibGib:w})),m=H({ibGib:f})??_({ibGib:f});if(h.includes(m)){console.log(`${t} already did this comment (${m}) (I: bce18642bb9babeb553e6188d7ae2825)`);return}let{safeIbCommentMetadataText:g}=wt({ib:f.ib}),{textSrc:b}=Qt({addlMetadataText:g??"",ifError:"warn"}),y=f.data.text.startsWith("system: ");await this.addTexts({infos:[{textSrc:b??ee.UNKNOWN,commentIbGib:f,isSystem:y}]}),b===ee.HUMAN&&(y?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] ${E(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} ${E(i)}`),i}finally{L&&console.log(`${t} complete.`)}}async updateName({name:e}){let t=`${this.lc}[${this.updateName.name}]`;try{if(L&&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(Tt.test(e))await this.mut8Self({dataToAddOrPatch:{name:e}});else throw new Error(`invalid name ${e}. must match regexp: ${Tt.source} (E: 507a2bfc0aaa60bd7bb608d253239e25)`)}catch(i){throw console.error(`${t} ${E(i)}`),i}finally{L&&console.log(`${t} complete.`)}}async updateAvailableFunctions({availableFunctions:e}){let t=`${this.lc}[${this.updateAvailableFunctions.name}]`;try{L&&console.log(`${t} starting... (I: 68f1bfa343925a657f8c0545b191c725)`);let i=[];for(let o of e)if(!this.availableFunctions.has(o.nameOrId)){let s=ht().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} ${E(i)}`),i}finally{L&&console.log(`${t} complete.`)}}async mut8Self({dataToAddOrPatch:e}){let t=`${this.lc}[${this.mut8Self.name}]`;try{L&&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 cn({fn:p(async()=>{let a=Ue();await a.updateOrSetLatestAgent({agent:this,throwIfNewerFound:!1});let c=await Ls({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 bs({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} ${E(i)}`),i}finally{L&&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(L&&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 Ue().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} ${E(i)}`),i}finally{L&&console.log(`${t} complete.`)}}async doPrompt(){let e=`[${this.doPrompt.name}]`;try{if(L&&console.log(`${e} starting... (I: e7f1a7845cdf1bdce1f12d74c71a6425)`),!this.data)throw new Error("(UNEXPECTED) this.data falsy? (E: 3c528e2376a2f2600b347b2c183a5225)");let t=await this.composePromptInfo();L&&console.log(`${e} promptTextInfo: ${V(t)} (I: b769b5f2a47623a99f78210994d90525)`);let i=await this.callTextAPI(t);if(L&&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} ${E(t)}`),t}finally{L&&console.log(`${e} complete.`)}}async doPrompt_text(e){let t=`${this.lc}[${this.doPrompt_text.name}]`;try{L&&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} ${E(i)}`),i}finally{L&&console.log(`${t} complete.`)}}async doPrompt_functionCalls({functionCalls:e}){let t=`${this.lc}[${this.doPrompt_functionCalls.name}]`;try{if(L&&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 L&&console.log(`${t} no repromptWithResult. returning early. (I: 9c0113c958c7404534291f6700325925)`)}catch(i){throw console.error(`${t} ${E(i)}`),i}finally{L&&console.log(`${t} complete.`)}}async doPrompt_functionCalls_createFunctionInfoIbGibsAndExecFunctionCalls({functionCalls:e}){let t=`${this.lc}[${this.doPrompt_functionCalls_createFunctionInfoIbGibsAndExecFunctionCalls.name}]`;try{if(L&&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{L&&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(L&&console.log(`${t} functionCallParsedObj:`,V(c),"(I: 750f097243b85644d111971e0f929c25)"),u=ht().get(c.name),!u)throw new Error(`no APIFunctionInfo found that matches functionName (${h}) (E: 9d36b6472ec5cdf95e4f498292449925)`);f=c.args,L&&console.log(`${t} valid params (I: a4d5c13c79a2405c8d20464b42083325)`)}catch(m){d=`${t} invalid functionCallParsedObj. error: ${E(m)}. functionCallStr: ${s}. (E: 1687a24c5a3667d34689a09f8f753125)`,console.error(d),c=void 0}if(u){L&&console.log(`${t} found functionInfo: ${u.nameOrId} (I: 837c7a8200689a0b2314b73057812b25)`);let m,g=!1,b;try{L&&console.log(`${t} calling function impl for ${u.nameOrId} (I: b145d08186782089c18564305f0f1125)`),m=await u.fnViaCmd(f),g=!0,L&&console.log(`${t} functionImpl complete for ${u.nameOrId}. result:`,V(m),"(I: e19d476f489261263165914750472d25)")}catch(w){b=`${t} could not call functionImpl for ${u.nameOrId}: ${E(w)} (E: 9c0e97f29a9290f9d57637b7053f0c25)`,console.error(b)}a=(await gi({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 gi({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} ${E(a)}`),a}finally{L&&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} ${E(i)}`),i}finally{L&&console.log(`${t} complete.`)}}async doPrompt_functionCalls_addFunctionCallRequestComment({functionInfoIbGibs:e}){let t=`${this.lc}[${this.doPrompt_functionCalls_addFunctionCallRequestComment.name}]`;try{L&&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=St({tagText:_n,contentText:e.map(f=>_({ibGib:f})).join(`
676
+ `),randomIdLength:4}),a=Mt({textSrc:"ai",other:"functionCallRequest"}),c=await vt({text:s,addlMetadataText:a,saveInSpace:!0,space:o}),d=await it({type:"rel8",src:c.newIbGib,rel8nsToAddByAddr:{[mi]:e.map(f=>_({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} ${E(i)}`),i}finally{L&&console.log(`${t} complete.`)}}async doPrompt_functionCalls_getTransientDecompressionPromptForNextPrompt({functionInfoIbGibs:e}){let t=`${this.lc}[${this.doPrompt_functionCalls_getTransientDecompressionPromptForNextPrompt.name}]`;try{L&&console.log(`${t} starting... (I: c245f78f6c78a98d62375a9f14b3d625)`);let i=[];for(let o of e)try{let s=_({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=St({tagText:s,contentText:V({fnRawRequest:a,fnComplete:c,fnResult:d}),randomIdLength:void 0});i.push(f)}catch(s){console.error(`${t} could not call functionImpl: ${E(s)} (E: 2a3b8b37e146c524b67119e3a74e3d25)`)}return i.join(`
677
+ `)}catch(i){throw console.error(`${t} ${E(i)}`),i}finally{L&&console.log(`${t} complete.`)}}repromptCount=0;repromptMax=12;async rePrompt(){let e=`${this.lc}[${this.rePrompt.name}]`;try{L&&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} ${E(t)}`),t}finally{L&&console.log(`${e} complete.`)}}async witness(e){if(e.ib===rn&&e.gib===an)return this.getComments_Chat().length>0&&await this.doPrompt(),Ut;throw new Error(`arg (${V(e)}) not implemented. only expect ${Ut} right now to trigger doPrompt. (E: 24da0ad7333b6bbb359d1be425db3c25)`)}};var q=Q,Ye=class n extends bi{static{p(this,"AgentWitnessGemini_V1")}lc=`[${n.name}]`;async validateThis(){let e=`${this.lc}[${this.validateThis.name}]`;try{q&&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} ${E(t)}`),t}finally{q&&console.log(`${e} complete.`)}}parseAddlMetadataString({ib:e}){let t=`${this.lc}[${this.parseAddlMetadataString.name}]`;try{throw q&&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} ${E(i)}`),i}finally{q&&console.log(`${t} complete.`)}}async addTexts(e){let t=`${this.lc}[${this.addTexts.name}]`;try{let i=Ue();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:y}=h;if(b&&y)throw new Error("(UNEXPECTED) both text and commentIbGib provided? (E: a3fd590db1a5efc301f3c7e66b322f25)");if(!b&&!y)throw new Error("(UNEXPECTED) both text and commentIbGib falsy? one or the other is required (E: e08c7c694a17319085adfb75914b2725)");let w=Mt({textSrc:m});if(y)q&&console.log(`${t} adding existing commentIbGib (I: 72a3f7aafde92f65b168d27605f94625)`);else{if(q&&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)");y=(await vt({text:b,addlMetadataText:w,saveInSpace:!0,space:d})).newIbGib,await o.registerNewIbGib({ibGib:y,space:d})}if(!y)throw new Error("(UNEXPECTED) commentIbGib still falsy? we should have just created one if it didn't exist (E: 9370b19aa207234db185cd74b57be525)");let v=await wi({ibGib:y});if(v.length>0)throw new Error(`validation errors with trying to add a commentIbGib. errors: ${v} (E: beee1893050f9bcf9842c66831595225)`);s.push(y),g?a.push(y):c.push(y)}let u=[];a.length>0&&u.push({rel8nName:"system",ibGibs:a}),c.length>0&&u.push({rel8nName:"chat",ibGibs:c});let f=await pr({timeline:this.toIbGibDto(),rel8nInfos:u,timelineIndexInfo:{rel8nName:dt,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} ${E(i)}`),i}}async composePromptInfo(){let e=`${this.lc}[${this.composePromptInfo.name}]`;try{if(q&&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"]??Z;if(i!==Z&&t.push({src:ee.HARDCODED,content:{role:Yt(ee.HARDCODED),parts:[{text:Kl({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 q&&console.log(`${e} resPromptInfo:`,V(u),"(I: 8f17a8c45b9a91e20a5c5064d9114a25)"),u}catch(t){throw console.error(`${e} ${E(t)}`),t}finally{q&&console.log(`${e} complete.`)}}async callTextAPI(e){let t=`${this.lc}[${this.callTextAPI.name}]`;try{if(q&&console.log(`${t} starting... (I: 27885f5b14682646542e9658417b2f25)`),!ql(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)`);q&&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 Jt({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)`),q&&(console.log(`${t} Gemini functionDeclarations:`),console.dir(a));let{systemPromptEntries:c,chatPromptHistoryParts:d,chatPromptCurrent:u}=e,f=xe(u);q&&console.log(`chatPromptCurrent_final (before decompression): ${V(f)} (I: bbd4c7b9f3225afe9da1761918d0ac25)`),q&&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 C=d.map(G=>G.content),T={model:I,history:C,config:{systemInstruction:hs({systemPromptEntries:c}),tools:[{functionDeclarations:a}],toolConfig:{functionCallingConfig:{mode:e.overrideFunctionCallingMode??Mn.ANY}}}},x=this._genAI.chats.create(T),N={message:u.content.parts};return await x.sendMessage(N)},"fnGoModel"),g=0,b=o;do{g++;try{h=await m(b);break}catch(I){let C=I.message,T=I.status??"[STATUS?]";C.includes(`${503}`)?(console.error(`${t}[fnGoModel][${b}] error trying to get result from model. will try using backup model (${_t}) for this next call. error (${I.status}): ${E(I)} (E: a5cd7d174183518058da57cc6d0d8a25)`),b=_t):C.includes(`${429}`)?(console.error(`${t}[fnGoModel][${b}] error trying to get result from model. will try using backup model (${_t}) for this next call. error (${I.status}): ${E(I)} (E: a5cd7d174183518058da57cc6d0d8a25)`),b=_t):console.error(`${t}[fnGoModel][${b}] error trying to get result from model. error (${I.status}): ${E(I)} (E: a67d595c8ed313d458369d4d0b3e7f25)`)}await z(2e3)}while(!h&&g<io);if(!h)throw new Error("couldn't get result from model (E: ede013a53f875d99a96a2e257c7e7125)");let y=h,w=[],v=y.candidates?.[0]?.content?.parts||[];for(let I of v)I.functionCall&&w.push(I.functionCall);if(!w||w.length===0){if(q&&console.warn(`${t} no function calls in response, returning text. (W: 3a4b8c940983b9e28e3f04c01a09bb25)`),!y.text)throw new Error("response generated no function calls and no response.text (E: 6123b8cacfb834105ad3160cfc4ef825)");return{text:y.text}}return q&&(console.log(`${t} Gemini function calls:`),console.dir(w)),{functionCalls:w.map(I=>JSON.stringify(I,null,2))}}catch(i){throw console.error(`${t} ${E(i)}`),i}finally{q&&console.log(`${t} complete.`)}}async createPromptInfoEntriesFromGeminiComment({commentIbGib:e}){let t=`[${this.createPromptInfoEntriesFromGeminiComment.name}]`;try{q&&console.log(`${t} starting... (I: 826a9d6b120d96532afbe1f7a22e8d25)`);let i=await wi({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}=wt({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}=Qt({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(ms({ibGib:e})){let f=await this.getFunctionInfoIbGibs({fcrCommentIbGib:e}),h=[],m=[];for(let y of f){let{call:w,response:v}=gs({functionInfoIbGib:y});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:ee.AI,content:{role:Yt("ai"),parts:h}},b={src:ee.FUNCTION,content:{role:Yt(ee.FUNCTION),parts:m}};return[g,b]}else return[{src:s,content:{role:Yt(s),parts:[{text:e.data.text}]}}]}catch(i){throw console.error(`${t} ${E(i)}`),i}finally{q&&console.log(`${t} complete.`)}}async promptOneOff(e){let t=`${this.lc}[${this.promptOneOff.name}]`;try{q&&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)`);q&&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 Jt({apiKey:c});let d=p(async b=>{if(!this._genAI)throw new Error("(UNEXPECTED) this._genAI falsy? (E: fbe235713d48f0d8e87cd0b88ec54825)");let y={model:b,config:{systemInstruction:o}},v=await this._genAI.chats.create(y).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(_t);let m=0,g=1;do{f++,g++;let b=h[m];try{u=await d(b);break}catch(y){if(y instanceof Error){let w=y.message,v=y.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}): ${E(y)} (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}): ${E(y)} (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}): ${E(y)} (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}): ${E(y)} (E: a9869883fc72bf156f1691183e27ee25)`)}else console.error(`${t}[fnGoModel][${b}] error trying to get result from model. error (${v}): ${E(y)} (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 z(g*1e3)}while(!u&&f<io);return u}catch(i){throw console.error(`${t} ${E(i)}`),i}finally{q&&console.log(`${t} complete.`)}}async getFunctionInfoIbGibs({fcrCommentIbGib:e}){let t=`[${this.getFunctionInfoIbGibs.name}]`;try{q&&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?.[mi]??[];if(a.length===0)return q&&console.warn(`${t} no functionInfoAddrs (I: 5f8965e92c305689c11677a1148b7425)`),[];q&&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,q&&console.log(`${t} resFunctionInfoIbGibs: ${V(i.map(d=>_({ibGib:d})))} (I: a5661b5c449608f0e8d773135a599a25)`),i}catch(i){throw console.error(`${t} ${E(i)}`),i}finally{q&&console.log(`${t} complete.`)}}async loadIbGibDto(e){let t=`[${this.loadIbGibDto.name}]`;try{if(q&&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=ht().get(d);u?this.availableFunctions.set(d,u):ps().includes(d)?q&&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: ${E(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: ${E(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 cn({scope:"prune",secondsValid:60,maxDelayMs:100,maxLockAttempts:1800,space:o,callerInstanceId:nt(),fn:s})}catch(i){throw console.error(`${t} ${E(i)}`),i}finally{q&&console.log(`${t} complete.`)}}};setTimeout(()=>{Ue().registerFactory({classname:Ye.name,fnDtoToAgentWitness:p(async e=>e.data?e.data.classname?e.data.classname===Ye.name?{applies:!0,agent:await ys({agentIbGib:e})}:{applies:!1}:{applies:!1}:{applies:!1},"fnDtoToAgentWitness")})});function Kl({currentContextTjpAddr:n}){let e=`[${Kl.name}]`;try{q&&console.log(`${e} starting... (I: 7edafbba277d57eae51af325cf7eb225)`);let t=W({ibGibAddr:n});return`Your current context ibGibAddr is ${n}
678
+ 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} ${E(t)}`),t}finally{q&&console.log(`${e} complete.`)}}p(Kl,"getTextPartForCurrentContextTjpAddr");var Xe=Q,vi=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{Xe&&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=xe(Mr);return i&&(d.name=i),d.uuid=await sn(),d.superSpaceId=e.data.uuid,d.api=o,d.model=s,d.type=a,d.availableFunctionNameOrIds=c.map(u=>u.nameOrId),d.classname=Ye.name,d}catch(i){throw console.error(`${t} ${E(i)}`),i}finally{Xe&&console.log(`${t} complete.`)}}async createInitialRel8ns(){let e=`${this.lc}[${this.createInitialRel8ns.name}]`;try{return Xe&&console.log(`${e} starting... (I: 2d4933ea3761bd7df701d8d306fb2825)`),oo?xe(oo):void 0}catch(t){throw console.error(`${e} ${E(t)}`),t}finally{Xe&&console.log(`${e} complete.`)}}async createWitness(){let e=`[${this.createWitness.name}]`;try{Xe&&console.log(`${e} starting... (I: 36709dfa0c398d63d64c4f6ba9055625)`);let{api:t,model:i}=this.arg;if(t==="gemini"){let o=new Ye;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} ${E(t)}`),t}finally{Xe&&console.log(`${e} complete.`)}}};async function ys({agentIbGib:n}){let e=`[${ys.name}]`;try{Xe&&console.log(`${e} starting... (I: 5a4efefba9e4bdfb942afbe7919fff25)`);let t=new Ye;return await t.initialized,await t.loadIbGibDto(n),t.fnGetAPIKey=async()=>await Tn({dbName:dr(),storeName:await cr(),key:await ur()})??"",t}catch(t){throw console.error(`${e} ${E(t)}`),t}finally{Xe&&console.log(`${e} complete.`)}}p(ys,"agentIbGibDtoToWitness");var ie=Q;async function ji({metaspace:n,space:e,createIfNone:t}){let i=`[${ji.name}]`;try{if(ie&&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 js({metaspace:n,space:e});if(!o.rel8ns)throw new Error("(UNEXPECTED) tagsIbGib.rel8ns falsy? (E: dc50e8d218fe5e30bbaec7f37d484525)");let a=(o.rel8ns[Us]??[]).filter(u=>{let{ib:f}=B({ibGibAddr:u});return f===Ks}),c,d;if(a.length===0){if(t){ie&&console.log(`${i} creating new agents tag... (I: 47f4f4fa89f1a1bba960e0a6ff5f5225)`);let{newTagIbGib:u}=await n.createTagIbGib({text:qs,icon:Hs,description:zs,space:e});return d=u,ie&&console.log(`${i} creating new agents tag complete. (I: 5f41d644f2b692348377f918057cf225)`),u}}else a.length===1?(c=a.at(0),ie&&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} ${E(o)}`),o}finally{ie&&console.log(`${i} complete.`)}}p(ji,"getTag_Agents");async function An({metaspace:n,type:e,spaceId:t,space:i}){let o=`[${An.name}]`;try{if(ie&&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:dt,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=Ue(),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} ${E(s)}`),s}finally{ie&&console.log(`${o} complete.`)}}p(An,"getAgents");async function bs({metaspace:n,type:e,space:t,newAgentIbGib:i}){await p(async()=>{let s=`[${bs.name}]`;try{if(ie&&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 Ue().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=_({ibGib:i});await re({type:i.data.type,rel8nInfos:[{rel8nName:dt,ibGibs:[J({ibGib:i})]}],metaspace:n,space:t})}catch(a){throw console.error(`${s} ${E(a)}`),a}finally{ie&&console.log(`${s} complete.`)}},"fn")()}p(bs,"updateAgentIndex");async function Es({ibGib:n,metaspace:e,space:t}){let i=`[${Es.name}]`;try{if(ie&&console.log(`${i} starting...`),!n)throw new Error("ibGib required (E: 753a0aa13e4e5ea20d7f6bb92d963625)");let o=await pn({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=H({ibGib:n,defaultIfNone:"incomingAddr"}),a=_({ibGib:o}),d=await Ue().getAgentByAddr({agentAddr:a,metaspace:e,spaceId:t.data.uuid});return ie&&console.log(d?`${i} complete. Found agent ${_({ibGib:d})} for domain ${s}`:`${i} complete. No agent found for ibgib tjp ${s}`),d}catch(o){throw console.error(`${i} ${E(o)}`),o}}p(Es,"getAgentForDomainIbGib");function eo(n){let e=`[${eo.name}]`;try{ie&&console.log(`${e} starting... (I: 2a9899514ac6e478eb55819a57fd9725)`);let{api:t}=n;switch(t){case"gemini":return new vi(n);default:throw new Error(`(UNEXPECTED) api: ${t}? only 'gemini' currently implemented? (E: 071fedab181fda80666858c14ea73625)`)}}catch(t){throw console.error(`${e} ${E(t)}`),t}finally{ie&&console.log(`${e} complete.`)}}p(eo,"getConcreteAgentFactory");function St({tagText:n,contentText:e,randomIdLength:t}){let i=`[${St.name}]`;try{ie&&console.log(`${i} starting... (I: 94104ec059c89d4ba458d96580791d25)`);let o=t?`${n}|${yt({count:t})}`:n;return[`[${o} begin]`,e,`[${o} end]`].join(`
679
+ `)}catch(o){throw console.error(`${i} ${E(o)}`),o}finally{ie&&console.log(`${i} complete.`)}}p(St,"taggifyForPrompt");function Mt({textSrc:n,other:e}){let t=`[${Mt.name}]`;return e?[n,nt(),e].join("_"):[n,nt()].join("_")}p(Mt,"getAddlMetadataTextForAgentText");function Qt({addlMetadataText:n,ifError:e="warn"}){let t=`[${Mt.name}]`;try{ie&&console.log(`${t} starting... (I: 89b8b19a8d785b945fe0f816df762d25)`);let[i,o,...s]=n.split("_");if(!i)throw new Error("addlMetadataText.textSrc falsy (E: 40bbec4269c1688ab1390fa5d5440325)");if(!Gr(i))throw new Error(`addlMetadataText.textSrc (${i}) is unexpected value. Expected one of ${Yi} (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} ${E(i)}`;switch(e){case"ignore":return{textSrc:ee.UNKNOWN,timestampInTicks:0,errorMsg:E(i)};case"warn":return console.warn(`${t} ${o} (W: 3e1f4a98ad6461c9bd96462841c31b25)`),{textSrc:ee.UNKNOWN,timestampInTicks:0,errorMsg:E(i)};default:throw console.error(`${t} ${o} (E: 6396ed44947c52adf85788e1adc22825)`),new Error(o)}}finally{ie&&console.log(`${t} complete.`)}}p(Qt,"parseAddlMetadataTextForAgentText");function to({data:n}){let e=`[${to.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[Ct,t,i,o].join(" ")}p(to,"getAgentIb");function Rr({ib:n}){let[e,t,i,o]=n.split(" ");if(e!==Ct)throw new Error(`invalid ib. first term expected to e an atom: ${Ct} (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(Rr,"parseAgentIb");async function wi({ibGib:n}){let e=`[${wi.name}]`;try{ie&&console.log(`${e} starting... (I: f9a733a5a05b7f7494836d86a79e2d25)`);let t=await ln({ibGib:n})??[];if(!It({ibGib:n}))return t.push(`${e} not a comment ibgib (E: 08676d94c698c6e42e6c35e94a58f125)`),t;let{safeIbCommentMetadataText:i}=wt({ib:n.ib});if(i){let o=Qt({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} ${E(t)}`),t}finally{ie&&console.log(`${e} complete.`)}}p(wi,"validateAgentWitnessCommentIbGib");var Ii="settings",gg="general",bg="text-editor",yg="projects",Eg="projects-explorer",wg="projects-dropdown",vg="project",Ig="minigame",Cg="chronologys",Tg="identity-manager",ce={general:gg,textEditor:bg,projects:yg,projectsExplorer:Eg,projectsDropdown:wg,project:vg,minigame:Ig,chronologys:Cg,identityManager:Tg},Sg=Object.values(ce);var ws={type:ce.general,editor:void 0,readonly:!0,viewer:"ibgib-raw-viewer"},vs={type:ce.textEditor,wrap:"wrap"},_g={type:ce.project,openChildTjpAddrs:[],activeChildTjpAddr:void 0,lensMode:"raw"},Ag={type:ce.minigame},xg={type:ce.chronologys,openChildTjpAddrs:[],activeChildTjpAddr:void 0},Pg={type:ce.identityManager,openChildTjpAddrs:[],activeChildTjpAddr:void 0},Wl={sections:{},children:{}};var Qe=Q;async function Is({ibGib:n}){let e=`[${Is.name}]`;try{Qe&&console.log(`${e} starting... (I: 57ac4c0a3448bc5e98ecf5bfb02ce825)`);let{ib:t}=B({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} ${E(t)}`),t}finally{Qe&&console.log(`${e} complete.`)}}p(Is,"getSettingsScope");async function Te({settingsType:n,useCase:e}){let t=`[${Te.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} ${E(i)}`),i}finally{Qe&&console.log(`${t} complete.`)}}p(Te,"getSectionName");async function Ci({sectionName:n,settingsIbGib:e}){let t=`[${Ci.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} ${E(i)}`),i}finally{Qe&&console.log(`${t} complete.`)}}p(Ci,"getSettingsSection");function Jl({scope:n}){let e=`[${Jl.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} ${E(t)}`),t}}p(Jl,"getSettingsIb");async function Cs({scope:n,metaspace:e,space:t,saveInSpace:i}){let o=`[${Cs.name}]`;try{let s=Jl({scope:n}),a=await Yl(),d=await Ie.firstGen({parentIbGib:Ie.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} ${E(s)}`),s}}p(Cs,"createSettings");async function Yl(){let n=`[${Yl.name}]`;try{Qe&&console.log(`${n} starting... (I: 3d7cc3f242cc88ad28dafaf85d646a25)`);let e=xe(Wl),t=await Te({settingsType:"general",useCase:"default"}),i=await Te({settingsType:"general",useCase:"current"});e.sections[t]=xe(ws),e.sections[i]=xe(ws);let o=await Te({settingsType:"text-editor",useCase:"default"}),s=await Te({settingsType:"text-editor",useCase:"current"});return e.sections[o]=xe(vs),e.sections[s]=xe(vs),e}catch(e){throw console.error(`${n} ${E(e)}`),e}finally{Qe&&console.log(`${n} complete.`)}}p(Yl,"getDefaultSettingsData");var R=Q,ae=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}},Fe=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}=B({ibGibAddr:this.ibGibAddr??Z});return e}get gib(){let{gib:e}=B({ibGibAddr:this.ibGibAddr??Z});return e}ibGibAddr=Z;ibGibProxy;get ibGib(){let e=this.ibGibAddr??Z,{ib:t,gib:i}=B({ibGibAddr:e});return this.ibGibAddr&&!Ft({gib:i})?this.ibGibProxy?.ibGib:Ie.primitive({ib:t})}get tjpAddr(){return this.ibGib?H({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(Bt,{detail:{isBusy:e,title:t,msg:i,animationEmoji:s},bubbles:!0,composed:!0})):window.dispatchEvent(new CustomEvent(Bt,{detail:{isBusy:e,title:t,msg:i,animationEmoji:s}}))}catch(c){throw console.error(`${a} ${E(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} ${E(t)}`),t}finally{R&&console.log(`${e} complete.`)}}constructor(){super(),this._instanceId=yt({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} ${E(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} ${E(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?`
680
680
  <style>
681
681
  ${this.css.join(`
682
682
  `)}
683
683
  </style>
684
684
  ${this.html}
685
- `: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} ${E(t)}`),t}finally{R&&console.log(`${e} complete.`)}}async connectedCallback_reconnectComponent(){let e=`${this.lc}[${this.connectedCallback_reconnectComponent.name}]`;try{R&&console.log(`${e} starting... (I: 7fccefbeff68c0dda15642ebaa1eb525)`),console.log(`${e} does nothing in base class (I: 724bc670d4ccb0fde2b2fa49830cd425)`)}catch(t){throw console.error(`${e} ${E(t)}`),t}finally{R&&console.log(`${e} complete.`)}}async disconnectedCallback(){let e=`${this.lc}[${this.disconnectedCallback.name}]`;try{R&&console.log(`${e} starting... (I: 6f3b25c23fb874b1ac513e8f0d1f4e25)`),await this.disconnected()}catch(t){throw console.error(`${e} ${E(t)}`),t}finally{R&&console.log(`${e} complete.`)}}async attributeChangedCallback(e,t,i){let o=`${this.lc}[attributeChangedCallback]`;R&&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{R&&console.log(`${e} starting... (I: 536989c9491b544105b6d01a688fbb25)`),await this.destroyed()}catch(t){throw console.error(`${e} ${E(t)}`),t}finally{R&&console.log(`${e} complete.`)}}async destroyed(){let e=`${this.lc}[${this.destroyed.name}]`;try{R&&console.log(`${e} starting... (I: f34f3ca04b06b1e00ebe04df22331125)`)}catch(t){throw console.error(`${e} ${E(t)}`),t}finally{R&&console.log(`${e} complete.`)}return R&&console.log(`${e} does nothing in the base class. (I: d9437f962e0aec40d69ad6159e7b5725)`),Promise.resolve()}async loadIbGib(e){let t=`${this.lc}[${this.loadIbGib.name}]`;try{R&&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(Ft({gib:B({ibGibAddr:this.ibGibAddr??j}).gib})){R&&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 d=a.ibGibs.at(0),c=new ze;if(await c.initialized,!c.contextUpdated$)throw new Error("(UNEXPECTED) ibGibProxy.contextUpdated$ falsy? (E: 351dfc898d2c3da2d7928079cec14925)");if(c.contextUpdated$.subscribe(Be({next:p(async h=>{let m=`${t}[ibGibProxy.contextUpdated$][next]`;R&&console.log(`${m} nextIbGib: ${V(h)} (I: 96c846357b94fda2cefa615aed88c325)`),await this.handleContextUpdated()},"next"),error:p(async h=>{debugger;console.error(`${t}[ibGibProxy.contextUpdated$][error] what up? ${E(h)}`)},"error")})),!c.newContextChild$)throw new Error("(UNEXPECTED) ibGibProxy.newContextChild$ falsy? (E: 2cbde5ab402cc6d81259c74d68bca725)");c.newContextChild$.subscribe(Be({next:p(async h=>{let m=`${t}[ibGibProxy.contextUpdated$][next]`;R&&console.log(`${m} childIbGib: ${V(h)} (I: 96c846357b94fda2cefa615aed88c325)`),await this.handleNewContextChild({childIbGib:h})},"next"),error:p(async h=>{debugger;console.error(`${t}[ibGibProxy.contextUpdated$][error] what up? ${E(h)}`)},"error")}));let u=await c.witness(s),f=await c.witness(d);this.ibGibProxy=c,this.ibGibAddr=_({ibGib:c.ibGib})}catch(i){throw console.error(`${t} ${E(i)}`),i}finally{R&&console.log(`${t} complete.`)}}async handleContextUpdated(){let e=`${this.lc}[${this.handleContextUpdated.name}]`;try{let{ibGib:t}=this;this.ibGibAddr=t?_({ibGib:t}):j,R&&console.log(`${e} context updated. this.ibGibAddr (I: 64e5876f58cc54b5af777c94f13a4325)`)}catch(t){throw console.error(`${e} ${E(t)}`),t}}async handleNewContextChild({childIbGib:e}){let t=`${this.lc}[${this.handleNewContextChild.name}]`;try{R&&console.log(`${t} child added to contextcontext updated. childIbGib: ${V(e)} (I: 07d02c9182c6629cbbacd39fd0ff7f25)`),console.log(_({ibGib:e}))}catch(i){throw console.error(`${t} ${E(i)}`),i}}async renderUI(){let e=`${this.lc}[${this.renderUI.name}]`;try{if(R&&console.log(`${e} starting... (I: 7e5704afe17fb937c8473e7801f56e25)`),this.ibGib){let{punctiliarColor:t,punctiliarColorTranslucent:i,punctiliarColorContrast:o,tjpColor:s,tjpColorTranslucent:a,tjpColorContrast:d,errorMsg:c}=cn({ibGib:this.ibGib,translucentAlpha:10});c?console.error(`${e} ${c} (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",d??"lime"))}await this.renderUI_busy()}catch(t){throw console.error(`${e} ${E(t)}`),t}finally{R&&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 ms({ibGib:this.ibGib,metaspace:i,space:o});if(s){let a=s.data.n;await s.setActiveContext({contextIbGib:this.ibGib,loggingInfo:this.lc}),await z(32);let d=s.data.n;a!==d&&console.warn(`${t} setting active context for agent changed agent.data.n.
686
- agent.data: ${V(W({ibGib:s}))}
687
- ibGib.data: ${W({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 (${_({ibGib:this.ibGib})}) (W: e4219903462baab438a23c786d714825)`);else throw new Error(`(UNEXPECTED) agent falsy? an agent should have been created and registered with the ibGib (${_({ibGib:this.ibGib})}) (E: 7182d1aa070b9578c78a5b8b401d8425)`)}catch(i){throw console.error(`${t} ${E(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 wi({sectionName:await Te({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} ${E(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 Te({settingsType:e,useCase:t}),a=await Et({timeline:this.settings.ibGib,metaspace:await this.getMetaspace(),mut8Opts:{dataToAddOrPatch:{sections:{[s]:i}}}});await z(100)}catch(s){throw console.error(`${o} ${E(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 Te({settingsType:e,useCase:"current"});return wi({sectionName:i,settingsIbGib:this.settings.ibGib})}catch(i){throw console.error(`${t} ${E(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(Ft({ibGib:this.ibGib})){console.error(`${e} this.ibGib is primitive, so what are we initializing settings for? (W: 9915089019b81c6935b32ae877095825)`);return}let o=await ys({ibGib:this.ibGib}),s=await dn({scope:o,ibGib:this.ibGib,metaspace:t,space:i});if(s||(s=(await Es({scope:o,metaspace:t,space:i,saveInSpace:!0})).newIbGib,await Ni({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 ze;if(await a.setWrappedIbGib({ibGib:s,space:i}),this.settings=a,!await this.getCurrentSettings({settingsType:ae.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} ${E(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(Ft({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 nr({ibGib:e,compress:t,metaspace:o,space:s})}catch(o){throw console.error(`${i} ${E(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 d=await this.getMetaspace(),c=await d.getLocalUserSpace({lock:!1});if(!c)throw new Error("(UNEXPECTED) couldn't get default local user space? (E: 947c983e57a91aa00c8c185320354325)");let[u,f]=await tr({exportIbGibJsonString:e,metaspace:d});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 d.get({addr:h,space:c});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){Gi;let g=[],b=[];Object.values(f).forEach(S=>{Ns({ibGib:S})?g.push(S):b.push(S)});let y=await d.put({ibGibs:g,isDna:!0,space:c,force:i});if(!y.success||y.errorMsg)throw new Error(`there was an error putting the export's dna ibgibs into the space (${c.ib}). error: ${y.errorMsg||"[unknown error (E: 7c7ef8d5281399b1d8f3fbeefba1b825)]"} (E: ce3e8b982208afc4889164ba20a31825)`);let{mapWithTjp_YesDna:w,mapWithTjp_NoDna:v,mapWithoutTjps:I}=Gi({ibGibs:b}),C=await d.put({ibGibs:Object.values(I),space:c,force:i});if(!C.success||C.errorMsg)throw new Error(`there was an error putting the export's non-dna stone ibgibs (no-tjp) into the space (${c.ib}). error: ${C.errorMsg||"[unknown error (E: dc17f8ee7aed5c445f8b827f274b0825)]"} (E: 9561364961e89c132818f6784a607825)`);let T={...w,...v},x=Object.values(T),G=await d.put({ibGibs:x,space:c,force:i});if(!G.success||G.errorMsg)throw new Error(`there was an error putting the export's timeline ibgibs into the space (${c.ib}). error: ${G.errorMsg||"[unknown error (E: be4a28961574765798c8d3686ae89c25)]"} (E: 066796a23da3c9f748558fd25bfdf525)`);if(!o){let S=Se({ibGibs:x}),N=Object.values(S);for(let P of N){let $=P.at(-1);if(!$)throw new Error("(UNEXPECTED) latestInTimeline falsy? this would mean that we had an empty timeline, and this doesn't make sense... (E: 3bec09e79768cc39d8029f4fe3af9825)");let F=await d.getLatestAddr({ibGib:$,space:c});!1||await d.registerNewIbGib({ibGib:$,space:c})}}}throw new Error("not implemented (E: 66c308e420e848c8d7cd01c8fddf8425)")}catch(d){throw console.error(`${a} ${E(d)}`),d}finally{R&&console.log(`${a} complete.`)}}},Qt=class extends Qe{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=B({ibGibAddr:g.addr}).gib;return(J({gib:b}).tjpGib??b)===h};var o=m;for(p(m,"tabInfoSharesTjpGib"),R&&console.log(`${i} starting... (I: 05015d78983488496dcca4fa36718725)`);!this.createdPromise;)await z(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&&_({ibGib:t})!==e)throw new Error("(UNEXPECTED) addr !== getIbGibAddr({ibGib})? (E: c99a94d8744e3a720cdbc094d53c4e25)");e??=_({ibGib:t});let a=await de(),d=await this.getLoadedChildInfo({addr:e,ibGib:t});if(d.active){console.log(`${i} same tab already active. returning early. childInfo.addr: ${d.addr} (user just clicked on the same tab) (I: e67c0d02f3143c49c7a20c82d0730225)`);return}let c=this.activeChildInfo;c&&(c.childBtnEl.classList.remove("active"),c.active=!1,s.innerHTML=""),d.childBtnEl.classList.add("active"),d.childBtnEl.scrollIntoView({behavior:"smooth"}),d.active=!0;let u=B({ibGibAddr:e}).gib,h=J({gib:u}).tjpGib??u;if(this.childInfos.some(g=>m(g))||this.childInfos.push(d),!d.component)throw new Error("(UNEXPECTED) childInfo.component falsy? should be populated by this point in code (E: 77abfd1e8cd395605d46716bd087fb25)");await a.inject({parentEl:s,componentToInject:d.component})}catch(s){throw console.error(`${i} ${E(s)}`),s}finally{R&&console.log(`${i} complete.`)}}},vi=class n extends Qt{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=_({ibGib:e}),o=H({ibGib:e,defaultIfNone:"incomingAddr"});if(!o)throw new Error(`(UNEXPECTED) tjpAddr false after incomingAddr default? ibGib: ${V(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: ${V(this.ibGib)} (E: ecea08dcacd198bb38cc44a860cc6825)`);if(!a.openChildTjpAddrs.includes(o))throw new Error(`${t} (UNEXPECTED) projectSettings didn't have the tjpAddr (${o})? projectSettings: ${V(a)} (E: genuuid)`);let d=a.openChildTjpAddrs.filter(g=>g!==o),c;if(a.activeChildTjpAddr===o)if(d.length>0){let g=a.openChildTjpAddrs.indexOf(o)-1;g<0&&(g=0),c=a.openChildTjpAddrs.at(g)}else c=this.tjpAddr,d.push(this.tjpAddr);let u=await Te({settingsType:this.settingsType,useCase:"current"}),f={...a,openChildTjpAddrs:d},h=await this.getMetaspace(),m=await Et({timeline:this.settings.ibGib,metaspace:h,mut8Opts:{dataToAddOrPatch:{sections:{[u]:f}}}});s.active&&await this.activateIbGib({addr:c}),this.childInfos=this.childInfos.filter(g=>g.addr!==s.addr),await this.removeTabBtn({tabInfo:s})}catch(i){throw console.error(`${t} ${E(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} ${E(t)}`),t}finally{R&&console.log(`${e} complete.`)}}},Ze=class extends Qe{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(oe,{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:d}){let c=`${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:d})}catch(u){throw console.error(`${c} ${E(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 Ol(n,e,t){let i=`[${Ol.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 wn({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} ${E(o)}`),o}}p(Ol,"initIbGibGlobalThis");function Eg(n,e,t){if(!globalThis.ibgib?.[n]){if(!e)throw new Error(`Global context not initialized and config not provided for key '${n}'.`);Ol(e,n,t)}return globalThis.ibgib[n]}p(Eg,"getIbGibGlobalThis_IbGibApp");function Ee(n){let e=p(async()=>k(),"fnGetMetaspace"),t=new Promise(async(i,o)=>{try{let s=1e5,a=0,d;do{if(n)d=Eg(n)?.bootstrapPromise;else if(d=globalThis.ibgib?.bootstrapPromise,!d&&globalThis.ibgib){let c=Object.keys(globalThis.ibgib);for(let u of c)if(globalThis.ibgib[u]?.bootstrapPromise){d=globalThis.ibgib[u].bootstrapPromise;break}}if(a++,a>s)break;await z(10)}while(d===void 0);if(!d){i();return}await d,i()}catch(s){o(s)}});return{fnGetMetaspace:e,bootstrapPromise:t}}p(Ee,"getComponentCtorArg");var Hl="ibgib-identity-header",Ii=class extends fe{static{p(this,"IdentityHeaderComponentMeta")}lc="[IdentityHeaderComponentMeta]";routeRegExp=new RegExp(`^${Hl}$`);componentName=Hl;constructor(){super(Ee()),customElements.get(this.componentName)||customElements.define(this.componentName,ws)}async createInstance({path:e,ibGibAddr:t}){let i=document.createElement(this.componentName);return await i.initialize({ibGibAddr:t,meta:this,html:wr,css:[me,Er]}),i}},ws=class extends Qe{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 k();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 Y().getKeystoneCommonInfo({addr:e,metaspace:i,space:o}),d={username:a?.name??"",description:a?.description??"",isPrimary:a?.isPrimary??!1};return this.keystoneCache.set(e,d),d}catch(s){return console.error(`${this.lc}[getKeystoneDetails] Registered keystone address ${e} not found in local browser space: ${E(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(Me,this._onRequestIdentityChange),window.addEventListener(Vt,this._onIdentityUpdateAvailable),window.addEventListener(Ce,this._onIdentityChanged),document.addEventListener("click",this._onDocumentClick),await this.resolveActiveIdentity(),await this.renderUI()}async loadKeystonesIndex(){let e=`${this.lc}[loadKeystonesIndex]`;try{let t=await k();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=_({ibGib:o}),await this.loadIbGib(),await this.initSettings())}catch(t){console.error(`${e} ${E(t)}`)}}async disconnected(){this._onRequestIdentityChange&&window.removeEventListener(Me,this._onRequestIdentityChange),this._onIdentityUpdateAvailable&&window.removeEventListener(Vt,this._onIdentityUpdateAvailable),this._onIdentityChanged&&window.removeEventListener(Ce,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 dt().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(Ce,{detail:{activeIdentityAddr:this.activeAddr},bubbles:!0,composed:!0}))}catch(s){console.error(`${t} ${E(s)}`),this.elements&&(this.elements.syncModalSpinnerEl.textContent="\u274C",this.elements.syncModalSpinnerEl.style.animation="none",this.elements.syncModalTitleEl.textContent="Update Failed",this.elements.syncModalMsgEl.textContent=E(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(oe,{detail:{action:"show-keystone-creator"},bubbles:!0,composed:!0}))}),this.elements.btnMenuSignInEl.addEventListener("click",e=>{e.stopPropagation(),this.closeDropdown(),window.dispatchEvent(new CustomEvent(oe,{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(oe,{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:ae.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}}),c=(await Promise.all(a)).filter(u=>u.isPrimary).map(u=>u.addr);if(o&&c.includes(o)?this.activeAddr=o:c.length>0?this.activeAddr=c[0]:this.activeAddr=null,this.activeAddr){let u=await k();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 y of Object.keys(b)){let w=b[y];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} ${E(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 d=cn({ibGibAddr:i});this.elements.identityAvatarEl.style.backgroundColor=d.tjpColor||d.punctiliarColor,this.elements.identityAvatarEl.style.color=d.tjpColorContrast||d.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=`
685
+ `: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} ${E(t)}`),t}finally{R&&console.log(`${e} complete.`)}}async connectedCallback_reconnectComponent(){let e=`${this.lc}[${this.connectedCallback_reconnectComponent.name}]`;try{R&&console.log(`${e} starting... (I: 7fccefbeff68c0dda15642ebaa1eb525)`),console.log(`${e} does nothing in base class (I: 724bc670d4ccb0fde2b2fa49830cd425)`)}catch(t){throw console.error(`${e} ${E(t)}`),t}finally{R&&console.log(`${e} complete.`)}}async disconnectedCallback(){let e=`${this.lc}[${this.disconnectedCallback.name}]`;try{R&&console.log(`${e} starting... (I: 6f3b25c23fb874b1ac513e8f0d1f4e25)`),await this.disconnected()}catch(t){throw console.error(`${e} ${E(t)}`),t}finally{R&&console.log(`${e} complete.`)}}async attributeChangedCallback(e,t,i){let o=`${this.lc}[attributeChangedCallback]`;R&&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{R&&console.log(`${e} starting... (I: 536989c9491b544105b6d01a688fbb25)`),await this.destroyed()}catch(t){throw console.error(`${e} ${E(t)}`),t}finally{R&&console.log(`${e} complete.`)}}async destroyed(){let e=`${this.lc}[${this.destroyed.name}]`;try{R&&console.log(`${e} starting... (I: f34f3ca04b06b1e00ebe04df22331125)`)}catch(t){throw console.error(`${e} ${E(t)}`),t}finally{R&&console.log(`${e} complete.`)}return R&&console.log(`${e} does nothing in the base class. (I: d9437f962e0aec40d69ad6159e7b5725)`),Promise.resolve()}async loadIbGib(e){let t=`${this.lc}[${this.loadIbGib.name}]`;try{R&&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(Ft({gib:B({ibGibAddr:this.ibGibAddr??Z}).gib})){R&&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 Ke;if(await d.initialized,!d.contextUpdated$)throw new Error("(UNEXPECTED) ibGibProxy.contextUpdated$ falsy? (E: 351dfc898d2c3da2d7928079cec14925)");if(d.contextUpdated$.subscribe(Ve({next:p(async h=>{let m=`${t}[ibGibProxy.contextUpdated$][next]`;R&&console.log(`${m} nextIbGib: ${V(h)} (I: 96c846357b94fda2cefa615aed88c325)`),await this.handleContextUpdated()},"next"),error:p(async h=>{debugger;console.error(`${t}[ibGibProxy.contextUpdated$][error] what up? ${E(h)}`)},"error")})),!d.newContextChild$)throw new Error("(UNEXPECTED) ibGibProxy.newContextChild$ falsy? (E: 2cbde5ab402cc6d81259c74d68bca725)");d.newContextChild$.subscribe(Ve({next:p(async h=>{let m=`${t}[ibGibProxy.contextUpdated$][next]`;R&&console.log(`${m} childIbGib: ${V(h)} (I: 96c846357b94fda2cefa615aed88c325)`),await this.handleNewContextChild({childIbGib:h})},"next"),error:p(async h=>{debugger;console.error(`${t}[ibGibProxy.contextUpdated$][error] what up? ${E(h)}`)},"error")}));let u=await d.witness(s),f=await d.witness(c);this.ibGibProxy=d,this.ibGibAddr=_({ibGib:d.ibGib})}catch(i){throw console.error(`${t} ${E(i)}`),i}finally{R&&console.log(`${t} complete.`)}}async handleContextUpdated(){let e=`${this.lc}[${this.handleContextUpdated.name}]`;try{let{ibGib:t}=this;this.ibGibAddr=t?_({ibGib:t}):Z,R&&console.log(`${e} context updated. this.ibGibAddr (I: 64e5876f58cc54b5af777c94f13a4325)`)}catch(t){throw console.error(`${e} ${E(t)}`),t}}async handleNewContextChild({childIbGib:e}){let t=`${this.lc}[${this.handleNewContextChild.name}]`;try{R&&console.log(`${t} child added to contextcontext updated. childIbGib: ${V(e)} (I: 07d02c9182c6629cbbacd39fd0ff7f25)`),console.log(_({ibGib:e}))}catch(i){throw console.error(`${t} ${E(i)}`),i}}async renderUI(){let e=`${this.lc}[${this.renderUI.name}]`;try{if(R&&console.log(`${e} starting... (I: 7e5704afe17fb937c8473e7801f56e25)`),this.ibGib){let{punctiliarColor:t,punctiliarColorTranslucent:i,punctiliarColorContrast:o,tjpColor:s,tjpColorTranslucent:a,tjpColorContrast:c,errorMsg:d}=hn({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} ${E(t)}`),t}finally{R&&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 Es({ibGib:this.ibGib,metaspace:i,space:o});if(s){let a=s.data.n;await s.setActiveContext({contextIbGib:this.ibGib,loggingInfo:this.lc}),await z(32);let c=s.data.n;a!==c&&console.warn(`${t} setting active context for agent changed agent.data.n.
686
+ agent.data: ${V(J({ibGib:s}))}
687
+ ibGib.data: ${J({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 (${_({ibGib:this.ibGib})}) (W: e4219903462baab438a23c786d714825)`);else throw new Error(`(UNEXPECTED) agent falsy? an agent should have been created and registered with the ibGib (${_({ibGib:this.ibGib})}) (E: 7182d1aa070b9578c78a5b8b401d8425)`)}catch(i){throw console.error(`${t} ${E(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 Ci({sectionName:await Te({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} ${E(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 Te({settingsType:e,useCase:t}),a=await Et({timeline:this.settings.ibGib,metaspace:await this.getMetaspace(),mut8Opts:{dataToAddOrPatch:{sections:{[s]:i}}}});await z(100)}catch(s){throw console.error(`${o} ${E(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 Te({settingsType:e,useCase:"current"});return Ci({sectionName:i,settingsIbGib:this.settings.ibGib})}catch(i){throw console.error(`${t} ${E(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(Ft({ibGib:this.ibGib})){console.error(`${e} this.ibGib is primitive, so what are we initializing settings for? (W: 9915089019b81c6935b32ae877095825)`);return}let o=await Is({ibGib:this.ibGib}),s=await pn({scope:o,ibGib:this.ibGib,metaspace:t,space:i});if(s||(s=(await Cs({scope:o,metaspace:t,space:i,saveInSpace:!0})).newIbGib,await Di({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 Ke;if(await a.setWrappedIbGib({ibGib:s,space:i}),this.settings=a,!await this.getCurrentSettings({settingsType:ce.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} ${E(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(Ft({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 lr({ibGib:e,compress:t,metaspace:o,space:s})}catch(o){throw console.error(`${i} ${E(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 ar({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){Ri;let g=[],b=[];Object.values(f).forEach(S=>{Ms({ibGib:S})?g.push(S):b.push(S)});let y=await c.put({ibGibs:g,isDna:!0,space:d,force:i});if(!y.success||y.errorMsg)throw new Error(`there was an error putting the export's dna ibgibs into the space (${d.ib}). error: ${y.errorMsg||"[unknown error (E: 7c7ef8d5281399b1d8f3fbeefba1b825)]"} (E: ce3e8b982208afc4889164ba20a31825)`);let{mapWithTjp_YesDna:w,mapWithTjp_NoDna:v,mapWithoutTjps:I}=Ri({ibGibs:b}),C=await c.put({ibGibs:Object.values(I),space:d,force:i});if(!C.success||C.errorMsg)throw new Error(`there was an error putting the export's non-dna stone ibgibs (no-tjp) into the space (${d.ib}). error: ${C.errorMsg||"[unknown error (E: dc17f8ee7aed5c445f8b827f274b0825)]"} (E: 9561364961e89c132818f6784a607825)`);let T={...w,...v},x=Object.values(T),N=await c.put({ibGibs:x,space:d,force:i});if(!N.success||N.errorMsg)throw new Error(`there was an error putting the export's timeline ibgibs into the space (${d.ib}). error: ${N.errorMsg||"[unknown error (E: be4a28961574765798c8d3686ae89c25)]"} (E: 066796a23da3c9f748558fd25bfdf525)`);if(!o){let S=Se({ibGibs:x}),G=Object.values(S);for(let P of G){let $=P.at(-1);if(!$)throw new Error("(UNEXPECTED) latestInTimeline falsy? this would mean that we had an empty timeline, and this doesn't make sense... (E: 3bec09e79768cc39d8029f4fe3af9825)");let F=await c.getLatestAddr({ibGib:$,space:d});!1||await c.registerNewIbGib({ibGib:$,space:d})}}}throw new Error("not implemented (E: 66c308e420e848c8d7cd01c8fddf8425)")}catch(c){throw console.error(`${a} ${E(c)}`),c}finally{R&&console.log(`${a} complete.`)}}},Zt=class extends Fe{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=B({ibGibAddr:g.addr}).gib;return(W({gib:b}).tjpGib??b)===h};var o=m;for(p(m,"tabInfoSharesTjpGib"),R&&console.log(`${i} starting... (I: 05015d78983488496dcca4fa36718725)`);!this.createdPromise;)await z(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&&_({ibGib:t})!==e)throw new Error("(UNEXPECTED) addr !== getIbGibAddr({ibGib})? (E: c99a94d8744e3a720cdbc094d53c4e25)");e??=_({ibGib:t});let a=await ne(),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=B({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} ${E(s)}`),s}finally{R&&console.log(`${i} complete.`)}}},Ti=class n extends Zt{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=_({ibGib:e}),o=H({ibGib:e,defaultIfNone:"incomingAddr"});if(!o)throw new Error(`(UNEXPECTED) tjpAddr false after incomingAddr default? ibGib: ${V(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: ${V(this.ibGib)} (E: ecea08dcacd198bb38cc44a860cc6825)`);if(!a.openChildTjpAddrs.includes(o))throw new Error(`${t} (UNEXPECTED) projectSettings didn't have the tjpAddr (${o})? projectSettings: ${V(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 Te({settingsType:this.settingsType,useCase:"current"}),f={...a,openChildTjpAddrs:c},h=await this.getMetaspace(),m=await Et({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} ${E(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} ${E(t)}`),t}finally{R&&console.log(`${e} complete.`)}}},Ze=class extends Fe{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} ${E(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 Xl(n,e,t){let i=`[${Xl.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 Tn({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} ${E(o)}`),o}}p(Xl,"initIbGibGlobalThis");function Ng(n,e,t){if(!globalThis.ibgib?.[n]){if(!e)throw new Error(`Global context not initialized and config not provided for key '${n}'.`);Xl(e,n,t)}return globalThis.ibgib[n]}p(Ng,"getIbGibGlobalThis_IbGibApp");function he(n){let e=p(async()=>k(),"fnGetMetaspace"),t=new Promise(async(i,o)=>{try{let s=1e5,a=0,c;do{if(n)c=Ng(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 z(10)}while(c===void 0);if(!c){i();return}await c,i()}catch(s){o(s)}});return{fnGetMetaspace:e,bootstrapPromise:t}}p(he,"getComponentCtorArg");var Ql="ibgib-identity-header",Si=class extends ae{static{p(this,"IdentityHeaderComponentMeta")}lc="[IdentityHeaderComponentMeta]";routeRegExp=new RegExp(`^${Ql}$`);componentName=Ql;constructor(){super(he()),customElements.get(this.componentName)||customElements.define(this.componentName,Ts)}async createInstance({path:e,ibGibAddr:t}){let i=document.createElement(this.componentName);return await i.initialize({ibGibAddr:t,meta:this,html:Ar,css:[ue,_r]}),i}},Ts=class extends Fe{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 k();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 Y().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: ${E(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(Me,this._onRequestIdentityChange),window.addEventListener(Vt,this._onIdentityUpdateAvailable),window.addEventListener(Ce,this._onIdentityChanged),document.addEventListener("click",this._onDocumentClick),await this.resolveActiveIdentity(),await this.renderUI()}async loadKeystonesIndex(){let e=`${this.lc}[loadKeystonesIndex]`;try{let t=await k();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=_({ibGib:o}),await this.loadIbGib(),await this.initSettings())}catch(t){console.error(`${e} ${E(t)}`)}}async disconnected(){this._onRequestIdentityChange&&window.removeEventListener(Me,this._onRequestIdentityChange),this._onIdentityUpdateAvailable&&window.removeEventListener(Vt,this._onIdentityUpdateAvailable),this._onIdentityChanged&&window.removeEventListener(Ce,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 ct().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(Ce,{detail:{activeIdentityAddr:this.activeAddr},bubbles:!0,composed:!0}))}catch(s){console.error(`${t} ${E(s)}`),this.elements&&(this.elements.syncModalSpinnerEl.textContent="\u274C",this.elements.syncModalSpinnerEl.style.animation="none",this.elements.syncModalTitleEl.textContent="Update Failed",this.elements.syncModalMsgEl.textContent=E(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:un},bubbles:!0,composed:!0}))}),this.elements.btnMenuSignInEl.addEventListener("click",e=>{e.stopPropagation(),this.closeDropdown(),window.dispatchEvent(new CustomEvent(se,{detail:{action:fn},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:dn},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:ce.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 k();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 y of Object.keys(b)){let w=b[y];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} ${E(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=hn({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
688
  <span class="icon">${o?"\u{1F7E2}":"\u26AA"}</span>
689
689
  <span class="identity-name">${i.username}</span>
690
690
  ${o?'<span class="identity-badge-active">Active</span>':""}
691
- `,s.addEventListener("click",a=>{a.stopPropagation(),this.closeDropdown(),o||window.dispatchEvent(new CustomEvent(Me,{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:ae.general,useCase:"current"})??{type:"general"};o.activeIdentityAddr=i,await this.updateSettings({settingsType:ae.general,useCase:"current",newSectionInfo:o}),await this.resolveActiveIdentity(),await this.renderUI(),window.dispatchEvent(new CustomEvent(Ce,{detail:{activeIdentityAddr:i},bubbles:!0,composed:!0}))}catch(o){console.error(`${t} ${E(o)}`)}}async handleContextUpdated(){await this.renderUI()}};var zl=`:host {
691
+ `,s.addEventListener("click",a=>{a.stopPropagation(),this.closeDropdown(),o||window.dispatchEvent(new CustomEvent(Me,{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:ce.general,useCase:"current"})??{type:"general"};o.activeIdentityAddr=i,await this.updateSettings({settingsType:ce.general,useCase:"current",newSectionInfo:o}),await this.resolveActiveIdentity(),await this.renderUI(),window.dispatchEvent(new CustomEvent(Ce,{detail:{activeIdentityAddr:i},bubbles:!0,composed:!0}))}catch(o){console.error(`${t} ${E(o)}`)}}async handleContextUpdated(){await this.renderUI()}};var Zl=`:host {
692
692
  display: block;
693
693
  width: 100%;
694
694
  max-width: 100%;
@@ -865,7 +865,7 @@ h2 {
865
865
 
866
866
  .close-tab-button:hover {
867
867
  color: var(--clr-danger, #ff5555) !important;
868
- }`;var Kl=`<div id="container" class="component-container">
868
+ }`;var jl=`<div id="container" class="component-container">
869
869
  <header id="identity-manager-header">
870
870
  <h2 id="title">Identity Manager</h2>
871
871
  <div class="tabs-row">
@@ -883,8 +883,8 @@ h2 {
883
883
  <button id="btn-create-placeholder" class="action-btn">Create/Load Identity</button>
884
884
  </div>
885
885
  </div>
886
- </div>`;var Jl="ibgib-identity-manager",Ci=class extends fe{static{p(this,"IdentityManagerComponentMeta")}lc="[IdentityManagerComponentMeta]";routeRegExp=new RegExp(`^${Jl}$`);componentName=Jl;constructor(){super(Ee()),customElements.get(this.componentName)||customElements.define(this.componentName,vs)}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:Kl,css:[me,zl]}),o}},vs=class extends vi{static{p(this,"IdentityManagerComponentInstance")}lc="[IdentityManagerComponentInstance]";globalActiveAddr=null;_onIdentityChanged=null;_onUiMessage=null;keystoneCache=new Map;metaspace;get settingsType(){return ae.identityManager}constructor(){super()}async getKeystoneDetails(e){let t=this.keystoneCache.get(e);if(t)return t;let i=await k();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 Y().getKeystoneCommonInfo({addr:e,metaspace:i,space:o});if(a){let d={username:a.name,description:a.description,isPrimary:a.isPrimary,n:a.n};return this.keystoneCache.set(e,d),d}}catch(s){console.warn(`Error getting details for keystone ${e}: ${E(s)}`)}return{username:"",description:"",isPrimary:!1,n:0}}async initialize(e){this.metaspace||(this.metaspace=await k({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: ${E(o)}`)}}await this.renderUI()},window.addEventListener(Ce,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(oe,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(oe,this._onUiMessage),this.ibGibAddr===j||!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}=B({ibGibAddr:i});return!!o&&o!=="gib"&&o!=="^"});if(t.length!==(e.openChildTjpAddrs??[]).length){e.openChildTjpAddrs=t;let i=await k();if(i){let o=await Te({settingsType:this.settingsType,useCase:"current"});await Et({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(Ce,this._onIdentityChanged),this._onIdentityChanged=null),this._onUiMessage&&(window.removeEventListener(oe,this._onUiMessage),this._onUiMessage=null)}async loadKeystonesIndex(){let e=`${this.lc}[loadKeystonesIndex]`;try{let t=await k();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=_({ibGib:o}),await this.loadIbGib({getLatest:!0}),await this.initSettings())}catch(t){console.error(`${e} ${E(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 de()).getComponentInstance({path:e,ibGibAddr:j,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 d=this.activeChildInfo;d&&(d.childBtnEl.classList.remove("active"),d.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} ${E(i)}`)}}async resolveActiveIdentity(){let e=`${this.lc}[resolveActiveIdentity]`;try{if(!this.settings){this.globalActiveAddr=null;return}let i=(await this.getSettings({settingsType:ae.general,useCase:"current"}))?.activeIdentityAddr,s=(this.ibGib?.rel8ns?.keystone??[]).map(async c=>{let u=await this.getKeystoneDetails(c);return{addr:c,isPrimary:u?.isPrimary??!1}}),d=(await Promise.all(s)).filter(c=>c.isPrimary).map(c=>c.addr);i&&d.includes(i)?this.globalActiveAddr=i:d.length>0?this.globalActiveAddr=d[0]:this.globalActiveAddr=null}catch(t){console.error(`${e} ${E(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:d}=B({ibGibAddr:a});return!!d&&d!=="gib"&&d!=="^"}).map(async a=>{let d=await this.getKeystoneDetails(a);return{addr:a,isPrimary:d?.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(Ri))throw new Error(`ibGib.ib (${t.ib}) does not start with keystone atom (${Ri}) (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=H({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 d=await k();if(d){let c=await Te({settingsType:this.settingsType,useCase:"current"});await Et({timeline:this.settings.ibGib,metaspace:d,mut8Opts:{dataToAddOrPatch:{sections:{[c]:o}}}})}}}}await this.renderUI()}catch(o){console.error(`${i} ${E(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"||B({ibGibAddr:e}).gib==="^")throw new Error(`Cannot load child info for primitive address ${e}`);let o=J({ibGibAddr:e}).tjpGib??B({ibGibAddr:e}).gib,s=p(async()=>{let u=await(await de()).getComponentInstance({path:"ibgib-keystone-scrubber",ibGibAddr:e,useRegExpPrefilter:!0});if(!u)throw new Error("(UNEXPECTED) detailsComponent falsy?");return u},"fnCreateAndLoadChildComponent"),a,d=this.childInfos.filter(c=>(J({ibGibAddr:c.addr}).tjpGib??B({ibGibAddr:c.addr}).gib)===o);if(d.length>0){if(d.length!==1)throw new Error("(UNEXPECTED) filtered.length !== 1?");a=d[0],a.component||(a.component=await s())}else{let c=await s(),u=0;for(;!c.ibGib;)if(await z(100),u++,u>50){debugger;throw new Error("(UNEXPECTED) detailsComponent.ibGib falsy? didn't load? (E: de50689834124914f770520f1eccb826)")}t=c.ibGib,e=_({ibGib:t});let f=await this.addChild({addr:e,ibGib:t});a={addr:e,childBtnEl:f,component:c,active:!1},this.childInfos.push(a)}return a}catch(o){throw console.error(`${i} ${E(o)}`),o}}async addChild({addr:e,ibGib:t}){let i=`${this.lc}[addChild]`;try{if(e??=_({ibGib:t}),e==="^"||e==="gib"||B({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??=_({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 d=document.createElement("span");d.className="close-tab-button",d.textContent=" \xD7",d.style.marginLeft="0.5rem",d.style.cursor="pointer",s.appendChild(d),d.addEventListener("click",async c=>{c.stopPropagation(),await this.closeTab({ibGib:t})})}return o.appendChild(s),s.addEventListener("click",async d=>{await this.activateIbGib({addr:e})}),s}catch(o){throw console.error(`${i} ${E(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 c=i;c.length>12&&(c=c.substring(0,5)+"..."+c.substring(c.length-4)),e.textContent=c}let d=[];if(o.username&&d.push(`User: ${o.username}`),o.description){let c=o.description.length>100?o.description.substring(0,97)+"...":o.description;d.push(`Desc: ${c}`)}d.push(`Addr: ${i}`),e.title=d.join(`
887
- `)}async removeTabBtn({tabInfo:e}){this.elements.tabsListEl.removeChild(e.childBtnEl)}};var Wl=`:host {
886
+ </div>`;var ec="ibgib-identity-manager",_i=class extends ae{static{p(this,"IdentityManagerComponentMeta")}lc="[IdentityManagerComponentMeta]";routeRegExp=new RegExp(`^${ec}$`);componentName=ec;constructor(){super(he()),customElements.get(this.componentName)||customElements.define(this.componentName,Ss)}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:jl,css:[ue,Zl]}),o}},Ss=class extends Ti{static{p(this,"IdentityManagerComponentInstance")}lc="[IdentityManagerComponentInstance]";globalActiveAddr=null;_onIdentityChanged=null;_onUiMessage=null;keystoneCache=new Map;metaspace;get settingsType(){return ce.identityManager}constructor(){super()}async getKeystoneDetails(e){let t=this.keystoneCache.get(e);if(t)return t;let i=await k();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 Y().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}: ${E(s)}`)}return{username:"",description:"",isPrimary:!1,n:0}}async initialize(e){this.metaspace||(this.metaspace=await k({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: ${E(o)}`)}}await this.renderUI()},window.addEventListener(Ce,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===Z||!this.ibGib?await this.loadKeystonesIndex():await this.initSettings(),await this.renderUI(),this.restoreOrInitTabs()}async restoreOrInitTabs(){let e=await this.getSettings({settingsType:this.settingsType,useCase:"current"});if(e){let t=(e.openChildTjpAddrs??[]).filter(i=>{if(!i||i==="^"||i==="gib")return!1;let{gib:o}=B({ibGibAddr:i});return!!o&&o!=="gib"&&o!=="^"});if(t.length!==(e.openChildTjpAddrs??[]).length){e.openChildTjpAddrs=t;let i=await k();if(i){let o=await Te({settingsType:this.settingsType,useCase:"current"});await Et({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(Ce,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 k();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=_({ibGib:o}),await this.loadIbGib({getLatest:!0}),await this.initSettings())}catch(t){console.error(`${e} ${E(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 ne()).getComponentInstance({path:e,ibGibAddr:Z,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} ${E(i)}`)}}async resolveActiveIdentity(){let e=`${this.lc}[resolveActiveIdentity]`;try{if(!this.settings){this.globalActiveAddr=null;return}let i=(await this.getSettings({settingsType:ce.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} ${E(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}=B({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(Ui))throw new Error(`ibGib.ib (${t.ib}) does not start with keystone atom (${Ui}) (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=H({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 k();if(c){let d=await Te({settingsType:this.settingsType,useCase:"current"});await Et({timeline:this.settings.ibGib,metaspace:c,mut8Opts:{dataToAddOrPatch:{sections:{[d]:o}}}})}}}}await this.renderUI()}catch(o){console.error(`${i} ${E(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"||B({ibGibAddr:e}).gib==="^")throw new Error(`Cannot load child info for primitive address ${e}`);let o=W({ibGibAddr:e}).tjpGib??B({ibGibAddr:e}).gib,s=p(async()=>{let u=await(await ne()).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??B({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 z(100),u++,u>50){debugger;throw new Error("(UNEXPECTED) detailsComponent.ibGib falsy? didn't load? (E: de50689834124914f770520f1eccb826)")}t=d.ibGib,e=_({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} ${E(o)}`),o}}async addChild({addr:e,ibGib:t}){let i=`${this.lc}[addChild]`;try{if(e??=_({ibGib:t}),e==="^"||e==="gib"||B({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??=_({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} ${E(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(`
887
+ `)}async removeTabBtn({tabInfo:e}){this.elements.tabsListEl.removeChild(e.childBtnEl)}};var tc=`:host {
888
888
  display: block;
889
889
  width: 100%;
890
890
  margin: 1rem auto;
@@ -1111,7 +1111,7 @@ input::placeholder {
1111
1111
 
1112
1112
  .notice-body strong {
1113
1113
  color: #89b4fa;
1114
- }`;var Yl=`<div id="container" class="component-container">
1114
+ }`;var nc=`<div id="container" class="component-container">
1115
1115
  <h2 id="title">Create Account</h2>
1116
1116
 
1117
1117
  <!-- Mode Selector Tabs -->
@@ -1289,13 +1289,13 @@ input::placeholder {
1289
1289
  Identity keystones form part of the public graph for account discovery. Learn more in our <a id="link-privacy-policy" href="/privacy" target="_blank" rel="noopener" style="color: #89b4fa; text-decoration: underline;">Privacy Policy</a>.
1290
1290
  </div>
1291
1291
  </div>
1292
- </div>`;async function je({providerId:n,parentTjpAddr:e}){let t=`[${je.name}]`;try{let o=await D().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 d=await on(),c={providerId:n,parentTjpAddr:e,userNonce:d},u=btoa(JSON.stringify(c)),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(y=>{if(y.origin!==window.location.origin)return;let w=y.data;w&&w.type==="sso-oauth-callback"&&(window.removeEventListener("message",b),clearInterval(g),m({success:!0,code:w.code,stateObj:w.stateObj||c,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=E(i);return console.error(`${t} ${o}`),{success:!1,message:o}}}p(je,"executeSsoOAuthPopup");var Xl="ibgib-keystone-creator",Ti=class extends fe{static{p(this,"KeystoneCreatorComponentMeta")}lc="[KeystoneCreatorComponentMeta]";routeRegExp=new RegExp(`^${Xl}$`);componentName=Xl;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:Yl,css:[me,Wl]}),o}},Is=class extends Ze{static{p(this,"KeystoneCreatorComponentInstance")}lc="[KeystoneCreatorComponentInstance]";hasExistingIdentities=!1;resendCooldownInterval=null;constructor(){super()}async initialize(e){await super.initialize(e)}async disconnected(){this.resendCooldownInterval&&(clearInterval(this.resendCooldownInterval),this.resendCooldownInterval=null)}startResendCooldownTimer({btnId:e,durationSecs:t=30}){let i=this.shadowRoot?.getElementById(e);if(!i)return;this.resendCooldownInterval&&(clearInterval(this.resendCooldownInterval),this.resendCooldownInterval=null);let o=t;i.disabled=!0,i.textContent=`Resend Code (${o}s)`,this.resendCooldownInterval=setInterval(()=>{o-=1,o<=0?(clearInterval(this.resendCooldownInterval),this.resendCooldownInterval=null,i.disabled=!1,i.textContent="Resend Code"):i.textContent=`Resend Code (${o}s)`},1e3)}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.inputPasskeyUsername=this.shadowRoot.getElementById("input-passkey-username"),this.elements.inputPasskeyDescription=this.shadowRoot.getElementById("input-passkey-description"),this.elements.inputPasskeyEmail=this.shadowRoot.getElementById("input-passkey-email"),this.elements.inputPasskeyName=this.shadowRoot.getElementById("input-passkey-name"),this.elements.checkboxPasskeyMakeActive=this.shadowRoot.getElementById("checkbox-passkey-make-active"),this.elements.btnGeneratePasskey=this.shadowRoot.getElementById("btn-generate-passkey"),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 k(),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: ${E(i)}`),this.hasExistingIdentities=!1}let t=[this.elements.checkboxMakeActive,this.elements.checkboxPasskeyMakeActive];for(let i of t)i&&(this.hasExistingIdentities?(i.disabled=!1,i.title=""):(i.checked=!0,i.disabled=!0,i.title="At least one active identity is required."))}initHandlers(){let e=this.shadowRoot?.getElementById("tab-quick"),t=this.shadowRoot?.getElementById("tab-passkey"),i=this.shadowRoot?.getElementById("tab-password"),o=this.shadowRoot?.getElementById("panel-quick"),s=this.shadowRoot?.getElementById("panel-passkey"),a=this.shadowRoot?.getElementById("panel-password"),d=this.shadowRoot?.getElementById("subtitle-quick"),c=this.shadowRoot?.getElementById("subtitle-passkey"),u=this.shadowRoot?.getElementById("subtitle-password"),f=p(T=>{e?.classList.toggle("active",T==="quick"),t?.classList.toggle("active",T==="passkey"),i?.classList.toggle("active",T==="password"),o?.classList.toggle("hidden",T!=="quick"),s?.classList.toggle("hidden",T!=="passkey"),a?.classList.toggle("hidden",T!=="password"),d?.classList.toggle("hidden",T!=="quick"),c?.classList.toggle("hidden",T!=="passkey"),u?.classList.toggle("hidden",T!=="password")},"switchTab");e?.addEventListener("click",()=>f("quick")),t?.addEventListener("click",()=>f("passkey")),i?.addEventListener("click",()=>f("password")),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",T=>{T.preventDefault(),er({title:"Custom Email Sign-In",msg:`When you enter your email address, we dispatch a 6-digit one-time verification code to your inbox.
1292
+ </div>`;async function je({providerId:n,parentTjpAddr:e}){let t=`[${je.name}]`;try{let o=await D().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 sn(),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(y=>{if(y.origin!==window.location.origin)return;let w=y.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=E(i);return console.error(`${t} ${o}`),{success:!1,message:o}}}p(je,"executeSsoOAuthPopup");var ic="ibgib-keystone-creator",Ai=class extends ae{static{p(this,"KeystoneCreatorComponentMeta")}lc="[KeystoneCreatorComponentMeta]";routeRegExp=new RegExp(`^${ic}$`);componentName=ic;constructor(){super(he()),customElements.get(this.componentName)||customElements.define(this.componentName,_s)}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:nc,css:[ue,tc]}),o}},_s=class extends Ze{static{p(this,"KeystoneCreatorComponentInstance")}lc="[KeystoneCreatorComponentInstance]";hasExistingIdentities=!1;resendCooldownInterval=null;constructor(){super()}async initialize(e){await super.initialize(e)}async disconnected(){this.resendCooldownInterval&&(clearInterval(this.resendCooldownInterval),this.resendCooldownInterval=null)}startResendCooldownTimer({btnId:e,durationSecs:t=30}){let i=this.shadowRoot?.getElementById(e);if(!i)return;this.resendCooldownInterval&&(clearInterval(this.resendCooldownInterval),this.resendCooldownInterval=null);let o=t;i.disabled=!0,i.textContent=`Resend Code (${o}s)`,this.resendCooldownInterval=setInterval(()=>{o-=1,o<=0?(clearInterval(this.resendCooldownInterval),this.resendCooldownInterval=null,i.disabled=!1,i.textContent="Resend Code"):i.textContent=`Resend Code (${o}s)`},1e3)}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.inputPasskeyUsername=this.shadowRoot.getElementById("input-passkey-username"),this.elements.inputPasskeyDescription=this.shadowRoot.getElementById("input-passkey-description"),this.elements.inputPasskeyEmail=this.shadowRoot.getElementById("input-passkey-email"),this.elements.inputPasskeyName=this.shadowRoot.getElementById("input-passkey-name"),this.elements.checkboxPasskeyMakeActive=this.shadowRoot.getElementById("checkbox-passkey-make-active"),this.elements.btnGeneratePasskey=this.shadowRoot.getElementById("btn-generate-passkey"),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 k(),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: ${E(i)}`),this.hasExistingIdentities=!1}let t=[this.elements.checkboxMakeActive,this.elements.checkboxPasskeyMakeActive];for(let i of t)i&&(this.hasExistingIdentities?(i.disabled=!1,i.title=""):(i.checked=!0,i.disabled=!0,i.title="At least one active identity is required."))}initHandlers(){let e=this.shadowRoot?.getElementById("tab-quick"),t=this.shadowRoot?.getElementById("tab-passkey"),i=this.shadowRoot?.getElementById("tab-password"),o=this.shadowRoot?.getElementById("panel-quick"),s=this.shadowRoot?.getElementById("panel-passkey"),a=this.shadowRoot?.getElementById("panel-password"),c=this.shadowRoot?.getElementById("subtitle-quick"),d=this.shadowRoot?.getElementById("subtitle-passkey"),u=this.shadowRoot?.getElementById("subtitle-password"),f=p(T=>{e?.classList.toggle("active",T==="quick"),t?.classList.toggle("active",T==="passkey"),i?.classList.toggle("active",T==="password"),o?.classList.toggle("hidden",T!=="quick"),s?.classList.toggle("hidden",T!=="passkey"),a?.classList.toggle("hidden",T!=="password"),c?.classList.toggle("hidden",T!=="quick"),d?.classList.toggle("hidden",T!=="passkey"),u?.classList.toggle("hidden",T!=="password")},"switchTab");e?.addEventListener("click",()=>f("quick")),t?.addEventListener("click",()=>f("passkey")),i?.addEventListener("click",()=>f("password")),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",T=>{T.preventDefault(),rr({title:"Custom Email Sign-In",msg:`When you enter your email address, we dispatch a 6-digit one-time verification code to your inbox.
1293
1293
 
1294
- Entering the code creates your cryptographic identity delegate on your device and signs you in seamlessly without needing a password!`})});let b=this.shadowRoot?.getElementById("btn-quick-send-code"),y=this.shadowRoot?.getElementById("input-quick-email"),w=this.shadowRoot?.getElementById("section-quick-otp"),v=this.shadowRoot?.getElementById("input-quick-otp"),I=this.shadowRoot?.getElementById("btn-quick-verify-code"),C=this.shadowRoot?.getElementById("btn-quick-resend-code");b?.addEventListener("click",()=>this.handleQuickSendCode()),I?.addEventListener("click",()=>this.handleQuickVerifyCode()),C?.addEventListener("click",()=>this.handleQuickResendCode()),this.elements.btnGeneratePasskey?.addEventListener("click",()=>this.handleGeneratePasskey()),this.elements.btnGenerateEl.addEventListener("click",()=>this.handleGenerate()),this.shadowRoot.getElementById("btn-switch-sign-in")?.addEventListener("click",T=>{T.preventDefault(),window.dispatchEvent(new CustomEvent(oe,{detail:{action:"show-add-device"},bubbles:!0,composed:!0}))}),this.elements.inputPasskeyUsername?.addEventListener("input",()=>{this.elements.inputPasskeyUsername.classList.remove("invalid")}),this.elements.inputPasskeyDescription?.addEventListener("input",()=>{this.elements.inputPasskeyDescription.classList.remove("invalid")}),this.elements.inputPasskeyEmail?.addEventListener("input",()=>{this.elements.inputPasskeyEmail.classList.remove("invalid")}),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}]`,i=e==="google"?"Google":e==="github"?"GitHub":e;this.setStatus(`Opening ${i} SSO authorization window...`,"info"),this.showBusy({isBusy:!0,title:`Connecting to ${i}...`,msg:`Opening ${i} SSO authorization window...
1295
- Please complete authorization in the popup window.`,animationEmoji:"\u{1F310}"});try{let o=await je({providerId:e});if(!o.success||!o.code){this.setStatus(o.message||`${i} sign-in cancelled.`,"error");return}this.setStatus(`Exchanging ${i} authorization code...`,"info"),this.showBusy({isBusy:!0,title:"Exchanging SSO Code...",msg:`Validating ${i} authorization code with custodian server...`,animationEmoji:"\u{1F510}"});let s=D(),a=await s.postSsoLogin({code:o.code,providerId:e,redirectUri:o.redirectUri});if(!a.success||!a.primaryTjpAddr||!a.custodianReqs){this.setStatus(a.message||`${i} login failed.`,"error");return}let{primaryTjpAddr:d,custodianReqs:c}=a;this.setStatus("Deriving local device delegate keys...","info"),this.showBusy({isBusy:!0,title:"Creating Sync Delegate...",msg:"Generating cryptographic sync delegate keys...",animationEmoji:"\u{1F511}"});let u=await k(),f=await u.getLocalUserSpace({lock:!1});if(!f){this.setStatus("Could not access local user space.","error");return}let h=a.userInfo?.email||"",m=h?h.split("@")[0]:"user",{delegateKeystone:g,delegateSecret:b}=await mn({providerId:e,username:m,primaryTjpAddr:d,custodianReqs:c,metaspace:u,space:f});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 y=await s.postCustodianRegisterDelegate({delegateKeystone:g});if(!y.success){this.setStatus(y.message||"Custodian delegate registration failed.","error");return}await this.finalizeIdentityOnboarding({primaryKeystone:y.evolvedPrimaryKeystone||a.primaryKeystone,primaryGraph:y.primaryGraph||a.primaryGraph,delegateKeystone:g,primaryTjpAddr:d,delegateSecret:b,makeActive:!0})}catch(o){let s=E(o);console.error(`${t} ${s}`,o),this.setStatus(`SSO sign-in error: ${s}`,"error")}finally{this.showBusy({isBusy:!1})}}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||!st(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 D().postVerificationCode({email:s});a.success?(o?.classList.remove("hidden"),this.setStatus("\u2709\uFE0F 6-digit verification code sent to your email!","success"),this.startResendCooldownTimer({btnId:"btn-quick-resend-code",durationSecs:30})):this.setStatus(a.message||"Failed to dispatch verification code.","error")}catch(a){let d=E(a);console.error(`${e} ${d}`),this.setStatus(`Failed to dispatch verification code: ${d}`,"error")}finally{t&&(t.disabled=!1,t.textContent="Send 6-Digit Verification Code")}}async handleQuickResendCode(){let e=`${this.lc}[${this.handleQuickResendCode.name}]`,t=this.shadowRoot?.getElementById("btn-quick-resend-code"),i=this.shadowRoot?.getElementById("input-quick-email"),o=this.shadowRoot?.getElementById("input-quick-otp"),s=(i?.value||"").trim();if(!s||!st(s)){this.setStatus("Please enter a valid email address.","error");return}t&&(t.disabled=!0,t.textContent="Sending..."),this.setStatus("Resending verification code...","info");try{let a=await D().postVerificationCode({email:s});a.success?(this.setStatus(`\u2709\uFE0F Fresh 6-digit verification code sent to ${s}!`,"success"),this.startResendCooldownTimer({btnId:"btn-quick-resend-code",durationSecs:30}),o&&(o.value="",o.focus())):(this.setStatus(a.message||"Failed to resend verification code.","error"),t&&(t.disabled=!1,t.textContent="Resend Code"))}catch(a){let d=E(a);console.error(`${e} ${d}`),this.setStatus(`Failed to resend verification code: ${d}`,"error"),t&&(t.disabled=!1,t.textContent="Resend 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...
1296
- (Validating code, promoting server domain space, other security stuff...)`,animationEmoji:"\u{1F510}"});try{let d=await D().postCustodianGenesis({email:s,code:a});if(!d.success||!d.primaryTjpAddr||!d.custodianReqs){this.setStatus(d.message||"Custodian verification failed.","error");return}let c=d.primaryTjpAddr,u=d.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 k(),h=await f.getLocalUserSpace({lock:!1});if(!h){this.setStatus("Failed to access local user space.","error");return}let{delegateKeystone:m,delegateSecret:g}=await Zs({email:s,primaryTjpAddr:c,custodianReqs:u,metaspace:f,space:h});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 b=await D().postCustodianRegisterDelegate({delegateKeystone:m});if(!b.success){this.setStatus(b.message||"Failed to register delegate with custodian server.","error");return}await this.finalizeIdentityOnboarding({primaryKeystone:b.evolvedPrimaryKeystone||d.primaryKeystone,primaryGraph:b.primaryGraph||d.primaryGraph,delegateKeystone:m,primaryTjpAddr:c,delegateSecret:g,makeActive:!0})}catch(d){let c=E(d);console.error(`${e} ${c}`,d),this.setStatus(`Error: ${c}`,"error")}finally{this.showBusy({isBusy:!1}),o&&(o.disabled=!1,o.textContent="Verify Code")}}async handleGeneratePasskey(){let e=`${this.lc}[${this.handleGeneratePasskey.name}]`,t=this.shadowRoot?.getElementById("btn-generate-passkey");try{console.log(`${e} starting passkey genesis orchestration...`);let i=500;this.setStatus("Initializing passkey genesis...","info");let o=this.elements.inputPasskeyUsername,s=this.elements.inputPasskeyDescription,a=this.elements.inputPasskeyEmail,d=this.elements.inputPasskeyName,c=this.elements.checkboxPasskeyMakeActive,u=(o?.value||"").trim();if(o&&(o.value=u),!this.validateInputPattern({input:o,pattern:qt,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 f=(s?.value||"").trim();if(s&&(s.value=f),s&&!this.validateInputPattern({input:s,pattern:Di,errorMessage:"Description must be 0-128 characters.",required:!1})){this.setStatus("Invalid description. Max 128 chars.","error");return}let h=(a?.value||"").trim();if(a&&(a.value=h),h&&!st(h)){a?.classList.add("invalid"),this.setStatus("Invalid email address format.","error");return}if(t&&(t.disabled=!0,t.textContent="Awaiting Biometrics / Security Key..."),h){this.showBusy({isBusy:!0,title:"Checking Email Availability...",msg:"Checking server identity index...",animationEmoji:"\u{1F50D}"});let le=await D().checkEmailAvailability({email:h});if(!le.available){let He=le.message||"Email/Identity is already registered.";this.setStatus(He,"error"),this.showBusy({isBusy:!1}),t&&(t.disabled=!1,t.textContent="\u{1F6E1}\uFE0F Create Identity with Passkey / Biometrics");return}}this.showBusy({isBusy:!0,title:"Touch Biometrics or Security Key",msg:"Please touch your fingerprint sensor, Face ID, or insert your USB security key when prompted...",animationEmoji:"\u{1F6E1}\uFE0F"});let g=this.shadowRoot?.querySelector("#select-passkey-attachment")?.value,b=g==="cross-platform"||g==="platform"?g:void 0,y=crypto.getRandomValues(new Uint8Array(32)),w=gn(y.buffer),v=await bn({username:u,displayName:u,salt:w,authenticatorAttachment:b,userVerification:"preferred"}),{credentialId:I,transports:C}=v,T=v.passkeySecret;T||(T=(await yn({credentialId:I,salt:w,transports:C,userVerification:"preferred"})).passkeySecret);let x=(d?.value||"").trim()||at(),S=`passkey-manage-${bt({text:x,length:12,keepLiterals:["-"]})||"key"}`,N={credentialId:I,poolId:S,name:x,salt:w,createdUTC:new Date().toISOString(),...C&&C.length>0?{transports:C}:{}};this.showBusy({isBusy:!0,title:"Generating Identity...",msg:"Compiling sovereign passkey challenge pools...",animationEmoji:"\u2699\uFE0F"});let P="primary-profile.dev";if(!P||!P.trim())throw new Error("KEYSTONE_PROFILE_SOVEREIGN_PRIMARY environment variable is missing.");let $=Mi.buildKeystone(P.trim()).withUsername(u).withDescription(f);h&&$.withEmails([h]),$.withDetails({client:"space-gib-web",role:"domain-identity",passkeys:{[I]:N}});let F=await $.compileConfigs();for(let le of F)le.id==="manage"&&(le.id=S);let X=await k(),U=await X.getLocalUserSpace({lock:!1});if(!U){this.setStatus("Failed to access local user space.","error");return}this.showBusy({isBusy:!0,title:"Generating Identity...",msg:"Generating cryptographic domain identity keys...",animationEmoji:"\u{1F511}"});let ie=new Y,ve=await ie.genesis({masterSecret:T,emails:h?[h]:void 0,credentialIds:[I],configs:F,metaspace:X,space:U,frameDetails:$.getFrameDetails(),isPrimary:!0}),Z=H({ibGib:ve,defaultIfNone:"incomingAddr"});console.log(`${e} passkey local genesis complete: ${Z}`),await z(i),this.setStatus("Local genesis complete. Creating passkey sync delegate...","info"),this.showBusy({isBusy:!0,title:"Creating Sync Delegate...",msg:"Generating cryptographic sync delegate keys...",animationEmoji:"\u{1F511}"});let{delegateKeystone:he,deviceTag:Zt,delegateSecret:jt}=await En({username:u,primaryTjpAddr:Z,passkeySecret:T,transports:C,metaspace:X,space:U}),et=await ie.registerDelegate({parentKeystone:ve,delegateKeystone:he,masterSecret:T,signingPoolId:S,allowedVerbs:[Pe,Ge],deviceName:Zt,metaspace:X,space:U});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 en=await D().postGenesisKeystone(ve);if(!en.success){let le=`Sync failed: ${en.message}`;console.error(`${e} ${le}`),this.setStatus(le,"error"),this.showBusy({isBusy:!1}),t&&(t.disabled=!1,t.textContent="\u{1F6E1}\uFE0F Create Identity with Passkey / Biometrics");return}if(en.pending||en.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 le=Fe(this.shadowRoot,"section-code-verification"),He=Fe(this.shadowRoot,"input-verify-code"),mt=Fe(this.shadowRoot,"btn-submit-code"),tt=Fe(this.shadowRoot,"btn-resend-code");le.classList.remove("hidden"),le.scrollIntoView({behavior:"smooth",block:"nearest"}),this.setStatus("\u2709\uFE0F Verification code sent to your email. Enter 6-digit code below:","info"),this.startResendCooldownTimer({btnId:"btn-resend-code",durationSecs:30});let cd=p(async()=>{tt.disabled=!0,tt.textContent="Sending...",this.setStatus("Resending verification code to your email...","info");try{let gt=await D().postVerificationCode({email:h,primaryTjpAddr:Z});gt.success?(this.setStatus("\u2709\uFE0F Fresh 6-digit verification code sent to your email!","success"),this.startResendCooldownTimer({btnId:"btn-resend-code",durationSecs:30}),He.value="",He.focus()):(this.setStatus(gt.message||"Failed to resend verification code.","error"),tt.disabled=!1,tt.textContent="Resend Code")}catch(gt){let Lt=E(gt);console.error(`${e} ${Lt}`),this.setStatus(`Failed to resend verification code: ${Lt}`,"error"),tt.disabled=!1,tt.textContent="Resend Code"}},"onResendCode");tt.addEventListener("click",cd),await new Promise(gt=>{let Lt=p(async()=>{let tn=He.value.trim();if(!tn||tn.length!==6||!/^\d{6}$/.test(tn)){this.setStatus("Please enter a valid 6-digit numeric verification code (e.g. 482901).","error");return}mt.disabled=!0,mt.textContent="Verifying...",this.showBusy({isBusy:!0,title:"Verifying & Activating...",msg:`Great! Juust a moment...
1297
- (Validating code, promoting server domain space, other security stuff...)`,animationEmoji:"\u{1F510}"});let xs=await D().postVerifyCode({email:h,primaryTjpAddr:Z,code:tn});if(!xs.success){this.showBusy({isBusy:!1}),this.setStatus(xs.message||"Incorrect verification code.","error"),mt.disabled=!1,mt.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"}),mt.removeEventListener("click",Lt),le.classList.add("hidden"),this.setFormDisabled(!1);let Ps=await D().putEvolveKeystone({domainAddr:Z,keystoneIbGib:et,relatedKeystoneIbGibs:[he]});Ps.success||console.warn(`${e} Delegate sync warning after code verification: ${Ps.message}`),gt()},"onSubmitCode");mt.addEventListener("click",Lt)})}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 le=await D().putEvolveKeystone({domainAddr:Z,keystoneIbGib:et,relatedKeystoneIbGibs:[he]});if(!le.success){let He=`Delegate registration sync failed: ${le.message}`;console.error(`${e} ${He}`),this.setStatus(He,"error"),this.showBusy({isBusy:!1}),t&&(t.disabled=!1,t.textContent="\u{1F6E1}\uFE0F Create Identity with Passkey / Biometrics");return}}await this.finalizeIdentityOnboarding({primaryKeystone:et,delegateKeystone:he,primaryTjpAddr:Z,masterSecret:T,delegateSecret:jt,makeActive:c?.checked??!0})}catch(i){let o=E(i);console.error(`${e} ${o}`,i),this.setStatus(`Error: ${o}`,"error")}finally{this.showBusy({isBusy:!1}),t&&(t.disabled=!1,t.textContent="\u{1F6E1}\uFE0F Create Identity with Passkey / Biometrics")}}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:qt,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:Di,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&&!st(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 S=await D().checkEmailAvailability({email:s});if(!S.available){let N=S.message||"Email/Identity is already registered.";console.error(`${e} ${N}`),this.setStatus(N,"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 d="primary-profile.dev";if(!d||!d.trim())throw new Error('KEYSTONE_PROFILE_SOVEREIGN_PRIMARY environment variable is missing. Expected valid profile name like "primary-profile.dev" or "primary-profile.prod". (E: 3c4d5e6f7890123456789abcdef3)');console.log(`${e} Using sovereign primary keystone policy profile '${d}' (I: 90123456789abcdef0123456789abcde)`);let c=Mi.buildKeystone(d.trim()).withUsername(i).withDescription(o);s&&c.withEmails([s]),c.withDetails({client:"space-gib-web",role:"domain-identity"});let u=await c.compileConfigs(),f=await k(),h=await f.getLocalUserSpace({lock:!1});if(!h){this.setStatus("Failed to access local user space.","error");return}this.showBusy({isBusy:!0,title:"Generating Identity...",msg:"Generating cryptographic domain identity keys...",animationEmoji:"\u{1F511}"});let m=new Y,g=await m.genesis({masterSecret:a,emails:s?[s]:void 0,configs:u,metaspace:f,space:h,frameDetails:c.getFrameDetails(),isPrimary:!0}),b=H({ibGib:g,defaultIfNone:"incomingAddr"});console.log(`${e} local genesis complete: ${b}`),await z(t),this.setStatus("Local genesis complete. Creating sync delegate...","info"),console.log(`\u2713 Local genesis complete: ${b}`),this.showBusy({isBusy:!0,title:"Creating Sync Delegate...",msg:"Generating cryptographic sync delegate keys...",animationEmoji:"\u{1F511}"});let{delegateKeystone:y,deviceTag:w,delegateSecret:v}=await hn({username:i,primaryTjpAddr:b,masterSecret:a,metaspace:f,space:h}),I=_({ibGib:y});console.log(`${e} sync delegate genesis complete: ${I}`),await z(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 C=await m.registerDelegate({parentKeystone:g,delegateKeystone:y,masterSecret:a,signingPoolId:"manage",metaspace:f,space:h,allowedVerbs:[Pe,Ge],deviceName:w}),T=_({ibGib:C});console.log(`${e} delegate registered. evolved parent address: ${T}`),await z(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 x=await D().postGenesisKeystone(g);if(!x.success){let S=`Sync failed: ${x.message}`;console.error(`${e} ${S}`),this.setStatus(S,"error"),this.showBusy({isBusy:!1}),this.setButtonLoading(!1);return}if(x.pending||x.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 S=Fe(this.shadowRoot,"section-code-verification"),N=Fe(this.shadowRoot,"input-verify-code"),P=Fe(this.shadowRoot,"btn-submit-code"),$=Fe(this.shadowRoot,"btn-resend-code");S.classList.remove("hidden"),S.scrollIntoView({behavior:"smooth",block:"nearest"}),this.setStatus("\u2709\uFE0F Verification code sent to your email. Enter 6-digit code below:","info"),this.startResendCooldownTimer({btnId:"btn-resend-code",durationSecs:30});let F=p(async()=>{$.disabled=!0,$.textContent="Sending...",this.setStatus("Resending verification code to your email...","info");try{let X=await D().postVerificationCode({email:s,primaryTjpAddr:b});X.success?(this.setStatus("\u2709\uFE0F Fresh 6-digit verification code sent to your email!","success"),this.startResendCooldownTimer({btnId:"btn-resend-code",durationSecs:30}),N.value="",N.focus()):(this.setStatus(X.message||"Failed to resend verification code.","error"),$.disabled=!1,$.textContent="Resend Code")}catch(X){let U=E(X);console.error(`${e} ${U}`),this.setStatus(`Failed to resend verification code: ${U}`,"error"),$.disabled=!1,$.textContent="Resend Code"}},"onResendCode");$.addEventListener("click",F),await new Promise((X,U)=>{let ie=p(async()=>{let ve=N.value.trim();if(!ve||ve.length!==6||!/^\d{6}$/.test(ve)){this.setStatus("Please enter a valid 6-digit numeric verification code (e.g. 482901).","error");return}P.disabled=!0,P.textContent="Verifying...",this.showBusy({isBusy:!0,title:"Verifying & Activating...",msg:`Great! Juust a moment...
1298
- (Validating code, promoting server domain space, other security stuff...)`,animationEmoji:"\u{1F510}"});let Z=await D().postVerifyCode({email:s,primaryTjpAddr:b,code:ve});if(!Z.success){this.showBusy({isBusy:!1}),this.setStatus(Z.message||"Incorrect verification code.","error"),P.disabled=!1,P.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"}),P.removeEventListener("click",ie),S.classList.add("hidden"),this.setFormDisabled(!1);let he=await D().putEvolveKeystone({domainAddr:b,keystoneIbGib:C,relatedKeystoneIbGibs:[y]});he.success||console.warn(`${e} Delegate sync warning after code verification: ${he.message}`),X()},"onSubmitCode");P.addEventListener("click",ie)})}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 S=await D().putEvolveKeystone({domainAddr:b,keystoneIbGib:C,relatedKeystoneIbGibs:[y]});if(!S.success){let N=`Delegate registration sync failed: ${S.message}`;console.error(`${e} ${N}`),this.setStatus(N,"error"),this.showBusy({isBusy:!1}),this.setButtonLoading(!1);return}}await this.finalizeIdentityOnboarding({primaryKeystone:C,delegateKeystone:y,primaryTjpAddr:T,masterSecret:a,delegateSecret:v,makeActive:this.elements.checkboxMakeActive?.checked??!0})}catch(t){let i=E(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:d=!0}){let c=`${this.lc}[${this.finalizeIdentityOnboarding.name}]`,u=500,f=await k();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 y=Object.values(t);await f.put({ibGibs:y,space:h});let w=Se({ibGibs:y});for(let v of Object.keys(w))for(let I of w[v])await f.registerNewIbGib({ibGib:I,space:h})}else e&&(await f.put({ibGibs:[e],space:h}),await f.registerNewIbGib({ibGib:e,space:h}));let m=new Y;try{await m.getLatestKeystone({addr:o,metaspace:f,space:h})}catch(y){let w=`Primary identity keystone ${o} not found in local browser space! Error: ${E(y)}`;throw console.error(`${c} ${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=[W({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(W({ibGib:e})),await se({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),d&&window.dispatchEvent(new CustomEvent(Me,{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 z(u),this.elements?.keystoneAddrEl&&(this.elements.keystoneAddrEl.textContent=o),this.elements?.statusArea&&this.elements.statusArea.classList.remove("hidden"),this.setStatus(b,"success"),console.log(`${c} \u2713 ${b}`),this.elements?.inputSecret&&(this.elements.inputSecret.value=""),window.dispatchEvent(new CustomEvent(oe,{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 Ql=`:host {
1294
+ Entering the code creates your cryptographic identity delegate on your device and signs you in seamlessly without needing a password!`})});let b=this.shadowRoot?.getElementById("btn-quick-send-code"),y=this.shadowRoot?.getElementById("input-quick-email"),w=this.shadowRoot?.getElementById("section-quick-otp"),v=this.shadowRoot?.getElementById("input-quick-otp"),I=this.shadowRoot?.getElementById("btn-quick-verify-code"),C=this.shadowRoot?.getElementById("btn-quick-resend-code");b?.addEventListener("click",()=>this.handleQuickSendCode()),I?.addEventListener("click",()=>this.handleQuickVerifyCode()),C?.addEventListener("click",()=>this.handleQuickResendCode()),this.elements.btnGeneratePasskey?.addEventListener("click",()=>this.handleGeneratePasskey()),this.elements.btnGenerateEl.addEventListener("click",()=>this.handleGenerate()),this.shadowRoot.getElementById("btn-switch-sign-in")?.addEventListener("click",T=>{T.preventDefault(),window.dispatchEvent(new CustomEvent(se,{detail:{action:"show-add-device"},bubbles:!0,composed:!0}))}),this.elements.inputPasskeyUsername?.addEventListener("input",()=>{this.elements.inputPasskeyUsername.classList.remove("invalid")}),this.elements.inputPasskeyDescription?.addEventListener("input",()=>{this.elements.inputPasskeyDescription.classList.remove("invalid")}),this.elements.inputPasskeyEmail?.addEventListener("input",()=>{this.elements.inputPasskeyEmail.classList.remove("invalid")}),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}]`,i=e==="google"?"Google":e==="github"?"GitHub":e;this.setStatus(`Opening ${i} SSO authorization window...`,"info"),this.showBusy({isBusy:!0,title:`Connecting to ${i}...`,msg:`Opening ${i} SSO authorization window...
1295
+ Please complete authorization in the popup window.`,animationEmoji:"\u{1F310}"});try{let o=await je({providerId:e});if(!o.success||!o.code){this.setStatus(o.message||`${i} sign-in cancelled.`,"error");return}this.setStatus(`Exchanging ${i} authorization code...`,"info"),this.showBusy({isBusy:!0,title:"Exchanging SSO Code...",msg:`Validating ${i} authorization code with custodian server...`,animationEmoji:"\u{1F510}"});let s=D(),a=await s.postSsoLogin({code:o.code,providerId:e,redirectUri:o.redirectUri});if(!a.success||!a.primaryTjpAddr||!a.custodianReqs){this.setStatus(a.message||`${i} login failed.`,"error");return}let{primaryTjpAddr:c,custodianReqs:d}=a;this.setStatus("Deriving local device delegate keys...","info"),this.showBusy({isBusy:!0,title:"Creating Sync Delegate...",msg:"Generating cryptographic sync delegate keys...",animationEmoji:"\u{1F511}"});let u=await k(),f=await u.getLocalUserSpace({lock:!1});if(!f){this.setStatus("Could not access local user space.","error");return}let h=a.userInfo?.email||"",m=h?h.split("@")[0]:"user",{delegateKeystone:g,delegateSecret:b}=await En({providerId:e,username:m,primaryTjpAddr:c,custodianReqs:d,metaspace:u,space:f});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 y=await s.postCustodianRegisterDelegate({delegateKeystone:g});if(!y.success){this.setStatus(y.message||"Custodian delegate registration failed.","error");return}await this.finalizeIdentityOnboarding({primaryKeystone:y.evolvedPrimaryKeystone||a.primaryKeystone,primaryGraph:y.primaryGraph||a.primaryGraph,delegateKeystone:g,primaryTjpAddr:c,delegateSecret:b,makeActive:!0})}catch(o){let s=E(o);console.error(`${t} ${s}`,o),this.setStatus(`SSO sign-in error: ${s}`,"error")}finally{this.showBusy({isBusy:!1})}}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||!st(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 D().postVerificationCode({email:s});a.success?(o?.classList.remove("hidden"),this.setStatus("\u2709\uFE0F 6-digit verification code sent to your email!","success"),this.startResendCooldownTimer({btnId:"btn-quick-resend-code",durationSecs:30})):this.setStatus(a.message||"Failed to dispatch verification code.","error")}catch(a){let c=E(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 handleQuickResendCode(){let e=`${this.lc}[${this.handleQuickResendCode.name}]`,t=this.shadowRoot?.getElementById("btn-quick-resend-code"),i=this.shadowRoot?.getElementById("input-quick-email"),o=this.shadowRoot?.getElementById("input-quick-otp"),s=(i?.value||"").trim();if(!s||!st(s)){this.setStatus("Please enter a valid email address.","error");return}t&&(t.disabled=!0,t.textContent="Sending..."),this.setStatus("Resending verification code...","info");try{let a=await D().postVerificationCode({email:s});a.success?(this.setStatus(`\u2709\uFE0F Fresh 6-digit verification code sent to ${s}!`,"success"),this.startResendCooldownTimer({btnId:"btn-quick-resend-code",durationSecs:30}),o&&(o.value="",o.focus())):(this.setStatus(a.message||"Failed to resend verification code.","error"),t&&(t.disabled=!1,t.textContent="Resend Code"))}catch(a){let c=E(a);console.error(`${e} ${c}`),this.setStatus(`Failed to resend verification code: ${c}`,"error"),t&&(t.disabled=!1,t.textContent="Resend 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...
1296
+ (Validating code, promoting server domain space, other security stuff...)`,animationEmoji:"\u{1F510}"});try{let c=await D().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 k(),h=await f.getLocalUserSpace({lock:!1});if(!h){this.setStatus("Failed to access local user space.","error");return}let{delegateKeystone:m,delegateSecret:g}=await or({email:s,primaryTjpAddr:d,custodianReqs:u,metaspace:f,space:h});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 b=await D().postCustodianRegisterDelegate({delegateKeystone:m});if(!b.success){this.setStatus(b.message||"Failed to register delegate with custodian server.","error");return}await this.finalizeIdentityOnboarding({primaryKeystone:b.evolvedPrimaryKeystone||c.primaryKeystone,primaryGraph:b.primaryGraph||c.primaryGraph,delegateKeystone:m,primaryTjpAddr:d,delegateSecret:g,makeActive:!0})}catch(c){let d=E(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 handleGeneratePasskey(){let e=`${this.lc}[${this.handleGeneratePasskey.name}]`,t=this.shadowRoot?.getElementById("btn-generate-passkey");try{console.log(`${e} starting passkey genesis orchestration...`);let i=500;this.setStatus("Initializing passkey genesis...","info");let o=this.elements.inputPasskeyUsername,s=this.elements.inputPasskeyDescription,a=this.elements.inputPasskeyEmail,c=this.elements.inputPasskeyName,d=this.elements.checkboxPasskeyMakeActive,u=(o?.value||"").trim();if(o&&(o.value=u),!this.validateInputPattern({input:o,pattern:Ot,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 f=(s?.value||"").trim();if(s&&(s.value=f),s&&!this.validateInputPattern({input:s,pattern:Fi,errorMessage:"Description must be 0-128 characters.",required:!1})){this.setStatus("Invalid description. Max 128 chars.","error");return}let h=(a?.value||"").trim();if(a&&(a.value=h),h&&!st(h)){a?.classList.add("invalid"),this.setStatus("Invalid email address format.","error");return}if(t&&(t.disabled=!0,t.textContent="Awaiting Biometrics / Security Key..."),h){this.showBusy({isBusy:!0,title:"Checking Email Availability...",msg:"Checking server identity index...",animationEmoji:"\u{1F50D}"});let de=await D().checkEmailAvailability({email:h});if(!de.available){let ze=de.message||"Email/Identity is already registered.";this.setStatus(ze,"error"),this.showBusy({isBusy:!1}),t&&(t.disabled=!1,t.textContent="\u{1F6E1}\uFE0F Create Identity with Passkey / Biometrics");return}}this.showBusy({isBusy:!0,title:"Touch Biometrics or Security Key",msg:"Please touch your fingerprint sensor, Face ID, or insert your USB security key when prompted...",animationEmoji:"\u{1F6E1}\uFE0F"});let g=this.shadowRoot?.querySelector("#select-passkey-attachment")?.value,b=g==="cross-platform"||g==="platform"?g:void 0,y=crypto.getRandomValues(new Uint8Array(32)),w=wn(y.buffer),v=await vn({username:u,displayName:u,salt:w,authenticatorAttachment:b,userVerification:"preferred"}),{credentialId:I,transports:C}=v,T=v.passkeySecret;T||(T=(await In({credentialId:I,salt:w,transports:C,userVerification:"preferred"})).passkeySecret);let x=(c?.value||"").trim()||at(),S=`passkey-manage-${bt({text:x,length:12,keepLiterals:["-"]})||"key"}`,G={credentialId:I,poolId:S,name:x,salt:w,createdUTC:new Date().toISOString(),...C&&C.length>0?{transports:C}:{}};this.showBusy({isBusy:!0,title:"Generating Identity...",msg:"Compiling sovereign passkey challenge pools...",animationEmoji:"\u2699\uFE0F"});let P="primary-profile.dev";if(!P||!P.trim())throw new Error("KEYSTONE_PROFILE_SOVEREIGN_PRIMARY environment variable is missing.");let $=Bi.buildKeystone(P.trim()).withUsername(u).withDescription(f);h&&$.withEmails([h]),$.withDetails({client:"space-gib-web",role:"domain-identity",passkeys:{[I]:G}});let F=await $.compileConfigs();for(let de of F)de.id==="manage"&&(de.id=S);let X=await k(),U=await X.getLocalUserSpace({lock:!1});if(!U){this.setStatus("Failed to access local user space.","error");return}this.showBusy({isBusy:!0,title:"Generating Identity...",msg:"Generating cryptographic domain identity keys...",animationEmoji:"\u{1F511}"});let oe=new Y,ve=await oe.genesis({masterSecret:T,emails:h?[h]:void 0,credentialIds:[I],configs:F,metaspace:X,space:U,frameDetails:$.getFrameDetails(),isPrimary:!0}),j=H({ibGib:ve,defaultIfNone:"incomingAddr"});console.log(`${e} passkey local genesis complete: ${j}`),await z(i),this.setStatus("Local genesis complete. Creating passkey sync delegate...","info"),this.showBusy({isBusy:!0,title:"Creating Sync Delegate...",msg:"Generating cryptographic sync delegate keys...",animationEmoji:"\u{1F511}"});let{delegateKeystone:ge,deviceTag:jt,delegateSecret:en}=await Cn({username:u,primaryTjpAddr:j,passkeySecret:T,transports:C,metaspace:X,space:U}),et=await oe.registerDelegate({parentKeystone:ve,delegateKeystone:ge,masterSecret:T,signingPoolId:S,allowedVerbs:[Pe,Ne],deviceName:jt,metaspace:X,space:U});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 tn=await D().postGenesisKeystone(ve);if(!tn.success){let de=`Sync failed: ${tn.message}`;console.error(`${e} ${de}`),this.setStatus(de,"error"),this.showBusy({isBusy:!1}),t&&(t.disabled=!1,t.textContent="\u{1F6E1}\uFE0F Create Identity with Passkey / Biometrics");return}if(tn.pending||tn.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 de=Be(this.shadowRoot,"section-code-verification"),ze=Be(this.shadowRoot,"input-verify-code"),mt=Be(this.shadowRoot,"btn-submit-code"),tt=Be(this.shadowRoot,"btn-resend-code");de.classList.remove("hidden"),de.scrollIntoView({behavior:"smooth",block:"nearest"}),this.setStatus("\u2709\uFE0F Verification code sent to your email. Enter 6-digit code below:","info"),this.startResendCooldownTimer({btnId:"btn-resend-code",durationSecs:30});let vc=p(async()=>{tt.disabled=!0,tt.textContent="Sending...",this.setStatus("Resending verification code to your email...","info");try{let gt=await D().postVerificationCode({email:h,primaryTjpAddr:j});gt.success?(this.setStatus("\u2709\uFE0F Fresh 6-digit verification code sent to your email!","success"),this.startResendCooldownTimer({btnId:"btn-resend-code",durationSecs:30}),ze.value="",ze.focus()):(this.setStatus(gt.message||"Failed to resend verification code.","error"),tt.disabled=!1,tt.textContent="Resend Code")}catch(gt){let Lt=E(gt);console.error(`${e} ${Lt}`),this.setStatus(`Failed to resend verification code: ${Lt}`,"error"),tt.disabled=!1,tt.textContent="Resend Code"}},"onResendCode");tt.addEventListener("click",vc),await new Promise(gt=>{let Lt=p(async()=>{let nn=ze.value.trim();if(!nn||nn.length!==6||!/^\d{6}$/.test(nn)){this.setStatus("Please enter a valid 6-digit numeric verification code (e.g. 482901).","error");return}mt.disabled=!0,mt.textContent="Verifying...",this.showBusy({isBusy:!0,title:"Verifying & Activating...",msg:`Great! Juust a moment...
1297
+ (Validating code, promoting server domain space, other security stuff...)`,animationEmoji:"\u{1F510}"});let ks=await D().postVerifyCode({email:h,primaryTjpAddr:j,code:nn});if(!ks.success){this.showBusy({isBusy:!1}),this.setStatus(ks.message||"Incorrect verification code.","error"),mt.disabled=!1,mt.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"}),mt.removeEventListener("click",Lt),de.classList.add("hidden"),this.setFormDisabled(!1);let Rs=await D().putEvolveKeystone({domainAddr:j,keystoneIbGib:et,relatedKeystoneIbGibs:[ge]});Rs.success||console.warn(`${e} Delegate sync warning after code verification: ${Rs.message}`),gt()},"onSubmitCode");mt.addEventListener("click",Lt)})}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 de=await D().putEvolveKeystone({domainAddr:j,keystoneIbGib:et,relatedKeystoneIbGibs:[ge]});if(!de.success){let ze=`Delegate registration sync failed: ${de.message}`;console.error(`${e} ${ze}`),this.setStatus(ze,"error"),this.showBusy({isBusy:!1}),t&&(t.disabled=!1,t.textContent="\u{1F6E1}\uFE0F Create Identity with Passkey / Biometrics");return}}await this.finalizeIdentityOnboarding({primaryKeystone:et,delegateKeystone:ge,primaryTjpAddr:j,masterSecret:T,delegateSecret:en,makeActive:d?.checked??!0})}catch(i){let o=E(i);console.error(`${e} ${o}`,i),this.setStatus(`Error: ${o}`,"error")}finally{this.showBusy({isBusy:!1}),t&&(t.disabled=!1,t.textContent="\u{1F6E1}\uFE0F Create Identity with Passkey / Biometrics")}}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:Ot,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:Fi,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&&!st(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 S=await D().checkEmailAvailability({email:s});if(!S.available){let G=S.message||"Email/Identity is already registered.";console.error(`${e} ${G}`),this.setStatus(G,"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="primary-profile.dev";if(!c||!c.trim())throw new Error('KEYSTONE_PROFILE_SOVEREIGN_PRIMARY environment variable is missing. Expected valid profile name like "primary-profile.dev" or "primary-profile.prod". (E: 3c4d5e6f7890123456789abcdef3)');console.log(`${e} Using sovereign primary keystone policy profile '${c}' (I: 90123456789abcdef0123456789abcde)`);let d=Bi.buildKeystone(c.trim()).withUsername(i).withDescription(o);s&&d.withEmails([s]),d.withDetails({client:"space-gib-web",role:"domain-identity"});let u=await d.compileConfigs(),f=await k(),h=await f.getLocalUserSpace({lock:!1});if(!h){this.setStatus("Failed to access local user space.","error");return}this.showBusy({isBusy:!0,title:"Generating Identity...",msg:"Generating cryptographic domain identity keys...",animationEmoji:"\u{1F511}"});let m=new Y,g=await m.genesis({masterSecret:a,emails:s?[s]:void 0,configs:u,metaspace:f,space:h,frameDetails:d.getFrameDetails(),isPrimary:!0}),b=H({ibGib:g,defaultIfNone:"incomingAddr"});console.log(`${e} local genesis complete: ${b}`),await z(t),this.setStatus("Local genesis complete. Creating sync delegate...","info"),console.log(`\u2713 Local genesis complete: ${b}`),this.showBusy({isBusy:!0,title:"Creating Sync Delegate...",msg:"Generating cryptographic sync delegate keys...",animationEmoji:"\u{1F511}"});let{delegateKeystone:y,deviceTag:w,delegateSecret:v}=await yn({username:i,primaryTjpAddr:b,masterSecret:a,metaspace:f,space:h}),I=_({ibGib:y});console.log(`${e} sync delegate genesis complete: ${I}`),await z(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 C=await m.registerDelegate({parentKeystone:g,delegateKeystone:y,masterSecret:a,signingPoolId:"manage",metaspace:f,space:h,allowedVerbs:[Pe,Ne],deviceName:w}),T=_({ibGib:C});console.log(`${e} delegate registered. evolved parent address: ${T}`),await z(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 x=await D().postGenesisKeystone(g);if(!x.success){let S=`Sync failed: ${x.message}`;console.error(`${e} ${S}`),this.setStatus(S,"error"),this.showBusy({isBusy:!1}),this.setButtonLoading(!1);return}if(x.pending||x.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 S=Be(this.shadowRoot,"section-code-verification"),G=Be(this.shadowRoot,"input-verify-code"),P=Be(this.shadowRoot,"btn-submit-code"),$=Be(this.shadowRoot,"btn-resend-code");S.classList.remove("hidden"),S.scrollIntoView({behavior:"smooth",block:"nearest"}),this.setStatus("\u2709\uFE0F Verification code sent to your email. Enter 6-digit code below:","info"),this.startResendCooldownTimer({btnId:"btn-resend-code",durationSecs:30});let F=p(async()=>{$.disabled=!0,$.textContent="Sending...",this.setStatus("Resending verification code to your email...","info");try{let X=await D().postVerificationCode({email:s,primaryTjpAddr:b});X.success?(this.setStatus("\u2709\uFE0F Fresh 6-digit verification code sent to your email!","success"),this.startResendCooldownTimer({btnId:"btn-resend-code",durationSecs:30}),G.value="",G.focus()):(this.setStatus(X.message||"Failed to resend verification code.","error"),$.disabled=!1,$.textContent="Resend Code")}catch(X){let U=E(X);console.error(`${e} ${U}`),this.setStatus(`Failed to resend verification code: ${U}`,"error"),$.disabled=!1,$.textContent="Resend Code"}},"onResendCode");$.addEventListener("click",F),await new Promise((X,U)=>{let oe=p(async()=>{let ve=G.value.trim();if(!ve||ve.length!==6||!/^\d{6}$/.test(ve)){this.setStatus("Please enter a valid 6-digit numeric verification code (e.g. 482901).","error");return}P.disabled=!0,P.textContent="Verifying...",this.showBusy({isBusy:!0,title:"Verifying & Activating...",msg:`Great! Juust a moment...
1298
+ (Validating code, promoting server domain space, other security stuff...)`,animationEmoji:"\u{1F510}"});let j=await D().postVerifyCode({email:s,primaryTjpAddr:b,code:ve});if(!j.success){this.showBusy({isBusy:!1}),this.setStatus(j.message||"Incorrect verification code.","error"),P.disabled=!1,P.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"}),P.removeEventListener("click",oe),S.classList.add("hidden"),this.setFormDisabled(!1);let ge=await D().putEvolveKeystone({domainAddr:b,keystoneIbGib:C,relatedKeystoneIbGibs:[y]});ge.success||console.warn(`${e} Delegate sync warning after code verification: ${ge.message}`),X()},"onSubmitCode");P.addEventListener("click",oe)})}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 S=await D().putEvolveKeystone({domainAddr:b,keystoneIbGib:C,relatedKeystoneIbGibs:[y]});if(!S.success){let G=`Delegate registration sync failed: ${S.message}`;console.error(`${e} ${G}`),this.setStatus(G,"error"),this.showBusy({isBusy:!1}),this.setButtonLoading(!1);return}}await this.finalizeIdentityOnboarding({primaryKeystone:C,delegateKeystone:y,primaryTjpAddr:T,masterSecret:a,delegateSecret:v,makeActive:this.elements.checkboxMakeActive?.checked??!0})}catch(t){let i=E(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 k();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 y=Object.values(t);await f.put({ibGibs:y,space:h});let w=Se({ibGibs:y});for(let v of Object.keys(w))for(let I of w[v])await f.registerNewIbGib({ibGib:I,space:h})}else e&&(await f.put({ibGibs:[e],space:h}),await f.registerNewIbGib({ibGib:e,space:h}));let m=new Y;try{await m.getLatestKeystone({addr:o,metaspace:f,space:h})}catch(y){let w=`Primary identity keystone ${o} not found in local browser space! Error: ${E(y)}`;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=[J({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(J({ibGib:e})),await re({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(Me,{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 z(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}`),this.elements?.inputSecret&&(this.elements.inputSecret.value=""),window.dispatchEvent(new CustomEvent(se,{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 oc=`:host {
1299
1299
  display: block;
1300
1300
  width: 100%;
1301
1301
  max-width: 100%;
@@ -1916,7 +1916,7 @@ Please complete authorization in the popup window.`,animationEmoji:"\u{1F310}"})
1916
1916
  background: rgba(0, 0, 0, 0.5);
1917
1917
  box-shadow: 0 0 8px rgba(80, 250, 123, 0.15);
1918
1918
  }
1919
- `;var Zl=`<div id="container" class="component-container">
1919
+ `;var sc=`<div id="container" class="component-container">
1920
1920
  <div id="historical-warning-banner" class="warning-banner hidden">
1921
1921
  <span>\u26A0\uFE0F Viewing Historical Frame (Past State)</span>
1922
1922
  </div>
@@ -2124,7 +2124,7 @@ Please complete authorization in the popup window.`,animationEmoji:"\u{1F310}"})
2124
2124
  </div>
2125
2125
  </div>
2126
2126
  </div>
2127
- </div>`;var we=!1,jl="ibgib-keystone-details",Si=class extends fe{static{p(this,"KeystoneDetailsComponentMeta")}lc="[KeystoneDetailsComponentMeta]";routeRegExp=new RegExp(`^${jl}$`);componentName=jl;constructor(){super(Ee()),customElements.get(this.componentName)||customElements.define(this.componentName,Cs)}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:Zl,css:[me,Ql]}),o}},Cs=class extends Qe{static{p(this,"KeystoneDetailsComponentInstance")}lc="[KeystoneDetailsComponentInstance]";staticIbGib;get ibGib(){return this.staticIbGib}globalActiveAddr=null;isHistoricalFrame=!1;_onIdentityChanged=null;keystoneCache=new Map;aggregatedDetails;resendCooldownInterval=null;constructor(){super()}async initialize(e){let t=`${this.lc}[${this.initialize.name}]`;try{we&&console.log(`${t} starting... (I: 4c9328643a18e56b56e57292c87bd226)`),await super.initialize(e),await this.loadIbGib({getLatest:!1})}catch(i){throw console.error(`${t} ${E(i)}`),i}finally{we&&console.log(`${t} complete.`)}}async disconnected(){this._onIdentityChanged&&window.removeEventListener(Ce,this._onIdentityChanged),this.resendCooldownInterval&&(clearInterval(this.resendCooldownInterval),this.resendCooldownInterval=null)}startResendCooldownTimer(e=30){let t=this.elements?.btnResendAddPasswordOtpEl;if(!t)return;this.resendCooldownInterval&&(clearInterval(this.resendCooldownInterval),this.resendCooldownInterval=null);let i=e;t.disabled=!0,t.textContent=`Resend Code (${i}s)`,this.resendCooldownInterval=setInterval(()=>{i-=1,i<=0?(clearInterval(this.resendCooldownInterval),this.resendCooldownInterval=null,t.disabled=!1,t.textContent="Resend Code"):t.textContent=`Resend Code (${i}s)`},1e3)}async getKeystoneDetails(e){let t=this.keystoneCache.get(e);if(t)return t;let i=await k();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 Y().getKeystoneCommonInfo({addr:e,metaspace:i,space:o});if(a){let d={username:a.name,description:a.description,isPrimary:a.isPrimary,n:a.n};return this.keystoneCache.set(e,d),d}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}: ${E(s)}`)}return{username:"",description:"",isPrimary:!1,n:0}}async created(){let e=`${this.lc}[${this.created.name}]`;try{we&&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.passkeysCardEl=t.getElementById("passkeys-card"),this.elements.passkeysListEl=t.getElementById("passkeys-list"),this.elements.btnAddPasskeyEl=t.getElementById("btn-add-passkey"),this.elements.selectPasskeyAttachmentEl=t.getElementById("select-passkey-attachment"),this.elements.passkeyStatusMsgEl=t.getElementById("passkey-status-msg"),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.inputCurrentPasswordEl=t.getElementById("input-current-password"),this.elements.inputNewPasswordEl=t.getElementById("input-new-password"),this.elements.inputConfirmPasswordEl=t.getElementById("input-confirm-password"),this.elements.btnChangePasswordEl=t.getElementById("btn-change-password"),this.elements.changePasswordStatusEl=t.getElementById("change-password-status"),this.elements.changePasswordCardEl=t.getElementById("change-password-card"),this.elements.sectionAddPasswordOtpEl=t.getElementById("section-add-password-otp"),this.elements.inputAddPasswordOtpEl=t.getElementById("input-add-password-otp"),this.elements.btnResendAddPasswordOtpEl=t.getElementById("btn-resend-add-password-otp"),this.elements.descAddPasswordOtpEl=t.getElementById("desc-add-password-otp"),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(Ce,this._onIdentityChanged),await this.resolveActiveIdentity(),await this.loadIbGib({getLatest:!1})}catch(t){throw console.error(`${e} ${E(t)}`),t}finally{we&&console.log(`${e} complete.`)}}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.btnAddPasskeyEl?.addEventListener("click",()=>this.handleAddPasskey()),this.elements.btnLinkGoogleEl.addEventListener("click",()=>this.handleSSOClick("google")),this.elements.btnLinkGithubEl.addEventListener("click",()=>this.handleSSOClick("github")),this.elements.btnChangePasswordEl.addEventListener("click",()=>this.handleChangePassword()),this.elements.btnResendAddPasswordOtpEl?.addEventListener("click",()=>this.handleResendAddPasswordOtp())}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 k(),i=t?await t.getLocalUserSpace({lock:!1}):void 0,s=await dt().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} ${E(t)}`),this.setSyncStatus(`Check failed: ${E(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 k(),i=t?await t.getLocalUserSpace({lock:!1}):void 0,s=await dt().updateActiveKeystone({activePrimaryAddr:this.ibGibAddr,metaspace:t,space:i});if(s){let 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} ${E(t)}`),this.setSyncStatus(`Update failed: ${E(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: ${E(t)}`,"error")}}async handleSetActiveIdentity(){this.ibGibAddr&&window.dispatchEvent(new CustomEvent(Me,{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?_({ibGib:t}):null}catch(t){console.error(`${e} ${E(t)}`),this.globalActiveAddr=null}}async loadIbGib(e){let t=`${this.lc}[${this.loadIbGib.name}]`;try{if(we&&console.log(`${t} starting... (I: f0f7e8d52cbdc37bec844b2875996e26)`),!this.ibGibAddr)return;let i=await k();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 d=await i.getLatestAddr({addr:this.ibGibAddr,space:o});d&&(s=d,this.ibGibAddr=d)}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 c=a.rawResultIbGib?.data?.addrsNotFound??"unknown";throw new Error(`couldn't find address ${s}. addrsNotFound: ${c}? 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: ${E(i)} (E: a123456789abcdef0123456789c0003)`),i}finally{we&&console.log(`${t} complete.`)}}async renderUI(){let e=`${this.lc}[${this.renderUI.name}]`;try{we&&console.log(`${e} starting... (I: c8aa086352d8079708e00f78b6ac0826)`),await super.renderUI()}catch(t){throw console.error(`${e} ${E(t)}`),t}finally{we&&console.log(`${e} complete.`)}}updateActiveButtonState(){if(!this.elements)return;let e=J({ibGibAddr:this.ibGibAddr}).tjpGib??B({ibGibAddr:this.ibGibAddr}).gib,t=this.globalActiveAddr?J({ibGibAddr:this.globalActiveAddr}).tjpGib??B({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=this.aggregatedDetails?.custodianProvider||this.ibGib?.data?.frameDetails?.custodianProvider,s=this.ibGib?pn({keystone:this.ibGib,aggregatedDetails:this.aggregatedDetails,providerId:"google"}):!1,a=this.ibGib?pn({keystone:this.ibGib,aggregatedDetails:this.aggregatedDetails,providerId:"github"}):!1,d=this.ibGib?rt({keystone:this.ibGib,aggregatedDetails:this.aggregatedDetails}):void 0,c=this.elements.btnLinkGoogleEl,u=c.querySelector(".toggle-state-text");if(s){if(!d)throw new Error("(UNEXPECTED) isGoogleLinked but capabilities falsy? (E: cc62e8357b66860dd2cb8148c833b726)");c.classList.remove("unlinked"),c.classList.add("linked");let m=o==="google";m&&!d.isSovereign?(u.textContent="Google (Primary Account) \u{1F512}",c.title="Cannot unlink primary account without first adding a Master Password below."):m?(u.textContent="Google (Primary Account) \u2705",c.title="Click to unlink Google provider (requires Master Password)."):(u.textContent="Google Linked \u2705",c.title="Click to unlink Google provider.")}else c.classList.remove("linked"),c.classList.add("unlinked"),u.textContent="Unlinked",c.title="Click to link Google account.";let f=this.elements.btnLinkGithubEl,h=f.querySelector(".toggle-state-text");if(a){if(!d)throw new Error("(UNEXPECTED) isGithubLinked but capabilities falsy? (E: e94688210538e0e82878088873a46826)");f.classList.remove("unlinked"),f.classList.add("linked");let m=o==="github";m&&!d.isSovereign?(h.textContent="GitHub (Primary Account) \u{1F512}",f.title="Cannot unlink primary account without first adding a Master Password below."):m?(h.textContent="GitHub (Primary Account) \u2705",f.title="Click to unlink GitHub provider (requires Master Password)."):(h.textContent="GitHub Linked \u2705",f.title="Click to unlink GitHub provider.")}else f.classList.remove("linked"),f.classList.add("unlinked"),h.textContent="Unlinked",f.title="Click to link GitHub account."}}updatePasswordCardView(){let e=this.ibGib?rt({keystone:this.ibGib,aggregatedDetails:this.aggregatedDetails}):void 0,t=this.elements?.changePasswordCardEl?.querySelector("h3"),i=this.elements?.changePasswordCardEl?.querySelector(".description"),o=this.elements?.inputCurrentPasswordEl?.closest(".form-group"),s=this.elements?.btnChangePasswordEl;!!e?.hasPassword?(t&&(t.textContent="Change Password"),i&&(i.textContent="Rotate your local password that drives this identity. This will cryptographically evolve your primary identity and all registered user-owned delegate keystones to the new password."),o&&(o.style.display=""),s&&(s.textContent="Update Password")):(t&&(t.textContent="Add Master Password"),i&&(i.textContent="Establish a master password for this identity. This enables sovereign password authentication alongside your passkeys and linked providers."),o&&(o.style.display="none"),s&&(s.textContent="Add Master Password")),this.elements?.sectionAddPasswordOtpEl&&(this.elements.sectionAddPasswordOtpEl.classList.add("hidden"),this.elements.inputAddPasswordOtpEl&&(this.elements.inputAddPasswordOtpEl.value=""))}async updateFrameDetailsView(){let e=`${this.lc}[${this.updateFrameDetailsView.name}]`;try{if(we&&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?V(a):"{}";let d=!1,c=await k();if(c){let m=await c.getLocalUserSpace({lock:!1});if(m){try{let g=await c.getLatestAddr({addr:this.ibGibAddr,space:m});g&&g!==this.ibGibAddr&&(d=!0)}catch(g){console.warn(`${e} Error checking latest address: ${E(g)}`)}try{let b=await new Y().getAggregateDetails({latestKeystone:t,metaspace:c,space:m});this.aggregatedDetails=b,this.elements.identityAggrDetailsEl.textContent=b?V(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: ${E(g)}`),this.aggregatedDetails=void 0,this.elements.identityAggrDetailsEl.textContent="{}",this.elements.identityNameEl.textContent="-",this.elements.identityDescriptionEl.textContent="-"}}else this.aggregatedDetails=void 0,this.elements.identityAggrDetailsEl.textContent="{}",this.elements.identityNameEl.textContent="-",this.elements.identityDescriptionEl.textContent="-"}else this.aggregatedDetails=void 0,this.elements.identityAggrDetailsEl.textContent="{}",this.elements.identityNameEl.textContent="-",this.elements.identityDescriptionEl.textContent="-";this.isHistoricalFrame=d;let u=this.elements.historicalWarningBannerEl,f=this.elements.containerEl;u&&f&&(d?(u.classList.remove("hidden"),f.classList.add("is-historical")):(u.classList.add("hidden"),f.classList.remove("is-historical"))),this.elements.rawKeystoneJsonEl.textContent=V(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.passkeysCardEl.classList.remove("hidden"),await this.renderPasskeys(this.aggregatedDetails?.passkeys),this.elements.ssoLinkCardEl.classList.remove("hidden"),this.elements.changePasswordCardEl.classList.remove("hidden"),this.updatePasswordCardView()):(this.elements.delegatesCardEl.classList.add("hidden"),this.elements.passkeysCardEl.classList.add("hidden"),this.elements.ssoLinkCardEl.classList.add("hidden"),this.elements.changePasswordCardEl.classList.add("hidden")),this.updateActiveButtonState()}catch(t){throw console.error(`${e} ${E(t)}`),t}finally{we&&console.log(`${e} complete.`)}}clearActiveDetails(){this.elements&&(this.aggregatedDetails=void 0,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=""),this.elements.passkeysListEl&&(this.elements.passkeysListEl.innerHTML=""),this.elements.sectionAddPasswordOtpEl&&(this.elements.sectionAddPasswordOtpEl.classList.add("hidden"),this.elements.inputAddPasswordOtpEl&&(this.elements.inputAddPasswordOtpEl.value="")))}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||{},d=s.allowedVerbs||[],c=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`
2127
+ </div>`;var we=!1,rc="ibgib-keystone-details",xi=class extends ae{static{p(this,"KeystoneDetailsComponentMeta")}lc="[KeystoneDetailsComponentMeta]";routeRegExp=new RegExp(`^${rc}$`);componentName=rc;constructor(){super(he()),customElements.get(this.componentName)||customElements.define(this.componentName,As)}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:sc,css:[ue,oc]}),o}},As=class extends Fe{static{p(this,"KeystoneDetailsComponentInstance")}lc="[KeystoneDetailsComponentInstance]";staticIbGib;get ibGib(){return this.staticIbGib}globalActiveAddr=null;isHistoricalFrame=!1;_onIdentityChanged=null;keystoneCache=new Map;aggregatedDetails;resendCooldownInterval=null;constructor(){super()}async initialize(e){let t=`${this.lc}[${this.initialize.name}]`;try{we&&console.log(`${t} starting... (I: 4c9328643a18e56b56e57292c87bd226)`),await super.initialize(e),await this.loadIbGib({getLatest:!1})}catch(i){throw console.error(`${t} ${E(i)}`),i}finally{we&&console.log(`${t} complete.`)}}async disconnected(){this._onIdentityChanged&&window.removeEventListener(Ce,this._onIdentityChanged),this.resendCooldownInterval&&(clearInterval(this.resendCooldownInterval),this.resendCooldownInterval=null)}startResendCooldownTimer(e=30){let t=this.elements?.btnResendAddPasswordOtpEl;if(!t)return;this.resendCooldownInterval&&(clearInterval(this.resendCooldownInterval),this.resendCooldownInterval=null);let i=e;t.disabled=!0,t.textContent=`Resend Code (${i}s)`,this.resendCooldownInterval=setInterval(()=>{i-=1,i<=0?(clearInterval(this.resendCooldownInterval),this.resendCooldownInterval=null,t.disabled=!1,t.textContent="Resend Code"):t.textContent=`Resend Code (${i}s)`},1e3)}async getKeystoneDetails(e){let t=this.keystoneCache.get(e);if(t)return t;let i=await k();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 Y().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}: ${E(s)}`)}return{username:"",description:"",isPrimary:!1,n:0}}async created(){let e=`${this.lc}[${this.created.name}]`;try{we&&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.passkeysCardEl=t.getElementById("passkeys-card"),this.elements.passkeysListEl=t.getElementById("passkeys-list"),this.elements.btnAddPasskeyEl=t.getElementById("btn-add-passkey"),this.elements.selectPasskeyAttachmentEl=t.getElementById("select-passkey-attachment"),this.elements.passkeyStatusMsgEl=t.getElementById("passkey-status-msg"),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.inputCurrentPasswordEl=t.getElementById("input-current-password"),this.elements.inputNewPasswordEl=t.getElementById("input-new-password"),this.elements.inputConfirmPasswordEl=t.getElementById("input-confirm-password"),this.elements.btnChangePasswordEl=t.getElementById("btn-change-password"),this.elements.changePasswordStatusEl=t.getElementById("change-password-status"),this.elements.changePasswordCardEl=t.getElementById("change-password-card"),this.elements.sectionAddPasswordOtpEl=t.getElementById("section-add-password-otp"),this.elements.inputAddPasswordOtpEl=t.getElementById("input-add-password-otp"),this.elements.btnResendAddPasswordOtpEl=t.getElementById("btn-resend-add-password-otp"),this.elements.descAddPasswordOtpEl=t.getElementById("desc-add-password-otp"),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(Ce,this._onIdentityChanged),await this.resolveActiveIdentity(),await this.loadIbGib({getLatest:!1})}catch(t){throw console.error(`${e} ${E(t)}`),t}finally{we&&console.log(`${e} complete.`)}}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.btnAddPasskeyEl?.addEventListener("click",()=>this.handleAddPasskey()),this.elements.btnLinkGoogleEl.addEventListener("click",()=>this.handleSSOClick("google")),this.elements.btnLinkGithubEl.addEventListener("click",()=>this.handleSSOClick("github")),this.elements.btnChangePasswordEl.addEventListener("click",()=>this.handleChangePassword()),this.elements.btnResendAddPasswordOtpEl?.addEventListener("click",()=>this.handleResendAddPasswordOtp())}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 k(),i=t?await t.getLocalUserSpace({lock:!1}):void 0,s=await ct().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} ${E(t)}`),this.setSyncStatus(`Check failed: ${E(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 k(),i=t?await t.getLocalUserSpace({lock:!1}):void 0,s=await ct().updateActiveKeystone({activePrimaryAddr:this.ibGibAddr,metaspace:t,space:i});if(s){let 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} ${E(t)}`),this.setSyncStatus(`Update failed: ${E(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: ${E(t)}`,"error")}}async handleSetActiveIdentity(){this.ibGibAddr&&window.dispatchEvent(new CustomEvent(Me,{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?_({ibGib:t}):null}catch(t){console.error(`${e} ${E(t)}`),this.globalActiveAddr=null}}async loadIbGib(e){let t=`${this.lc}[${this.loadIbGib.name}]`;try{if(we&&console.log(`${t} starting... (I: f0f7e8d52cbdc37bec844b2875996e26)`),!this.ibGibAddr)return;let i=await k();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: ${E(i)} (E: a123456789abcdef0123456789c0003)`),i}finally{we&&console.log(`${t} complete.`)}}async renderUI(){let e=`${this.lc}[${this.renderUI.name}]`;try{we&&console.log(`${e} starting... (I: c8aa086352d8079708e00f78b6ac0826)`),await super.renderUI()}catch(t){throw console.error(`${e} ${E(t)}`),t}finally{we&&console.log(`${e} complete.`)}}updateActiveButtonState(){if(!this.elements)return;let e=W({ibGibAddr:this.ibGibAddr}).tjpGib??B({ibGibAddr:this.ibGibAddr}).gib,t=this.globalActiveAddr?W({ibGibAddr:this.globalActiveAddr}).tjpGib??B({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=this.aggregatedDetails?.custodianProvider||this.ibGib?.data?.frameDetails?.custodianProvider,s=this.ibGib?bn({keystone:this.ibGib,aggregatedDetails:this.aggregatedDetails,providerId:"google"}):!1,a=this.ibGib?bn({keystone:this.ibGib,aggregatedDetails:this.aggregatedDetails,providerId:"github"}):!1,c=this.ibGib?rt({keystone:this.ibGib,aggregatedDetails:this.aggregatedDetails}):void 0,d=this.elements.btnLinkGoogleEl,u=d.querySelector(".toggle-state-text");if(s){if(!c)throw new Error("(UNEXPECTED) isGoogleLinked but capabilities falsy? (E: cc62e8357b66860dd2cb8148c833b726)");d.classList.remove("unlinked"),d.classList.add("linked");let m=o==="google";m&&!c.isSovereign?(u.textContent="Google (Primary Account) \u{1F512}",d.title="Cannot unlink primary account without first adding a Master Password below."):m?(u.textContent="Google (Primary Account) \u2705",d.title="Click to unlink Google provider (requires Master Password)."):(u.textContent="Google Linked \u2705",d.title="Click to unlink Google provider.")}else d.classList.remove("linked"),d.classList.add("unlinked"),u.textContent="Unlinked",d.title="Click to link Google account.";let f=this.elements.btnLinkGithubEl,h=f.querySelector(".toggle-state-text");if(a){if(!c)throw new Error("(UNEXPECTED) isGithubLinked but capabilities falsy? (E: e94688210538e0e82878088873a46826)");f.classList.remove("unlinked"),f.classList.add("linked");let m=o==="github";m&&!c.isSovereign?(h.textContent="GitHub (Primary Account) \u{1F512}",f.title="Cannot unlink primary account without first adding a Master Password below."):m?(h.textContent="GitHub (Primary Account) \u2705",f.title="Click to unlink GitHub provider (requires Master Password)."):(h.textContent="GitHub Linked \u2705",f.title="Click to unlink GitHub provider.")}else f.classList.remove("linked"),f.classList.add("unlinked"),h.textContent="Unlinked",f.title="Click to link GitHub account."}}updatePasswordCardView(){let e=this.ibGib?rt({keystone:this.ibGib,aggregatedDetails:this.aggregatedDetails}):void 0,t=this.elements?.changePasswordCardEl?.querySelector("h3"),i=this.elements?.changePasswordCardEl?.querySelector(".description"),o=this.elements?.inputCurrentPasswordEl?.closest(".form-group"),s=this.elements?.btnChangePasswordEl;!!e?.hasPassword?(t&&(t.textContent="Change Password"),i&&(i.textContent="Rotate your local password that drives this identity. This will cryptographically evolve your primary identity and all registered user-owned delegate keystones to the new password."),o&&(o.style.display=""),s&&(s.textContent="Update Password")):(t&&(t.textContent="Add Master Password"),i&&(i.textContent="Establish a master password for this identity. This enables sovereign password authentication alongside your passkeys and linked providers."),o&&(o.style.display="none"),s&&(s.textContent="Add Master Password")),this.elements?.sectionAddPasswordOtpEl&&(this.elements.sectionAddPasswordOtpEl.classList.add("hidden"),this.elements.inputAddPasswordOtpEl&&(this.elements.inputAddPasswordOtpEl.value=""))}async updateFrameDetailsView(){let e=`${this.lc}[${this.updateFrameDetailsView.name}]`;try{if(we&&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?V(a):"{}";let c=!1,d=await k();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: ${E(g)}`)}try{let b=await new Y().getAggregateDetails({latestKeystone:t,metaspace:d,space:m});this.aggregatedDetails=b,this.elements.identityAggrDetailsEl.textContent=b?V(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: ${E(g)}`),this.aggregatedDetails=void 0,this.elements.identityAggrDetailsEl.textContent="{}",this.elements.identityNameEl.textContent="-",this.elements.identityDescriptionEl.textContent="-"}}else this.aggregatedDetails=void 0,this.elements.identityAggrDetailsEl.textContent="{}",this.elements.identityNameEl.textContent="-",this.elements.identityDescriptionEl.textContent="-"}else this.aggregatedDetails=void 0,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=V(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.passkeysCardEl.classList.remove("hidden"),await this.renderPasskeys(this.aggregatedDetails?.passkeys),this.elements.ssoLinkCardEl.classList.remove("hidden"),this.elements.changePasswordCardEl.classList.remove("hidden"),this.updatePasswordCardView()):(this.elements.delegatesCardEl.classList.add("hidden"),this.elements.passkeysCardEl.classList.add("hidden"),this.elements.ssoLinkCardEl.classList.add("hidden"),this.elements.changePasswordCardEl.classList.add("hidden")),this.updateActiveButtonState()}catch(t){throw console.error(`${e} ${E(t)}`),t}finally{we&&console.log(`${e} complete.`)}}clearActiveDetails(){this.elements&&(this.aggregatedDetails=void 0,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=""),this.elements.passkeysListEl&&(this.elements.passkeysListEl.innerHTML=""),this.elements.sectionAddPasswordOtpEl&&(this.elements.sectionAddPasswordOtpEl.classList.add("hidden"),this.elements.inputAddPasswordOtpEl&&(this.elements.inputAddPasswordOtpEl.value="")))}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`
2128
2128
  <div class="pool-challenge-item">
2129
2129
  <span class="challenge-id">${m}</span>
2130
2130
  <span class="challenge-hash" title="${g.hash||""}">${b}</span>
@@ -2137,7 +2137,7 @@ Please complete authorization in the popup window.`,animationEmoji:"\u{1F310}"})
2137
2137
  <div class="pool-grid">
2138
2138
  <div class="pool-field">
2139
2139
  <label>Verbs Allowed</label>
2140
- <span>${d.length>0?d.join(", "):"Any"}</span>
2140
+ <span>${c.length>0?c.join(", "):"Any"}</span>
2141
2141
  </div>
2142
2142
  <div class="pool-field">
2143
2143
  <label>FIFO / Random cost</label>
@@ -2147,7 +2147,7 @@ Please complete authorization in the popup window.`,animationEmoji:"\u{1F310}"})
2147
2147
 
2148
2148
  <!-- Collapsible Challenges List -->
2149
2149
  <details class="pool-details">
2150
- <summary class="pool-details-summary">Challenges (${c})</summary>
2150
+ <summary class="pool-details-summary">Challenges (${d})</summary>
2151
2151
  <div class="pool-challenges-list">
2152
2152
  ${h||'<p class="placeholder-text" style="padding: 0.5rem; text-align: center;">No challenges active.</p>'}
2153
2153
  </div>
@@ -2172,7 +2172,7 @@ Please complete authorization in the popup window.`,animationEmoji:"\u{1F310}"})
2172
2172
  width: 90%;
2173
2173
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.5);
2174
2174
  font-family: inherit;
2175
- `;let s=e.deviceName||e.details?.deviceTag||e.details?.name||"Device Delegate",a=e.username||e.name||e.details?.name||e.details?.username||"Remote Delegate",d=e.description||e.details?.description||"N/A",c=e.spaceId||e.details?.spaceId||"N/A",u=e.allowedVerbs?e.allowedVerbs.join(", "):"None",f=e.delegateTjpAddr||"N/A";o.innerHTML=`
2175
+ `;let s=e.deviceName||e.details?.deviceTag||e.details?.name||"Device Delegate",a=e.username||e.name||e.details?.name||e.details?.username||"Remote Delegate",c=e.description||e.details?.description||"N/A",d=e.spaceId||e.details?.spaceId||"N/A",u=e.allowedVerbs?e.allowedVerbs.join(", "):"None",f=e.delegateTjpAddr||"N/A";o.innerHTML=`
2176
2176
  <h3 style="margin-top: 0; display: flex; align-items: center; justify-content: space-between; gap: 0.5rem;">
2177
2177
  <span>Remote Delegate Metadata</span>
2178
2178
  <span class="badge badge-remote-device" style="background-color: #0d47a1; color: #90caf9; font-size: 0.75rem; padding: 0.2rem 0.5rem; border-radius: 4px; font-weight: bold;">Remote Device</span>
@@ -2188,10 +2188,10 @@ Please complete authorization in the popup window.`,animationEmoji:"\u{1F310}"})
2188
2188
  <div>${a}</div>
2189
2189
 
2190
2190
  <div style="font-weight: bold; color: var(--clr-text-secondary, #b3b3b3);">Description</div>
2191
- <div>${d}</div>
2191
+ <div>${c}</div>
2192
2192
 
2193
2193
  <div style="font-weight: bold; color: var(--clr-text-secondary, #b3b3b3);">Space ID</div>
2194
- <code style="word-break: break-all; background: rgba(255,255,255,0.05); padding: 2px 6px; border-radius: 4px;">${c}</code>
2194
+ <code style="word-break: break-all; background: rgba(255,255,255,0.05); padding: 2px 6px; border-radius: 4px;">${d}</code>
2195
2195
 
2196
2196
  <div style="font-weight: bold; color: var(--clr-text-secondary, #b3b3b3);">Allowed Verbs</div>
2197
2197
  <div>${u}</div>
@@ -2208,14 +2208,14 @@ Please complete authorization in the popup window.`,animationEmoji:"\u{1F310}"})
2208
2208
  No registered delegates.
2209
2209
  </td>
2210
2210
  </tr>
2211
- `;return}let i=await k();if(!i)throw new Error("(UNEXPECTED) metaspace falsy? (E: 8a9b0c1d2e3f4a5b6c7d8e9f0a1b2c3e)");let o=await i.getLocalUserSpace({lock:!1});if(!o)throw new Error("(UNEXPECTED) space falsy? (E: 9b0c1d2e3f4a5b6c7d8e9f0a1b2c3d4f)");let s=o.ib?Ms({spaceIb:o.ib}).spaceId:void 0;for(let[a,d]of Object.entries(e)){let c=document.createElement("tr"),u=d.deviceName||d.details?.deviceTag||d.details?.name||"Device Delegate",f=document.createElement("td"),h=d.spaceId||d.details?.spaceId,m=!1;if(s&&h===s)m=!0;else try{let N=await i.get({addrs:[a],space:o});m=!!(N.success&&N.ibGibs&&N.ibGibs.length>0)}catch{m=!1}let g=document.createElement("span");g.style.marginLeft="0.5rem",g.style.padding="0.15rem 0.4rem",g.style.borderRadius="4px",g.style.fontSize="0.75rem",g.style.fontWeight="bold",m?(g.textContent="This Device",g.className="badge badge-this-device",g.style.backgroundColor="#1b5e20",g.style.color="#a5d6a7"):(g.textContent="Remote Device",g.className="badge badge-remote-device",g.style.backgroundColor="#0d47a1",g.style.color="#90caf9");let b=fn({delegateInfo:d}),y=null;b&&(y=document.createElement("span"),y.textContent="Expired",y.className="badge badge-expired",y.style.marginLeft="0.3rem",y.style.padding="0.15rem 0.4rem",y.style.borderRadius="4px",y.style.fontSize="0.75rem",y.style.fontWeight="bold",y.style.backgroundColor="#b71c1c",y.style.color="#ef9a9a");let w=p((N,P)=>{f.innerHTML="";let $=document.createElement("span");$.textContent=N,f.appendChild($),g&&f.appendChild(g),y&&f.appendChild(y),f.title=P||N},"applyNameAndBadge"),v=`\u{1F4BB} ${u}`;w(v,`TJP: ${a}
2212
- Device: ${u}`);let I=document.createElement("td");I.textContent=a,I.title=a;let C=document.createElement("td");C.textContent=d.allowedVerbs?d.allowedVerbs.join(", "):"-",C.title=C.textContent;let T=!m,x=document.createElement("td"),G=document.createElement("button");G.className="action-btn secondary small",G.textContent="View Details",G.addEventListener("click",async()=>{let N=`${this.lc}[renderDelegates.click]`;if(T)this.showRemoteDelegateModal(d);else if(d.delegateAddr||a){let P=d.delegateAddr;try{let F=await new Y().getLatestKeystone({addr:a,metaspace:i,space:o});F&&(P=_({ibGib:F}))}catch($){console.warn(`${N} Error resolving latest delegate keystone: ${E($)}`)}this.dispatchEvent(new CustomEvent("ibgib-view-keystone-details",{detail:{addr:P},bubbles:!0,composed:!0}))}else this.showRemoteDelegateModal(d)}),x.appendChild(G);let S=document.createElement("button");S.className="action-btn danger small",S.style.marginLeft="0.4rem",S.textContent="Revoke",S.addEventListener("click",async()=>{await this.handleRevokeDelegate(a,u)}),x.appendChild(S),c.appendChild(f),c.appendChild(I),c.appendChild(C),c.appendChild(x),t.appendChild(c)}}async handleRevokeDelegate(e,t){let i=`${this.lc}[${this.handleRevokeDelegate.name}]`;try{let o,s;try{let g=await lt({keystone:this.ibGib,aggregatedDetails:this.aggregatedDetails,title:"Revoke Delegate",msg:`Enter Master Password or touch security key to revoke delegate '${t}':`,verb:Le});o=g.secret,s=g.poolId}catch{return}if(!o)return;this.setSyncStatus("Revoking delegate device...","info");let a=await k();if(!a)throw new Error("Metaspace not found");let d=await a.getLocalUserSpace({lock:!1});if(!d)throw new Error("Local space not found");let u=await new Y().unregisterDelegate({parentKeystone:this.ibGib,delegateTjpAddr:e,masterSecret:o,signingPoolId:s,metaspace:a,space:d}),f=H({ibGib:this.ibGib})||_({ibGib:this.ibGib}),h=await D().putEvolveKeystone({domainAddr:f,keystoneIbGib:u,relatedKeystoneIbGibs:[]});if(!h.success)throw new Error(`Server rejected delegate revocation: ${h.message}`);await a.put({ibGibs:[u],space:d}),await a.registerNewIbGib({ibGib:u,space:d}),await se({type:"keystones",rel8nInfos:[{rel8nName:"keystone",ibGibs:[W({ibGib:u})]}],metaspace:a,space:d});let m=_({ibGib:u});window.dispatchEvent(new CustomEvent(Ce,{detail:{activeIdentityAddr:m},bubbles:!0,composed:!0})),this.setSyncStatus(`Successfully revoked device '${t}'!`,"success"),this.ibGibAddr=m,this.staticIbGib=u,await this.loadIbGib({getLatest:!0})}catch(o){console.error(`${i} Delegate revocation failed: ${E(o)}`),this.setSyncStatus(`Revocation failed: ${E(o)}`,"error")}}setPasskeyStatus(e,t){let i=this.elements?.passkeyStatusMsgEl;i&&(i.textContent=e,i.className=`status-msg ${t}`,i.classList.remove("hidden"))}async renderPasskeys(e){if(!this.elements)return;let t=this.elements.passkeysListEl;t.innerHTML="";let i=this.ibGib?rt({keystone:this.ibGib,aggregatedDetails:this.aggregatedDetails}):void 0,o=i?i.isCustodial&&!i.isSovereign:!1;this.elements.btnAddPasskeyEl&&(this.elements.btnAddPasskeyEl.textContent=o?"\u{1F6E1}\uFE0F Add Passkey (Passwordless Sovereign Elevation)":"\u{1F6E1}\uFE0F Register New Passkey / Security Key");let s=Object.entries(e||{}).filter(([a,d])=>d!=null);if(s.length===0){t.innerHTML=`
2211
+ `;return}let i=await k();if(!i)throw new Error("(UNEXPECTED) metaspace falsy? (E: genuuid)");let o=await i.getLocalUserSpace({lock:!1});if(!o)throw new Error("(UNEXPECTED) space falsy? (E: genuuid)");let s=o.ib?Vs({spaceIb:o.ib}).spaceId:void 0;for(let[a,c]of Object.entries(e)){let d=document.createElement("tr"),u=c.deviceName||c.details?.deviceTag||c.details?.name||"Device Delegate",f=document.createElement("td"),h=c.spaceId||c.details?.spaceId,m=!1;if(s&&h===s)m=!0;else try{let G=await i.get({addrs:[a],space:o});m=!!(G.success&&G.ibGibs&&G.ibGibs.length>0)}catch{m=!1}let g=document.createElement("span");g.style.marginLeft="0.5rem",g.style.padding="0.15rem 0.4rem",g.style.borderRadius="4px",g.style.fontSize="0.75rem",g.style.fontWeight="bold",m?(g.textContent="This Device",g.className="badge badge-this-device",g.style.backgroundColor="#1b5e20",g.style.color="#a5d6a7"):(g.textContent="Remote Device",g.className="badge badge-remote-device",g.style.backgroundColor="#0d47a1",g.style.color="#90caf9");let b=gn({delegateInfo:c}),y=null;b&&(y=document.createElement("span"),y.textContent="Expired",y.className="badge badge-expired",y.style.marginLeft="0.3rem",y.style.padding="0.15rem 0.4rem",y.style.borderRadius="4px",y.style.fontSize="0.75rem",y.style.fontWeight="bold",y.style.backgroundColor="#b71c1c",y.style.color="#ef9a9a");let w=p((G,P)=>{f.innerHTML="";let $=document.createElement("span");$.textContent=G,f.appendChild($),g&&f.appendChild(g),y&&f.appendChild(y),f.title=P||G},"applyNameAndBadge"),v=`\u{1F4BB} ${u}`;w(v,`TJP: ${a}
2212
+ Device: ${u}`);let I=document.createElement("td");I.textContent=a,I.title=a;let C=document.createElement("td");C.textContent=c.allowedVerbs?c.allowedVerbs.join(", "):"-",C.title=C.textContent;let T=!m,x=document.createElement("td"),N=document.createElement("button");N.className="action-btn secondary small",N.textContent="View Details",N.addEventListener("click",async()=>{let G=`${this.lc}[renderDelegates.click]`;if(T)this.showRemoteDelegateModal(c);else if(c.delegateAddr||a){let P=c.delegateAddr;try{let F=await new Y().getLatestKeystone({addr:a,metaspace:i,space:o});F&&(P=_({ibGib:F}))}catch($){console.warn(`${G} Error resolving latest delegate keystone: ${E($)}`)}this.dispatchEvent(new CustomEvent("ibgib-view-keystone-details",{detail:{addr:P},bubbles:!0,composed:!0}))}else this.showRemoteDelegateModal(c)}),x.appendChild(N);let S=document.createElement("button");S.className="action-btn danger small",S.style.marginLeft="0.4rem",S.textContent="Revoke",S.addEventListener("click",async()=>{await this.handleRevokeDelegate(a,u)}),x.appendChild(S),d.appendChild(f),d.appendChild(I),d.appendChild(C),d.appendChild(x),t.appendChild(d)}}async handleRevokeDelegate(e,t){let i=`${this.lc}[${this.handleRevokeDelegate.name}]`;try{let o,s;try{let g=await lt({keystone:this.ibGib,aggregatedDetails:this.aggregatedDetails,title:"Revoke Delegate",msg:`Enter Master Password or touch security key to revoke delegate '${t}':`,verb:Le});o=g.secret,s=g.poolId}catch{return}if(!o)return;this.setSyncStatus("Revoking delegate device...","info");let a=await k();if(!a)throw new Error("Metaspace not found");let c=await a.getLocalUserSpace({lock:!1});if(!c)throw new Error("Local space not found");let u=await new Y().unregisterDelegate({parentKeystone:this.ibGib,delegateTjpAddr:e,masterSecret:o,signingPoolId:s,metaspace:a,space:c}),f=H({ibGib:this.ibGib})||_({ibGib:this.ibGib}),h=await D().putEvolveKeystone({domainAddr:f,keystoneIbGib:u,relatedKeystoneIbGibs:[]});if(!h.success)throw new Error(`Server rejected delegate revocation: ${h.message}`);await a.put({ibGibs:[u],space:c}),await a.registerNewIbGib({ibGib:u,space:c}),await re({type:"keystones",rel8nInfos:[{rel8nName:"keystone",ibGibs:[J({ibGib:u})]}],metaspace:a,space:c});let m=_({ibGib:u});window.dispatchEvent(new CustomEvent(Ce,{detail:{activeIdentityAddr:m},bubbles:!0,composed:!0})),this.setSyncStatus(`Successfully revoked device '${t}'!`,"success"),this.ibGibAddr=m,this.staticIbGib=u,await this.loadIbGib({getLatest:!0})}catch(o){console.error(`${i} Delegate revocation failed: ${E(o)}`),this.setSyncStatus(`Revocation failed: ${E(o)}`,"error")}}setPasskeyStatus(e,t){let i=this.elements?.passkeyStatusMsgEl;i&&(i.textContent=e,i.className=`status-msg ${t}`,i.classList.remove("hidden"))}async renderPasskeys(e){if(!this.elements)return;let t=this.elements.passkeysListEl;t.innerHTML="";let i=this.ibGib?rt({keystone:this.ibGib,aggregatedDetails:this.aggregatedDetails}):void 0,o=i?i.isCustodial&&!i.isSovereign:!1;this.elements.btnAddPasskeyEl&&(this.elements.btnAddPasskeyEl.textContent=o?"\u{1F6E1}\uFE0F Add Passkey (Passwordless Sovereign Elevation)":"\u{1F6E1}\uFE0F Register New Passkey / Security Key");let s=Object.entries(e||{}).filter(([a,c])=>c!=null);if(s.length===0){t.innerHTML=`
2213
2213
  <tr>
2214
2214
  <td colspan="4" style="text-align: center; color: var(--clr-text-secondary, #b3b3b3); padding: 1rem;">
2215
2215
  No hardware passkeys or biometrics registered.
2216
2216
  </td>
2217
2217
  </tr>
2218
- `;return}for(let[a,d]of s){let c=document.createElement("tr"),u=d.createdUTC?new Date(d.createdUTC).toLocaleString():"N/A",f=d.name||"Hardware Key",h="";d.transports&&d.transports.length>0?h=d.transports.map(g=>{let b="\u{1F511}",y=g;return g==="internal"?(b="\u{1F4BB}",y="Touch ID / Built-in"):g==="usb"?(b="\u{1F511}",y="USB Key"):g==="nfc"?(b="\u{1F4F6}",y="NFC"):(g==="ble"||g==="hybrid")&&(b="\u{1F4F2}",y="Mobile / Bluetooth"),`<span class="badge badge-remote-device" style="background-color: #1b5e20; color: #a5d6a7; font-size: 0.75rem; padding: 0.2rem 0.5rem; border-radius: 4px; font-weight: bold; margin-right: 0.3rem;">${b} ${y}</span>`}).join(" "):h='<span class="badge badge-remote-device" style="background-color: #2e7d32; color: #c8e6c9; font-size: 0.75rem; padding: 0.2rem 0.5rem; border-radius: 4px; font-weight: bold;">\u{1F6E1}\uFE0F Resident Passkey</span>',c.innerHTML=`
2218
+ `;return}for(let[a,c]of s){let d=document.createElement("tr"),u=c.createdUTC?new Date(c.createdUTC).toLocaleString():"N/A",f=c.name||"Hardware Key",h="";c.transports&&c.transports.length>0?h=c.transports.map(g=>{let b="\u{1F511}",y=g;return g==="internal"?(b="\u{1F4BB}",y="Touch ID / Built-in"):g==="usb"?(b="\u{1F511}",y="USB Key"):g==="nfc"?(b="\u{1F4F6}",y="NFC"):(g==="ble"||g==="hybrid")&&(b="\u{1F4F2}",y="Mobile / Bluetooth"),`<span class="badge badge-remote-device" style="background-color: #1b5e20; color: #a5d6a7; font-size: 0.75rem; padding: 0.2rem 0.5rem; border-radius: 4px; font-weight: bold; margin-right: 0.3rem;">${b} ${y}</span>`}).join(" "):h='<span class="badge badge-remote-device" style="background-color: #2e7d32; color: #c8e6c9; font-size: 0.75rem; padding: 0.2rem 0.5rem; border-radius: 4px; font-weight: bold;">\u{1F6E1}\uFE0F Resident Passkey</span>',d.innerHTML=`
2219
2219
  <td>
2220
2220
  <div style="font-weight: 500;">${f}</div>
2221
2221
  <code style="font-size: 0.75rem; color: var(--clr-text-secondary, #b3b3b3); word-break: break-all;">${a.substring(0,16)}...</code>
@@ -2227,8 +2227,8 @@ Device: ${u}`);let I=document.createElement("td");I.textContent=a,I.title=a;let
2227
2227
  Remove
2228
2228
  </button>
2229
2229
  </td>
2230
- `,c.querySelector(".btn-remove-passkey")?.addEventListener("click",()=>this.handleRemovePasskey(a)),t.appendChild(c)}}async handleAddPasskey(){let e=`${this.lc}[${this.handleAddPasskey.name}]`;if(!(!this.ibGib||!this.ibGibAddr))try{let t=rt({keystone:this.ibGib,aggregatedDetails:this.aggregatedDetails}),i=t.isCustodial&&!t.isSovereign;if(!await js()){this.setPasskeyStatus("WebAuthn PRF extension is not supported in this browser environment.","error");return}this.showBusy({isBusy:!0,title:"Touch Biometrics or Security Key",msg:"Please touch your fingerprint sensor, Face ID, or insert your USB security key when prompted...",animationEmoji:"\u{1F6E1}\uFE0F"});let s=this.aggregatedDetails?.username||this.ibGib.data?.frameDetails?.username||"user",a=crypto.getRandomValues(new Uint8Array(32)),d=gn(a.buffer),c=this.elements?.selectPasskeyAttachmentEl?.value,f=await bn({username:s,displayName:s,salt:d,userVerification:"preferred",authenticatorAttachment:c==="cross-platform"||c==="platform"?c:void 0}),{credentialId:h,transports:m}=f,g=f.passkeySecret;g||(g=(await yn({credentialId:h,salt:d,transports:m,userVerification:"preferred"})).passkeySecret);let y=at(),v=`passkey-manage-${bt({text:y,length:12,keepLiterals:["-"]})||"key"}`,I={credentialId:h,poolId:v,name:y,salt:d,createdUTC:new Date().toISOString(),...m&&m.length>0?{transports:m}:{}},C=await k();if(!C)throw new Error("Metaspace not found");let T=await C.getLocalUserSpace({lock:!1});if(!T)throw new Error("Local space not found");let x=new Y,G,S={id:v,type:$i.hash_reveal_v1,salt:v,algo:Pi.sha_256,rounds:1,allowedVerbs:[Le,Pe,Ge],behavior:{size:10,replenish:ki.topUp,selectSequentially:1,selectRandomly:0,targetBindingCount:0}},N=await un({config:S,masterSecret:g}),P={id:v,config:S,challenges:N},$,F;if(i)this.showBusy({isBusy:!0,title:"Elevating Account Ownership...",msg:"Establishing sovereign passkey pool on identity...",animationEmoji:"\u26A1"}),$=g,F=v,G=await x.addPools({latestKeystone:this.ibGib,masterSecret:$,signingPoolId:F,newPools:[P],frameDetails:{passkeys:{[h]:I}},dataToPatch:{credentialIds:[...this.ibGib.data?.credentialIds||[],h]},metaspace:C,space:T});else{try{let et=await lt({keystone:this.ibGib,aggregatedDetails:this.aggregatedDetails,title:"Authorize New Passkey",msg:"Enter Master Password or touch security key to authorize adding this passkey:",verb:Le});$=et.secret,F=et.poolId}catch{this.setPasskeyStatus("Registration cancelled (authorization required).","error");return}this.showBusy({isBusy:!0,title:"Registering Passkey...",msg:"Adding cryptographic challenge pool and evolving identity...",animationEmoji:"\u{1F6E1}\uFE0F"}),G=await x.addPools({latestKeystone:this.ibGib,masterSecret:$,signingPoolId:F,newPools:[P],frameDetails:{passkeys:{[h]:I}},dataToPatch:{credentialIds:[...this.ibGib.data?.credentialIds||[],h]},metaspace:C,space:T});let Zt=H({ibGib:G,defaultIfNone:"incomingAddr"}),jt=await D().putEvolveKeystone({domainAddr:Zt,keystoneIbGib:G,relatedKeystoneIbGibs:[]});if(!jt.success)throw new Error(`Server synchronization of passkey pool failed: ${jt.message}`)}this.showBusy({isBusy:!0,title:"Creating Sync Delegate...",msg:"Constructing outward passkey device sync delegate...",animationEmoji:"\u{1F4F1}"});let X=H({ibGib:G,defaultIfNone:"incomingAddr"}),{delegateKeystone:U,deviceTag:ie}=await En({username:s,primaryTjpAddr:X,passkeySecret:g,transports:m,metaspace:C,space:T});this.showBusy({isBusy:!0,title:"Registering Delegate...",msg:"Registering outward passkey delegate on primary identity...",animationEmoji:"\u{1F4DD}"});let ve=i?v:F,Z=i?g:$;G=await x.registerDelegate({parentKeystone:G,delegateKeystone:U,masterSecret:Z,signingPoolId:ve,metaspace:C,space:T,allowedVerbs:[Pe,Ge],deviceName:ie}),this.showBusy({isBusy:!0,title:"Syncing to Server...",msg:"Publishing evolved identity keystone and delegate to server...",animationEmoji:"\u26A1"});let he=await D().putEvolveKeystone({domainAddr:X,keystoneIbGib:G,relatedKeystoneIbGibs:[U]});if(!he.success)throw new Error(`Server synchronization of delegate failed: ${he.message}`);await se({type:"keystones",rel8nInfos:[{rel8nName:"keystone",ibGibs:[W({ibGib:G}),W({ibGib:U})]}],metaspace:C,space:T}),this.setPasskeyStatus("Passkey successfully registered and bound to identity!","success"),this.ibGibAddr=_({ibGib:G}),this.staticIbGib=G,await this.loadIbGib({getLatest:!1})}catch(t){console.error(`${e} ${E(t)}`,t),this.setPasskeyStatus(`Failed to register passkey: ${E(t)}`,"error")}finally{this.showBusy({isBusy:!1})}}async handleRemovePasskey(e){let t=`${this.lc}[${this.handleRemovePasskey.name}]`;if(!this.ibGib||!this.ibGibAddr)return;let i=this.aggregatedDetails?.passkeys?.[e],o=i?.name||"this passkey";try{let s=new Y,a,d;try{let y=await lt({keystone:this.ibGib,aggregatedDetails:this.aggregatedDetails,title:"Authorize Removal",msg:`Are you sure you want to remove "${o}"? Enter your Master Secret (Password) or touch security key to authorize:`,verb:Le});a=y.secret,d=y.poolId}catch{this.setPasskeyStatus("Removal cancelled or unauthorized.","error");return}this.showBusy({isBusy:!0,title:"Revoking Passkey...",msg:"Tombstoning passkey record and removing challenge pool...",animationEmoji:"\u{1F5D1}\uFE0F"});let c=await k();if(!c)throw new Error("Metaspace not found");let u=await c.getLocalUserSpace({lock:!1});if(!u)throw new Error("Local space not found");let f=i?.poolId||`passkey-manage-${e.substring(0,8)}`,h=this.ibGib.data?.challengePools.some(y=>y.id===f),m=(this.ibGib.data?.credentialIds||[]).filter(y=>y!==e),g;h?g=await s.removePools({latestKeystone:this.ibGib,masterSecret:a,signingPoolId:d,poolIds:[f],frameDetails:{passkeys:{[e]:null}},dataToPatch:{credentialIds:m},metaspace:c,space:u}):g=await s.sign({latestKeystone:this.ibGib,masterSecret:a,poolId:d,claim:{target:_({ibGib:this.ibGib})},frameDetails:{passkeys:{[e]:null}},dataToPatch:{credentialIds:m},metaspace:c,space:u}),this.showBusy({isBusy:!0,title:"Syncing to Server...",msg:"Publishing updated keystone to server...",animationEmoji:"\u26A1"});let b=H({ibGib:g,defaultIfNone:"incomingAddr"});await D().putEvolveKeystone({domainAddr:b,keystoneIbGib:g,relatedKeystoneIbGibs:[]}),await se({type:"keystones",rel8nInfos:[{rel8nName:"keystone",ibGibs:[W({ibGib:g})]}],metaspace:c,space:u}),this.setPasskeyStatus(`Passkey "${o}" successfully removed.`,"success"),this.ibGibAddr=_({ibGib:g}),this.staticIbGib=g,await this.loadIbGib({getLatest:!1})}catch(s){console.error(`${t} ${E(s)}`,s),this.setPasskeyStatus(`Failed to remove passkey: ${E(s)}`,"error")}finally{this.showBusy({isBusy:!1})}}async handleContextUpdated(){let e=`${this.lc}[${this.handleContextUpdated.name}]`;try{we&&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} ${E(t)}`),t}finally{we&&console.log(`${e} complete.`)}}async handleNewContextChild({childIbGib:e}){let t=`${this.lc}[${this.handleNewContextChild.name}]`;try{we&&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} ${E(i)}`),i}finally{we&&console.log(`${t} complete.`)}}async handleSSOLink(e){let t=`${this.lc}[${this.handleSSOLink.name}]`;this.setSSOStatus(`Linking ${e}...`,"info");let i=e==="google"?"Google":e==="github"?"GitHub":e;this.setSSOStatus(`Opening ${i} SSO authorization window...`,"info"),this.showBusy({isBusy:!0,title:`Connecting to ${i}...`,msg:`Opening ${i} SSO authorization window...
2231
- Please complete authorization in the popup window.`,animationEmoji:"\u{1F310}"});try{let o=(this.ibGib?H({ibGib:this.ibGib}):void 0)||(this.ibGibAddr?(()=>{let{ib:a}=B({ibGibAddr:this.ibGibAddr}),{tjpGib:d}=J({ibGibAddr:this.ibGibAddr});return d&&a?`${a}^${d}`:this.ibGibAddr})():void 0),s=await je({providerId:e,parentTjpAddr:o});if(!s.success||!s.code){this.setSSOStatus(s.message||"Linking cancelled.","error");return}await this.handleSSOLinkCallback(s.code,s.stateObj,s.redirectUri)}catch(o){console.error(`${t} SSO link initiation failed: ${E(o)}`),this.setSSOStatus(`Link failed: ${E(o)}`,"error")}finally{this.showBusy({isBusy:!1})}}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}]`,s=t.providerId==="google"?"Google":t.providerId==="github"?"GitHub":t.providerId;this.setSSOStatus("Retrieving challenge pool configuration from server...","info"),this.showBusy({isBusy:!0,title:`Linking ${s}...`,msg:`Validating ${s} authorization with server...`,animationEmoji:"\u{1F510}"});try{let a=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(!a.ok){let x=await a.json().catch(()=>({}));throw new Error(`Server link exchange failed: ${x.message||a.statusText}`)}let d=await a.json();if(!d.success||!d.custodianPool)throw new Error(`Failed to retrieve custodian challenge pool: ${d.message||"unknown error"}`);let c=d.custodianPool,u=new Y,f,h;try{let x=await lt({keystone:this.ibGib,aggregatedDetails:this.aggregatedDetails,title:`Link ${s}`,msg:`Enter Master Password or touch security key to authorize linking ${s}:`,verb:Le});f=x.secret,h=x.poolId}catch{this.setSSOStatus("Link cancelled or failed.","error");return}this.showBusy({isBusy:!0,title:"Evolving Identity...",msg:`Installing ${s} custodian pool and signing evolution...`,animationEmoji:"\u{1F4DD}"}),this.setSSOStatus("Evolving identity locally and generating cryptographic signatures...","info");let m=await k();if(!m)throw new Error("Metaspace not found");let g=await m.getLocalUserSpace({lock:!1});if(!g)throw new Error("Local space not found");let b=await u.addPools({latestKeystone:this.ibGib,masterSecret:f,signingPoolId:h,newPools:[c],metaspace:m,space:g}),y=await D().putEvolveKeystone({domainAddr:t.parentTjpAddr,keystoneIbGib:b,relatedKeystoneIbGibs:[]});if(!y.success)throw new Error(`Server synchronization of linked pool rejected: ${y.message}`);let w=this.aggregatedDetails?.username||this.ibGib?.data?.username||"user",{delegateKeystone:v,deviceTag:I}=await mn({providerId:t.providerId,username:w,primaryTjpAddr:t.parentTjpAddr,custodianReqs:d.custodianReqs,metaspace:m,space:g}),C=await u.registerDelegate({parentKeystone:b,delegateKeystone:v,masterSecret:f,signingPoolId:h,metaspace:m,space:g,allowedVerbs:[Pe,Ge],deviceName:I});await m.put({ibGibs:[v,C],space:g}),this.showBusy({isBusy:!0,title:"Syncing to Server...",msg:"Publishing linked identity and delegate to server...",animationEmoji:"\u26A1"}),this.setSSOStatus("Publishing evolved identity keystone to server...","info");let T=await D().putEvolveKeystone({domainAddr:t.parentTjpAddr,keystoneIbGib:C,relatedKeystoneIbGibs:[v]});if(!T.success)throw new Error(`Server synchronization of delegate rejected: ${T.message}`);await se({type:"keystones",rel8nInfos:[{rel8nName:"keystone",ibGibs:[W({ibGib:C}),W({ibGib:v})]}],metaspace:m,space:g}),this.setSSOStatus(`Successfully linked with ${t.providerId}!`,"success"),this.ibGibAddr=_({ibGib:C}),this.staticIbGib=C,await this.loadIbGib({getLatest:!1})}catch(a){console.error(`${o} SSO callback processing failed: ${E(a)}`),this.setSSOStatus(`Link failed: ${E(a)}`,"error")}finally{this.showBusy({isBusy:!1})}}async handleSSOClick(e){if(this.ibGib?pn({keystone:this.ibGib,aggregatedDetails:this.aggregatedDetails,providerId:e}):!1){if(!rt({keystone:this.ibGib,aggregatedDetails:this.aggregatedDetails}).isSovereign){this.setSSOStatus(`Cannot unlink ${e}: This is your only identity recovery and management method. Please add a Master Password first in the Password card below to enable sovereign ownership before unlinking.`,"error");return}await this.handleSSOUnlink(e)}else await this.handleSSOLink(e)}async handleSSOUnlink(e){let t=`${this.lc}[${this.handleSSOUnlink.name}]`,i=e==="google"?"Google":e==="github"?"GitHub":e;this.setSSOStatus(`Unlinking ${i}...`,"info");try{let o=new Y,s,a;try{let b=await lt({keystone:this.ibGib,aggregatedDetails:this.aggregatedDetails,title:`Unlink ${i}`,msg:`Are you sure you want to unlink your ${i} account? If so, enter your Master Password or touch security key to authorize.`,verb:Le});s=b.secret,a=b.poolId}catch{this.setSSOStatus("Unlink cancelled or failed.","error");return}this.showBusy({isBusy:!0,title:"Unlinking Provider...",msg:`Removing ${i} custodian pool and delegate keys...`,animationEmoji:"\u{1F513}"}),this.setSSOStatus("Evolving identity locally and removing custodian pool...","info");let d=await k();if(!d)throw new Error("Metaspace not found");let c=await d.getLocalUserSpace({lock:!1});if(!c)throw new Error("Local space not found");let u=`custodian-manage-${e}`,f=await o.removePools({latestKeystone:this.ibGib,masterSecret:s,signingPoolId:a,poolIds:[u],metaspace:d,space:c}),h=(this.ibGib?H({ibGib:this.ibGib}):void 0)||(this.ibGibAddr?(()=>{let{ib:b}=B({ibGibAddr:this.ibGibAddr}),{tjpGib:y}=J({ibGibAddr:this.ibGibAddr});return y&&b?`${b}^${y}`:this.ibGibAddr})():void 0)||_({ibGib:this.ibGib});this.showBusy({isBusy:!0,title:"Syncing to Server...",msg:`Publishing ${i} pool removal to server...`,animationEmoji:"\u26A1"}),this.setSSOStatus("Publishing evolved identity keystone to server...","info");let m=await D().putEvolveKeystone({domainAddr:h,keystoneIbGib:f,relatedKeystoneIbGibs:[]});if(!m.success)throw new Error(`Server synchronization rejected: ${m.message}`);let g=f.data?.delegates||this.ibGib?.data?.delegates;if(g){for(let[b,y]of Object.entries(g))if(Ys({delegateInfo:y,providerId:e})&&(f=await o.unregisterDelegate({parentKeystone:f,delegateTjpAddr:b,masterSecret:s,signingPoolId:"manage",metaspace:d,space:c}),this.showBusy({isBusy:!0,title:"Syncing to Server...",msg:`Publishing ${i} delegate unregistration to server...`,animationEmoji:"\u26A1"}),m=await D().putEvolveKeystone({domainAddr:h,keystoneIbGib:f,relatedKeystoneIbGibs:[]}),!m.success))throw new Error(`Server synchronization rejected: ${m.message}`)}await se({type:"keystones",rel8nInfos:[{rel8nName:"keystone",ibGibs:[W({ibGib:f})]}],metaspace:d,space:c}),this.setSSOStatus(`Successfully unlinked ${i}!`,"success"),this.ibGibAddr=_({ibGib:f}),this.staticIbGib=f,await this.loadIbGib({getLatest:!1})}catch(o){console.error(`${t} ${E(o)}`,o),this.setSSOStatus(`Failed to unlink ${i}: ${E(o)}`,"error")}finally{this.showBusy({isBusy:!1})}}setChangePasswordStatus(e,t){let i=this.elements.changePasswordStatusEl;i.textContent=e,i.className=`status-msg ${t}`,i.classList.remove("hidden")}async handleAddMasterPassword(){let e=`${this.lc}[${this.handleAddMasterPassword.name}]`;this.setChangePasswordStatus("Validating entries...","info");try{let t=this.elements.inputNewPasswordEl.value,i=this.elements.inputConfirmPasswordEl.value;if(!t){this.setChangePasswordStatus("Master password is required.","error");return}if(t!==i){this.setChangePasswordStatus("Master password and confirmation do not match.","error");return}let o=this.ibGib?.data?.challengePools?.find(y=>y.id===ot);if(!o){this.setChangePasswordStatus("Primary keystone missing active manage challenge pool.","error");return}this.showBusy({isBusy:!0,title:"Elevating Identity...",msg:"Generating cryptographic sovereign challenge pool...",animationEmoji:"\u{1F511}"}),this.setChangePasswordStatus("Generating sovereign challenge pool...","info");let s=await un({config:o.config,masterSecret:t}),a={id:ot,config:o.config,challenges:s},d=(this.ibGib?H({ibGib:this.ibGib}):void 0)||(this.ibGibAddr?(()=>{let{ib:y}=B({ibGibAddr:this.ibGibAddr}),{tjpGib:w}=J({ibGibAddr:this.ibGibAddr});return w&&y?`${y}^${w}`:this.ibGibAddr})():void 0)||_({ibGib:this.ibGib}),c=this.aggregatedDetails?.custodianProvider||this.ibGib?.data?.frameDetails?.custodianProvider||this.ibGib?.data?.custodianProvider,u={primaryTjpAddr:d,newManagePool:a};if(c==="google"||c==="github"){this.showBusy({isBusy:!0,title:"Re-authenticating with Provider...",msg:`Please complete authentication in the ${c} popup window...`,animationEmoji:"\u{1F512}"}),this.setChangePasswordStatus(`Please authenticate in the popup with ${c} to verify ownership...`,"info");let y=await je({providerId:c,parentTjpAddr:d});if(!y.success||!y.code){this.showBusy({isBusy:!1}),this.setChangePasswordStatus(y.message||"Re-authentication cancelled.","error");return}u.providerId=c,u.code=y.code,u.redirectUri=y.redirectUri}else{let y=this.aggregatedDetails?.emails?.[0]||this.ibGib?.data?.emails?.[0]||this.ibGib?.data?.frameDetails?.emails?.[0];if(!y){this.showBusy({isBusy:!1}),this.setChangePasswordStatus("No email address found for this identity to send verification code.","error");return}let w=this.elements?.sectionAddPasswordOtpEl,v=this.elements?.inputAddPasswordOtpEl;if(!(w&&!w.classList.contains("hidden"))){this.showBusy({isBusy:!0,title:"Sending Verification Code...",msg:`Sending 6-digit verification code to ${y}...`,animationEmoji:"\u{1F4E7}"}),this.setChangePasswordStatus(`Sending verification code to ${y}...`,"info");let T=await D().postVerificationCode({email:y,primaryTjpAddr:d});if(this.showBusy({isBusy:!1}),!T.success){this.setChangePasswordStatus(T.message||"Failed to send verification code.","error");return}w&&w.classList.remove("hidden"),this.elements?.descAddPasswordOtpEl&&(this.elements.descAddPasswordOtpEl.textContent=`A 6-digit verification code was sent to ${y}. Enter it below to establish sovereign ownership:`),this.elements?.btnChangePasswordEl&&(this.elements.btnChangePasswordEl.textContent="Verify Code & Add Master Password"),this.setChangePasswordStatus(`\u2709\uFE0F 6-digit verification code sent to ${y}. Enter the code and click "Verify Code & Add Master Password".`,"info"),this.startResendCooldownTimer(30),v&&(v.value="",v.focus());return}let C=(v?.value||"").trim();if(!C||C.length<6){this.setChangePasswordStatus("Please enter the complete 6-digit verification code sent to your email.","error"),v&&v.focus();return}u.email=y,u.code=C}this.showBusy({isBusy:!0,title:"Updating Keystone Timeline...",msg:"Publishing sovereign master password and evolving identity DAG...",animationEmoji:"\u23F3"}),this.setChangePasswordStatus("Elevating identity to sovereign master password on server...","info");let f=await fetch("/api/identity/custodian/add-master-password",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(u)}),h=await f.json();if(!f.ok||!h.success)throw new Error(h.error||h.message||`Server error (${f.status})`);let m=h.primaryKeystone,g=await k();if(!g)throw new Error("Global metaspace not available");let b=await g.getLocalUserSpace({lock:!1});if(!b)throw new Error("Local user space not available");if(h.primaryGraph){let y=Object.values(h.primaryGraph);await g.put({ibGibs:y,space:b});let w=Se({ibGibs:y});for(let v of Object.keys(w))for(let I of w[v])await g.registerNewIbGib({ibGib:I,space:b})}else await g.put({ibGibs:[m],space:b}),await g.registerNewIbGib({ibGib:m,space:b});await this.registerAndSyncSovereignPasswordDelegate({evolvedParent:m,newPassword:t,primaryTjpAddr:d,metaspace:g,space:b})}catch(t){console.error(`${e} Elevation failed: ${E(t)}`),this.setChangePasswordStatus(`Failed to add master password: ${E(t)}`,"error"),this.elements?.inputAddPasswordOtpEl&&!this.elements.sectionAddPasswordOtpEl?.classList.contains("hidden")&&(this.elements.inputAddPasswordOtpEl.select(),this.elements.inputAddPasswordOtpEl.focus())}finally{this.showBusy({isBusy:!1})}}async handleResendAddPasswordOtp(){let e=`${this.lc}[${this.handleResendAddPasswordOtp.name}]`,t=this.aggregatedDetails?.emails?.[0]||this.ibGib?.data?.emails?.[0]||this.ibGib?.data?.frameDetails?.emails?.[0];if(!t){this.setChangePasswordStatus("No email address found for this identity to send verification code.","error");return}let i=(this.ibGib?H({ibGib:this.ibGib}):void 0)||(this.ibGibAddr?(()=>{let{ib:s}=B({ibGibAddr:this.ibGibAddr}),{tjpGib:a}=J({ibGibAddr:this.ibGibAddr});return a&&s?`${s}^${a}`:this.ibGibAddr})():void 0)||_({ibGib:this.ibGib}),o=this.elements.btnResendAddPasswordOtpEl;o&&(o.disabled=!0,o.textContent="Sending..."),this.setChangePasswordStatus(`Resending verification code to ${t}...`,"info");try{let s=await D().postVerificationCode({email:t,primaryTjpAddr:i});s.success?(this.setChangePasswordStatus(`\u2709\uFE0F Fresh 6-digit verification code sent to ${t}!`,"success"),this.startResendCooldownTimer(30),this.elements?.inputAddPasswordOtpEl&&(this.elements.inputAddPasswordOtpEl.value="",this.elements.inputAddPasswordOtpEl.focus())):(this.setChangePasswordStatus(s.message||"Failed to resend verification code.","error"),o&&(o.disabled=!1,o.textContent="Resend Code"))}catch(s){this.setChangePasswordStatus(`Error resending verification code: ${E(s)}`,"error"),o&&(o.disabled=!1,o.textContent="Resend Code")}}async registerAndSyncSovereignPasswordDelegate({evolvedParent:e,newPassword:t,primaryTjpAddr:i,metaspace:o,space:s}){let a=`${this.lc}[${this.registerAndSyncSovereignPasswordDelegate.name}]`;this.showBusy({isBusy:!0,title:"Creating Sovereign Sync Delegate...",msg:"Deriving local device sync delegate keys from Master Password...",animationEmoji:"\u{1F511}"}),await z(50);let d=this.aggregatedDetails?.username||this.ibGib?.data?.username||this.aggregatedDetails?.emails?.[0]?.split("@")[0]||this.ibGib?.data?.emails?.[0]?.split("@")[0]||"user",{delegateKeystone:c,deviceTag:u}=await hn({username:d,primaryTjpAddr:i,masterSecret:t,metaspace:o,space:s});this.showBusy({isBusy:!0,title:"Registering Sovereign Delegate...",msg:"Registering user sync delegate on primary keystone...",animationEmoji:"\u{1F4DD}"}),await z(50);let h=await new Y().registerDelegate({parentKeystone:e,delegateKeystone:c,masterSecret:t,signingPoolId:ot,metaspace:o,space:s,allowedVerbs:[Pe,Ge],deviceName:u});this.showBusy({isBusy:!0,title:"Syncing to Server...",msg:"Publishing updated domain identity and sovereign delegate to server...",animationEmoji:"\u26A1"});let m=await D().putEvolveKeystone({domainAddr:i,keystoneIbGib:h,relatedKeystoneIbGibs:[c]});if(!m.success)throw new Error(`Server sync of password delegate failed: ${m.message}`);await o.put({ibGibs:[h,c],space:s}),await o.registerNewIbGib({ibGib:h,space:s}),await o.registerNewIbGib({ibGib:c,space:s}),await se({type:"keystones",rel8nInfos:[{rel8nName:"keystone",ibGibs:[W({ibGib:h}),W({ibGib:c})]}],metaspace:o,space:s});let g=_({ibGib:h});return window.dispatchEvent(new CustomEvent(Ce,{detail:{activeIdentityAddr:g},bubbles:!0,composed:!0})),this.setChangePasswordStatus("Successfully added Master Password! Identity is now sovereign.","success"),this.elements?.sectionAddPasswordOtpEl&&(this.elements.sectionAddPasswordOtpEl.classList.add("hidden"),this.elements.inputAddPasswordOtpEl&&(this.elements.inputAddPasswordOtpEl.value="")),this.elements?.btnChangePasswordEl&&(this.elements.btnChangePasswordEl.textContent="Update Password"),this.ibGibAddr=g,this.staticIbGib=h,await this.loadIbGib({getLatest:!0}),this.elements.inputNewPasswordEl.value="",this.elements.inputConfirmPasswordEl.value="",h}async handleAddPasswordToPasskeyIdentity(){let e=`${this.lc}[${this.handleAddPasswordToPasskeyIdentity.name}]`;this.setChangePasswordStatus("Validating entries...","info");try{let t=this.elements.inputNewPasswordEl.value,i=this.elements.inputConfirmPasswordEl.value;if(!t){this.setChangePasswordStatus("Master password is required.","error");return}if(t!==i){this.setChangePasswordStatus("Master password and confirmation do not match.","error");return}let o=this.aggregatedDetails?.passkeys||this.ibGib?.data?.frameDetails?.passkeys||this.ibGib?.data?.passkeys||{},s=Array.isArray(o)?o:Object.values(o);if(!this.ibGib?.data?.challengePools?.find(I=>I.id.startsWith("passkey-manage-"))){this.setChangePasswordStatus("No active passkey manage pool found on this identity.","error");return}let d,c;try{let I=await lt({keystone:this.ibGib,aggregatedDetails:this.aggregatedDetails,title:"Authorize Master Password",msg:"Please touch your fingerprint sensor, Face ID, or security key to authorize adding a Master Password...",verb:Le});d=I.secret,c=I.poolId}catch{this.setChangePasswordStatus("Authorization cancelled.","error");return}this.showBusy({isBusy:!0,title:"Adding Master Password...",msg:"Compiling cryptographic master password pool and evolving identity...",animationEmoji:"\u{1F511}"}),await z(50),this.setChangePasswordStatus("Generating sovereign master password challenge pool...","info");let u=await k();if(!u)throw new Error("Global metaspace not available");let f=await u.getLocalUserSpace({lock:!1});if(!f)throw new Error("Local user space not available");let h={id:ot,type:$i.hash_reveal_v1,salt:ot,algo:Pi.sha_256,rounds:1,allowedVerbs:[Le,Pe,Ge],behavior:{size:10,replenish:ki.topUp,selectSequentially:1,selectRandomly:0,targetBindingCount:0}},m=await un({config:h,masterSecret:t}),g={id:ot,config:h,challenges:m},b=(this.ibGib?H({ibGib:this.ibGib}):void 0)||(this.ibGibAddr?(()=>{let{ib:I}=B({ibGibAddr:this.ibGibAddr}),{tjpGib:C}=J({ibGibAddr:this.ibGibAddr});return C&&I?`${I}^${C}`:this.ibGibAddr})():void 0)||_({ibGib:this.ibGib}),w=await new Y().sign({latestKeystone:this.ibGib,claim:{target:b,verb:Le},masterSecret:d,poolId:c,dataToPatch:{challengePools:[...this.ibGib.data.challengePools||[],g]},metaspace:u,space:f});this.showBusy({isBusy:!0,title:"Syncing to Server...",msg:"Publishing updated identity to server...",animationEmoji:"\u26A1"});let v=await D().putEvolveKeystone({domainAddr:b,keystoneIbGib:w,relatedKeystoneIbGibs:[]});if(!v.success)throw new Error(`Server sync failed: ${v.message}`);await u.put({ibGibs:[w],space:f}),await u.registerNewIbGib({ibGib:w,space:f}),await this.registerAndSyncSovereignPasswordDelegate({evolvedParent:w,newPassword:t,primaryTjpAddr:b,metaspace:u,space:f})}catch(t){console.error(`${e} Failed to add password to passkey identity: ${E(t)}`,t),this.setChangePasswordStatus(`Failed to add master password: ${E(t)}`,"error")}finally{this.showBusy({isBusy:!1})}}async handleChangePassword(){let e=`${this.lc}[${this.handleChangePassword.name}]`,t=this.ibGib?rt({keystone:this.ibGib,aggregatedDetails:this.aggregatedDetails}):void 0;if(!!!t?.hasPassword){(t?t.isCustodial&&!t.isSovereign:!1)?await this.handleAddMasterPassword():await this.handleAddPasswordToPasskeyIdentity();return}this.setChangePasswordStatus("Validating entries...","info"),this.showBusy({isBusy:!0,title:"Changing Master Password...",msg:"Validating current password...",animationEmoji:"\u{1F510}"});try{let o=this.elements.inputCurrentPasswordEl.value,s=this.elements.inputNewPasswordEl.value,a=this.elements.inputConfirmPasswordEl.value;if(!o){this.setChangePasswordStatus("Current password is required.","error");return}if(!s){this.setChangePasswordStatus("New password is required.","error");return}if(s!==a){this.setChangePasswordStatus("New password and confirmation do not match.","error");return}let d=new Y;if(!await d.verifySigningSecret({keystoneIbGib:this.ibGib,signingSecret:o,poolId:"manage"})){this.setChangePasswordStatus("Incorrect current password.","error");return}this.showBusy({isBusy:!0,title:"Evolving Master Password...",msg:"Generating new challenge proofs and rotating local user delegates...",animationEmoji:"\u2699\uFE0F"}),this.setChangePasswordStatus("Evolving primary identity keystone...","info");let u=await k();if(!u)throw new Error("(UNEXPECTED) metaspace falsy? (E: 95e3c8374b0f088f339f5c5a8700f826)");let f=await u.getLocalUserSpace({lock:!1});if(!f)throw new Error("(UNEXPECTED) couldn't get default local space? (E: 2fc1281c28351fd378a1d7f88eaa0526)");let{newKeystone:h,newDelegates:m}=await d.changePassword({keystoneIbGib:this.ibGib,newMasterSecret:s,signingSecret:o,signingPoolId:"manage",metaspace:u,space:f});this.showBusy({isBusy:!0,title:"Syncing to Server...",msg:"Publishing rotated identity and delegates to server...",animationEmoji:"\u26A1"}),this.setChangePasswordStatus("Syncing evolved keystones to server...","info");let g=(this.ibGib?H({ibGib:this.ibGib}):void 0)||(this.ibGibAddr?(()=>{let{ib:v}=B({ibGibAddr:this.ibGibAddr}),{tjpGib:I}=J({ibGibAddr:this.ibGibAddr});return I&&v?`${v}^${I}`:this.ibGibAddr})():void 0)||_({ibGib:this.ibGib}),b=await D().putEvolveKeystone({domainAddr:g,keystoneIbGib:h,relatedKeystoneIbGibs:m});if(!b.success)throw new Error(`Server synchronization rejected: ${b.message}`);this.setChangePasswordStatus("Updating local indexes...","info");let y=[W({ibGib:h})];m&&m.forEach(v=>{y.push(W({ibGib:v}))}),await se({type:"keystones",rel8nInfos:[{rel8nName:"keystone",ibGibs:y}],metaspace:u,space:f}),this.elements.inputCurrentPasswordEl.value="",this.elements.inputNewPasswordEl.value="",this.elements.inputConfirmPasswordEl.value="",this.setChangePasswordStatus("Password updated successfully!","success"),this.ibGibAddr=_({ibGib:h}),this.staticIbGib=h,await this.loadIbGib({getLatest:!0})}catch(o){debugger;console.error(`${e} Password rotation failed: ${E(o)}`),this.setChangePasswordStatus(`Update failed: ${E(o)}`,"error")}finally{this.showBusy({isBusy:!1})}}};var ed=`:host {
2230
+ `,d.querySelector(".btn-remove-passkey")?.addEventListener("click",()=>this.handleRemovePasskey(a)),t.appendChild(d)}}async handleAddPasskey(){let e=`${this.lc}[${this.handleAddPasskey.name}]`;if(!(!this.ibGib||!this.ibGibAddr))try{let t=rt({keystone:this.ibGib,aggregatedDetails:this.aggregatedDetails}),i=t.isCustodial&&!t.isSovereign;if(!await sr()){this.setPasskeyStatus("WebAuthn PRF extension is not supported in this browser environment.","error");return}this.showBusy({isBusy:!0,title:"Touch Biometrics or Security Key",msg:"Please touch your fingerprint sensor, Face ID, or insert your USB security key when prompted...",animationEmoji:"\u{1F6E1}\uFE0F"});let s=this.aggregatedDetails?.username||this.ibGib.data?.frameDetails?.username||"user",a=crypto.getRandomValues(new Uint8Array(32)),c=wn(a.buffer),d=this.elements?.selectPasskeyAttachmentEl?.value,f=await vn({username:s,displayName:s,salt:c,userVerification:"preferred",authenticatorAttachment:d==="cross-platform"||d==="platform"?d:void 0}),{credentialId:h,transports:m}=f,g=f.passkeySecret;g||(g=(await In({credentialId:h,salt:c,transports:m,userVerification:"preferred"})).passkeySecret);let y=at(),v=`passkey-manage-${bt({text:y,length:12,keepLiterals:["-"]})||"key"}`,I={credentialId:h,poolId:v,name:y,salt:c,createdUTC:new Date().toISOString(),...m&&m.length>0?{transports:m}:{}},C=await k();if(!C)throw new Error("Metaspace not found");let T=await C.getLocalUserSpace({lock:!1});if(!T)throw new Error("Local space not found");let x=new Y,N,S={id:v,type:Mi.hash_reveal_v1,salt:v,algo:ki.sha_256,rounds:1,allowedVerbs:[Le,Pe,Ne],behavior:{size:10,replenish:Li.topUp,selectSequentially:1,selectRandomly:0,targetBindingCount:0}},G=await mn({config:S,masterSecret:g}),P={id:v,config:S,challenges:G},$,F;if(i)this.showBusy({isBusy:!0,title:"Elevating Account Ownership...",msg:"Establishing sovereign passkey pool on identity...",animationEmoji:"\u26A1"}),$=g,F=v,N=await x.addPools({latestKeystone:this.ibGib,masterSecret:$,signingPoolId:F,newPools:[P],frameDetails:{passkeys:{[h]:I}},dataToPatch:{credentialIds:[...this.ibGib.data?.credentialIds||[],h]},metaspace:C,space:T});else{try{let et=await lt({keystone:this.ibGib,aggregatedDetails:this.aggregatedDetails,title:"Authorize New Passkey",msg:"Enter Master Password or touch security key to authorize adding this passkey:",verb:Le});$=et.secret,F=et.poolId}catch{this.setPasskeyStatus("Registration cancelled (authorization required).","error");return}this.showBusy({isBusy:!0,title:"Registering Passkey...",msg:"Adding cryptographic challenge pool and evolving identity...",animationEmoji:"\u{1F6E1}\uFE0F"}),N=await x.addPools({latestKeystone:this.ibGib,masterSecret:$,signingPoolId:F,newPools:[P],frameDetails:{passkeys:{[h]:I}},dataToPatch:{credentialIds:[...this.ibGib.data?.credentialIds||[],h]},metaspace:C,space:T});let jt=H({ibGib:N,defaultIfNone:"incomingAddr"}),en=await D().putEvolveKeystone({domainAddr:jt,keystoneIbGib:N,relatedKeystoneIbGibs:[]});if(!en.success)throw new Error(`Server synchronization of passkey pool failed: ${en.message}`)}this.showBusy({isBusy:!0,title:"Creating Sync Delegate...",msg:"Constructing outward passkey device sync delegate...",animationEmoji:"\u{1F4F1}"});let X=H({ibGib:N,defaultIfNone:"incomingAddr"}),{delegateKeystone:U,deviceTag:oe}=await Cn({username:s,primaryTjpAddr:X,passkeySecret:g,transports:m,metaspace:C,space:T});this.showBusy({isBusy:!0,title:"Registering Delegate...",msg:"Registering outward passkey delegate on primary identity...",animationEmoji:"\u{1F4DD}"});let ve=i?v:F,j=i?g:$;N=await x.registerDelegate({parentKeystone:N,delegateKeystone:U,masterSecret:j,signingPoolId:ve,metaspace:C,space:T,allowedVerbs:[Pe,Ne],deviceName:oe}),this.showBusy({isBusy:!0,title:"Syncing to Server...",msg:"Publishing evolved identity keystone and delegate to server...",animationEmoji:"\u26A1"});let ge=await D().putEvolveKeystone({domainAddr:X,keystoneIbGib:N,relatedKeystoneIbGibs:[U]});if(!ge.success)throw new Error(`Server synchronization of delegate failed: ${ge.message}`);await re({type:"keystones",rel8nInfos:[{rel8nName:"keystone",ibGibs:[J({ibGib:N}),J({ibGib:U})]}],metaspace:C,space:T}),this.setPasskeyStatus("Passkey successfully registered and bound to identity!","success"),this.ibGibAddr=_({ibGib:N}),this.staticIbGib=N,await this.loadIbGib({getLatest:!1})}catch(t){console.error(`${e} ${E(t)}`,t),this.setPasskeyStatus(`Failed to register passkey: ${E(t)}`,"error")}finally{this.showBusy({isBusy:!1})}}async handleRemovePasskey(e){let t=`${this.lc}[${this.handleRemovePasskey.name}]`;if(!this.ibGib||!this.ibGibAddr)return;let i=this.aggregatedDetails?.passkeys?.[e],o=i?.name||"this passkey";try{let s=new Y,a,c;try{let y=await lt({keystone:this.ibGib,aggregatedDetails:this.aggregatedDetails,title:"Authorize Removal",msg:`Are you sure you want to remove "${o}"? Enter your Master Secret (Password) or touch security key to authorize:`,verb:Le});a=y.secret,c=y.poolId}catch{this.setPasskeyStatus("Removal cancelled or unauthorized.","error");return}this.showBusy({isBusy:!0,title:"Revoking Passkey...",msg:"Tombstoning passkey record and removing challenge pool...",animationEmoji:"\u{1F5D1}\uFE0F"});let d=await k();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=i?.poolId||`passkey-manage-${e.substring(0,8)}`,h=this.ibGib.data?.challengePools.some(y=>y.id===f),m=(this.ibGib.data?.credentialIds||[]).filter(y=>y!==e),g;h?g=await s.removePools({latestKeystone:this.ibGib,masterSecret:a,signingPoolId:c,poolIds:[f],frameDetails:{passkeys:{[e]:null}},dataToPatch:{credentialIds:m},metaspace:d,space:u}):g=await s.sign({latestKeystone:this.ibGib,masterSecret:a,poolId:c,claim:{target:_({ibGib:this.ibGib})},frameDetails:{passkeys:{[e]:null}},dataToPatch:{credentialIds:m},metaspace:d,space:u}),this.showBusy({isBusy:!0,title:"Syncing to Server...",msg:"Publishing updated keystone to server...",animationEmoji:"\u26A1"});let b=H({ibGib:g,defaultIfNone:"incomingAddr"});await D().putEvolveKeystone({domainAddr:b,keystoneIbGib:g,relatedKeystoneIbGibs:[]}),await re({type:"keystones",rel8nInfos:[{rel8nName:"keystone",ibGibs:[J({ibGib:g})]}],metaspace:d,space:u}),this.setPasskeyStatus(`Passkey "${o}" successfully removed.`,"success"),this.ibGibAddr=_({ibGib:g}),this.staticIbGib=g,await this.loadIbGib({getLatest:!1})}catch(s){console.error(`${t} ${E(s)}`,s),this.setPasskeyStatus(`Failed to remove passkey: ${E(s)}`,"error")}finally{this.showBusy({isBusy:!1})}}async handleContextUpdated(){let e=`${this.lc}[${this.handleContextUpdated.name}]`;try{we&&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} ${E(t)}`),t}finally{we&&console.log(`${e} complete.`)}}async handleNewContextChild({childIbGib:e}){let t=`${this.lc}[${this.handleNewContextChild.name}]`;try{we&&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} ${E(i)}`),i}finally{we&&console.log(`${t} complete.`)}}async handleSSOLink(e){let t=`${this.lc}[${this.handleSSOLink.name}]`;this.setSSOStatus(`Linking ${e}...`,"info");let i=e==="google"?"Google":e==="github"?"GitHub":e;this.setSSOStatus(`Opening ${i} SSO authorization window...`,"info"),this.showBusy({isBusy:!0,title:`Connecting to ${i}...`,msg:`Opening ${i} SSO authorization window...
2231
+ Please complete authorization in the popup window.`,animationEmoji:"\u{1F310}"});try{let o=(this.ibGib?H({ibGib:this.ibGib}):void 0)||(this.ibGibAddr?(()=>{let{ib:a}=B({ibGibAddr:this.ibGibAddr}),{tjpGib:c}=W({ibGibAddr:this.ibGibAddr});return c&&a?`${a}^${c}`:this.ibGibAddr})():void 0),s=await je({providerId:e,parentTjpAddr:o});if(!s.success||!s.code){this.setSSOStatus(s.message||"Linking cancelled.","error");return}await this.handleSSOLinkCallback(s.code,s.stateObj,s.redirectUri)}catch(o){console.error(`${t} SSO link initiation failed: ${E(o)}`),this.setSSOStatus(`Link failed: ${E(o)}`,"error")}finally{this.showBusy({isBusy:!1})}}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}]`,s=t.providerId==="google"?"Google":t.providerId==="github"?"GitHub":t.providerId;this.setSSOStatus("Retrieving challenge pool configuration from server...","info"),this.showBusy({isBusy:!0,title:`Linking ${s}...`,msg:`Validating ${s} authorization with server...`,animationEmoji:"\u{1F510}"});try{let a=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(!a.ok){let x=await a.json().catch(()=>({}));throw new Error(`Server link exchange failed: ${x.message||a.statusText}`)}let c=await a.json();if(!c.success||!c.custodianPool)throw new Error(`Failed to retrieve custodian challenge pool: ${c.message||"unknown error"}`);let d=c.custodianPool,u=new Y,f,h;try{let x=await lt({keystone:this.ibGib,aggregatedDetails:this.aggregatedDetails,title:`Link ${s}`,msg:`Enter Master Password or touch security key to authorize linking ${s}:`,verb:Le});f=x.secret,h=x.poolId}catch{this.setSSOStatus("Link cancelled or failed.","error");return}this.showBusy({isBusy:!0,title:"Evolving Identity...",msg:`Installing ${s} custodian pool and signing evolution...`,animationEmoji:"\u{1F4DD}"}),this.setSSOStatus("Evolving identity locally and generating cryptographic signatures...","info");let m=await k();if(!m)throw new Error("Metaspace not found");let g=await m.getLocalUserSpace({lock:!1});if(!g)throw new Error("Local space not found");let b=await u.addPools({latestKeystone:this.ibGib,masterSecret:f,signingPoolId:h,newPools:[d],metaspace:m,space:g}),y=await D().putEvolveKeystone({domainAddr:t.parentTjpAddr,keystoneIbGib:b,relatedKeystoneIbGibs:[]});if(!y.success)throw new Error(`Server synchronization of linked pool rejected: ${y.message}`);let w=this.aggregatedDetails?.username||this.ibGib?.data?.username||"user",{delegateKeystone:v,deviceTag:I}=await En({providerId:t.providerId,username:w,primaryTjpAddr:t.parentTjpAddr,custodianReqs:c.custodianReqs,metaspace:m,space:g}),C=await u.registerDelegate({parentKeystone:b,delegateKeystone:v,masterSecret:f,signingPoolId:h,metaspace:m,space:g,allowedVerbs:[Pe,Ne],deviceName:I});await m.put({ibGibs:[v,C],space:g}),this.showBusy({isBusy:!0,title:"Syncing to Server...",msg:"Publishing linked identity and delegate to server...",animationEmoji:"\u26A1"}),this.setSSOStatus("Publishing evolved identity keystone to server...","info");let T=await D().putEvolveKeystone({domainAddr:t.parentTjpAddr,keystoneIbGib:C,relatedKeystoneIbGibs:[v]});if(!T.success)throw new Error(`Server synchronization of delegate rejected: ${T.message}`);await re({type:"keystones",rel8nInfos:[{rel8nName:"keystone",ibGibs:[J({ibGib:C}),J({ibGib:v})]}],metaspace:m,space:g}),this.setSSOStatus(`Successfully linked with ${t.providerId}!`,"success"),this.ibGibAddr=_({ibGib:C}),this.staticIbGib=C,await this.loadIbGib({getLatest:!1})}catch(a){console.error(`${o} SSO callback processing failed: ${E(a)}`),this.setSSOStatus(`Link failed: ${E(a)}`,"error")}finally{this.showBusy({isBusy:!1})}}async handleSSOClick(e){if(this.ibGib?bn({keystone:this.ibGib,aggregatedDetails:this.aggregatedDetails,providerId:e}):!1){if(!rt({keystone:this.ibGib,aggregatedDetails:this.aggregatedDetails}).isSovereign){this.setSSOStatus(`Cannot unlink ${e}: This is your only identity recovery and management method. Please add a Master Password first in the Password card below to enable sovereign ownership before unlinking.`,"error");return}await this.handleSSOUnlink(e)}else await this.handleSSOLink(e)}async handleSSOUnlink(e){let t=`${this.lc}[${this.handleSSOUnlink.name}]`,i=e==="google"?"Google":e==="github"?"GitHub":e;this.setSSOStatus(`Unlinking ${i}...`,"info");try{let o=new Y,s,a;try{let b=await lt({keystone:this.ibGib,aggregatedDetails:this.aggregatedDetails,title:`Unlink ${i}`,msg:`Are you sure you want to unlink your ${i} account? If so, enter your Master Password or touch security key to authorize.`,verb:Le});s=b.secret,a=b.poolId}catch{this.setSSOStatus("Unlink cancelled or failed.","error");return}this.showBusy({isBusy:!0,title:"Unlinking Provider...",msg:`Removing ${i} custodian pool and delegate keys...`,animationEmoji:"\u{1F513}"}),this.setSSOStatus("Evolving identity locally and removing custodian pool...","info");let c=await k();if(!c)throw new Error("Metaspace not found");let d=await c.getLocalUserSpace({lock:!1});if(!d)throw new Error("Local space not found");let u=`custodian-manage-${e}`,f=await o.removePools({latestKeystone:this.ibGib,masterSecret:s,signingPoolId:a,poolIds:[u],metaspace:c,space:d}),h=(this.ibGib?H({ibGib:this.ibGib}):void 0)||(this.ibGibAddr?(()=>{let{ib:b}=B({ibGibAddr:this.ibGibAddr}),{tjpGib:y}=W({ibGibAddr:this.ibGibAddr});return y&&b?`${b}^${y}`:this.ibGibAddr})():void 0)||_({ibGib:this.ibGib});this.showBusy({isBusy:!0,title:"Syncing to Server...",msg:`Publishing ${i} pool removal to server...`,animationEmoji:"\u26A1"}),this.setSSOStatus("Publishing evolved identity keystone to server...","info");let m=await D().putEvolveKeystone({domainAddr:h,keystoneIbGib:f,relatedKeystoneIbGibs:[]});if(!m.success)throw new Error(`Server synchronization rejected: ${m.message}`);let g=f.data?.delegates||this.ibGib?.data?.delegates;if(g){for(let[b,y]of Object.entries(g))if(tr({delegateInfo:y,providerId:e})&&(f=await o.unregisterDelegate({parentKeystone:f,delegateTjpAddr:b,masterSecret:s,signingPoolId:"manage",metaspace:c,space:d}),this.showBusy({isBusy:!0,title:"Syncing to Server...",msg:`Publishing ${i} delegate unregistration to server...`,animationEmoji:"\u26A1"}),m=await D().putEvolveKeystone({domainAddr:h,keystoneIbGib:f,relatedKeystoneIbGibs:[]}),!m.success))throw new Error(`Server synchronization rejected: ${m.message}`)}await re({type:"keystones",rel8nInfos:[{rel8nName:"keystone",ibGibs:[J({ibGib:f})]}],metaspace:c,space:d}),this.setSSOStatus(`Successfully unlinked ${i}!`,"success"),this.ibGibAddr=_({ibGib:f}),this.staticIbGib=f,await this.loadIbGib({getLatest:!1})}catch(o){console.error(`${t} ${E(o)}`,o),this.setSSOStatus(`Failed to unlink ${i}: ${E(o)}`,"error")}finally{this.showBusy({isBusy:!1})}}setChangePasswordStatus(e,t){let i=this.elements.changePasswordStatusEl;i.textContent=e,i.className=`status-msg ${t}`,i.classList.remove("hidden")}async handleAddMasterPassword(){let e=`${this.lc}[${this.handleAddMasterPassword.name}]`;this.setChangePasswordStatus("Validating entries...","info");try{let t=this.elements.inputNewPasswordEl.value,i=this.elements.inputConfirmPasswordEl.value;if(!t){this.setChangePasswordStatus("Master password is required.","error");return}if(t!==i){this.setChangePasswordStatus("Master password and confirmation do not match.","error");return}let o=this.ibGib?.data?.challengePools?.find(y=>y.id===ot);if(!o){this.setChangePasswordStatus("Primary keystone missing active manage challenge pool.","error");return}this.showBusy({isBusy:!0,title:"Elevating Identity...",msg:"Generating cryptographic sovereign challenge pool...",animationEmoji:"\u{1F511}"}),this.setChangePasswordStatus("Generating sovereign challenge pool...","info");let s=await mn({config:o.config,masterSecret:t}),a={id:ot,config:o.config,challenges:s},c=(this.ibGib?H({ibGib:this.ibGib}):void 0)||(this.ibGibAddr?(()=>{let{ib:y}=B({ibGibAddr:this.ibGibAddr}),{tjpGib:w}=W({ibGibAddr:this.ibGibAddr});return w&&y?`${y}^${w}`:this.ibGibAddr})():void 0)||_({ibGib:this.ibGib}),d=this.aggregatedDetails?.custodianProvider||this.ibGib?.data?.frameDetails?.custodianProvider||this.ibGib?.data?.custodianProvider,u={primaryTjpAddr:c,newManagePool:a};if(d==="google"||d==="github"){this.showBusy({isBusy:!0,title:"Re-authenticating with Provider...",msg:`Please complete authentication in the ${d} popup window...`,animationEmoji:"\u{1F512}"}),this.setChangePasswordStatus(`Please authenticate in the popup with ${d} to verify ownership...`,"info");let y=await je({providerId:d,parentTjpAddr:c});if(!y.success||!y.code){this.showBusy({isBusy:!1}),this.setChangePasswordStatus(y.message||"Re-authentication cancelled.","error");return}u.providerId=d,u.code=y.code,u.redirectUri=y.redirectUri}else{let y=this.aggregatedDetails?.emails?.[0]||this.ibGib?.data?.emails?.[0]||this.ibGib?.data?.frameDetails?.emails?.[0];if(!y){this.showBusy({isBusy:!1}),this.setChangePasswordStatus("No email address found for this identity to send verification code.","error");return}let w=this.elements?.sectionAddPasswordOtpEl,v=this.elements?.inputAddPasswordOtpEl;if(!(w&&!w.classList.contains("hidden"))){this.showBusy({isBusy:!0,title:"Sending Verification Code...",msg:`Sending 6-digit verification code to ${y}...`,animationEmoji:"\u{1F4E7}"}),this.setChangePasswordStatus(`Sending verification code to ${y}...`,"info");let T=await D().postVerificationCode({email:y,primaryTjpAddr:c});if(this.showBusy({isBusy:!1}),!T.success){this.setChangePasswordStatus(T.message||"Failed to send verification code.","error");return}w&&w.classList.remove("hidden"),this.elements?.descAddPasswordOtpEl&&(this.elements.descAddPasswordOtpEl.textContent=`A 6-digit verification code was sent to ${y}. Enter it below to establish sovereign ownership:`),this.elements?.btnChangePasswordEl&&(this.elements.btnChangePasswordEl.textContent="Verify Code & Add Master Password"),this.setChangePasswordStatus(`\u2709\uFE0F 6-digit verification code sent to ${y}. Enter the code and click "Verify Code & Add Master Password".`,"info"),this.startResendCooldownTimer(30),v&&(v.value="",v.focus());return}let C=(v?.value||"").trim();if(!C||C.length<6){this.setChangePasswordStatus("Please enter the complete 6-digit verification code sent to your email.","error"),v&&v.focus();return}u.email=y,u.code=C}this.showBusy({isBusy:!0,title:"Updating Keystone Timeline...",msg:"Publishing sovereign master password and evolving identity DAG...",animationEmoji:"\u23F3"}),this.setChangePasswordStatus("Elevating identity to sovereign master password on server...","info");let f=await fetch("/api/identity/custodian/add-master-password",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(u)}),h=await f.json();if(!f.ok||!h.success)throw new Error(h.error||h.message||`Server error (${f.status})`);let m=h.primaryKeystone,g=await k();if(!g)throw new Error("Global metaspace not available");let b=await g.getLocalUserSpace({lock:!1});if(!b)throw new Error("Local user space not available");if(h.primaryGraph){let y=Object.values(h.primaryGraph);await g.put({ibGibs:y,space:b});let w=Se({ibGibs:y});for(let v of Object.keys(w))for(let I of w[v])await g.registerNewIbGib({ibGib:I,space:b})}else await g.put({ibGibs:[m],space:b}),await g.registerNewIbGib({ibGib:m,space:b});await this.registerAndSyncSovereignPasswordDelegate({evolvedParent:m,newPassword:t,primaryTjpAddr:c,metaspace:g,space:b})}catch(t){console.error(`${e} Elevation failed: ${E(t)}`),this.setChangePasswordStatus(`Failed to add master password: ${E(t)}`,"error"),this.elements?.inputAddPasswordOtpEl&&!this.elements.sectionAddPasswordOtpEl?.classList.contains("hidden")&&(this.elements.inputAddPasswordOtpEl.select(),this.elements.inputAddPasswordOtpEl.focus())}finally{this.showBusy({isBusy:!1})}}async handleResendAddPasswordOtp(){let e=`${this.lc}[${this.handleResendAddPasswordOtp.name}]`,t=this.aggregatedDetails?.emails?.[0]||this.ibGib?.data?.emails?.[0]||this.ibGib?.data?.frameDetails?.emails?.[0];if(!t){this.setChangePasswordStatus("No email address found for this identity to send verification code.","error");return}let i=(this.ibGib?H({ibGib:this.ibGib}):void 0)||(this.ibGibAddr?(()=>{let{ib:s}=B({ibGibAddr:this.ibGibAddr}),{tjpGib:a}=W({ibGibAddr:this.ibGibAddr});return a&&s?`${s}^${a}`:this.ibGibAddr})():void 0)||_({ibGib:this.ibGib}),o=this.elements.btnResendAddPasswordOtpEl;o&&(o.disabled=!0,o.textContent="Sending..."),this.setChangePasswordStatus(`Resending verification code to ${t}...`,"info");try{let s=await D().postVerificationCode({email:t,primaryTjpAddr:i});s.success?(this.setChangePasswordStatus(`\u2709\uFE0F Fresh 6-digit verification code sent to ${t}!`,"success"),this.startResendCooldownTimer(30),this.elements?.inputAddPasswordOtpEl&&(this.elements.inputAddPasswordOtpEl.value="",this.elements.inputAddPasswordOtpEl.focus())):(this.setChangePasswordStatus(s.message||"Failed to resend verification code.","error"),o&&(o.disabled=!1,o.textContent="Resend Code"))}catch(s){this.setChangePasswordStatus(`Error resending verification code: ${E(s)}`,"error"),o&&(o.disabled=!1,o.textContent="Resend Code")}}async registerAndSyncSovereignPasswordDelegate({evolvedParent:e,newPassword:t,primaryTjpAddr:i,metaspace:o,space:s}){let a=`${this.lc}[${this.registerAndSyncSovereignPasswordDelegate.name}]`;this.showBusy({isBusy:!0,title:"Creating Sovereign Sync Delegate...",msg:"Deriving local device sync delegate keys from Master Password...",animationEmoji:"\u{1F511}"}),await z(50);let c=this.aggregatedDetails?.username||this.ibGib?.data?.username||this.aggregatedDetails?.emails?.[0]?.split("@")[0]||this.ibGib?.data?.emails?.[0]?.split("@")[0]||"user",{delegateKeystone:d,deviceTag:u}=await yn({username:c,primaryTjpAddr:i,masterSecret:t,metaspace:o,space:s});this.showBusy({isBusy:!0,title:"Registering Sovereign Delegate...",msg:"Registering user sync delegate on primary keystone...",animationEmoji:"\u{1F4DD}"}),await z(50);let h=await new Y().registerDelegate({parentKeystone:e,delegateKeystone:d,masterSecret:t,signingPoolId:ot,metaspace:o,space:s,allowedVerbs:[Pe,Ne],deviceName:u});this.showBusy({isBusy:!0,title:"Syncing to Server...",msg:"Publishing updated domain identity and sovereign delegate to server...",animationEmoji:"\u26A1"});let m=await D().putEvolveKeystone({domainAddr:i,keystoneIbGib:h,relatedKeystoneIbGibs:[d]});if(!m.success)throw new Error(`Server sync of password delegate failed: ${m.message}`);await o.put({ibGibs:[h,d],space:s}),await o.registerNewIbGib({ibGib:h,space:s}),await o.registerNewIbGib({ibGib:d,space:s}),await re({type:"keystones",rel8nInfos:[{rel8nName:"keystone",ibGibs:[J({ibGib:h}),J({ibGib:d})]}],metaspace:o,space:s});let g=_({ibGib:h});return window.dispatchEvent(new CustomEvent(Ce,{detail:{activeIdentityAddr:g},bubbles:!0,composed:!0})),this.setChangePasswordStatus("Successfully added Master Password! Identity is now sovereign.","success"),this.elements?.sectionAddPasswordOtpEl&&(this.elements.sectionAddPasswordOtpEl.classList.add("hidden"),this.elements.inputAddPasswordOtpEl&&(this.elements.inputAddPasswordOtpEl.value="")),this.elements?.btnChangePasswordEl&&(this.elements.btnChangePasswordEl.textContent="Update Password"),this.ibGibAddr=g,this.staticIbGib=h,await this.loadIbGib({getLatest:!0}),this.elements.inputNewPasswordEl.value="",this.elements.inputConfirmPasswordEl.value="",h}async handleAddPasswordToPasskeyIdentity(){let e=`${this.lc}[${this.handleAddPasswordToPasskeyIdentity.name}]`;this.setChangePasswordStatus("Validating entries...","info");try{let t=this.elements.inputNewPasswordEl.value,i=this.elements.inputConfirmPasswordEl.value;if(!t){this.setChangePasswordStatus("Master password is required.","error");return}if(t!==i){this.setChangePasswordStatus("Master password and confirmation do not match.","error");return}let o=this.aggregatedDetails?.passkeys||this.ibGib?.data?.frameDetails?.passkeys||this.ibGib?.data?.passkeys||{},s=Array.isArray(o)?o:Object.values(o);if(!this.ibGib?.data?.challengePools?.find(I=>I.id.startsWith("passkey-manage-"))){this.setChangePasswordStatus("No active passkey manage pool found on this identity.","error");return}let c,d;try{let I=await lt({keystone:this.ibGib,aggregatedDetails:this.aggregatedDetails,title:"Authorize Master Password",msg:"Please touch your fingerprint sensor, Face ID, or security key to authorize adding a Master Password...",verb:Le});c=I.secret,d=I.poolId}catch{this.setChangePasswordStatus("Authorization cancelled.","error");return}this.showBusy({isBusy:!0,title:"Adding Master Password...",msg:"Compiling cryptographic master password pool and evolving identity...",animationEmoji:"\u{1F511}"}),await z(50),this.setChangePasswordStatus("Generating sovereign master password challenge pool...","info");let u=await k();if(!u)throw new Error("Global metaspace not available");let f=await u.getLocalUserSpace({lock:!1});if(!f)throw new Error("Local user space not available");let h={id:ot,type:Mi.hash_reveal_v1,salt:ot,algo:ki.sha_256,rounds:1,allowedVerbs:[Le,Pe,Ne],behavior:{size:10,replenish:Li.topUp,selectSequentially:1,selectRandomly:0,targetBindingCount:0}},m=await mn({config:h,masterSecret:t}),g={id:ot,config:h,challenges:m},b=(this.ibGib?H({ibGib:this.ibGib}):void 0)||(this.ibGibAddr?(()=>{let{ib:I}=B({ibGibAddr:this.ibGibAddr}),{tjpGib:C}=W({ibGibAddr:this.ibGibAddr});return C&&I?`${I}^${C}`:this.ibGibAddr})():void 0)||_({ibGib:this.ibGib}),w=await new Y().sign({latestKeystone:this.ibGib,claim:{target:b,verb:Le},masterSecret:c,poolId:d,dataToPatch:{challengePools:[...this.ibGib.data.challengePools||[],g]},metaspace:u,space:f});this.showBusy({isBusy:!0,title:"Syncing to Server...",msg:"Publishing updated identity to server...",animationEmoji:"\u26A1"});let v=await D().putEvolveKeystone({domainAddr:b,keystoneIbGib:w,relatedKeystoneIbGibs:[]});if(!v.success)throw new Error(`Server sync failed: ${v.message}`);await u.put({ibGibs:[w],space:f}),await u.registerNewIbGib({ibGib:w,space:f}),await this.registerAndSyncSovereignPasswordDelegate({evolvedParent:w,newPassword:t,primaryTjpAddr:b,metaspace:u,space:f})}catch(t){console.error(`${e} Failed to add password to passkey identity: ${E(t)}`,t),this.setChangePasswordStatus(`Failed to add master password: ${E(t)}`,"error")}finally{this.showBusy({isBusy:!1})}}async handleChangePassword(){let e=`${this.lc}[${this.handleChangePassword.name}]`,t=this.ibGib?rt({keystone:this.ibGib,aggregatedDetails:this.aggregatedDetails}):void 0;if(!!!t?.hasPassword){(t?t.isCustodial&&!t.isSovereign:!1)?await this.handleAddMasterPassword():await this.handleAddPasswordToPasskeyIdentity();return}this.setChangePasswordStatus("Validating entries...","info"),this.showBusy({isBusy:!0,title:"Changing Master Password...",msg:"Validating current password...",animationEmoji:"\u{1F510}"});try{let o=this.elements.inputCurrentPasswordEl.value,s=this.elements.inputNewPasswordEl.value,a=this.elements.inputConfirmPasswordEl.value;if(!o){this.setChangePasswordStatus("Current password is required.","error");return}if(!s){this.setChangePasswordStatus("New password is required.","error");return}if(s!==a){this.setChangePasswordStatus("New password and confirmation do not match.","error");return}let c=new Y;if(!await c.verifySigningSecret({keystoneIbGib:this.ibGib,signingSecret:o,poolId:"manage"})){this.setChangePasswordStatus("Incorrect current password.","error");return}this.showBusy({isBusy:!0,title:"Evolving Master Password...",msg:"Generating new challenge proofs and rotating local user delegates...",animationEmoji:"\u2699\uFE0F"}),this.setChangePasswordStatus("Evolving primary identity keystone...","info");let u=await k();if(!u)throw new Error("(UNEXPECTED) metaspace falsy? (E: 95e3c8374b0f088f339f5c5a8700f826)");let f=await u.getLocalUserSpace({lock:!1});if(!f)throw new Error("(UNEXPECTED) couldn't get default local space? (E: 2fc1281c28351fd378a1d7f88eaa0526)");let{newKeystone:h,newDelegates:m}=await c.changePassword({keystoneIbGib:this.ibGib,newMasterSecret:s,signingSecret:o,signingPoolId:"manage",metaspace:u,space:f});this.showBusy({isBusy:!0,title:"Syncing to Server...",msg:"Publishing rotated identity and delegates to server...",animationEmoji:"\u26A1"}),this.setChangePasswordStatus("Syncing evolved keystones to server...","info");let g=(this.ibGib?H({ibGib:this.ibGib}):void 0)||(this.ibGibAddr?(()=>{let{ib:v}=B({ibGibAddr:this.ibGibAddr}),{tjpGib:I}=W({ibGibAddr:this.ibGibAddr});return I&&v?`${v}^${I}`:this.ibGibAddr})():void 0)||_({ibGib:this.ibGib}),b=await D().putEvolveKeystone({domainAddr:g,keystoneIbGib:h,relatedKeystoneIbGibs:m});if(!b.success)throw new Error(`Server synchronization rejected: ${b.message}`);this.setChangePasswordStatus("Updating local indexes...","info");let y=[J({ibGib:h})];m&&m.forEach(v=>{y.push(J({ibGib:v}))}),await re({type:"keystones",rel8nInfos:[{rel8nName:"keystone",ibGibs:y}],metaspace:u,space:f}),this.elements.inputCurrentPasswordEl.value="",this.elements.inputNewPasswordEl.value="",this.elements.inputConfirmPasswordEl.value="",this.setChangePasswordStatus("Password updated successfully!","success"),this.ibGibAddr=_({ibGib:h}),this.staticIbGib=h,await this.loadIbGib({getLatest:!0})}catch(o){debugger;console.error(`${e} Password rotation failed: ${E(o)}`),this.setChangePasswordStatus(`Update failed: ${E(o)}`,"error")}finally{this.showBusy({isBusy:!1})}}};var ac=`:host {
2232
2232
  display: block;
2233
2233
  width: 100%;
2234
2234
  max-width: 100%;
@@ -2274,7 +2274,7 @@ Please complete authorization in the popup window.`,animationEmoji:"\u{1F310}"})
2274
2274
  flex-direction: column;
2275
2275
  gap: 1.5rem;
2276
2276
  }
2277
- `;var td=`<div id="container" class="scrubber-container">
2277
+ `;var lc=`<div id="container" class="scrubber-container">
2278
2278
  <div class="scrubber-nav">
2279
2279
  <button id="btn-scrub-first" class="action-btn scrubber-btn" title="First Frame">&lt;&lt;</button>
2280
2280
  <button id="btn-scrub-prev10" class="action-btn scrubber-btn" title="Back 10 Frames">-10</button>
@@ -2289,7 +2289,7 @@ Please complete authorization in the popup window.`,animationEmoji:"\u{1F310}"})
2289
2289
  <!-- Details component for the active frame will be injected here -->
2290
2290
  </div>
2291
2291
  </div>
2292
- `;var Ae=!1,nd="ibgib-keystone-scrubber",_i=class extends fe{static{p(this,"KeystoneScrubberComponentMeta")}lc="[KeystoneScrubberComponentMeta]";routeRegExp=new RegExp(`^${nd}$`);componentName=nd;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:td,css:[me,ed]}),o}},Ts=class n extends Qt{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]`;Ae&&console.log(`${e} (I: 3adca837d5c898d8e839d23c59538126)`),super()}async initialize(e){let t=`${this.lc}[${this.initialize.name}]`;try{Ae&&console.log(`${t} starting... (I: 75eecfc01af7f3fa9897932ec5457526)`),await super.initialize(e),await this.loadIbGib()}catch(i){throw console.error(`${t} ${E(i)}`),i}finally{Ae&&console.log(`${t} complete.`)}}async created(){let e=`${this.lc}[${this.created.name}]`;try{Ae&&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: ${E(i)}`))}catch(t){throw console.error(`${e} ${E(t)}`),t}finally{Ae&&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(Ae&&console.log(`${e} starting... (I: a4a9181bbb58a22cc71c8745a91ec426)`),!this.ibGibAddr)return;await super.loadIbGib(),await this.loadHistoryData()}catch(t){throw console.error(`${e} ${E(t)}`),t}finally{Ae&&console.log(`${e} complete.`)}}async activateIbGib({addr:e,ibGib:t}){let i=`${this.lc}[activateIbGib]`;try{if(Ae&&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 de()).inject({parentEl:this.elements.contentEl,componentToInject:o.component})}catch(o){console.error(`${i} ${E(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 k();if(!i)return;let o=await i.getLocalUserSpace({lock:!1});if(!o)return;let s=e,a=[];for(;s;){let d=await i.get({addr:s,space:o});if(!d.success||!d.ibGibs||d.ibGibs.length===0){console.warn(`${t} Could not find frame at ${s}`);break}let c=d.ibGibs[0];if(a.push(s),c.data?.n===0)break;let u=c.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(Ae&&console.log(`${i} starting... (I: 9eea188f6b55f04b483fbda8a110f826)`),!e)throw new Error("(UNEXPECTED) addr falsy?");let o=J({ibGibAddr:e}).tjpGib??B({ibGibAddr:e}).gib,s=p(async()=>{let u=await(await de()).getComponentInstance({path:"ibgib-keystone-details",ibGibAddr:e,useRegExpPrefilter:!0});if(!u)throw new Error("(UNEXPECTED) detailsComponent falsy?");return u},"fnCreateAndLoadChildComponent"),a,d=this.childInfos.filter(c=>c.addr===e);if(d.length>0){if(d.length!==1)throw new Error("(UNEXPECTED) filtered.length !== 1?");a=d[0],a.component||(a.component=await s())}else{let c=await s();t=c.ibGib??t;let u=await this.addChild({addr:e,ibGib:t});a={addr:e,childBtnEl:u,component:c,active:!1},this.childInfos.push(a)}return a}catch(o){throw console.error(`${i} ${E(o)}`),o}finally{Ae&&console.log(`${i} complete.`)}}async addChild({addr:e,ibGib:t}){let i=`${this.lc}[${this.addChild.name}]`;try{Ae&&console.log(`${i} starting... (I: 824f98b6f9a2c922f8b3a9f67ad63e26)`);let o=document.createElement("div");return o.style.display="none",o}catch(o){throw console.error(`${i} ${E(o)}`),o}finally{Ae&&console.log(`${i} complete.`)}}};var id=`:host {
2292
+ `;var Ae=!1,cc="ibgib-keystone-scrubber",Pi=class extends ae{static{p(this,"KeystoneScrubberComponentMeta")}lc="[KeystoneScrubberComponentMeta]";routeRegExp=new RegExp(`^${cc}$`);componentName=cc;constructor(){super(he()),customElements.get(this.componentName)||customElements.define(this.componentName,xs)}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:lc,css:[ue,ac]}),o}},xs=class n extends Zt{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]`;Ae&&console.log(`${e} (I: 3adca837d5c898d8e839d23c59538126)`),super()}async initialize(e){let t=`${this.lc}[${this.initialize.name}]`;try{Ae&&console.log(`${t} starting... (I: 75eecfc01af7f3fa9897932ec5457526)`),await super.initialize(e),await this.loadIbGib()}catch(i){throw console.error(`${t} ${E(i)}`),i}finally{Ae&&console.log(`${t} complete.`)}}async created(){let e=`${this.lc}[${this.created.name}]`;try{Ae&&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: ${E(i)}`))}catch(t){throw console.error(`${e} ${E(t)}`),t}finally{Ae&&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(Ae&&console.log(`${e} starting... (I: a4a9181bbb58a22cc71c8745a91ec426)`),!this.ibGibAddr)return;await super.loadIbGib(),await this.loadHistoryData()}catch(t){throw console.error(`${e} ${E(t)}`),t}finally{Ae&&console.log(`${e} complete.`)}}async activateIbGib({addr:e,ibGib:t}){let i=`${this.lc}[activateIbGib]`;try{if(Ae&&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 ne()).inject({parentEl:this.elements.contentEl,componentToInject:o.component})}catch(o){console.error(`${i} ${E(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 k();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(Ae&&console.log(`${i} starting... (I: 9eea188f6b55f04b483fbda8a110f826)`),!e)throw new Error("(UNEXPECTED) addr falsy?");let o=W({ibGibAddr:e}).tjpGib??B({ibGibAddr:e}).gib,s=p(async()=>{let u=await(await ne()).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} ${E(o)}`),o}finally{Ae&&console.log(`${i} complete.`)}}async addChild({addr:e,ibGib:t}){let i=`${this.lc}[${this.addChild.name}]`;try{Ae&&console.log(`${i} starting... (I: 824f98b6f9a2c922f8b3a9f67ad63e26)`);let o=document.createElement("div");return o.style.display="none",o}catch(o){throw console.error(`${i} ${E(o)}`),o}finally{Ae&&console.log(`${i} complete.`)}}};var dc=`:host {
2293
2293
  display: block;
2294
2294
  width: 100%;
2295
2295
  margin: 1rem auto;
@@ -2497,7 +2497,7 @@ Please complete authorization in the popup window.`,animationEmoji:"\u{1F310}"})
2497
2497
  margin: 0;
2498
2498
  font-size: 0.85rem;
2499
2499
  color: #a6adc8;
2500
- }`;var od=`<div id="container" class="component-container">
2500
+ }`;var uc=`<div id="container" class="component-container">
2501
2501
  <h2 id="title">Sign In to Device</h2>
2502
2502
  <div class="content">
2503
2503
  <p id="subtitle" style="margin-bottom: 1.25rem; font-size: 0.95rem; color: #a6adc8;">
@@ -2621,8 +2621,8 @@ Please complete authorization in the popup window.`,animationEmoji:"\u{1F310}"})
2621
2621
  <p class="warning">\u2705 This device is now authorized to sync with your primary identity.</p>
2622
2622
  </div>
2623
2623
  </div>
2624
- </div>`;var sd="ibgib-add-device",Ai=class extends fe{static{p(this,"AddDeviceComponentMeta")}lc="[AddDeviceComponentMeta]";routeRegExp=new RegExp(`^${sd}$`);componentName=sd;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:od,css:[me,id]}),i}},Ss=class extends Ze{static{p(this,"AddDeviceComponentInstance")}lc="[AddDeviceComponentInstance]";_stagedEmail;_stagedPrimaryTjpAddr;_stagedPrimaryKeystone;_stagedPrimaryGraph;constructor(){super()}async initialize(e){await super.initialize(e)}async created(){let e=this.shadowRoot,t={};t.containerEl=e.getElementById("container"),t.titleEl=e.getElementById("title"),t.subtitleEl=e.getElementById("subtitle"),t.surfaceEntryEl=e.getElementById("surface-entry"),t.btnGoogleSso=e.getElementById("btn-google-sso"),t.btnGithubSso=e.getElementById("btn-github-sso"),t.inputIdentifier=e.getElementById("input-identifier"),t.btnContinueEmail=e.getElementById("btn-continue-email"),t.sectionCodeVerification=e.getElementById("section-code-verification"),t.inputCode=e.getElementById("input-code"),t.btnVerifyCode=e.getElementById("btn-verify-code"),t.sectionSovereignPassword=e.getElementById("section-sovereign-password"),t.inputPassword=e.getElementById("input-password"),t.btnAuthorizePassword=e.getElementById("btn-authorize-password"),t.inputDeviceTag=e.getElementById("input-device-tag"),t.checkboxMakeActive=e.getElementById("checkbox-make-active"),t.statusArea=e.getElementById("status-area"),t.statusText=e.getElementById("status-text"),t.resultAreaEl=e.getElementById("result-area"),t.delegateAddrEl=e.getElementById("delegate-addr"),t.contentEl=t.containerEl,this.elements=t,t.inputDeviceTag&&!t.inputDeviceTag.value&&(t.inputDeviceTag.value=at()),this.initHandlers(),await this.renderUI()}async disconnected(){}initHandlers(){let e=this.elements;e.btnGoogleSso?.addEventListener("click",()=>this.handleSsoClick("google")),e.btnGithubSso?.addEventListener("click",()=>this.handleSsoClick("github")),e.btnContinueEmail?.addEventListener("click",()=>this.handleContinueEmail()),e.btnVerifyCode?.addEventListener("click",()=>this.handleVerifyCode()),e.btnAuthorizePassword?.addEventListener("click",()=>this.handleAuthorizePassword()),this.shadowRoot.getElementById("btn-switch-create-account")?.addEventListener("click",t=>{t.preventDefault(),window.dispatchEvent(new CustomEvent(oe,{detail:{action:"show-keystone-creator"},bubbles:!0,composed:!0}))}),e.inputIdentifier?.addEventListener("input",()=>{e.inputIdentifier.classList.remove("invalid")}),e.inputCode?.addEventListener("input",()=>{e.inputCode.classList.remove("invalid")}),e.inputPassword?.addEventListener("input",()=>{e.inputPassword.classList.remove("invalid")}),e.inputDeviceTag?.addEventListener("input",()=>{e.inputDeviceTag.classList.remove("invalid")})}getDeviceTag(){let e=this.elements,t=e.inputDeviceTag?.value?.trim();if(t&&qt.test(t))return t;let i=at();return e.inputDeviceTag&&(e.inputDeviceTag.value=i),i}async handleSsoClick(e){let t=`${this.lc}[${this.handleSsoClick.name}]`,i=e==="google"?"Google":"GitHub";this.setStatus(`Opening ${i} sign-in window...`,"info"),this.showBusy({isBusy:!0,title:"Sign In via SSO",msg:`Opening ${i} authorization window...
2625
- Please complete sign-in in the popup window.`,animationEmoji:"\u{1F310}"});try{let o=await je({providerId:e});if(!o.success||!o.code){this.setStatus(o.message||`${i} sign-in cancelled.`,"error");return}this.setStatus(`Validating ${i} authorization...`,"info"),this.showBusy({isBusy:!0,title:"Exchanging SSO Code...",msg:`Validating ${i} authorization with server...`,animationEmoji:"\u{1F510}"});let a=await D().postSsoLogin({code:o.code,providerId:e,redirectUri:o.redirectUri});if(!a.success||!a.primaryTjpAddr||!a.custodianReqs){this.setStatus(a.message||`${i} login failed.`,"error");return}let{primaryTjpAddr:d,custodianReqs:c,primaryKeystone:u}=a,f=a.userInfo?.email||"",h=f?f.split("@")[0]:"user";await this.completeCustodialDelegateOnboarding({primaryTjpAddr:d,custodianReqs:c,fallbackPrimaryKeystone:u,fallbackPrimaryGraph:a.primaryGraph,email:f,username:h})}catch(o){let s=E(o);console.error(`${t} SSO login error: ${s}`,o),this.setStatus(`Error: ${s}`,"error")}finally{this.showBusy({isBusy:!1})}}async handleContinueEmail(){let e=`${this.lc}[${this.handleContinueEmail.name}]`,t=this.elements,i=t.inputIdentifier?.value?.trim();if(!i||!st(i)){t.inputIdentifier.classList.add("invalid"),this.setStatus("Please enter a valid email address.","error");return}t.btnContinueEmail.disabled=!0,t.btnContinueEmail.textContent="Checking...",this.setStatus("Checking identity on server...","info"),this.showBusy({isBusy:!0,title:"Locating Identity...",msg:"Locating account on server...",animationEmoji:"\u{1F50D}"});try{let o=await D().lookupPrimaryKeystone({identifier:i});if(!o.success||!o.tjpAddr){this.setStatus('No account found for this email address. Please click "Create Account" below.',"error");return}this._stagedEmail=i,this._stagedPrimaryTjpAddr=o.tjpAddr,this.setStatus("Dispatching 6-digit verification code...","info"),this.showBusy({isBusy:!0,title:"Sending Code...",msg:"Dispatching 6-digit verification code to your email...",animationEmoji:"\u2709\uFE0F"});let s=await D().postVerificationCode({email:i,primaryTjpAddr:this._stagedPrimaryTjpAddr});if(!s.success){this.setStatus(s.message||"Failed to dispatch verification code.","error");return}t.sectionCodeVerification.classList.remove("hidden"),t.sectionCodeVerification.scrollIntoView({behavior:"smooth"}),this.setStatus(`Verification code sent to ${i}! Enter the 6-digit code above to continue.`,"info"),t.inputCode?.focus()}catch(o){let s=E(o);console.error(`${e} ${s}`,o),this.setStatus(`Error: ${s}`,"error")}finally{t.btnContinueEmail.disabled=!1,t.btnContinueEmail.textContent="Continue with Email",this.showBusy({isBusy:!1})}}async handleVerifyCode(){let e=`${this.lc}[${this.handleVerifyCode.name}]`,t=this.elements,i=t.inputCode?.value?.trim(),o=this._stagedEmail,s=this._stagedPrimaryTjpAddr;if(!o||!s){this.setStatus("Please enter your email and request a code first.","error");return}if(!i||i.length!==6){t.inputCode.classList.add("invalid"),this.setStatus("Please enter a 6-digit verification code.","error");return}t.btnVerifyCode.disabled=!0,t.btnVerifyCode.textContent="Verifying...",this.setStatus("Verifying 6-digit code...","info"),this.showBusy({isBusy:!0,title:"Verifying Code...",msg:"Validating verification code with server...",animationEmoji:"\u{1F510}"});try{let a=await D().postCustodianGenesis({email:o,code:i});if(a.success&&a.primaryTjpAddr&&a.custodianReqs){let{primaryTjpAddr:h,custodianReqs:m,primaryKeystone:g,primaryGraph:b}=a,y=o?o.split("@")[0]:"user";await this.completeCustodialDelegateOnboarding({primaryTjpAddr:h,custodianReqs:m,fallbackPrimaryKeystone:g,fallbackPrimaryGraph:b,email:o,username:y});return}let d=await D().postVerifyCode({email:o,primaryTjpAddr:s,code:i});if(!d.success){this.setStatus(d.message||"Verification failed. Please check the code.","error");return}this.setStatus("Retrieving identity graph from server...","info"),this.showBusy({isBusy:!0,title:"Loading Identity Graph...",msg:"Fetching cryptographic identity timeline from server...",animationEmoji:"\u{1F4E5}"});let c=await D().getKeystoneGraph(s);if(!c.success||!c.graph){this.setStatus("Failed to retrieve identity graph from server.","error");return}this._stagedPrimaryGraph=c.graph;let u=await k(),f=await u.getLocalUserSpace({});if(f){let h=Object.values(c.graph);await u.put({ibGibs:h,space:f});let m=Se({ibGibs:h});for(let b of Object.keys(m))for(let y of m[b])await u.registerNewIbGib({ibGib:y,space:f});let g=m[s]||m[Object.keys(m)[0]];g&&g.length>0&&(this._stagedPrimaryKeystone=g[g.length-1])}t.sectionCodeVerification.classList.add("hidden"),t.sectionSovereignPassword.classList.remove("hidden"),t.sectionSovereignPassword.scrollIntoView({behavior:"smooth"}),this.setStatus("2FA verified! Please enter your master password to authorize this device.","info"),t.inputPassword?.focus()}catch(a){let d=E(a);console.error(`${e} ${d}`,a),this.setStatus(`Error: ${d}`,"error")}finally{t.btnVerifyCode.disabled=!1,t.btnVerifyCode.textContent="Verify Code",this.showBusy({isBusy:!1})}}async completeCustodialDelegateOnboarding({primaryTjpAddr:e,custodianReqs:t,fallbackPrimaryKeystone:i,fallbackPrimaryGraph:o,email:s,username:a}){let d=`${this.lc}[${this.completeCustodialDelegateOnboarding.name}]`,c=this.getDeviceTag();this.setStatus("Deriving local device delegate keys...","info"),this.showBusy({isBusy:!0,title:"Creating Sync Delegate...",msg:`Generating cryptographic sync delegate keys for ${c}...`,animationEmoji:"\u{1F511}"});let u=await k(),f=await u.getLocalUserSpace({lock:!1});if(!f){this.setStatus("Could not access local user space.","error");return}let h=await Qs({primaryTjpAddr:e,deviceTag:c}),m=a||(s?s.split("@")[0]:"user"),g="sync-profile.dev";if(!g||!g.trim())throw new Error('KEYSTONE_PROFILE_CUSTODIAN_SYNC environment variable is missing. Expected valid profile name like "sync-profile.dev" or "sync-profile.prod". (E: 4d5e6f7890123456789abcdef4)');let b=await Li({profileName:g.trim(),username:m,deviceTag:c,primaryTjpAddr:e,delegateSecret:h,custodianReqs:t,additionalFrameDetails:{client:"space-gib-web"},metaspace:u,space:f});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{1F504}"});let y=await D().postCustodianRegisterDelegate({delegateKeystone:b});if(!y.success){this.setStatus(y.message||"Custodian delegate registration failed.","error");return}await this.finalizeDeviceOnboarding({primaryKeystone:y.evolvedPrimaryKeystone||i,primaryGraph:y.primaryGraph||o,delegateKeystone:b,primaryTjpAddr:e,delegateSecret:h,makeActive:this.elements?.checkboxMakeActive?.checked??!0})}async handleAuthorizePassword(){let e=`${this.lc}[${this.handleAuthorizePassword.name}]`,t=this.elements,i=t.inputPassword?.value?.trim(),o=this._stagedPrimaryKeystone,s=this._stagedPrimaryTjpAddr;if(!i){t.inputPassword.classList.add("invalid"),this.setStatus("Please enter your master password.","error");return}if(!o||!s){this.setStatus("Missing staged primary identity context. Please restart sign-in.","error");return}t.btnAuthorizePassword.disabled=!0,t.btnAuthorizePassword.textContent="Authorizing...",this.setStatus("Verifying master password locally...","info"),this.showBusy({isBusy:!0,title:"Verifying Password...",msg:"Verifying cryptographic password locally in browser...",animationEmoji:"\u{1F510}"});try{let a=new Y;if(!await a.verifySigningSecret({keystoneIbGib:o,signingSecret:i,poolId:"manage"})){t.inputPassword.classList.add("invalid"),this.setStatus("Incorrect master password. Please try again.","error");return}let c=this.getDeviceTag(),u=o.data?.frameDetails?.username||"user";this.setStatus(`Generating local sync delegate for ${c}...`,"info"),this.showBusy({isBusy:!0,title:"Generating Keys...",msg:`Generating cryptographic delegate keys for ${c}...`,animationEmoji:"\u{1F511}"});let f=await k(),h=await f.getLocalUserSpace({});if(!h)throw new Error("No default space found in metaspace.");let m=await Ws({masterSecret:i});await Xs({primaryTjpAddr:s,delegateSecret:m});let g="sync-profile.dev";if(!g||!g.trim())throw new Error('KEYSTONE_PROFILE_SOVEREIGN_SYNC environment variable is missing. Expected valid profile name like "sync-profile.dev" or "sync-profile.prod". (E: 8f9e0a1b2c3d4e5f67890123456789ab)');let b=await Li({profileName:g.trim(),username:u,deviceTag:c,primaryTjpAddr:s,delegateSecret:m,additionalFrameDetails:{client:"space-gib-web"},metaspace:f,space:h});this.setStatus("Evolving primary identity to register delegate...","info"),this.showBusy({isBusy:!0,title:"Registering Device...",msg:"Evolving primary identity to register new device delegate...",animationEmoji:"\u2699\uFE0F"});let y=await a.registerDelegate({parentKeystone:o,delegateKeystone:b,masterSecret:i,signingPoolId:"manage",allowedVerbs:[Pe,Ge],metaspace:f,space:h,deviceName:c});this.setStatus("Publishing evolved identity to server...","info"),this.showBusy({isBusy:!0,title:"Syncing to Server...",msg:"Publishing evolved identity and delegate to server...",animationEmoji:"\u26A1"});let w=await D().putEvolveKeystone({domainAddr:s,keystoneIbGib:y,relatedKeystoneIbGibs:[b]});w.success||console.warn(`${e} Warning syncing delegate evolution to server: ${w.message}`),await this.finalizeDeviceOnboarding({primaryKeystone:y,primaryGraph:this._stagedPrimaryGraph,delegateKeystone:b,primaryTjpAddr:s,masterSecret:i,delegateSecret:m,makeActive:t.checkboxMakeActive?.checked??!0})}catch(a){let d=E(a);console.error(`${e} ${d}`,a),this.setStatus(`Error: ${d}`,"error")}finally{t.btnAuthorizePassword.disabled=!1,t.btnAuthorizePassword.textContent="Authorize & Pair Device",this.showBusy({isBusy:!1})}}async finalizeDeviceOnboarding({primaryKeystone:e,primaryGraph:t,delegateKeystone:i,primaryTjpAddr:o,masterSecret:s,delegateSecret:a,makeActive:d=!0}){let c=`${this.lc}[${this.finalizeDeviceOnboarding.name}]`,u=500,f=await k();if(!f)throw new Error("Metaspace not found");let h=await f.getLocalUserSpace({});if(!h)throw new Error("Local user space not found");if(t){let y=Object.values(t);await f.put({ibGibs:y,space:h});let w=Se({ibGibs:y});for(let v of Object.keys(w))for(let I of w[v])await f.registerNewIbGib({ibGib:I,space:h})}else e&&(await f.put({ibGibs:[e],space:h}),await f.registerNewIbGib({ibGib:e,space:h}));await f.put({ibGibs:[i],space:h}),await f.registerNewIbGib({ibGib:i,space:h});let m=[W({ibGib:i})];e&&m.unshift(W({ibGib:e})),await se({type:"keystones",rel8nInfos:[{rel8nName:"keystone",ibGibs:m}],metaspace:f,space:h}),d&&window.dispatchEvent(new CustomEvent(Me,{detail:{activeIdentityAddr:o},bubbles:!0,composed:!0}));let g=_({ibGib:i});this.elements?.delegateAddrEl&&(this.elements.delegateAddrEl.textContent=g),this.elements?.resultAreaEl&&this.elements.resultAreaEl.classList.remove("collapsed");let b="Device paired and identity activated successfully!";this.setStatus(b,"success"),this.showBusy({isBusy:!0,title:"Success!",msg:b,animationEmoji:"\u2705"}),await z(u),this.elements?.inputPassword&&(this.elements.inputPassword.value=""),window.dispatchEvent(new CustomEvent(oe,{detail:{action:"show-identity-manager",addr:o},bubbles:!0,composed:!0})),this.showBusy({isBusy:!1})}async renderUI(){}async handleContextUpdated(){await this.renderUI()}};var rd=`:host {
2624
+ </div>`;var fc="ibgib-add-device",Ni=class extends ae{static{p(this,"AddDeviceComponentMeta")}lc="[AddDeviceComponentMeta]";routeRegExp=new RegExp(`^${fc}$`);componentName=fc;constructor(){super(he()),customElements.get(this.componentName)||customElements.define(this.componentName,Ps)}async createInstance({path:e,ibGibAddr:t}){let i=document.createElement(this.componentName);return await i.initialize({ibGibAddr:t,meta:this,html:uc,css:[ue,dc]}),i}},Ps=class extends Ze{static{p(this,"AddDeviceComponentInstance")}lc="[AddDeviceComponentInstance]";_stagedEmail;_stagedPrimaryTjpAddr;_stagedPrimaryKeystone;_stagedPrimaryGraph;constructor(){super()}async initialize(e){await super.initialize(e)}async created(){let e=this.shadowRoot,t={};t.containerEl=e.getElementById("container"),t.titleEl=e.getElementById("title"),t.subtitleEl=e.getElementById("subtitle"),t.surfaceEntryEl=e.getElementById("surface-entry"),t.btnGoogleSso=e.getElementById("btn-google-sso"),t.btnGithubSso=e.getElementById("btn-github-sso"),t.inputIdentifier=e.getElementById("input-identifier"),t.btnContinueEmail=e.getElementById("btn-continue-email"),t.sectionCodeVerification=e.getElementById("section-code-verification"),t.inputCode=e.getElementById("input-code"),t.btnVerifyCode=e.getElementById("btn-verify-code"),t.sectionSovereignPassword=e.getElementById("section-sovereign-password"),t.inputPassword=e.getElementById("input-password"),t.btnAuthorizePassword=e.getElementById("btn-authorize-password"),t.inputDeviceTag=e.getElementById("input-device-tag"),t.checkboxMakeActive=e.getElementById("checkbox-make-active"),t.statusArea=e.getElementById("status-area"),t.statusText=e.getElementById("status-text"),t.resultAreaEl=e.getElementById("result-area"),t.delegateAddrEl=e.getElementById("delegate-addr"),t.contentEl=t.containerEl,this.elements=t,t.inputDeviceTag&&!t.inputDeviceTag.value&&(t.inputDeviceTag.value=at()),this.initHandlers(),await this.renderUI()}async disconnected(){}initHandlers(){let e=this.elements;e.btnGoogleSso?.addEventListener("click",()=>this.handleSsoClick("google")),e.btnGithubSso?.addEventListener("click",()=>this.handleSsoClick("github")),e.btnContinueEmail?.addEventListener("click",()=>this.handleContinueEmail()),e.btnVerifyCode?.addEventListener("click",()=>this.handleVerifyCode()),e.btnAuthorizePassword?.addEventListener("click",()=>this.handleAuthorizePassword()),this.shadowRoot.getElementById("btn-switch-create-account")?.addEventListener("click",t=>{t.preventDefault(),window.dispatchEvent(new CustomEvent(se,{detail:{action:"show-keystone-creator"},bubbles:!0,composed:!0}))}),e.inputIdentifier?.addEventListener("input",()=>{e.inputIdentifier.classList.remove("invalid")}),e.inputCode?.addEventListener("input",()=>{e.inputCode.classList.remove("invalid")}),e.inputPassword?.addEventListener("input",()=>{e.inputPassword.classList.remove("invalid")}),e.inputDeviceTag?.addEventListener("input",()=>{e.inputDeviceTag.classList.remove("invalid")})}getDeviceTag(){let e=this.elements,t=e.inputDeviceTag?.value?.trim();if(t&&Ot.test(t))return t;let i=at();return e.inputDeviceTag&&(e.inputDeviceTag.value=i),i}async handleSsoClick(e){let t=`${this.lc}[${this.handleSsoClick.name}]`,i=e==="google"?"Google":"GitHub";this.setStatus(`Opening ${i} sign-in window...`,"info"),this.showBusy({isBusy:!0,title:"Sign In via SSO",msg:`Opening ${i} authorization window...
2625
+ Please complete sign-in in the popup window.`,animationEmoji:"\u{1F310}"});try{let o=await je({providerId:e});if(!o.success||!o.code){this.setStatus(o.message||`${i} sign-in cancelled.`,"error");return}this.setStatus(`Validating ${i} authorization...`,"info"),this.showBusy({isBusy:!0,title:"Exchanging SSO Code...",msg:`Validating ${i} authorization with server...`,animationEmoji:"\u{1F510}"});let a=await D().postSsoLogin({code:o.code,providerId:e,redirectUri:o.redirectUri});if(!a.success||!a.primaryTjpAddr||!a.custodianReqs){this.setStatus(a.message||`${i} login failed.`,"error");return}let{primaryTjpAddr:c,custodianReqs:d,primaryKeystone:u}=a,f=a.userInfo?.email||"",h=f?f.split("@")[0]:"user";await this.completeCustodialDelegateOnboarding({primaryTjpAddr:c,custodianReqs:d,fallbackPrimaryKeystone:u,fallbackPrimaryGraph:a.primaryGraph,email:f,username:h})}catch(o){let s=E(o);console.error(`${t} SSO login error: ${s}`,o),this.setStatus(`Error: ${s}`,"error")}finally{this.showBusy({isBusy:!1})}}async handleContinueEmail(){let e=`${this.lc}[${this.handleContinueEmail.name}]`,t=this.elements,i=t.inputIdentifier?.value?.trim();if(!i||!st(i)){t.inputIdentifier.classList.add("invalid"),this.setStatus("Please enter a valid email address.","error");return}t.btnContinueEmail.disabled=!0,t.btnContinueEmail.textContent="Checking...",this.setStatus("Checking identity on server...","info"),this.showBusy({isBusy:!0,title:"Locating Identity...",msg:"Locating account on server...",animationEmoji:"\u{1F50D}"});try{let o=await D().lookupPrimaryKeystone({identifier:i});if(!o.success||!o.tjpAddr){this.setStatus('No account found for this email address. Please click "Create Account" below.',"error");return}this._stagedEmail=i,this._stagedPrimaryTjpAddr=o.tjpAddr,this.setStatus("Dispatching 6-digit verification code...","info"),this.showBusy({isBusy:!0,title:"Sending Code...",msg:"Dispatching 6-digit verification code to your email...",animationEmoji:"\u2709\uFE0F"});let s=await D().postVerificationCode({email:i,primaryTjpAddr:this._stagedPrimaryTjpAddr});if(!s.success){this.setStatus(s.message||"Failed to dispatch verification code.","error");return}t.sectionCodeVerification.classList.remove("hidden"),t.sectionCodeVerification.scrollIntoView({behavior:"smooth"}),this.setStatus(`Verification code sent to ${i}! Enter the 6-digit code above to continue.`,"info"),t.inputCode?.focus()}catch(o){let s=E(o);console.error(`${e} ${s}`,o),this.setStatus(`Error: ${s}`,"error")}finally{t.btnContinueEmail.disabled=!1,t.btnContinueEmail.textContent="Continue with Email",this.showBusy({isBusy:!1})}}async handleVerifyCode(){let e=`${this.lc}[${this.handleVerifyCode.name}]`,t=this.elements,i=t.inputCode?.value?.trim(),o=this._stagedEmail,s=this._stagedPrimaryTjpAddr;if(!o||!s){this.setStatus("Please enter your email and request a code first.","error");return}if(!i||i.length!==6){t.inputCode.classList.add("invalid"),this.setStatus("Please enter a 6-digit verification code.","error");return}t.btnVerifyCode.disabled=!0,t.btnVerifyCode.textContent="Verifying...",this.setStatus("Verifying 6-digit code...","info"),this.showBusy({isBusy:!0,title:"Verifying Code...",msg:"Validating verification code with server...",animationEmoji:"\u{1F510}"});try{let a=await D().postCustodianGenesis({email:o,code:i});if(a.success&&a.primaryTjpAddr&&a.custodianReqs){let{primaryTjpAddr:h,custodianReqs:m,primaryKeystone:g,primaryGraph:b}=a,y=o?o.split("@")[0]:"user";await this.completeCustodialDelegateOnboarding({primaryTjpAddr:h,custodianReqs:m,fallbackPrimaryKeystone:g,fallbackPrimaryGraph:b,email:o,username:y});return}let c=await D().postVerifyCode({email:o,primaryTjpAddr:s,code:i});if(!c.success){this.setStatus(c.message||"Verification failed. Please check the code.","error");return}this.setStatus("Retrieving identity graph from server...","info"),this.showBusy({isBusy:!0,title:"Loading Identity Graph...",msg:"Fetching cryptographic identity timeline from server...",animationEmoji:"\u{1F4E5}"});let d=await D().getKeystoneGraph(s);if(!d.success||!d.graph){this.setStatus("Failed to retrieve identity graph from server.","error");return}this._stagedPrimaryGraph=d.graph;let u=await k(),f=await u.getLocalUserSpace({});if(f){let h=Object.values(d.graph);await u.put({ibGibs:h,space:f});let m=Se({ibGibs:h});for(let b of Object.keys(m))for(let y of m[b])await u.registerNewIbGib({ibGib:y,space:f});let g=m[s]||m[Object.keys(m)[0]];g&&g.length>0&&(this._stagedPrimaryKeystone=g[g.length-1])}t.sectionCodeVerification.classList.add("hidden"),t.sectionSovereignPassword.classList.remove("hidden"),t.sectionSovereignPassword.scrollIntoView({behavior:"smooth"}),this.setStatus("2FA verified! Please enter your master password to authorize this device.","info"),t.inputPassword?.focus()}catch(a){let c=E(a);console.error(`${e} ${c}`,a),this.setStatus(`Error: ${c}`,"error")}finally{t.btnVerifyCode.disabled=!1,t.btnVerifyCode.textContent="Verify Code",this.showBusy({isBusy:!1})}}async completeCustodialDelegateOnboarding({primaryTjpAddr:e,custodianReqs:t,fallbackPrimaryKeystone:i,fallbackPrimaryGraph:o,email:s,username:a}){let c=`${this.lc}[${this.completeCustodialDelegateOnboarding.name}]`,d=this.getDeviceTag();this.setStatus("Deriving local device delegate keys...","info"),this.showBusy({isBusy:!0,title:"Creating Sync Delegate...",msg:`Generating cryptographic sync delegate keys for ${d}...`,animationEmoji:"\u{1F511}"});let u=await k(),f=await u.getLocalUserSpace({lock:!1});if(!f){this.setStatus("Could not access local user space.","error");return}let h=await ir({primaryTjpAddr:e,deviceTag:d}),m=a||(s?s.split("@")[0]:"user"),g="sync-profile.dev";if(!g||!g.trim())throw new Error('KEYSTONE_PROFILE_CUSTODIAN_SYNC environment variable is missing. Expected valid profile name like "sync-profile.dev" or "sync-profile.prod". (E: 4d5e6f7890123456789abcdef4)');let b=await Vi({profileName:g.trim(),username:m,deviceTag:d,primaryTjpAddr:e,delegateSecret:h,custodianReqs:t,additionalFrameDetails:{client:"space-gib-web"},metaspace:u,space:f});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{1F504}"});let y=await D().postCustodianRegisterDelegate({delegateKeystone:b});if(!y.success){this.setStatus(y.message||"Custodian delegate registration failed.","error");return}await this.finalizeDeviceOnboarding({primaryKeystone:y.evolvedPrimaryKeystone||i,primaryGraph:y.primaryGraph||o,delegateKeystone:b,primaryTjpAddr:e,delegateSecret:h,makeActive:this.elements?.checkboxMakeActive?.checked??!0})}async handleAuthorizePassword(){let e=`${this.lc}[${this.handleAuthorizePassword.name}]`,t=this.elements,i=t.inputPassword?.value?.trim(),o=this._stagedPrimaryKeystone,s=this._stagedPrimaryTjpAddr;if(!i){t.inputPassword.classList.add("invalid"),this.setStatus("Please enter your master password.","error");return}if(!o||!s){this.setStatus("Missing staged primary identity context. Please restart sign-in.","error");return}t.btnAuthorizePassword.disabled=!0,t.btnAuthorizePassword.textContent="Authorizing...",this.setStatus("Verifying master password locally...","info"),this.showBusy({isBusy:!0,title:"Verifying Password...",msg:"Verifying cryptographic password locally in browser...",animationEmoji:"\u{1F510}"});try{let a=new Y;if(!await a.verifySigningSecret({keystoneIbGib:o,signingSecret:i,poolId:"manage"})){t.inputPassword.classList.add("invalid"),this.setStatus("Incorrect master password. Please try again.","error");return}let d=this.getDeviceTag(),u=o.data?.frameDetails?.username||"user";this.setStatus(`Generating local sync delegate for ${d}...`,"info"),this.showBusy({isBusy:!0,title:"Generating Keys...",msg:`Generating cryptographic delegate keys for ${d}...`,animationEmoji:"\u{1F511}"});let f=await k(),h=await f.getLocalUserSpace({});if(!h)throw new Error("No default space found in metaspace.");let m=await er({masterSecret:i});await nr({primaryTjpAddr:s,delegateSecret:m});let g="sync-profile.dev";if(!g||!g.trim())throw new Error('KEYSTONE_PROFILE_SOVEREIGN_SYNC environment variable is missing. Expected valid profile name like "sync-profile.dev" or "sync-profile.prod". (E: genuuid)');let b=await Vi({profileName:g.trim(),username:u,deviceTag:d,primaryTjpAddr:s,delegateSecret:m,additionalFrameDetails:{client:"space-gib-web"},metaspace:f,space:h});this.setStatus("Evolving primary identity to register delegate...","info"),this.showBusy({isBusy:!0,title:"Registering Device...",msg:"Evolving primary identity to register new device delegate...",animationEmoji:"\u2699\uFE0F"});let y=await a.registerDelegate({parentKeystone:o,delegateKeystone:b,masterSecret:i,signingPoolId:"manage",allowedVerbs:[Pe,Ne],metaspace:f,space:h,deviceName:d});this.setStatus("Publishing evolved identity to server...","info"),this.showBusy({isBusy:!0,title:"Syncing to Server...",msg:"Publishing evolved identity and delegate to server...",animationEmoji:"\u26A1"});let w=await D().putEvolveKeystone({domainAddr:s,keystoneIbGib:y,relatedKeystoneIbGibs:[b]});w.success||console.warn(`${e} Warning syncing delegate evolution to server: ${w.message}`),await this.finalizeDeviceOnboarding({primaryKeystone:y,primaryGraph:this._stagedPrimaryGraph,delegateKeystone:b,primaryTjpAddr:s,masterSecret:i,delegateSecret:m,makeActive:t.checkboxMakeActive?.checked??!0})}catch(a){let c=E(a);console.error(`${e} ${c}`,a),this.setStatus(`Error: ${c}`,"error")}finally{t.btnAuthorizePassword.disabled=!1,t.btnAuthorizePassword.textContent="Authorize & Pair Device",this.showBusy({isBusy:!1})}}async finalizeDeviceOnboarding({primaryKeystone:e,primaryGraph:t,delegateKeystone:i,primaryTjpAddr:o,masterSecret:s,delegateSecret:a,makeActive:c=!0}){let d=`${this.lc}[${this.finalizeDeviceOnboarding.name}]`,u=500,f=await k();if(!f)throw new Error("Metaspace not found");let h=await f.getLocalUserSpace({});if(!h)throw new Error("Local user space not found");if(t){let y=Object.values(t);await f.put({ibGibs:y,space:h});let w=Se({ibGibs:y});for(let v of Object.keys(w))for(let I of w[v])await f.registerNewIbGib({ibGib:I,space:h})}else e&&(await f.put({ibGibs:[e],space:h}),await f.registerNewIbGib({ibGib:e,space:h}));await f.put({ibGibs:[i],space:h}),await f.registerNewIbGib({ibGib:i,space:h});let m=[J({ibGib:i})];e&&m.unshift(J({ibGib:e})),await re({type:"keystones",rel8nInfos:[{rel8nName:"keystone",ibGibs:m}],metaspace:f,space:h}),c&&window.dispatchEvent(new CustomEvent(Me,{detail:{activeIdentityAddr:o},bubbles:!0,composed:!0}));let g=_({ibGib:i});this.elements?.delegateAddrEl&&(this.elements.delegateAddrEl.textContent=g),this.elements?.resultAreaEl&&this.elements.resultAreaEl.classList.remove("collapsed");let b="Device paired and identity activated successfully!";this.setStatus(b,"success"),this.showBusy({isBusy:!0,title:"Success!",msg:b,animationEmoji:"\u2705"}),await z(u),this.elements?.inputPassword&&(this.elements.inputPassword.value=""),window.dispatchEvent(new CustomEvent(se,{detail:{action:"show-identity-manager",addr:o},bubbles:!0,composed:!0})),this.showBusy({isBusy:!1})}async renderUI(){}async handleContextUpdated(){await this.renderUI()}};var pc=`:host {
2626
2626
  display: block;
2627
2627
  width: 100%;
2628
2628
  }
@@ -2740,7 +2740,7 @@ Please complete sign-in in the popup window.`,animationEmoji:"\u{1F310}"});try{l
2740
2740
  margin-top: 0;
2741
2741
  color: #f38ba8;
2742
2742
  }
2743
- `;var ad=`<div id="container" class="component-container">
2743
+ `;var hc=`<div id="container" class="component-container">
2744
2744
  <h2 id="title">Remove / Unlink Device</h2>
2745
2745
  <div class="content">
2746
2746
  <p>Unlink an authorized delegate device from your primary identity timeline.</p>
@@ -2770,7 +2770,297 @@ Please complete sign-in in the popup window.`,animationEmoji:"\u{1F310}"});try{l
2770
2770
  <p class="warning">\u{1F512} The selected device delegate has been unlinked from your primary identity.</p>
2771
2771
  </div>
2772
2772
  </div>
2773
- </div>`;var ld="ibgib-remove-device",xi=class extends fe{static{p(this,"RemoveDeviceComponentMeta")}lc="[RemoveDeviceComponentMeta]";routeRegExp=new RegExp(`^${ld}$`);componentName=ld;constructor(){super(Ee()),customElements.get(this.componentName)||customElements.define(this.componentName,_s)}async createInstance({path:e,ibGibAddr:t}){let i=document.createElement(this.componentName);return await i.initialize({ibGibAddr:t,meta:this,html:ad,css:[me,rd]}),i}},_s=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.inputPassword=this.shadowRoot.getElementById("input-password"),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.inputPassword.addEventListener("input",()=>{this.elements.inputPassword.classList.remove("invalid")})}async loadRegisteredDelegates(){let e=`${this.lc}[${this.loadRegisteredDelegates.name}]`;try{let t=await k(),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 d=this.activePrimaryKeystone?.data?.delegates??{},c=Object.keys(d);if(c.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 c){let h=d[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} ${E(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.inputPassword.value.trim();if(this.elements.inputPassword.value=o,!o){this.elements.inputPassword.classList.add("invalid"),this.setStatus("Please enter your master password.","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 k(),a=await s.getLocalUserSpace({});if(!a)throw new Error("No default space found in metaspace.");let c=await new Y().unregisterDelegate({parentKeystone:this.activePrimaryKeystone,delegateTjpAddr:i,masterSecret:o,signingPoolId:"manage",metaspace:s,space:a});await s.put({ibGibs:[c],space:a}),await s.registerNewIbGib({ibGib:c,space:a}),this.activePrimaryKeystone=c,await z(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} ${E(t)}`),this.setStatus(`Revocation failed: ${E(t)}`,"error"),this.showBusy({isBusy:!1})}}};async function dd(){let n=await de();n.registerComponentMeta(new Ii),n.registerComponentMeta(new Ci),n.registerComponentMeta(new Ti),n.registerComponentMeta(new Si),n.registerComponentMeta(new _i),n.registerComponentMeta(new Ai),n.registerComponentMeta(new xi)}p(dd,"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} ${E(t)}`)}}initEventHandlers(){let e=`${this.lc}[${this.initEventHandlers.name}]`;try{let t=document.getElementById(gr);t&&t.addEventListener("click",()=>this.toggleLeftPanel());let i=document.getElementById(br);i&&i.addEventListener("click",()=>this.toggleRightPanel());let o=document.getElementById(pr);o&&(o.addEventListener("mousedown",()=>{this.leftPanelState==="expanded"&&(this.isResizingLeft=!0)}),o.addEventListener("dblclick",()=>this.toggleLeftPanel()));let s=document.getElementById(hr);s&&(s.addEventListener("mousedown",()=>{this.rightPanelState==="expanded"&&(this.isResizingRight=!0)}),s.addEventListener("dblclick",()=>this.toggleRightPanel()));let a=document.getElementById(mr);a&&a.addEventListener("mousedown",()=>this.isResizingFooter=!0),window.addEventListener("mousemove",f=>this.handleMouseMove(f)),window.addEventListener("mouseup",()=>this.handleMouseUp());let d=document.getElementById(yr);d&&d.addEventListener("click",()=>this.showIdentityManager()),window.addEventListener(oe,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 c,u=!1;window.addEventListener(Bt,f=>{let{isBusy:h,title:m,msg:g,animationEmoji:b}=f.detail;h?(u=!0,c?c.update({title:m,msg:g,animationEmoji:b}):Ks({title:m||"Processing...",msg:g||"Please do not navigate away or refresh.",isBusy:!0,animationEmoji:b}).then(y=>{u?c=y:y.close()}).catch(y=>{console.error(`${e}[showFullscreenDialog] ${E(y)}`)})):(u=!1,c&&(c.close(),c=void 0))})}catch(t){console.error(`${e} ${E(t)}`)}}async showIdentityManager(){let e=`${this.lc}[${this.showIdentityManager.name}]`;try{let i=await(await de()).getComponentInstance({path:"ibgib-identity-manager",ibGibAddr:j,useRegExpPrefilter:!0}),o=document.getElementById(vn);o&&i&&(o.innerHTML="",o.appendChild(i))}catch(t){console.error(`${e} ${E(t)}`)}}async showKeystoneCreator(){let e=`${this.lc}[${this.showKeystoneCreator.name}]`;try{let i=await(await de()).getComponentInstance({path:"ibgib-keystone-creator",ibGibAddr:j,useRegExpPrefilter:!0}),o=document.getElementById(vn);o&&i&&(o.innerHTML="",o.appendChild(i))}catch(t){console.error(`${e} ${E(t)}`)}}async showAddDevice(){let e=`${this.lc}[${this.showAddDevice.name}]`;try{let i=await(await de()).getComponentInstance({path:"ibgib-add-device",ibGibAddr:j,useRegExpPrefilter:!0}),o=document.getElementById(vn);o&&i&&(o.innerHTML="",o.appendChild(i))}catch(t){console.error(`${e} ${E(t)}`)}}toggleLeftPanel(){this.leftPanelState=this.leftPanelState==="expanded"?"collapsed":"expanded";let e=document.getElementById(ur);e&&(this.leftPanelState==="collapsed"?e.classList.add("collapsed"):e.classList.remove("collapsed"))}toggleRightPanel(){this.rightPanelState=this.rightPanelState==="expanded"?"collapsed":"expanded";let e=document.getElementById(fr);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{dd()}catch(t){console.error(`${e} ${E(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 de()).getComponentInstance({path:"ibgib-identity-header",ibGibAddr:j,useRegExpPrefilter:!0}),s=document.getElementById("identity-header-container");s&&o&&(s.innerHTML="",s.appendChild(o)),window.dispatchEvent(new CustomEvent(Hs,{detail:{timestamp:Date.now()}}));let a=globalThis.ibgib?.identity?.domainIdentity;if(a){let d=_({ibGib:a}),c=dt(),u=await c.checkForKeystoneUpdate({activePrimaryAddr:d});u.hasUpdate?(console.log(`${e} \u{1F514} Keystone update available on app boot! Server n=${u.serverN}, Local n=${u.localN}`),await c.updateActiveKeystone({activePrimaryAddr:d})):console.log(`${e} Keystone identity up to date on app boot (n=${u.localN}).`)}}catch(t){console.error(`${e} ${E(t)}`)}}};function P0(){let n="[getSpaceGibShellSvc]",e=rr(Os);return e.spaceGibShellSvc||(typeof console<"u"&&console.log(`${n} initializing SpaceGibShellService singleton on globalThis... (I: genuuid)`),e.spaceGibShellSvc=new As),e.spaceGibShellSvc}p(P0,"getSpaceGibShellSvc");export{In as a,ze as b,Cb as c,Tb as d,ee as e,Sb as f,Ue as g,ht as h,og as i,Mt as j,Ei as k,P0 as l};
2773
+ </div>`;var mc="ibgib-remove-device",Gi=class extends ae{static{p(this,"RemoveDeviceComponentMeta")}lc="[RemoveDeviceComponentMeta]";routeRegExp=new RegExp(`^${mc}$`);componentName=mc;constructor(){super(he()),customElements.get(this.componentName)||customElements.define(this.componentName,Ns)}async createInstance({path:e,ibGibAddr:t}){let i=document.createElement(this.componentName);return await i.initialize({ibGibAddr:t,meta:this,html:hc,css:[ue,pc]}),i}},Ns=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.inputPassword=this.shadowRoot.getElementById("input-password"),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.inputPassword.addEventListener("input",()=>{this.elements.inputPassword.classList.remove("invalid")})}async loadRegisteredDelegates(){let e=`${this.lc}[${this.loadRegisteredDelegates.name}]`;try{let t=await k(),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} ${E(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.inputPassword.value.trim();if(this.elements.inputPassword.value=o,!o){this.elements.inputPassword.classList.add("invalid"),this.setStatus("Please enter your master password.","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 k(),a=await s.getLocalUserSpace({});if(!a)throw new Error("No default space found in metaspace.");let d=await new Y().unregisterDelegate({parentKeystone:this.activePrimaryKeystone,delegateTjpAddr:i,masterSecret:o,signingPoolId:"manage",metaspace:s,space:a});await s.put({ibGibs:[d],space:a}),await s.registerNewIbGib({ibGib:d,space:a}),this.activePrimaryKeystone=d,await z(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} ${E(t)}`),this.setStatus(`Revocation failed: ${E(t)}`,"error"),this.showBusy({isBusy:!1})}}};async function gc(){let n=await ne();n.registerComponentMeta(new Si),n.registerComponentMeta(new _i),n.registerComponentMeta(new Ai),n.registerComponentMeta(new xi),n.registerComponentMeta(new Pi),n.registerComponentMeta(new Ni),n.registerComponentMeta(new Gi)}p(gc,"registerStandardIdentityComponents");var bc=`/* =========================================================================
2774
+ ibgib \u2014 privacy-policy.css
2775
+ Scoped styles for <ibgib-privacy-policy> Web Component.
2776
+ Inherits CSS custom properties from the host application.
2777
+ ========================================================================= */
2778
+
2779
+ :host {
2780
+ display: block;
2781
+ width: 100%;
2782
+ height: 100%;
2783
+ overflow-y: auto;
2784
+ overflow-x: hidden;
2785
+ color: var(--clr-text-primary, #e8f0e8);
2786
+ font-family: var(--font-sans, system-ui, sans-serif);
2787
+ line-height: 1.6;
2788
+ box-sizing: border-box;
2789
+ }
2790
+
2791
+ .privacy-container {
2792
+ max-width: 860px;
2793
+ margin: 0 auto;
2794
+ padding: 2rem 1.5rem 4rem;
2795
+ box-sizing: border-box;
2796
+ }
2797
+
2798
+ /* \u2500\u2500 Header \u2500\u2500 */
2799
+ .privacy-header {
2800
+ display: flex;
2801
+ align-items: center;
2802
+ justify-content: space-between;
2803
+ padding-bottom: 1.25rem;
2804
+ margin-bottom: 2rem;
2805
+ border-bottom: 1px solid var(--clr-border, rgba(120, 248, 126, 0.12));
2806
+ }
2807
+
2808
+ .btn-back {
2809
+ display: inline-flex;
2810
+ align-items: center;
2811
+ gap: 0.5rem;
2812
+ padding: 0.45rem 0.9rem;
2813
+ font-size: 0.88rem;
2814
+ font-family: inherit;
2815
+ color: var(--clr-text-secondary, #8fa08f);
2816
+ background: var(--clr-bg-glass, rgba(11, 17, 32, 0.7));
2817
+ border: 1px solid var(--clr-border, rgba(120, 248, 126, 0.12));
2818
+ border-radius: var(--radius-sm, 6px);
2819
+ cursor: pointer;
2820
+ transition: all var(--t-fast, 120ms ease);
2821
+ }
2822
+
2823
+ .btn-back:hover {
2824
+ color: var(--clr-text-primary, #ffffff);
2825
+ border-color: var(--clr-border-hover, rgba(120, 248, 126, 0.32));
2826
+ background: var(--clr-accent-glow, rgba(120, 248, 126, 0.15));
2827
+ }
2828
+
2829
+ .privacy-badge {
2830
+ font-size: 0.85rem;
2831
+ color: var(--clr-accent, #78f87e);
2832
+ padding: 0.3rem 0.75rem;
2833
+ border-radius: var(--radius-sm, 6px);
2834
+ background: var(--clr-accent-glow, rgba(120, 248, 126, 0.1));
2835
+ border: 1px solid var(--clr-border, rgba(120, 248, 126, 0.15));
2836
+ }
2837
+
2838
+ /* \u2500\u2500 Loading State \u2500\u2500 */
2839
+ .privacy-loading {
2840
+ display: flex;
2841
+ flex-direction: column;
2842
+ align-items: center;
2843
+ justify-content: center;
2844
+ padding: 4rem 1rem;
2845
+ gap: 1rem;
2846
+ color: var(--clr-text-secondary, #8fa08f);
2847
+ }
2848
+
2849
+ .spinner {
2850
+ width: 32px;
2851
+ height: 32px;
2852
+ border: 3px solid var(--clr-border, rgba(120, 248, 126, 0.15));
2853
+ border-top-color: var(--clr-accent, #78f87e);
2854
+ border-radius: 50%;
2855
+ animation: spin 0.8s linear infinite;
2856
+ }
2857
+
2858
+ @keyframes spin {
2859
+ to { transform: rotate(360deg); }
2860
+ }
2861
+
2862
+ /* \u2500\u2500 Error State \u2500\u2500 */
2863
+ .privacy-error {
2864
+ display: flex;
2865
+ flex-direction: column;
2866
+ align-items: center;
2867
+ justify-content: center;
2868
+ padding: 3rem 1rem;
2869
+ gap: 1rem;
2870
+ color: var(--clr-danger, #ff5b5b);
2871
+ background: rgba(255, 91, 91, 0.08);
2872
+ border: 1px solid rgba(255, 91, 91, 0.25);
2873
+ border-radius: var(--radius-md, 12px);
2874
+ margin: 2rem 0;
2875
+ }
2876
+
2877
+ .btn-retry {
2878
+ padding: 0.4rem 1rem;
2879
+ font-size: 0.88rem;
2880
+ color: var(--clr-text-primary, #ffffff);
2881
+ background: var(--clr-danger, #ff5b5b);
2882
+ border: none;
2883
+ border-radius: var(--radius-sm, 6px);
2884
+ cursor: pointer;
2885
+ }
2886
+
2887
+ /* \u2500\u2500 Markdown Rendered Typography \u2500\u2500 */
2888
+ .privacy-content {
2889
+ display: block;
2890
+ }
2891
+
2892
+ .privacy-content .policy-title {
2893
+ font-size: 2.2rem;
2894
+ color: var(--clr-text-primary, #ffffff);
2895
+ margin-top: 0;
2896
+ margin-bottom: 0.75rem;
2897
+ line-height: 1.25;
2898
+ }
2899
+
2900
+ .privacy-content .policy-h2 {
2901
+ font-size: 1.35rem;
2902
+ color: var(--clr-accent, #78f87e);
2903
+ margin-top: 2.25rem;
2904
+ margin-bottom: 0.75rem;
2905
+ padding-bottom: 0.35rem;
2906
+ border-bottom: 1px solid var(--clr-border, rgba(120, 248, 126, 0.12));
2907
+ }
2908
+
2909
+ .privacy-content .policy-h3 {
2910
+ font-size: 1.1rem;
2911
+ color: var(--clr-text-primary, #e8f0e8);
2912
+ margin-top: 1.5rem;
2913
+ margin-bottom: 0.5rem;
2914
+ }
2915
+
2916
+ .privacy-content .policy-h4 {
2917
+ font-size: 0.95rem;
2918
+ color: var(--clr-text-secondary, #8fa08f);
2919
+ margin-top: 1.25rem;
2920
+ margin-bottom: 0.4rem;
2921
+ }
2922
+
2923
+ .privacy-content p {
2924
+ color: var(--clr-text-primary, #e8f0e8);
2925
+ font-size: 0.95rem;
2926
+ margin: 0.75rem 0;
2927
+ }
2928
+
2929
+ .privacy-content ul,
2930
+ .privacy-content ol {
2931
+ padding-left: 1.5rem;
2932
+ margin: 0.5rem 0 1rem;
2933
+ }
2934
+
2935
+ .privacy-content li {
2936
+ color: var(--clr-text-primary, #e8f0e8);
2937
+ font-size: 0.95rem;
2938
+ margin-bottom: 0.35rem;
2939
+ }
2940
+
2941
+ .privacy-content code {
2942
+ font-family: var(--font-mono, monospace);
2943
+ font-size: 0.85em;
2944
+ background: rgba(255, 255, 255, 0.08);
2945
+ padding: 0.15rem 0.35rem;
2946
+ border-radius: 4px;
2947
+ color: var(--clr-accent, #78f87e);
2948
+ }
2949
+
2950
+ .privacy-content code.math {
2951
+ color: var(--clr-info, #44aaff);
2952
+ }
2953
+
2954
+ .privacy-content a {
2955
+ color: var(--clr-accent, #78f87e);
2956
+ text-decoration: underline;
2957
+ transition: color var(--t-fast, 120ms ease);
2958
+ }
2959
+
2960
+ .privacy-content a:hover {
2961
+ color: var(--clr-border-hover, #a6fca9);
2962
+ }
2963
+
2964
+ .privacy-content .divider {
2965
+ border: 0;
2966
+ border-top: 1px solid var(--clr-border, rgba(120, 248, 126, 0.12));
2967
+ margin: 2.25rem 0;
2968
+ }
2969
+
2970
+ /* \u2500\u2500 Alert Boxes \u2500\u2500 */
2971
+ .privacy-content .alert-box {
2972
+ display: flex;
2973
+ gap: 0.75rem;
2974
+ padding: 1rem 1.25rem;
2975
+ border-radius: var(--radius-sm, 6px);
2976
+ margin: 1.25rem 0;
2977
+ align-items: flex-start;
2978
+ border: 1px solid var(--clr-border, rgba(120, 248, 126, 0.12));
2979
+ background: var(--clr-bg-glass, rgba(11, 17, 32, 0.7));
2980
+ }
2981
+
2982
+ .privacy-content .alert-warning {
2983
+ background: rgba(255, 204, 68, 0.08);
2984
+ border-color: rgba(255, 204, 68, 0.3);
2985
+ color: var(--clr-warn, #ffcc44);
2986
+ }
2987
+
2988
+ .privacy-content .alert-important {
2989
+ background: rgba(68, 170, 255, 0.08);
2990
+ border-color: rgba(68, 170, 255, 0.3);
2991
+ color: var(--clr-info, #44aaff);
2992
+ }
2993
+
2994
+ .privacy-content .alert-note {
2995
+ background: rgba(120, 248, 126, 0.08);
2996
+ border-color: rgba(120, 248, 126, 0.3);
2997
+ color: var(--clr-accent, #78f87e);
2998
+ }
2999
+
3000
+ .privacy-content .alert-icon {
3001
+ font-size: 1.2rem;
3002
+ line-height: 1.2;
3003
+ }
3004
+
3005
+ .privacy-content .alert-body {
3006
+ font-size: 0.88rem;
3007
+ line-height: 1.45;
3008
+ color: var(--clr-text-primary, #e8f0e8);
3009
+ }
3010
+
3011
+ /* \u2500\u2500 Footer \u2500\u2500 */
3012
+ .privacy-footer {
3013
+ margin-top: 3.5rem;
3014
+ padding-top: 1.5rem;
3015
+ border-top: 1px solid var(--clr-border, rgba(120, 248, 126, 0.12));
3016
+ font-size: 0.85rem;
3017
+ color: var(--clr-text-secondary, #8fa08f);
3018
+ display: flex;
3019
+ justify-content: space-between;
3020
+ flex-wrap: wrap;
3021
+ gap: 1rem;
3022
+ }
3023
+
3024
+ .privacy-footer a {
3025
+ color: var(--clr-accent, #78f87e);
3026
+ text-decoration: none;
3027
+ }
3028
+
3029
+ .privacy-footer a:hover {
3030
+ text-decoration: underline;
3031
+ }
3032
+
3033
+ .hidden {
3034
+ display: none !important;
3035
+ }
3036
+ `;var yc=`<div class="privacy-container">
3037
+ <header class="privacy-header">
3038
+ <button id="btn-back" class="btn-back" type="button">
3039
+ <span class="icon">\u2190</span>
3040
+ <span>Return</span>
3041
+ </button>
3042
+ <span class="privacy-badge">\u{1F512} Privacy Policy</span>
3043
+ </header>
3044
+
3045
+ <div id="loading-spinner" class="privacy-loading">
3046
+ <div class="spinner"></div>
3047
+ <p>Loading Privacy Policy...</p>
3048
+ </div>
3049
+
3050
+ <div id="error-container" class="privacy-error hidden">
3051
+ <p id="error-message">Unable to load Privacy Policy.</p>
3052
+ <button id="btn-retry" class="btn-retry" type="button">Retry</button>
3053
+ </div>
3054
+
3055
+ <main id="privacy-content" class="privacy-content hidden">
3056
+ </main>
3057
+
3058
+ <footer class="privacy-footer">
3059
+ <span>\xA9 ibgib contributors</span>
3060
+ <span class="footer-link"><a href="https://ibgib.space" target="_blank" rel="noopener">ibgib.space</a></span>
3061
+ </footer>
3062
+ </div>
3063
+ `;var Ec="ibgib-privacy-policy",$i=class extends ae{static{p(this,"PrivacyPolicyComponentMeta")}lc="[PrivacyPolicyComponentMeta]";routeRegExp=new RegExp(`^${Ec}$|^privacy(-policy)?$`,"i");componentName=Ec;constructor(){super(he()),typeof customElements<"u"&&!customElements.get(this.componentName)&&customElements.define(this.componentName,Gs)}async createInstance({path:e,ibGibAddr:t}){let i=`${this.lc}[${this.createInstance.name}]`,o=document.createElement(this.componentName);return await o.initialize({ibGibAddr:t||Z,meta:this,html:yc,css:[ue,bc]}),o}},Gs=class extends Fe{static{p(this,"PrivacyPolicyComponentInstance")}lc="[PrivacyPolicyComponentInstance]";markdownUrl="/PRIVACY_POLICY.md";constructor(){super()}async created(){let e=`${this.lc}[${this.created.name}]`;try{let t=this.shadowRoot,i=t.querySelector(".privacy-container")||t.querySelector("#privacy-content")||this;this.elements={contentEl:i,btnBack:t.querySelector("#btn-back"),loadingSpinner:t.querySelector("#loading-spinner"),errorContainer:t.querySelector("#error-container"),errorMessage:t.querySelector("#error-message"),btnRetry:t.querySelector("#btn-retry"),privacyContent:t.querySelector("#privacy-content")},this.elements.btnBack?.addEventListener("click",()=>{window.history.length>1?window.history.back():window.location.href="/"}),this.elements.btnRetry?.addEventListener("click",()=>{this.loadPrivacyPolicy()}),await this.loadPrivacyPolicy()}catch(t){console.error(`${e} ${E(t)}`)}}async disconnected(){let e=`${this.lc}[${this.disconnected.name}]`}async loadPrivacyPolicy(){let e=`${this.lc}[${this.loadPrivacyPolicy.name}]`;try{let t=this.elements;t?.loadingSpinner&&t.loadingSpinner.classList.remove("hidden"),t?.errorContainer&&t.errorContainer.classList.add("hidden"),t?.privacyContent&&t.privacyContent.classList.add("hidden");let i=await fetch(this.markdownUrl);if(!i.ok)throw new Error(`Failed to load ${this.markdownUrl} (status ${i.status}: ${i.statusText})`);let o=await i.text(),s=br(o,{linkTarget:"_blank",linkRel:"noopener",enableAlerts:!0});this.elements?.privacyContent&&(this.elements.privacyContent.innerHTML=s,this.elements.privacyContent.classList.remove("hidden"))}catch(t){let i=E(t);console.error(`${e} ${i}`),this.elements?.errorMessage&&(this.elements.errorMessage.textContent=`Unable to load Privacy Policy: ${i}`),this.elements?.errorContainer&&this.elements.errorContainer.classList.remove("hidden")}finally{this.elements?.loadingSpinner&&this.elements.loadingSpinner.classList.add("hidden")}}};async function wc(){(await ne()).registerComponentMeta(new $i)}p(wc,"registerPrivacyPolicyComponent");var $s=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} ${E(t)}`)}}initEventHandlers(){let e=`${this.lc}[${this.initEventHandlers.name}]`;try{let t=document.getElementById(Cr);t&&t.addEventListener("click",()=>this.toggleLeftPanel());let i=document.getElementById(Tr);i&&i.addEventListener("click",()=>this.toggleRightPanel());let o=document.getElementById(wr);o&&(o.addEventListener("mousedown",()=>{this.leftPanelState==="expanded"&&(this.isResizingLeft=!0)}),o.addEventListener("dblclick",()=>this.toggleLeftPanel()));let s=document.getElementById(vr);s&&(s.addEventListener("mousedown",()=>{this.rightPanelState==="expanded"&&(this.isResizingRight=!0)}),s.addEventListener("dblclick",()=>this.toggleRightPanel()));let a=document.getElementById(Ir);a&&a.addEventListener("mousedown",()=>this.isResizingFooter=!0),window.addEventListener("mousemove",h=>this.handleMouseMove(h)),window.addEventListener("mouseup",()=>this.handleMouseUp());let c=document.getElementById(Sr);c&&c.addEventListener("click",()=>this.showIdentityManager());let d=document.getElementById("link-privacy-policy");d&&d.addEventListener("click",h=>{h.preventDefault(),this.showPrivacyPolicy()}),window.addEventListener(se,h=>{let m=h.detail?.action;m===dn?this.showIdentityManager():m===un?this.showKeystoneCreator():m===fn?this.showAddDevice():m===Qs&&this.showPrivacyPolicy()});let u,f=!1;window.addEventListener(Bt,h=>{let{isBusy:m,title:g,msg:b,animationEmoji:y}=h.detail;m?(f=!0,u?u.update({title:g,msg:b,animationEmoji:y}):Zs({title:g||"Processing...",msg:b||"Please do not navigate away or refresh.",isBusy:!0,animationEmoji:y}).then(w=>{f?u=w:w.close()}).catch(w=>{console.error(`${e}[showFullscreenDialog] ${E(w)}`)})):(f=!1,u&&(u.close(),u=void 0))})}catch(t){console.error(`${e} ${E(t)}`)}}async showIdentityManager(){let e=`${this.lc}[${this.showIdentityManager.name}]`;try{let t=await ne(),i=await t.getComponentInstance({path:"ibgib-identity-manager",ibGibAddr:Z,useRegExpPrefilter:!0});if(!i)throw new Error("(UNEXPECTED) identityMgrComponent falsy? (E: b814f2d7818811b87e31851835017b26)");let o=document.getElementById(Ht);if(!o)throw new Error("(UNEXPECTED) centerPanel falsy? (E: 769e952153b6af539a8e4ba9ff3c8126)");await t.inject({parentEl:o,componentToInject:i})}catch(t){console.error(`${e} ${E(t)}`)}}async showKeystoneCreator(){let e=`${this.lc}[${this.showKeystoneCreator.name}]`;try{let i=await(await ne()).getComponentInstance({path:"ibgib-keystone-creator",ibGibAddr:Z,useRegExpPrefilter:!0}),o=document.getElementById(Ht);o&&i&&(o.innerHTML="",o.appendChild(i))}catch(t){console.error(`${e} ${E(t)}`)}}async showAddDevice(){let e=`${this.lc}[${this.showAddDevice.name}]`;try{let i=await(await ne()).getComponentInstance({path:"ibgib-add-device",ibGibAddr:Z,useRegExpPrefilter:!0}),o=document.getElementById(Ht);o&&i&&(o.innerHTML="",o.appendChild(i))}catch(t){console.error(`${e} ${E(t)}`)}}async showPrivacyPolicy(){let e=`${this.lc}[${this.showPrivacyPolicy.name}]`;try{let t=await ne(),i=await t.getComponentInstance({path:"ibgib-privacy-policy",ibGibAddr:Z,useRegExpPrefilter:!0});if(!i)throw new Error("(UNEXPECTED) privacyComponent falsy? (E: 74b8742dee3b6c19a1784ec99cf1d526)");let o=document.getElementById(Ht);if(!o)throw new Error("(UNEXPECTED) centerPanel falsy? (E: 786a1373bc0fa22bc83f1fdaeab3b126)");await t.inject({parentEl:o,componentToInject:i})}catch(t){console.error(`${e} ${E(t)}`)}}toggleLeftPanel(){this.leftPanelState=this.leftPanelState==="expanded"?"collapsed":"expanded";let e=document.getElementById(yr);e&&(this.leftPanelState==="collapsed"?e.classList.add("collapsed"):e.classList.remove("collapsed"))}toggleRightPanel(){this.rightPanelState=this.rightPanelState==="expanded"?"collapsed":"expanded";let e=document.getElementById(Er);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{await gc(),await wc()}catch(t){console.error(`${e} ${E(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 ne()).getComponentInstance({path:"ibgib-identity-header",ibGibAddr:Z,useRegExpPrefilter:!0}),s=document.getElementById("identity-header-container");s&&o&&(s.innerHTML="",s.appendChild(o)),window.dispatchEvent(new CustomEvent(Ys,{detail:{timestamp:Date.now()}}));let a=globalThis.ibgib?.identity?.domainIdentity;if(a){let c=_({ibGib:a}),d=ct(),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} ${E(t)}`)}}};function rC(){let n="[getSpaceGibShellSvc]",e=fr(Js);return e.spaceGibShellSvc||(typeof console<"u"&&console.log(`${n} initializing SpaceGibShellService singleton on globalThis... (I: genuuid)`),e.spaceGibShellSvc=new $s),e.spaceGibShellSvc}p(rC,"getSpaceGibShellSvc");export{Sn as a,Ke as b,Mb as c,Lb as d,ee as e,Ub as f,Ue as g,ht as h,mg as i,Mt as j,Ii as k,rC as l};
2774
3064
  /*! Bundled license information:
2775
3065
 
2776
3066
  @google/genai/dist/web/index.mjs: