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 { todoWrite, todoList } from "agency-lang/stdlib/agent.js";
import { typecheck } from "agency-lang/stdlib/agency.js";
import { openDir, Workspace } from "agency-lang/stdlib/fs.js";
import { remember, recall } from "agency-lang/stdlib/memory.js";
import { skillsDir } from "agency-lang/stdlib/skills.js";
import { highlight } from "agency-lang/stdlib/syntax.js";
import { cwd } from "agency-lang/stdlib/system.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,
  deepFreeze as __deepFreeze,
  __UNINIT_STATIC,
  __readStatic,
  __registerStaticInit,
  __registerGlobalsInit,
  failure,
  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: "dist/lib/agents/agency-agent/code.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(todoWrite);
__registerTool(todoList);
__registerTool(typecheck);
__registerTool(openDir);
__registerTool(Workspace);
__registerTool(remember);
__registerTool(recall);
__registerTool(skillsDir);
__registerTool(highlight);
__registerTool(cwd);
let __staticInitPromise = null;
let workspace = __UNINIT_STATIC;
let superpowersSkill = __UNINIT_STATIC;
let codeSysPrompt = __UNINIT_STATIC;
let codeTools = __UNINIT_STATIC;
async function __initializeStatic(__ctx) {
  if (__staticInitPromise) {
    return __staticInitPromise;
  }
  __staticInitPromise = (async () => {
    workspace = __deepFreeze(await __call(openDir, {
      type: "positional",
      args: [await __call(cwd, {
        type: "positional",
        args: []
      })]
    }));
    getRuntimeContext().ctx.pushHandler(async (__data) => approve());
    try {
      superpowersSkill = __deepFreeze(await __call(skillsDir, {
        type: "positional",
        args: [`./skills/superpowers`]
      }));
    } finally {
      getRuntimeContext().ctx.popHandler();
    }
    codeSysPrompt = __deepFreeze(`
You are the **code specialist** of a multi-thread Agency-language
assistant. You handle anything that touches code or the file system:
writing, editing, running, and typechecking Agency or shell code.

You do NOT have access to web search, documentation lookup, Wikipedia,
or URL fetching. If the user asks a question that needs research
(Agency syntax you're unsure of, an external API, a Wikipedia
summary, or a URL fetch), call \`handoff(reason)\` \u2014 the only valid
target for you is the research specialist, so just pass a brief
reason. The runtime will re-route the user's original message there.

**Bias toward staying in the code thread.** Most follow-up messages
("can you make it faster?", "fix the error", "what about edge
cases?") are continuations of the current coding task, NOT new
categories. Only call \`handoff\` when the message clearly needs
research-specialist tools.

## Hard rules

These are non-negotiable. They override anything else in this prompt
when in conflict.

1. **NEVER assume a function, library, or type exists.** Before
   importing or calling something, verify it with \`grep\` or \`read\`.
   "I think there's a \`foo()\` in std::array" is not good enough \u2014 go
   look. Hallucinated imports are the #1 cause of broken first drafts.
2. **NEVER \`write\` or \`edit\` a file you have not \`read\` in this
   session.** Even if you wrote it last turn. The file on disk may
   have been changed by the user or another tool.
3. **MUST call \`typecheck\` on every Agency source file you produce
   or modify, before claiming the change is done.** If typecheck
   reports errors, fix them and run it again. Don't silence errors \u2014
   no \`as any\` cast, no \`// @ts-ignore\`, no deleting tests to make
   them pass. Address the real issue or report the blocker.
4. **Be concise. Minimize tokens.** Show code, not commentary. Don't
   restate what just happened \u2014 the user can see the diff and the
   tool output. End your turn when the work is done; don't pad with
   summaries or next-step suggestions unless the user asked.
5. **NEVER add code comments to explain your changes.** Explanations
   belong in your reply, not in the source. Existing comments in the
   codebase that document non-obvious behavior should be preserved.
6. **Mimic the existing code style.** Before editing a file, look
   at how nearby code is written and match it: brace style, naming,
   import grouping, error handling pattern. The codebase has
   conventions; respect them.
7. **State your plan in one sentence before a multi-step task.**
   "I'll grep for callers of X, then update the three sites." This
   gives the user a chance to redirect before tool use burns time.
8. **For any task with more than two steps, call \`todoWrite\` first
   to plan, and mark each item completed the moment it's done.**
   Use this VERY frequently \u2014 it gives the user visibility into your
   progress and protects against forgetting a step. Mark items
   completed one at a time, NEVER batch the completions at the end.
   Skip the list for trivial single-step changes.

## Agency syntax \u2014 common mistakes to never make

The Agency language has TypeScript-style braces and parens, not
Python-style colons. If your draft has any of these, it's wrong:

- \u274C \`function foo() -> ReturnType:\` \u2192 \u2705 \`def foo(): ReturnType { ... }\`
- \u274C \`node main -> end:\` \u2192 \u2705 \`node main() { ... }\`
- \u274C \`if condition:\` or \`if condition {\` (no parens) \u2192 \u2705 \`if (condition) { ... }\`
- \u274C \`for item in items:\` \u2192 \u2705 \`for (item in items) { ... }\`
- \u274C \`result = foo()\` without prior declaration \u2192 \u2705 \`let result = foo()\` or \`const result = foo()\`
- \u274C Python-style indentation for blocks \u2192 \u2705 always \`{ ... }\`

When unsure about syntax, read \`docs/site/guide/basic-syntax.md\` or
an existing fixture in \`tests/agency/\` before writing. Agency tests
live in \`.agency\` files you can \`read\` directly.

## Workflow

1. Call \`setCwd\` with the user's project directory first. After
   that, every file-system tool resolves filenames against that
   directory and its subtree.
2. Read \`AGENTS.md\` and \`CLAUDE.md\` at the project root if either
   exists and you haven't yet this session. They contain project
   conventions you MUST follow.
3. Use \`ls\` or \`glob\` to discover what files exist before guessing
   filenames. \`glob("**/*.agency")\` is a good first move on a new
   project. The returned paths (which may include subdirectories
   like \`"sub/foo.agency"\`) are exactly what \`read\` / \`edit\` expect
   as their \`filename\` argument.
4. Use \`read\` to inspect existing code before modifying it (see
   rule 2 above).
5. Use \`write\` / \`edit\` to persist changes. \`edit\` takes an array
   of \`{oldText, newText, replaceAll}\` entries \u2014 prefer one call
   with multiple entries over several \`edit\` calls when you have
   more than one change to make to the same file. The user will be
   prompted to approve every write.
6. After every change, run \`typecheck\` (rule 3 above) and any
   relevant tests via \`bash\`.
7. Use \`bash\` to run project-level commands (tests, git, formatters,
   package managers). Prefer the dedicated file tools above for file
   operations; use \`bash\` for everything else. The user is asked to
   approve each command.
8. You have a persistent knowledge graph scoped to coding work. Call
   \`recall(query)\` to retrieve anything the user told you in a
   previous session (project conventions, decisions made earlier).
   Call \`remember(content)\` to persist a fact worth keeping across
   sessions \u2014 user preferences ("prefers tabs"), project conventions
   ("uses \`def\` not \`node\` for utilities"), or important decisions.
   Don't \`remember\` transient details or things already in
   AGENTS.md. Relevant facts are also auto-injected before each turn,
   so often you don't need to call \`recall\` explicitly.
9. For **larger coding tasks that benefit from up-front thinking**
   \u2014 building a new feature, designing a non-trivial component,
   refactoring across multiple files, debugging something the user
   has already tried once \u2014 call \`superpowersSkill\` to read the
   relevant Superpowers skill before jumping into code. Good
   defaults:
     * \`brainstorming.md\` first whenever the user describes a
       *new* feature or behavior change, before writing any code.
     * \`writing-plans.md\` once you have a spec, before touching
       implementation.
     * \`executing-plans.md\` while working through a written plan.
     * \`test-driven-development.md\` for any feature or bugfix.
     * \`systematic-debugging.md\` for bugs / unexpected failures.
     * \`verification-before-completion.md\` before claiming work
       is done.
   Skip the skill for trivial one-line edits, single-file
   tweaks, or quick questions \u2014 the skills are for tasks where
   structure pays for itself.
10. Whenever you want to show the user a multi-line code snippet,
   call \`print(highlight(code))\` instead of including the raw
   source in your reply. \`highlight\` returns a terminal-colored
   string and \`print\` writes it directly to the user's console, so
   the snippet appears with proper syntax highlighting. Skip this
   for inline identifiers or one-token excerpts; use it for any
   multi-line block. Your reply can then refer to the printed
   snippet without repeating the source.

## Output style

Respond in Markdown \u2014 use \`#\`/\`##\` headings, \`-\` bullets, **bold**,
_italic_, and fenced code blocks (\`\`\`ts, \`\`\`bash, \`\`\`json, \`\`\`diff)
for any code or command output. The REPL renders your reply through a
Markdown syntax highlighter, so well-marked-up replies appear with
colored headings, bold/italic styling, and properly highlighted code
fences. Code fences are especially important \u2014 they're how code in
your reply gets per-language coloring.

**Important:** put a blank line between a heading and any bullet list
or paragraph that follows it (\`## Heading\\n\\n- item\`, not
\`## Heading\\n- item\`). Without the blank line our Markdown renderer
silently truncates everything after the heading.
`);
    codeTools = __deepFreeze([setCwd, __readStatic(workspace, "workspace", "dist/lib/agents/agency-agent/code.agency").read, __readStatic(workspace, "workspace", "dist/lib/agents/agency-agent/code.agency").write, await __callMethod(__readStatic(workspace, "workspace", "dist/lib/agents/agency-agent/code.agency").edit, "partial", {
      type: "named",
      positionalArgs: [],
      namedArgs: {
        printDiff: true
      }
    }), __readStatic(workspace, "workspace", "dist/lib/agents/agency-agent/code.agency").ls, __readStatic(workspace, "workspace", "dist/lib/agents/agency-agent/code.agency").glob, __readStatic(workspace, "workspace", "dist/lib/agents/agency-agent/code.agency").grep, __readStatic(workspace, "workspace", "dist/lib/agents/agency-agent/code.agency").bash, __readStatic(typecheck, "typecheck", "/Users/adityabhargava/agency-lang/packages/agency-lang/stdlib/agency.agency"), await __callMethod(__readStatic(highlight, "highlight", "/Users/adityabhargava/agency-lang/packages/agency-lang/stdlib/syntax.agency"), "partial", {
      type: "named",
      positionalArgs: [],
      namedArgs: {
        language: `ts`
      }
    }), __readStatic(print, "print", "/Users/adityabhargava/agency-lang/packages/agency-lang/stdlib/index.agency"), __readStatic(remember, "remember", "/Users/adityabhargava/agency-lang/packages/agency-lang/stdlib/memory.agency"), __readStatic(recall, "recall", "/Users/adityabhargava/agency-lang/packages/agency-lang/stdlib/memory.agency"), __readStatic(superpowersSkill, "superpowersSkill", "dist/lib/agents/agency-agent/code.agency"), __readStatic(todoWrite, "todoWrite", "/Users/adityabhargava/agency-lang/packages/agency-lang/stdlib/agent.agency"), __readStatic(todoList, "todoList", "/Users/adityabhargava/agency-lang/packages/agency-lang/stdlib/agent.agency")]);
  })();
  return __staticInitPromise;
}
function __getStaticVars() {
  return {
    workspace,
    superpowersSkill,
    codeSysPrompt,
    codeTools
  };
}
__globalCtx.getStaticVars = __getStaticVars;
__registerStaticInit("dist/lib/agents/agency-agent/code.agency", __initializeStatic);
async function __initializeGlobals(__ctx) {
  if (__ctx.globals.isInitialized("dist/lib/agents/agency-agent/code.agency")) {
    return;
  }
  __ctx.globals.markInitialized("dist/lib/agents/agency-agent/code.agency");
  await __initializeStatic(__ctx);
  await __ctx.writeStaticStateToTrace(__globalCtx.getStaticVars());
}
__registerGlobalsInit("dist/lib/agents/agency-agent/code.agency", __initializeGlobals);
async function __registerTopLevelCallbacks(__ctx) {
  __ctx.topLevelCallbacks = [];
}
__functionRefReviver.registry = __toolRegistry;
async function __setCwd_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("dist/lib/agents/agency-agent/code.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: "dist/lib/agents/agency-agent/code.agency", scopeName: "setCwd", 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: "setCwd",
            args: {
              dir
            },
            isBuiltin: false,
            moduleId: "dist/lib/agents/agency-agent/code.agency"
          }
        });
      });
      await runner.ifElse(1, [
        {
          condition: async () => __stack.args.dir === `cwd`,
          body: async (runner2) => {
            await runner2.step(0, async (runner3) => {
              __stack.args.dir = await __call(cwd, {
                type: "positional",
                args: []
              });
              if (hasInterrupts(__stack.args.dir)) {
                await getRuntimeContext().ctx.pendingPromises.awaitAll();
                runner3.halt(__stack.args.dir);
                return;
              }
            });
          }
        }
      ]);
      await runner.step(2, async (runner2) => {
      });
      await runner.step(3, async (runner2) => {
        __functionCompleted = true;
        runner2.halt(`Working directory set to: ${__stack.args.dir}`);
        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 setCwd threw an exception (converted to Failure): " + __errMsg);
      if (__errStack) __log.error(__errStack);
      __ctx.statelogClient?.error?.({
        errorType: "runtimeError",
        message: __errMsg,
        functionName: "setCwd",
        retryable: __self.__retryable
      });
    }
    return failure(
      __error instanceof Error ? __error.message : String(__error),
      {
        checkpoint: getRuntimeContext().ctx.getResultCheckpoint(),
        retryable: __self.__retryable,
        functionName: "setCwd",
        args: __stack.args
      }
    );
  } finally {
    __stateStack()?.pop();
    if (__functionCompleted) {
      await callHook({
        name: "onFunctionEnd",
        data: {
          functionName: "setCwd",
          timeTaken: performance.now() - __funcStartTime
        }
      });
    }
  }
}
const setCwd = __AgencyFunction.create({
  name: "setCwd",
  module: "dist/lib/agents/agency-agent/code.agency",
  fn: __setCwd_impl,
  params: [{
    name: "dir",
    hasDefault: false,
    defaultValue: void 0,
    variadic: false
  }],
  toolDefinition: {
    name: "setCwd",
    description: `Use this when the user tells you to change your current working
  directory. After you call this, every file-system tool (read,
  write, edit, ls, glob, grep, bash) will resolve filenames against
  the given directory and its subtree. Pass \`"cwd"\` to anchor to the
  user's current working directory.

  @param dir - The directory to anchor file operations against`,
    schema: z.object({ "dir": z.string() })
  },
  safe: false,
  exported: true
}, __toolRegistry);
var stdin_default = graph;
const __sourceMap = { "dist/lib/agents/agency-agent/code.agency:setCwd": { "1": { "line": 48, "col": 2 }, "3": { "line": 52, "col": 2 }, "1.0": { "line": 49, "col": 4 } } };
export {
  __getCheckpoints,
  __setDebugger,
  __setLLMClient,
  __setTraceFile,
  __sourceMap,
  __toolRegistry,
  approve,
  codeSysPrompt,
  codeTools,
  stdin_default as default,
  hasInterrupts,
  interrupt,
  isDebugger,
  isInterrupt,
  reject,
  respondToInterrupts,
  rewindFrom,
  setCwd
};
