@google/adk 0.2.0 → 0.2.1
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/README.md +1 -7
- package/dist/cjs/index.js +1 -1
- package/dist/cjs/index.js.map +1 -1
- package/dist/cjs/version.js +1 -1
- package/dist/esm/index.js +1 -1
- package/dist/esm/index.js.map +1 -1
- package/dist/esm/version.js +1 -1
- package/dist/types/version.d.ts +1 -1
- package/dist/web/index.js +1 -1
- package/dist/web/index.js.map +1 -1
- package/dist/web/version.js +1 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -1,9 +1,3 @@
|
|
|
1
1
|
# @google/adk
|
|
2
2
|
|
|
3
|
-
|
|
4
|
-
> **API Stability:** Mostly stable, but expect potential breaking changes
|
|
5
|
-
> before 1.0.
|
|
6
|
-
> **Production Use:** Not recommended yet. Use at your own risk.
|
|
7
|
-
> **Collaboration:** General contributions are closed (issues/PRs). We are,
|
|
8
|
-
> however, accepting organized teams that can follow our coding standards and
|
|
9
|
-
> planning. Please contact us if you are interested.
|
|
3
|
+
Please see README for adk-js at https://github.com/google/adk-js
|
package/dist/cjs/index.js
CHANGED
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
* SPDX-License-Identifier: Apache-2.0
|
|
5
5
|
*/
|
|
6
6
|
|
|
7
|
-
"use strict";var Ne=Object.defineProperty;var Cn=Object.getOwnPropertyDescriptor;var vn=Object.getOwnPropertyNames;var yn=Object.prototype.hasOwnProperty;var An=(o,e)=>{for(var t in e)Ne(o,t,{get:e[t],enumerable:!0})},bn=(o,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of vn(e))!yn.call(o,r)&&r!==t&&Ne(o,r,{get:()=>e[r],enumerable:!(n=Cn(e,r))||n.enumerable});return o};var Tn=o=>bn(Ne({},"__esModule",{value:!0}),o);var yo={};An(yo,{AgentTool:()=>we,BaseAgent:()=>k,BaseLlm:()=>F,BasePlugin:()=>K,BaseSessionService:()=>ce,BaseTool:()=>S,BaseToolset:()=>te,CallbackContext:()=>w,FunctionTool:()=>B,GOOGLE_SEARCH:()=>Xt,GcsArtifactService:()=>ut,Gemini:()=>W,InMemoryArtifactService:()=>J,InMemoryMemoryService:()=>j,InMemoryPolicyEngine:()=>ae,InMemoryRunner:()=>Ie,InMemorySessionService:()=>V,InvocationContext:()=>M,LLMRegistry:()=>Q,LiveRequestQueue:()=>Ce,LlmAgent:()=>b,LogLevel:()=>je,LoggingPlugin:()=>Re,LongRunningFunctionTool:()=>ke,LoopAgent:()=>be,MCPSessionManager:()=>fe,MCPTool:()=>de,MCPToolset:()=>lt,ParallelAgent:()=>Te,PluginManager:()=>ee,PolicyOutcome:()=>st,REQUEST_CONFIRMATION_FUNCTION_CALL_NAME:()=>it,Runner:()=>Z,SecurityPlugin:()=>Se,SequentialAgent:()=>xe,State:()=>h,StreamingMode:()=>Ae,ToolConfirmation:()=>q,ToolContext:()=>N,createEvent:()=>T,createEventActions:()=>_,createSession:()=>le,functionsExportedForTestingOnly:()=>At,getAskUserConfirmationFunctionCalls:()=>Kt,getFunctionCalls:()=>x,getFunctionResponses:()=>I,getGcpExporters:()=>Co,getGcpResource:()=>vo,hasTrailingCodeExecutionResult:()=>Fe,isFinalResponse:()=>z,maybeSetOtelProviders:()=>uo,setLogLevel:()=>vt,stringifyContent:()=>gt,version:()=>ve,zodObjectToSchema:()=>ie});module.exports=Tn(yo);var qe=require("@opentelemetry/api");function _(o={}){return{stateDelta:{},artifactDelta:{},requestedAuthConfigs:{},requestedToolConfirmations:{},...o}}function mt(o,e){let t=_();e&&Object.assign(t,e);for(let n of o)n&&(n.stateDelta&&Object.assign(t.stateDelta,n.stateDelta),n.artifactDelta&&Object.assign(t.artifactDelta,n.artifactDelta),n.requestedAuthConfigs&&Object.assign(t.requestedAuthConfigs,n.requestedAuthConfigs),n.requestedToolConfirmations&&Object.assign(t.requestedToolConfirmations,n.requestedToolConfirmations),n.skipSummarization!==void 0&&(t.skipSummarization=n.skipSummarization),n.transferToAgent!==void 0&&(t.transferToAgent=n.transferToAgent),n.escalate!==void 0&&(t.escalate=n.escalate));return t}function T(o={}){return{...o,id:o.id||$e(),invocationId:o.invocationId||"",author:o.author,actions:o.actions||_(),longRunningToolIds:o.longRunningToolIds||[],branch:o.branch,timestamp:o.timestamp||Date.now()}}function z(o){return o.actions.skipSummarization||o.longRunningToolIds&&o.longRunningToolIds.length>0?!0:x(o).length===0&&I(o).length===0&&!o.partial&&!Fe(o)}function x(o){let e=[];if(o.content&&o.content.parts)for(let t of o.content.parts)t.functionCall&&e.push(t.functionCall);return e}function I(o){let e=[];if(o.content&&o.content.parts)for(let t of o.content.parts)t.functionResponse&&e.push(t.functionResponse);return e}function Fe(o){var e;return o.content&&((e=o.content.parts)!=null&&e.length)?o.content.parts[o.content.parts.length-1].codeExecutionResult!==void 0:!1}function gt(o){var e;return(e=o.content)!=null&&e.parts?o.content.parts.map(t=>{var n;return(n=t.text)!=null?n:""}).join(""):""}var pt="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";function $e(){let o="";for(let e=0;e<8;e++)o+=pt[Math.floor(Math.random()*pt.length)];return o}var h=class{constructor(e,t){this.value=e;this.delta=t}get(e,t){return e in this.delta?this.delta[e]:e in this.value?this.value[e]:t}set(e,t){this.value[e]=t,this.delta[e]=t}has(e){return e in this.value||e in this.delta}hasDelta(){return Object.keys(this.delta).length>0}update(e){this.delta={...this.delta,...e},this.value={...this.value,...e}}toRecord(){return{...this.value,...this.delta}}};h.APP_PREFIX="app:",h.USER_PREFIX="user:",h.TEMP_PREFIX="temp:";var P=class{constructor(e){this.invocationContext=e}get userContent(){return this.invocationContext.userContent}get invocationId(){return this.invocationContext.invocationId}get agentName(){return this.invocationContext.agent.name}get state(){return new h(this.invocationContext.session.state,{})}};var w=class extends P{constructor({invocationContext:e,eventActions:t}){super(e),this.eventActions=t||_(),this._state=new h(e.session.state,this.eventActions.stateDelta)}get state(){return this._state}loadArtifact(e,t){if(!this.invocationContext.artifactService)throw new Error("Artifact service is not initialized.");return this.invocationContext.artifactService.loadArtifact({appName:this.invocationContext.appName,userId:this.invocationContext.userId,sessionId:this.invocationContext.session.id,filename:e,version:t})}async saveArtifact(e,t){if(!this.invocationContext.artifactService)throw new Error("Artifact service is not initialized.");let n=await this.invocationContext.artifactService.saveArtifact({appName:this.invocationContext.appName,userId:this.invocationContext.userId,sessionId:this.invocationContext.session.id,filename:e,artifact:t});return this.eventActions.artifactDelta[e]=n,n}};function De(){return typeof window<"u"}var me="xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx";function X(){let o="";for(let e=0;e<me.length;e++){let t=Math.random()*16|0;me[e]==="x"?o+=t.toString(16):me[e]==="y"?o+=(t&3|8).toString(16):o+=me[e]}return o}var Ge=class{constructor(){this.numberOfLlmCalls=0}incrementAndEnforceLlmCallsLimit(e){if(this.numberOfLlmCalls++,e&&e.maxLlmCalls>0&&this.numberOfLlmCalls>e.maxLlmCalls)throw new Error(`Max number of llm calls limit of ${e.maxLlmCalls} exceeded`)}},M=class{constructor(e){this.invocationCostManager=new Ge;this.artifactService=e.artifactService,this.sessionService=e.sessionService,this.memoryService=e.memoryService,this.invocationId=e.invocationId,this.branch=e.branch,this.agent=e.agent,this.userContent=e.userContent,this.session=e.session,this.endInvocation=e.endInvocation||!1,this.transcriptionCache=e.transcriptionCache,this.runConfig=e.runConfig,this.liveRequestQueue=e.liveRequestQueue,this.activeStreamingTools=e.activeStreamingTools,this.pluginManager=e.pluginManager}get appName(){return this.session.appName}get userId(){return this.session.userId}incrementLlmCallCount(){this.invocationCostManager.incrementAndEnforceLlmCallsLimit(this.runConfig)}};function ht(){return`e-${X()}`}var k=class{constructor(e){this.name=xn(e.name),this.description=e.description,this.parentAgent=e.parentAgent,this.subAgents=e.subAgents||[],this.rootAgent=Rn(this),this.beforeAgentCallback=Ct(e.beforeAgentCallback),this.afterAgentCallback=Ct(e.afterAgentCallback),this.setParentAgentForSubAgents()}async*runAsync(e){let t=qe.trace.getTracer("gcp.vertex.agent").startSpan(`agent_run [${this.name}]`);try{let n=this.createInvocationContext(e),r=await this.handleBeforeAgentCallback(n);if(r&&(yield r),n.endInvocation)return;for await(let s of this.runAsyncImpl(n))yield s;if(n.endInvocation)return;let i=await this.handleAfterAgentCallback(n);i&&(yield i)}finally{t.end()}}async*runLive(e){let t=qe.trace.getTracer("gcp.vertex.agent").startSpan(`agent_run [${this.name}]`);try{throw new Error("Live mode is not implemented yet.")}finally{t.end()}}findAgent(e){return this.name===e?this:this.findSubAgent(e)}findSubAgent(e){for(let t of this.subAgents){let n=t.findAgent(e);if(n)return n}}createInvocationContext(e){return new M({...e,agent:this})}async handleBeforeAgentCallback(e){if(this.beforeAgentCallback.length===0)return;let t=new w({invocationContext:e});for(let n of this.beforeAgentCallback){let r=await n(t);if(r)return e.endInvocation=!0,T({invocationId:e.invocationId,author:this.name,branch:e.branch,content:r,actions:t.eventActions})}if(t.state.hasDelta())return T({invocationId:e.invocationId,author:this.name,branch:e.branch,actions:t.eventActions})}async handleAfterAgentCallback(e){if(this.afterAgentCallback.length===0)return;let t=new w({invocationContext:e});for(let n of this.afterAgentCallback){let r=await n(t);if(r)return T({invocationId:e.invocationId,author:this.name,branch:e.branch,content:r,actions:t.eventActions})}if(t.state.hasDelta())return T({invocationId:e.invocationId,author:this.name,branch:e.branch,actions:t.eventActions})}setParentAgentForSubAgents(){for(let e of this.subAgents){if(e.parentAgent)throw new Error(`Agent "${e.name}" already has a parent agent, current parent: "${e.parentAgent.name}", trying to add: "${this.name}"`);e.parentAgent=this}}};function xn(o){if(!En(o))throw new Error(`Found invalid agent name: "${o}". Agent name must be a valid identifier. It should start with a letter (a-z, A-Z) or an underscore (_), and can only contain letters, digits (0-9), and underscores.`);if(o==="user")throw new Error("Agent name cannot be 'user'. 'user' is reserved for end-user's input.");return o}function En(o){return/^[\p{ID_Start}$_][\p{ID_Continue}$_]*$/u.test(o)}function Rn(o){for(;o.parentAgent;)o=o.parentAgent;return o}function Ct(o){return o?Array.isArray(o)?o:[o]:[]}var yt=require("@google/genai");var oe=class{constructor(e){this.authConfig=e}getAuthResponse(e){let t="temp:"+this.authConfig.credentialKey;return e.get(t)}generateAuthRequest(){var t,n;let e=this.authConfig.authScheme.type;if(!["oauth2","openIdConnect"].includes(e))return this.authConfig;if((n=(t=this.authConfig.exchangedAuthCredential)==null?void 0:t.oauth2)!=null&&n.authUri)return this.authConfig;if(!this.authConfig.rawAuthCredential)throw new Error(`Auth Scheme ${e} requires authCredential.`);if(!this.authConfig.rawAuthCredential.oauth2)throw new Error(`Auth Scheme ${e} requires oauth2 in authCredential.`);if(this.authConfig.rawAuthCredential.oauth2.authUri)return{credentialKey:this.authConfig.credentialKey,authScheme:this.authConfig.authScheme,rawAuthCredential:this.authConfig.rawAuthCredential,exchangedAuthCredential:this.authConfig.rawAuthCredential};if(!this.authConfig.rawAuthCredential.oauth2.clientId||!this.authConfig.rawAuthCredential.oauth2.clientSecret)throw new Error(`Auth Scheme ${e} requires both clientId and clientSecret in authCredential.oauth2.`);return{credentialKey:this.authConfig.credentialKey,authScheme:this.authConfig.authScheme,rawAuthCredential:this.authConfig.rawAuthCredential,exchangedAuthCredential:this.generateAuthUri()}}generateAuthUri(){return this.authConfig.rawAuthCredential}};var q=class{constructor({hint:e,confirmed:t,payload:n}){this.hint=e!=null?e:"",this.confirmed=t,this.payload=n}};var N=class extends w{constructor({invocationContext:e,eventActions:t,functionCallId:n,toolConfirmation:r}){super({invocationContext:e,eventActions:t}),this.functionCallId=n,this.toolConfirmation=r}get actions(){return this.eventActions}requestCredential(e){if(!this.functionCallId)throw new Error("functionCallId is not set.");let t=new oe(e);this.eventActions.requestedAuthConfigs[this.functionCallId]=t.generateAuthRequest()}getAuthResponse(e){return new oe(e).getAuthResponse(this.state)}listArtifacts(){if(!this.invocationContext.artifactService)throw new Error("Artifact service is not initialized.");return this.invocationContext.artifactService.listArtifactKeys({appName:this.invocationContext.session.appName,userId:this.invocationContext.session.userId,sessionId:this.invocationContext.session.id})}searchMemory(e){if(!this.invocationContext.memoryService)throw new Error("Memory service is not initialized.");return this.invocationContext.memoryService.searchMemory({appName:this.invocationContext.session.appName,userId:this.invocationContext.session.userId,query:e})}requestConfirmation({hint:e,payload:t}){if(!this.functionCallId)throw new Error("functionCallId is not set.");this.eventActions.requestedToolConfirmations[this.functionCallId]=new q({hint:e,confirmed:!1,payload:t})}};var je=(r=>(r[r.DEBUG=0]="DEBUG",r[r.INFO=1]="INFO",r[r.WARN=2]="WARN",r[r.ERROR=3]="ERROR",r))(je||{}),H=1;function vt(o){H=o}var Ue=class{log(e,...t){if(!(e<H))switch(e){case 0:this.debug(...t);break;case 1:this.info(...t);break;case 2:this.warn(...t);break;case 3:this.error(...t);break;default:throw new Error(`Unsupported log level: ${e}`)}}debug(...e){H>0||console.debug(pe(0),...e)}info(...e){H>1||console.info(pe(1),...e)}warn(...e){H>2||console.warn(pe(2),...e)}error(...e){H>3||console.error(pe(3),...e)}},Sn={0:"DEBUG",1:"INFO",2:"WARN",3:"ERROR"},In={0:"\x1B[34m",1:"\x1B[32m",2:"\x1B[33m",3:"\x1B[31m"},Pn="\x1B[0m";function pe(o){return`${In[o]}[ADK ${Sn[o]}]:${Pn}`}var m=new Ue;var Ke="adk-",ge="adk_request_credential",Y="adk_request_confirmation",At={handleFunctionCallList:he};function Ve(){return`${Ke}${X()}`}function bt(o){let e=x(o);if(e)for(let t of e)t.id||(t.id=Ve())}function Tt(o){if(o&&o.parts)for(let e of o.parts)e.functionCall&&e.functionCall.id&&e.functionCall.id.startsWith(Ke)&&(e.functionCall.id=void 0),e.functionResponse&&e.functionResponse.id&&e.functionResponse.id.startsWith(Ke)&&(e.functionResponse.id=void 0)}function xt(o,e){let t=new Set;for(let n of o)n.name&&n.name in e&&e[n.name].isLongRunning&&n.id&&t.add(n.id);return t}function Et(o,e){var r;if(!((r=e.actions)!=null&&r.requestedAuthConfigs))return;let t=[],n=new Set;for(let[i,s]of Object.entries(e.actions.requestedAuthConfigs)){let a={name:ge,args:{function_call_id:i,auth_config:s},id:Ve()};n.add(a.id),t.push({functionCall:a})}return T({invocationId:o.invocationId,author:o.agent.name,branch:o.branch,content:{parts:t,role:e.content.role},longRunningToolIds:Array.from(n)})}function Rt({invocationContext:o,functionCallEvent:e,functionResponseEvent:t}){var s,a;if(!((s=t.actions)!=null&&s.requestedToolConfirmations))return;let n=[],r=new Set,i=x(e);for(let[c,l]of Object.entries(t.actions.requestedToolConfirmations)){let f=(a=i.find(d=>d.id===c))!=null?a:void 0;if(!f)continue;let u={name:Y,args:{originalFunctionCall:f,toolConfirmation:l},id:Ve()};r.add(u.id),n.push({functionCall:u})}return T({invocationId:o.invocationId,author:o.agent.name,branch:o.branch,content:{parts:n,role:t.content.role},longRunningToolIds:Array.from(r)})}async function wn(o,e,t){return m.debug(`callToolAsync ${o.name}`),await o.runAsync({args:e,toolContext:t})}async function St({invocationContext:o,functionCallEvent:e,toolsDict:t,beforeToolCallbacks:n,afterToolCallbacks:r,filters:i,toolConfirmationDict:s}){let a=x(e);return await he({invocationContext:o,functionCalls:a,toolsDict:t,beforeToolCallbacks:n,afterToolCallbacks:r,filters:i,toolConfirmationDict:s})}async function he({invocationContext:o,functionCalls:e,toolsDict:t,beforeToolCallbacks:n,afterToolCallbacks:r,filters:i,toolConfirmationDict:s}){var f;let a=[],c=e.filter(u=>!i||u.id&&i.has(u.id));for(let u of c){let d;s&&u.id&&(d=s[u.id]);let{tool:C,toolContext:v}=kn({invocationContext:o,functionCall:u,toolsDict:t,toolConfirmation:d});m.debug(`execute_tool ${C.name}`);let g=(f=u.args)!=null?f:{},p=null,y;if(p=await o.pluginManager.runBeforeToolCallback({tool:C,toolArgs:g,toolContext:v}),p==null){for(let G of n)if(p=await G({tool:C,args:g,context:v}),p)break}if(p==null)try{p=await wn(C,g,v)}catch(G){if(G instanceof Error){let dt=await o.pluginManager.runOnToolErrorCallback({tool:C,toolArgs:g,toolContext:v,error:G});dt?p=dt:y=G.message}else y=G}let R=await o.pluginManager.runAfterToolCallback({tool:C,toolArgs:g,toolContext:v,result:p});if(R==null){for(let G of r)if(R=await G({tool:C,args:g,context:v,response:p}),R)break}if(R!=null&&(p=R),C.isLongRunning&&!p)continue;y?p={error:y}:(typeof p!="object"||p==null)&&(p={result:p});let ft=T({invocationId:o.invocationId,author:o.agent.name,content:(0,yt.createUserContent)({functionResponse:{id:v.functionCallId,name:C.name,response:p}}),actions:v.actions,branch:o.branch});m.debug("traceToolCall",{tool:C.name,args:g,functionResponseEvent:ft.id}),a.push(ft)}if(!a.length)return null;let l=Ln(a);return a.length>1&&(m.debug("execute_tool (merged)"),m.debug("traceMergedToolCalls",{responseEventId:l.id,functionResponseEvent:l.id})),l}function kn({invocationContext:o,functionCall:e,toolsDict:t,toolConfirmation:n}){if(!e.name||!(e.name in t))throw new Error(`Function ${e.name} is not found in the toolsDict.`);let r=new N({invocationContext:o,functionCallId:e.id||void 0,toolConfirmation:n});return{tool:t[e.name],toolContext:r}}function Ln(o){if(!o.length)throw new Error("No function response events provided.");if(o.length===1)return o[0];let e=[];for(let i of o)i.content&&i.content.parts&&e.push(...i.content.parts);let t=o[0],n=o.map(i=>i.actions||{}),r=mt(n);return T({author:t.author,branch:t.branch,content:{role:"user",parts:e},actions:r,timestamp:t.timestamp})}var Ce=class{constructor(){this.queue=[];this.resolveFnFifoQueue=[];this.isClosed=!1}send(e){if(this.isClosed)throw new Error("Cannot send to a closed queue.");this.resolveFnFifoQueue.length>0?this.resolveFnFifoQueue.shift()(e):this.queue.push(e)}async get(){return this.queue.length>0?this.queue.shift():this.isClosed?{close:!0}:new Promise(e=>{this.resolveFnFifoQueue.push(e)})}close(){if(this.isClosed)return;for(this.isClosed=!0;this.resolveFnFifoQueue.length>0&&this.queue.length>0;){let t=this.resolveFnFifoQueue.shift(),n=this.queue.shift();t(n)}let e={close:!0};for(;this.resolveFnFifoQueue.length>0;)this.resolveFnFifoQueue.shift()(e)}sendContent(e){this.send({content:e})}sendRealtime(e){this.send({blob:e})}sendActivityStart(){this.send({activityStart:{}})}sendActivityEnd(){this.send({activityEnd:{}})}async*[Symbol.asyncIterator](){for(;;){let e=await this.get();if(yield e,e.close)break}}};var Xe=require("zod");var ve="0.2.0";var Mn="google-adk",Bn="gl-typescript",On="remote_reasoning_engine",_n="GOOGLE_CLOUD_AGENT_ENGINE_ID";function Nn(){let o=`${Mn}/${ve}`;!De()&&process.env[_n]&&(o=`${o}+${On}`);let e=`${Bn}/${De()?window.navigator.userAgent:process.version}`;return[o,e]}function It(){return Nn()}var F=class{constructor({model:e}){this.model=e}get trackingHeaders(){let t=It().join(" ");return{"x-goog-api-client":t,"user-agent":t}}maybeAppendUserContent(e){var t;e.contents.length===0&&e.contents.push({role:"user",parts:[{text:"Handle the requests as specified in the System Instruction."}]}),((t=e.contents[e.contents.length-1])==null?void 0:t.role)!=="user"&&e.contents.push({role:"user",parts:[{text:"Continue processing previous requests as instructed. Exit or provide a summary if no more outputs are needed."}]})}};F.supportedModels=[];function re(o,e){o.config||(o.config={});let t=e.join(`
|
|
7
|
+
"use strict";var Ne=Object.defineProperty;var Cn=Object.getOwnPropertyDescriptor;var vn=Object.getOwnPropertyNames;var yn=Object.prototype.hasOwnProperty;var An=(o,e)=>{for(var t in e)Ne(o,t,{get:e[t],enumerable:!0})},bn=(o,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of vn(e))!yn.call(o,r)&&r!==t&&Ne(o,r,{get:()=>e[r],enumerable:!(n=Cn(e,r))||n.enumerable});return o};var Tn=o=>bn(Ne({},"__esModule",{value:!0}),o);var yo={};An(yo,{AgentTool:()=>we,BaseAgent:()=>k,BaseLlm:()=>F,BasePlugin:()=>K,BaseSessionService:()=>ce,BaseTool:()=>S,BaseToolset:()=>te,CallbackContext:()=>w,FunctionTool:()=>B,GOOGLE_SEARCH:()=>Xt,GcsArtifactService:()=>ut,Gemini:()=>W,InMemoryArtifactService:()=>J,InMemoryMemoryService:()=>j,InMemoryPolicyEngine:()=>ae,InMemoryRunner:()=>Ie,InMemorySessionService:()=>V,InvocationContext:()=>M,LLMRegistry:()=>Q,LiveRequestQueue:()=>Ce,LlmAgent:()=>b,LogLevel:()=>je,LoggingPlugin:()=>Re,LongRunningFunctionTool:()=>ke,LoopAgent:()=>be,MCPSessionManager:()=>fe,MCPTool:()=>de,MCPToolset:()=>lt,ParallelAgent:()=>Te,PluginManager:()=>ee,PolicyOutcome:()=>st,REQUEST_CONFIRMATION_FUNCTION_CALL_NAME:()=>it,Runner:()=>Z,SecurityPlugin:()=>Se,SequentialAgent:()=>xe,State:()=>h,StreamingMode:()=>Ae,ToolConfirmation:()=>q,ToolContext:()=>N,createEvent:()=>T,createEventActions:()=>_,createSession:()=>le,functionsExportedForTestingOnly:()=>At,getAskUserConfirmationFunctionCalls:()=>Kt,getFunctionCalls:()=>x,getFunctionResponses:()=>I,getGcpExporters:()=>Co,getGcpResource:()=>vo,hasTrailingCodeExecutionResult:()=>Fe,isFinalResponse:()=>z,maybeSetOtelProviders:()=>uo,setLogLevel:()=>vt,stringifyContent:()=>gt,version:()=>ve,zodObjectToSchema:()=>ie});module.exports=Tn(yo);var qe=require("@opentelemetry/api");function _(o={}){return{stateDelta:{},artifactDelta:{},requestedAuthConfigs:{},requestedToolConfirmations:{},...o}}function mt(o,e){let t=_();e&&Object.assign(t,e);for(let n of o)n&&(n.stateDelta&&Object.assign(t.stateDelta,n.stateDelta),n.artifactDelta&&Object.assign(t.artifactDelta,n.artifactDelta),n.requestedAuthConfigs&&Object.assign(t.requestedAuthConfigs,n.requestedAuthConfigs),n.requestedToolConfirmations&&Object.assign(t.requestedToolConfirmations,n.requestedToolConfirmations),n.skipSummarization!==void 0&&(t.skipSummarization=n.skipSummarization),n.transferToAgent!==void 0&&(t.transferToAgent=n.transferToAgent),n.escalate!==void 0&&(t.escalate=n.escalate));return t}function T(o={}){return{...o,id:o.id||$e(),invocationId:o.invocationId||"",author:o.author,actions:o.actions||_(),longRunningToolIds:o.longRunningToolIds||[],branch:o.branch,timestamp:o.timestamp||Date.now()}}function z(o){return o.actions.skipSummarization||o.longRunningToolIds&&o.longRunningToolIds.length>0?!0:x(o).length===0&&I(o).length===0&&!o.partial&&!Fe(o)}function x(o){let e=[];if(o.content&&o.content.parts)for(let t of o.content.parts)t.functionCall&&e.push(t.functionCall);return e}function I(o){let e=[];if(o.content&&o.content.parts)for(let t of o.content.parts)t.functionResponse&&e.push(t.functionResponse);return e}function Fe(o){var e;return o.content&&((e=o.content.parts)!=null&&e.length)?o.content.parts[o.content.parts.length-1].codeExecutionResult!==void 0:!1}function gt(o){var e;return(e=o.content)!=null&&e.parts?o.content.parts.map(t=>{var n;return(n=t.text)!=null?n:""}).join(""):""}var pt="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";function $e(){let o="";for(let e=0;e<8;e++)o+=pt[Math.floor(Math.random()*pt.length)];return o}var h=class{constructor(e,t){this.value=e;this.delta=t}get(e,t){return e in this.delta?this.delta[e]:e in this.value?this.value[e]:t}set(e,t){this.value[e]=t,this.delta[e]=t}has(e){return e in this.value||e in this.delta}hasDelta(){return Object.keys(this.delta).length>0}update(e){this.delta={...this.delta,...e},this.value={...this.value,...e}}toRecord(){return{...this.value,...this.delta}}};h.APP_PREFIX="app:",h.USER_PREFIX="user:",h.TEMP_PREFIX="temp:";var P=class{constructor(e){this.invocationContext=e}get userContent(){return this.invocationContext.userContent}get invocationId(){return this.invocationContext.invocationId}get agentName(){return this.invocationContext.agent.name}get state(){return new h(this.invocationContext.session.state,{})}};var w=class extends P{constructor({invocationContext:e,eventActions:t}){super(e),this.eventActions=t||_(),this._state=new h(e.session.state,this.eventActions.stateDelta)}get state(){return this._state}loadArtifact(e,t){if(!this.invocationContext.artifactService)throw new Error("Artifact service is not initialized.");return this.invocationContext.artifactService.loadArtifact({appName:this.invocationContext.appName,userId:this.invocationContext.userId,sessionId:this.invocationContext.session.id,filename:e,version:t})}async saveArtifact(e,t){if(!this.invocationContext.artifactService)throw new Error("Artifact service is not initialized.");let n=await this.invocationContext.artifactService.saveArtifact({appName:this.invocationContext.appName,userId:this.invocationContext.userId,sessionId:this.invocationContext.session.id,filename:e,artifact:t});return this.eventActions.artifactDelta[e]=n,n}};function De(){return typeof window<"u"}var me="xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx";function X(){let o="";for(let e=0;e<me.length;e++){let t=Math.random()*16|0;me[e]==="x"?o+=t.toString(16):me[e]==="y"?o+=(t&3|8).toString(16):o+=me[e]}return o}var Ge=class{constructor(){this.numberOfLlmCalls=0}incrementAndEnforceLlmCallsLimit(e){if(this.numberOfLlmCalls++,e&&e.maxLlmCalls>0&&this.numberOfLlmCalls>e.maxLlmCalls)throw new Error(`Max number of llm calls limit of ${e.maxLlmCalls} exceeded`)}},M=class{constructor(e){this.invocationCostManager=new Ge;this.artifactService=e.artifactService,this.sessionService=e.sessionService,this.memoryService=e.memoryService,this.invocationId=e.invocationId,this.branch=e.branch,this.agent=e.agent,this.userContent=e.userContent,this.session=e.session,this.endInvocation=e.endInvocation||!1,this.transcriptionCache=e.transcriptionCache,this.runConfig=e.runConfig,this.liveRequestQueue=e.liveRequestQueue,this.activeStreamingTools=e.activeStreamingTools,this.pluginManager=e.pluginManager}get appName(){return this.session.appName}get userId(){return this.session.userId}incrementLlmCallCount(){this.invocationCostManager.incrementAndEnforceLlmCallsLimit(this.runConfig)}};function ht(){return`e-${X()}`}var k=class{constructor(e){this.name=xn(e.name),this.description=e.description,this.parentAgent=e.parentAgent,this.subAgents=e.subAgents||[],this.rootAgent=Rn(this),this.beforeAgentCallback=Ct(e.beforeAgentCallback),this.afterAgentCallback=Ct(e.afterAgentCallback),this.setParentAgentForSubAgents()}async*runAsync(e){let t=qe.trace.getTracer("gcp.vertex.agent").startSpan(`agent_run [${this.name}]`);try{let n=this.createInvocationContext(e),r=await this.handleBeforeAgentCallback(n);if(r&&(yield r),n.endInvocation)return;for await(let s of this.runAsyncImpl(n))yield s;if(n.endInvocation)return;let i=await this.handleAfterAgentCallback(n);i&&(yield i)}finally{t.end()}}async*runLive(e){let t=qe.trace.getTracer("gcp.vertex.agent").startSpan(`agent_run [${this.name}]`);try{throw new Error("Live mode is not implemented yet.")}finally{t.end()}}findAgent(e){return this.name===e?this:this.findSubAgent(e)}findSubAgent(e){for(let t of this.subAgents){let n=t.findAgent(e);if(n)return n}}createInvocationContext(e){return new M({...e,agent:this})}async handleBeforeAgentCallback(e){if(this.beforeAgentCallback.length===0)return;let t=new w({invocationContext:e});for(let n of this.beforeAgentCallback){let r=await n(t);if(r)return e.endInvocation=!0,T({invocationId:e.invocationId,author:this.name,branch:e.branch,content:r,actions:t.eventActions})}if(t.state.hasDelta())return T({invocationId:e.invocationId,author:this.name,branch:e.branch,actions:t.eventActions})}async handleAfterAgentCallback(e){if(this.afterAgentCallback.length===0)return;let t=new w({invocationContext:e});for(let n of this.afterAgentCallback){let r=await n(t);if(r)return T({invocationId:e.invocationId,author:this.name,branch:e.branch,content:r,actions:t.eventActions})}if(t.state.hasDelta())return T({invocationId:e.invocationId,author:this.name,branch:e.branch,actions:t.eventActions})}setParentAgentForSubAgents(){for(let e of this.subAgents){if(e.parentAgent)throw new Error(`Agent "${e.name}" already has a parent agent, current parent: "${e.parentAgent.name}", trying to add: "${this.name}"`);e.parentAgent=this}}};function xn(o){if(!En(o))throw new Error(`Found invalid agent name: "${o}". Agent name must be a valid identifier. It should start with a letter (a-z, A-Z) or an underscore (_), and can only contain letters, digits (0-9), and underscores.`);if(o==="user")throw new Error("Agent name cannot be 'user'. 'user' is reserved for end-user's input.");return o}function En(o){return/^[\p{ID_Start}$_][\p{ID_Continue}$_]*$/u.test(o)}function Rn(o){for(;o.parentAgent;)o=o.parentAgent;return o}function Ct(o){return o?Array.isArray(o)?o:[o]:[]}var yt=require("@google/genai");var oe=class{constructor(e){this.authConfig=e}getAuthResponse(e){let t="temp:"+this.authConfig.credentialKey;return e.get(t)}generateAuthRequest(){var t,n;let e=this.authConfig.authScheme.type;if(!["oauth2","openIdConnect"].includes(e))return this.authConfig;if((n=(t=this.authConfig.exchangedAuthCredential)==null?void 0:t.oauth2)!=null&&n.authUri)return this.authConfig;if(!this.authConfig.rawAuthCredential)throw new Error(`Auth Scheme ${e} requires authCredential.`);if(!this.authConfig.rawAuthCredential.oauth2)throw new Error(`Auth Scheme ${e} requires oauth2 in authCredential.`);if(this.authConfig.rawAuthCredential.oauth2.authUri)return{credentialKey:this.authConfig.credentialKey,authScheme:this.authConfig.authScheme,rawAuthCredential:this.authConfig.rawAuthCredential,exchangedAuthCredential:this.authConfig.rawAuthCredential};if(!this.authConfig.rawAuthCredential.oauth2.clientId||!this.authConfig.rawAuthCredential.oauth2.clientSecret)throw new Error(`Auth Scheme ${e} requires both clientId and clientSecret in authCredential.oauth2.`);return{credentialKey:this.authConfig.credentialKey,authScheme:this.authConfig.authScheme,rawAuthCredential:this.authConfig.rawAuthCredential,exchangedAuthCredential:this.generateAuthUri()}}generateAuthUri(){return this.authConfig.rawAuthCredential}};var q=class{constructor({hint:e,confirmed:t,payload:n}){this.hint=e!=null?e:"",this.confirmed=t,this.payload=n}};var N=class extends w{constructor({invocationContext:e,eventActions:t,functionCallId:n,toolConfirmation:r}){super({invocationContext:e,eventActions:t}),this.functionCallId=n,this.toolConfirmation=r}get actions(){return this.eventActions}requestCredential(e){if(!this.functionCallId)throw new Error("functionCallId is not set.");let t=new oe(e);this.eventActions.requestedAuthConfigs[this.functionCallId]=t.generateAuthRequest()}getAuthResponse(e){return new oe(e).getAuthResponse(this.state)}listArtifacts(){if(!this.invocationContext.artifactService)throw new Error("Artifact service is not initialized.");return this.invocationContext.artifactService.listArtifactKeys({appName:this.invocationContext.session.appName,userId:this.invocationContext.session.userId,sessionId:this.invocationContext.session.id})}searchMemory(e){if(!this.invocationContext.memoryService)throw new Error("Memory service is not initialized.");return this.invocationContext.memoryService.searchMemory({appName:this.invocationContext.session.appName,userId:this.invocationContext.session.userId,query:e})}requestConfirmation({hint:e,payload:t}){if(!this.functionCallId)throw new Error("functionCallId is not set.");this.eventActions.requestedToolConfirmations[this.functionCallId]=new q({hint:e,confirmed:!1,payload:t})}};var je=(r=>(r[r.DEBUG=0]="DEBUG",r[r.INFO=1]="INFO",r[r.WARN=2]="WARN",r[r.ERROR=3]="ERROR",r))(je||{}),H=1;function vt(o){H=o}var Ue=class{log(e,...t){if(!(e<H))switch(e){case 0:this.debug(...t);break;case 1:this.info(...t);break;case 2:this.warn(...t);break;case 3:this.error(...t);break;default:throw new Error(`Unsupported log level: ${e}`)}}debug(...e){H>0||console.debug(pe(0),...e)}info(...e){H>1||console.info(pe(1),...e)}warn(...e){H>2||console.warn(pe(2),...e)}error(...e){H>3||console.error(pe(3),...e)}},Sn={0:"DEBUG",1:"INFO",2:"WARN",3:"ERROR"},In={0:"\x1B[34m",1:"\x1B[32m",2:"\x1B[33m",3:"\x1B[31m"},Pn="\x1B[0m";function pe(o){return`${In[o]}[ADK ${Sn[o]}]:${Pn}`}var m=new Ue;var Ke="adk-",ge="adk_request_credential",Y="adk_request_confirmation",At={handleFunctionCallList:he};function Ve(){return`${Ke}${X()}`}function bt(o){let e=x(o);if(e)for(let t of e)t.id||(t.id=Ve())}function Tt(o){if(o&&o.parts)for(let e of o.parts)e.functionCall&&e.functionCall.id&&e.functionCall.id.startsWith(Ke)&&(e.functionCall.id=void 0),e.functionResponse&&e.functionResponse.id&&e.functionResponse.id.startsWith(Ke)&&(e.functionResponse.id=void 0)}function xt(o,e){let t=new Set;for(let n of o)n.name&&n.name in e&&e[n.name].isLongRunning&&n.id&&t.add(n.id);return t}function Et(o,e){var r;if(!((r=e.actions)!=null&&r.requestedAuthConfigs))return;let t=[],n=new Set;for(let[i,s]of Object.entries(e.actions.requestedAuthConfigs)){let a={name:ge,args:{function_call_id:i,auth_config:s},id:Ve()};n.add(a.id),t.push({functionCall:a})}return T({invocationId:o.invocationId,author:o.agent.name,branch:o.branch,content:{parts:t,role:e.content.role},longRunningToolIds:Array.from(n)})}function Rt({invocationContext:o,functionCallEvent:e,functionResponseEvent:t}){var s,a;if(!((s=t.actions)!=null&&s.requestedToolConfirmations))return;let n=[],r=new Set,i=x(e);for(let[c,l]of Object.entries(t.actions.requestedToolConfirmations)){let f=(a=i.find(d=>d.id===c))!=null?a:void 0;if(!f)continue;let u={name:Y,args:{originalFunctionCall:f,toolConfirmation:l},id:Ve()};r.add(u.id),n.push({functionCall:u})}return T({invocationId:o.invocationId,author:o.agent.name,branch:o.branch,content:{parts:n,role:t.content.role},longRunningToolIds:Array.from(r)})}async function wn(o,e,t){return m.debug(`callToolAsync ${o.name}`),await o.runAsync({args:e,toolContext:t})}async function St({invocationContext:o,functionCallEvent:e,toolsDict:t,beforeToolCallbacks:n,afterToolCallbacks:r,filters:i,toolConfirmationDict:s}){let a=x(e);return await he({invocationContext:o,functionCalls:a,toolsDict:t,beforeToolCallbacks:n,afterToolCallbacks:r,filters:i,toolConfirmationDict:s})}async function he({invocationContext:o,functionCalls:e,toolsDict:t,beforeToolCallbacks:n,afterToolCallbacks:r,filters:i,toolConfirmationDict:s}){var f;let a=[],c=e.filter(u=>!i||u.id&&i.has(u.id));for(let u of c){let d;s&&u.id&&(d=s[u.id]);let{tool:C,toolContext:v}=kn({invocationContext:o,functionCall:u,toolsDict:t,toolConfirmation:d});m.debug(`execute_tool ${C.name}`);let g=(f=u.args)!=null?f:{},p=null,y;if(p=await o.pluginManager.runBeforeToolCallback({tool:C,toolArgs:g,toolContext:v}),p==null){for(let G of n)if(p=await G({tool:C,args:g,context:v}),p)break}if(p==null)try{p=await wn(C,g,v)}catch(G){if(G instanceof Error){let dt=await o.pluginManager.runOnToolErrorCallback({tool:C,toolArgs:g,toolContext:v,error:G});dt?p=dt:y=G.message}else y=G}let R=await o.pluginManager.runAfterToolCallback({tool:C,toolArgs:g,toolContext:v,result:p});if(R==null){for(let G of r)if(R=await G({tool:C,args:g,context:v,response:p}),R)break}if(R!=null&&(p=R),C.isLongRunning&&!p)continue;y?p={error:y}:(typeof p!="object"||p==null)&&(p={result:p});let ft=T({invocationId:o.invocationId,author:o.agent.name,content:(0,yt.createUserContent)({functionResponse:{id:v.functionCallId,name:C.name,response:p}}),actions:v.actions,branch:o.branch});m.debug("traceToolCall",{tool:C.name,args:g,functionResponseEvent:ft.id}),a.push(ft)}if(!a.length)return null;let l=Ln(a);return a.length>1&&(m.debug("execute_tool (merged)"),m.debug("traceMergedToolCalls",{responseEventId:l.id,functionResponseEvent:l.id})),l}function kn({invocationContext:o,functionCall:e,toolsDict:t,toolConfirmation:n}){if(!e.name||!(e.name in t))throw new Error(`Function ${e.name} is not found in the toolsDict.`);let r=new N({invocationContext:o,functionCallId:e.id||void 0,toolConfirmation:n});return{tool:t[e.name],toolContext:r}}function Ln(o){if(!o.length)throw new Error("No function response events provided.");if(o.length===1)return o[0];let e=[];for(let i of o)i.content&&i.content.parts&&e.push(...i.content.parts);let t=o[0],n=o.map(i=>i.actions||{}),r=mt(n);return T({author:t.author,branch:t.branch,content:{role:"user",parts:e},actions:r,timestamp:t.timestamp})}var Ce=class{constructor(){this.queue=[];this.resolveFnFifoQueue=[];this.isClosed=!1}send(e){if(this.isClosed)throw new Error("Cannot send to a closed queue.");this.resolveFnFifoQueue.length>0?this.resolveFnFifoQueue.shift()(e):this.queue.push(e)}async get(){return this.queue.length>0?this.queue.shift():this.isClosed?{close:!0}:new Promise(e=>{this.resolveFnFifoQueue.push(e)})}close(){if(this.isClosed)return;for(this.isClosed=!0;this.resolveFnFifoQueue.length>0&&this.queue.length>0;){let t=this.resolveFnFifoQueue.shift(),n=this.queue.shift();t(n)}let e={close:!0};for(;this.resolveFnFifoQueue.length>0;)this.resolveFnFifoQueue.shift()(e)}sendContent(e){this.send({content:e})}sendRealtime(e){this.send({blob:e})}sendActivityStart(){this.send({activityStart:{}})}sendActivityEnd(){this.send({activityEnd:{}})}async*[Symbol.asyncIterator](){for(;;){let e=await this.get();if(yield e,e.close)break}}};var Xe=require("zod");var ve="0.2.1";var Mn="google-adk",Bn="gl-typescript",On="remote_reasoning_engine",_n="GOOGLE_CLOUD_AGENT_ENGINE_ID";function Nn(){let o=`${Mn}/${ve}`;!De()&&process.env[_n]&&(o=`${o}+${On}`);let e=`${Bn}/${De()?window.navigator.userAgent:process.version}`;return[o,e]}function It(){return Nn()}var F=class{constructor({model:e}){this.model=e}get trackingHeaders(){let t=It().join(" ");return{"x-goog-api-client":t,"user-agent":t}}maybeAppendUserContent(e){var t;e.contents.length===0&&e.contents.push({role:"user",parts:[{text:"Handle the requests as specified in the System Instruction."}]}),((t=e.contents[e.contents.length-1])==null?void 0:t.role)!=="user"&&e.contents.push({role:"user",parts:[{text:"Continue processing previous requests as instructed. Exit or provide a summary if no more outputs are needed."}]})}};F.supportedModels=[];function re(o,e){o.config||(o.config={});let t=e.join(`
|
|
8
8
|
|
|
9
9
|
`);o.config.systemInstruction?o.config.systemInstruction+=`
|
|
10
10
|
|