@artinet/sdk
Version:
A TypeScript SDK for building collaborative AI agents.
103 lines (102 loc) • 3.57 kB
JavaScript
import { A2A } from "../../types/index.js";
import { Stream } from "./streams.js";
import { createBaseContext, createContext, } from "./factory/context.js";
import { v4 } from "uuid";
import { getCurrentTimestamp } from "../../utils/index.js";
import { handleUpdate } from "./handlers/update.js";
import { Manager } from "../core/manager.js";
import { logger } from "../../config/index.js";
export class Cancellations extends Manager {
constructor(cancellations = new Map()) {
super(cancellations, false);
}
}
export class Connections extends Manager {
constructor(connections = new Map()) {
super(connections, false);
}
}
export class Contexts extends Manager {
constructor(contexts = new Map()) {
super(contexts, true);
}
async create(params) {
if (await this.has(params.contextId)) {
logger.warn("Contexts[create]: context already exists", {
contextId: params.contextId,
});
return (await this.get(params.contextId));
}
logger.info(`Contexts[create]: creating context`, {
contextId: params.contextId,
});
logger.debug(`Contexts[create]: params`, { params });
const baseContext = createBaseContext(params);
/**intentional deep copy*/
const context = {
...createContext({
baseContext: baseContext,
taskId: params.task.id,
messenger: params.messenger,
references: params.references,
extensions: params.extensions,
userId: params.userId,
}),
};
logger.debug(`Contexts[create]: context created`, context.contextId);
await this.set(context.contextId, context);
return context;
}
}
export class Streams extends Manager {
constructor(streams = new Map()) {
super(streams, true);
}
async create({ contextId, context, updates, }) {
if (await this.has(contextId)) {
throw new Error("Stream already exists");
}
await this.set(contextId, new Stream(contextId, context, updates));
return (await this.get(contextId));
}
}
export class Tasks extends Manager {
constructor(tasks = new Map()) {
super(tasks, true);
}
async update(context, update) {
logger.info(`Tasks[update]: updating task`, { taskId: context.taskId });
logger.debug(`Tasks[update]: update`, { update });
logger.debug(`Tasks[update]: context`, { context });
logger.debug(`Tasks[update]: context task`, {
task: await context.getTask(),
});
const task = await handleUpdate({
context,
task: await context.getTask(),
update,
});
logger.debug(`Tasks[update]: task`, task);
await this.set(task.id, task);
return task;
}
async create(params) {
if (params.id && (await this.has(params.id))) {
return (await this.get(params.id));
}
logger.info(`Tasks[create]: creating task`, { id: params.id });
const task = {
...params,
id: params.id ?? v4(),
contextId: params.contextId ?? v4(),
kind: "task",
status: {
state: A2A.TaskState.submitted,
timestamp: getCurrentTimestamp(),
},
};
logger.debug(`Tasks[create]:`, { taskId: task.id });
await this.set(task.id, task);
return task;
}
}