UNPKG

@artinet/sdk

Version:

A TypeScript SDK for building collaborative AI agents.

80 lines (79 loc) 2.51 kB
import { EventEmitter } from "eventemitter3"; import { INTERNAL_ERROR } from "../../utils/index.js"; import { logger } from "../../config/index.js"; import { createStateMachine } from "./factory/state-machine.js"; export class StateMachine extends EventEmitter { _contextId; _consumer; _currentTask; onStart = async (context) => { if (this.consumer.onStart) { this.currentTask = await this.consumer.onStart(context); } this.emit("start", context.messages, this.currentTask); return this.currentTask; }; onCancel = async (update) => { if (this.consumer.onCancel) { await this.consumer.onCancel(update, this.currentTask); } this.emit("cancel", update); }; onUpdate = async (update) => { if (this.consumer.onUpdate) { this.currentTask = await this.consumer.onUpdate(update, this.currentTask); } else { logger.warn(`onUpdate[${this.contextId}]:`, "onUpdate callback not found"); this.currentTask = update; } this.emit("update", this.currentTask, update); return this.currentTask; }; onError = async (error) => { if (this.consumer.onError) { await this.consumer.onError(error, this.currentTask); } //TODO: no longer necessary with eventemitter3 if (!this.listenerCount("error")) return; this.emit("error", error, this.currentTask); }; onComplete = async () => { if (this.consumer.onComplete) { await this.consumer.onComplete(this.currentTask); } this.emit("complete", this.currentTask); }; constructor(_contextId, _consumer, _currentTask) { super(); this._contextId = _contextId; this._consumer = _consumer; this._currentTask = _currentTask; } get currentTask() { if (!this._currentTask) { throw INTERNAL_ERROR({ error: { message: "state machine is not initialized" }, }); } return this._currentTask; } set currentTask(task) { this._currentTask = task; } get consumer() { return this._consumer; } get contextId() { return this._contextId; } static create(contextId, service, task, overrides) { return createStateMachine({ contextId, service, task, overrides, }); } }