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 { _speak, _record, _transcribe } from "agency-lang/stdlib-lib/speech.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,
  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/speech.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/speech.agency")) {
    return;
  }
  __ctx.globals.markInitialized("stdlib/speech.agency");
}
__registerGlobalsInit("stdlib/speech.agency", __initializeGlobals);
async function __registerTopLevelCallbacks(__ctx) {
  __ctx.topLevelCallbacks = [];
}
__functionRefReviver.registry = __toolRegistry;
async function __speak_impl(text, voice = __UNSET, rate = __UNSET, outputFile = __UNSET, allowedPaths = __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/speech.agency")) {
    await __initializeGlobals(__ctx);
  }
  let __funcStartTime = performance.now();
  __stack.args["text"] = text;
  __stack.args["voice"] = voice === __UNSET ? `` : voice;
  __stack.args["rate"] = rate === __UNSET ? 0 : rate;
  __stack.args["outputFile"] = outputFile === __UNSET ? `` : outputFile;
  __stack.args["allowedPaths"] = allowedPaths === __UNSET ? [] : allowedPaths;
  __self.__retryable = __self.__retryable ?? true;
  const runner = new Runner(__ctx, __stack, { state: __stack, moduleId: "stdlib/speech.agency", scopeName: "speak", threads: __setupData.threads });
  let __resultCheckpointId = -1;
  if (__ctx._pendingArgOverrides) {
    const __overrides = __ctx._pendingArgOverrides;
    __ctx._pendingArgOverrides = void 0;
    if ("text" in __overrides) {
      text = __overrides["text"];
      __stack.args["text"] = text;
    }
    if ("voice" in __overrides) {
      voice = __overrides["voice"];
      __stack.args["voice"] = voice;
    }
    if ("rate" in __overrides) {
      rate = __overrides["rate"];
      __stack.args["rate"] = rate;
    }
    if ("outputFile" in __overrides) {
      outputFile = __overrides["outputFile"];
      __stack.args["outputFile"] = outputFile;
    }
    if ("allowedPaths" in __overrides) {
      allowedPaths = __overrides["allowedPaths"];
      __stack.args["allowedPaths"] = allowedPaths;
    }
  }
  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: "speak",
            args: {
              text,
              voice,
              rate,
              outputFile,
              allowedPaths
            },
            isBuiltin: false,
            moduleId: "stdlib/speech.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::speak", `Are you sure you want to use text-to-speech?`, {
            "textLength": __stack.args.text.length
          }, "std::speech", __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/speech.agency", scopeName: "speak", stepPath: "1" });
            __handlerResult[0].checkpointId = __checkpointId;
            __handlerResult[0].checkpoint = getRuntimeContext().ctx.checkpoints.get(__checkpointId);
            runner2.halt(__handlerResult);
            return;
          }
        }
      });
      await runner.step(2, async (runner2) => {
        __self.__retryable = false;
        const __funcResult = await __call(_speak, {
          type: "positional",
          args: [__stack.args.text, __stack.args.voice, __stack.args.rate, __stack.args.outputFile, __stack.args.allowedPaths]
        });
        if (hasInterrupts(__funcResult)) {
          await getRuntimeContext().ctx.pendingPromises.awaitAll();
          runner2.halt(__funcResult);
          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 speak threw an exception (converted to Failure): " + __errMsg);
      if (__errStack) __log.error(__errStack);
      __ctx.statelogClient?.error?.({
        errorType: "runtimeError",
        message: __errMsg,
        functionName: "speak",
        retryable: __self.__retryable
      });
    }
    return failure(
      __error instanceof Error ? __error.message : String(__error),
      {
        checkpoint: getRuntimeContext().ctx.getResultCheckpoint(),
        retryable: __self.__retryable,
        functionName: "speak",
        args: __stack.args
      }
    );
  } finally {
    __stateStack()?.pop();
    if (__functionCompleted) {
      await callHook({
        name: "onFunctionEnd",
        data: {
          functionName: "speak",
          timeTaken: performance.now() - __funcStartTime
        }
      });
    }
  }
}
const speak = __AgencyFunction.create({
  name: "speak",
  module: "stdlib/speech.agency",
  fn: __speak_impl,
  params: [{
    name: "text",
    hasDefault: false,
    defaultValue: void 0,
    variadic: false
  }, {
    name: "voice",
    hasDefault: true,
    defaultValue: void 0,
    variadic: false
  }, {
    name: "rate",
    hasDefault: true,
    defaultValue: void 0,
    variadic: false
  }, {
    name: "outputFile",
    hasDefault: true,
    defaultValue: void 0,
    variadic: false
  }, {
    name: "allowedPaths",
    hasDefault: true,
    defaultValue: void 0,
    variadic: false
  }],
  toolDefinition: {
    name: "speak",
    description: `A tool for speaking text aloud using text-to-speech. Optionally specify a voice name, rate in words per minute, and an output file to save the audio to instead of playing it. Set allowedPaths to restrict where the output file may be written.

  Cancellation: in-progress speech playback is stopped on Ctrl-C, race-loser, or time-guard abort.

  @param text - The text to speak
  @param voice - Voice name
  @param rate - Words per minute
  @param outputFile - File path to save audio to
  @param allowedPaths - Only allow saving under these path prefixes`,
    schema: z.object({ "text": z.string(), "voice": z.string().nullable().describe("Default: "), "rate": z.number().nullable().describe("Default: 0"), "outputFile": z.string().nullable().describe("Default: "), "allowedPaths": z.array(z.string()).nullable().describe("Default: []") })
  },
  safe: false,
  exported: true
}, __toolRegistry);
async function __record_impl(outputFile = __UNSET, silenceTimeout = __UNSET, allowedPaths = __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/speech.agency")) {
    await __initializeGlobals(__ctx);
  }
  let __funcStartTime = performance.now();
  __stack.args["outputFile"] = outputFile === __UNSET ? `` : outputFile;
  __stack.args["silenceTimeout"] = silenceTimeout === __UNSET ? 2e3 : silenceTimeout;
  __stack.args["allowedPaths"] = allowedPaths === __UNSET ? [] : allowedPaths;
  __self.__retryable = __self.__retryable ?? true;
  const runner = new Runner(__ctx, __stack, { state: __stack, moduleId: "stdlib/speech.agency", scopeName: "record", threads: __setupData.threads });
  let __resultCheckpointId = -1;
  if (__ctx._pendingArgOverrides) {
    const __overrides = __ctx._pendingArgOverrides;
    __ctx._pendingArgOverrides = void 0;
    if ("outputFile" in __overrides) {
      outputFile = __overrides["outputFile"];
      __stack.args["outputFile"] = outputFile;
    }
    if ("silenceTimeout" in __overrides) {
      silenceTimeout = __overrides["silenceTimeout"];
      __stack.args["silenceTimeout"] = silenceTimeout;
    }
    if ("allowedPaths" in __overrides) {
      allowedPaths = __overrides["allowedPaths"];
      __stack.args["allowedPaths"] = allowedPaths;
    }
  }
  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: "record",
            args: {
              outputFile,
              silenceTimeout,
              allowedPaths
            },
            isBuiltin: false,
            moduleId: "stdlib/speech.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::record", `Allow microphone recording?`, {}, "std::speech", __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/speech.agency", scopeName: "record", stepPath: "1" });
            __handlerResult[0].checkpointId = __checkpointId;
            __handlerResult[0].checkpoint = getRuntimeContext().ctx.checkpoints.get(__checkpointId);
            runner2.halt(__handlerResult);
            return;
          }
        }
      });
      await runner.step(2, async (runner2) => {
        __self.__retryable = false;
        __functionCompleted = true;
        runner2.halt(await __call(_record, {
          type: "positional",
          args: [__stack.args.outputFile, __stack.args.silenceTimeout, __stack.args.allowedPaths]
        }));
        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 record threw an exception (converted to Failure): " + __errMsg);
      if (__errStack) __log.error(__errStack);
      __ctx.statelogClient?.error?.({
        errorType: "runtimeError",
        message: __errMsg,
        functionName: "record",
        retryable: __self.__retryable
      });
    }
    return failure(
      __error instanceof Error ? __error.message : String(__error),
      {
        checkpoint: getRuntimeContext().ctx.getResultCheckpoint(),
        retryable: __self.__retryable,
        functionName: "record",
        args: __stack.args
      }
    );
  } finally {
    __stateStack()?.pop();
    if (__functionCompleted) {
      await callHook({
        name: "onFunctionEnd",
        data: {
          functionName: "record",
          timeTaken: performance.now() - __funcStartTime
        }
      });
    }
  }
}
const record = __AgencyFunction.create({
  name: "record",
  module: "stdlib/speech.agency",
  fn: __record_impl,
  params: [{
    name: "outputFile",
    hasDefault: true,
    defaultValue: void 0,
    variadic: false
  }, {
    name: "silenceTimeout",
    hasDefault: true,
    defaultValue: void 0,
    variadic: false
  }, {
    name: "allowedPaths",
    hasDefault: true,
    defaultValue: void 0,
    variadic: false
  }],
  toolDefinition: {
    name: "record",
    description: `Record audio from the microphone. Stops when the user presses Enter,
  or after the specified silence timeout. Set silenceTimeout to 0 to
  disable silence detection (recording stops only on Enter).

  The silenceTimeout parameter is in milliseconds, so you can use
  Agency's unit literals: record(silenceTimeout: 3s), record(silenceTimeout: 500ms).
  Set to 0 for no timeout.

  Cancellation: an in-progress recording is stopped on Ctrl-C, race-loser, or time-guard abort, surfacing as an AgencyCancelledError.

  Set allowedPaths to restrict where a non-empty outputFile may be written; an empty outputFile is auto-generated under the system temp directory and is not subject to the allow-list.

  @param outputFile - File path to save audio to (auto-generated if empty)
  @param silenceTimeout - Silence before auto-stopping in ms (0 to disable)
  @param allowedPaths - Only allow saving under these path prefixes`,
    schema: z.object({ "outputFile": z.string().nullable().describe("Default: "), "silenceTimeout": z.number().nullable().describe("Default: 2000"), "allowedPaths": z.array(z.string()).nullable().describe("Default: []") })
  },
  safe: false,
  exported: true
}, __toolRegistry);
async function __transcribe_impl(filepath, language = __UNSET, allowedPaths = __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/speech.agency")) {
    await __initializeGlobals(__ctx);
  }
  let __funcStartTime = performance.now();
  __stack.args["filepath"] = filepath;
  __stack.args["language"] = language === __UNSET ? `` : language;
  __stack.args["allowedPaths"] = allowedPaths === __UNSET ? [] : allowedPaths;
  __self.__retryable = __self.__retryable ?? true;
  const runner = new Runner(__ctx, __stack, { state: __stack, moduleId: "stdlib/speech.agency", scopeName: "transcribe", threads: __setupData.threads });
  let __resultCheckpointId = -1;
  if (__ctx._pendingArgOverrides) {
    const __overrides = __ctx._pendingArgOverrides;
    __ctx._pendingArgOverrides = void 0;
    if ("filepath" in __overrides) {
      filepath = __overrides["filepath"];
      __stack.args["filepath"] = filepath;
    }
    if ("language" in __overrides) {
      language = __overrides["language"];
      __stack.args["language"] = language;
    }
    if ("allowedPaths" in __overrides) {
      allowedPaths = __overrides["allowedPaths"];
      __stack.args["allowedPaths"] = allowedPaths;
    }
  }
  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: "transcribe",
            args: {
              filepath,
              language,
              allowedPaths
            },
            isBuiltin: false,
            moduleId: "stdlib/speech.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::transcribe", `Are you sure you want to send this audio file to the OpenAI Whisper API for transcription?`, {
            "filepath": __stack.args.filepath
          }, "std::speech", __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/speech.agency", scopeName: "transcribe", stepPath: "1" });
            __handlerResult[0].checkpointId = __checkpointId;
            __handlerResult[0].checkpoint = getRuntimeContext().ctx.checkpoints.get(__checkpointId);
            runner2.halt(__handlerResult);
            return;
          }
        }
      });
      await runner.step(2, async (runner2) => {
        __self.__retryable = false;
        __functionCompleted = true;
        runner2.halt(await __call(_transcribe, {
          type: "positional",
          args: [__stack.args.filepath, __stack.args.language, __stack.args.allowedPaths]
        }));
        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 transcribe threw an exception (converted to Failure): " + __errMsg);
      if (__errStack) __log.error(__errStack);
      __ctx.statelogClient?.error?.({
        errorType: "runtimeError",
        message: __errMsg,
        functionName: "transcribe",
        retryable: __self.__retryable
      });
    }
    return failure(
      __error instanceof Error ? __error.message : String(__error),
      {
        checkpoint: getRuntimeContext().ctx.getResultCheckpoint(),
        retryable: __self.__retryable,
        functionName: "transcribe",
        args: __stack.args
      }
    );
  } finally {
    __stateStack()?.pop();
    if (__functionCompleted) {
      await callHook({
        name: "onFunctionEnd",
        data: {
          functionName: "transcribe",
          timeTaken: performance.now() - __funcStartTime
        }
      });
    }
  }
}
const transcribe = __AgencyFunction.create({
  name: "transcribe",
  module: "stdlib/speech.agency",
  fn: __transcribe_impl,
  params: [{
    name: "filepath",
    hasDefault: false,
    defaultValue: void 0,
    variadic: false
  }, {
    name: "language",
    hasDefault: true,
    defaultValue: void 0,
    variadic: false
  }, {
    name: "allowedPaths",
    hasDefault: true,
    defaultValue: void 0,
    variadic: false
  }],
  toolDefinition: {
    name: "transcribe",
    description: `A tool for transcribing an audio file to text using OpenAI's Whisper API. Optionally specify a language code (e.g. "en") for better accuracy. Set allowedPaths to restrict which audio files may be uploaded.

  Cancellation: an in-flight Whisper upload tears down on Ctrl-C, race-loser, or time-guard abort.

  @param filepath - Path to the audio file
  @param language - Language code for better accuracy
  @param allowedPaths - Only allow reading audio files under these path prefixes`,
    schema: z.object({ "filepath": z.string(), "language": z.string().nullable().describe("Default: "), "allowedPaths": z.array(z.string()).nullable().describe("Default: []") })
  },
  safe: false,
  exported: true
}, __toolRegistry);
var stdin_default = graph;
const __sourceMap = { "stdlib/speech.agency:speak": { "1": { "line": 25, "col": 2 }, "2": { "line": 29, "col": 2 } }, "stdlib/speech.agency:record": { "1": { "line": 50, "col": 2 }, "2": { "line": 52, "col": 2 } }, "stdlib/speech.agency:transcribe": { "1": { "line": 65, "col": 2 }, "2": { "line": 69, "col": 2 } } };
export {
  __getCheckpoints,
  __setDebugger,
  __setLLMClient,
  __setTraceFile,
  __sourceMap,
  __toolRegistry,
  approve,
  stdin_default as default,
  hasInterrupts,
  interrupt,
  isDebugger,
  isInterrupt,
  record,
  reject,
  respondToInterrupts,
  rewindFrom,
  speak,
  transcribe
};
