import { print, printJSON, parseJSON, input, sleep, round, read, write, readImage, notify, range, mostCommon, keys, values, entries, emit, callback } from "agency-lang/stdlib/index.js";
import { fileURLToPath } from "url";
import __process from "process";
import { z } from "agency-lang/zod";
import { goToNode, nanoid } from "agency-lang";
import path from "path";
import {
  RuntimeContext,
  ThreadStore,
  Runner,
  setupNode,
  runNode,
  runPrompt,
  callHook,
  checkpoint as __checkpoint_impl,
  getCheckpoint as __getCheckpoint_impl,
  restore as __restore_impl,
  _run as __runtime_run_impl,
  interrupt,
  isInterrupt,
  hasInterrupts,
  isDebugger,
  respondToInterrupts as _respondToInterrupts,
  rewindFrom as _rewindFrom,
  RestoreSignal,
  GuardExceededError,
  __registerGlobalsInit,
  failure,
  AgencyFunction as __AgencyFunction,
  __call,
  __threads,
  __stateStack,
  getRuntimeContext,
  agencyStore,
  functionRefReviver as __functionRefReviver,
  DeterministicClient as __DeterministicClient,
  createLogger as __createLogger
} from "agency-lang/runtime";
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const __cwd = __process.cwd();
const getDirname = () => __dirname;
const __globalCtx = new RuntimeContext({
  statelogConfig: {
    host: "https://statelog.adit.io",
    apiKey: __process.env["STATELOG_API_KEY"] || "",
    projectId: "agency-lang",
    debugMode: false,
    observability: true,
    logFile: "statelog.log"
  },
  smoltalkDefaults: {
    openAiApiKey: __process.env["OPENAI_API_KEY"] || "",
    googleApiKey: __process.env["GEMINI_API_KEY"] || "",
    model: "gpt-4o-mini",
    logLevel: "warn",
    statelog: {
      host: "https://statelog.adit.io",
      projectId: "smoltalk",
      apiKey: __process.env["STATELOG_SMOLTALK_API_KEY"] || "",
      traceId: nanoid()
    }
  },
  dirname: __dirname,
  logLevel: "info",
  traceConfig: {
    program: "dist/lib/agents/agency-agent/prompts/codeSample.agency"
  }
});
const graph = __globalCtx.graph;
function approve(value) {
  return { type: "approve", value };
}
function reject(value) {
  return { type: "reject", value };
}
function propagate() {
  return { type: "propagate" };
}
const respondToInterrupts = (interrupts, responses, opts) => _respondToInterrupts({ ctx: __globalCtx, interrupts, responses, overrides: opts?.overrides, metadata: opts?.metadata, registerTopLevelCallbacks: __registerTopLevelCallbacks, moduleDir: __dirname });
const rewindFrom = (checkpoint2, overrides, opts) => _rewindFrom({ ctx: __globalCtx, checkpoint: checkpoint2, overrides, metadata: opts?.metadata, registerTopLevelCallbacks: __registerTopLevelCallbacks, moduleDir: __dirname });
const __setDebugger = (dbg) => {
  __globalCtx.debuggerState = dbg;
};
const __setTraceFile = (filePath) => {
  __globalCtx.traceConfig.traceFile = filePath;
};
const __setLLMClient = (client) => {
  __globalCtx.setLLMClient(client);
};
const __getCheckpoints = () => __globalCtx.checkpoints;
if (__process.env.AGENCY_LLM_MOCKS) {
  __globalCtx.setLLMClient(
    new __DeterministicClient(JSON.parse(__process.env.AGENCY_LLM_MOCKS))
  );
}
const __toolRegistry = __functionRefReviver.registry ??= {};
function __registerTool(value, _aliasName) {
  if (__AgencyFunction.isAgencyFunction(value)) {
    __toolRegistry[`${value.module}:${value.name}`] = value;
  }
}
const checkpoint = __AgencyFunction.create({ name: "checkpoint", module: "__runtime", fn: __checkpoint_impl, params: [], toolDefinition: null }, __toolRegistry);
const getCheckpoint = __AgencyFunction.create({ name: "getCheckpoint", module: "__runtime", fn: __getCheckpoint_impl, params: [{ name: "checkpointId", hasDefault: false, defaultValue: void 0, variadic: false }], toolDefinition: null }, __toolRegistry);
const restore = __AgencyFunction.create({ name: "restore", module: "__runtime", fn: __restore_impl, params: [{ name: "checkpointIdOrCheckpoint", hasDefault: false, defaultValue: void 0, variadic: false }, { name: "options", hasDefault: false, defaultValue: void 0, variadic: false }], toolDefinition: null }, __toolRegistry);
const _run = __AgencyFunction.create({ name: "_run", module: "__runtime", fn: __runtime_run_impl, params: [{ name: "compiled", hasDefault: false, defaultValue: void 0, variadic: false }, { name: "node", hasDefault: false, defaultValue: void 0, variadic: false }, { name: "args", hasDefault: false, defaultValue: void 0, variadic: false }, { name: "wallClock", hasDefault: false, defaultValue: void 0, variadic: false }, { name: "memory", hasDefault: false, defaultValue: void 0, variadic: false }, { name: "ipcPayload", hasDefault: false, defaultValue: void 0, variadic: false }, { name: "stdout", hasDefault: false, defaultValue: void 0, variadic: false }], toolDefinition: null }, __toolRegistry);
function setLLMClient(client) {
  __globalCtx.setLLMClient(client);
}
function registerTools(tools) {
  for (const tool of tools) {
    if (__AgencyFunction.isAgencyFunction(tool)) {
      __toolRegistry[`${tool.module}:${tool.name}`] = tool;
    }
  }
}
__registerTool(print);
__registerTool(printJSON);
__registerTool(parseJSON);
__registerTool(input);
__registerTool(sleep);
__registerTool(round);
__registerTool(read);
__registerTool(write);
__registerTool(readImage);
__registerTool(notify);
__registerTool(range);
__registerTool(mostCommon);
__registerTool(keys);
__registerTool(values);
__registerTool(entries);
__registerTool(emit);
__registerTool(callback);
async function __initializeGlobals(__ctx) {
  if (__ctx.globals.isInitialized("dist/lib/agents/agency-agent/prompts/codeSample.agency")) {
    return;
  }
  __ctx.globals.markInitialized("dist/lib/agents/agency-agent/prompts/codeSample.agency");
}
__registerGlobalsInit("dist/lib/agents/agency-agent/prompts/codeSample.agency", __initializeGlobals);
async function __registerTopLevelCallbacks(__ctx) {
  __ctx.topLevelCallbacks = [];
}
__functionRefReviver.registry = __toolRegistry;
graph.node("main", async (__state) => {
  const __setupData = setupNode({
    state: __state
  });
  const __stack = __setupData.stack;
  const __step = __setupData.step;
  const __self = __setupData.self;
  const __ctx = getRuntimeContext().ctx;
  let __forked;
  let __functionCompleted = false;
  const runner = new Runner(__ctx, __stack, { nodeContext: true, state: __stack, moduleId: "dist/lib/agents/agency-agent/prompts/codeSample.agency", scopeName: "main", threads: __setupData.threads });
  try {
    await agencyStore.run({
      ...getRuntimeContext(),
      ctx: __ctx,
      stack: __ctx.stateStack,
      threads: __setupData.threads
    }, async () => {
      await runner.hook(0, async () => {
        await callHook({
          name: "onNodeStart",
          data: {
            nodeName: "main"
          }
        });
      });
      await runner.step(1, async (runner2) => {
        const __funcResult = await __call(print, {
          type: "positional",
          args: [`Welcome to the meal planning agent!`]
        });
        if (hasInterrupts(__funcResult)) {
          await getRuntimeContext().ctx.pendingPromises.awaitAll();
          runner2.halt({
            ...__state,
            data: __funcResult
          });
          return;
        }
      });
      await runner.step(2, async (runner2) => {
        __stack.locals.userMsg = await __call(input, {
          type: "positional",
          args: [`How may I help you? `]
        });
        if (hasInterrupts(__stack.locals.userMsg)) {
          await getRuntimeContext().ctx.pendingPromises.awaitAll();
          runner2.halt({
            ...__state,
            data: __stack.locals.userMsg
          });
          return;
        }
      });
      await runner.step(3, async (runner2) => {
        __stateStack()?.pop();
        __functionCompleted = true;
        runner2.halt(goToNode("categorize", {
          messages: __threads(),
          ctx: getRuntimeContext().ctx,
          data: {
            userMsg: __stack.locals.userMsg
          }
        }));
        return;
      });
    });
    if (runner.halted) return runner.haltResult;
    await runner.hook(4, async () => {
      await callHook({
        name: "onNodeEnd",
        data: {
          nodeName: "main",
          data: void 0
        }
      });
    });
    return {
      messages: __threads(),
      data: void 0
    };
  } catch (__error) {
    if (__error instanceof RestoreSignal) {
      throw __error;
    }
    if (__error instanceof GuardExceededError) {
      throw __error;
    }
    {
      const __errMsg = __error instanceof Error ? __error.message : String(__error);
      const __errStack = __error instanceof Error && __error.stack ? __error.stack : "";
      const __log = __createLogger(__ctx.logLevel);
      __log.error(`Node main crashed: ${__errMsg}`);
      if (__errStack) __log.error(__errStack);
      __ctx.statelogClient?.error?.({
        errorType: "runtimeError",
        message: __errMsg,
        functionName: "main"
      });
    }
    return {
      messages: __threads(),
      data: failure(__error instanceof Error ? __error.message : String(__error), { functionName: "main" })
    };
  }
});
const Category = z.union([z.literal("scrape-recipe"), z.literal("create-ingredients"), z.literal("create-meals")]);
graph.node("categorize", async (__state) => {
  const __setupData = setupNode({
    state: __state
  });
  const __stack = __setupData.stack;
  const __step = __setupData.step;
  const __self = __setupData.self;
  const __ctx = getRuntimeContext().ctx;
  let __forked;
  let __functionCompleted = false;
  const runner = new Runner(__ctx, __stack, { nodeContext: true, state: __stack, moduleId: "dist/lib/agents/agency-agent/prompts/codeSample.agency", scopeName: "categorize", threads: __setupData.threads });
  if (!__state.isResume) {
    __stack.args["userMsg"] = __state.data.userMsg;
  }
  try {
    await agencyStore.run({
      ...getRuntimeContext(),
      ctx: __ctx,
      stack: __ctx.stateStack,
      threads: __setupData.threads
    }, async () => {
      await runner.hook(0, async () => {
        await callHook({
          name: "onNodeStart",
          data: {
            nodeName: "categorize"
          }
        });
      });
      await runner.step(1, async (runner2) => {
        __stack.locals.categorizePrompt = `
  If you are a master at categorization, the user is going to give you some text regarding meal planning. Take this user input, and classify their intent into one of these categories:
  
  - If the user wants to scrape recipe data from a provided URL, return "scrape-recipe"
  - If the user wants to create ingredients in the database based on scraped data, return "create-ingredients"
  - If the user wants to create meals in the database based on scraped recipe data, return "create-meals"
  Here is the user input: ${__stack.args.userMsg}
  `;
      });
      await runner.step(2, async (runner2) => {
        __self.__removedTools = __self.__removedTools || [];
        __stack.locals.category = await runPrompt({
          prompt: `${__stack.locals.categorizePrompt}`,
          messages: __threads().getOrCreateActive(),
          responseFormat: z.object({
            response: Category
          }),
          clientConfig: {},
          maxToolCallRounds: 10,
          removedTools: __self.__removedTools,
          checkpointInfo: runner2.getCheckpointInfo()
        });
        if (hasInterrupts(__stack.locals.category)) {
          await getRuntimeContext().ctx.pendingPromises.awaitAll();
          runner2.halt({
            messages: __threads(),
            data: __stack.locals.category
          });
          return;
        }
      });
      await runner.ifElse(3, [
        {
          condition: async () => __stack.locals.category === `scrape-recipe`,
          body: async (runner2) => {
            __stateStack()?.pop();
            __functionCompleted = true;
            runner2.halt(goToNode("scrapeRecipe", {
              messages: __threads(),
              ctx: getRuntimeContext().ctx,
              data: {}
            }));
            return;
          }
        },
        {
          condition: async () => __stack.locals.category === `create-ingredients`,
          body: async (runner2) => {
            __stateStack()?.pop();
            __functionCompleted = true;
            runner2.halt(goToNode("createIngredients", {
              messages: __threads(),
              ctx: getRuntimeContext().ctx,
              data: {}
            }));
            return;
          }
        },
        {
          condition: async () => __stack.locals.category === `create-meals`,
          body: async (runner2) => {
            __stateStack()?.pop();
            __functionCompleted = true;
            runner2.halt(goToNode("createMeals", {
              messages: __threads(),
              ctx: getRuntimeContext().ctx,
              data: {}
            }));
            return;
          }
        }
      ]);
    });
    if (runner.halted) return runner.haltResult;
    await runner.hook(4, async () => {
      await callHook({
        name: "onNodeEnd",
        data: {
          nodeName: "categorize",
          data: void 0
        }
      });
    });
    return {
      messages: __threads(),
      data: void 0
    };
  } catch (__error) {
    if (__error instanceof RestoreSignal) {
      throw __error;
    }
    if (__error instanceof GuardExceededError) {
      throw __error;
    }
    {
      const __errMsg = __error instanceof Error ? __error.message : String(__error);
      const __errStack = __error instanceof Error && __error.stack ? __error.stack : "";
      const __log = __createLogger(__ctx.logLevel);
      __log.error(`Node categorize crashed: ${__errMsg}`);
      if (__errStack) __log.error(__errStack);
      __ctx.statelogClient?.error?.({
        errorType: "runtimeError",
        message: __errMsg,
        functionName: "categorize"
      });
    }
    return {
      messages: __threads(),
      data: failure(__error instanceof Error ? __error.message : String(__error), { functionName: "categorize" })
    };
  }
});
graph.node("scrapeRecipe", async (__state) => {
  const __setupData = setupNode({
    state: __state
  });
  const __stack = __setupData.stack;
  const __step = __setupData.step;
  const __self = __setupData.self;
  const __ctx = getRuntimeContext().ctx;
  let __forked;
  let __functionCompleted = false;
  const runner = new Runner(__ctx, __stack, { nodeContext: true, state: __stack, moduleId: "dist/lib/agents/agency-agent/prompts/codeSample.agency", scopeName: "scrapeRecipe", threads: __setupData.threads });
  try {
    await agencyStore.run({
      ...getRuntimeContext(),
      ctx: __ctx,
      stack: __ctx.stateStack,
      threads: __setupData.threads
    }, async () => {
      await runner.hook(0, async () => {
        await callHook({
          name: "onNodeStart",
          data: {
            nodeName: "scrapeRecipe"
          }
        });
      });
      await runner.step(1, async (runner2) => {
        const __funcResult = await __call(print, {
          type: "positional",
          args: [`Scraping recipe data from URL!`]
        });
        if (hasInterrupts(__funcResult)) {
          await getRuntimeContext().ctx.pendingPromises.awaitAll();
          runner2.halt({
            ...__state,
            data: __funcResult
          });
          return;
        }
      });
    });
    if (runner.halted) return runner.haltResult;
    await runner.hook(2, async () => {
      await callHook({
        name: "onNodeEnd",
        data: {
          nodeName: "scrapeRecipe",
          data: void 0
        }
      });
    });
    return {
      messages: __threads(),
      data: void 0
    };
  } catch (__error) {
    if (__error instanceof RestoreSignal) {
      throw __error;
    }
    if (__error instanceof GuardExceededError) {
      throw __error;
    }
    {
      const __errMsg = __error instanceof Error ? __error.message : String(__error);
      const __errStack = __error instanceof Error && __error.stack ? __error.stack : "";
      const __log = __createLogger(__ctx.logLevel);
      __log.error(`Node scrapeRecipe crashed: ${__errMsg}`);
      if (__errStack) __log.error(__errStack);
      __ctx.statelogClient?.error?.({
        errorType: "runtimeError",
        message: __errMsg,
        functionName: "scrapeRecipe"
      });
    }
    return {
      messages: __threads(),
      data: failure(__error instanceof Error ? __error.message : String(__error), { functionName: "scrapeRecipe" })
    };
  }
});
graph.node("createIngredients", async (__state) => {
  const __setupData = setupNode({
    state: __state
  });
  const __stack = __setupData.stack;
  const __step = __setupData.step;
  const __self = __setupData.self;
  const __ctx = getRuntimeContext().ctx;
  let __forked;
  let __functionCompleted = false;
  const runner = new Runner(__ctx, __stack, { nodeContext: true, state: __stack, moduleId: "dist/lib/agents/agency-agent/prompts/codeSample.agency", scopeName: "createIngredients", threads: __setupData.threads });
  try {
    await agencyStore.run({
      ...getRuntimeContext(),
      ctx: __ctx,
      stack: __ctx.stateStack,
      threads: __setupData.threads
    }, async () => {
      await runner.hook(0, async () => {
        await callHook({
          name: "onNodeStart",
          data: {
            nodeName: "createIngredients"
          }
        });
      });
      await runner.step(1, async (runner2) => {
        const __funcResult = await __call(print, {
          type: "positional",
          args: [`Creating ingredients in the database!`]
        });
        if (hasInterrupts(__funcResult)) {
          await getRuntimeContext().ctx.pendingPromises.awaitAll();
          runner2.halt({
            ...__state,
            data: __funcResult
          });
          return;
        }
      });
    });
    if (runner.halted) return runner.haltResult;
    await runner.hook(2, async () => {
      await callHook({
        name: "onNodeEnd",
        data: {
          nodeName: "createIngredients",
          data: void 0
        }
      });
    });
    return {
      messages: __threads(),
      data: void 0
    };
  } catch (__error) {
    if (__error instanceof RestoreSignal) {
      throw __error;
    }
    if (__error instanceof GuardExceededError) {
      throw __error;
    }
    {
      const __errMsg = __error instanceof Error ? __error.message : String(__error);
      const __errStack = __error instanceof Error && __error.stack ? __error.stack : "";
      const __log = __createLogger(__ctx.logLevel);
      __log.error(`Node createIngredients crashed: ${__errMsg}`);
      if (__errStack) __log.error(__errStack);
      __ctx.statelogClient?.error?.({
        errorType: "runtimeError",
        message: __errMsg,
        functionName: "createIngredients"
      });
    }
    return {
      messages: __threads(),
      data: failure(__error instanceof Error ? __error.message : String(__error), { functionName: "createIngredients" })
    };
  }
});
graph.node("createMeals", async (__state) => {
  const __setupData = setupNode({
    state: __state
  });
  const __stack = __setupData.stack;
  const __step = __setupData.step;
  const __self = __setupData.self;
  const __ctx = getRuntimeContext().ctx;
  let __forked;
  let __functionCompleted = false;
  const runner = new Runner(__ctx, __stack, { nodeContext: true, state: __stack, moduleId: "dist/lib/agents/agency-agent/prompts/codeSample.agency", scopeName: "createMeals", threads: __setupData.threads });
  try {
    await agencyStore.run({
      ...getRuntimeContext(),
      ctx: __ctx,
      stack: __ctx.stateStack,
      threads: __setupData.threads
    }, async () => {
      await runner.hook(0, async () => {
        await callHook({
          name: "onNodeStart",
          data: {
            nodeName: "createMeals"
          }
        });
      });
      await runner.step(1, async (runner2) => {
        const __funcResult = await __call(print, {
          type: "positional",
          args: [`Creating meals in the database!`]
        });
        if (hasInterrupts(__funcResult)) {
          await getRuntimeContext().ctx.pendingPromises.awaitAll();
          runner2.halt({
            ...__state,
            data: __funcResult
          });
          return;
        }
      });
    });
    if (runner.halted) return runner.haltResult;
    await runner.hook(2, async () => {
      await callHook({
        name: "onNodeEnd",
        data: {
          nodeName: "createMeals",
          data: void 0
        }
      });
    });
    return {
      messages: __threads(),
      data: void 0
    };
  } catch (__error) {
    if (__error instanceof RestoreSignal) {
      throw __error;
    }
    if (__error instanceof GuardExceededError) {
      throw __error;
    }
    {
      const __errMsg = __error instanceof Error ? __error.message : String(__error);
      const __errStack = __error instanceof Error && __error.stack ? __error.stack : "";
      const __log = __createLogger(__ctx.logLevel);
      __log.error(`Node createMeals crashed: ${__errMsg}`);
      if (__errStack) __log.error(__errStack);
      __ctx.statelogClient?.error?.({
        errorType: "runtimeError",
        message: __errMsg,
        functionName: "createMeals"
      });
    }
    return {
      messages: __threads(),
      data: failure(__error instanceof Error ? __error.message : String(__error), { functionName: "createMeals" })
    };
  }
});
graph.conditionalEdge("main", ["categorize"]);
graph.conditionalEdge("categorize", ["scrapeRecipe", "createIngredients", "createMeals"]);
async function main({ messages, callbacks } = {}) {
  return runNode({
    ctx: __globalCtx,
    nodeName: "main",
    data: {},
    messages,
    callbacks,
    initializeGlobals: __initializeGlobals,
    registerTopLevelCallbacks: __registerTopLevelCallbacks,
    moduleDir: __dirname
  });
}
const __mainNodeParams = [];
async function categorize(userMsg, { messages, callbacks } = {}) {
  return runNode({
    ctx: __globalCtx,
    nodeName: "categorize",
    data: {
      userMsg
    },
    messages,
    callbacks,
    initializeGlobals: __initializeGlobals,
    registerTopLevelCallbacks: __registerTopLevelCallbacks,
    moduleDir: __dirname
  });
}
const __categorizeNodeParams = ["userMsg"];
async function scrapeRecipe({ messages, callbacks } = {}) {
  return runNode({
    ctx: __globalCtx,
    nodeName: "scrapeRecipe",
    data: {},
    messages,
    callbacks,
    initializeGlobals: __initializeGlobals,
    registerTopLevelCallbacks: __registerTopLevelCallbacks,
    moduleDir: __dirname
  });
}
const __scrapeRecipeNodeParams = [];
async function createIngredients({ messages, callbacks } = {}) {
  return runNode({
    ctx: __globalCtx,
    nodeName: "createIngredients",
    data: {},
    messages,
    callbacks,
    initializeGlobals: __initializeGlobals,
    registerTopLevelCallbacks: __registerTopLevelCallbacks,
    moduleDir: __dirname
  });
}
const __createIngredientsNodeParams = [];
async function createMeals({ messages, callbacks } = {}) {
  return runNode({
    ctx: __globalCtx,
    nodeName: "createMeals",
    data: {},
    messages,
    callbacks,
    initializeGlobals: __initializeGlobals,
    registerTopLevelCallbacks: __registerTopLevelCallbacks,
    moduleDir: __dirname
  });
}
const __createMealsNodeParams = [];
if (__process.argv[1] === fileURLToPath(import.meta.url)) {
  try {
    const initialState = {
      messages: new ThreadStore(),
      data: {}
    };
    await main(initialState);
  } catch (__error) {
    console.error(`
Agent crashed: ${__error.message}`);
    throw __error;
  }
}
var stdin_default = graph;
const __sourceMap = { "dist/lib/agents/agency-agent/prompts/codeSample.agency:main": { "1": { "line": 1, "col": 2 }, "2": { "line": 2, "col": 2 }, "3": { "line": 3, "col": 2 } }, "dist/lib/agents/agency-agent/prompts/codeSample.agency:categorize": { "1": { "line": 10, "col": 2 }, "2": { "line": 18, "col": 2 }, "3": { "line": 20, "col": 2 } }, "dist/lib/agents/agency-agent/prompts/codeSample.agency:scrapeRecipe": { "1": { "line": 28, "col": 2 } }, "dist/lib/agents/agency-agent/prompts/codeSample.agency:createIngredients": { "1": { "line": 33, "col": 2 } }, "dist/lib/agents/agency-agent/prompts/codeSample.agency:createMeals": { "1": { "line": 38, "col": 2 } } };
export {
  __categorizeNodeParams,
  __createIngredientsNodeParams,
  __createMealsNodeParams,
  __getCheckpoints,
  __mainNodeParams,
  __scrapeRecipeNodeParams,
  __setDebugger,
  __setLLMClient,
  __setTraceFile,
  __sourceMap,
  __toolRegistry,
  approve,
  categorize,
  createIngredients,
  createMeals,
  stdin_default as default,
  hasInterrupts,
  interrupt,
  isDebugger,
  isInterrupt,
  main,
  reject,
  respondToInterrupts,
  rewindFrom,
  scrapeRecipe
};
