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 { fetch, fetchJSON, fetchMarkdown } from "agency-lang/stdlib/http.js";
import { remember, recall } from "agency-lang/stdlib/memory.js";
import { search } from "agency-lang/stdlib/search.js";
import { skillsDir } from "agency-lang/stdlib/skills.js";
import { highlight } from "agency-lang/stdlib/syntax.js";
import { search as wikipediaSearch, summary as wikipediaSummary, article as wikipediaArticle } from "agency-lang/stdlib/wikipedia.js";
import { fileURLToPath } from "url";
import __process from "process";
import { nanoid } from "agency-lang";
import path from "path";
import {
  RuntimeContext,
  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,
  deepFreeze as __deepFreeze,
  __UNINIT_STATIC,
  __readStatic,
  __registerStaticInit,
  __registerGlobalsInit,
  AgencyFunction as __AgencyFunction,
  __call,
  __callMethod,
  getRuntimeContext,
  functionRefReviver as __functionRefReviver,
  DeterministicClient as __DeterministicClient
} 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/research.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(fetch);
__registerTool(fetchJSON);
__registerTool(fetchMarkdown);
__registerTool(remember);
__registerTool(recall);
__registerTool(search);
__registerTool(skillsDir);
__registerTool(highlight);
__registerTool(wikipediaSearch);
__registerTool(wikipediaSummary);
__registerTool(wikipediaArticle);
let __staticInitPromise = null;
let docSkill = __UNINIT_STATIC;
let cliSkill = __UNINIT_STATIC;
let appendixSkill = __UNINIT_STATIC;
let researchSysPrompt = __UNINIT_STATIC;
let researchTools = __UNINIT_STATIC;
async function __initializeStatic(__ctx) {
  if (__staticInitPromise) {
    return __staticInitPromise;
  }
  __staticInitPromise = (async () => {
    getRuntimeContext().ctx.pushHandler(async (__data) => approve());
    try {
      docSkill = __deepFreeze(await __call(skillsDir, {
        type: "positional",
        args: [`../docs/guide`]
      }));
    } finally {
      getRuntimeContext().ctx.popHandler();
    }
    getRuntimeContext().ctx.pushHandler(async (__data) => approve());
    try {
      cliSkill = __deepFreeze(await __call(skillsDir, {
        type: "positional",
        args: [`../docs/cli`]
      }));
    } finally {
      getRuntimeContext().ctx.popHandler();
    }
    getRuntimeContext().ctx.pushHandler(async (__data) => approve());
    try {
      appendixSkill = __deepFreeze(await __call(skillsDir, {
        type: "positional",
        args: [`../docs/appendix`]
      }));
    } finally {
      getRuntimeContext().ctx.popHandler();
    }
    researchSysPrompt = __deepFreeze(`
You are the **research specialist** of a multi-thread Agency-language
assistant. You answer questions that need reading: Agency-language
syntax / semantics / built-ins, CLI usage, external docs, Wikipedia
background, URL contents, and general conversation backed by recall.

You do NOT have file-system write tools (no write, edit, bash, or
typecheck). If the user asks you to actually write, edit, or run
code, call \`handoff(reason)\` \u2014 the only valid target for you is
the code specialist, so just pass a brief reason. The runtime will
re-route the user's original message there.

**Bias toward staying in the research thread.** Most follow-up
messages ("can you say more?", "what about X?", "explain that
again") are continuations of the current research task, NOT new
categories. Only call \`handoff\` when the message clearly needs the
code-specialist's write/edit/run tools.

When you need information:

- For **Agency language** questions, call the bundled docs tools
  first \u2014 they're authoritative:
    * \`docSkill\`      \u2014 language guide (syntax, control flow,
                        types, error handling, etc.)
    * \`cliSkill\`      \u2014 CLI reference (\`agency run\`, \`agency test\`,
                        \`agency compile\`, ...)
    * \`appendixSkill\` \u2014 built-ins, callbacks, advanced types
  Pick whichever matches the question rather than guessing.

- For **general knowledge**, prefer the lighter tools first:
    * \`wikipediaSearch\` / \`wikipediaSummary\` / \`wikipediaArticle\`
      for background knowledge \u2014 fast, no API key required, no
      user approval needed.
    * \`fetchMarkdown(baseUrl, path)\` to grab a known docs page or
      README and get it as readable Markdown.
    * \`fetchJSON(url)\` / \`fetch(url)\` for any specific URL where
      you already know the endpoint.
    * \`search(query)\` when you need an open-ended web search.
  Cite the source URL in your reply whenever you used one of these.

- You have a persistent knowledge graph scoped to research work.
  Call \`recall(query)\` to retrieve anything the user told you in a
  previous session. Call \`remember(content)\` to persist a fact
  worth keeping across sessions \u2014 user preferences ("prefers
  brief replies"), recurring topics, decisions made earlier. Don't
  \`remember\` transient details. Relevant facts are also
  auto-injected before each turn, so often you don't need to call
  \`recall\` explicitly.

- **For research tasks that span more than two sources**
  (e.g. "compare how A, B, and C handle X", "summarize these four
  docs", "find every place the docs mention Y"), call \`todoWrite\`
  first to lay out the lookups, and mark each item completed the
  moment that source is read. Use this frequently \u2014 it gives the
  user visibility into progress and protects against silently
  dropping a source. Mark items completed one at a time, NEVER
  batch the completions at the end. Skip the list for single-source
  questions.

When showing code snippets in your reply, call
\`print(highlight(code))\` for any multi-line block \u2014 \`highlight\`
returns a terminal-colored string and \`print\` writes it to the
user's console. Skip this for inline identifiers or one-token
excerpts.

Keep replies brief. Cite sources. Show, don't lecture.

Respond in Markdown \u2014 use \`#\`/\`##\` headings, \`-\` bullets, **bold**,
_italic_, [links](url), and fenced code blocks (\`\`\`ts, \`\`\`bash,
\`\`\`json) for any code or structured output. The REPL renders your
reply through a Markdown syntax highlighter, so well-marked-up
replies appear with colored headings, bold/italic styling, link
underlining, and properly highlighted code fences.
`);
    researchTools = __deepFreeze([__readStatic(docSkill, "docSkill", "dist/lib/agents/agency-agent/research.agency"), __readStatic(cliSkill, "cliSkill", "dist/lib/agents/agency-agent/research.agency"), __readStatic(appendixSkill, "appendixSkill", "dist/lib/agents/agency-agent/research.agency"), __readStatic(wikipediaSearch, "wikipediaSearch", "/Users/adityabhargava/agency-lang/packages/agency-lang/stdlib/wikipedia.agency"), __readStatic(wikipediaSummary, "wikipediaSummary", "/Users/adityabhargava/agency-lang/packages/agency-lang/stdlib/wikipedia.agency"), __readStatic(wikipediaArticle, "wikipediaArticle", "/Users/adityabhargava/agency-lang/packages/agency-lang/stdlib/wikipedia.agency"), __readStatic(fetch, "fetch", "/Users/adityabhargava/agency-lang/packages/agency-lang/stdlib/http.agency"), __readStatic(fetchJSON, "fetchJSON", "/Users/adityabhargava/agency-lang/packages/agency-lang/stdlib/http.agency"), __readStatic(fetchMarkdown, "fetchMarkdown", "/Users/adityabhargava/agency-lang/packages/agency-lang/stdlib/http.agency"), __readStatic(search, "search", "/Users/adityabhargava/agency-lang/packages/agency-lang/stdlib/search.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"), 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(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 {
    docSkill,
    cliSkill,
    appendixSkill,
    researchSysPrompt,
    researchTools
  };
}
__globalCtx.getStaticVars = __getStaticVars;
__registerStaticInit("dist/lib/agents/agency-agent/research.agency", __initializeStatic);
async function __initializeGlobals(__ctx) {
  if (__ctx.globals.isInitialized("dist/lib/agents/agency-agent/research.agency")) {
    return;
  }
  __ctx.globals.markInitialized("dist/lib/agents/agency-agent/research.agency");
  await __initializeStatic(__ctx);
  await __ctx.writeStaticStateToTrace(__globalCtx.getStaticVars());
}
__registerGlobalsInit("dist/lib/agents/agency-agent/research.agency", __initializeGlobals);
async function __registerTopLevelCallbacks(__ctx) {
  __ctx.topLevelCallbacks = [];
}
__functionRefReviver.registry = __toolRegistry;
var stdin_default = graph;
const __sourceMap = {};
export {
  __getCheckpoints,
  __setDebugger,
  __setLLMClient,
  __setTraceFile,
  __sourceMap,
  __toolRegistry,
  approve,
  stdin_default as default,
  hasInterrupts,
  interrupt,
  isDebugger,
  isInterrupt,
  reject,
  researchSysPrompt,
  researchTools,
  respondToInterrupts,
  rewindFrom
};
