"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var task_group_exports = {};
__export(task_group_exports, {
  TaskGroup: () => TaskGroup
});
module.exports = __toCommonJS(task_group_exports);
var import_zod = require("zod");
var import_llm = require("../llm/index.cjs");
var import_utils = require("../utils.cjs");
var import_agent = require("../voice/agent.cjs");
class OutOfScopeError extends import_llm.ToolError {
  targetTaskIds;
  constructor(targetTaskIds) {
    super("out_of_scope");
    this.targetTaskIds = targetTaskIds;
  }
}
class TaskGroup extends import_agent.AgentTask {
  _summarizeChatCtx;
  _returnExceptions;
  _visitedTasks = /* @__PURE__ */ new Set();
  _registeredFactories = /* @__PURE__ */ new Map();
  _taskCompletedCallback;
  _currentTask;
  constructor(options = {}) {
    const {
      summarizeChatCtx = true,
      returnExceptions = false,
      chatCtx,
      onTaskCompleted,
      preserveFunctionCallHistory = false
    } = options;
    super({ instructions: "*empty*", chatCtx, preserveFunctionCallHistory });
    this._summarizeChatCtx = summarizeChatCtx;
    this._returnExceptions = returnExceptions;
    this._taskCompletedCallback = onTaskCompleted;
  }
  add(task, { id, description }) {
    this._registeredFactories.set(id, { taskFactory: task, id, description });
    return this;
  }
  async onEnter() {
    const taskStack = [...this._registeredFactories.keys()];
    const taskResults = {};
    while (taskStack.length > 0) {
      const taskId = taskStack.shift();
      const factoryInfo = this._registeredFactories.get(taskId);
      this._currentTask = factoryInfo.taskFactory();
      const sharedChatCtx = this._chatCtx.copy();
      await this._currentTask.updateChatCtx(sharedChatCtx);
      const outOfScopeTool = this.buildOutOfScopeTool(taskId);
      if (outOfScopeTool) {
        await this._currentTask.updateTools([...this._currentTask.toolCtx.tools, outOfScopeTool]);
      }
      try {
        this._visitedTasks.add(taskId);
        const res = await this._currentTask.run();
        this._chatCtx.merge(this._currentTask.chatCtx.copy(), {
          excludeInstructions: true
        });
        taskResults[taskId] = res;
        if (this._taskCompletedCallback) {
          await this._taskCompletedCallback({
            agentTask: this._currentTask,
            taskId,
            result: res
          });
        }
      } catch (e) {
        if (e instanceof OutOfScopeError) {
          taskStack.unshift(taskId);
          for (let i = e.targetTaskIds.length - 1; i >= 0; i--) {
            taskStack.unshift(e.targetTaskIds[i]);
          }
          continue;
        }
        if (this._returnExceptions) {
          taskResults[taskId] = e;
          continue;
        } else {
          this.complete((0, import_utils.asError)(e));
          return;
        }
      }
    }
    try {
      if (this._summarizeChatCtx) {
        const sessionLlm = this.session.llm;
        if (!(sessionLlm instanceof import_llm.LLM)) {
          throw new Error("summarizeChatCtx requires a standard LLM on the session");
        }
        const ctxToSummarize = this._chatCtx.copy({
          excludeInstructions: false,
          excludeFunctionCall: false,
          excludeEmptyMessage: false,
          excludeHandoff: false
        });
        const summarizedChatCtx = await ctxToSummarize._summarize(sessionLlm, {
          keepLastTurns: 0
        });
        await this.updateChatCtx(summarizedChatCtx);
      }
    } catch (e) {
      this.complete(new Error(`failed to summarize the chat_ctx: ${e}`));
      return;
    }
    this.complete({ taskResults });
  }
  buildOutOfScopeTool(activeTaskId) {
    if (this._visitedTasks.size === 0) {
      return void 0;
    }
    const regressionTaskIds = new Set(this._visitedTasks);
    regressionTaskIds.delete(activeTaskId);
    if (regressionTaskIds.size === 0) {
      return void 0;
    }
    const taskRepr = {};
    for (const [id, info] of this._registeredFactories) {
      if (regressionTaskIds.has(id)) {
        taskRepr[id] = info.description;
      }
    }
    const taskIdValues = [...regressionTaskIds];
    const description = `Call to regress to other tasks according to what the user requested to modify, return the corresponding task ids. For example, if the user wants to change their email and there is a task with id "email_task" with a description of "Collect the user's email", return the id ("get_email_task"). If the user requests to regress to multiple tasks, such as changing their phone number and email, return both task ids in the order they were requested. The following are the IDs and their corresponding task description. ${JSON.stringify(taskRepr)}`;
    const currentTask = this._currentTask;
    const registeredFactories = this._registeredFactories;
    const visitedTasks = this._visitedTasks;
    return (0, import_llm.tool)({
      name: "out_of_scope",
      description,
      flags: import_llm.ToolFlag.IGNORE_ON_ENTER,
      parameters: import_zod.z.object({
        task_ids: import_zod.z.array(import_zod.z.enum(taskIdValues)).describe("The IDs of the tasks requested")
      }),
      execute: async ({ task_ids }) => {
        for (const tid of task_ids) {
          if (!registeredFactories.has(tid) || !visitedTasks.has(tid)) {
            throw new import_llm.ToolError(`Unable to regress, invalid task id ${tid}`);
          }
        }
        if (currentTask && !currentTask.done) {
          currentTask.complete(new OutOfScopeError(task_ids));
        }
      }
    });
  }
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  TaskGroup
});
//# sourceMappingURL=task_group.cjs.map