@paean-ai/adk 0.2.29 → 0.2.30

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.
@@ -97,6 +97,7 @@ class Gemini extends import_base_llm.BaseLlm {
97
97
  }
98
98
  useVertexAI = false;
99
99
  this.apiKey = aiStudioApiKey;
100
+ this.vertexApiEndpoint = void 0;
100
101
  }
101
102
  if (this.isGemini3Preview && useVertexAI) {
102
103
  const availableApiKey = apiKey || (canReadEnv ? process.env["GOOGLE_GENAI_API_KEY"] || process.env["GEMINI_API_KEY"] : void 0);
package/dist/esm/index.js CHANGED
@@ -14,7 +14,7 @@ ${o.stdout}
14
14
 
15
15
  `);o.config.systemInstruction?o.config.systemInstruction+=`
16
16
 
17
- `+t:o.config.systemInstruction=t}function nn(o,e){o.config||(o.config={}),o.config.responseSchema=e,o.config.responseMimeType="application/json"}import{createPartFromText as ot,FinishReason as zn,GoogleGenAI as rt}from"@google/genai";function on(){return Kn("GOOGLE_GENAI_USE_VERTEXAI")?"VERTEX_AI":"GEMINI_API"}function Kn(o){if(!process.env)return!1;let e=(process.env[o]||"").toLowerCase();return["true","1"].includes(e)}var ke=class{constructor(e){this.geminiSession=e}async sendHistory(e){let t=e.filter(n=>{var r;return n.parts&&((r=n.parts[0])==null?void 0:r.text)});t.length>0?this.geminiSession.sendClientContent({turns:t,turnComplete:t[t.length-1].role==="user"}):p.info("no content is sent")}async sendContent(e){if(!e.parts)throw new Error("Content must have parts.");if(e.parts[0].functionResponse){let t=e.parts.map(n=>n.functionResponse).filter(n=>!!n);p.debug("Sending LLM function response:",t),this.geminiSession.sendToolResponse({functionResponses:t})}else p.debug("Sending LLM new content",e),this.geminiSession.sendClientContent({turns:[e],turnComplete:!0})}async sendRealtime(e){p.debug("Sending LLM Blob:",e),this.geminiSession.sendRealtimeInput({media:e})}buildFullTextResponse(e){return{content:{role:"model",parts:[{text:e}]}}}async*receive(){throw new Error("Not Implemented.")}async close(){this.geminiSession.close()}};import{FinishReason as Vn}from"@google/genai";function nt(o){var t;let e=o.usageMetadata;if(o.candidates&&o.candidates.length>0){let n=o.candidates[0];return(t=n.content)!=null&&t.parts&&n.content.parts.length>0?{content:n.content,groundingMetadata:n.groundingMetadata,usageMetadata:e,finishReason:n.finishReason}:n.finishReason===Vn.STOP?{usageMetadata:e,finishReason:n.finishReason}:{errorCode:n.finishReason,errorMessage:n.finishMessage,usageMetadata:e,finishReason:n.finishReason}}return o.promptFeedback?{errorCode:o.promptFeedback.blockReason,errorMessage:o.promptFeedback.blockReasonMessage,usageMetadata:e}:{errorCode:"UNKNOWN_ERROR",errorMessage:"Unknown error.",usageMetadata:e}}var it="https://aiplatform.googleapis.com/v1/publishers/google",ge=class extends me{constructor({model:e,apiKey:t,vertexai:n,project:r,location:i,headers:s,apiEndpoint:a,vertexApiEndpoint:c}){e||(e="gemini-2.5-flash"),super({model:e}),this.project=r,this.location=i,this.apiKey=t,this.headers=s,this.isGemini3Preview=Wt(e);let l=typeof process=="object",f=l?process.env.AI_STUDIO_API_KEY:void 0,u=!!f;this.apiEndpoint=a,!this.apiEndpoint&&l&&(this.apiEndpoint=process.env.GEMINI_API_ENDPOINT),this.vertexApiEndpoint=c,!this.vertexApiEndpoint&&l&&(this.vertexApiEndpoint=process.env.GEMINI_VERTEX_API_ENDPOINT),!this.vertexApiEndpoint&&this.isGemini3Preview&&!u&&(this.vertexApiEndpoint=it,p.info(`Using Gemini 3 preview endpoint: ${this.vertexApiEndpoint}`));let d=!!n;if(!d&&l){let m=process.env.GOOGLE_GENAI_USE_VERTEXAI;m&&(d=m.toLowerCase()==="true"||m==="1")}if(u&&(d&&p.info("AI_STUDIO_API_KEY set \u2014 overriding Vertex AI mode to use AI Studio (generativelanguage.googleapis.com)"),d=!1,this.apiKey=f),this.isGemini3Preview&&d){let m=t||(l?process.env.GOOGLE_GENAI_API_KEY||process.env.GEMINI_API_KEY:void 0);m?(p.info("Gemini 3 preview detected with Vertex AI mode. Switching to API key mode for correct endpoint handling."),d=!1,this.apiKey=m):p.warn("Gemini 3 preview requires API key authentication for correct endpoint handling. Set GEMINI_API_KEY or GOOGLE_GENAI_API_KEY environment variable for best compatibility.")}if(this.vertexai=d,this.vertexai){if(l&&!this.project&&(this.project=process.env.GOOGLE_CLOUD_PROJECT),l&&!this.location&&(this.location=process.env.GOOGLE_CLOUD_LOCATION),!this.project)throw new Error("VertexAI project must be provided via constructor or GOOGLE_CLOUD_PROJECT environment variable.");if(!this.location)throw new Error("VertexAI location must be provided via constructor or GOOGLE_CLOUD_LOCATION environment variable.")}else if(!this.apiKey&&l&&(this.apiKey=process.env.GOOGLE_GENAI_API_KEY||process.env.GEMINI_API_KEY),!this.apiKey)throw new Error("API key must be provided via constructor or GOOGLE_GENAI_API_KEY or GEMINI_API_KEY environment variable.")}async*generateContentAsync(e,t=!1){var n,r,i,s,a,c,l,f,u,d,m,w,R,y,g,b,h;if(this.preprocessRequest(e),this.maybeAppendUserContent(e),p.info(`Sending out request, model: ${e.model}, backend: ${this.apiBackend}, stream: ${t}`),(n=e.config)!=null&&n.httpOptions&&(e.config.httpOptions.headers={...e.config.httpOptions.headers,...this.trackingHeaders}),t){let I=await this.apiClient.models.generateContentStream({model:(r=e.model)!=null?r:this.model,contents:e.contents,config:e.config}),v="",A,C="",ee,k,O=null;for await(let Z of I){k=Z;let E=nt(Z);ee=E.usageMetadata;let D=(s=(i=E.content)==null?void 0:i.parts)==null?void 0:s[0],Ce=(c=(a=E.content)==null?void 0:a.parts)==null?void 0:c.some(N=>N.functionCall);if(this.isGemini3Preview&&((l=E.content)!=null&&l.parts)){for(let N of E.content.parts)if(N.thoughtSignature&&!A){A=N.thoughtSignature,p.debug(`[Gemini3] Captured thoughtSignature (length: ${A.length})`);break}}if(D!=null&&D.text)"thought"in D&&D.thought?(v+=D.text,"thoughtSignature"in D&&D.thoughtSignature&&(A=D.thoughtSignature)):C+=D.text,Ce||(E.partial=!0),this.isGemini3Preview&&Ce&&(v="",A=void 0,C="");else if((v||C)&&(!D||!D.inlineData))if(this.isGemini3Preview&&Ce&&E.content){let N=[];if(v){let M={text:v,thought:!0};A&&(M.thoughtSignature=A),N.push(M)}if(C&&N.push(ot(C)),!v&&A){for(let M of E.content.parts||[])if(M.functionCall&&!M.thoughtSignature){M.thoughtSignature=A;break}}E.content.parts=[...N,...E.content.parts||[]],v="",A=void 0,C=""}else{let N=[];if(v){let M={text:v,thought:!0};A&&(M.thoughtSignature=A),N.push(M)}C&&N.push(ot(C)),yield{content:{role:"model",parts:N},usageMetadata:E.usageMetadata},v="",A=void 0,C=""}if(this.isGemini3Preview&&Ce&&((f=E.content)!=null&&f.parts)&&!E.content.parts.some(M=>M.thoughtSignature)&&A){for(let M of E.content.parts)if(M.functionCall){M.thoughtSignature=A;break}}if(Ce){if(O&&((u=O.content)!=null&&u.parts)){let N=(((d=E.content)==null?void 0:d.parts)||[]).filter(M=>M.functionCall||M.thoughtSignature);O.content.parts.push(...N),O.usageMetadata=E.usageMetadata}else O=E;continue}if(O){if(!((w=(m=E.content)==null?void 0:m.parts)!=null&&w.length))continue;yield O,O=null}yield E}if(O){if(this.isGemini3Preview&&((R=O.content)!=null&&R.parts)){let Z=O.content.parts.filter(E=>E.thoughtSignature).length;if(Z===0&&A){for(let E of O.content.parts)if(E.functionCall){E.thoughtSignature=A;break}}else Z===0&&p.warn("[Gemini3] No thoughtSignature on merged function call parts \u2014 may cause 400 on next request")}yield O,O=null}if((C||v)&&((g=(y=k==null?void 0:k.candidates)==null?void 0:y[0])==null?void 0:g.finishReason)===zn.STOP){let Z=[];if(v){let E={text:v,thought:!0};A&&(E.thoughtSignature=A),Z.push(E)}C&&Z.push({text:C}),yield{content:{role:"model",parts:Z},usageMetadata:ee}}}else{let I=await this.apiClient.models.generateContent({model:(b=e.model)!=null?b:this.model,contents:e.contents,config:e.config}),v=nt(I);if(this.isGemini3Preview&&((h=v.content)!=null&&h.parts)){let A,C=!1;for(let k of v.content.parts)if(k.thoughtSignature){A=k.thoughtSignature,k.thought&&(C=!0);break}if(A&&!C){for(let k of v.content.parts)if(k.functionCall&&!k.thoughtSignature){k.thoughtSignature=A;break}}v.content.parts.some(k=>k.functionCall)&&v.content.parts.filter(O=>O.thoughtSignature).length===0&&p.warn("[Gemini3] No thoughtSignature on function call parts \u2014 may cause 400 on next request")}yield v}}get apiClient(){if(this._apiClient)return this._apiClient;let e={...this.trackingHeaders,...this.headers};if(this.vertexai)this._apiClient=new rt({vertexai:this.vertexai,project:this.project,location:this.location,httpOptions:{headers:e}});else{let t={headers:e};if(this.isGemini3Preview&&this.vertexApiEndpoint){let n=this.vertexApiEndpoint===it;t.baseUrl=n?this.vertexApiEndpoint:`${this.vertexApiEndpoint}/v1/publishers/google`,t.apiVersion="",p.debug(`Gemini 3 preview endpoint: ${t.baseUrl}`)}else this.apiEndpoint&&(t.baseUrl=this.apiEndpoint,p.debug(`API endpoint: ${t.baseUrl}`));this._apiClient=new rt({apiKey:this.apiKey,vertexai:!1,httpOptions:t})}return this._apiClient}get apiBackend(){return this._apiBackend||(this._apiBackend=this.apiClient.vertexai?"VERTEX_AI":"GEMINI_API"),this._apiBackend}get liveApiVersion(){return this._liveApiVersion||(this._liveApiVersion=this.apiBackend==="VERTEX_AI"?"v1beta1":"v1alpha"),this._liveApiVersion}get liveApiClient(){if(!this._liveApiClient){let e={headers:this.trackingHeaders,apiVersion:this.liveApiVersion};if(this.isGemini3Preview&&this.vertexApiEndpoint){let t=this.vertexApiEndpoint===it;e.baseUrl=t?this.vertexApiEndpoint:`${this.vertexApiEndpoint}/v1/publishers/google`,e.apiVersion=""}else this.apiEndpoint&&(e.baseUrl=this.apiEndpoint);this._liveApiClient=new rt({apiKey:this.apiKey,httpOptions:e})}return this._liveApiClient}async connect(e){var n,r,i,s;(n=e.liveConnectConfig)!=null&&n.httpOptions&&(e.liveConnectConfig.httpOptions.headers||(e.liveConnectConfig.httpOptions.headers={}),Object.assign(e.liveConnectConfig.httpOptions.headers,this.trackingHeaders),e.liveConnectConfig.httpOptions.apiVersion=this.isGemini3Preview?"":this.liveApiVersion),(r=e.config)!=null&&r.systemInstruction&&(e.liveConnectConfig.systemInstruction={role:"system",parts:[ot(e.config.systemInstruction)]}),e.liveConnectConfig.tools=(i=e.config)==null?void 0:i.tools;let t=await this.liveApiClient.live.connect({model:(s=e.model)!=null?s:this.model,config:e.liveConnectConfig,callbacks:{onmessage:()=>{}}});return new ke(t)}preprocessRequest(e){var t;if(this.apiBackend==="GEMINI_API"){if(e.config&&(e.config.labels=void 0),e.contents){for(let n of e.contents)if(n.parts)for(let r of n.parts)rn(r.inlineData),rn(r.fileData)}if((t=e.config)!=null&&t.tools&&e.config.tools.length>1){let n=e.config.tools.some(i=>"googleSearch"in i||"googleSearchRetrieval"in i),r=e.config.tools.some(i=>"functionDeclarations"in i);n&&r&&(p.warn("Gemini API (AI Studio) does not support combining built-in search tools with custom function declarations. Removing built-in search tool from this request."),e.config.tools=e.config.tools.filter(i=>!("googleSearch"in i)&&!("googleSearchRetrieval"in i)))}}}};ge.supportedModels=[/gemini-.*/,/projects\/.+\/locations\/.+\/endpoints\/.+/,/projects\/.+\/locations\/.+\/publishers\/google\/models\/gemini.+/];function rn(o){o&&o.displayName&&(o.displayName=void 0)}var st=class{constructor(e){this.maxSize=e,this.cache=new Map}get(e){let t=this.cache.get(e);return t&&(this.cache.delete(e),this.cache.set(e,t)),t}set(e,t){if(this.cache.size>=this.maxSize&&!this.cache.has(e)){let n=this.cache.keys().next().value;n!==void 0&&this.cache.delete(n)}this.cache.set(e,t)}},j=class j{static newLlm(e){return new(j.resolve(e))({model:e})}static _register(e,t){j.llmRegistryDict.has(e)&&p.info(`Updating LLM class for ${e} from ${j.llmRegistryDict.get(e)} to ${t}`),j.llmRegistryDict.set(e,t)}static register(e){for(let t of e.supportedModels)j._register(t,e)}static resolve(e){let t=j.resolveCache.get(e);if(t)return t;for(let[n,r]of j.llmRegistryDict.entries())if(new RegExp(`^${n instanceof RegExp?n.source:n}$`,n instanceof RegExp?n.flags:void 0).test(e))return j.resolveCache.set(e,r),r;throw new Error(`Model ${e} not found.`)}};j.llmRegistryDict=new Map,j.resolveCache=new st(32);var he=j;he.register(ge);var $=class{constructor(e){var t;this.name=e.name,this.description=e.description,this.isLongRunning=(t=e.isLongRunning)!=null?t:!1}_getDeclaration(){}async processLlmRequest({toolContext:e,llmRequest:t}){let n=this._getDeclaration();if(!n)return;t.toolsDict[this.name]=this;let r=Yn(t);r?(r.functionDeclarations||(r.functionDeclarations=[]),r.functionDeclarations.push(n)):(t.config=t.config||{},t.config.tools=t.config.tools||[],t.config.tools.push({functionDeclarations:[n]}))}get apiVariant(){return on()}};function Yn(o){var e;return(((e=o.config)==null?void 0:e.tools)||[]).find(t=>"functionDeclarations"in t)}import{Type as Wn}from"@google/genai";import{ZodObject as Xn}from"zod";import{Type as B}from"@google/genai";import{z as P}from"zod";function sn(o){var e;return o!==null&&typeof o=="object"&&((e=o._def)==null?void 0:e.typeName)==="ZodObject"}function Y(o){let e=o._def;if(!e)return{};let t=e.description,n={};t&&(n.description=t);let r=i=>(i.description===void 0&&delete i.description,i);switch(e.typeName){case P.ZodFirstPartyTypeKind.ZodString:n.type=B.STRING;for(let c of e.checks||[])c.kind==="min"?n.minLength=c.value.toString():c.kind==="max"?n.maxLength=c.value.toString():c.kind==="email"?n.format="email":c.kind==="uuid"?n.format="uuid":c.kind==="url"?n.format="uri":c.kind==="regex"&&(n.pattern=c.regex.source);return r(n);case P.ZodFirstPartyTypeKind.ZodNumber:n.type=B.NUMBER;for(let c of e.checks||[])c.kind==="min"?n.minimum=c.value:c.kind==="max"?n.maximum=c.value:c.kind==="int"&&(n.type=B.INTEGER);return r(n);case P.ZodFirstPartyTypeKind.ZodBoolean:return n.type=B.BOOLEAN,r(n);case P.ZodFirstPartyTypeKind.ZodArray:return n.type=B.ARRAY,n.items=Y(e.type),e.minLength&&(n.minItems=e.minLength.value.toString()),e.maxLength&&(n.maxItems=e.maxLength.value.toString()),r(n);case P.ZodFirstPartyTypeKind.ZodObject:return _e(o);case P.ZodFirstPartyTypeKind.ZodLiteral:let i=typeof e.value;if(n.enum=[e.value.toString()],i==="string")n.type=B.STRING;else if(i==="number")n.type=B.NUMBER;else if(i==="boolean")n.type=B.BOOLEAN;else if(e.value===null)n.type=B.NULL;else throw new Error(`Unsupported ZodLiteral value type: ${i}`);return r(n);case P.ZodFirstPartyTypeKind.ZodEnum:return n.type=B.STRING,n.enum=e.values,r(n);case P.ZodFirstPartyTypeKind.ZodNativeEnum:return n.type=B.STRING,n.enum=Object.values(e.values),r(n);case P.ZodFirstPartyTypeKind.ZodUnion:return n.anyOf=e.options.map(Y),r(n);case P.ZodFirstPartyTypeKind.ZodOptional:return Y(e.innerType);case P.ZodFirstPartyTypeKind.ZodNullable:let s=Y(e.innerType);return r(s?{anyOf:[s,{type:B.NULL}],...t&&{description:t}}:{type:B.NULL,...t&&{description:t}});case P.ZodFirstPartyTypeKind.ZodDefault:let a=Y(e.innerType);return a&&(a.default=e.defaultValue()),a;case P.ZodFirstPartyTypeKind.ZodBranded:return Y(e.type);case P.ZodFirstPartyTypeKind.ZodReadonly:return Y(e.innerType);case P.ZodFirstPartyTypeKind.ZodNull:return n.type=B.NULL,r(n);case P.ZodFirstPartyTypeKind.ZodAny:case P.ZodFirstPartyTypeKind.ZodUnknown:return r({...t&&{description:t}});default:throw new Error(`Unsupported Zod type: ${e.typeName}`)}}function _e(o){if(o._def.typeName!==P.ZodFirstPartyTypeKind.ZodObject)throw new Error("Expected a ZodObject");let e=o.shape,t={},n=[];for(let s in e){let a=e[s],c=Y(a);c&&(t[s]=c);let l=a,f=!1;for(;l._def.typeName===P.ZodFirstPartyTypeKind.ZodOptional||l._def.typeName===P.ZodFirstPartyTypeKind.ZodDefault;)f=!0,l=l._def.innerType;f||n.push(s)}let r=o._def.catchall,i=!1;return r&&r._def.typeName!==P.ZodFirstPartyTypeKind.ZodNever?i=Y(r)||!0:i=o._def.unknownKeys==="passthrough",{type:B.OBJECT,properties:t,required:n.length>0?n:[],...o._def.description?{description:o._def.description}:{}}}function Qn(o){return o===void 0?{type:Wn.OBJECT,properties:{}}:sn(o)?_e(o):o}var W=class extends ${constructor(e){var n;let t=(n=e.name)!=null?n:e.execute.name;if(!t)throw new Error("Tool name cannot be empty. Either name the `execute` function or provide a `name`.");super({name:t,description:e.description,isLongRunning:e.isLongRunning}),this.execute=e.execute,this.parameters=e.parameters}_getDeclaration(){return{name:this.name,description:this.description,parameters:Qn(this.parameters)}}async runAsync(e){try{let t=e.args;return this.parameters instanceof Xn&&(t=this.parameters.parse(e.args)),await this.execute(t,e.toolContext)}catch(t){let n=t instanceof Error?t.message:String(t);throw new Error(`Error in tool '${this.name}': ${n}`)}}};var X=class{};function at(o,e,t){var s,a;let n=[];for(let c of o)!((s=c.content)!=null&&s.role)||!((a=c.content.parts)!=null&&a.length)||t&&c.branch&&!t.startsWith(c.branch)||Hn(c)||Jn(c)||n.push(ln(e,c)?eo(c):c);let r=to(n);r=no(r);let i=[];for(let c of r){let l=U(c.content);Gt(l),i.push(l)}return i}function cn(o,e,t){for(let n=o.length-1;n>=0;n--){let r=o[n];if(r.author==="user"||ln(e,r))return at(o.slice(n),e,t)}return[]}function Hn(o){var e,t,n;if(!((e=o.content)!=null&&e.parts))return!1;for(let r of o.content.parts)if(((t=r.functionCall)==null?void 0:t.name)===Pe||((n=r.functionResponse)==null?void 0:n.name)===Pe)return!0;return!1}function Jn(o){var e,t,n;if(!((e=o.content)!=null&&e.parts))return!1;for(let r of o.content.parts)if(((t=r.functionCall)==null?void 0:t.name)===de||((n=r.functionResponse)==null?void 0:n.name)===de)return!0;return!1}function ln(o,e){return!!o&&e.author!==o&&e.author!=="user"}function eo(o){var t,n,r,i,s,a;if(!((n=(t=o.content)==null?void 0:t.parts)!=null&&n.length))return o;let e={role:"user",parts:[{text:"For context:"}]};for(let c of o.content.parts)if(c.text&&!c.thought)(r=e.parts)==null||r.push({text:`[${o.author}] said: ${c.text}`});else if(c.functionCall){let l=an(c.functionCall.args);(i=e.parts)==null||i.push({text:`[${o.author}] called tool \`${c.functionCall.name}\` with parameters: ${l}`})}else if(c.functionResponse){let l=an(c.functionResponse.response);(s=e.parts)==null||s.push({text:`[${o.author}] tool \`${c.functionResponse.name}\` returned result: ${l}`})}else(a=e.parts)==null||a.push(c);return T({invocationId:o.invocationId,author:"user",content:e,branch:o.branch,timestamp:o.timestamp})}function un(o){var r;if(o.length===0)throw new Error("Cannot merge an empty list of events.");let e=T(o[0]),t=((r=e.content)==null?void 0:r.parts)||[];if(t.length===0)throw new Error("There should be at least one function_response part.");let n={};for(let i=0;i<t.length;i++){let s=t[i];s.functionResponse&&s.functionResponse.id&&(n[s.functionResponse.id]=i)}for(let i of o.slice(1)){if(!i.content||!i.content.parts)throw new Error("There should be at least one function_response part.");for(let s of i.content.parts)if(s.functionResponse&&s.functionResponse.id){let a=s.functionResponse.id;a in n?t[n[a]]=s:(t.push(s),n[a]=t.length-1)}else t.push(s)}return e}function to(o){if(o.length===0)return o;let e=o[o.length-1],t=G(e);if(!(t!=null&&t.length))return o;let n=new Set(t.filter(c=>!!c.id).map(c=>c.id)),r=o.at(-2);if(r){let c=L(r);if(c){for(let l of c)if(l.id&&n.has(l.id))return o}}let i=-1;for(let c=o.length-2;c>=0;c--){let l=o[c],f=L(l);if(f!=null&&f.length){for(let u of f)if(u.id&&n.has(u.id)){i=c;let d=new Set(f.map(w=>w.id).filter(w=>!!w));if(!Array.from(n).every(w=>d.has(w)))throw new Error(`Last response event should only contain the responses for the function calls in the same function call event. Function call ids found : ${Array.from(d).join(", ")}, function response ids provided: ${Array.from(n).join(", ")}`);n=d;break}}}if(i===-1)throw new Error(`No function call event found for function responses ids: ${Array.from(n).join(", ")}`);let s=[];for(let c=i+1;c<o.length-1;c++){let l=o[c],f=G(l);f&&f.some(u=>u.id&&n.has(u.id))&&s.push(l)}s.push(o[o.length-1]);let a=o.slice(0,i+1);return a.push(un(s)),a}function no(o){let e=new Map;for(let n=0;n<o.length;n++){let r=o[n],i=G(r);if(i!=null&&i.length)for(let s of i)s.id&&e.set(s.id,n)}let t=[];for(let n of o){if(G(n).length>0)continue;let r=L(n);if(r!=null&&r.length){let i=new Set;for(let s of r){let a=s.id;a&&e.has(a)&&i.add(e.get(a))}if(t.push(n),i.size===0)continue;if(i.size===1){let[s]=[...i];t.push(o[s])}else{let a=Array.from(i).sort((c,l)=>c-l).map(c=>o[c]);t.push(un(a))}}else t.push(n)}return t}function an(o){if(typeof o=="string")return o;try{return JSON.stringify(o)}catch{return String(o)}}async function ct(o,e){let t=e.invocationContext;async function n(c){let l=c[0].replace(/^\{+/,"").replace(/\}+$/,"").trim(),f=l.endsWith("?");if(f&&(l=l.slice(0,-1)),l.startsWith("artifact.")){let u=l.substring(9);if(t.artifactService===void 0)throw new Error("Artifact service is not initialized.");let d=await t.artifactService.loadArtifact({appName:t.session.appName,userId:t.session.userId,sessionId:t.session.id,filename:u});if(!d)throw new Error(`Artifact ${u} not found.`);return String(d)}if(!io(l))return c[0];if(l in t.session.state)return String(t.session.state[l]);if(f)return"";throw new Error(`Context variable not found: \`${l}\`.`)}let r=/\{+[^{}]*}+/g,i=[],s=0,a=o.matchAll(r);for(let c of a){i.push(o.slice(s,c.index));let l=await n(c);i.push(l),s=c.index+c[0].length}return i.push(o.slice(s)),i.join("")}var oo=/^[a-zA-Z_][a-zA-Z0-9_]*$/;function fn(o){return o===""||o===void 0?!1:oo.test(o)}var ro=[x.APP_PREFIX,x.USER_PREFIX,x.TEMP_PREFIX];function io(o){let e=o.split(":");return e.length===0||e.length>2?!1:e.length===1?fn(o):ro.includes(e[0]+":")?fn(e[1]):!1}var lt=(n=>(n.NONE="none",n.SSE="sse",n.BIDI="bidi",n))(lt||{});function dn(o={}){return{saveInputBlobsAsArtifacts:!1,supportCfc:!1,enableAffectiveDialog:!1,streamingMode:"none",maxLlmCalls:so(o.maxLlmCalls||500),...o}}function so(o){if(o>Number.MAX_SAFE_INTEGER)throw new Error(`maxLlmCalls should be less than ${Number.MAX_SAFE_INTEGER}.`);return o<=0&&p.warn("maxLlmCalls is less than or equal to 0. This will result in no enforcement on total number of llm calls that will be made for a run. This may not be ideal, as this could result in a never ending communication between the model and the agent in certain cases."),o}var mn="adk_agent_name";async function gn(o,e){return o instanceof $?[o]:await o.getTools(e)}var ut=class extends X{async*runAsync(e,t){var r;let n=e.agent;n instanceof S&&(t.model=n.canonicalModel.model,t.config={...(r=n.generateContentConfig)!=null?r:{}},n.outputSchema&&nn(t,n.outputSchema),e.runConfig&&(t.liveConnectConfig.responseModalities=e.runConfig.responseModalities,t.liveConnectConfig.speechConfig=e.runConfig.speechConfig,t.liveConnectConfig.outputAudioTranscription=e.runConfig.outputAudioTranscription,t.liveConnectConfig.inputAudioTranscription=e.runConfig.inputAudioTranscription,t.liveConnectConfig.realtimeInputConfig=e.runConfig.realtimeInputConfig,t.liveConnectConfig.enableAffectiveDialog=e.runConfig.enableAffectiveDialog,t.liveConnectConfig.proactivity=e.runConfig.proactivity))}},ao=new ut,ft=class extends X{async*runAsync(e,t){let n=e.agent,r=[`You are an agent. Your internal name is "${n.name}".`];n.description&&r.push(`The description about you is "${n.description}"`),ye(t,r)}},co=new ft,dt=class extends X{async*runAsync(e,t){let n=e.agent;if(!(n instanceof S)||!(n.rootAgent instanceof S))return;let r=n.rootAgent;if(r instanceof S&&r.globalInstruction){let{instruction:i,requireStateInjection:s}=await r.canonicalGlobalInstruction(new F(e)),a=i;s&&(a=await ct(i,new F(e))),ye(t,[a])}if(n.instruction){let{instruction:i,requireStateInjection:s}=await n.canonicalInstruction(new F(e)),a=i;s&&(a=await ct(i,new F(e))),ye(t,[a])}}},lo=new dt,pt=class{async*runAsync(e,t){let n=e.agent;!n||!(n instanceof S)||(n.includeContents==="default"?t.contents=at(e.session.events,n.name,e.branch):t.contents=cn(e.session.events,n.name,e.branch))}},uo=new pt,mt=class extends X{constructor(){super(...arguments);this.toolName="transfer_to_agent";this.tool=new W({name:this.toolName,description:"Transfer the question to another agent. This tool hands off control to another agent when it is more suitable to answer the user question according to the agent description.",parameters:pn.object({agentName:pn.string().describe("the agent name to transfer to.")}),execute:function(t,n){if(!n)throw new Error("toolContext is required.");return n.actions.transferToAgent=t.agentName,"Transfer queued"}})}async*runAsync(t,n){if(!(t.agent instanceof S))return;let r=this.getTransferTargets(t.agent);if(!r.length)return;ye(n,[this.buildTargetAgentsInstructions(t.agent,r)]);let i=new H({invocationContext:t});await this.tool.processLlmRequest({toolContext:i,llmRequest:n})}buildTargetAgentsInfo(t){return`
17
+ `+t:o.config.systemInstruction=t}function nn(o,e){o.config||(o.config={}),o.config.responseSchema=e,o.config.responseMimeType="application/json"}import{createPartFromText as ot,FinishReason as zn,GoogleGenAI as rt}from"@google/genai";function on(){return Kn("GOOGLE_GENAI_USE_VERTEXAI")?"VERTEX_AI":"GEMINI_API"}function Kn(o){if(!process.env)return!1;let e=(process.env[o]||"").toLowerCase();return["true","1"].includes(e)}var ke=class{constructor(e){this.geminiSession=e}async sendHistory(e){let t=e.filter(n=>{var r;return n.parts&&((r=n.parts[0])==null?void 0:r.text)});t.length>0?this.geminiSession.sendClientContent({turns:t,turnComplete:t[t.length-1].role==="user"}):p.info("no content is sent")}async sendContent(e){if(!e.parts)throw new Error("Content must have parts.");if(e.parts[0].functionResponse){let t=e.parts.map(n=>n.functionResponse).filter(n=>!!n);p.debug("Sending LLM function response:",t),this.geminiSession.sendToolResponse({functionResponses:t})}else p.debug("Sending LLM new content",e),this.geminiSession.sendClientContent({turns:[e],turnComplete:!0})}async sendRealtime(e){p.debug("Sending LLM Blob:",e),this.geminiSession.sendRealtimeInput({media:e})}buildFullTextResponse(e){return{content:{role:"model",parts:[{text:e}]}}}async*receive(){throw new Error("Not Implemented.")}async close(){this.geminiSession.close()}};import{FinishReason as Vn}from"@google/genai";function nt(o){var t;let e=o.usageMetadata;if(o.candidates&&o.candidates.length>0){let n=o.candidates[0];return(t=n.content)!=null&&t.parts&&n.content.parts.length>0?{content:n.content,groundingMetadata:n.groundingMetadata,usageMetadata:e,finishReason:n.finishReason}:n.finishReason===Vn.STOP?{usageMetadata:e,finishReason:n.finishReason}:{errorCode:n.finishReason,errorMessage:n.finishMessage,usageMetadata:e,finishReason:n.finishReason}}return o.promptFeedback?{errorCode:o.promptFeedback.blockReason,errorMessage:o.promptFeedback.blockReasonMessage,usageMetadata:e}:{errorCode:"UNKNOWN_ERROR",errorMessage:"Unknown error.",usageMetadata:e}}var it="https://aiplatform.googleapis.com/v1/publishers/google",ge=class extends me{constructor({model:e,apiKey:t,vertexai:n,project:r,location:i,headers:s,apiEndpoint:a,vertexApiEndpoint:c}){e||(e="gemini-2.5-flash"),super({model:e}),this.project=r,this.location=i,this.apiKey=t,this.headers=s,this.isGemini3Preview=Wt(e);let l=typeof process=="object",f=l?process.env.AI_STUDIO_API_KEY:void 0,u=!!f;this.apiEndpoint=a,!this.apiEndpoint&&l&&(this.apiEndpoint=process.env.GEMINI_API_ENDPOINT),this.vertexApiEndpoint=c,!this.vertexApiEndpoint&&l&&(this.vertexApiEndpoint=process.env.GEMINI_VERTEX_API_ENDPOINT),!this.vertexApiEndpoint&&this.isGemini3Preview&&!u&&(this.vertexApiEndpoint=it,p.info(`Using Gemini 3 preview endpoint: ${this.vertexApiEndpoint}`));let d=!!n;if(!d&&l){let m=process.env.GOOGLE_GENAI_USE_VERTEXAI;m&&(d=m.toLowerCase()==="true"||m==="1")}if(u&&(d&&p.info("AI_STUDIO_API_KEY set \u2014 overriding Vertex AI mode to use AI Studio (generativelanguage.googleapis.com)"),d=!1,this.apiKey=f,this.vertexApiEndpoint=void 0),this.isGemini3Preview&&d){let m=t||(l?process.env.GOOGLE_GENAI_API_KEY||process.env.GEMINI_API_KEY:void 0);m?(p.info("Gemini 3 preview detected with Vertex AI mode. Switching to API key mode for correct endpoint handling."),d=!1,this.apiKey=m):p.warn("Gemini 3 preview requires API key authentication for correct endpoint handling. Set GEMINI_API_KEY or GOOGLE_GENAI_API_KEY environment variable for best compatibility.")}if(this.vertexai=d,this.vertexai){if(l&&!this.project&&(this.project=process.env.GOOGLE_CLOUD_PROJECT),l&&!this.location&&(this.location=process.env.GOOGLE_CLOUD_LOCATION),!this.project)throw new Error("VertexAI project must be provided via constructor or GOOGLE_CLOUD_PROJECT environment variable.");if(!this.location)throw new Error("VertexAI location must be provided via constructor or GOOGLE_CLOUD_LOCATION environment variable.")}else if(!this.apiKey&&l&&(this.apiKey=process.env.GOOGLE_GENAI_API_KEY||process.env.GEMINI_API_KEY),!this.apiKey)throw new Error("API key must be provided via constructor or GOOGLE_GENAI_API_KEY or GEMINI_API_KEY environment variable.")}async*generateContentAsync(e,t=!1){var n,r,i,s,a,c,l,f,u,d,m,w,R,y,g,b,h;if(this.preprocessRequest(e),this.maybeAppendUserContent(e),p.info(`Sending out request, model: ${e.model}, backend: ${this.apiBackend}, stream: ${t}`),(n=e.config)!=null&&n.httpOptions&&(e.config.httpOptions.headers={...e.config.httpOptions.headers,...this.trackingHeaders}),t){let I=await this.apiClient.models.generateContentStream({model:(r=e.model)!=null?r:this.model,contents:e.contents,config:e.config}),v="",A,C="",ee,k,O=null;for await(let Z of I){k=Z;let E=nt(Z);ee=E.usageMetadata;let D=(s=(i=E.content)==null?void 0:i.parts)==null?void 0:s[0],Ce=(c=(a=E.content)==null?void 0:a.parts)==null?void 0:c.some(N=>N.functionCall);if(this.isGemini3Preview&&((l=E.content)!=null&&l.parts)){for(let N of E.content.parts)if(N.thoughtSignature&&!A){A=N.thoughtSignature,p.debug(`[Gemini3] Captured thoughtSignature (length: ${A.length})`);break}}if(D!=null&&D.text)"thought"in D&&D.thought?(v+=D.text,"thoughtSignature"in D&&D.thoughtSignature&&(A=D.thoughtSignature)):C+=D.text,Ce||(E.partial=!0),this.isGemini3Preview&&Ce&&(v="",A=void 0,C="");else if((v||C)&&(!D||!D.inlineData))if(this.isGemini3Preview&&Ce&&E.content){let N=[];if(v){let M={text:v,thought:!0};A&&(M.thoughtSignature=A),N.push(M)}if(C&&N.push(ot(C)),!v&&A){for(let M of E.content.parts||[])if(M.functionCall&&!M.thoughtSignature){M.thoughtSignature=A;break}}E.content.parts=[...N,...E.content.parts||[]],v="",A=void 0,C=""}else{let N=[];if(v){let M={text:v,thought:!0};A&&(M.thoughtSignature=A),N.push(M)}C&&N.push(ot(C)),yield{content:{role:"model",parts:N},usageMetadata:E.usageMetadata},v="",A=void 0,C=""}if(this.isGemini3Preview&&Ce&&((f=E.content)!=null&&f.parts)&&!E.content.parts.some(M=>M.thoughtSignature)&&A){for(let M of E.content.parts)if(M.functionCall){M.thoughtSignature=A;break}}if(Ce){if(O&&((u=O.content)!=null&&u.parts)){let N=(((d=E.content)==null?void 0:d.parts)||[]).filter(M=>M.functionCall||M.thoughtSignature);O.content.parts.push(...N),O.usageMetadata=E.usageMetadata}else O=E;continue}if(O){if(!((w=(m=E.content)==null?void 0:m.parts)!=null&&w.length))continue;yield O,O=null}yield E}if(O){if(this.isGemini3Preview&&((R=O.content)!=null&&R.parts)){let Z=O.content.parts.filter(E=>E.thoughtSignature).length;if(Z===0&&A){for(let E of O.content.parts)if(E.functionCall){E.thoughtSignature=A;break}}else Z===0&&p.warn("[Gemini3] No thoughtSignature on merged function call parts \u2014 may cause 400 on next request")}yield O,O=null}if((C||v)&&((g=(y=k==null?void 0:k.candidates)==null?void 0:y[0])==null?void 0:g.finishReason)===zn.STOP){let Z=[];if(v){let E={text:v,thought:!0};A&&(E.thoughtSignature=A),Z.push(E)}C&&Z.push({text:C}),yield{content:{role:"model",parts:Z},usageMetadata:ee}}}else{let I=await this.apiClient.models.generateContent({model:(b=e.model)!=null?b:this.model,contents:e.contents,config:e.config}),v=nt(I);if(this.isGemini3Preview&&((h=v.content)!=null&&h.parts)){let A,C=!1;for(let k of v.content.parts)if(k.thoughtSignature){A=k.thoughtSignature,k.thought&&(C=!0);break}if(A&&!C){for(let k of v.content.parts)if(k.functionCall&&!k.thoughtSignature){k.thoughtSignature=A;break}}v.content.parts.some(k=>k.functionCall)&&v.content.parts.filter(O=>O.thoughtSignature).length===0&&p.warn("[Gemini3] No thoughtSignature on function call parts \u2014 may cause 400 on next request")}yield v}}get apiClient(){if(this._apiClient)return this._apiClient;let e={...this.trackingHeaders,...this.headers};if(this.vertexai)this._apiClient=new rt({vertexai:this.vertexai,project:this.project,location:this.location,httpOptions:{headers:e}});else{let t={headers:e};if(this.isGemini3Preview&&this.vertexApiEndpoint){let n=this.vertexApiEndpoint===it;t.baseUrl=n?this.vertexApiEndpoint:`${this.vertexApiEndpoint}/v1/publishers/google`,t.apiVersion="",p.debug(`Gemini 3 preview endpoint: ${t.baseUrl}`)}else this.apiEndpoint&&(t.baseUrl=this.apiEndpoint,p.debug(`API endpoint: ${t.baseUrl}`));this._apiClient=new rt({apiKey:this.apiKey,vertexai:!1,httpOptions:t})}return this._apiClient}get apiBackend(){return this._apiBackend||(this._apiBackend=this.apiClient.vertexai?"VERTEX_AI":"GEMINI_API"),this._apiBackend}get liveApiVersion(){return this._liveApiVersion||(this._liveApiVersion=this.apiBackend==="VERTEX_AI"?"v1beta1":"v1alpha"),this._liveApiVersion}get liveApiClient(){if(!this._liveApiClient){let e={headers:this.trackingHeaders,apiVersion:this.liveApiVersion};if(this.isGemini3Preview&&this.vertexApiEndpoint){let t=this.vertexApiEndpoint===it;e.baseUrl=t?this.vertexApiEndpoint:`${this.vertexApiEndpoint}/v1/publishers/google`,e.apiVersion=""}else this.apiEndpoint&&(e.baseUrl=this.apiEndpoint);this._liveApiClient=new rt({apiKey:this.apiKey,httpOptions:e})}return this._liveApiClient}async connect(e){var n,r,i,s;(n=e.liveConnectConfig)!=null&&n.httpOptions&&(e.liveConnectConfig.httpOptions.headers||(e.liveConnectConfig.httpOptions.headers={}),Object.assign(e.liveConnectConfig.httpOptions.headers,this.trackingHeaders),e.liveConnectConfig.httpOptions.apiVersion=this.isGemini3Preview?"":this.liveApiVersion),(r=e.config)!=null&&r.systemInstruction&&(e.liveConnectConfig.systemInstruction={role:"system",parts:[ot(e.config.systemInstruction)]}),e.liveConnectConfig.tools=(i=e.config)==null?void 0:i.tools;let t=await this.liveApiClient.live.connect({model:(s=e.model)!=null?s:this.model,config:e.liveConnectConfig,callbacks:{onmessage:()=>{}}});return new ke(t)}preprocessRequest(e){var t;if(this.apiBackend==="GEMINI_API"){if(e.config&&(e.config.labels=void 0),e.contents){for(let n of e.contents)if(n.parts)for(let r of n.parts)rn(r.inlineData),rn(r.fileData)}if((t=e.config)!=null&&t.tools&&e.config.tools.length>1){let n=e.config.tools.some(i=>"googleSearch"in i||"googleSearchRetrieval"in i),r=e.config.tools.some(i=>"functionDeclarations"in i);n&&r&&(p.warn("Gemini API (AI Studio) does not support combining built-in search tools with custom function declarations. Removing built-in search tool from this request."),e.config.tools=e.config.tools.filter(i=>!("googleSearch"in i)&&!("googleSearchRetrieval"in i)))}}}};ge.supportedModels=[/gemini-.*/,/projects\/.+\/locations\/.+\/endpoints\/.+/,/projects\/.+\/locations\/.+\/publishers\/google\/models\/gemini.+/];function rn(o){o&&o.displayName&&(o.displayName=void 0)}var st=class{constructor(e){this.maxSize=e,this.cache=new Map}get(e){let t=this.cache.get(e);return t&&(this.cache.delete(e),this.cache.set(e,t)),t}set(e,t){if(this.cache.size>=this.maxSize&&!this.cache.has(e)){let n=this.cache.keys().next().value;n!==void 0&&this.cache.delete(n)}this.cache.set(e,t)}},j=class j{static newLlm(e){return new(j.resolve(e))({model:e})}static _register(e,t){j.llmRegistryDict.has(e)&&p.info(`Updating LLM class for ${e} from ${j.llmRegistryDict.get(e)} to ${t}`),j.llmRegistryDict.set(e,t)}static register(e){for(let t of e.supportedModels)j._register(t,e)}static resolve(e){let t=j.resolveCache.get(e);if(t)return t;for(let[n,r]of j.llmRegistryDict.entries())if(new RegExp(`^${n instanceof RegExp?n.source:n}$`,n instanceof RegExp?n.flags:void 0).test(e))return j.resolveCache.set(e,r),r;throw new Error(`Model ${e} not found.`)}};j.llmRegistryDict=new Map,j.resolveCache=new st(32);var he=j;he.register(ge);var $=class{constructor(e){var t;this.name=e.name,this.description=e.description,this.isLongRunning=(t=e.isLongRunning)!=null?t:!1}_getDeclaration(){}async processLlmRequest({toolContext:e,llmRequest:t}){let n=this._getDeclaration();if(!n)return;t.toolsDict[this.name]=this;let r=Yn(t);r?(r.functionDeclarations||(r.functionDeclarations=[]),r.functionDeclarations.push(n)):(t.config=t.config||{},t.config.tools=t.config.tools||[],t.config.tools.push({functionDeclarations:[n]}))}get apiVariant(){return on()}};function Yn(o){var e;return(((e=o.config)==null?void 0:e.tools)||[]).find(t=>"functionDeclarations"in t)}import{Type as Wn}from"@google/genai";import{ZodObject as Xn}from"zod";import{Type as B}from"@google/genai";import{z as P}from"zod";function sn(o){var e;return o!==null&&typeof o=="object"&&((e=o._def)==null?void 0:e.typeName)==="ZodObject"}function Y(o){let e=o._def;if(!e)return{};let t=e.description,n={};t&&(n.description=t);let r=i=>(i.description===void 0&&delete i.description,i);switch(e.typeName){case P.ZodFirstPartyTypeKind.ZodString:n.type=B.STRING;for(let c of e.checks||[])c.kind==="min"?n.minLength=c.value.toString():c.kind==="max"?n.maxLength=c.value.toString():c.kind==="email"?n.format="email":c.kind==="uuid"?n.format="uuid":c.kind==="url"?n.format="uri":c.kind==="regex"&&(n.pattern=c.regex.source);return r(n);case P.ZodFirstPartyTypeKind.ZodNumber:n.type=B.NUMBER;for(let c of e.checks||[])c.kind==="min"?n.minimum=c.value:c.kind==="max"?n.maximum=c.value:c.kind==="int"&&(n.type=B.INTEGER);return r(n);case P.ZodFirstPartyTypeKind.ZodBoolean:return n.type=B.BOOLEAN,r(n);case P.ZodFirstPartyTypeKind.ZodArray:return n.type=B.ARRAY,n.items=Y(e.type),e.minLength&&(n.minItems=e.minLength.value.toString()),e.maxLength&&(n.maxItems=e.maxLength.value.toString()),r(n);case P.ZodFirstPartyTypeKind.ZodObject:return _e(o);case P.ZodFirstPartyTypeKind.ZodLiteral:let i=typeof e.value;if(n.enum=[e.value.toString()],i==="string")n.type=B.STRING;else if(i==="number")n.type=B.NUMBER;else if(i==="boolean")n.type=B.BOOLEAN;else if(e.value===null)n.type=B.NULL;else throw new Error(`Unsupported ZodLiteral value type: ${i}`);return r(n);case P.ZodFirstPartyTypeKind.ZodEnum:return n.type=B.STRING,n.enum=e.values,r(n);case P.ZodFirstPartyTypeKind.ZodNativeEnum:return n.type=B.STRING,n.enum=Object.values(e.values),r(n);case P.ZodFirstPartyTypeKind.ZodUnion:return n.anyOf=e.options.map(Y),r(n);case P.ZodFirstPartyTypeKind.ZodOptional:return Y(e.innerType);case P.ZodFirstPartyTypeKind.ZodNullable:let s=Y(e.innerType);return r(s?{anyOf:[s,{type:B.NULL}],...t&&{description:t}}:{type:B.NULL,...t&&{description:t}});case P.ZodFirstPartyTypeKind.ZodDefault:let a=Y(e.innerType);return a&&(a.default=e.defaultValue()),a;case P.ZodFirstPartyTypeKind.ZodBranded:return Y(e.type);case P.ZodFirstPartyTypeKind.ZodReadonly:return Y(e.innerType);case P.ZodFirstPartyTypeKind.ZodNull:return n.type=B.NULL,r(n);case P.ZodFirstPartyTypeKind.ZodAny:case P.ZodFirstPartyTypeKind.ZodUnknown:return r({...t&&{description:t}});default:throw new Error(`Unsupported Zod type: ${e.typeName}`)}}function _e(o){if(o._def.typeName!==P.ZodFirstPartyTypeKind.ZodObject)throw new Error("Expected a ZodObject");let e=o.shape,t={},n=[];for(let s in e){let a=e[s],c=Y(a);c&&(t[s]=c);let l=a,f=!1;for(;l._def.typeName===P.ZodFirstPartyTypeKind.ZodOptional||l._def.typeName===P.ZodFirstPartyTypeKind.ZodDefault;)f=!0,l=l._def.innerType;f||n.push(s)}let r=o._def.catchall,i=!1;return r&&r._def.typeName!==P.ZodFirstPartyTypeKind.ZodNever?i=Y(r)||!0:i=o._def.unknownKeys==="passthrough",{type:B.OBJECT,properties:t,required:n.length>0?n:[],...o._def.description?{description:o._def.description}:{}}}function Qn(o){return o===void 0?{type:Wn.OBJECT,properties:{}}:sn(o)?_e(o):o}var W=class extends ${constructor(e){var n;let t=(n=e.name)!=null?n:e.execute.name;if(!t)throw new Error("Tool name cannot be empty. Either name the `execute` function or provide a `name`.");super({name:t,description:e.description,isLongRunning:e.isLongRunning}),this.execute=e.execute,this.parameters=e.parameters}_getDeclaration(){return{name:this.name,description:this.description,parameters:Qn(this.parameters)}}async runAsync(e){try{let t=e.args;return this.parameters instanceof Xn&&(t=this.parameters.parse(e.args)),await this.execute(t,e.toolContext)}catch(t){let n=t instanceof Error?t.message:String(t);throw new Error(`Error in tool '${this.name}': ${n}`)}}};var X=class{};function at(o,e,t){var s,a;let n=[];for(let c of o)!((s=c.content)!=null&&s.role)||!((a=c.content.parts)!=null&&a.length)||t&&c.branch&&!t.startsWith(c.branch)||Hn(c)||Jn(c)||n.push(ln(e,c)?eo(c):c);let r=to(n);r=no(r);let i=[];for(let c of r){let l=U(c.content);Gt(l),i.push(l)}return i}function cn(o,e,t){for(let n=o.length-1;n>=0;n--){let r=o[n];if(r.author==="user"||ln(e,r))return at(o.slice(n),e,t)}return[]}function Hn(o){var e,t,n;if(!((e=o.content)!=null&&e.parts))return!1;for(let r of o.content.parts)if(((t=r.functionCall)==null?void 0:t.name)===Pe||((n=r.functionResponse)==null?void 0:n.name)===Pe)return!0;return!1}function Jn(o){var e,t,n;if(!((e=o.content)!=null&&e.parts))return!1;for(let r of o.content.parts)if(((t=r.functionCall)==null?void 0:t.name)===de||((n=r.functionResponse)==null?void 0:n.name)===de)return!0;return!1}function ln(o,e){return!!o&&e.author!==o&&e.author!=="user"}function eo(o){var t,n,r,i,s,a;if(!((n=(t=o.content)==null?void 0:t.parts)!=null&&n.length))return o;let e={role:"user",parts:[{text:"For context:"}]};for(let c of o.content.parts)if(c.text&&!c.thought)(r=e.parts)==null||r.push({text:`[${o.author}] said: ${c.text}`});else if(c.functionCall){let l=an(c.functionCall.args);(i=e.parts)==null||i.push({text:`[${o.author}] called tool \`${c.functionCall.name}\` with parameters: ${l}`})}else if(c.functionResponse){let l=an(c.functionResponse.response);(s=e.parts)==null||s.push({text:`[${o.author}] tool \`${c.functionResponse.name}\` returned result: ${l}`})}else(a=e.parts)==null||a.push(c);return T({invocationId:o.invocationId,author:"user",content:e,branch:o.branch,timestamp:o.timestamp})}function un(o){var r;if(o.length===0)throw new Error("Cannot merge an empty list of events.");let e=T(o[0]),t=((r=e.content)==null?void 0:r.parts)||[];if(t.length===0)throw new Error("There should be at least one function_response part.");let n={};for(let i=0;i<t.length;i++){let s=t[i];s.functionResponse&&s.functionResponse.id&&(n[s.functionResponse.id]=i)}for(let i of o.slice(1)){if(!i.content||!i.content.parts)throw new Error("There should be at least one function_response part.");for(let s of i.content.parts)if(s.functionResponse&&s.functionResponse.id){let a=s.functionResponse.id;a in n?t[n[a]]=s:(t.push(s),n[a]=t.length-1)}else t.push(s)}return e}function to(o){if(o.length===0)return o;let e=o[o.length-1],t=G(e);if(!(t!=null&&t.length))return o;let n=new Set(t.filter(c=>!!c.id).map(c=>c.id)),r=o.at(-2);if(r){let c=L(r);if(c){for(let l of c)if(l.id&&n.has(l.id))return o}}let i=-1;for(let c=o.length-2;c>=0;c--){let l=o[c],f=L(l);if(f!=null&&f.length){for(let u of f)if(u.id&&n.has(u.id)){i=c;let d=new Set(f.map(w=>w.id).filter(w=>!!w));if(!Array.from(n).every(w=>d.has(w)))throw new Error(`Last response event should only contain the responses for the function calls in the same function call event. Function call ids found : ${Array.from(d).join(", ")}, function response ids provided: ${Array.from(n).join(", ")}`);n=d;break}}}if(i===-1)throw new Error(`No function call event found for function responses ids: ${Array.from(n).join(", ")}`);let s=[];for(let c=i+1;c<o.length-1;c++){let l=o[c],f=G(l);f&&f.some(u=>u.id&&n.has(u.id))&&s.push(l)}s.push(o[o.length-1]);let a=o.slice(0,i+1);return a.push(un(s)),a}function no(o){let e=new Map;for(let n=0;n<o.length;n++){let r=o[n],i=G(r);if(i!=null&&i.length)for(let s of i)s.id&&e.set(s.id,n)}let t=[];for(let n of o){if(G(n).length>0)continue;let r=L(n);if(r!=null&&r.length){let i=new Set;for(let s of r){let a=s.id;a&&e.has(a)&&i.add(e.get(a))}if(t.push(n),i.size===0)continue;if(i.size===1){let[s]=[...i];t.push(o[s])}else{let a=Array.from(i).sort((c,l)=>c-l).map(c=>o[c]);t.push(un(a))}}else t.push(n)}return t}function an(o){if(typeof o=="string")return o;try{return JSON.stringify(o)}catch{return String(o)}}async function ct(o,e){let t=e.invocationContext;async function n(c){let l=c[0].replace(/^\{+/,"").replace(/\}+$/,"").trim(),f=l.endsWith("?");if(f&&(l=l.slice(0,-1)),l.startsWith("artifact.")){let u=l.substring(9);if(t.artifactService===void 0)throw new Error("Artifact service is not initialized.");let d=await t.artifactService.loadArtifact({appName:t.session.appName,userId:t.session.userId,sessionId:t.session.id,filename:u});if(!d)throw new Error(`Artifact ${u} not found.`);return String(d)}if(!io(l))return c[0];if(l in t.session.state)return String(t.session.state[l]);if(f)return"";throw new Error(`Context variable not found: \`${l}\`.`)}let r=/\{+[^{}]*}+/g,i=[],s=0,a=o.matchAll(r);for(let c of a){i.push(o.slice(s,c.index));let l=await n(c);i.push(l),s=c.index+c[0].length}return i.push(o.slice(s)),i.join("")}var oo=/^[a-zA-Z_][a-zA-Z0-9_]*$/;function fn(o){return o===""||o===void 0?!1:oo.test(o)}var ro=[x.APP_PREFIX,x.USER_PREFIX,x.TEMP_PREFIX];function io(o){let e=o.split(":");return e.length===0||e.length>2?!1:e.length===1?fn(o):ro.includes(e[0]+":")?fn(e[1]):!1}var lt=(n=>(n.NONE="none",n.SSE="sse",n.BIDI="bidi",n))(lt||{});function dn(o={}){return{saveInputBlobsAsArtifacts:!1,supportCfc:!1,enableAffectiveDialog:!1,streamingMode:"none",maxLlmCalls:so(o.maxLlmCalls||500),...o}}function so(o){if(o>Number.MAX_SAFE_INTEGER)throw new Error(`maxLlmCalls should be less than ${Number.MAX_SAFE_INTEGER}.`);return o<=0&&p.warn("maxLlmCalls is less than or equal to 0. This will result in no enforcement on total number of llm calls that will be made for a run. This may not be ideal, as this could result in a never ending communication between the model and the agent in certain cases."),o}var mn="adk_agent_name";async function gn(o,e){return o instanceof $?[o]:await o.getTools(e)}var ut=class extends X{async*runAsync(e,t){var r;let n=e.agent;n instanceof S&&(t.model=n.canonicalModel.model,t.config={...(r=n.generateContentConfig)!=null?r:{}},n.outputSchema&&nn(t,n.outputSchema),e.runConfig&&(t.liveConnectConfig.responseModalities=e.runConfig.responseModalities,t.liveConnectConfig.speechConfig=e.runConfig.speechConfig,t.liveConnectConfig.outputAudioTranscription=e.runConfig.outputAudioTranscription,t.liveConnectConfig.inputAudioTranscription=e.runConfig.inputAudioTranscription,t.liveConnectConfig.realtimeInputConfig=e.runConfig.realtimeInputConfig,t.liveConnectConfig.enableAffectiveDialog=e.runConfig.enableAffectiveDialog,t.liveConnectConfig.proactivity=e.runConfig.proactivity))}},ao=new ut,ft=class extends X{async*runAsync(e,t){let n=e.agent,r=[`You are an agent. Your internal name is "${n.name}".`];n.description&&r.push(`The description about you is "${n.description}"`),ye(t,r)}},co=new ft,dt=class extends X{async*runAsync(e,t){let n=e.agent;if(!(n instanceof S)||!(n.rootAgent instanceof S))return;let r=n.rootAgent;if(r instanceof S&&r.globalInstruction){let{instruction:i,requireStateInjection:s}=await r.canonicalGlobalInstruction(new F(e)),a=i;s&&(a=await ct(i,new F(e))),ye(t,[a])}if(n.instruction){let{instruction:i,requireStateInjection:s}=await n.canonicalInstruction(new F(e)),a=i;s&&(a=await ct(i,new F(e))),ye(t,[a])}}},lo=new dt,pt=class{async*runAsync(e,t){let n=e.agent;!n||!(n instanceof S)||(n.includeContents==="default"?t.contents=at(e.session.events,n.name,e.branch):t.contents=cn(e.session.events,n.name,e.branch))}},uo=new pt,mt=class extends X{constructor(){super(...arguments);this.toolName="transfer_to_agent";this.tool=new W({name:this.toolName,description:"Transfer the question to another agent. This tool hands off control to another agent when it is more suitable to answer the user question according to the agent description.",parameters:pn.object({agentName:pn.string().describe("the agent name to transfer to.")}),execute:function(t,n){if(!n)throw new Error("toolContext is required.");return n.actions.transferToAgent=t.agentName,"Transfer queued"}})}async*runAsync(t,n){if(!(t.agent instanceof S))return;let r=this.getTransferTargets(t.agent);if(!r.length)return;ye(n,[this.buildTargetAgentsInstructions(t.agent,r)]);let i=new H({invocationContext:t});await this.tool.processLlmRequest({toolContext:i,llmRequest:n})}buildTargetAgentsInfo(t){return`
18
18
  Agent name: ${t.name}
19
19
  Agent description: ${t.description}
20
20
  `}buildTargetAgentsInstructions(t,n){let r=`