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 { _sendWithResend, _sendWithSendGrid, _sendWithMailgun } from "agency-lang/stdlib-lib/email.js";
import { fileURLToPath } from "url";
import __process from "process";
import { z } from "agency-lang/zod";
import { nanoid } from "agency-lang";
import path from "path";
import {
  RuntimeContext,
  Runner,
  setupFunction,
  callHook,
  checkpoint as __checkpoint_impl,
  getCheckpoint as __getCheckpoint_impl,
  restore as __restore_impl,
  _run as __runtime_run_impl,
  interrupt,
  isInterrupt,
  hasInterrupts,
  isDebugger,
  isRejected,
  isApproved,
  interruptWithHandlers,
  respondToInterrupts as _respondToInterrupts,
  rewindFrom as _rewindFrom,
  RestoreSignal,
  GuardExceededError,
  __registerGlobalsInit,
  failure,
  isFailure,
  __tryCall,
  AgencyFunction as __AgencyFunction,
  UNSET as __UNSET,
  __call,
  __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: "stdlib/email.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("stdlib/email.agency")) {
    return;
  }
  __ctx.globals.markInitialized("stdlib/email.agency");
}
__registerGlobalsInit("stdlib/email.agency", __initializeGlobals);
async function __registerTopLevelCallbacks(__ctx) {
  __ctx.topLevelCallbacks = [];
}
__functionRefReviver.registry = __toolRegistry;
const EmailResult = z.object({ "id": z.string(), "provider": z.string() });
async function __sendWithResend_impl(from, to, subject, html = __UNSET, text = __UNSET, cc = __UNSET, bcc = __UNSET, replyTo = __UNSET, apiKey = __UNSET, allowList = __UNSET, blockList = __UNSET) {
  const __setupData = setupFunction();
  const __stack = __setupData.stack;
  const __step = __setupData.step;
  const __self = __setupData.self;
  const __ctx = getRuntimeContext().ctx;
  let __forked;
  let __functionCompleted = false;
  if (!__ctx.globals.isInitialized("stdlib/email.agency")) {
    await __initializeGlobals(__ctx);
  }
  let __funcStartTime = performance.now();
  __stack.args["from"] = from;
  __stack.args["to"] = to;
  __stack.args["subject"] = subject;
  __stack.args["html"] = html === __UNSET ? `` : html;
  __stack.args["text"] = text === __UNSET ? `` : text;
  __stack.args["cc"] = cc === __UNSET ? `` : cc;
  __stack.args["bcc"] = bcc === __UNSET ? `` : bcc;
  __stack.args["replyTo"] = replyTo === __UNSET ? `` : replyTo;
  __stack.args["apiKey"] = apiKey === __UNSET ? `` : apiKey;
  __stack.args["allowList"] = allowList === __UNSET ? [] : allowList;
  __stack.args["blockList"] = blockList === __UNSET ? [] : blockList;
  __self.__retryable = __self.__retryable ?? true;
  const runner = new Runner(__ctx, __stack, { state: __stack, moduleId: "stdlib/email.agency", scopeName: "sendWithResend", threads: __setupData.threads });
  let __resultCheckpointId = -1;
  if (__ctx._pendingArgOverrides) {
    const __overrides = __ctx._pendingArgOverrides;
    __ctx._pendingArgOverrides = void 0;
    if ("from" in __overrides) {
      from = __overrides["from"];
      __stack.args["from"] = from;
    }
    if ("to" in __overrides) {
      to = __overrides["to"];
      __stack.args["to"] = to;
    }
    if ("subject" in __overrides) {
      subject = __overrides["subject"];
      __stack.args["subject"] = subject;
    }
    if ("html" in __overrides) {
      html = __overrides["html"];
      __stack.args["html"] = html;
    }
    if ("text" in __overrides) {
      text = __overrides["text"];
      __stack.args["text"] = text;
    }
    if ("cc" in __overrides) {
      cc = __overrides["cc"];
      __stack.args["cc"] = cc;
    }
    if ("bcc" in __overrides) {
      bcc = __overrides["bcc"];
      __stack.args["bcc"] = bcc;
    }
    if ("replyTo" in __overrides) {
      replyTo = __overrides["replyTo"];
      __stack.args["replyTo"] = replyTo;
    }
    if ("apiKey" in __overrides) {
      apiKey = __overrides["apiKey"];
      __stack.args["apiKey"] = apiKey;
    }
    if ("allowList" in __overrides) {
      allowList = __overrides["allowList"];
      __stack.args["allowList"] = allowList;
    }
    if ("blockList" in __overrides) {
      blockList = __overrides["blockList"];
      __stack.args["blockList"] = blockList;
    }
  }
  try {
    await agencyStore.run({
      ...getRuntimeContext(),
      ctx: __ctx,
      stack: __setupData.stateStack,
      threads: __setupData.threads
    }, async () => {
      await runner.hook(0, async () => {
        await callHook({
          name: "onFunctionStart",
          data: {
            functionName: "sendWithResend",
            args: {
              from,
              to,
              subject,
              html,
              text,
              cc,
              bcc,
              replyTo,
              apiKey,
              allowList,
              blockList
            },
            isBuiltin: false,
            moduleId: "stdlib/email.agency"
          }
        });
      });
      await runner.step(1, async (runner2) => {
        const __response = getRuntimeContext().ctx.getInterruptResponse(__self.__interruptId_1);
        if (__response) {
          if (__response.type === "approve") {
          } else if (__response.type === "reject") {
            runner2.halt(failure("interrupt rejected", { retryable: false, checkpoint: getRuntimeContext().ctx.getResultCheckpoint() }));
            return;
          }
        } else {
          const __handlerResult = await interruptWithHandlers("std::sendEmail", `Are you sure you want to send this email via Resend?`, {
            "from": __stack.args.from,
            "to": __stack.args.to,
            "subject": __stack.args.subject
          }, "std::email", __ctx, __stateStack());
          if (isRejected(__handlerResult)) {
            runner2.halt(failure(__handlerResult.value ?? "interrupt rejected", { retryable: false, checkpoint: getRuntimeContext().ctx.checkpoints.get(__resultCheckpointId) }));
            return;
          }
          if (!isApproved(__handlerResult)) {
            __self.__interruptId_1 = __handlerResult[0].interruptId;
            const __checkpointId = getRuntimeContext().ctx.checkpoints.create(__stateStack(), __ctx, { moduleId: "stdlib/email.agency", scopeName: "sendWithResend", stepPath: "1" });
            __handlerResult[0].checkpointId = __checkpointId;
            __handlerResult[0].checkpoint = getRuntimeContext().ctx.checkpoints.get(__checkpointId);
            runner2.halt(__handlerResult);
            return;
          }
        }
      });
      await runner.step(2, async (runner2) => {
        __functionCompleted = true;
        runner2.halt(await __tryCall(async () => await __call(_sendWithResend, {
          type: "positional",
          args: [{
            "from": __stack.args.from,
            "to": __stack.args.to,
            "subject": __stack.args.subject,
            "html": __stack.args.html,
            "text": __stack.args.text,
            "cc": __stack.args.cc,
            "bcc": __stack.args.bcc,
            "replyTo": __stack.args.replyTo
          }, {
            "apiKey": __stack.args.apiKey,
            "allowList": __stack.args.allowList,
            "blockList": __stack.args.blockList
          }]
        }), {
          checkpoint: getRuntimeContext().ctx.getResultCheckpoint(),
          functionName: "sendWithResend",
          args: __stack.args
        }));
        return;
      });
    });
    if (runner.halted) {
      if (isFailure(runner.haltResult)) {
        runner.haltResult.retryable = runner.haltResult.retryable && __self.__retryable;
      }
      return runner.haltResult;
    }
  } 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("Function sendWithResend threw an exception (converted to Failure): " + __errMsg);
      if (__errStack) __log.error(__errStack);
      __ctx.statelogClient?.error?.({
        errorType: "runtimeError",
        message: __errMsg,
        functionName: "sendWithResend",
        retryable: __self.__retryable
      });
    }
    return failure(
      __error instanceof Error ? __error.message : String(__error),
      {
        checkpoint: getRuntimeContext().ctx.getResultCheckpoint(),
        retryable: __self.__retryable,
        functionName: "sendWithResend",
        args: __stack.args
      }
    );
  } finally {
    __stateStack()?.pop();
    if (__functionCompleted) {
      await callHook({
        name: "onFunctionEnd",
        data: {
          functionName: "sendWithResend",
          timeTaken: performance.now() - __funcStartTime
        }
      });
    }
  }
}
const sendWithResend = __AgencyFunction.create({
  name: "sendWithResend",
  module: "stdlib/email.agency",
  fn: __sendWithResend_impl,
  params: [{
    name: "from",
    hasDefault: false,
    defaultValue: void 0,
    variadic: false
  }, {
    name: "to",
    hasDefault: false,
    defaultValue: void 0,
    variadic: false
  }, {
    name: "subject",
    hasDefault: false,
    defaultValue: void 0,
    variadic: false
  }, {
    name: "html",
    hasDefault: true,
    defaultValue: void 0,
    variadic: false
  }, {
    name: "text",
    hasDefault: true,
    defaultValue: void 0,
    variadic: false
  }, {
    name: "cc",
    hasDefault: true,
    defaultValue: void 0,
    variadic: false
  }, {
    name: "bcc",
    hasDefault: true,
    defaultValue: void 0,
    variadic: false
  }, {
    name: "replyTo",
    hasDefault: true,
    defaultValue: void 0,
    variadic: false
  }, {
    name: "apiKey",
    hasDefault: true,
    defaultValue: void 0,
    variadic: false
  }, {
    name: "allowList",
    hasDefault: true,
    defaultValue: void 0,
    variadic: false
  }, {
    name: "blockList",
    hasDefault: true,
    defaultValue: void 0,
    variadic: false
  }],
  toolDefinition: {
    name: "sendWithResend",
    description: `Send an email using the Resend API. Requires RESEND_API_KEY env var or pass apiKey directly. Set allowList to restrict recipients to specific addresses. Set blockList to reject specific addresses.

  @param from - Sender email address
  @param to - Recipient email address
  @param subject - Email subject
  @param html - HTML content
  @param text - Plain text content
  @param cc - CC recipients
  @param bcc - BCC recipients
  @param replyTo - Reply-to address
  @param apiKey - Resend API key
  @param allowList - Only allow sending to these addresses
  @param blockList - Block sending to these addresses`,
    schema: z.object({ "from": z.string(), "to": z.string(), "subject": z.string(), "html": z.string().nullable().describe("Default: "), "text": z.string().nullable().describe("Default: "), "cc": z.string().nullable().describe("Default: "), "bcc": z.string().nullable().describe("Default: "), "replyTo": z.string().nullable().describe("Default: "), "apiKey": z.string().nullable().describe("Default: "), "allowList": z.array(z.string()).nullable().describe("Default: []"), "blockList": z.array(z.string()).nullable().describe("Default: []") })
  },
  safe: false,
  exported: true
}, __toolRegistry);
async function __sendWithSendGrid_impl(from, to, subject, html = __UNSET, text = __UNSET, cc = __UNSET, bcc = __UNSET, replyTo = __UNSET, apiKey = __UNSET, allowList = __UNSET, blockList = __UNSET) {
  const __setupData = setupFunction();
  const __stack = __setupData.stack;
  const __step = __setupData.step;
  const __self = __setupData.self;
  const __ctx = getRuntimeContext().ctx;
  let __forked;
  let __functionCompleted = false;
  if (!__ctx.globals.isInitialized("stdlib/email.agency")) {
    await __initializeGlobals(__ctx);
  }
  let __funcStartTime = performance.now();
  __stack.args["from"] = from;
  __stack.args["to"] = to;
  __stack.args["subject"] = subject;
  __stack.args["html"] = html === __UNSET ? `` : html;
  __stack.args["text"] = text === __UNSET ? `` : text;
  __stack.args["cc"] = cc === __UNSET ? `` : cc;
  __stack.args["bcc"] = bcc === __UNSET ? `` : bcc;
  __stack.args["replyTo"] = replyTo === __UNSET ? `` : replyTo;
  __stack.args["apiKey"] = apiKey === __UNSET ? `` : apiKey;
  __stack.args["allowList"] = allowList === __UNSET ? [] : allowList;
  __stack.args["blockList"] = blockList === __UNSET ? [] : blockList;
  __self.__retryable = __self.__retryable ?? true;
  const runner = new Runner(__ctx, __stack, { state: __stack, moduleId: "stdlib/email.agency", scopeName: "sendWithSendGrid", threads: __setupData.threads });
  let __resultCheckpointId = -1;
  if (__ctx._pendingArgOverrides) {
    const __overrides = __ctx._pendingArgOverrides;
    __ctx._pendingArgOverrides = void 0;
    if ("from" in __overrides) {
      from = __overrides["from"];
      __stack.args["from"] = from;
    }
    if ("to" in __overrides) {
      to = __overrides["to"];
      __stack.args["to"] = to;
    }
    if ("subject" in __overrides) {
      subject = __overrides["subject"];
      __stack.args["subject"] = subject;
    }
    if ("html" in __overrides) {
      html = __overrides["html"];
      __stack.args["html"] = html;
    }
    if ("text" in __overrides) {
      text = __overrides["text"];
      __stack.args["text"] = text;
    }
    if ("cc" in __overrides) {
      cc = __overrides["cc"];
      __stack.args["cc"] = cc;
    }
    if ("bcc" in __overrides) {
      bcc = __overrides["bcc"];
      __stack.args["bcc"] = bcc;
    }
    if ("replyTo" in __overrides) {
      replyTo = __overrides["replyTo"];
      __stack.args["replyTo"] = replyTo;
    }
    if ("apiKey" in __overrides) {
      apiKey = __overrides["apiKey"];
      __stack.args["apiKey"] = apiKey;
    }
    if ("allowList" in __overrides) {
      allowList = __overrides["allowList"];
      __stack.args["allowList"] = allowList;
    }
    if ("blockList" in __overrides) {
      blockList = __overrides["blockList"];
      __stack.args["blockList"] = blockList;
    }
  }
  try {
    await agencyStore.run({
      ...getRuntimeContext(),
      ctx: __ctx,
      stack: __setupData.stateStack,
      threads: __setupData.threads
    }, async () => {
      await runner.hook(0, async () => {
        await callHook({
          name: "onFunctionStart",
          data: {
            functionName: "sendWithSendGrid",
            args: {
              from,
              to,
              subject,
              html,
              text,
              cc,
              bcc,
              replyTo,
              apiKey,
              allowList,
              blockList
            },
            isBuiltin: false,
            moduleId: "stdlib/email.agency"
          }
        });
      });
      await runner.step(1, async (runner2) => {
        const __response = getRuntimeContext().ctx.getInterruptResponse(__self.__interruptId_1);
        if (__response) {
          if (__response.type === "approve") {
          } else if (__response.type === "reject") {
            runner2.halt(failure("interrupt rejected", { retryable: false, checkpoint: getRuntimeContext().ctx.getResultCheckpoint() }));
            return;
          }
        } else {
          const __handlerResult = await interruptWithHandlers("std::sendEmail", `Are you sure you want to send this email via SendGrid?`, {
            "from": __stack.args.from,
            "to": __stack.args.to,
            "subject": __stack.args.subject
          }, "std::email", __ctx, __stateStack());
          if (isRejected(__handlerResult)) {
            runner2.halt(failure(__handlerResult.value ?? "interrupt rejected", { retryable: false, checkpoint: getRuntimeContext().ctx.checkpoints.get(__resultCheckpointId) }));
            return;
          }
          if (!isApproved(__handlerResult)) {
            __self.__interruptId_1 = __handlerResult[0].interruptId;
            const __checkpointId = getRuntimeContext().ctx.checkpoints.create(__stateStack(), __ctx, { moduleId: "stdlib/email.agency", scopeName: "sendWithSendGrid", stepPath: "1" });
            __handlerResult[0].checkpointId = __checkpointId;
            __handlerResult[0].checkpoint = getRuntimeContext().ctx.checkpoints.get(__checkpointId);
            runner2.halt(__handlerResult);
            return;
          }
        }
      });
      await runner.step(2, async (runner2) => {
        __functionCompleted = true;
        runner2.halt(await __tryCall(async () => await __call(_sendWithSendGrid, {
          type: "positional",
          args: [{
            "from": __stack.args.from,
            "to": __stack.args.to,
            "subject": __stack.args.subject,
            "html": __stack.args.html,
            "text": __stack.args.text,
            "cc": __stack.args.cc,
            "bcc": __stack.args.bcc,
            "replyTo": __stack.args.replyTo
          }, {
            "apiKey": __stack.args.apiKey,
            "allowList": __stack.args.allowList,
            "blockList": __stack.args.blockList
          }]
        }), {
          checkpoint: getRuntimeContext().ctx.getResultCheckpoint(),
          functionName: "sendWithSendGrid",
          args: __stack.args
        }));
        return;
      });
    });
    if (runner.halted) {
      if (isFailure(runner.haltResult)) {
        runner.haltResult.retryable = runner.haltResult.retryable && __self.__retryable;
      }
      return runner.haltResult;
    }
  } 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("Function sendWithSendGrid threw an exception (converted to Failure): " + __errMsg);
      if (__errStack) __log.error(__errStack);
      __ctx.statelogClient?.error?.({
        errorType: "runtimeError",
        message: __errMsg,
        functionName: "sendWithSendGrid",
        retryable: __self.__retryable
      });
    }
    return failure(
      __error instanceof Error ? __error.message : String(__error),
      {
        checkpoint: getRuntimeContext().ctx.getResultCheckpoint(),
        retryable: __self.__retryable,
        functionName: "sendWithSendGrid",
        args: __stack.args
      }
    );
  } finally {
    __stateStack()?.pop();
    if (__functionCompleted) {
      await callHook({
        name: "onFunctionEnd",
        data: {
          functionName: "sendWithSendGrid",
          timeTaken: performance.now() - __funcStartTime
        }
      });
    }
  }
}
const sendWithSendGrid = __AgencyFunction.create({
  name: "sendWithSendGrid",
  module: "stdlib/email.agency",
  fn: __sendWithSendGrid_impl,
  params: [{
    name: "from",
    hasDefault: false,
    defaultValue: void 0,
    variadic: false
  }, {
    name: "to",
    hasDefault: false,
    defaultValue: void 0,
    variadic: false
  }, {
    name: "subject",
    hasDefault: false,
    defaultValue: void 0,
    variadic: false
  }, {
    name: "html",
    hasDefault: true,
    defaultValue: void 0,
    variadic: false
  }, {
    name: "text",
    hasDefault: true,
    defaultValue: void 0,
    variadic: false
  }, {
    name: "cc",
    hasDefault: true,
    defaultValue: void 0,
    variadic: false
  }, {
    name: "bcc",
    hasDefault: true,
    defaultValue: void 0,
    variadic: false
  }, {
    name: "replyTo",
    hasDefault: true,
    defaultValue: void 0,
    variadic: false
  }, {
    name: "apiKey",
    hasDefault: true,
    defaultValue: void 0,
    variadic: false
  }, {
    name: "allowList",
    hasDefault: true,
    defaultValue: void 0,
    variadic: false
  }, {
    name: "blockList",
    hasDefault: true,
    defaultValue: void 0,
    variadic: false
  }],
  toolDefinition: {
    name: "sendWithSendGrid",
    description: `Send an email using the SendGrid API. Requires SENDGRID_API_KEY env var or pass apiKey directly. Set allowList to restrict recipients to specific addresses. Set blockList to reject specific addresses.

  @param from - Sender email address
  @param to - Recipient email address
  @param subject - Email subject
  @param html - HTML content
  @param text - Plain text content
  @param cc - CC recipients
  @param bcc - BCC recipients
  @param replyTo - Reply-to address
  @param apiKey - SendGrid API key
  @param allowList - Only allow sending to these addresses
  @param blockList - Block sending to these addresses`,
    schema: z.object({ "from": z.string(), "to": z.string(), "subject": z.string(), "html": z.string().nullable().describe("Default: "), "text": z.string().nullable().describe("Default: "), "cc": z.string().nullable().describe("Default: "), "bcc": z.string().nullable().describe("Default: "), "replyTo": z.string().nullable().describe("Default: "), "apiKey": z.string().nullable().describe("Default: "), "allowList": z.array(z.string()).nullable().describe("Default: []"), "blockList": z.array(z.string()).nullable().describe("Default: []") })
  },
  safe: false,
  exported: true
}, __toolRegistry);
async function __sendWithMailgun_impl(from, to, subject, html = __UNSET, text = __UNSET, cc = __UNSET, bcc = __UNSET, replyTo = __UNSET, apiKey = __UNSET, domain = __UNSET, region = __UNSET, allowList = __UNSET, blockList = __UNSET) {
  const __setupData = setupFunction();
  const __stack = __setupData.stack;
  const __step = __setupData.step;
  const __self = __setupData.self;
  const __ctx = getRuntimeContext().ctx;
  let __forked;
  let __functionCompleted = false;
  if (!__ctx.globals.isInitialized("stdlib/email.agency")) {
    await __initializeGlobals(__ctx);
  }
  let __funcStartTime = performance.now();
  __stack.args["from"] = from;
  __stack.args["to"] = to;
  __stack.args["subject"] = subject;
  __stack.args["html"] = html === __UNSET ? `` : html;
  __stack.args["text"] = text === __UNSET ? `` : text;
  __stack.args["cc"] = cc === __UNSET ? `` : cc;
  __stack.args["bcc"] = bcc === __UNSET ? `` : bcc;
  __stack.args["replyTo"] = replyTo === __UNSET ? `` : replyTo;
  __stack.args["apiKey"] = apiKey === __UNSET ? `` : apiKey;
  __stack.args["domain"] = domain === __UNSET ? `` : domain;
  __stack.args["region"] = region === __UNSET ? `` : region;
  __stack.args["allowList"] = allowList === __UNSET ? [] : allowList;
  __stack.args["blockList"] = blockList === __UNSET ? [] : blockList;
  __self.__retryable = __self.__retryable ?? true;
  const runner = new Runner(__ctx, __stack, { state: __stack, moduleId: "stdlib/email.agency", scopeName: "sendWithMailgun", threads: __setupData.threads });
  let __resultCheckpointId = -1;
  if (__ctx._pendingArgOverrides) {
    const __overrides = __ctx._pendingArgOverrides;
    __ctx._pendingArgOverrides = void 0;
    if ("from" in __overrides) {
      from = __overrides["from"];
      __stack.args["from"] = from;
    }
    if ("to" in __overrides) {
      to = __overrides["to"];
      __stack.args["to"] = to;
    }
    if ("subject" in __overrides) {
      subject = __overrides["subject"];
      __stack.args["subject"] = subject;
    }
    if ("html" in __overrides) {
      html = __overrides["html"];
      __stack.args["html"] = html;
    }
    if ("text" in __overrides) {
      text = __overrides["text"];
      __stack.args["text"] = text;
    }
    if ("cc" in __overrides) {
      cc = __overrides["cc"];
      __stack.args["cc"] = cc;
    }
    if ("bcc" in __overrides) {
      bcc = __overrides["bcc"];
      __stack.args["bcc"] = bcc;
    }
    if ("replyTo" in __overrides) {
      replyTo = __overrides["replyTo"];
      __stack.args["replyTo"] = replyTo;
    }
    if ("apiKey" in __overrides) {
      apiKey = __overrides["apiKey"];
      __stack.args["apiKey"] = apiKey;
    }
    if ("domain" in __overrides) {
      domain = __overrides["domain"];
      __stack.args["domain"] = domain;
    }
    if ("region" in __overrides) {
      region = __overrides["region"];
      __stack.args["region"] = region;
    }
    if ("allowList" in __overrides) {
      allowList = __overrides["allowList"];
      __stack.args["allowList"] = allowList;
    }
    if ("blockList" in __overrides) {
      blockList = __overrides["blockList"];
      __stack.args["blockList"] = blockList;
    }
  }
  try {
    await agencyStore.run({
      ...getRuntimeContext(),
      ctx: __ctx,
      stack: __setupData.stateStack,
      threads: __setupData.threads
    }, async () => {
      await runner.hook(0, async () => {
        await callHook({
          name: "onFunctionStart",
          data: {
            functionName: "sendWithMailgun",
            args: {
              from,
              to,
              subject,
              html,
              text,
              cc,
              bcc,
              replyTo,
              apiKey,
              domain,
              region,
              allowList,
              blockList
            },
            isBuiltin: false,
            moduleId: "stdlib/email.agency"
          }
        });
      });
      await runner.step(1, async (runner2) => {
        const __response = getRuntimeContext().ctx.getInterruptResponse(__self.__interruptId_1);
        if (__response) {
          if (__response.type === "approve") {
          } else if (__response.type === "reject") {
            runner2.halt(failure("interrupt rejected", { retryable: false, checkpoint: getRuntimeContext().ctx.getResultCheckpoint() }));
            return;
          }
        } else {
          const __handlerResult = await interruptWithHandlers("std::sendEmail", `Are you sure you want to send this email via Mailgun?`, {
            "from": __stack.args.from,
            "to": __stack.args.to,
            "subject": __stack.args.subject
          }, "std::email", __ctx, __stateStack());
          if (isRejected(__handlerResult)) {
            runner2.halt(failure(__handlerResult.value ?? "interrupt rejected", { retryable: false, checkpoint: getRuntimeContext().ctx.checkpoints.get(__resultCheckpointId) }));
            return;
          }
          if (!isApproved(__handlerResult)) {
            __self.__interruptId_1 = __handlerResult[0].interruptId;
            const __checkpointId = getRuntimeContext().ctx.checkpoints.create(__stateStack(), __ctx, { moduleId: "stdlib/email.agency", scopeName: "sendWithMailgun", stepPath: "1" });
            __handlerResult[0].checkpointId = __checkpointId;
            __handlerResult[0].checkpoint = getRuntimeContext().ctx.checkpoints.get(__checkpointId);
            runner2.halt(__handlerResult);
            return;
          }
        }
      });
      await runner.step(2, async (runner2) => {
        __functionCompleted = true;
        runner2.halt(await __tryCall(async () => await __call(_sendWithMailgun, {
          type: "positional",
          args: [{
            "from": __stack.args.from,
            "to": __stack.args.to,
            "subject": __stack.args.subject,
            "html": __stack.args.html,
            "text": __stack.args.text,
            "cc": __stack.args.cc,
            "bcc": __stack.args.bcc,
            "replyTo": __stack.args.replyTo
          }, {
            "apiKey": __stack.args.apiKey,
            "domain": __stack.args.domain,
            "region": __stack.args.region,
            "allowList": __stack.args.allowList,
            "blockList": __stack.args.blockList
          }]
        }), {
          checkpoint: getRuntimeContext().ctx.getResultCheckpoint(),
          functionName: "sendWithMailgun",
          args: __stack.args
        }));
        return;
      });
    });
    if (runner.halted) {
      if (isFailure(runner.haltResult)) {
        runner.haltResult.retryable = runner.haltResult.retryable && __self.__retryable;
      }
      return runner.haltResult;
    }
  } 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("Function sendWithMailgun threw an exception (converted to Failure): " + __errMsg);
      if (__errStack) __log.error(__errStack);
      __ctx.statelogClient?.error?.({
        errorType: "runtimeError",
        message: __errMsg,
        functionName: "sendWithMailgun",
        retryable: __self.__retryable
      });
    }
    return failure(
      __error instanceof Error ? __error.message : String(__error),
      {
        checkpoint: getRuntimeContext().ctx.getResultCheckpoint(),
        retryable: __self.__retryable,
        functionName: "sendWithMailgun",
        args: __stack.args
      }
    );
  } finally {
    __stateStack()?.pop();
    if (__functionCompleted) {
      await callHook({
        name: "onFunctionEnd",
        data: {
          functionName: "sendWithMailgun",
          timeTaken: performance.now() - __funcStartTime
        }
      });
    }
  }
}
const sendWithMailgun = __AgencyFunction.create({
  name: "sendWithMailgun",
  module: "stdlib/email.agency",
  fn: __sendWithMailgun_impl,
  params: [{
    name: "from",
    hasDefault: false,
    defaultValue: void 0,
    variadic: false
  }, {
    name: "to",
    hasDefault: false,
    defaultValue: void 0,
    variadic: false
  }, {
    name: "subject",
    hasDefault: false,
    defaultValue: void 0,
    variadic: false
  }, {
    name: "html",
    hasDefault: true,
    defaultValue: void 0,
    variadic: false
  }, {
    name: "text",
    hasDefault: true,
    defaultValue: void 0,
    variadic: false
  }, {
    name: "cc",
    hasDefault: true,
    defaultValue: void 0,
    variadic: false
  }, {
    name: "bcc",
    hasDefault: true,
    defaultValue: void 0,
    variadic: false
  }, {
    name: "replyTo",
    hasDefault: true,
    defaultValue: void 0,
    variadic: false
  }, {
    name: "apiKey",
    hasDefault: true,
    defaultValue: void 0,
    variadic: false
  }, {
    name: "domain",
    hasDefault: true,
    defaultValue: void 0,
    variadic: false
  }, {
    name: "region",
    hasDefault: true,
    defaultValue: void 0,
    variadic: false
  }, {
    name: "allowList",
    hasDefault: true,
    defaultValue: void 0,
    variadic: false
  }, {
    name: "blockList",
    hasDefault: true,
    defaultValue: void 0,
    variadic: false
  }],
  toolDefinition: {
    name: "sendWithMailgun",
    description: `Send an email using the Mailgun API. Requires MAILGUN_API_KEY and MAILGUN_DOMAIN env vars, or pass them directly. Set allowList to restrict recipients to specific addresses. Set blockList to reject specific addresses.

  @param from - Sender email address
  @param to - Recipient email address
  @param subject - Email subject
  @param html - HTML content
  @param text - Plain text content
  @param cc - CC recipients
  @param bcc - BCC recipients
  @param replyTo - Reply-to address
  @param apiKey - Mailgun API key
  @param domain - Mailgun domain
  @param region - Mailgun region ("eu" for EU)
  @param allowList - Only allow sending to these addresses
  @param blockList - Block sending to these addresses`,
    schema: z.object({ "from": z.string(), "to": z.string(), "subject": z.string(), "html": z.string().nullable().describe("Default: "), "text": z.string().nullable().describe("Default: "), "cc": z.string().nullable().describe("Default: "), "bcc": z.string().nullable().describe("Default: "), "replyTo": z.string().nullable().describe("Default: "), "apiKey": z.string().nullable().describe("Default: "), "domain": z.string().nullable().describe("Default: "), "region": z.string().nullable().describe("Default: "), "allowList": z.array(z.string()).nullable().describe("Default: []"), "blockList": z.array(z.string()).nullable().describe("Default: []") })
  },
  safe: false,
  exported: true
}, __toolRegistry);
var stdin_default = graph;
const __sourceMap = { "stdlib/email.agency:sendWithResend": { "1": { "line": 60, "col": 2 }, "2": { "line": 66, "col": 2 } }, "stdlib/email.agency:sendWithSendGrid": { "1": { "line": 99, "col": 2 }, "2": { "line": 105, "col": 2 } }, "stdlib/email.agency:sendWithMailgun": { "1": { "line": 140, "col": 2 }, "2": { "line": 146, "col": 2 } } };
export {
  __getCheckpoints,
  __setDebugger,
  __setLLMClient,
  __setTraceFile,
  __sourceMap,
  __toolRegistry,
  approve,
  stdin_default as default,
  hasInterrupts,
  interrupt,
  isDebugger,
  isInterrupt,
  reject,
  respondToInterrupts,
  rewindFrom,
  sendWithMailgun,
  sendWithResend,
  sendWithSendGrid
};
