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 { map } from "agency-lang/stdlib/array.js";
import { frontmatter } from "agency-lang/stdlib/markdown.js";
import { glob } from "agency-lang/stdlib/shell.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,
  __readStatic,
  __registerGlobalsInit,
  failure,
  isSuccess,
  isFailure,
  AgencyFunction as __AgencyFunction,
  __call,
  __callMethod,
  __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/skills.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(map);
__registerTool(frontmatter);
__registerTool(glob);
async function __initializeGlobals(__ctx) {
  if (__ctx.globals.isInitialized("stdlib/skills.agency")) {
    return;
  }
  __ctx.globals.markInitialized("stdlib/skills.agency");
}
__registerGlobalsInit("stdlib/skills.agency", __initializeGlobals);
async function __registerTopLevelCallbacks(__ctx) {
  __ctx.topLevelCallbacks = [];
}
__functionRefReviver.registry = __toolRegistry;
async function __readSkills_impl(dir) {
  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/skills.agency")) {
    await __initializeGlobals(__ctx);
  }
  let __funcStartTime = performance.now();
  __stack.args["dir"] = dir;
  __self.__retryable = __self.__retryable ?? true;
  const runner = new Runner(__ctx, __stack, { state: __stack, moduleId: "stdlib/skills.agency", scopeName: "readSkills", threads: __setupData.threads });
  let __resultCheckpointId = -1;
  if (__ctx._pendingArgOverrides) {
    const __overrides = __ctx._pendingArgOverrides;
    __ctx._pendingArgOverrides = void 0;
    if ("dir" in __overrides) {
      dir = __overrides["dir"];
      __stack.args["dir"] = dir;
    }
  }
  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: "readSkills",
            args: {
              dir
            },
            isBuiltin: false,
            moduleId: "stdlib/skills.agency"
          }
        });
      });
      await runner.step(1, async (runner2) => {
        __stack.locals.description = `todo`;
      });
      await runner.step(2, async (runner2) => {
        __functionCompleted = true;
        runner2.halt(await __callMethod(await __callMethod(__readStatic(read, "read", ""), "partial", {
          type: "named",
          positionalArgs: [],
          namedArgs: {
            dir: __stack.args.dir
          }
        }), "describe", {
          type: "positional",
          args: [__stack.locals.description]
        }));
        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 readSkills threw an exception (converted to Failure): " + __errMsg);
      if (__errStack) __log.error(__errStack);
      __ctx.statelogClient?.error?.({
        errorType: "runtimeError",
        message: __errMsg,
        functionName: "readSkills",
        retryable: __self.__retryable
      });
    }
    return failure(
      __error instanceof Error ? __error.message : String(__error),
      {
        checkpoint: getRuntimeContext().ctx.getResultCheckpoint(),
        retryable: __self.__retryable,
        functionName: "readSkills",
        args: __stack.args
      }
    );
  } finally {
    __stateStack()?.pop();
    if (__functionCompleted) {
      await callHook({
        name: "onFunctionEnd",
        data: {
          functionName: "readSkills",
          timeTaken: performance.now() - __funcStartTime
        }
      });
    }
  }
}
const readSkills = __AgencyFunction.create({
  name: "readSkills",
  module: "stdlib/skills.agency",
  fn: __readSkills_impl,
  params: [{
    name: "dir",
    hasDefault: false,
    defaultValue: void 0,
    variadic: false
  }],
  toolDefinition: {
    name: "readSkills",
    description: "No description provided.",
    schema: z.object({ "dir": z.string() })
  },
  safe: true,
  exported: true
}, __toolRegistry);
async function __xmlEscape_impl(s) {
  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/skills.agency")) {
    await __initializeGlobals(__ctx);
  }
  let __funcStartTime = performance.now();
  __stack.args["s"] = s;
  __self.__retryable = __self.__retryable ?? true;
  const runner = new Runner(__ctx, __stack, { state: __stack, moduleId: "stdlib/skills.agency", scopeName: "xmlEscape", threads: __setupData.threads });
  let __resultCheckpointId = -1;
  if (__ctx._pendingArgOverrides) {
    const __overrides = __ctx._pendingArgOverrides;
    __ctx._pendingArgOverrides = void 0;
    if ("s" in __overrides) {
      s = __overrides["s"];
      __stack.args["s"] = s;
    }
  }
  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: "xmlEscape",
            args: {
              s
            },
            isBuiltin: false,
            moduleId: "stdlib/skills.agency"
          }
        });
      });
      await runner.step(1, async (runner2) => {
        __stack.locals.out = __stack.args.s;
      });
      await runner.step(2, async (runner2) => {
        __stack.locals.out = await __callMethod(__stack.locals.out, "replaceAll", {
          type: "positional",
          args: [`&`, `&amp;`]
        });
      });
      await runner.step(3, async (runner2) => {
        __stack.locals.out = await __callMethod(__stack.locals.out, "replaceAll", {
          type: "positional",
          args: [`<`, `&lt;`]
        });
      });
      await runner.step(4, async (runner2) => {
        __stack.locals.out = await __callMethod(__stack.locals.out, "replaceAll", {
          type: "positional",
          args: [`>`, `&gt;`]
        });
      });
      await runner.step(5, async (runner2) => {
        __stack.locals.out = await __callMethod(__stack.locals.out, "replaceAll", {
          type: "positional",
          args: [`"`, `&quot;`]
        });
      });
      await runner.step(6, async (runner2) => {
        __stack.locals.out = await __callMethod(__stack.locals.out, "replaceAll", {
          type: "positional",
          args: [`'`, `&apos;`]
        });
      });
      await runner.step(7, async (runner2) => {
        __functionCompleted = true;
        runner2.halt(__stack.locals.out);
        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 xmlEscape threw an exception (converted to Failure): " + __errMsg);
      if (__errStack) __log.error(__errStack);
      __ctx.statelogClient?.error?.({
        errorType: "runtimeError",
        message: __errMsg,
        functionName: "xmlEscape",
        retryable: __self.__retryable
      });
    }
    return failure(
      __error instanceof Error ? __error.message : String(__error),
      {
        checkpoint: getRuntimeContext().ctx.getResultCheckpoint(),
        retryable: __self.__retryable,
        functionName: "xmlEscape",
        args: __stack.args
      }
    );
  } finally {
    __stateStack()?.pop();
    if (__functionCompleted) {
      await callHook({
        name: "onFunctionEnd",
        data: {
          functionName: "xmlEscape",
          timeTaken: performance.now() - __funcStartTime
        }
      });
    }
  }
}
const xmlEscape = __AgencyFunction.create({
  name: "xmlEscape",
  module: "stdlib/skills.agency",
  fn: __xmlEscape_impl,
  params: [{
    name: "s",
    hasDefault: false,
    defaultValue: void 0,
    variadic: false
  }],
  toolDefinition: {
    name: "xmlEscape",
    description: `Escape \`&\`, \`<\`, \`>\`, \`"\`, \`'\` so the result is safe to embed inside
  XML text or attribute values. Used before splicing frontmatter or
  filenames into the \`<available_skills>\` block \u2014 without this, a
  description containing \`&\` or a closing tag would produce malformed
  markup and could inject extra tags into the prompt.`,
    schema: z.object({ "s": z.string() })
  },
  safe: false,
  exported: false
}, __toolRegistry);
async function __describeSkill_impl(filename, fm) {
  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/skills.agency")) {
    await __initializeGlobals(__ctx);
  }
  let __funcStartTime = performance.now();
  __stack.args["filename"] = filename;
  __stack.args["fm"] = fm;
  __self.__retryable = __self.__retryable ?? true;
  const runner = new Runner(__ctx, __stack, { state: __stack, moduleId: "stdlib/skills.agency", scopeName: "describeSkill", threads: __setupData.threads });
  let __resultCheckpointId = -1;
  if (__ctx._pendingArgOverrides) {
    const __overrides = __ctx._pendingArgOverrides;
    __ctx._pendingArgOverrides = void 0;
    if ("filename" in __overrides) {
      filename = __overrides["filename"];
      __stack.args["filename"] = filename;
    }
    if ("fm" in __overrides) {
      fm = __overrides["fm"];
      __stack.args["fm"] = fm;
    }
  }
  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: "describeSkill",
            args: {
              filename,
              fm
            },
            isBuiltin: false,
            moduleId: "stdlib/skills.agency"
          }
        });
      });
      await runner.step(1, async (runner2) => {
        __stack.locals.fileX = await __call(xmlEscape, {
          type: "positional",
          args: [__stack.args.filename]
        });
        if (hasInterrupts(__stack.locals.fileX)) {
          await getRuntimeContext().ctx.pendingPromises.awaitAll();
          runner2.halt(__stack.locals.fileX);
          return;
        }
      });
      await runner.ifElse(2, [
        {
          condition: async () => await isFailure(__stack.args.fm),
          body: async (runner2) => {
            await runner2.step(0, async (runner3) => {
              __functionCompleted = true;
              runner3.halt(`  <skill>
    <name>${__stack.locals.fileX}</name>
    <description>(no frontmatter)</description>
    <location>${__stack.locals.fileX}</location>
  </skill>`);
              return;
            });
          }
        }
      ]);
      await runner.step(3, async (runner2) => {
        __stack.locals.data = __stack.args.fm.value;
      });
      await runner.step(4, async (runner2) => {
        __stack.locals.title = __stack.args.filename;
      });
      await runner.ifElse(5, [
        {
          condition: async () => __stack.locals.data.title !== null,
          body: async (runner2) => {
            await runner2.step(0, async (runner3) => {
              __stack.locals.title = __stack.locals.data.title;
            });
          }
        }
      ]);
      await runner.step(6, async (runner2) => {
        __stack.locals.description = ``;
      });
      await runner.ifElse(7, [
        {
          condition: async () => __stack.locals.data.description !== null,
          body: async (runner2) => {
            await runner2.step(0, async (runner3) => {
              __stack.locals.description = __stack.locals.data.description;
            });
          }
        }
      ]);
      await runner.step(8, async (runner2) => {
        __stack.locals.titleX = await __call(xmlEscape, {
          type: "positional",
          args: [__stack.locals.title]
        });
        if (hasInterrupts(__stack.locals.titleX)) {
          await getRuntimeContext().ctx.pendingPromises.awaitAll();
          runner2.halt(__stack.locals.titleX);
          return;
        }
      });
      await runner.step(9, async (runner2) => {
        __stack.locals.descX = await __call(xmlEscape, {
          type: "positional",
          args: [__stack.locals.description]
        });
        if (hasInterrupts(__stack.locals.descX)) {
          await getRuntimeContext().ctx.pendingPromises.awaitAll();
          runner2.halt(__stack.locals.descX);
          return;
        }
      });
      await runner.step(10, async (runner2) => {
        __functionCompleted = true;
        runner2.halt(`  <skill>
    <name>${__stack.locals.titleX}</name>
    <description>${__stack.locals.descX}</description>
    <location>${__stack.locals.fileX}</location>
  </skill>`);
        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 describeSkill threw an exception (converted to Failure): " + __errMsg);
      if (__errStack) __log.error(__errStack);
      __ctx.statelogClient?.error?.({
        errorType: "runtimeError",
        message: __errMsg,
        functionName: "describeSkill",
        retryable: __self.__retryable
      });
    }
    return failure(
      __error instanceof Error ? __error.message : String(__error),
      {
        checkpoint: getRuntimeContext().ctx.getResultCheckpoint(),
        retryable: __self.__retryable,
        functionName: "describeSkill",
        args: __stack.args
      }
    );
  } finally {
    __stateStack()?.pop();
    if (__functionCompleted) {
      await callHook({
        name: "onFunctionEnd",
        data: {
          functionName: "describeSkill",
          timeTaken: performance.now() - __funcStartTime
        }
      });
    }
  }
}
const describeSkill = __AgencyFunction.create({
  name: "describeSkill",
  module: "stdlib/skills.agency",
  fn: __describeSkill_impl,
  params: [{
    name: "filename",
    hasDefault: false,
    defaultValue: void 0,
    variadic: false
  }, {
    name: "fm",
    hasDefault: false,
    defaultValue: void 0,
    variadic: false
  }],
  toolDefinition: {
    name: "describeSkill",
    description: `Render one \`<skill>\` XML block for the skills tool description given
  a filename and the frontmatter Result returned from \`frontmatter(...)\`.
  Falls back gracefully when the file has no frontmatter or is missing
  one of title/description. All interpolated values are XML-escaped so
  metacharacters in user-authored titles / descriptions / filenames
  cannot break the surrounding markup.`,
    schema: z.object({ "filename": z.string(), "fm": z.union([z.object({ __type: z.literal("resultType"), success: z.literal(true), value: z.any() }), z.object({ __type: z.literal("resultType"), success: z.literal(false), error: z.any() })]) })
  },
  safe: false,
  exported: false
}, __toolRegistry);
async function __skillsDir_impl(dir) {
  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/skills.agency")) {
    await __initializeGlobals(__ctx);
  }
  let __funcStartTime = performance.now();
  __stack.args["dir"] = dir;
  __self.__retryable = __self.__retryable ?? true;
  const runner = new Runner(__ctx, __stack, { state: __stack, moduleId: "stdlib/skills.agency", scopeName: "skillsDir", threads: __setupData.threads });
  let __resultCheckpointId = -1;
  if (__ctx._pendingArgOverrides) {
    const __overrides = __ctx._pendingArgOverrides;
    __ctx._pendingArgOverrides = void 0;
    if ("dir" in __overrides) {
      dir = __overrides["dir"];
      __stack.args["dir"] = dir;
    }
  }
  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: "skillsDir",
            args: {
              dir
            },
            isBuiltin: false,
            moduleId: "stdlib/skills.agency"
          }
        });
      });
      await runner.step(1, async (runner2) => {
        __stack.locals.lines = [];
      });
      await runner.step(2, async (runner2) => {
        __self.__retryable = false;
        __stack.locals.pathsResult = await __call(glob, {
          type: "positional",
          args: [`*.{md,markdown}`, __stack.args.dir]
        });
        if (hasInterrupts(__stack.locals.pathsResult)) {
          await getRuntimeContext().ctx.pendingPromises.awaitAll();
          runner2.halt(__stack.locals.pathsResult);
          return;
        }
      });
      await runner.ifElse(3, [
        {
          condition: async () => await isSuccess(__stack.locals.pathsResult),
          body: async (runner2) => {
            await runner2.step(0, async (runner3) => {
              __stack.locals.paths = __stack.locals.pathsResult.value;
            });
            await runner2.step(1, async (runner3) => {
              __self.__retryable = false;
              __stack.locals.lines = await __call(map, {
                type: "named",
                positionalArgs: [__stack.locals.paths],
                namedArgs: {},
                blockArg: __AgencyFunction.create({ name: "__block_0", module: "stdlib/skills.agency", fn: async (filename) => {
                  const __bsetup = setupFunction();
                  const __bstack = __bsetup.stack;
                  const __self2 = __bstack.locals;
                  __bstack.args["filename"] = filename;
                  const runner4 = new Runner(__ctx, __bstack, { state: __bstack, moduleId: "stdlib/skills.agency", scopeName: "__block_0" });
                  try {
                    await runner4.step(0, async (runner5) => {
                    });
                    await runner4.step(1, async (runner5) => {
                      __stack.locals.__pipe_0 = await __call(read, {
                        type: "positional",
                        args: [__bstack.args.filename, __stack.args.dir]
                      });
                    });
                    __bstack.locals.fm = await runner4.pipe(2, __stack.locals.__pipe_0, async (__pipeArg) => await __call(__readStatic(frontmatter, "frontmatter", ""), {
                      type: "positional",
                      args: [__pipeArg]
                    }));
                    await runner4.step(3, async (runner5) => {
                      runner5.halt(await __call(describeSkill, {
                        type: "positional",
                        args: [__bstack.args.filename, __bstack.locals.fm]
                      }));
                      return;
                    });
                    return runner4.halted ? runner4.haltResult : void 0;
                  } finally {
                    __ctx.stateStack.pop();
                  }
                }, params: [{ name: "filename", hasDefault: false, defaultValue: void 0, variadic: false }], toolDefinition: null }, __toolRegistry)
              });
              if (hasInterrupts(__stack.locals.lines)) {
                await getRuntimeContext().ctx.pendingPromises.awaitAll();
                runner3.halt(__stack.locals.lines);
                return;
              }
            });
          }
        }
      ]);
      await runner.step(4, async (runner2) => {
        __self.__retryable = false;
      });
      await runner.step(5, async (runner2) => {
        __stack.locals.header = `Read a skill file from the skills directory '${__stack.args.dir}' by passing its <location> as \`filename\` to the tool. Available skills:
<available_skills>
`;
      });
      await runner.step(6, async (runner2) => {
        __stack.locals.footer = `
</available_skills>`;
      });
      await runner.step(7, async (runner2) => {
        __stack.locals.description = __stack.locals.header + await __callMethod(__stack.locals.lines, "join", {
          type: "positional",
          args: [`
`]
        }) + __stack.locals.footer;
      });
      await runner.step(8, async (runner2) => {
        __functionCompleted = true;
        runner2.halt(await __callMethod(await __callMethod(__readStatic(read, "read", ""), "partial", {
          type: "named",
          positionalArgs: [],
          namedArgs: {
            dir: __stack.args.dir
          }
        }), "describe", {
          type: "positional",
          args: [__stack.locals.description]
        }));
        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 skillsDir threw an exception (converted to Failure): " + __errMsg);
      if (__errStack) __log.error(__errStack);
      __ctx.statelogClient?.error?.({
        errorType: "runtimeError",
        message: __errMsg,
        functionName: "skillsDir",
        retryable: __self.__retryable
      });
    }
    return failure(
      __error instanceof Error ? __error.message : String(__error),
      {
        checkpoint: getRuntimeContext().ctx.getResultCheckpoint(),
        retryable: __self.__retryable,
        functionName: "skillsDir",
        args: __stack.args
      }
    );
  } finally {
    __stateStack()?.pop();
    if (__functionCompleted) {
      await callHook({
        name: "onFunctionEnd",
        data: {
          functionName: "skillsDir",
          timeTaken: performance.now() - __funcStartTime
        }
      });
    }
  }
}
const skillsDir = __AgencyFunction.create({
  name: "skillsDir",
  module: "stdlib/skills.agency",
  fn: __skillsDir_impl,
  params: [{
    name: "dir",
    hasDefault: false,
    defaultValue: void 0,
    variadic: false
  }],
  toolDefinition: {
    name: "skillsDir",
    description: `Build a skills tool for an LLM. Scans \`dir\` for Markdown files
  (\`.md\` and \`.markdown\`), reads each one's frontmatter title and
  description, and returns the \`read\` function partially applied with
  \`dir: dir\`. The returned tool's description lists every available
  skill so the LLM knows which filename to pass.

  @param dir - Directory containing skill Markdown files`,
    schema: z.object({ "dir": z.string() })
  },
  safe: false,
  exported: true
}, __toolRegistry);
var stdin_default = graph;
const __sourceMap = { "stdlib/skills.agency:readSkills": { "1": { "line": 8, "col": 2 }, "2": { "line": 9, "col": 2 } }, "stdlib/skills.agency:xmlEscape": { "1": { "line": 20, "col": 2 }, "2": { "line": 21, "col": 2 }, "3": { "line": 22, "col": 2 }, "4": { "line": 23, "col": 2 }, "5": { "line": 24, "col": 2 }, "6": { "line": 25, "col": 2 }, "7": { "line": 26, "col": 2 } }, "stdlib/skills.agency:describeSkill": { "1": { "line": 38, "col": 2 }, "2": { "line": 39, "col": 2 }, "3": { "line": 42, "col": 2 }, "4": { "line": 43, "col": 2 }, "5": { "line": 44, "col": 2 }, "6": { "line": 47, "col": 2 }, "7": { "line": 48, "col": 2 }, "8": { "line": 51, "col": 2 }, "9": { "line": 52, "col": 2 }, "10": { "line": 53, "col": 2 }, "2.0": { "line": 40, "col": 4 }, "5.0": { "line": 45, "col": 4 }, "7.0": { "line": 49, "col": 4 } }, "stdlib/skills.agency:skillsDir": { "1": { "line": 77, "col": 2 }, "2": { "line": 78, "col": 2 }, "3": { "line": 79, "col": 2 }, "5": { "line": 89, "col": 2 }, "6": { "line": 90, "col": 2 }, "7": { "line": 91, "col": 2 }, "8": { "line": 92, "col": 2 }, "3.0": { "line": 79, "col": 2 }, "3.1": { "line": 80, "col": 4 } }, "stdlib/skills.agency:__block_0": { "3.1.1": { "line": 84, "col": 6 }, "3.1.2": { "line": 84, "col": 6 }, "3.1.3": { "line": 85, "col": 6 } } };
export {
  __getCheckpoints,
  __setDebugger,
  __setLLMClient,
  __setTraceFile,
  __sourceMap,
  __toolRegistry,
  approve,
  stdin_default as default,
  hasInterrupts,
  interrupt,
  isDebugger,
  isInterrupt,
  readSkills,
  reject,
  respondToInterrupts,
  rewindFrom,
  skillsDir
};
