@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.
- package/dist/cjs/index.js +1 -1
- package/dist/cjs/index.js.map +2 -2
- package/dist/cjs/models/google_llm.js +1 -0
- package/dist/esm/index.js +1 -1
- package/dist/esm/index.js.map +2 -2
- package/dist/esm/models/google_llm.js +1 -0
- package/dist/web/index.js +1 -1
- package/dist/web/index.js.map +2 -2
- package/dist/web/models/google_llm.js +1 -0
- package/package.json +1 -1
package/dist/cjs/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 gn(o,e){o.config||(o.config={}),o.config.responseSchema=e,o.config.responseMimeType="application/json"}var z=require("@google/genai");function hn(){return So("GOOGLE_GENAI_USE_VERTEXAI")?"VERTEX_AI":"GEMINI_API"}function So(o){if(!process.env)return!1;let e=(process.env[o]||"").toLowerCase();return["true","1"].includes(e)}var je=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()}};var Cn=require("@google/genai");function xt(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===Cn.FinishReason.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 bt="https://aiplatform.googleapis.com/v1/publishers/google",pe=class extends de{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=ln(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=bt,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,L,R,A,g,S,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="",x,C="",se,k,O=null;for await(let X of I){k=X;let E=xt(X);se=E.usageMetadata;let q=(s=(i=E.content)==null?void 0:i.parts)==null?void 0:s[0],xe=(c=(a=E.content)==null?void 0:a.parts)==null?void 0:c.some(B=>B.functionCall);if(this.isGemini3Preview&&((l=E.content)!=null&&l.parts)){for(let B of E.content.parts)if(B.thoughtSignature&&!x){x=B.thoughtSignature,p.debug(`[Gemini3] Captured thoughtSignature (length: ${x.length})`);break}}if(q!=null&&q.text)"thought"in q&&q.thought?(v+=q.text,"thoughtSignature"in q&&q.thoughtSignature&&(x=q.thoughtSignature)):C+=q.text,xe||(E.partial=!0),this.isGemini3Preview&&xe&&(v="",x=void 0,C="");else if((v||C)&&(!q||!q.inlineData))if(this.isGemini3Preview&&xe&&E.content){let B=[];if(v){let M={text:v,thought:!0};x&&(M.thoughtSignature=x),B.push(M)}if(C&&B.push((0,z.createPartFromText)(C)),!v&&x){for(let M of E.content.parts||[])if(M.functionCall&&!M.thoughtSignature){M.thoughtSignature=x;break}}E.content.parts=[...B,...E.content.parts||[]],v="",x=void 0,C=""}else{let B=[];if(v){let M={text:v,thought:!0};x&&(M.thoughtSignature=x),B.push(M)}C&&B.push((0,z.createPartFromText)(C)),yield{content:{role:"model",parts:B},usageMetadata:E.usageMetadata},v="",x=void 0,C=""}if(this.isGemini3Preview&&xe&&((f=E.content)!=null&&f.parts)&&!E.content.parts.some(M=>M.thoughtSignature)&&x){for(let M of E.content.parts)if(M.functionCall){M.thoughtSignature=x;break}}if(xe){if(O&&((u=O.content)!=null&&u.parts)){let B=(((d=E.content)==null?void 0:d.parts)||[]).filter(M=>M.functionCall||M.thoughtSignature);O.content.parts.push(...B),O.usageMetadata=E.usageMetadata}else O=E;continue}if(O){if(!((L=(m=E.content)==null?void 0:m.parts)!=null&&L.length))continue;yield O,O=null}yield E}if(O){if(this.isGemini3Preview&&((R=O.content)!=null&&R.parts)){let X=O.content.parts.filter(E=>E.thoughtSignature).length;if(X===0&&x){for(let E of O.content.parts)if(E.functionCall){E.thoughtSignature=x;break}}else X===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=(A=k==null?void 0:k.candidates)==null?void 0:A[0])==null?void 0:g.finishReason)===z.FinishReason.STOP){let X=[];if(v){let E={text:v,thought:!0};x&&(E.thoughtSignature=x),X.push(E)}C&&X.push({text:C}),yield{content:{role:"model",parts:X},usageMetadata:se}}}else{let I=await this.apiClient.models.generateContent({model:(S=e.model)!=null?S:this.model,contents:e.contents,config:e.config}),v=xt(I);if(this.isGemini3Preview&&((h=v.content)!=null&&h.parts)){let x,C=!1;for(let k of v.content.parts)if(k.thoughtSignature){x=k.thoughtSignature,k.thought&&(C=!0);break}if(x&&!C){for(let k of v.content.parts)if(k.functionCall&&!k.thoughtSignature){k.thoughtSignature=x;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 z.GoogleGenAI({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===bt;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 z.GoogleGenAI({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===bt;e.baseUrl=t?this.vertexApiEndpoint:`${this.vertexApiEndpoint}/v1/publishers/google`,e.apiVersion=""}else this.apiEndpoint&&(e.baseUrl=this.apiEndpoint);this._liveApiClient=new z.GoogleGenAI({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:[(0,z.createPartFromText)(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 je(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)vn(r.inlineData),vn(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)))}}}};pe.supportedModels=[/gemini-.*/,/projects\/.+\/locations\/.+\/endpoints\/.+/,/projects\/.+\/locations\/.+\/publishers\/google\/models\/gemini.+/];function vn(o){o&&o.displayName&&(o.displayName=void 0)}var Tt=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)}},K=class K{static newLlm(e){return new(K.resolve(e))({model:e})}static _register(e,t){K.llmRegistryDict.has(e)&&p.info(`Updating LLM class for ${e} from ${K.llmRegistryDict.get(e)} to ${t}`),K.llmRegistryDict.set(e,t)}static register(e){for(let t of e.supportedModels)K._register(t,e)}static resolve(e){let t=K.resolveCache.get(e);if(t)return t;for(let[n,r]of K.llmRegistryDict.entries())if(new RegExp(`^${n instanceof RegExp?n.source:n}$`,n instanceof RegExp?n.flags:void 0).test(e))return K.resolveCache.set(e,r),r;throw new Error(`Model ${e} not found.`)}};K.llmRegistryDict=new Map,K.resolveCache=new Tt(32);var me=K;me.register(pe);var F=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=Io(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 hn()}};function Io(o){var e;return(((e=o.config)==null?void 0:e.tools)||[]).find(t=>"functionDeclarations"in t)}var yn=require("@google/genai"),An=require("zod");var N=require("@google/genai"),P=require("zod");function En(o){var e;return o!==null&&typeof o=="object"&&((e=o._def)==null?void 0:e.typeName)==="ZodObject"}function H(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.z.ZodFirstPartyTypeKind.ZodString:n.type=N.Type.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.z.ZodFirstPartyTypeKind.ZodNumber:n.type=N.Type.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=N.Type.INTEGER);return r(n);case P.z.ZodFirstPartyTypeKind.ZodBoolean:return n.type=N.Type.BOOLEAN,r(n);case P.z.ZodFirstPartyTypeKind.ZodArray:return n.type=N.Type.ARRAY,n.items=H(e.type),e.minLength&&(n.minItems=e.minLength.value.toString()),e.maxLength&&(n.maxItems=e.maxLength.value.toString()),r(n);case P.z.ZodFirstPartyTypeKind.ZodObject:return Ie(o);case P.z.ZodFirstPartyTypeKind.ZodLiteral:let i=typeof e.value;if(n.enum=[e.value.toString()],i==="string")n.type=N.Type.STRING;else if(i==="number")n.type=N.Type.NUMBER;else if(i==="boolean")n.type=N.Type.BOOLEAN;else if(e.value===null)n.type=N.Type.NULL;else throw new Error(`Unsupported ZodLiteral value type: ${i}`);return r(n);case P.z.ZodFirstPartyTypeKind.ZodEnum:return n.type=N.Type.STRING,n.enum=e.values,r(n);case P.z.ZodFirstPartyTypeKind.ZodNativeEnum:return n.type=N.Type.STRING,n.enum=Object.values(e.values),r(n);case P.z.ZodFirstPartyTypeKind.ZodUnion:return n.anyOf=e.options.map(H),r(n);case P.z.ZodFirstPartyTypeKind.ZodOptional:return H(e.innerType);case P.z.ZodFirstPartyTypeKind.ZodNullable:let s=H(e.innerType);return r(s?{anyOf:[s,{type:N.Type.NULL}],...t&&{description:t}}:{type:N.Type.NULL,...t&&{description:t}});case P.z.ZodFirstPartyTypeKind.ZodDefault:let a=H(e.innerType);return a&&(a.default=e.defaultValue()),a;case P.z.ZodFirstPartyTypeKind.ZodBranded:return H(e.type);case P.z.ZodFirstPartyTypeKind.ZodReadonly:return H(e.innerType);case P.z.ZodFirstPartyTypeKind.ZodNull:return n.type=N.Type.NULL,r(n);case P.z.ZodFirstPartyTypeKind.ZodAny:case P.z.ZodFirstPartyTypeKind.ZodUnknown:return r({...t&&{description:t}});default:throw new Error(`Unsupported Zod type: ${e.typeName}`)}}function Ie(o){if(o._def.typeName!==P.z.ZodFirstPartyTypeKind.ZodObject)throw new Error("Expected a ZodObject");let e=o.shape,t={},n=[];for(let s in e){let a=e[s],c=H(a);c&&(t[s]=c);let l=a,f=!1;for(;l._def.typeName===P.z.ZodFirstPartyTypeKind.ZodOptional||l._def.typeName===P.z.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.z.ZodFirstPartyTypeKind.ZodNever?i=H(r)||!0:i=o._def.unknownKeys==="passthrough",{type:N.Type.OBJECT,properties:t,required:n.length>0?n:[],...o._def.description?{description:o._def.description}:{}}}function Po(o){return o===void 0?{type:yn.Type.OBJECT,properties:{}}:En(o)?Ie(o):o}var Y=class extends F{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:Po(this.parameters)}}async runAsync(e){try{let t=e.args;return this.parameters instanceof An.ZodObject&&(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 J=class{};function St(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)||wo(c)||Lo(c)||n.push(Tn(e,c)?ko(c):c);let r=_o(n);r=Mo(r);let i=[];for(let c of r){let l=j(c.content);Jt(l),i.push(l)}return i}function bn(o,e,t){for(let n=o.length-1;n>=0;n--){let r=o[n];if(r.author==="user"||Tn(e,r))return St(o.slice(n),e,t)}return[]}function wo(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)===Fe||((n=r.functionResponse)==null?void 0:n.name)===Fe)return!0;return!1}function Lo(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)===Ce||((n=r.functionResponse)==null?void 0:n.name)===Ce)return!0;return!1}function Tn(o,e){return!!o&&e.author!==o&&e.author!=="user"}function ko(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=xn(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=xn(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 b({invocationId:o.invocationId,author:"user",content:e,branch:o.branch,timestamp:o.timestamp})}function Sn(o){var r;if(o.length===0)throw new Error("Cannot merge an empty list of events.");let e=b(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 _o(o){if(o.length===0)return o;let e=o[o.length-1],t=$(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=w(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=w(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(L=>L.id).filter(L=>!!L));if(!Array.from(n).every(L=>d.has(L)))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=$(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(Sn(s)),a}function Mo(o){let e=new Map;for(let n=0;n<o.length;n++){let r=o[n],i=$(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($(n).length>0)continue;let r=w(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(Sn(a))}}else t.push(n)}return t}function xn(o){if(typeof o=="string")return o;try{return JSON.stringify(o)}catch{return String(o)}}async function Rt(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(!Bo(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 Rn(o){return o===""||o===void 0?!1:Oo.test(o)}var No=[y.APP_PREFIX,y.USER_PREFIX,y.TEMP_PREFIX];function Bo(o){let e=o.split(":");return e.length===0||e.length>2?!1:e.length===1?Rn(o):No.includes(e[0]+":")?Rn(e[1]):!1}var Ke=(n=>(n.NONE="none",n.SSE="sse",n.BIDI="bidi",n))(Ke||{});function In(o={}){return{saveInputBlobsAsArtifacts:!1,supportCfc:!1,enableAffectiveDialog:!1,streamingMode:"none",maxLlmCalls:Fo(o.maxLlmCalls||500),...o}}function Fo(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 Pn="adk_agent_name";async function wn(o,e){return o instanceof F?[o]:await o.getTools(e)}var Pt=class extends J{async*runAsync(e,t){var r;let n=e.agent;n instanceof T&&(t.model=n.canonicalModel.model,t.config={...(r=n.generateContentConfig)!=null?r:{}},n.outputSchema&&gn(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))}},$o=new Pt,wt=class extends J{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}"`),Re(t,r)}},Do=new wt,Lt=class extends J{async*runAsync(e,t){let n=e.agent;if(!(n instanceof T)||!(n.rootAgent instanceof T))return;let r=n.rootAgent;if(r instanceof T&&r.globalInstruction){let{instruction:i,requireStateInjection:s}=await r.canonicalGlobalInstruction(new D(e)),a=i;s&&(a=await Rt(i,new D(e))),Re(t,[a])}if(n.instruction){let{instruction:i,requireStateInjection:s}=await n.canonicalInstruction(new D(e)),a=i;s&&(a=await Rt(i,new D(e))),Re(t,[a])}}},Go=new Lt,kt=class{async*runAsync(e,t){let n=e.agent;!n||!(n instanceof T)||(n.includeContents==="default"?t.contents=St(e.session.events,n.name,e.branch):t.contents=bn(e.session.events,n.name,e.branch))}},qo=new kt,_t=class extends J{constructor(){super(...arguments);this.toolName="transfer_to_agent";this.tool=new Y({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:It.z.object({agentName:It.z.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 T))return;let r=this.getTransferTargets(t.agent);if(!r.length)return;Re(n,[this.buildTargetAgentsInstructions(t.agent,r)]);let i=new Q({invocationContext:t});await this.tool.processLlmRequest({toolContext:i,llmRequest:n})}buildTargetAgentsInfo(t){return`
|
|
17
|
+
`+t:o.config.systemInstruction=t}function gn(o,e){o.config||(o.config={}),o.config.responseSchema=e,o.config.responseMimeType="application/json"}var z=require("@google/genai");function hn(){return So("GOOGLE_GENAI_USE_VERTEXAI")?"VERTEX_AI":"GEMINI_API"}function So(o){if(!process.env)return!1;let e=(process.env[o]||"").toLowerCase();return["true","1"].includes(e)}var je=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()}};var Cn=require("@google/genai");function xt(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===Cn.FinishReason.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 bt="https://aiplatform.googleapis.com/v1/publishers/google",pe=class extends de{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=ln(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=bt,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,L,R,A,g,S,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="",x,C="",se,k,O=null;for await(let X of I){k=X;let E=xt(X);se=E.usageMetadata;let q=(s=(i=E.content)==null?void 0:i.parts)==null?void 0:s[0],xe=(c=(a=E.content)==null?void 0:a.parts)==null?void 0:c.some(B=>B.functionCall);if(this.isGemini3Preview&&((l=E.content)!=null&&l.parts)){for(let B of E.content.parts)if(B.thoughtSignature&&!x){x=B.thoughtSignature,p.debug(`[Gemini3] Captured thoughtSignature (length: ${x.length})`);break}}if(q!=null&&q.text)"thought"in q&&q.thought?(v+=q.text,"thoughtSignature"in q&&q.thoughtSignature&&(x=q.thoughtSignature)):C+=q.text,xe||(E.partial=!0),this.isGemini3Preview&&xe&&(v="",x=void 0,C="");else if((v||C)&&(!q||!q.inlineData))if(this.isGemini3Preview&&xe&&E.content){let B=[];if(v){let M={text:v,thought:!0};x&&(M.thoughtSignature=x),B.push(M)}if(C&&B.push((0,z.createPartFromText)(C)),!v&&x){for(let M of E.content.parts||[])if(M.functionCall&&!M.thoughtSignature){M.thoughtSignature=x;break}}E.content.parts=[...B,...E.content.parts||[]],v="",x=void 0,C=""}else{let B=[];if(v){let M={text:v,thought:!0};x&&(M.thoughtSignature=x),B.push(M)}C&&B.push((0,z.createPartFromText)(C)),yield{content:{role:"model",parts:B},usageMetadata:E.usageMetadata},v="",x=void 0,C=""}if(this.isGemini3Preview&&xe&&((f=E.content)!=null&&f.parts)&&!E.content.parts.some(M=>M.thoughtSignature)&&x){for(let M of E.content.parts)if(M.functionCall){M.thoughtSignature=x;break}}if(xe){if(O&&((u=O.content)!=null&&u.parts)){let B=(((d=E.content)==null?void 0:d.parts)||[]).filter(M=>M.functionCall||M.thoughtSignature);O.content.parts.push(...B),O.usageMetadata=E.usageMetadata}else O=E;continue}if(O){if(!((L=(m=E.content)==null?void 0:m.parts)!=null&&L.length))continue;yield O,O=null}yield E}if(O){if(this.isGemini3Preview&&((R=O.content)!=null&&R.parts)){let X=O.content.parts.filter(E=>E.thoughtSignature).length;if(X===0&&x){for(let E of O.content.parts)if(E.functionCall){E.thoughtSignature=x;break}}else X===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=(A=k==null?void 0:k.candidates)==null?void 0:A[0])==null?void 0:g.finishReason)===z.FinishReason.STOP){let X=[];if(v){let E={text:v,thought:!0};x&&(E.thoughtSignature=x),X.push(E)}C&&X.push({text:C}),yield{content:{role:"model",parts:X},usageMetadata:se}}}else{let I=await this.apiClient.models.generateContent({model:(S=e.model)!=null?S:this.model,contents:e.contents,config:e.config}),v=xt(I);if(this.isGemini3Preview&&((h=v.content)!=null&&h.parts)){let x,C=!1;for(let k of v.content.parts)if(k.thoughtSignature){x=k.thoughtSignature,k.thought&&(C=!0);break}if(x&&!C){for(let k of v.content.parts)if(k.functionCall&&!k.thoughtSignature){k.thoughtSignature=x;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 z.GoogleGenAI({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===bt;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 z.GoogleGenAI({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===bt;e.baseUrl=t?this.vertexApiEndpoint:`${this.vertexApiEndpoint}/v1/publishers/google`,e.apiVersion=""}else this.apiEndpoint&&(e.baseUrl=this.apiEndpoint);this._liveApiClient=new z.GoogleGenAI({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:[(0,z.createPartFromText)(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 je(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)vn(r.inlineData),vn(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)))}}}};pe.supportedModels=[/gemini-.*/,/projects\/.+\/locations\/.+\/endpoints\/.+/,/projects\/.+\/locations\/.+\/publishers\/google\/models\/gemini.+/];function vn(o){o&&o.displayName&&(o.displayName=void 0)}var Tt=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)}},K=class K{static newLlm(e){return new(K.resolve(e))({model:e})}static _register(e,t){K.llmRegistryDict.has(e)&&p.info(`Updating LLM class for ${e} from ${K.llmRegistryDict.get(e)} to ${t}`),K.llmRegistryDict.set(e,t)}static register(e){for(let t of e.supportedModels)K._register(t,e)}static resolve(e){let t=K.resolveCache.get(e);if(t)return t;for(let[n,r]of K.llmRegistryDict.entries())if(new RegExp(`^${n instanceof RegExp?n.source:n}$`,n instanceof RegExp?n.flags:void 0).test(e))return K.resolveCache.set(e,r),r;throw new Error(`Model ${e} not found.`)}};K.llmRegistryDict=new Map,K.resolveCache=new Tt(32);var me=K;me.register(pe);var F=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=Io(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 hn()}};function Io(o){var e;return(((e=o.config)==null?void 0:e.tools)||[]).find(t=>"functionDeclarations"in t)}var yn=require("@google/genai"),An=require("zod");var N=require("@google/genai"),P=require("zod");function En(o){var e;return o!==null&&typeof o=="object"&&((e=o._def)==null?void 0:e.typeName)==="ZodObject"}function H(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.z.ZodFirstPartyTypeKind.ZodString:n.type=N.Type.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.z.ZodFirstPartyTypeKind.ZodNumber:n.type=N.Type.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=N.Type.INTEGER);return r(n);case P.z.ZodFirstPartyTypeKind.ZodBoolean:return n.type=N.Type.BOOLEAN,r(n);case P.z.ZodFirstPartyTypeKind.ZodArray:return n.type=N.Type.ARRAY,n.items=H(e.type),e.minLength&&(n.minItems=e.minLength.value.toString()),e.maxLength&&(n.maxItems=e.maxLength.value.toString()),r(n);case P.z.ZodFirstPartyTypeKind.ZodObject:return Ie(o);case P.z.ZodFirstPartyTypeKind.ZodLiteral:let i=typeof e.value;if(n.enum=[e.value.toString()],i==="string")n.type=N.Type.STRING;else if(i==="number")n.type=N.Type.NUMBER;else if(i==="boolean")n.type=N.Type.BOOLEAN;else if(e.value===null)n.type=N.Type.NULL;else throw new Error(`Unsupported ZodLiteral value type: ${i}`);return r(n);case P.z.ZodFirstPartyTypeKind.ZodEnum:return n.type=N.Type.STRING,n.enum=e.values,r(n);case P.z.ZodFirstPartyTypeKind.ZodNativeEnum:return n.type=N.Type.STRING,n.enum=Object.values(e.values),r(n);case P.z.ZodFirstPartyTypeKind.ZodUnion:return n.anyOf=e.options.map(H),r(n);case P.z.ZodFirstPartyTypeKind.ZodOptional:return H(e.innerType);case P.z.ZodFirstPartyTypeKind.ZodNullable:let s=H(e.innerType);return r(s?{anyOf:[s,{type:N.Type.NULL}],...t&&{description:t}}:{type:N.Type.NULL,...t&&{description:t}});case P.z.ZodFirstPartyTypeKind.ZodDefault:let a=H(e.innerType);return a&&(a.default=e.defaultValue()),a;case P.z.ZodFirstPartyTypeKind.ZodBranded:return H(e.type);case P.z.ZodFirstPartyTypeKind.ZodReadonly:return H(e.innerType);case P.z.ZodFirstPartyTypeKind.ZodNull:return n.type=N.Type.NULL,r(n);case P.z.ZodFirstPartyTypeKind.ZodAny:case P.z.ZodFirstPartyTypeKind.ZodUnknown:return r({...t&&{description:t}});default:throw new Error(`Unsupported Zod type: ${e.typeName}`)}}function Ie(o){if(o._def.typeName!==P.z.ZodFirstPartyTypeKind.ZodObject)throw new Error("Expected a ZodObject");let e=o.shape,t={},n=[];for(let s in e){let a=e[s],c=H(a);c&&(t[s]=c);let l=a,f=!1;for(;l._def.typeName===P.z.ZodFirstPartyTypeKind.ZodOptional||l._def.typeName===P.z.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.z.ZodFirstPartyTypeKind.ZodNever?i=H(r)||!0:i=o._def.unknownKeys==="passthrough",{type:N.Type.OBJECT,properties:t,required:n.length>0?n:[],...o._def.description?{description:o._def.description}:{}}}function Po(o){return o===void 0?{type:yn.Type.OBJECT,properties:{}}:En(o)?Ie(o):o}var Y=class extends F{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:Po(this.parameters)}}async runAsync(e){try{let t=e.args;return this.parameters instanceof An.ZodObject&&(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 J=class{};function St(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)||wo(c)||Lo(c)||n.push(Tn(e,c)?ko(c):c);let r=_o(n);r=Mo(r);let i=[];for(let c of r){let l=j(c.content);Jt(l),i.push(l)}return i}function bn(o,e,t){for(let n=o.length-1;n>=0;n--){let r=o[n];if(r.author==="user"||Tn(e,r))return St(o.slice(n),e,t)}return[]}function wo(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)===Fe||((n=r.functionResponse)==null?void 0:n.name)===Fe)return!0;return!1}function Lo(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)===Ce||((n=r.functionResponse)==null?void 0:n.name)===Ce)return!0;return!1}function Tn(o,e){return!!o&&e.author!==o&&e.author!=="user"}function ko(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=xn(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=xn(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 b({invocationId:o.invocationId,author:"user",content:e,branch:o.branch,timestamp:o.timestamp})}function Sn(o){var r;if(o.length===0)throw new Error("Cannot merge an empty list of events.");let e=b(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 _o(o){if(o.length===0)return o;let e=o[o.length-1],t=$(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=w(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=w(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(L=>L.id).filter(L=>!!L));if(!Array.from(n).every(L=>d.has(L)))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=$(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(Sn(s)),a}function Mo(o){let e=new Map;for(let n=0;n<o.length;n++){let r=o[n],i=$(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($(n).length>0)continue;let r=w(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(Sn(a))}}else t.push(n)}return t}function xn(o){if(typeof o=="string")return o;try{return JSON.stringify(o)}catch{return String(o)}}async function Rt(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(!Bo(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 Rn(o){return o===""||o===void 0?!1:Oo.test(o)}var No=[y.APP_PREFIX,y.USER_PREFIX,y.TEMP_PREFIX];function Bo(o){let e=o.split(":");return e.length===0||e.length>2?!1:e.length===1?Rn(o):No.includes(e[0]+":")?Rn(e[1]):!1}var Ke=(n=>(n.NONE="none",n.SSE="sse",n.BIDI="bidi",n))(Ke||{});function In(o={}){return{saveInputBlobsAsArtifacts:!1,supportCfc:!1,enableAffectiveDialog:!1,streamingMode:"none",maxLlmCalls:Fo(o.maxLlmCalls||500),...o}}function Fo(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 Pn="adk_agent_name";async function wn(o,e){return o instanceof F?[o]:await o.getTools(e)}var Pt=class extends J{async*runAsync(e,t){var r;let n=e.agent;n instanceof T&&(t.model=n.canonicalModel.model,t.config={...(r=n.generateContentConfig)!=null?r:{}},n.outputSchema&&gn(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))}},$o=new Pt,wt=class extends J{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}"`),Re(t,r)}},Do=new wt,Lt=class extends J{async*runAsync(e,t){let n=e.agent;if(!(n instanceof T)||!(n.rootAgent instanceof T))return;let r=n.rootAgent;if(r instanceof T&&r.globalInstruction){let{instruction:i,requireStateInjection:s}=await r.canonicalGlobalInstruction(new D(e)),a=i;s&&(a=await Rt(i,new D(e))),Re(t,[a])}if(n.instruction){let{instruction:i,requireStateInjection:s}=await n.canonicalInstruction(new D(e)),a=i;s&&(a=await Rt(i,new D(e))),Re(t,[a])}}},Go=new Lt,kt=class{async*runAsync(e,t){let n=e.agent;!n||!(n instanceof T)||(n.includeContents==="default"?t.contents=St(e.session.events,n.name,e.branch):t.contents=bn(e.session.events,n.name,e.branch))}},qo=new kt,_t=class extends J{constructor(){super(...arguments);this.toolName="transfer_to_agent";this.tool=new Y({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:It.z.object({agentName:It.z.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 T))return;let r=this.getTransferTargets(t.agent);if(!r.length)return;Re(n,[this.buildTargetAgentsInstructions(t.agent,r)]);let i=new Q({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=`
|