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 { _parseMarkdown, _walkMarkdown, _renderMarkdownForCli } from "agency-lang/stdlib-lib/markdown.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,
  success,
  failure,
  isFailure,
  AgencyFunction as __AgencyFunction,
  __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/markdown.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/markdown.agency")) {
    return;
  }
  __ctx.globals.markInitialized("stdlib/markdown.agency");
}
__registerGlobalsInit("stdlib/markdown.agency", __initializeGlobals);
async function __registerTopLevelCallbacks(__ctx) {
  __ctx.topLevelCallbacks = [];
}
__functionRefReviver.registry = __toolRegistry;
const InlineText = z.object({ "type": z.literal("inline-text"), "content": z.string() });
const InlineSoftBreak = z.object({ "type": z.literal("inline-soft-break") });
const InlineHardBreak = z.object({ "type": z.literal("inline-hard-break") });
const InlineBold = z.object({ "type": z.literal("inline-bold"), "content": z.array(z.any()) });
const InlineItalic = z.object({ "type": z.literal("inline-italic"), "content": z.array(z.any()) });
const InlineBoldItalic = z.object({ "type": z.literal("inline-bold-italic"), "content": z.array(z.any()) });
const InlineStrike = z.object({ "type": z.literal("inline-strike"), "content": z.array(z.any()) });
const InlineCode = z.object({ "type": z.literal("inline-code"), "content": z.string() });
const InlineLink = z.object({ "type": z.literal("inline-link"), "content": z.array(z.any()), "url": z.string(), "title": z.union([z.string(), z.null()]) });
const Image = z.object({ "type": z.literal("image"), "url": z.string(), "alt": z.string(), "title": z.union([z.string(), z.null()]) });
const InlineRefLink = z.object({ "type": z.literal("inline-ref-link"), "text": z.string(), "id": z.string() });
const InlineRefImage = z.object({ "type": z.literal("inline-ref-image"), "alt": z.string(), "id": z.string() });
const InlineFootnoteRef = z.object({ "type": z.literal("inline-footnote-ref"), "id": z.string(), "content": z.union([z.string(), z.null()]) });
const InlineHTML = z.object({ "type": z.literal("inline-html"), "content": z.string() });
const Paragraph = z.object({ "type": z.literal("paragraph"), "content": z.array(z.any()) });
const Heading = z.object({ "type": z.literal("heading"), "level": z.number(), "content": z.array(z.any()) });
const CodeBlock = z.object({ "type": z.literal("code-block"), "content": z.string(), "language": z.union([z.string(), z.null()]) });
const BlockQuote = z.object({ "type": z.literal("block-quote"), "content": z.array(z.any()) });
const ListItem = z.object({ "content": z.array(z.any()), "sublist": z.union([z.any(), z.null()]), "checked": z.union([z.boolean(), z.null()]) });
const List = z.object({ "type": z.literal("list"), "ordered": z.boolean(), "start": z.number(), "items": z.array(ListItem) });
const HorizontalRule = z.object({ "type": z.literal("horizontal-rule") });
const Alignment = z.union([z.literal("left"), z.literal("right"), z.literal("center"), z.null()]);
const Table = z.object({ "type": z.literal("table"), "headers": z.array(z.string()), "alignments": z.array(Alignment), "rows": z.array(z.array(z.string())) });
const LinkDef = z.object({ "type": z.literal("link-definition"), "id": z.string(), "url": z.string(), "title": z.union([z.string(), z.null()]) });
const FootnoteDef = z.object({ "type": z.literal("footnote-definition"), "id": z.string(), "content": z.string() });
const HTMLBlock = z.object({ "type": z.literal("html-block"), "content": z.string() });
const Frontmatter = z.object({ "type": z.literal("frontmatter"), "data": z.record(z.string(), z.any()) });
const ParseResult = z.object({ "success": z.boolean(), "blocks": z.array(z.any()), "error": z.string(), "rest": z.string() });
async function __parse_impl(input2) {
  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/markdown.agency")) {
    await __initializeGlobals(__ctx);
  }
  let __funcStartTime = performance.now();
  __stack.args["input"] = input2;
  __self.__retryable = __self.__retryable ?? true;
  const runner = new Runner(__ctx, __stack, { state: __stack, moduleId: "stdlib/markdown.agency", scopeName: "parse", threads: __setupData.threads });
  let __resultCheckpointId = -1;
  if (__ctx._pendingArgOverrides) {
    const __overrides = __ctx._pendingArgOverrides;
    __ctx._pendingArgOverrides = void 0;
    if ("input" in __overrides) {
      input2 = __overrides["input"];
      __stack.args["input"] = input2;
    }
  }
  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: "parse",
            args: {
              input: input2
            },
            isBuiltin: false,
            moduleId: "stdlib/markdown.agency"
          }
        });
      });
      await runner.step(1, async (runner2) => {
        __functionCompleted = true;
        runner2.halt(await __call(_parseMarkdown, {
          type: "positional",
          args: [__stack.args.input]
        }));
        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 parse threw an exception (converted to Failure): " + __errMsg);
      if (__errStack) __log.error(__errStack);
      __ctx.statelogClient?.error?.({
        errorType: "runtimeError",
        message: __errMsg,
        functionName: "parse",
        retryable: __self.__retryable
      });
    }
    return failure(
      __error instanceof Error ? __error.message : String(__error),
      {
        checkpoint: getRuntimeContext().ctx.getResultCheckpoint(),
        retryable: __self.__retryable,
        functionName: "parse",
        args: __stack.args
      }
    );
  } finally {
    __stateStack()?.pop();
    if (__functionCompleted) {
      await callHook({
        name: "onFunctionEnd",
        data: {
          functionName: "parse",
          timeTaken: performance.now() - __funcStartTime
        }
      });
    }
  }
}
const parse = __AgencyFunction.create({
  name: "parse",
  module: "stdlib/markdown.agency",
  fn: __parse_impl,
  params: [{
    name: "input",
    hasDefault: false,
    defaultValue: void 0,
    variadic: false
  }],
  toolDefinition: {
    name: "parse",
    description: `Parse a Markdown string into a structured AST. Returns an object with
  \`success\` (true if parsing finished cleanly), \`blocks\` (an array of
  block-level nodes such as Paragraph, Heading, CodeBlock, List, Table,
  BlockQuote, HorizontalRule, HTMLBlock, FootnoteDef, Frontmatter), an
  \`error\` message (empty on success), and \`rest\` (unconsumed input).

  Each block is tagged with a \`type\` discriminator that you can switch on.
  Inline nodes inside blocks (like InlineBold or InlineLink) are also
  tagged with \`type\`.

  @param input - The Markdown source text to parse`,
    schema: z.object({ "input": z.string() })
  },
  safe: true,
  exported: true
}, __toolRegistry);
async function __frontmatter_impl(input2) {
  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/markdown.agency")) {
    await __initializeGlobals(__ctx);
  }
  let __funcStartTime = performance.now();
  __stack.args["input"] = input2;
  __self.__retryable = __self.__retryable ?? true;
  const runner = new Runner(__ctx, __stack, { state: __stack, moduleId: "stdlib/markdown.agency", scopeName: "frontmatter", threads: __setupData.threads });
  let __resultCheckpointId = -1;
  if (__ctx._pendingArgOverrides) {
    const __overrides = __ctx._pendingArgOverrides;
    __ctx._pendingArgOverrides = void 0;
    if ("input" in __overrides) {
      input2 = __overrides["input"];
      __stack.args["input"] = input2;
    }
  }
  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: "frontmatter",
            args: {
              input: input2
            },
            isBuiltin: false,
            moduleId: "stdlib/markdown.agency"
          }
        });
      });
      await runner.step(1, async (runner2) => {
        __stack.locals.result = await __call(_parseMarkdown, {
          type: "positional",
          args: [__stack.args.input]
        });
        if (hasInterrupts(__stack.locals.result)) {
          await getRuntimeContext().ctx.pendingPromises.awaitAll();
          runner2.halt(__stack.locals.result);
          return;
        }
      });
      await runner.ifElse(2, [
        {
          condition: async () => !__stack.locals.result.success,
          body: async (runner2) => {
            await runner2.step(0, async (runner3) => {
              __functionCompleted = true;
              runner3.halt(failure(__stack.locals.result.error, { checkpoint: getRuntimeContext().ctx.getResultCheckpoint(), functionName: "frontmatter", args: __stack.args }));
              return;
            });
          }
        }
      ]);
      await runner.loop(3, __stack.locals.result.blocks, async (block, _, runner2) => {
        await runner2.ifElse(0, [
          {
            condition: async () => block.type === `frontmatter`,
            body: async (runner3) => {
              await runner3.step(0, async (runner4) => {
                __functionCompleted = true;
                runner4.halt(await success(block.data));
                return;
              });
            }
          }
        ]);
      });
      await runner.step(4, async (runner2) => {
        __functionCompleted = true;
        runner2.halt(failure(`no frontmatter`, { checkpoint: getRuntimeContext().ctx.getResultCheckpoint(), functionName: "frontmatter", 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 frontmatter threw an exception (converted to Failure): " + __errMsg);
      if (__errStack) __log.error(__errStack);
      __ctx.statelogClient?.error?.({
        errorType: "runtimeError",
        message: __errMsg,
        functionName: "frontmatter",
        retryable: __self.__retryable
      });
    }
    return failure(
      __error instanceof Error ? __error.message : String(__error),
      {
        checkpoint: getRuntimeContext().ctx.getResultCheckpoint(),
        retryable: __self.__retryable,
        functionName: "frontmatter",
        args: __stack.args
      }
    );
  } finally {
    __stateStack()?.pop();
    if (__functionCompleted) {
      await callHook({
        name: "onFunctionEnd",
        data: {
          functionName: "frontmatter",
          timeTaken: performance.now() - __funcStartTime
        }
      });
    }
  }
}
const frontmatter = __AgencyFunction.create({
  name: "frontmatter",
  module: "stdlib/markdown.agency",
  fn: __frontmatter_impl,
  params: [{
    name: "input",
    hasDefault: false,
    defaultValue: void 0,
    variadic: false
  }],
  toolDefinition: {
    name: "frontmatter",
    description: `Extract just the YAML-style frontmatter block from a Markdown string.
  Returns \`success(data)\` where \`data\` is a \`Record<string, any>\` of the
  parsed frontmatter fields, or \`failure(...)\` if the document has no
  frontmatter or the parse failed.

  Useful for chaining with the pipe operator, e.g.
  \`read(filename, dir) |> frontmatter\`.

  @param input - The Markdown source text to parse`,
    schema: z.object({ "input": z.string() })
  },
  safe: true,
  exported: true
}, __toolRegistry);
async function __walk_impl(blocks, block) {
  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/markdown.agency")) {
    await __initializeGlobals(__ctx);
  }
  let __funcStartTime = performance.now();
  __stack.args["blocks"] = blocks;
  __stack.args["block"] = block;
  __self.__retryable = __self.__retryable ?? true;
  const runner = new Runner(__ctx, __stack, { state: __stack, moduleId: "stdlib/markdown.agency", scopeName: "walk", threads: __setupData.threads });
  let __resultCheckpointId = -1;
  if (__ctx._pendingArgOverrides) {
    const __overrides = __ctx._pendingArgOverrides;
    __ctx._pendingArgOverrides = void 0;
    if ("blocks" in __overrides) {
      blocks = __overrides["blocks"];
      __stack.args["blocks"] = blocks;
    }
    if ("block" in __overrides) {
      block = __overrides["block"];
      __stack.args["block"] = block;
    }
  }
  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: "walk",
            args: {
              blocks,
              block
            },
            isBuiltin: false,
            moduleId: "stdlib/markdown.agency"
          }
        });
      });
      await runner.step(1, async (runner2) => {
        __functionCompleted = true;
        runner2.halt(await __call(_walkMarkdown, {
          type: "positional",
          args: [__stack.args.blocks, __stack.args.block]
        }));
        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 walk threw an exception (converted to Failure): " + __errMsg);
      if (__errStack) __log.error(__errStack);
      __ctx.statelogClient?.error?.({
        errorType: "runtimeError",
        message: __errMsg,
        functionName: "walk",
        retryable: __self.__retryable
      });
    }
    return failure(
      __error instanceof Error ? __error.message : String(__error),
      {
        checkpoint: getRuntimeContext().ctx.getResultCheckpoint(),
        retryable: __self.__retryable,
        functionName: "walk",
        args: __stack.args
      }
    );
  } finally {
    __stateStack()?.pop();
    if (__functionCompleted) {
      await callHook({
        name: "onFunctionEnd",
        data: {
          functionName: "walk",
          timeTaken: performance.now() - __funcStartTime
        }
      });
    }
  }
}
const walk = __AgencyFunction.create({
  name: "walk",
  module: "stdlib/markdown.agency",
  fn: __walk_impl,
  params: [{
    name: "blocks",
    hasDefault: false,
    defaultValue: void 0,
    variadic: false
  }, {
    name: "block",
    hasDefault: false,
    defaultValue: void 0,
    variadic: false
  }],
  toolDefinition: {
    name: "walk",
    description: `Walk a Markdown AST top-down, calling \`block\` on every block and inline
  node. The block receives the node as an object and returns a (possibly
  new) node \u2014 children of the returned node are then walked recursively.
  Returns the transformed array of block nodes. The input AST is not
  mutated.

  Typically used with the trailing-block syntax:

  \`\`\`ts
  const result = parse(input)
  const transformed = walk(result.blocks) as node {
    if (node.type == "code-block") {
      return { ...node, content: highlight(node.content, node.language) }
    }
    return node
  }
  \`\`\`

  @param blocks - The array of block nodes returned by \`parse(...).blocks\`
  @param block - Callback invoked with each node; returns the replacement node`,
    schema: z.object({ "blocks": z.array(z.any()) })
  },
  safe: true,
  exported: true
}, __toolRegistry);
async function __renderForCli_impl(blocks) {
  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/markdown.agency")) {
    await __initializeGlobals(__ctx);
  }
  let __funcStartTime = performance.now();
  __stack.args["blocks"] = blocks;
  __self.__retryable = __self.__retryable ?? true;
  const runner = new Runner(__ctx, __stack, { state: __stack, moduleId: "stdlib/markdown.agency", scopeName: "renderForCli", threads: __setupData.threads });
  let __resultCheckpointId = -1;
  if (__ctx._pendingArgOverrides) {
    const __overrides = __ctx._pendingArgOverrides;
    __ctx._pendingArgOverrides = void 0;
    if ("blocks" in __overrides) {
      blocks = __overrides["blocks"];
      __stack.args["blocks"] = blocks;
    }
  }
  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: "renderForCli",
            args: {
              blocks
            },
            isBuiltin: false,
            moduleId: "stdlib/markdown.agency"
          }
        });
      });
      await runner.step(1, async (runner2) => {
        __functionCompleted = true;
        runner2.halt(await __call(_renderMarkdownForCli, {
          type: "positional",
          args: [__stack.args.blocks]
        }));
        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 renderForCli threw an exception (converted to Failure): " + __errMsg);
      if (__errStack) __log.error(__errStack);
      __ctx.statelogClient?.error?.({
        errorType: "runtimeError",
        message: __errMsg,
        functionName: "renderForCli",
        retryable: __self.__retryable
      });
    }
    return failure(
      __error instanceof Error ? __error.message : String(__error),
      {
        checkpoint: getRuntimeContext().ctx.getResultCheckpoint(),
        retryable: __self.__retryable,
        functionName: "renderForCli",
        args: __stack.args
      }
    );
  } finally {
    __stateStack()?.pop();
    if (__functionCompleted) {
      await callHook({
        name: "onFunctionEnd",
        data: {
          functionName: "renderForCli",
          timeTaken: performance.now() - __funcStartTime
        }
      });
    }
  }
}
const renderForCli = __AgencyFunction.create({
  name: "renderForCli",
  module: "stdlib/markdown.agency",
  fn: __renderForCli_impl,
  params: [{
    name: "blocks",
    hasDefault: false,
    defaultValue: void 0,
    variadic: false
  }],
  toolDefinition: {
    name: "renderForCli",
    description: `Render a Markdown AST (array of block nodes) to an ANSI-styled string
  suitable for direct printing in a terminal. Links use OSC 8 escapes so
  capable terminals render them as clickable hyperlinks.

  Code-block bodies are emitted verbatim, so pre-process them with \`walk\`
  if you want syntax highlighting inside the fences (this is what
  \`highlight(code, "markdown")\` does internally).

  @param blocks - The array of block nodes to render`,
    schema: z.object({ "blocks": z.array(z.any()) })
  },
  safe: true,
  exported: true
}, __toolRegistry);
var stdin_default = graph;
const __sourceMap = { "stdlib/markdown.agency:parse": { "1": { "line": 248, "col": 2 } }, "stdlib/markdown.agency:frontmatter": { "1": { "line": 263, "col": 2 }, "2": { "line": 264, "col": 2 }, "3": { "line": 267, "col": 2 }, "4": { "line": 272, "col": 2 }, "2.0": { "line": 265, "col": 4 }, "3.0.0": { "line": 269, "col": 6 }, "3.0": { "line": 268, "col": 4 } }, "stdlib/markdown.agency:walk": { "1": { "line": 298, "col": 2 } }, "stdlib/markdown.agency:renderForCli": { "1": { "line": 313, "col": 2 } } };
export {
  Alignment,
  BlockQuote,
  CodeBlock,
  FootnoteDef,
  Frontmatter,
  HTMLBlock,
  Heading,
  HorizontalRule,
  Image,
  InlineBold,
  InlineBoldItalic,
  InlineCode,
  InlineFootnoteRef,
  InlineHTML,
  InlineHardBreak,
  InlineItalic,
  InlineLink,
  InlineRefImage,
  InlineRefLink,
  InlineSoftBreak,
  InlineStrike,
  InlineText,
  LinkDef,
  List,
  ListItem,
  Paragraph,
  ParseResult,
  Table,
  __getCheckpoints,
  __setDebugger,
  __setLLMClient,
  __setTraceFile,
  __sourceMap,
  __toolRegistry,
  approve,
  stdin_default as default,
  frontmatter,
  hasInterrupts,
  interrupt,
  isDebugger,
  isInterrupt,
  parse,
  reject,
  renderForCli,
  respondToInterrupts,
  rewindFrom,
  walk
};
