adk-typescript
Version:
TypeScript port of Google's Agent Development Kit (ADK)
92 lines (91 loc) • 3.49 kB
JavaScript
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.CallbackContext = void 0;
const ReadonlyContext_1 = require("./ReadonlyContext");
const EventActions_1 = require("../events/EventActions");
const State_1 = require("../sessions/State");
/**
* Callback context for agent invocations.
* Provides mutable access to the agent's state and context.
*/
class CallbackContext extends ReadonlyContext_1.ReadonlyContext {
constructor(invocationContext, eventActions) {
super(invocationContext);
this.eventActions = eventActions || new EventActions_1.EventActions();
// Merge the session state and event actions delta into a new State instance
const baseState = invocationContext.session.state.getAll ? invocationContext.session.state.getAll() : {};
const delta = this.eventActions.stateDelta || {};
this.mutableState = new State_1.State({
...baseState,
...delta
});
}
/**
* The delta-aware state of the current session.
*
* For any state change, you can mutate this object directly,
* e.g. `ctx.state['foo'] = 'bar'`
*/
get state() {
return this.mutableState;
}
/**
* The user content that started this invocation. READONLY field.
*/
get userContent() {
return this.invocationContext.userContent;
}
/**
* Loads an artifact attached to the current session.
*
* @param filename The filename of the artifact.
* @param version The version of the artifact. If undefined, the latest version will be returned.
* @returns The artifact, or undefined if not found.
*/
loadArtifact(filename, version) {
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,
version
});
}
/**
* Saves an artifact and records it as delta for the current session.
*
* @param filename The filename of the artifact.
* @param artifact The artifact to save.
* @returns The version of the artifact.
*/
saveArtifact(filename, artifact) {
if (!this.invocationContext.artifactService) {
throw new Error("Artifact service is not initialized.");
}
const version = this.invocationContext.artifactService.saveArtifact({
appName: this.invocationContext.appName,
userId: this.invocationContext.userId,
sessionId: this.invocationContext.session.id,
filename,
artifact
});
// Handle both synchronous and asynchronous cases
if (version instanceof Promise) {
// If it's a Promise, we need to return a new Promise that resolves
// after we've updated the artifact delta
return version.then(v => {
this.eventActions.artifactDelta[filename] = v;
return v;
});
}
else {
// If it's synchronous, we can update the artifact delta directly
this.eventActions.artifactDelta[filename] = version;
return version;
}
}
}
exports.CallbackContext = CallbackContext;