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 { _join, _resolve, _basename, _dirname, _extname, _relative, _isAbsolute } from "agency-lang/stdlib-lib/path.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,
  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/path.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/path.agency")) {
    return;
  }
  __ctx.globals.markInitialized("stdlib/path.agency");
}
__registerGlobalsInit("stdlib/path.agency", __initializeGlobals);
async function __registerTopLevelCallbacks(__ctx) {
  __ctx.topLevelCallbacks = [];
}
__functionRefReviver.registry = __toolRegistry;
async function __join_impl(parts) {
  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/path.agency")) {
    await __initializeGlobals(__ctx);
  }
  let __funcStartTime = performance.now();
  __stack.args["parts"] = parts;
  __self.__retryable = __self.__retryable ?? true;
  const runner = new Runner(__ctx, __stack, { state: __stack, moduleId: "stdlib/path.agency", scopeName: "join", threads: __setupData.threads });
  let __resultCheckpointId = -1;
  if (__ctx._pendingArgOverrides) {
    const __overrides = __ctx._pendingArgOverrides;
    __ctx._pendingArgOverrides = void 0;
    if ("parts" in __overrides) {
      parts = __overrides["parts"];
      __stack.args["parts"] = parts;
    }
  }
  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: "join",
            args: {
              parts
            },
            isBuiltin: false,
            moduleId: "stdlib/path.agency"
          }
        });
      });
      await runner.step(1, async (runner2) => {
        __functionCompleted = true;
        runner2.halt(await __call(_join, {
          type: "positional",
          args: [__stack.args.parts]
        }));
        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 join threw an exception (converted to Failure): " + __errMsg);
      if (__errStack) __log.error(__errStack);
      __ctx.statelogClient?.error?.({
        errorType: "runtimeError",
        message: __errMsg,
        functionName: "join",
        retryable: __self.__retryable
      });
    }
    return failure(
      __error instanceof Error ? __error.message : String(__error),
      {
        checkpoint: getRuntimeContext().ctx.getResultCheckpoint(),
        retryable: __self.__retryable,
        functionName: "join",
        args: __stack.args
      }
    );
  } finally {
    __stateStack()?.pop();
    if (__functionCompleted) {
      await callHook({
        name: "onFunctionEnd",
        data: {
          functionName: "join",
          timeTaken: performance.now() - __funcStartTime
        }
      });
    }
  }
}
const join = __AgencyFunction.create({
  name: "join",
  module: "stdlib/path.agency",
  fn: __join_impl,
  params: [{
    name: "parts",
    hasDefault: false,
    defaultValue: void 0,
    variadic: true
  }],
  toolDefinition: {
    name: "join",
    description: `Join path segments using the platform separator, normalizing the result.`,
    schema: z.object({ "parts": z.array(z.string()) })
  },
  safe: true,
  exported: true
}, __toolRegistry);
async function __resolve_impl(parts) {
  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/path.agency")) {
    await __initializeGlobals(__ctx);
  }
  let __funcStartTime = performance.now();
  __stack.args["parts"] = parts;
  __self.__retryable = __self.__retryable ?? true;
  const runner = new Runner(__ctx, __stack, { state: __stack, moduleId: "stdlib/path.agency", scopeName: "resolve", threads: __setupData.threads });
  let __resultCheckpointId = -1;
  if (__ctx._pendingArgOverrides) {
    const __overrides = __ctx._pendingArgOverrides;
    __ctx._pendingArgOverrides = void 0;
    if ("parts" in __overrides) {
      parts = __overrides["parts"];
      __stack.args["parts"] = parts;
    }
  }
  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: "resolve",
            args: {
              parts
            },
            isBuiltin: false,
            moduleId: "stdlib/path.agency"
          }
        });
      });
      await runner.step(1, async (runner2) => {
        __functionCompleted = true;
        runner2.halt(await __call(_resolve, {
          type: "positional",
          args: [__stack.args.parts]
        }));
        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 resolve threw an exception (converted to Failure): " + __errMsg);
      if (__errStack) __log.error(__errStack);
      __ctx.statelogClient?.error?.({
        errorType: "runtimeError",
        message: __errMsg,
        functionName: "resolve",
        retryable: __self.__retryable
      });
    }
    return failure(
      __error instanceof Error ? __error.message : String(__error),
      {
        checkpoint: getRuntimeContext().ctx.getResultCheckpoint(),
        retryable: __self.__retryable,
        functionName: "resolve",
        args: __stack.args
      }
    );
  } finally {
    __stateStack()?.pop();
    if (__functionCompleted) {
      await callHook({
        name: "onFunctionEnd",
        data: {
          functionName: "resolve",
          timeTaken: performance.now() - __funcStartTime
        }
      });
    }
  }
}
const resolve = __AgencyFunction.create({
  name: "resolve",
  module: "stdlib/path.agency",
  fn: __resolve_impl,
  params: [{
    name: "parts",
    hasDefault: false,
    defaultValue: void 0,
    variadic: true
  }],
  toolDefinition: {
    name: "resolve",
    description: `Resolve path segments into an absolute path, relative to the current working directory.`,
    schema: z.object({ "parts": z.array(z.string()) })
  },
  safe: true,
  exported: true
}, __toolRegistry);
async function __basename_impl(p, ext = __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/path.agency")) {
    await __initializeGlobals(__ctx);
  }
  let __funcStartTime = performance.now();
  __stack.args["p"] = p;
  __stack.args["ext"] = ext === __UNSET ? `` : ext;
  __self.__retryable = __self.__retryable ?? true;
  const runner = new Runner(__ctx, __stack, { state: __stack, moduleId: "stdlib/path.agency", scopeName: "basename", threads: __setupData.threads });
  let __resultCheckpointId = -1;
  if (__ctx._pendingArgOverrides) {
    const __overrides = __ctx._pendingArgOverrides;
    __ctx._pendingArgOverrides = void 0;
    if ("p" in __overrides) {
      p = __overrides["p"];
      __stack.args["p"] = p;
    }
    if ("ext" in __overrides) {
      ext = __overrides["ext"];
      __stack.args["ext"] = ext;
    }
  }
  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: "basename",
            args: {
              p,
              ext
            },
            isBuiltin: false,
            moduleId: "stdlib/path.agency"
          }
        });
      });
      await runner.step(1, async (runner2) => {
        __functionCompleted = true;
        runner2.halt(await __call(_basename, {
          type: "positional",
          args: [__stack.args.p, __stack.args.ext]
        }));
        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 basename threw an exception (converted to Failure): " + __errMsg);
      if (__errStack) __log.error(__errStack);
      __ctx.statelogClient?.error?.({
        errorType: "runtimeError",
        message: __errMsg,
        functionName: "basename",
        retryable: __self.__retryable
      });
    }
    return failure(
      __error instanceof Error ? __error.message : String(__error),
      {
        checkpoint: getRuntimeContext().ctx.getResultCheckpoint(),
        retryable: __self.__retryable,
        functionName: "basename",
        args: __stack.args
      }
    );
  } finally {
    __stateStack()?.pop();
    if (__functionCompleted) {
      await callHook({
        name: "onFunctionEnd",
        data: {
          functionName: "basename",
          timeTaken: performance.now() - __funcStartTime
        }
      });
    }
  }
}
const basename = __AgencyFunction.create({
  name: "basename",
  module: "stdlib/path.agency",
  fn: __basename_impl,
  params: [{
    name: "p",
    hasDefault: false,
    defaultValue: void 0,
    variadic: false
  }, {
    name: "ext",
    hasDefault: true,
    defaultValue: void 0,
    variadic: false
  }],
  toolDefinition: {
    name: "basename",
    description: `Return the last portion of a path. If ext is given and the path ends with it, ext is trimmed off.

  @param p - The file path
  @param ext - Extension to strip from the result`,
    schema: z.object({ "p": z.string(), "ext": z.string().nullable().describe("Default: ") })
  },
  safe: true,
  exported: true
}, __toolRegistry);
async function __dirname_impl(p) {
  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/path.agency")) {
    await __initializeGlobals(__ctx);
  }
  let __funcStartTime = performance.now();
  __stack.args["p"] = p;
  __self.__retryable = __self.__retryable ?? true;
  const runner = new Runner(__ctx, __stack, { state: __stack, moduleId: "stdlib/path.agency", scopeName: "dirname", threads: __setupData.threads });
  let __resultCheckpointId = -1;
  if (__ctx._pendingArgOverrides) {
    const __overrides = __ctx._pendingArgOverrides;
    __ctx._pendingArgOverrides = void 0;
    if ("p" in __overrides) {
      p = __overrides["p"];
      __stack.args["p"] = p;
    }
  }
  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: "dirname",
            args: {
              p
            },
            isBuiltin: false,
            moduleId: "stdlib/path.agency"
          }
        });
      });
      await runner.step(1, async (runner2) => {
        __functionCompleted = true;
        runner2.halt(await __call(_dirname, {
          type: "positional",
          args: [__stack.args.p]
        }));
        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 dirname threw an exception (converted to Failure): " + __errMsg);
      if (__errStack) __log.error(__errStack);
      __ctx.statelogClient?.error?.({
        errorType: "runtimeError",
        message: __errMsg,
        functionName: "dirname",
        retryable: __self.__retryable
      });
    }
    return failure(
      __error instanceof Error ? __error.message : String(__error),
      {
        checkpoint: getRuntimeContext().ctx.getResultCheckpoint(),
        retryable: __self.__retryable,
        functionName: "dirname",
        args: __stack.args
      }
    );
  } finally {
    __stateStack()?.pop();
    if (__functionCompleted) {
      await callHook({
        name: "onFunctionEnd",
        data: {
          functionName: "dirname",
          timeTaken: performance.now() - __funcStartTime
        }
      });
    }
  }
}
const dirname = __AgencyFunction.create({
  name: "dirname",
  module: "stdlib/path.agency",
  fn: __dirname_impl,
  params: [{
    name: "p",
    hasDefault: false,
    defaultValue: void 0,
    variadic: false
  }],
  toolDefinition: {
    name: "dirname",
    description: `Return the directory portion of a path.`,
    schema: z.object({ "p": z.string() })
  },
  safe: true,
  exported: true
}, __toolRegistry);
async function __extname_impl(p) {
  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/path.agency")) {
    await __initializeGlobals(__ctx);
  }
  let __funcStartTime = performance.now();
  __stack.args["p"] = p;
  __self.__retryable = __self.__retryable ?? true;
  const runner = new Runner(__ctx, __stack, { state: __stack, moduleId: "stdlib/path.agency", scopeName: "extname", threads: __setupData.threads });
  let __resultCheckpointId = -1;
  if (__ctx._pendingArgOverrides) {
    const __overrides = __ctx._pendingArgOverrides;
    __ctx._pendingArgOverrides = void 0;
    if ("p" in __overrides) {
      p = __overrides["p"];
      __stack.args["p"] = p;
    }
  }
  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: "extname",
            args: {
              p
            },
            isBuiltin: false,
            moduleId: "stdlib/path.agency"
          }
        });
      });
      await runner.step(1, async (runner2) => {
        __functionCompleted = true;
        runner2.halt(await __call(_extname, {
          type: "positional",
          args: [__stack.args.p]
        }));
        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 extname threw an exception (converted to Failure): " + __errMsg);
      if (__errStack) __log.error(__errStack);
      __ctx.statelogClient?.error?.({
        errorType: "runtimeError",
        message: __errMsg,
        functionName: "extname",
        retryable: __self.__retryable
      });
    }
    return failure(
      __error instanceof Error ? __error.message : String(__error),
      {
        checkpoint: getRuntimeContext().ctx.getResultCheckpoint(),
        retryable: __self.__retryable,
        functionName: "extname",
        args: __stack.args
      }
    );
  } finally {
    __stateStack()?.pop();
    if (__functionCompleted) {
      await callHook({
        name: "onFunctionEnd",
        data: {
          functionName: "extname",
          timeTaken: performance.now() - __funcStartTime
        }
      });
    }
  }
}
const extname = __AgencyFunction.create({
  name: "extname",
  module: "stdlib/path.agency",
  fn: __extname_impl,
  params: [{
    name: "p",
    hasDefault: false,
    defaultValue: void 0,
    variadic: false
  }],
  toolDefinition: {
    name: "extname",
    description: `Return the extension of a path (including the leading dot), or an empty string if there is none.`,
    schema: z.object({ "p": z.string() })
  },
  safe: true,
  exported: true
}, __toolRegistry);
async function __relative_impl(from, to) {
  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/path.agency")) {
    await __initializeGlobals(__ctx);
  }
  let __funcStartTime = performance.now();
  __stack.args["from"] = from;
  __stack.args["to"] = to;
  __self.__retryable = __self.__retryable ?? true;
  const runner = new Runner(__ctx, __stack, { state: __stack, moduleId: "stdlib/path.agency", scopeName: "relative", threads: __setupData.threads });
  let __resultCheckpointId = -1;
  if (__ctx._pendingArgOverrides) {
    const __overrides = __ctx._pendingArgOverrides;
    __ctx._pendingArgOverrides = void 0;
    if ("from" in __overrides) {
      from = __overrides["from"];
      __stack.args["from"] = from;
    }
    if ("to" in __overrides) {
      to = __overrides["to"];
      __stack.args["to"] = to;
    }
  }
  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: "relative",
            args: {
              from,
              to
            },
            isBuiltin: false,
            moduleId: "stdlib/path.agency"
          }
        });
      });
      await runner.step(1, async (runner2) => {
        __functionCompleted = true;
        runner2.halt(await __call(_relative, {
          type: "positional",
          args: [__stack.args.from, __stack.args.to]
        }));
        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 relative threw an exception (converted to Failure): " + __errMsg);
      if (__errStack) __log.error(__errStack);
      __ctx.statelogClient?.error?.({
        errorType: "runtimeError",
        message: __errMsg,
        functionName: "relative",
        retryable: __self.__retryable
      });
    }
    return failure(
      __error instanceof Error ? __error.message : String(__error),
      {
        checkpoint: getRuntimeContext().ctx.getResultCheckpoint(),
        retryable: __self.__retryable,
        functionName: "relative",
        args: __stack.args
      }
    );
  } finally {
    __stateStack()?.pop();
    if (__functionCompleted) {
      await callHook({
        name: "onFunctionEnd",
        data: {
          functionName: "relative",
          timeTaken: performance.now() - __funcStartTime
        }
      });
    }
  }
}
const relative = __AgencyFunction.create({
  name: "relative",
  module: "stdlib/path.agency",
  fn: __relative_impl,
  params: [{
    name: "from",
    hasDefault: false,
    defaultValue: void 0,
    variadic: false
  }, {
    name: "to",
    hasDefault: false,
    defaultValue: void 0,
    variadic: false
  }],
  toolDefinition: {
    name: "relative",
    description: `Return the relative path from 'from' to 'to'.

  @param from - The starting path
  @param to - The target path`,
    schema: z.object({ "from": z.string(), "to": z.string() })
  },
  safe: true,
  exported: true
}, __toolRegistry);
async function __isAbsolute_impl(p) {
  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/path.agency")) {
    await __initializeGlobals(__ctx);
  }
  let __funcStartTime = performance.now();
  __stack.args["p"] = p;
  __self.__retryable = __self.__retryable ?? true;
  const runner = new Runner(__ctx, __stack, { state: __stack, moduleId: "stdlib/path.agency", scopeName: "isAbsolute", threads: __setupData.threads });
  let __resultCheckpointId = -1;
  if (__ctx._pendingArgOverrides) {
    const __overrides = __ctx._pendingArgOverrides;
    __ctx._pendingArgOverrides = void 0;
    if ("p" in __overrides) {
      p = __overrides["p"];
      __stack.args["p"] = p;
    }
  }
  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: "isAbsolute",
            args: {
              p
            },
            isBuiltin: false,
            moduleId: "stdlib/path.agency"
          }
        });
      });
      await runner.step(1, async (runner2) => {
        __functionCompleted = true;
        runner2.halt(await __call(_isAbsolute, {
          type: "positional",
          args: [__stack.args.p]
        }));
        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 isAbsolute threw an exception (converted to Failure): " + __errMsg);
      if (__errStack) __log.error(__errStack);
      __ctx.statelogClient?.error?.({
        errorType: "runtimeError",
        message: __errMsg,
        functionName: "isAbsolute",
        retryable: __self.__retryable
      });
    }
    return failure(
      __error instanceof Error ? __error.message : String(__error),
      {
        checkpoint: getRuntimeContext().ctx.getResultCheckpoint(),
        retryable: __self.__retryable,
        functionName: "isAbsolute",
        args: __stack.args
      }
    );
  } finally {
    __stateStack()?.pop();
    if (__functionCompleted) {
      await callHook({
        name: "onFunctionEnd",
        data: {
          functionName: "isAbsolute",
          timeTaken: performance.now() - __funcStartTime
        }
      });
    }
  }
}
const isAbsolute = __AgencyFunction.create({
  name: "isAbsolute",
  module: "stdlib/path.agency",
  fn: __isAbsolute_impl,
  params: [{
    name: "p",
    hasDefault: false,
    defaultValue: void 0,
    variadic: false
  }],
  toolDefinition: {
    name: "isAbsolute",
    description: `Return true if the path is absolute.`,
    schema: z.object({ "p": z.string() })
  },
  safe: true,
  exported: true
}, __toolRegistry);
var stdin_default = graph;
const __sourceMap = { "stdlib/path.agency:join": { "1": { "line": 6, "col": 2 } }, "stdlib/path.agency:resolve": { "1": { "line": 13, "col": 2 } }, "stdlib/path.agency:basename": { "1": { "line": 23, "col": 2 } }, "stdlib/path.agency:dirname": { "1": { "line": 30, "col": 2 } }, "stdlib/path.agency:extname": { "1": { "line": 37, "col": 2 } }, "stdlib/path.agency:relative": { "1": { "line": 47, "col": 2 } }, "stdlib/path.agency:isAbsolute": { "1": { "line": 54, "col": 2 } } };
export {
  __getCheckpoints,
  __setDebugger,
  __setLLMClient,
  __setTraceFile,
  __sourceMap,
  __toolRegistry,
  approve,
  basename,
  stdin_default as default,
  dirname,
  extname,
  hasInterrupts,
  interrupt,
  isAbsolute,
  isDebugger,
  isInterrupt,
  join,
  reject,
  relative,
  resolve,
  respondToInterrupts,
  rewindFrom
};
