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 { _isAuthorized, _revokeAuth, _authorize, _getAccessToken } from "agency-lang/stdlib-lib/oauth.js";
import { fetchJSON } from "agency-lang/stdlib/http.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/oauth.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);
__registerTool(fetchJSON);
async function __initializeGlobals(__ctx) {
  if (__ctx.globals.isInitialized("stdlib/oauth.agency")) {
    return;
  }
  __ctx.globals.markInitialized("stdlib/oauth.agency");
}
__registerGlobalsInit("stdlib/oauth.agency", __initializeGlobals);
async function __registerTopLevelCallbacks(__ctx) {
  __ctx.topLevelCallbacks = [];
}
__functionRefReviver.registry = __toolRegistry;
async function __authorize_impl(name, authUrl, tokenUrl, clientId, clientSecret, scopes, port = __UNSET, extraAuthParams = __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/oauth.agency")) {
    await __initializeGlobals(__ctx);
  }
  let __funcStartTime = performance.now();
  __stack.args["name"] = name;
  __stack.args["authUrl"] = authUrl;
  __stack.args["tokenUrl"] = tokenUrl;
  __stack.args["clientId"] = clientId;
  __stack.args["clientSecret"] = clientSecret;
  __stack.args["scopes"] = scopes;
  __stack.args["port"] = port === __UNSET ? 8914 : port;
  __stack.args["extraAuthParams"] = extraAuthParams === __UNSET ? `` : extraAuthParams;
  __self.__retryable = __self.__retryable ?? true;
  const runner = new Runner(__ctx, __stack, { state: __stack, moduleId: "stdlib/oauth.agency", scopeName: "authorize", threads: __setupData.threads });
  let __resultCheckpointId = -1;
  if (__ctx._pendingArgOverrides) {
    const __overrides = __ctx._pendingArgOverrides;
    __ctx._pendingArgOverrides = void 0;
    if ("name" in __overrides) {
      name = __overrides["name"];
      __stack.args["name"] = name;
    }
    if ("authUrl" in __overrides) {
      authUrl = __overrides["authUrl"];
      __stack.args["authUrl"] = authUrl;
    }
    if ("tokenUrl" in __overrides) {
      tokenUrl = __overrides["tokenUrl"];
      __stack.args["tokenUrl"] = tokenUrl;
    }
    if ("clientId" in __overrides) {
      clientId = __overrides["clientId"];
      __stack.args["clientId"] = clientId;
    }
    if ("clientSecret" in __overrides) {
      clientSecret = __overrides["clientSecret"];
      __stack.args["clientSecret"] = clientSecret;
    }
    if ("scopes" in __overrides) {
      scopes = __overrides["scopes"];
      __stack.args["scopes"] = scopes;
    }
    if ("port" in __overrides) {
      port = __overrides["port"];
      __stack.args["port"] = port;
    }
    if ("extraAuthParams" in __overrides) {
      extraAuthParams = __overrides["extraAuthParams"];
      __stack.args["extraAuthParams"] = extraAuthParams;
    }
  }
  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: "authorize",
            args: {
              name,
              authUrl,
              tokenUrl,
              clientId,
              clientSecret,
              scopes,
              port,
              extraAuthParams
            },
            isBuiltin: false,
            moduleId: "stdlib/oauth.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::authorize", `Are you sure you want to start an OAuth authorization flow?`, {
            "name": __stack.args.name,
            "authUrl": __stack.args.authUrl,
            "scopes": __stack.args.scopes
          }, "std::oauth", __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/oauth.agency", scopeName: "authorize", 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(_authorize, {
          type: "positional",
          args: [__stack.args.name, {
            "authUrl": __stack.args.authUrl,
            "tokenUrl": __stack.args.tokenUrl,
            "clientId": __stack.args.clientId,
            "clientSecret": __stack.args.clientSecret,
            "scopes": __stack.args.scopes,
            "port": __stack.args.port,
            "extraAuthParams": __stack.args.extraAuthParams
          }]
        }), {
          checkpoint: getRuntimeContext().ctx.getResultCheckpoint(),
          functionName: "authorize",
          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 authorize threw an exception (converted to Failure): " + __errMsg);
      if (__errStack) __log.error(__errStack);
      __ctx.statelogClient?.error?.({
        errorType: "runtimeError",
        message: __errMsg,
        functionName: "authorize",
        retryable: __self.__retryable
      });
    }
    return failure(
      __error instanceof Error ? __error.message : String(__error),
      {
        checkpoint: getRuntimeContext().ctx.getResultCheckpoint(),
        retryable: __self.__retryable,
        functionName: "authorize",
        args: __stack.args
      }
    );
  } finally {
    __stateStack()?.pop();
    if (__functionCompleted) {
      await callHook({
        name: "onFunctionEnd",
        data: {
          functionName: "authorize",
          timeTaken: performance.now() - __funcStartTime
        }
      });
    }
  }
}
const authorize = __AgencyFunction.create({
  name: "authorize",
  module: "stdlib/oauth.agency",
  fn: __authorize_impl,
  params: [{
    name: "name",
    hasDefault: false,
    defaultValue: void 0,
    variadic: false
  }, {
    name: "authUrl",
    hasDefault: false,
    defaultValue: void 0,
    variadic: false
  }, {
    name: "tokenUrl",
    hasDefault: false,
    defaultValue: void 0,
    variadic: false
  }, {
    name: "clientId",
    hasDefault: false,
    defaultValue: void 0,
    variadic: false
  }, {
    name: "clientSecret",
    hasDefault: false,
    defaultValue: void 0,
    variadic: false
  }, {
    name: "scopes",
    hasDefault: false,
    defaultValue: void 0,
    variadic: false
  }, {
    name: "port",
    hasDefault: true,
    defaultValue: void 0,
    variadic: false
  }, {
    name: "extraAuthParams",
    hasDefault: true,
    defaultValue: void 0,
    variadic: false
  }],
  toolDefinition: {
    name: "authorize",
    description: `Start an OAuth 2.0 authorization flow. Opens the user's browser for consent, captures the callback, exchanges the code for tokens, and saves them locally. Only needs to be run once per provider. Parameters: name (identifier like "google-calendar"), authUrl (authorization endpoint), tokenUrl (token endpoint), clientId, clientSecret, scopes (space-separated), port (callback port, default 8914), extraAuthParams (space-separated key=value pairs for provider-specific params like "access_type=offline prompt=consent").

  @param name - Provider identifier
  @param authUrl - Authorization endpoint URL
  @param tokenUrl - Token endpoint URL
  @param clientId - OAuth client ID
  @param clientSecret - OAuth client secret
  @param scopes - Space-separated scopes
  @param port - Callback port
  @param extraAuthParams - Extra key=value pairs for the auth request`,
    schema: z.object({ "name": z.string(), "authUrl": z.string(), "tokenUrl": z.string(), "clientId": z.string(), "clientSecret": z.string(), "scopes": z.string(), "port": z.number().nullable().describe("Default: 8914"), "extraAuthParams": z.string().nullable().describe("Default: ") })
  },
  safe: false,
  exported: true
}, __toolRegistry);
async function __getAccessToken_impl(name) {
  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/oauth.agency")) {
    await __initializeGlobals(__ctx);
  }
  let __funcStartTime = performance.now();
  __stack.args["name"] = name;
  __self.__retryable = __self.__retryable ?? true;
  const runner = new Runner(__ctx, __stack, { state: __stack, moduleId: "stdlib/oauth.agency", scopeName: "getAccessToken", threads: __setupData.threads });
  let __resultCheckpointId = -1;
  if (__ctx._pendingArgOverrides) {
    const __overrides = __ctx._pendingArgOverrides;
    __ctx._pendingArgOverrides = void 0;
    if ("name" in __overrides) {
      name = __overrides["name"];
      __stack.args["name"] = name;
    }
  }
  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: "getAccessToken",
            args: {
              name
            },
            isBuiltin: false,
            moduleId: "stdlib/oauth.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::getAccessToken", `Are you sure you want to retrieve an OAuth access token? This exposes a sensitive credential.`, {
            "name": __stack.args.name
          }, "std::oauth", __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/oauth.agency", scopeName: "getAccessToken", 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(_getAccessToken, {
          type: "positional",
          args: [__stack.args.name]
        }), {
          checkpoint: getRuntimeContext().ctx.getResultCheckpoint(),
          functionName: "getAccessToken",
          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 getAccessToken threw an exception (converted to Failure): " + __errMsg);
      if (__errStack) __log.error(__errStack);
      __ctx.statelogClient?.error?.({
        errorType: "runtimeError",
        message: __errMsg,
        functionName: "getAccessToken",
        retryable: __self.__retryable
      });
    }
    return failure(
      __error instanceof Error ? __error.message : String(__error),
      {
        checkpoint: getRuntimeContext().ctx.getResultCheckpoint(),
        retryable: __self.__retryable,
        functionName: "getAccessToken",
        args: __stack.args
      }
    );
  } finally {
    __stateStack()?.pop();
    if (__functionCompleted) {
      await callHook({
        name: "onFunctionEnd",
        data: {
          functionName: "getAccessToken",
          timeTaken: performance.now() - __funcStartTime
        }
      });
    }
  }
}
const getAccessToken = __AgencyFunction.create({
  name: "getAccessToken",
  module: "stdlib/oauth.agency",
  fn: __getAccessToken_impl,
  params: [{
    name: "name",
    hasDefault: false,
    defaultValue: void 0,
    variadic: false
  }],
  toolDefinition: {
    name: "getAccessToken",
    description: `Get a valid OAuth access token for a previously authorized provider. Automatically refreshes the token if it has expired. Returns the access token string. Throws if not yet authorized.

  Cancellation: an in-flight refresh-token fetch is torn down on Ctrl-C, race-loser, or time-guard abort.`,
    schema: z.object({ "name": z.string() })
  },
  safe: false,
  exported: true
}, __toolRegistry);
async function __isAuthorized_impl(name) {
  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/oauth.agency")) {
    await __initializeGlobals(__ctx);
  }
  let __funcStartTime = performance.now();
  __stack.args["name"] = name;
  __self.__retryable = __self.__retryable ?? true;
  const runner = new Runner(__ctx, __stack, { state: __stack, moduleId: "stdlib/oauth.agency", scopeName: "isAuthorized", threads: __setupData.threads });
  let __resultCheckpointId = -1;
  if (__ctx._pendingArgOverrides) {
    const __overrides = __ctx._pendingArgOverrides;
    __ctx._pendingArgOverrides = void 0;
    if ("name" in __overrides) {
      name = __overrides["name"];
      __stack.args["name"] = name;
    }
  }
  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: "isAuthorized",
            args: {
              name
            },
            isBuiltin: false,
            moduleId: "stdlib/oauth.agency"
          }
        });
      });
      await runner.step(1, async (runner2) => {
        __functionCompleted = true;
        runner2.halt(await __call(_isAuthorized, {
          type: "positional",
          args: [__stack.args.name]
        }));
        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 isAuthorized threw an exception (converted to Failure): " + __errMsg);
      if (__errStack) __log.error(__errStack);
      __ctx.statelogClient?.error?.({
        errorType: "runtimeError",
        message: __errMsg,
        functionName: "isAuthorized",
        retryable: __self.__retryable
      });
    }
    return failure(
      __error instanceof Error ? __error.message : String(__error),
      {
        checkpoint: getRuntimeContext().ctx.getResultCheckpoint(),
        retryable: __self.__retryable,
        functionName: "isAuthorized",
        args: __stack.args
      }
    );
  } finally {
    __stateStack()?.pop();
    if (__functionCompleted) {
      await callHook({
        name: "onFunctionEnd",
        data: {
          functionName: "isAuthorized",
          timeTaken: performance.now() - __funcStartTime
        }
      });
    }
  }
}
const isAuthorized = __AgencyFunction.create({
  name: "isAuthorized",
  module: "stdlib/oauth.agency",
  fn: __isAuthorized_impl,
  params: [{
    name: "name",
    hasDefault: false,
    defaultValue: void 0,
    variadic: false
  }],
  toolDefinition: {
    name: "isAuthorized",
    description: `Check if OAuth tokens exist for a given provider name. Returns true if tokens are stored locally (does not verify they are still valid).`,
    schema: z.object({ "name": z.string() })
  },
  safe: true,
  exported: true
}, __toolRegistry);
async function __revokeAuth_impl(name) {
  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/oauth.agency")) {
    await __initializeGlobals(__ctx);
  }
  let __funcStartTime = performance.now();
  __stack.args["name"] = name;
  __self.__retryable = __self.__retryable ?? true;
  const runner = new Runner(__ctx, __stack, { state: __stack, moduleId: "stdlib/oauth.agency", scopeName: "revokeAuth", threads: __setupData.threads });
  let __resultCheckpointId = -1;
  if (__ctx._pendingArgOverrides) {
    const __overrides = __ctx._pendingArgOverrides;
    __ctx._pendingArgOverrides = void 0;
    if ("name" in __overrides) {
      name = __overrides["name"];
      __stack.args["name"] = name;
    }
  }
  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: "revokeAuth",
            args: {
              name
            },
            isBuiltin: false,
            moduleId: "stdlib/oauth.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::revokeAuth", `Are you sure you want to revoke OAuth authorization?`, {
            "name": __stack.args.name
          }, "std::oauth", __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/oauth.agency", scopeName: "revokeAuth", 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(_revokeAuth, {
          type: "positional",
          args: [__stack.args.name]
        }), {
          checkpoint: getRuntimeContext().ctx.getResultCheckpoint(),
          functionName: "revokeAuth",
          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 revokeAuth threw an exception (converted to Failure): " + __errMsg);
      if (__errStack) __log.error(__errStack);
      __ctx.statelogClient?.error?.({
        errorType: "runtimeError",
        message: __errMsg,
        functionName: "revokeAuth",
        retryable: __self.__retryable
      });
    }
    return failure(
      __error instanceof Error ? __error.message : String(__error),
      {
        checkpoint: getRuntimeContext().ctx.getResultCheckpoint(),
        retryable: __self.__retryable,
        functionName: "revokeAuth",
        args: __stack.args
      }
    );
  } finally {
    __stateStack()?.pop();
    if (__functionCompleted) {
      await callHook({
        name: "onFunctionEnd",
        data: {
          functionName: "revokeAuth",
          timeTaken: performance.now() - __funcStartTime
        }
      });
    }
  }
}
const revokeAuth = __AgencyFunction.create({
  name: "revokeAuth",
  module: "stdlib/oauth.agency",
  fn: __revokeAuth_impl,
  params: [{
    name: "name",
    hasDefault: false,
    defaultValue: void 0,
    variadic: false
  }],
  toolDefinition: {
    name: "revokeAuth",
    description: `Delete stored OAuth tokens for a provider. The user will need to run authorize again to re-authenticate.`,
    schema: z.object({ "name": z.string() })
  },
  safe: false,
  exported: true
}, __toolRegistry);
var stdin_default = graph;
const __sourceMap = { "stdlib/oauth.agency:authorize": { "1": { "line": 61, "col": 2 }, "2": { "line": 67, "col": 2 } }, "stdlib/oauth.agency:getAccessToken": { "1": { "line": 84, "col": 2 }, "2": { "line": 88, "col": 2 } }, "stdlib/oauth.agency:isAuthorized": { "1": { "line": 95, "col": 2 } }, "stdlib/oauth.agency:revokeAuth": { "1": { "line": 102, "col": 2 }, "2": { "line": 106, "col": 2 } } };
export {
  __getCheckpoints,
  __setDebugger,
  __setLLMClient,
  __setTraceFile,
  __sourceMap,
  __toolRegistry,
  approve,
  authorize,
  stdin_default as default,
  getAccessToken,
  hasInterrupts,
  interrupt,
  isAuthorized,
  isDebugger,
  isInterrupt,
  reject,
  respondToInterrupts,
  revokeAuth,
  rewindFrom
};
