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 { _authorizeCalendar, _listEvents, _createEvent, _updateEvent, _deleteEvent, _isCalendarAuthorized } from "agency-lang/stdlib-lib/calendar.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/calendar.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/calendar.agency")) {
    return;
  }
  __ctx.globals.markInitialized("stdlib/calendar.agency");
}
__registerGlobalsInit("stdlib/calendar.agency", __initializeGlobals);
async function __registerTopLevelCallbacks(__ctx) {
  __ctx.topLevelCallbacks = [];
}
__functionRefReviver.registry = __toolRegistry;
const CalendarEvent = z.object({ "id": z.string(), "summary": z.string(), "description": z.string(), "location": z.string(), "start": z.string(), "end": z.string(), "htmlLink": z.string() });
async function __authorizeCalendar_impl(clientId, clientSecret) {
  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/calendar.agency")) {
    await __initializeGlobals(__ctx);
  }
  let __funcStartTime = performance.now();
  __stack.args["clientId"] = clientId;
  __stack.args["clientSecret"] = clientSecret;
  __self.__retryable = __self.__retryable ?? true;
  const runner = new Runner(__ctx, __stack, { state: __stack, moduleId: "stdlib/calendar.agency", scopeName: "authorizeCalendar", threads: __setupData.threads });
  let __resultCheckpointId = -1;
  if (__ctx._pendingArgOverrides) {
    const __overrides = __ctx._pendingArgOverrides;
    __ctx._pendingArgOverrides = void 0;
    if ("clientId" in __overrides) {
      clientId = __overrides["clientId"];
      __stack.args["clientId"] = clientId;
    }
    if ("clientSecret" in __overrides) {
      clientSecret = __overrides["clientSecret"];
      __stack.args["clientSecret"] = clientSecret;
    }
  }
  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: "authorizeCalendar",
            args: {
              clientId,
              clientSecret
            },
            isBuiltin: false,
            moduleId: "stdlib/calendar.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::authorizeCalendar", `Are you sure you want to authorize access to Google Calendar?`, {
            "clientId": __stack.args.clientId
          }, "std::calendar", __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/calendar.agency", scopeName: "authorizeCalendar", 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(_authorizeCalendar, {
          type: "positional",
          args: [__stack.args.clientId, __stack.args.clientSecret]
        }), {
          checkpoint: getRuntimeContext().ctx.getResultCheckpoint(),
          functionName: "authorizeCalendar",
          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 authorizeCalendar threw an exception (converted to Failure): " + __errMsg);
      if (__errStack) __log.error(__errStack);
      __ctx.statelogClient?.error?.({
        errorType: "runtimeError",
        message: __errMsg,
        functionName: "authorizeCalendar",
        retryable: __self.__retryable
      });
    }
    return failure(
      __error instanceof Error ? __error.message : String(__error),
      {
        checkpoint: getRuntimeContext().ctx.getResultCheckpoint(),
        retryable: __self.__retryable,
        functionName: "authorizeCalendar",
        args: __stack.args
      }
    );
  } finally {
    __stateStack()?.pop();
    if (__functionCompleted) {
      await callHook({
        name: "onFunctionEnd",
        data: {
          functionName: "authorizeCalendar",
          timeTaken: performance.now() - __funcStartTime
        }
      });
    }
  }
}
const authorizeCalendar = __AgencyFunction.create({
  name: "authorizeCalendar",
  module: "stdlib/calendar.agency",
  fn: __authorizeCalendar_impl,
  params: [{
    name: "clientId",
    hasDefault: false,
    defaultValue: void 0,
    variadic: false
  }, {
    name: "clientSecret",
    hasDefault: false,
    defaultValue: void 0,
    variadic: false
  }],
  toolDefinition: {
    name: "authorizeCalendar",
    description: `Authorize access to Google Calendar. Opens a browser for the user to sign in and grant permission. Only needs to be run once \u2014 tokens are stored locally and refreshed automatically.

  @param clientId - Google OAuth client ID
  @param clientSecret - Google OAuth client secret`,
    schema: z.object({ "clientId": z.string(), "clientSecret": z.string() })
  },
  safe: false,
  exported: true
}, __toolRegistry);
async function __isCalendarAuthorized_impl() {
  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/calendar.agency")) {
    await __initializeGlobals(__ctx);
  }
  let __funcStartTime = performance.now();
  __self.__retryable = __self.__retryable ?? true;
  const runner = new Runner(__ctx, __stack, { state: __stack, moduleId: "stdlib/calendar.agency", scopeName: "isCalendarAuthorized", threads: __setupData.threads });
  let __resultCheckpointId = -1;
  if (__ctx._pendingArgOverrides) {
    const __overrides = __ctx._pendingArgOverrides;
    __ctx._pendingArgOverrides = void 0;
  }
  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: "isCalendarAuthorized",
            args: {},
            isBuiltin: false,
            moduleId: "stdlib/calendar.agency"
          }
        });
      });
      await runner.step(1, async (runner2) => {
        __functionCompleted = true;
        runner2.halt(await __call(_isCalendarAuthorized, {
          type: "positional",
          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 isCalendarAuthorized threw an exception (converted to Failure): " + __errMsg);
      if (__errStack) __log.error(__errStack);
      __ctx.statelogClient?.error?.({
        errorType: "runtimeError",
        message: __errMsg,
        functionName: "isCalendarAuthorized",
        retryable: __self.__retryable
      });
    }
    return failure(
      __error instanceof Error ? __error.message : String(__error),
      {
        checkpoint: getRuntimeContext().ctx.getResultCheckpoint(),
        retryable: __self.__retryable,
        functionName: "isCalendarAuthorized",
        args: __stack.args
      }
    );
  } finally {
    __stateStack()?.pop();
    if (__functionCompleted) {
      await callHook({
        name: "onFunctionEnd",
        data: {
          functionName: "isCalendarAuthorized",
          timeTaken: performance.now() - __funcStartTime
        }
      });
    }
  }
}
const isCalendarAuthorized = __AgencyFunction.create({
  name: "isCalendarAuthorized",
  module: "stdlib/calendar.agency",
  fn: __isCalendarAuthorized_impl,
  params: [],
  toolDefinition: {
    name: "isCalendarAuthorized",
    description: `Check if Google Calendar has been authorized. Returns true if OAuth tokens exist locally.`,
    schema: z.object({})
  },
  safe: true,
  exported: true
}, __toolRegistry);
async function __listEvents_impl(maxResults = __UNSET, timeMin = __UNSET, timeMax = __UNSET, query = __UNSET, calendarId = __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/calendar.agency")) {
    await __initializeGlobals(__ctx);
  }
  let __funcStartTime = performance.now();
  __stack.args["maxResults"] = maxResults === __UNSET ? 10 : maxResults;
  __stack.args["timeMin"] = timeMin === __UNSET ? `` : timeMin;
  __stack.args["timeMax"] = timeMax === __UNSET ? `` : timeMax;
  __stack.args["query"] = query === __UNSET ? `` : query;
  __stack.args["calendarId"] = calendarId === __UNSET ? `primary` : calendarId;
  __self.__retryable = __self.__retryable ?? true;
  const runner = new Runner(__ctx, __stack, { state: __stack, moduleId: "stdlib/calendar.agency", scopeName: "listEvents", threads: __setupData.threads });
  let __resultCheckpointId = -1;
  if (__ctx._pendingArgOverrides) {
    const __overrides = __ctx._pendingArgOverrides;
    __ctx._pendingArgOverrides = void 0;
    if ("maxResults" in __overrides) {
      maxResults = __overrides["maxResults"];
      __stack.args["maxResults"] = maxResults;
    }
    if ("timeMin" in __overrides) {
      timeMin = __overrides["timeMin"];
      __stack.args["timeMin"] = timeMin;
    }
    if ("timeMax" in __overrides) {
      timeMax = __overrides["timeMax"];
      __stack.args["timeMax"] = timeMax;
    }
    if ("query" in __overrides) {
      query = __overrides["query"];
      __stack.args["query"] = query;
    }
    if ("calendarId" in __overrides) {
      calendarId = __overrides["calendarId"];
      __stack.args["calendarId"] = calendarId;
    }
  }
  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: "listEvents",
            args: {
              maxResults,
              timeMin,
              timeMax,
              query,
              calendarId
            },
            isBuiltin: false,
            moduleId: "stdlib/calendar.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::listEvents", `Are you sure you want to read your Google Calendar events?`, {
            "maxResults": __stack.args.maxResults,
            "calendarId": __stack.args.calendarId,
            "query": __stack.args.query
          }, "std::calendar", __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/calendar.agency", scopeName: "listEvents", 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(_listEvents, {
          type: "positional",
          args: [{
            "maxResults": __stack.args.maxResults,
            "timeMin": __stack.args.timeMin,
            "timeMax": __stack.args.timeMax,
            "query": __stack.args.query,
            "calendarId": __stack.args.calendarId
          }]
        }), {
          checkpoint: getRuntimeContext().ctx.getResultCheckpoint(),
          functionName: "listEvents",
          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 listEvents threw an exception (converted to Failure): " + __errMsg);
      if (__errStack) __log.error(__errStack);
      __ctx.statelogClient?.error?.({
        errorType: "runtimeError",
        message: __errMsg,
        functionName: "listEvents",
        retryable: __self.__retryable
      });
    }
    return failure(
      __error instanceof Error ? __error.message : String(__error),
      {
        checkpoint: getRuntimeContext().ctx.getResultCheckpoint(),
        retryable: __self.__retryable,
        functionName: "listEvents",
        args: __stack.args
      }
    );
  } finally {
    __stateStack()?.pop();
    if (__functionCompleted) {
      await callHook({
        name: "onFunctionEnd",
        data: {
          functionName: "listEvents",
          timeTaken: performance.now() - __funcStartTime
        }
      });
    }
  }
}
const listEvents = __AgencyFunction.create({
  name: "listEvents",
  module: "stdlib/calendar.agency",
  fn: __listEvents_impl,
  params: [{
    name: "maxResults",
    hasDefault: true,
    defaultValue: void 0,
    variadic: false
  }, {
    name: "timeMin",
    hasDefault: true,
    defaultValue: void 0,
    variadic: false
  }, {
    name: "timeMax",
    hasDefault: true,
    defaultValue: void 0,
    variadic: false
  }, {
    name: "query",
    hasDefault: true,
    defaultValue: void 0,
    variadic: false
  }, {
    name: "calendarId",
    hasDefault: true,
    defaultValue: void 0,
    variadic: false
  }],
  toolDefinition: {
    name: "listEvents",
    description: `List upcoming events from Google Calendar. Returns an array of events with id, summary, description, location, start, end, and htmlLink. Parameters: maxResults (default 10), timeMin/timeMax (ISO 8601 datetime to filter range), query (free-text search), calendarId (default "primary").

  @param maxResults - Maximum number of events to return
  @param timeMin - Start of time range (ISO 8601)
  @param timeMax - End of time range (ISO 8601)
  @param query - Free-text search query
  @param calendarId - Calendar ID to query`,
    schema: z.object({ "maxResults": z.number().nullable().describe("Default: 10"), "timeMin": z.string().nullable().describe("Default: "), "timeMax": z.string().nullable().describe("Default: "), "query": z.string().nullable().describe("Default: "), "calendarId": z.string().nullable().describe("Default: primary") })
  },
  safe: false,
  exported: true
}, __toolRegistry);
async function __createEvent_impl(summary, start, end, description = __UNSET, location = __UNSET, calendarId = __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/calendar.agency")) {
    await __initializeGlobals(__ctx);
  }
  let __funcStartTime = performance.now();
  __stack.args["summary"] = summary;
  __stack.args["start"] = start;
  __stack.args["end"] = end;
  __stack.args["description"] = description === __UNSET ? `` : description;
  __stack.args["location"] = location === __UNSET ? `` : location;
  __stack.args["calendarId"] = calendarId === __UNSET ? `primary` : calendarId;
  __self.__retryable = __self.__retryable ?? true;
  const runner = new Runner(__ctx, __stack, { state: __stack, moduleId: "stdlib/calendar.agency", scopeName: "createEvent", threads: __setupData.threads });
  let __resultCheckpointId = -1;
  if (__ctx._pendingArgOverrides) {
    const __overrides = __ctx._pendingArgOverrides;
    __ctx._pendingArgOverrides = void 0;
    if ("summary" in __overrides) {
      summary = __overrides["summary"];
      __stack.args["summary"] = summary;
    }
    if ("start" in __overrides) {
      start = __overrides["start"];
      __stack.args["start"] = start;
    }
    if ("end" in __overrides) {
      end = __overrides["end"];
      __stack.args["end"] = end;
    }
    if ("description" in __overrides) {
      description = __overrides["description"];
      __stack.args["description"] = description;
    }
    if ("location" in __overrides) {
      location = __overrides["location"];
      __stack.args["location"] = location;
    }
    if ("calendarId" in __overrides) {
      calendarId = __overrides["calendarId"];
      __stack.args["calendarId"] = calendarId;
    }
  }
  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: "createEvent",
            args: {
              summary,
              start,
              end,
              description,
              location,
              calendarId
            },
            isBuiltin: false,
            moduleId: "stdlib/calendar.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::createEvent", `Are you sure you want to create this calendar event?`, {
            "summary": __stack.args.summary,
            "start": __stack.args.start,
            "end": __stack.args.end,
            "description": __stack.args.description,
            "location": __stack.args.location
          }, "std::calendar", __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/calendar.agency", scopeName: "createEvent", 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(_createEvent, {
          type: "positional",
          args: [{
            "summary": __stack.args.summary,
            "start": __stack.args.start,
            "end": __stack.args.end,
            "description": __stack.args.description,
            "location": __stack.args.location,
            "calendarId": __stack.args.calendarId
          }]
        }), {
          checkpoint: getRuntimeContext().ctx.getResultCheckpoint(),
          functionName: "createEvent",
          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 createEvent threw an exception (converted to Failure): " + __errMsg);
      if (__errStack) __log.error(__errStack);
      __ctx.statelogClient?.error?.({
        errorType: "runtimeError",
        message: __errMsg,
        functionName: "createEvent",
        retryable: __self.__retryable
      });
    }
    return failure(
      __error instanceof Error ? __error.message : String(__error),
      {
        checkpoint: getRuntimeContext().ctx.getResultCheckpoint(),
        retryable: __self.__retryable,
        functionName: "createEvent",
        args: __stack.args
      }
    );
  } finally {
    __stateStack()?.pop();
    if (__functionCompleted) {
      await callHook({
        name: "onFunctionEnd",
        data: {
          functionName: "createEvent",
          timeTaken: performance.now() - __funcStartTime
        }
      });
    }
  }
}
const createEvent = __AgencyFunction.create({
  name: "createEvent",
  module: "stdlib/calendar.agency",
  fn: __createEvent_impl,
  params: [{
    name: "summary",
    hasDefault: false,
    defaultValue: void 0,
    variadic: false
  }, {
    name: "start",
    hasDefault: false,
    defaultValue: void 0,
    variadic: false
  }, {
    name: "end",
    hasDefault: false,
    defaultValue: void 0,
    variadic: false
  }, {
    name: "description",
    hasDefault: true,
    defaultValue: void 0,
    variadic: false
  }, {
    name: "location",
    hasDefault: true,
    defaultValue: void 0,
    variadic: false
  }, {
    name: "calendarId",
    hasDefault: true,
    defaultValue: void 0,
    variadic: false
  }],
  toolDefinition: {
    name: "createEvent",
    description: `Create a new event on Google Calendar. Parameters: summary (title), start (ISO 8601 datetime or YYYY-MM-DD for all-day), end (same format), description (optional), location (optional), calendarId (default "primary"). Returns the created event.

  @param summary - Event title
  @param start - Start time (ISO 8601 or YYYY-MM-DD)
  @param end - End time (ISO 8601 or YYYY-MM-DD)
  @param description - Event description
  @param location - Event location
  @param calendarId - Calendar ID to create on`,
    schema: z.object({ "summary": z.string(), "start": z.string(), "end": z.string(), "description": z.string().nullable().describe("Default: "), "location": z.string().nullable().describe("Default: "), "calendarId": z.string().nullable().describe("Default: primary") })
  },
  safe: false,
  exported: true
}, __toolRegistry);
async function __updateEvent_impl(eventId, summary = __UNSET, start = __UNSET, end = __UNSET, description = __UNSET, location = __UNSET, calendarId = __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/calendar.agency")) {
    await __initializeGlobals(__ctx);
  }
  let __funcStartTime = performance.now();
  __stack.args["eventId"] = eventId;
  __stack.args["summary"] = summary === __UNSET ? `` : summary;
  __stack.args["start"] = start === __UNSET ? `` : start;
  __stack.args["end"] = end === __UNSET ? `` : end;
  __stack.args["description"] = description === __UNSET ? `` : description;
  __stack.args["location"] = location === __UNSET ? `` : location;
  __stack.args["calendarId"] = calendarId === __UNSET ? `primary` : calendarId;
  __self.__retryable = __self.__retryable ?? true;
  const runner = new Runner(__ctx, __stack, { state: __stack, moduleId: "stdlib/calendar.agency", scopeName: "updateEvent", threads: __setupData.threads });
  let __resultCheckpointId = -1;
  if (__ctx._pendingArgOverrides) {
    const __overrides = __ctx._pendingArgOverrides;
    __ctx._pendingArgOverrides = void 0;
    if ("eventId" in __overrides) {
      eventId = __overrides["eventId"];
      __stack.args["eventId"] = eventId;
    }
    if ("summary" in __overrides) {
      summary = __overrides["summary"];
      __stack.args["summary"] = summary;
    }
    if ("start" in __overrides) {
      start = __overrides["start"];
      __stack.args["start"] = start;
    }
    if ("end" in __overrides) {
      end = __overrides["end"];
      __stack.args["end"] = end;
    }
    if ("description" in __overrides) {
      description = __overrides["description"];
      __stack.args["description"] = description;
    }
    if ("location" in __overrides) {
      location = __overrides["location"];
      __stack.args["location"] = location;
    }
    if ("calendarId" in __overrides) {
      calendarId = __overrides["calendarId"];
      __stack.args["calendarId"] = calendarId;
    }
  }
  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: "updateEvent",
            args: {
              eventId,
              summary,
              start,
              end,
              description,
              location,
              calendarId
            },
            isBuiltin: false,
            moduleId: "stdlib/calendar.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::updateEvent", `Are you sure you want to update this calendar event?`, {
            "eventId": __stack.args.eventId,
            "summary": __stack.args.summary,
            "start": __stack.args.start,
            "end": __stack.args.end
          }, "std::calendar", __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/calendar.agency", scopeName: "updateEvent", 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(_updateEvent, {
          type: "positional",
          args: [{
            "eventId": __stack.args.eventId,
            "summary": __stack.args.summary,
            "start": __stack.args.start,
            "end": __stack.args.end,
            "description": __stack.args.description,
            "location": __stack.args.location,
            "calendarId": __stack.args.calendarId
          }]
        }), {
          checkpoint: getRuntimeContext().ctx.getResultCheckpoint(),
          functionName: "updateEvent",
          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 updateEvent threw an exception (converted to Failure): " + __errMsg);
      if (__errStack) __log.error(__errStack);
      __ctx.statelogClient?.error?.({
        errorType: "runtimeError",
        message: __errMsg,
        functionName: "updateEvent",
        retryable: __self.__retryable
      });
    }
    return failure(
      __error instanceof Error ? __error.message : String(__error),
      {
        checkpoint: getRuntimeContext().ctx.getResultCheckpoint(),
        retryable: __self.__retryable,
        functionName: "updateEvent",
        args: __stack.args
      }
    );
  } finally {
    __stateStack()?.pop();
    if (__functionCompleted) {
      await callHook({
        name: "onFunctionEnd",
        data: {
          functionName: "updateEvent",
          timeTaken: performance.now() - __funcStartTime
        }
      });
    }
  }
}
const updateEvent = __AgencyFunction.create({
  name: "updateEvent",
  module: "stdlib/calendar.agency",
  fn: __updateEvent_impl,
  params: [{
    name: "eventId",
    hasDefault: false,
    defaultValue: void 0,
    variadic: false
  }, {
    name: "summary",
    hasDefault: true,
    defaultValue: void 0,
    variadic: false
  }, {
    name: "start",
    hasDefault: true,
    defaultValue: void 0,
    variadic: false
  }, {
    name: "end",
    hasDefault: true,
    defaultValue: void 0,
    variadic: false
  }, {
    name: "description",
    hasDefault: true,
    defaultValue: void 0,
    variadic: false
  }, {
    name: "location",
    hasDefault: true,
    defaultValue: void 0,
    variadic: false
  }, {
    name: "calendarId",
    hasDefault: true,
    defaultValue: void 0,
    variadic: false
  }],
  toolDefinition: {
    name: "updateEvent",
    description: `Update an existing event on Google Calendar. Pass the eventId and any fields to change. Empty strings are treated as "don't change". Returns the updated event.

  @param eventId - ID of the event to update
  @param summary - New title (empty to keep)
  @param start - New start time (empty to keep)
  @param end - New end time (empty to keep)
  @param description - New description (empty to keep)
  @param location - New location (empty to keep)
  @param calendarId - Calendar ID`,
    schema: z.object({ "eventId": z.string(), "summary": z.string().nullable().describe("Default: "), "start": z.string().nullable().describe("Default: "), "end": z.string().nullable().describe("Default: "), "description": z.string().nullable().describe("Default: "), "location": z.string().nullable().describe("Default: "), "calendarId": z.string().nullable().describe("Default: primary") })
  },
  safe: false,
  exported: true
}, __toolRegistry);
async function __deleteEvent_impl(eventId, calendarId = __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/calendar.agency")) {
    await __initializeGlobals(__ctx);
  }
  let __funcStartTime = performance.now();
  __stack.args["eventId"] = eventId;
  __stack.args["calendarId"] = calendarId === __UNSET ? `primary` : calendarId;
  __self.__retryable = __self.__retryable ?? true;
  const runner = new Runner(__ctx, __stack, { state: __stack, moduleId: "stdlib/calendar.agency", scopeName: "deleteEvent", threads: __setupData.threads });
  let __resultCheckpointId = -1;
  if (__ctx._pendingArgOverrides) {
    const __overrides = __ctx._pendingArgOverrides;
    __ctx._pendingArgOverrides = void 0;
    if ("eventId" in __overrides) {
      eventId = __overrides["eventId"];
      __stack.args["eventId"] = eventId;
    }
    if ("calendarId" in __overrides) {
      calendarId = __overrides["calendarId"];
      __stack.args["calendarId"] = calendarId;
    }
  }
  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: "deleteEvent",
            args: {
              eventId,
              calendarId
            },
            isBuiltin: false,
            moduleId: "stdlib/calendar.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::deleteEvent", `Are you sure you want to delete this calendar event?`, {
            "eventId": __stack.args.eventId,
            "calendarId": __stack.args.calendarId
          }, "std::calendar", __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/calendar.agency", scopeName: "deleteEvent", 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(_deleteEvent, {
          type: "positional",
          args: [__stack.args.eventId, __stack.args.calendarId]
        }), {
          checkpoint: getRuntimeContext().ctx.getResultCheckpoint(),
          functionName: "deleteEvent",
          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 deleteEvent threw an exception (converted to Failure): " + __errMsg);
      if (__errStack) __log.error(__errStack);
      __ctx.statelogClient?.error?.({
        errorType: "runtimeError",
        message: __errMsg,
        functionName: "deleteEvent",
        retryable: __self.__retryable
      });
    }
    return failure(
      __error instanceof Error ? __error.message : String(__error),
      {
        checkpoint: getRuntimeContext().ctx.getResultCheckpoint(),
        retryable: __self.__retryable,
        functionName: "deleteEvent",
        args: __stack.args
      }
    );
  } finally {
    __stateStack()?.pop();
    if (__functionCompleted) {
      await callHook({
        name: "onFunctionEnd",
        data: {
          functionName: "deleteEvent",
          timeTaken: performance.now() - __funcStartTime
        }
      });
    }
  }
}
const deleteEvent = __AgencyFunction.create({
  name: "deleteEvent",
  module: "stdlib/calendar.agency",
  fn: __deleteEvent_impl,
  params: [{
    name: "eventId",
    hasDefault: false,
    defaultValue: void 0,
    variadic: false
  }, {
    name: "calendarId",
    hasDefault: true,
    defaultValue: void 0,
    variadic: false
  }],
  toolDefinition: {
    name: "deleteEvent",
    description: `Delete an event from Google Calendar by its event ID. Returns { deleted: true } on success.

  @param eventId - ID of the event to delete
  @param calendarId - Calendar ID`,
    schema: z.object({ "eventId": z.string(), "calendarId": z.string().nullable().describe("Default: primary") })
  },
  safe: false,
  exported: true
}, __toolRegistry);
var stdin_default = graph;
const __sourceMap = { "stdlib/calendar.agency:authorizeCalendar": { "1": { "line": 123, "col": 2 }, "2": { "line": 127, "col": 2 } }, "stdlib/calendar.agency:isCalendarAuthorized": { "1": { "line": 134, "col": 2 } }, "stdlib/calendar.agency:listEvents": { "1": { "line": 147, "col": 2 }, "2": { "line": 153, "col": 2 } }, "stdlib/calendar.agency:createEvent": { "1": { "line": 173, "col": 2 }, "2": { "line": 181, "col": 2 } }, "stdlib/calendar.agency:updateEvent": { "1": { "line": 203, "col": 2 }, "2": { "line": 210, "col": 2 } }, "stdlib/calendar.agency:deleteEvent": { "1": { "line": 228, "col": 2 }, "2": { "line": 233, "col": 2 } } };
export {
  __getCheckpoints,
  __setDebugger,
  __setLLMClient,
  __setTraceFile,
  __sourceMap,
  __toolRegistry,
  approve,
  authorizeCalendar,
  createEvent,
  stdin_default as default,
  deleteEvent,
  hasInterrupts,
  interrupt,
  isCalendarAuthorized,
  isDebugger,
  isInterrupt,
  listEvents,
  reject,
  respondToInterrupts,
  rewindFrom,
  updateEvent
};
