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 { 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,
  __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/strategy.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/strategy.agency")) {
    return;
  }
  __ctx.globals.markInitialized("stdlib/strategy.agency");
}
__registerGlobalsInit("stdlib/strategy.agency", __initializeGlobals);
async function __registerTopLevelCallbacks(__ctx) {
  __ctx.topLevelCallbacks = [];
}
__functionRefReviver.registry = __toolRegistry;
async function __sample_impl(n, 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/strategy.agency")) {
    await __initializeGlobals(__ctx);
  }
  let __funcStartTime = performance.now();
  __stack.args["n"] = n;
  __stack.args["block"] = block;
  __self.__retryable = __self.__retryable ?? true;
  const runner = new Runner(__ctx, __stack, { state: __stack, moduleId: "stdlib/strategy.agency", scopeName: "sample", threads: __setupData.threads });
  let __resultCheckpointId = -1;
  if (__ctx._pendingArgOverrides) {
    const __overrides = __ctx._pendingArgOverrides;
    __ctx._pendingArgOverrides = void 0;
    if ("n" in __overrides) {
      n = __overrides["n"];
      __stack.args["n"] = n;
    }
    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: "sample",
            args: {
              n,
              block
            },
            isBuiltin: false,
            moduleId: "stdlib/strategy.agency"
          }
        });
      });
      await runner.step(1, async (runner2) => {
        __functionCompleted = true;
        runner2.halt(await runner2.fork(1, await __call(range, {
          type: "positional",
          args: [__stack.args.n]
        }), async (__forkItem, __forkIndex, __forkBranchStack) => {
          const __bstack = __forkBranchStack.getNewState();
          const __self2 = __bstack.locals;
          const _ = __forkItem;
          __bstack.args["_"] = __forkItem;
          const runner3 = new Runner(__ctx, __bstack, { state: __bstack, moduleId: "stdlib/strategy.agency", scopeName: "__block_0" });
          try {
            await runner3.step(0, async (runner4) => {
              runner4.halt(await __call(__stack.args.block, {
                type: "positional",
                args: []
              }));
              return;
            });
            return runner3.halted ? runner3.haltResult : void 0;
          } finally {
            __forkBranchStack.pop();
          }
        }, "all", getRuntimeContext().stack));
        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 sample threw an exception (converted to Failure): " + __errMsg);
      if (__errStack) __log.error(__errStack);
      __ctx.statelogClient?.error?.({
        errorType: "runtimeError",
        message: __errMsg,
        functionName: "sample",
        retryable: __self.__retryable
      });
    }
    return failure(
      __error instanceof Error ? __error.message : String(__error),
      {
        checkpoint: getRuntimeContext().ctx.getResultCheckpoint(),
        retryable: __self.__retryable,
        functionName: "sample",
        args: __stack.args
      }
    );
  } finally {
    __stateStack()?.pop();
    if (__functionCompleted) {
      await callHook({
        name: "onFunctionEnd",
        data: {
          functionName: "sample",
          timeTaken: performance.now() - __funcStartTime
        }
      });
    }
  }
}
const sample = __AgencyFunction.create({
  name: "sample",
  module: "stdlib/strategy.agency",
  fn: __sample_impl,
  params: [{
    name: "n",
    hasDefault: false,
    defaultValue: void 0,
    variadic: false
  }, {
    name: "block",
    hasDefault: false,
    defaultValue: void 0,
    variadic: false
  }],
  toolDefinition: {
    name: "sample",
    description: `Run a block n times in parallel. Returns an array of all results.

  @param n - Number of times to run
  @param block - The block to execute`,
    schema: z.object({ "n": z.number() })
  },
  safe: false,
  exported: true
}, __toolRegistry);
async function __consensus_impl(n, 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/strategy.agency")) {
    await __initializeGlobals(__ctx);
  }
  let __funcStartTime = performance.now();
  __stack.args["n"] = n;
  __stack.args["block"] = block;
  __self.__retryable = __self.__retryable ?? true;
  const runner = new Runner(__ctx, __stack, { state: __stack, moduleId: "stdlib/strategy.agency", scopeName: "consensus", threads: __setupData.threads });
  let __resultCheckpointId = -1;
  if (__ctx._pendingArgOverrides) {
    const __overrides = __ctx._pendingArgOverrides;
    __ctx._pendingArgOverrides = void 0;
    if ("n" in __overrides) {
      n = __overrides["n"];
      __stack.args["n"] = n;
    }
    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: "consensus",
            args: {
              n,
              block
            },
            isBuiltin: false,
            moduleId: "stdlib/strategy.agency"
          }
        });
      });
      await runner.step(1, async (runner2) => {
        __stack.locals.results = await __call(sample, {
          type: "positional",
          args: [__stack.args.n, __stack.args.block]
        });
        if (hasInterrupts(__stack.locals.results)) {
          await getRuntimeContext().ctx.pendingPromises.awaitAll();
          runner2.halt(__stack.locals.results);
          return;
        }
      });
      await runner.step(2, async (runner2) => {
        __functionCompleted = true;
        runner2.halt(await __call(mostCommon, {
          type: "positional",
          args: [__stack.locals.results]
        }));
        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 consensus threw an exception (converted to Failure): " + __errMsg);
      if (__errStack) __log.error(__errStack);
      __ctx.statelogClient?.error?.({
        errorType: "runtimeError",
        message: __errMsg,
        functionName: "consensus",
        retryable: __self.__retryable
      });
    }
    return failure(
      __error instanceof Error ? __error.message : String(__error),
      {
        checkpoint: getRuntimeContext().ctx.getResultCheckpoint(),
        retryable: __self.__retryable,
        functionName: "consensus",
        args: __stack.args
      }
    );
  } finally {
    __stateStack()?.pop();
    if (__functionCompleted) {
      await callHook({
        name: "onFunctionEnd",
        data: {
          functionName: "consensus",
          timeTaken: performance.now() - __funcStartTime
        }
      });
    }
  }
}
const consensus = __AgencyFunction.create({
  name: "consensus",
  module: "stdlib/strategy.agency",
  fn: __consensus_impl,
  params: [{
    name: "n",
    hasDefault: false,
    defaultValue: void 0,
    variadic: false
  }, {
    name: "block",
    hasDefault: false,
    defaultValue: void 0,
    variadic: false
  }],
  toolDefinition: {
    name: "consensus",
    description: `Run a block n times in parallel and return the most common result (majority vote).

  @param n - Number of times to run
  @param block - The block to execute`,
    schema: z.object({ "n": z.number() })
  },
  safe: false,
  exported: true
}, __toolRegistry);
async function __retry_impl(n, test, 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/strategy.agency")) {
    await __initializeGlobals(__ctx);
  }
  let __funcStartTime = performance.now();
  __stack.args["n"] = n;
  __stack.args["test"] = test;
  __stack.args["block"] = block;
  __self.__retryable = __self.__retryable ?? true;
  const runner = new Runner(__ctx, __stack, { state: __stack, moduleId: "stdlib/strategy.agency", scopeName: "retry", threads: __setupData.threads });
  let __resultCheckpointId = -1;
  if (__ctx._pendingArgOverrides) {
    const __overrides = __ctx._pendingArgOverrides;
    __ctx._pendingArgOverrides = void 0;
    if ("n" in __overrides) {
      n = __overrides["n"];
      __stack.args["n"] = n;
    }
    if ("test" in __overrides) {
      test = __overrides["test"];
      __stack.args["test"] = test;
    }
    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: "retry",
            args: {
              n,
              test,
              block
            },
            isBuiltin: false,
            moduleId: "stdlib/strategy.agency"
          }
        });
      });
      await runner.loop(1, Array.from({ length: __stack.args.n - 0 }, (_, __i) => __i + 0), async (i, _, runner2) => {
        await runner2.step(0, async (runner3) => {
          __stack.locals.result = await __call(__stack.args.block, {
            type: "positional",
            args: []
          });
          if (hasInterrupts(__stack.locals.result)) {
            await getRuntimeContext().ctx.pendingPromises.awaitAll();
            runner3.halt(__stack.locals.result);
            return;
          }
        });
        await runner2.step(1, async (runner3) => {
          __stack.locals.passed = await __call(__stack.args.test, {
            type: "positional",
            args: [__stack.locals.result]
          });
          if (hasInterrupts(__stack.locals.passed)) {
            await getRuntimeContext().ctx.pendingPromises.awaitAll();
            runner3.halt(__stack.locals.passed);
            return;
          }
        });
        await runner2.ifElse(2, [
          {
            condition: async () => __stack.locals.passed,
            body: async (runner3) => {
              await runner3.step(0, async (runner4) => {
                __functionCompleted = true;
                runner4.halt(__stack.locals.result);
                return;
              });
            }
          }
        ]);
      });
      await runner.step(2, async (runner2) => {
        __functionCompleted = true;
        runner2.halt(null);
        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 retry threw an exception (converted to Failure): " + __errMsg);
      if (__errStack) __log.error(__errStack);
      __ctx.statelogClient?.error?.({
        errorType: "runtimeError",
        message: __errMsg,
        functionName: "retry",
        retryable: __self.__retryable
      });
    }
    return failure(
      __error instanceof Error ? __error.message : String(__error),
      {
        checkpoint: getRuntimeContext().ctx.getResultCheckpoint(),
        retryable: __self.__retryable,
        functionName: "retry",
        args: __stack.args
      }
    );
  } finally {
    __stateStack()?.pop();
    if (__functionCompleted) {
      await callHook({
        name: "onFunctionEnd",
        data: {
          functionName: "retry",
          timeTaken: performance.now() - __funcStartTime
        }
      });
    }
  }
}
const retry = __AgencyFunction.create({
  name: "retry",
  module: "stdlib/strategy.agency",
  fn: __retry_impl,
  params: [{
    name: "n",
    hasDefault: false,
    defaultValue: void 0,
    variadic: false
  }, {
    name: "test",
    hasDefault: false,
    defaultValue: void 0,
    variadic: false
  }, {
    name: "block",
    hasDefault: false,
    defaultValue: void 0,
    variadic: false
  }],
  toolDefinition: {
    name: "retry",
    description: `Run a block up to n times. Returns the first result that passes the test function. Returns null if all attempts fail.

  @param n - Maximum number of attempts
  @param test - The function that returns true when the result is acceptable
  @param block - The block to execute`,
    schema: z.object({ "n": z.number() })
  },
  safe: false,
  exported: true
}, __toolRegistry);
async function __retryWithFeedback_impl(n, test, 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/strategy.agency")) {
    await __initializeGlobals(__ctx);
  }
  let __funcStartTime = performance.now();
  __stack.args["n"] = n;
  __stack.args["test"] = test;
  __stack.args["block"] = block;
  __self.__retryable = __self.__retryable ?? true;
  const runner = new Runner(__ctx, __stack, { state: __stack, moduleId: "stdlib/strategy.agency", scopeName: "retryWithFeedback", threads: __setupData.threads });
  let __resultCheckpointId = -1;
  if (__ctx._pendingArgOverrides) {
    const __overrides = __ctx._pendingArgOverrides;
    __ctx._pendingArgOverrides = void 0;
    if ("n" in __overrides) {
      n = __overrides["n"];
      __stack.args["n"] = n;
    }
    if ("test" in __overrides) {
      test = __overrides["test"];
      __stack.args["test"] = test;
    }
    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: "retryWithFeedback",
            args: {
              n,
              test,
              block
            },
            isBuiltin: false,
            moduleId: "stdlib/strategy.agency"
          }
        });
      });
      await runner.step(1, async (runner2) => {
        __stack.locals.prev = null;
      });
      await runner.loop(2, Array.from({ length: __stack.args.n - 0 }, (_, __i) => __i + 0), async (i, _, runner2) => {
        await runner2.step(0, async (runner3) => {
          __stack.locals.result = await __call(__stack.args.block, {
            type: "positional",
            args: [__stack.locals.prev, i + 1]
          });
          if (hasInterrupts(__stack.locals.result)) {
            await getRuntimeContext().ctx.pendingPromises.awaitAll();
            runner3.halt(__stack.locals.result);
            return;
          }
        });
        await runner2.step(1, async (runner3) => {
          __stack.locals.passed = await __call(__stack.args.test, {
            type: "positional",
            args: [__stack.locals.result]
          });
          if (hasInterrupts(__stack.locals.passed)) {
            await getRuntimeContext().ctx.pendingPromises.awaitAll();
            runner3.halt(__stack.locals.passed);
            return;
          }
        });
        await runner2.ifElse(2, [
          {
            condition: async () => __stack.locals.passed,
            body: async (runner3) => {
              await runner3.step(0, async (runner4) => {
                __functionCompleted = true;
                runner4.halt(__stack.locals.result);
                return;
              });
            }
          }
        ]);
        await runner2.step(3, async (runner3) => {
          __stack.locals.prev = __stack.locals.result;
        });
      });
      await runner.step(3, async (runner2) => {
        __functionCompleted = true;
        runner2.halt(__stack.locals.prev);
        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 retryWithFeedback threw an exception (converted to Failure): " + __errMsg);
      if (__errStack) __log.error(__errStack);
      __ctx.statelogClient?.error?.({
        errorType: "runtimeError",
        message: __errMsg,
        functionName: "retryWithFeedback",
        retryable: __self.__retryable
      });
    }
    return failure(
      __error instanceof Error ? __error.message : String(__error),
      {
        checkpoint: getRuntimeContext().ctx.getResultCheckpoint(),
        retryable: __self.__retryable,
        functionName: "retryWithFeedback",
        args: __stack.args
      }
    );
  } finally {
    __stateStack()?.pop();
    if (__functionCompleted) {
      await callHook({
        name: "onFunctionEnd",
        data: {
          functionName: "retryWithFeedback",
          timeTaken: performance.now() - __funcStartTime
        }
      });
    }
  }
}
const retryWithFeedback = __AgencyFunction.create({
  name: "retryWithFeedback",
  module: "stdlib/strategy.agency",
  fn: __retryWithFeedback_impl,
  params: [{
    name: "n",
    hasDefault: false,
    defaultValue: void 0,
    variadic: false
  }, {
    name: "test",
    hasDefault: false,
    defaultValue: void 0,
    variadic: false
  }, {
    name: "block",
    hasDefault: false,
    defaultValue: void 0,
    variadic: false
  }],
  toolDefinition: {
    name: "retryWithFeedback",
    description: `Run a block up to n times. Each attempt receives the previous result and the attempt number (starting from 1). Returns the first result that passes the test, or the last result if all fail.

  @param n - Maximum number of attempts
  @param test - The function that returns true when the result is acceptable
  @param block - The block receiving (previousResult, attemptNumber)`,
    schema: z.object({ "n": z.number() })
  },
  safe: false,
  exported: true
}, __toolRegistry);
async function __firstValid_impl(variants, test, 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/strategy.agency")) {
    await __initializeGlobals(__ctx);
  }
  let __funcStartTime = performance.now();
  __stack.args["variants"] = variants;
  __stack.args["test"] = test;
  __stack.args["block"] = block;
  __self.__retryable = __self.__retryable ?? true;
  const runner = new Runner(__ctx, __stack, { state: __stack, moduleId: "stdlib/strategy.agency", scopeName: "firstValid", threads: __setupData.threads });
  let __resultCheckpointId = -1;
  if (__ctx._pendingArgOverrides) {
    const __overrides = __ctx._pendingArgOverrides;
    __ctx._pendingArgOverrides = void 0;
    if ("variants" in __overrides) {
      variants = __overrides["variants"];
      __stack.args["variants"] = variants;
    }
    if ("test" in __overrides) {
      test = __overrides["test"];
      __stack.args["test"] = test;
    }
    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: "firstValid",
            args: {
              variants,
              test,
              block
            },
            isBuiltin: false,
            moduleId: "stdlib/strategy.agency"
          }
        });
      });
      await runner.step(1, async (runner2) => {
        __stack.locals.results = await runner2.fork(1, __stack.args.variants, async (__forkItem, __forkIndex, __forkBranchStack) => {
          const __bstack = __forkBranchStack.getNewState();
          const __self2 = __bstack.locals;
          const v = __forkItem;
          __bstack.args["v"] = __forkItem;
          const runner3 = new Runner(__ctx, __bstack, { state: __bstack, moduleId: "stdlib/strategy.agency", scopeName: "__block_1" });
          try {
            await runner3.step(0, async (runner4) => {
              runner4.halt(await __call(__stack.args.block, {
                type: "positional",
                args: [__bstack.args.v]
              }));
              return;
            });
            return runner3.halted ? runner3.haltResult : void 0;
          } finally {
            __forkBranchStack.pop();
          }
        }, "all", getRuntimeContext().stack);
        if (hasInterrupts(__stack.locals.results)) {
          await getRuntimeContext().ctx.pendingPromises.awaitAll();
          runner2.halt(__stack.locals.results);
          return;
        }
      });
      await runner.loop(2, __stack.locals.results, async (r, _, runner2) => {
        await runner2.step(0, async (runner3) => {
          __stack.locals.passed = await __call(__stack.args.test, {
            type: "positional",
            args: [r]
          });
          if (hasInterrupts(__stack.locals.passed)) {
            await getRuntimeContext().ctx.pendingPromises.awaitAll();
            runner3.halt(__stack.locals.passed);
            return;
          }
        });
        await runner2.ifElse(1, [
          {
            condition: async () => __stack.locals.passed,
            body: async (runner3) => {
              await runner3.step(0, async (runner4) => {
                __functionCompleted = true;
                runner4.halt(r);
                return;
              });
            }
          }
        ]);
      });
      await runner.step(3, async (runner2) => {
        __functionCompleted = true;
        runner2.halt(null);
        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 firstValid threw an exception (converted to Failure): " + __errMsg);
      if (__errStack) __log.error(__errStack);
      __ctx.statelogClient?.error?.({
        errorType: "runtimeError",
        message: __errMsg,
        functionName: "firstValid",
        retryable: __self.__retryable
      });
    }
    return failure(
      __error instanceof Error ? __error.message : String(__error),
      {
        checkpoint: getRuntimeContext().ctx.getResultCheckpoint(),
        retryable: __self.__retryable,
        functionName: "firstValid",
        args: __stack.args
      }
    );
  } finally {
    __stateStack()?.pop();
    if (__functionCompleted) {
      await callHook({
        name: "onFunctionEnd",
        data: {
          functionName: "firstValid",
          timeTaken: performance.now() - __funcStartTime
        }
      });
    }
  }
}
const firstValid = __AgencyFunction.create({
  name: "firstValid",
  module: "stdlib/strategy.agency",
  fn: __firstValid_impl,
  params: [{
    name: "variants",
    hasDefault: false,
    defaultValue: void 0,
    variadic: false
  }, {
    name: "test",
    hasDefault: false,
    defaultValue: void 0,
    variadic: false
  }, {
    name: "block",
    hasDefault: false,
    defaultValue: void 0,
    variadic: false
  }],
  toolDefinition: {
    name: "firstValid",
    description: `Run a block for each variant in parallel, then return the first result that passes the test. Returns null if none pass.

  @param variants - Array of variants to try
  @param test - The function that returns true for valid results
  @param block - The block receiving each variant`,
    schema: z.object({ "variants": z.array(z.any()) })
  },
  safe: false,
  exported: true
}, __toolRegistry);
var stdin_default = graph;
const __sourceMap = { "stdlib/strategy.agency:sample": { "1": { "line": 7, "col": 2 } }, "stdlib/strategy.agency:__block_0": { "1.0": { "line": 8, "col": 4 } }, "stdlib/strategy.agency:consensus": { "1": { "line": 19, "col": 2 }, "2": { "line": 20, "col": 2 } }, "stdlib/strategy.agency:retry": { "1": { "line": 31, "col": 2 }, "2": { "line": 38, "col": 2 }, "1.0": { "line": 32, "col": 4 }, "1.1": { "line": 33, "col": 4 }, "1.2.0": { "line": 35, "col": 6 }, "1.2": { "line": 34, "col": 4 } }, "stdlib/strategy.agency:retryWithFeedback": { "1": { "line": 49, "col": 2 }, "2": { "line": 50, "col": 2 }, "3": { "line": 58, "col": 2 }, "2.0": { "line": 51, "col": 4 }, "2.1": { "line": 52, "col": 4 }, "2.2.0": { "line": 54, "col": 6 }, "2.2": { "line": 53, "col": 4 }, "2.3": { "line": 56, "col": 4 } }, "stdlib/strategy.agency:firstValid": { "1": { "line": 69, "col": 2 }, "2": { "line": 72, "col": 2 }, "3": { "line": 78, "col": 2 }, "2.0": { "line": 73, "col": 4 }, "2.1.0": { "line": 75, "col": 6 }, "2.1": { "line": 74, "col": 4 } }, "stdlib/strategy.agency:__block_1": { "1.0": { "line": 70, "col": 4 } } };
export {
  __getCheckpoints,
  __setDebugger,
  __setLLMClient,
  __setTraceFile,
  __sourceMap,
  __toolRegistry,
  approve,
  consensus,
  stdin_default as default,
  firstValid,
  hasInterrupts,
  interrupt,
  isDebugger,
  isInterrupt,
  reject,
  respondToInterrupts,
  retry,
  retryWithFeedback,
  rewindFrom,
  sample
};
