Skip to content

An open-source, faster Devin alternative

TypeScript
141 KB
Raw Blame
import { createHash } from "node:crypto";
import {
  access,
  cp,
  mkdir,
  readFile,
  readdir,
  rm,
  writeFile,
} from "node:fs/promises";
import { readFileSync } from "node:fs";
import { basename, dirname, join, relative, resolve } from "node:path";
import { fileURLToPath } from "node:url";
import { Cron } from "croner";
import { parse as parseToml } from "smol-toml";
import { build as bundle } from "esbuild";
import ts from "typescript";

import {
  defineMemory,
  documentMemory,
  httpMemory,
  memoryToolNames,
  type DocumentMemoryInput,
  type HttpMemoryConnection,
  type HttpMemoryInput,
  type MemoryDefinition,
  type MemoryDefinitionInput,
  type MemoryProvider,
} from "./memory.js";
import { type DeploymentEgress, splitEgressAllow } from "./egress.js";

/**
 * Regions a deployment may name in `opencomputer.toml` (work 057): Modal's
 * sandbox regions, broad then narrow. The service keeps the same list.
 */
export const DEPLOYMENT_REGIONS = [
  "us",
  "eu",
  "ap",
  "us-east",
  "us-central",
  "us-south",
  "us-west",
  "eu-west",
  "eu-north",
  "eu-south",
  "ap-northeast",
  "ap-southeast",
  "ap-south",
  "ap-melbourne",
  "jp",
  "au",
  "uk",
  "ca",
  "me",
  "sa",
  "af",
  "mx",
] as const;
export type DeploymentRegion = (typeof DEPLOYMENT_REGIONS)[number];

export interface AgentManifest {
  schema: 1;
  id: string;
  name: string;
  /** Where the deployment's sessions run; absent means the platform default. */
  region?: DeploymentRegion;
  /** `[egress] allow`, split; absent means an open network. */
  egress?: DeploymentEgress;
  /** `[egress] fixed_ips`: the region whose fixed IPs sandboxes leave from. */
  fixedIps?: string;
}

export interface BuiltAgentArtifact {
  agentId: string;
  name: string;
  channels: string[];
  connections: string[];
  httpConnections: HttpConnectionManifest[];
  githubConnections: GitHubConnectionManifest[];
  memory: MemoryDeclaration[];
  models: Array<{ provider: string; model: string }>;
  region?: DeploymentRegion;
  egress?: DeploymentEgress;
  fixedIps?: string;
  body: Buffer;
  digest: string;
  elapsedMs: number;
}

/**
 * A memory resource as registered with the deployment: the executable
 * definition without its `kind` and `version`. The same id in every agent of
 * a project names the same resource, so declarations sharing an id must agree
 * on the provider and its configuration.
 */
export interface MemoryDeclaration {
  id: string;
  description: string;
  provider: MemoryProvider;
}

export interface HttpConnectionManifest {
  id: string;
  origin: string;
  headers: Record<
    string,
    | string
    | {
        kind: "secret";
        name: string;
        /**
         * Omitted means project-wide; "tenant" resolves per installation and
         * "user" per person acted for.
         */
        scope?: "tenant" | "user";
        prefix?: string;
        suffix?: string;
      }
  >;
  methods?: string[];
  pathPrefix?: string;
  redirectOrigins?: Array<{ origin: string; pathPrefix?: string }>;
}

export type GitHubAppPermission = "read" | "write";

export interface GitHubConnectionManifest {
  id: string;
  provider: {
    kind: "github-app";
    permissions: Record<string, GitHubAppPermission>;
  };
}

/** The platform's question tool. Selected with useTool("ask"); no defined tool may take the id. */
const ASK_TOOL = "ask";

export interface McpServerManifest {
  id: string;
  url: string;
  connection?: string;
}

export type ChannelProviderManifest = "slack" | "twilio" | "email";

export interface ChannelDestinationManifest {
  type: "conversation" | "reply";
  visibility?: "public" | "private";
}

export interface ChannelDefinitionManifest {
  id: string;
  type: ChannelProviderManifest;
  displayName?: string;
  /** Slack only. */
  scopes?: { bot: string[] };
  events: string[];
  destinations: Record<string, ChannelDestinationManifest>;
  routing: { whenAmbiguous: "ask" };
  idle: { suspendAfterSeconds: number };
}

export interface ChannelRegistrationManifest {
  agentId: string;
  channelId: string;
  triggers: Array<"mention" | "direct-message" | "message">;
}

export interface OutboxDefinitionManifest {
  id: string;
  channelId: string;
  destination: string;
}

export interface OutboxRegistrationManifest {
  agentId: string;
  outboxId: string;
}

export interface ScheduleDefinitionManifest {
  id: string;
  agentId: string;
  cron: string;
  timezone: string;
  /**
   * Environments the schedule runs in. `production` also covers a
   * single-environment project's `default` scope; `development` alone
   * leaves it manual there.
   */
  enabled: Array<"default" | "development" | "production">;
  overlap: "skip" | "allow";
  dispatch: {
    text?: string;
    payload?: unknown;
  };
}

export interface GatedToolManifest {
  agentId: string;
  toolId: string;
}

export interface DatabaseMigrationManifest {
  name: string;
  checksum: string;
  sql: string;
}

export interface ProjectResourceManifest {
  version: 1;
  channels: ChannelDefinitionManifest[];
  channelRegistrations: ChannelRegistrationManifest[];
  outboxes: OutboxDefinitionManifest[];
  outboxRegistrations: OutboxRegistrationManifest[];
  schedules: ScheduleDefinitionManifest[];
  /** Ordered schema migrations for the environment's default database. */
  database?: { migrations: DatabaseMigrationManifest[] };
  /**
   * Which tools wait for a human. Declared here as well as in the agent's own
   * manifest because the platform authorizes a proposal before any agent code
   * is involved.
   */
  gatedTools: GatedToolManifest[];
}

export interface BuiltProjectResources {
  manifest: ProjectResourceManifest;
  digest: string;
}

export interface ProjectAgentSource {
  localId: string;
  root: string;
  manifest: AgentManifest;
}

const AGENT_ID_PATTERN = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;

async function exists(path: string): Promise<boolean> {
  try {
    await access(path);
    return true;
  } catch {
    return false;
  }
}

async function updateGitignore(root: string): Promise<void> {
  const path = resolve(root, ".gitignore");
  const required = [
    "node_modules/",
    "dist/",
    ".opencomputer/",
    ".env",
    ".env.local",
  ];
  let existing = "";
  try {
    existing = await readFile(path, "utf8");
  } catch {
    // New repositories do not have a gitignore yet.
  }
  const lines = new Set(existing.split(/\r?\n/));
  const missing = required.filter((line) => !lines.has(line));
  if (!missing.length) return;
  const prefix =
    existing && !existing.endsWith("\n") ? `${existing}\n` : existing;
  await writeFile(path, `${prefix}${missing.join("\n")}\n`);
}

export function agentIdFromName(value: string): string {
  const id = value
    .toLowerCase()
    .replace(/[^a-z0-9]+/g, "-")
    .replace(/^-+|-+$/g, "");
  if (!id || !AGENT_ID_PATTERN.test(id)) {
    throw new Error("Agent names must contain letters or numbers");
  }
  return id;
}

export async function writeManifest(
  root: string,
  manifest: AgentManifest,
): Promise<void> {
  if (!AGENT_ID_PATTERN.test(manifest.id)) {
    throw new Error(
      "Agent IDs must use lowercase letters, numbers, and single hyphens",
    );
  }
  await writeFile(
    resolve(root, "opencomputer.toml"),
    [
      "# Committed agent identity. Keep `id` stable across deployments.",
      "schema = 1",
      `id = ${JSON.stringify(manifest.id)}`,
      `name = ${JSON.stringify(manifest.name)}`,
      "",
    ].join("\n"),
  );
}

export async function readManifest(root: string): Promise<AgentManifest> {
  if (!(await exists(resolve(root, "opencomputer.toml")))) {
    const id = agentIdFromName(basename(root));
    return {
      schema: 1,
      id,
      name: id
        .split("-")
        .map((part) => `${part.slice(0, 1).toUpperCase()}${part.slice(1)}`)
        .join(" "),
    };
  }
  const source = await readFile(resolve(root, "opencomputer.toml"), "utf8");
  let toml: Record<string, unknown>;
  try {
    toml = parseToml(source);
  } catch (error) {
    if (/^\s*region\s*=\s*[^"\s]/m.test(source)) {
      throw new Error('opencomputer.toml region must be a quoted string, e.g. region = "au"');
    }
    throw new Error(
      `opencomputer.toml is not valid TOML: ${error instanceof Error ? error.message.split("\n")[0] : String(error)}`,
    );
  }
  const { schema, id, name, region } = toml;
  if (
    schema !== 1 ||
    typeof id !== "string" ||
    typeof name !== "string" ||
    !id ||
    !name ||
    !AGENT_ID_PATTERN.test(id)
  ) {
    throw new Error(
      "opencomputer.toml must contain schema = 1 and a valid id and name",
    );
  }
  if (region !== undefined && typeof region !== "string") {
    throw new Error('opencomputer.toml region must be a quoted string, e.g. region = "au"');
  }
  if (
    region !== undefined &&
    !(DEPLOYMENT_REGIONS as readonly string[]).includes(region)
  ) {
    throw new Error(
      `opencomputer.toml region ${JSON.stringify(region)} is not supported; use one of: ${DEPLOYMENT_REGIONS.join(", ")}`,
    );
  }
  const { egress, fixedIps } = manifestEgress(toml.egress);
  return {
    schema: 1,
    id,
    name,
    ...(region ? { region: region as DeploymentRegion } : {}),
    ...(egress ? { egress } : {}),
    ...(fixedIps ? { fixedIps } : {}),
  };
}

/**
 * The `[egress]` table. `allow` restricts the network; `fixed_ips` sends it
 * out through a region's fixed IPs (the service lists them at
 * /v1/egress-ips and refuses a region without them). With `fixed_ips` and no
 * `allow` the network stays open; a table with neither allows only the
 * platform's own hosts.
 */
function manifestEgress(table: unknown): { egress?: DeploymentEgress; fixedIps?: string } {
  if (table === undefined) return {};
  if (typeof table !== "object" || table === null || Array.isArray(table)) {
    throw new Error("opencomputer.toml egress must be a table: [egress]");
  }
  const unknown = Object.keys(table).filter((key) => key !== "allow" && key !== "fixed_ips");
  if (unknown.length) {
    throw new Error(
      `opencomputer.toml [egress] has unknown key ${JSON.stringify(unknown[0])}; only allow and fixed_ips are supported`,
    );
  }
  const { allow, fixed_ips: fixedIps } = table as { allow?: unknown; fixed_ips?: unknown };
  if (fixedIps !== undefined && (typeof fixedIps !== "string" || !/^[a-z]{2,3}$/.test(fixedIps))) {
    throw new Error('opencomputer.toml [egress] fixed_ips must be a region, e.g. fixed_ips = "au"');
  }
  if (fixedIps === undefined) return { egress: splitEgressAllow(allow ?? []) };
  return { ...(allow !== undefined ? { egress: splitEgressAllow(allow) } : {}), fixedIps };
}

export async function findAgentRoot(
  startDirectory = process.cwd(),
): Promise<string | undefined> {
  let directory = resolve(startDirectory);
  for (;;) {
    const nested = resolve(directory, "opencomputer");
    if (await exists(resolve(directory, "agent.ts"))) {
      return directory;
    }
    if (await exists(resolve(nested, "agent.ts"))) {
      return nested;
    }
    for (const agentsDirectory of [
      resolve(directory, "opencomputer", "agents"),
      resolve(directory, "agents"),
    ]) {
      if (!(await exists(agentsDirectory))) continue;
      const detected: string[] = [];
      for (const entry of await readdir(agentsDirectory, {
        withFileTypes: true,
      })) {
        if (!entry.isDirectory()) continue;
        const agent = resolve(agentsDirectory, entry.name);
        if (await exists(resolve(agent, "agent.ts"))) {
          detected.push(agent);
        }
      }
      if (detected.length === 1) return detected[0];
      if (detected.length > 1) {
        throw new Error(
          "This project has multiple agents. Select an agent when starting dev mode.",
        );
      }
    }
    const parent = dirname(directory);
    if (parent === directory) return undefined;
    directory = parent;
  }
}

function projectAgentIds(source: string, path: string): string[] {
  const file = ts.createSourceFile(path, source, ts.ScriptTarget.Latest, true);
  for (const statement of file.statements) {
    if (
      !ts.isExportAssignment(statement) ||
      !ts.isObjectLiteralExpression(statement.expression)
    ) {
      continue;
    }
    const property = statement.expression.properties.find(
      (candidate): candidate is ts.PropertyAssignment =>
        ts.isPropertyAssignment(candidate) &&
        ((ts.isIdentifier(candidate.name) &&
          candidate.name.text === "agents") ||
          (ts.isStringLiteral(candidate.name) &&
            candidate.name.text === "agents")),
    );
    if (!property || !ts.isArrayLiteralExpression(property.initializer)) break;
    const ids = property.initializer.elements.map((element) => {
      if (!ts.isStringLiteralLike(element)) {
        throw new Error(
          "opencomputer/project.ts agents must be string literals",
        );
      }
      return element.text;
    });
    if (!ids.length || new Set(ids).size !== ids.length) {
      throw new Error(
        "opencomputer/project.ts must list at least one unique agent",
      );
    }
    return ids;
  }
  throw new Error(
    "opencomputer/project.ts must export an object with an agents array",
  );
}

export async function readProjectAgents(
  projectRoot: string,
): Promise<ProjectAgentSource[]> {
  const path = resolve(projectRoot, "opencomputer", "project.ts");
  const ids = projectAgentIds(await readFile(path, "utf8"), path);
  return Promise.all(
    ids.map(async (localId) => {
      if (!AGENT_ID_PATTERN.test(localId)) {
        throw new Error(`Invalid project agent ID: ${localId}`);
      }
      const root = resolve(projectRoot, "opencomputer", "agents", localId);
      if (!(await exists(resolve(root, "agent.ts")))) {
        throw new Error(
          `Project agent ${localId} is missing opencomputer/agents/${localId}/agent.ts`,
        );
      }
      return { localId, root, manifest: await readManifest(root) };
    }),
  );
}

export async function assertStarterTarget(directory: string): Promise<void> {
  const root = resolve(directory);
  if (!(await exists(root))) {
    await mkdir(root, { recursive: true });
    return;
  }
  const reserved = [
    "opencomputer/project.ts",
    "opencomputer/agents/hello-world/agent.ts",
    "package.json",
    "vite.config.ts",
    "index.html",
    "src/App.tsx",
    "src/main.tsx",
  ];
  const conflicts: string[] = [];
  for (const path of reserved) {
    if (await exists(resolve(root, path))) conflicts.push(path);
  }
  if (conflicts.length) {
    throw new Error(
      `Target already contains OpenComputer app files: ${conflicts.join(", ")}`,
    );
  }
}

export async function initializeAgentProject(
  directory: string,
  project?: { id: string; name: string; agentId: string },
  options: { spa?: boolean } = {},
): Promise<{
  root: string;
  agentRoot: string;
  manifest: AgentManifest;
  files: string[];
}> {
  const root = resolve(directory);
  const spa = options.spa ?? false;
  const agentRoot = resolve(root, "opencomputer", "agents", "hello-world");
  await assertStarterTarget(root);
  await mkdir(agentRoot, { recursive: true });
  const manifest: AgentManifest = {
    schema: 1,
    id: project?.agentId ?? "hello-world",
    name: "Hello World",
  };
  for (const path of [
    "opencomputer.toml",
    "opencomputer.config.ts",
    "opencomputer.ts",
    "opencode.json",
    "package.json",
    ".gitignore",
    "README.md",
    "tools",
    "connections",
    "skills",
    "channels",
    "workspace",
    "evals",
  ]) {
    await rm(resolve(agentRoot, path), { recursive: true, force: true });
  }
  await writeManifest(agentRoot, manifest);
  await writeFile(
    resolve(agentRoot, "agent.ts"),
    `import { useInput, useModel } from "@opencomputer/agent";

export default function Agent() {
  const input = useInput();
  useModel("anthropic/claude-sonnet-4.6");

  return input.text
    ? "You are a helpful OpenComputer agent. Respond directly to: " + input.text
    : "You are a helpful OpenComputer agent.";
}
`,
  );
  await updateGitignore(root);
  await writeFile(
    resolve(root, "opencomputer", ".env.example"),
    `# Development agent secrets belong in .env.local beside this file.
# Add only names referenced by useSecret() in a defineConnection() declaration.
`,
  );
  if (spa) await mkdir(resolve(root, "src"), { recursive: true });
  await writeFile(
    resolve(root, "opencomputer", "project.ts"),
    `export default {
  name: ${JSON.stringify(project?.name ?? basename(root))},
  agents: ["hello-world"],
};
`,
  );

  await writeFile(
    resolve(root, "package.json"),
    `${JSON.stringify(
      {
        name: `opencomputer-app-${manifest.id}`,
        version: "0.1.0",
        private: true,
        type: "module",
        scripts: {
          ...(spa ? { "dev:web": "vite", build: "tsc -b && vite build" } : {}),
          session: "opencomputer session",
          deploy: "opencomputer deploy",
        },
        dependencies: {
          "@opencomputer/agent": "^0.8.0",
          ...(spa
            ? {
                "@opencomputer/react": "^0.4.0",
                react: "^19.2.0",
                "react-dom": "^19.2.0",
              }
            : {}),
        },
        devDependencies: {
          "@opencomputer/cli": "^0.7.0",
          ...(spa
            ? {
                "@types/node": "^24.0.0",
                "@types/react": "^19.2.0",
                "@types/react-dom": "^19.2.0",
                "@vitejs/plugin-react": "^6.0.0",
                typescript: "^5.9.0",
                vite: "^8.0.0",
              }
            : {}),
        },
      },
      null,
      2,
    )}\n`,
  );
  if (spa)
    await writeFile(
      resolve(root, "vite.config.ts"),
      `import { readFileSync } from "node:fs";
import { resolve } from "node:path";
import react from "@vitejs/plugin-react";
import { defineConfig } from "vite";

function openComputerDev() {
  try {
    return JSON.parse(
      readFileSync(resolve(".opencomputer/dev.json"), "utf8"),
    ) as { url: string; token: string; agent: string };
  } catch {
    throw new Error(
      "OpenComputer is not running. Start npm run deploy -- --watch first.",
    );
  }
}

function openComputerAgent() {
  try {
    const binding = JSON.parse(
      readFileSync(resolve(".opencomputer/project.json"), "utf8"),
    ) as { agentId?: string };
    if (binding.agentId) return binding.agentId;
  } catch {
    // The production build below reports the actionable binding error.
  }
  throw new Error(
    "This app is not connected to an OpenComputer project. Run npm run deploy -- --watch first.",
  );
}

export default defineConfig(({ command }) => {
  const dev = command === "serve" ? openComputerDev() : undefined;
  // A bare agent id addresses the live deployment: Production for a legacy
  // project, the single environment otherwise.
  return {
    plugins: [react()],
    define: {
      __OPENCOMPUTER_AGENT__: JSON.stringify(dev?.agent ?? openComputerAgent()),
    },
    ...(dev ? { server: {
      proxy: {
        "/api/opencomputer": {
          target: dev.url,
          headers: { authorization: \`Bearer \${dev.token}\` },
          rewrite: (path) => path.replace(/^\\/api\\/opencomputer/, ""),
        },
      },
    } } : {}),
  };
});
`,
    );
  if (spa)
    await writeFile(
      resolve(root, "tsconfig.json"),
      `${JSON.stringify(
        {
          compilerOptions: {
            target: "ES2022",
            useDefineForClassFields: true,
            lib: ["ES2022", "DOM", "DOM.Iterable"],
            allowJs: false,
            skipLibCheck: true,
            esModuleInterop: true,
            allowSyntheticDefaultImports: true,
            strict: true,
            forceConsistentCasingInFileNames: true,
            module: "ESNext",
            moduleResolution: "Bundler",
            resolveJsonModule: true,
            isolatedModules: true,
            noEmit: true,
            jsx: "react-jsx",
            types: ["node", "vite/client"],
          },
          include: ["src", "vite.config.ts"],
        },
        null,
        2,
      )}\n`,
    );
  if (spa)
    await writeFile(
      resolve(root, "index.html"),
      `<!doctype html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta name="theme-color" content="#11110f" />
    <title>Hello World · OpenComputer</title>
  </head>
  <body>
    <div id="root"></div>
    <script type="module" src="/src/main.tsx"></script>
  </body>
</html>
`,
    );
  if (spa)
    await writeFile(
      resolve(root, "src", "App.tsx"),
      `import { useAgent } from "@opencomputer/react";
import { FormEvent, useState } from "react";

declare const __OPENCOMPUTER_AGENT__: string;

export default function App() {
  const [input, setInput] = useState("");
  const { messages, send, isRunning, error } = useAgent(__OPENCOMPUTER_AGENT__);

  function submit(event: FormEvent) {
    event.preventDefault();
    const prompt = input;
    setInput("");
    // send rejects when no turn was admitted; the hook shows the error and
    // the draft comes back.
    send(prompt).catch(() => setInput(prompt));
  }

  return (
    <main>
      <section className="hero">
        <span className="eyebrow">OpenComputer</span>
        <h1>Hello, world.</h1>
        <p>Your first agent is live. The React app stays local while agent code syncs to Development (Cloud).</p>
      </section>

      <section className="chat" aria-label="Agent conversation">
        <div className="messages">
          {messages.length === 0 ? (
            <button className="suggestion" onClick={() => send("Say hello and tell me what you can do.").catch(() => undefined)}>
              Say hello and tell me what you can do →
            </button>
          ) : (
            messages.map((message) => (
              <article key={message.id} className={message.role}>
                <strong>{message.role === "user" ? "You" : "Agent"}</strong>
                <p>{message.text || "Thinking…"}</p>
              </article>
            ))
          )}
        </div>
        {error ? <p className="error">{error}</p> : null}
        <form onSubmit={submit}>
          <input
            value={input}
            onChange={(event) => setInput(event.target.value)}
            placeholder="Message the hello-world agent…"
            aria-label="Message"
          />
          <button disabled={isRunning || !input.trim()}>
            {isRunning ? "Running…" : "Send"}
          </button>
        </form>
      </section>
    </main>
  );
}
`,
    );
  if (spa)
    await writeFile(
      resolve(root, "src", "main.tsx"),
      `import { StrictMode } from "react";
import { createRoot } from "react-dom/client";
import App from "./App";
import "./styles.css";

createRoot(document.getElementById("root")!).render(
  <StrictMode>
    <App />
  </StrictMode>,
);
`,
    );
  if (spa)
    await writeFile(
      resolve(root, "src", "styles.css"),
      `@import url("https://fonts.googleapis.com/css2?family=DM+Sans:wght@400;500;600&family=DM+Serif+Display&display=swap");

:root { color: #1d1c19; background: #f4f1e9; font-family: "DM Sans", sans-serif; }
* { box-sizing: border-box; }
body { margin: 0; min-width: 320px; min-height: 100vh; }
button, input { font: inherit; }
main { width: min(760px, calc(100% - 32px)); margin: 0 auto; padding: 12vh 0 48px; }
.hero { margin-bottom: 36px; }
.eyebrow { color: #706b60; font-size: 12px; font-weight: 600; letter-spacing: .12em; text-transform: uppercase; }
h1 { margin: 10px 0; font: 400 clamp(48px, 10vw, 84px)/.95 "DM Serif Display", serif; }
.hero p { max-width: 580px; color: #625e55; font-size: 18px; line-height: 1.6; }
.chat { overflow: hidden; border: 1px solid #d9d4c8; border-radius: 18px; background: rgba(255,255,255,.72); box-shadow: 0 18px 60px rgba(56,48,34,.08); }
.messages { display: grid; gap: 14px; min-height: 260px; max-height: 52vh; overflow-y: auto; padding: 24px; }
article { max-width: 82%; border-radius: 14px; padding: 12px 14px; }
article strong { display: block; margin-bottom: 4px; font-size: 12px; color: #777166; }
article p { margin: 0; line-height: 1.55; white-space: pre-wrap; }
article.user { justify-self: end; background: #1d1c19; color: white; }
article.user strong { color: #bdb7ab; }
article.assistant { background: #ece8de; }
.suggestion { align-self: center; justify-self: center; border: 1px solid #d9d4c8; border-radius: 999px; background: transparent; padding: 10px 16px; cursor: pointer; }
.suggestion:hover { background: #ece8de; }
.error { margin: 0 24px 12px; color: #a33a2b; font-size: 14px; }
form { display: flex; gap: 10px; border-top: 1px solid #ddd8cc; padding: 14px; background: white; }
input { min-width: 0; flex: 1; border: 0; outline: 0; padding: 10px; background: transparent; }
form button { border: 0; border-radius: 10px; background: #d85b35; color: white; padding: 10px 18px; font-weight: 600; cursor: pointer; }
form button:disabled { cursor: default; opacity: .45; }
`,
    );
  await writeFile(
    resolve(root, "README.md"),
    spa
      ? `# Hello World OpenComputer app

This project keeps agent definitions in \`opencomputer/\` and the React app in
\`src/\`.

Deploy agent changes to Development (Cloud):

\`\`\`bash
npm run deploy -- --watch
\`\`\`

Start the web app separately:

\`\`\`bash
npm run dev:web
\`\`\`

Link once with \`opencomputer link --project <id|slug>\` or
\`opencomputer link --create-project <name>\`. Later commands reuse that binding.

Declare required names in \`opencomputer/.env.example\` and set values with
\`opencomputer secrets set <name> --value-stdin\`. Allowed origins are inferred
from \`defineConnection()\` declarations.
`
      : `# Hello World OpenComputer agent

This project keeps agent definitions in \`opencomputer/\`.

Deploy agent changes to Development (Cloud):

\`\`\`bash
npm run deploy -- --watch
\`\`\`

Link once with \`opencomputer link --project <id|slug>\` or
\`opencomputer link --create-project <name>\`. Later commands reuse that binding.

Declare required names in \`opencomputer/.env.example\` and set values with
\`opencomputer secrets set <name> --value-stdin\`. Allowed origins are inferred
from \`defineConnection()\` declarations.
`,
  );

  const appFiles = spa
    ? [
        "package.json",
        "vite.config.ts",
        "tsconfig.json",
        "index.html",
        "README.md",
        ".gitignore",
        "src/App.tsx",
        "src/main.tsx",
        "src/styles.css",
      ]
    : ["package.json", "README.md", ".gitignore"];
  return {
    root,
    agentRoot,
    manifest,
    files: [
      "opencomputer/project.ts",
      "opencomputer/.env.example",
      "opencomputer/agents/hello-world/opencomputer.toml",
      "opencomputer/agents/hello-world/agent.ts",
      ...appFiles,
    ],
  };
}

function literalHookIds(source: string, hook: string): string[] {
  const pattern = new RegExp(`\\b${hook}\\(\\s*["']([^"']+)["']`, "g");
  return [...source.matchAll(pattern)].map((match) => match[1]!).sort();
}

/**
 * The grant a managed service belongs to.
 *
 * The platform gates a session's connections on the PROVIDER, not the service:
 * gmail, calendar, drive and sheets are one Google grant, and github is its
 * own. An agent declares the service it uses, because that is what it calls;
 * the deployment records the provider, because that is what was consented to.
 */
const MANAGED_SERVICE_PROVIDERS: Readonly<Record<string, string>> = {
  gmail: "google",
  google: "google",
  calendar: "google",
  drive: "google",
  sheets: "google",
  github: "github",
  linear: "linear",
};

function declaredServiceProviders(agentSource: string): string[] {
  const declared = literalHookIds(agentSource, "useService");
  const unknown = declared.find(
    (service) => !MANAGED_SERVICE_PROVIDERS[service.trim().toLowerCase()],
  );
  if (unknown) {
    throw new Error(
      `useService(${JSON.stringify(unknown)}) names no managed service; ` +
        `expected one of ${Object.keys(MANAGED_SERVICE_PROVIDERS).join(", ")}`,
    );
  }
  return [
    ...new Set(
      declared.map(
        (service) => MANAGED_SERVICE_PROVIDERS[service.trim().toLowerCase()]!,
      ),
    ),
  ];
}

function definedConnectionBindings(
  source: string,
  path: string,
): Map<string, HttpConnectionManifest> {
  const file = ts.createSourceFile(path, source, ts.ScriptTarget.Latest, true);
  const definitions = new Map(
    definedHttpConnections(source, path).map((definition) => [
      definition.id,
      definition,
    ]),
  );
  const bindings = new Map<string, HttpConnectionManifest>();
  const visit = (node: ts.Node): void => {
    if (
      ts.isVariableDeclaration(node) &&
      ts.isIdentifier(node.name) &&
      node.initializer &&
      ts.isCallExpression(node.initializer) &&
      ts.isIdentifier(node.initializer.expression) &&
      node.initializer.expression.text === "defineConnection"
    ) {
      const input = node.initializer.arguments[0];
      if (input && ts.isObjectLiteralExpression(input)) {
        const id = literalStringValue(
          objectProperty(input, "id"),
          "connection id",
        );
        const definition = definitions.get(id);
        if (definition) bindings.set(node.name.text, definition);
      }
    }
    ts.forEachChild(node, visit);
  };
  visit(file);
  return bindings;
}

function definedMcpServers(
  source: string,
  path: string,
  connectionBindings: ReadonlyMap<string, HttpConnectionManifest>,
): McpServerManifest[] {
  const file = ts.createSourceFile(path, source, ts.ScriptTarget.Latest, true);
  const definitions: McpServerManifest[] = [];
  const visit = (node: ts.Node): void => {
    if (
      ts.isCallExpression(node) &&
      ts.isIdentifier(node.expression) &&
      node.expression.text === "defineMcpServer"
    ) {
      const input = node.arguments[0];
      if (!input || !ts.isObjectLiteralExpression(input)) {
        throw new Error("defineMcpServer() requires an object literal");
      }
      const id = literalStringValue(
        objectProperty(input, "id"),
        "MCP server id",
      );
      const value = literalStringValue(
        objectProperty(input, "url"),
        `MCP server ${id} URL`,
      );
      const url = new URL(value);
      if (url.protocol !== "https:") {
        throw new Error(`MCP server ${id} must use HTTPS`);
      }
      const connectionExpression = objectProperty(input, "connection");
      let connection: HttpConnectionManifest | undefined;
      if (connectionExpression) {
        if (!ts.isIdentifier(connectionExpression)) {
          throw new Error(
            `MCP server ${id} connection must reference a defineConnection() binding`,
          );
        }
        connection = connectionBindings.get(connectionExpression.text);
        if (!connection) {
          throw new Error(
            `MCP server ${id} references unknown connection ${connectionExpression.text}`,
          );
        }
        if (
          url.origin !== connection.origin ||
          (connection.pathPrefix &&
            !url.pathname.startsWith(connection.pathPrefix))
        ) {
          throw new Error(
            `MCP server ${id} URL is outside connection ${connection.id}`,
          );
        }
      }
      definitions.push({
        id,
        url: url.toString(),
        ...(connection ? { connection: connection.id } : {}),
      });
    }
    ts.forEachChild(node, visit);
  };
  visit(file);
  return definitions.sort((left, right) => left.id.localeCompare(right.id));
}

/**
 * The memory authoring functions the compiler registers from. A declaration
 * only counts when one of them is called directly, through a binding that
 * the compiler can trace to `@opencomputer/agent` (a named import, or a
 * re-export chain through the project's own modules), on literal arguments:
 * that is what lets the compiler run the same `defineMemory()` the artifact
 * runs and emit the executable definition itself. Any other reach (an alias,
 * a namespace member, a wrapper, a dynamic import) would let the definition
 * execute without being registered, or register something the definition
 * does not mean, so the build rejects it. A property, string or local
 * function that merely spells one of these names is unrelated to them.
 */
type MemoryAuthoringFunction = "defineMemory" | "documentMemory" | "httpMemory";

const MEMORY_AUTHORING_FUNCTIONS: ReadonlySet<string> =
  new Set<MemoryAuthoringFunction>([
    "defineMemory",
    "documentMemory",
    "httpMemory",
  ]);

const AGENT_PACKAGE = "@opencomputer/agent";

/** What a module makes available to importers, as far as memory authoring goes. */
interface MemoryModuleExports {
  /** Exported name -> the authoring function it is. */
  functions: Map<string, MemoryAuthoringFunction>;
  /** Exported names that are a namespace exposing the authoring functions. */
  namespaces: Set<string>;
}

/** The local identifiers of one module that reach the authoring functions. */
interface MemoryModuleBindings {
  functions: Map<string, MemoryAuthoringFunction>;
  namespaces: Set<string>;
}

const AGENT_PACKAGE_EXPORTS: MemoryModuleExports = {
  functions: new Map(
    [...MEMORY_AUTHORING_FUNCTIONS].map((name) => [
      name,
      name as MemoryAuthoringFunction,
    ]),
  ),
  namespaces: new Set(),
};

const EMPTY_MEMORY_EXPORTS: MemoryModuleExports = {
  functions: new Map(),
  namespaces: new Set(),
};

/**
 * Resolves, across the agent's own source modules, which identifiers are
 * bound to the memory authoring functions of `@opencomputer/agent`. Third
 * party packages are opaque: an import from one binds nothing here.
 */
class MemorySourceResolver {
  private readonly files = new Map<string, ts.SourceFile>();
  private readonly exports = new Map<string, MemoryModuleExports>();
  private readonly resolving = new Set<string>();

  constructor(private readonly modules: readonly AgentSourceModule[]) {}

  file(path: string): ts.SourceFile {
    let file = this.files.get(path);
    if (!file) {
      const module = this.modules.find((candidate) => candidate.path === path);
      if (!module)
        throw new Error(`Agent source module ${path} is not in the build`);
      file = ts.createSourceFile(
        path,
        module.source,
        ts.ScriptTarget.Latest,
        true,
      );
      this.files.set(path, file);
    }
    return file;
  }

  /** The module a specifier names from `from`: the agent package, one of ours, or neither. */
  target(from: string, specifier: string): string | "package" | undefined {
    if (specifier === AGENT_PACKAGE) return "package";
    if (!specifier.startsWith("./") && !specifier.startsWith("../")) {
      return undefined;
    }
    const base = join(dirname(from), specifier).split("\\").join("/");
    const stem = base.replace(/\.[cm]?jsx?$/, "");
    const candidates = [
      base,
      ...["ts", "tsx", "mts", "cts"].map((extension) => `${stem}.${extension}`),
      ...["ts", "tsx", "js", "jsx", "mts", "mjs", "cts", "cjs"].map(
        (extension) => `${base}.${extension}`,
      ),
      ...["ts", "tsx", "js", "jsx"].map(
        (extension) => `${base}/index.${extension}`,
      ),
    ];
    return candidates.find((candidate) =>
      this.modules.some((module) => module.path === candidate),
    );
  }

  exportsOf(target: string | "package" | undefined): MemoryModuleExports {
    if (target === "package") return AGENT_PACKAGE_EXPORTS;
    if (target === undefined) return EMPTY_MEMORY_EXPORTS;
    const cached = this.exports.get(target);
    if (cached) return cached;
    // A cycle contributes nothing on the way round; the first pass wins.
    if (this.resolving.has(target)) return EMPTY_MEMORY_EXPORTS;
    this.resolving.add(target);
    const result: MemoryModuleExports = {
      functions: new Map(),
      namespaces: new Set(),
    };
    const bindings = this.bindingsOf(target);
    for (const statement of this.file(target).statements) {
      if (!ts.isExportDeclaration(statement) || statement.isTypeOnly) continue;
      const source = statement.moduleSpecifier;
      const from =
        source && ts.isStringLiteral(source)
          ? this.exportsOf(this.target(target, source.text))
          : undefined;
      if (!statement.exportClause) {
        // export * from "..."
        for (const [name, fn] of from?.functions ?? [])
          result.functions.set(name, fn);
        for (const name of from?.namespaces ?? []) result.namespaces.add(name);
        continue;
      }
      if (ts.isNamespaceExport(statement.exportClause)) {
        // export * as ns from "..."
        if (from && (from.functions.size || from.namespaces.size)) {
          result.namespaces.add(statement.exportClause.name.text);
        }
        continue;
      }
      for (const specifier of statement.exportClause.elements) {
        if (specifier.isTypeOnly) continue;
        const local = (specifier.propertyName ?? specifier.name).text;
        const exported = specifier.name.text;
        if (from) {
          const fn = from.functions.get(local);
          if (fn) result.functions.set(exported, fn);
          if (from.namespaces.has(local)) result.namespaces.add(exported);
        } else {
          const fn = bindings.functions.get(local);
          if (fn) result.functions.set(exported, fn);
          if (bindings.namespaces.has(local)) result.namespaces.add(exported);
        }
      }
    }
    this.resolving.delete(target);
    this.exports.set(target, result);
    return result;
  }

  /**
   * The object literal an identifier names in `path`, read without
   * evaluating anything: a `const` declared in the module, or a named import
   * of such a `const` from a module inside the agent directory (one hop; a
   * re-export is refused with the module to import from). Every other form
   * fails with the form named, so the fix is one edit.
   */
  staticObjectBinding(
    path: string,
    name: string,
    label: string,
  ): ts.Expression {
    const file = this.file(path);
    const local = localVariable(file, name);
    if (local) {
      return staticObjectInitializer(
        local,
        `${label} references ${name}, which is`,
        `${label} references ${name}, whose`,
      );
    }
    for (const statement of file.statements) {
      if (!ts.isImportDeclaration(statement)) continue;
      const clause = statement.importClause;
      const specifier = statement.moduleSpecifier;
      if (!clause || clause.isTypeOnly || !ts.isStringLiteral(specifier))
        continue;
      if (clause.name?.text === name) {
        throw new Error(
          `${label} references ${name}, the default import of ${specifier.text}; import a named const from a module inside the agent directory`,
        );
      }
      const named = clause.namedBindings;
      if (!named || !ts.isNamedImports(named)) continue;
      const element = named.elements.find(
        (candidate) => !candidate.isTypeOnly && candidate.name.text === name,
      );
      if (!element) continue;
      const imported = (element.propertyName ?? element.name).text;
      const target = this.target(path, specifier.text);
      if (target === "package") {
        throw new Error(
          `${label} references ${name}, imported from ${AGENT_PACKAGE}; a schema must be a const declared in a module inside the agent directory`,
        );
      }
      if (target === undefined) {
        throw new Error(
          `${label} references ${name}, imported from ${specifier.text}, which is not a module inside the agent directory; a schema must be a const declared in one`,
        );
      }
      return this.exportedObject(target, imported, name, label);
    }
    throw new Error(
      `${label} references ${name}, which is neither a const declared in this module nor a named import from a module inside the agent directory`,
    );
  }

  private exportedObject(
    target: string,
    exported: string,
    name: string,
    label: string,
  ): ts.Expression {
    const file = this.file(target);
    for (const statement of file.statements) {
      if (
        ts.isVariableStatement(statement) &&
        statement.modifiers?.some(
          (modifier) => modifier.kind === ts.SyntaxKind.ExportKeyword,
        )
      ) {
        const declaration = statement.declarationList.declarations.find(
          (candidate) =>
            ts.isIdentifier(candidate.name) && candidate.name.text === exported,
        );
        if (declaration) {
          return staticObjectInitializer(
            { statement, declaration },
            `${label} references ${name}, exported by ${target}, which is`,
            `${label} references ${name}, exported by ${target}, whose`,
          );
        }
      }
      if (!ts.isExportDeclaration(statement) || statement.isTypeOnly) continue;
      const clause = statement.exportClause;
      if (!clause || !ts.isNamedExports(clause)) continue;
      const element = clause.elements.find(
        (candidate) =>
          !candidate.isTypeOnly && candidate.name.text === exported,
      );
      if (!element) continue;
      if (statement.moduleSpecifier) {
        throw new Error(
          `${label} references ${name}, which ${target} re-exports from another module; import it from the module that declares it`,
        );
      }
      const localName = (element.propertyName ?? element.name).text;
      const local = localVariable(file, localName);
      if (!local) {
        throw new Error(
          `${label} references ${name}, which ${target} exports as ${exported} without declaring it as a const`,
        );
      }
      const where =
        localName === exported
          ? `exported by ${target}`
          : `exported by ${target} (declared there as ${localName})`;
      return staticObjectInitializer(
        local,
        `${label} references ${name}, ${where}, which is`,
        `${label} references ${name}, ${where}, whose`,
      );
    }
    throw new Error(
      `${label} references ${name}, but ${target} does not export a const named ${exported}`,
    );
  }

  bindingsOf(path: string): MemoryModuleBindings {
    const bindings: MemoryModuleBindings = {
      functions: new Map(),
      namespaces: new Set(),
    };
    for (const statement of this.file(path).statements) {
      if (!ts.isImportDeclaration(statement)) continue;
      const clause = statement.importClause;
      if (
        !clause ||
        clause.isTypeOnly ||
        !ts.isStringLiteral(statement.moduleSpecifier)
      ) {
        continue;
      }
      const from = this.exportsOf(
        this.target(path, statement.moduleSpecifier.text),
      );
      if (!from.functions.size && !from.namespaces.size) continue;
      const named = clause.namedBindings;
      if (named && ts.isNamespaceImport(named)) {
        bindings.namespaces.add(named.name.text);
      } else if (named) {
        for (const specifier of named.elements) {
          if (specifier.isTypeOnly) continue;
          const imported = (specifier.propertyName ?? specifier.name).text;
          const fn = from.functions.get(imported);
          if (fn) bindings.functions.set(specifier.name.text, fn);
          if (from.namespaces.has(imported))
            bindings.namespaces.add(specifier.name.text);
        }
      }
    }
    return bindings;
  }
}

function isTypeOnlyContext(node: ts.Node): boolean {
  return (
    ts.isTypeNode(node) ||
    (ts.isImportDeclaration(node) && !!node.importClause?.isTypeOnly) ||
    (ts.isExportDeclaration(node) && node.isTypeOnly) ||
    (ts.isImportSpecifier(node) && node.isTypeOnly) ||
    (ts.isExportSpecifier(node) && node.isTypeOnly)
  );
}

/** An identifier that names a property, not a binding: `a.name`, `{ name: 1 }`, `{ name() {} }`. */
function isPropertyNamePosition(node: ts.Identifier): boolean {
  const parent = node.parent;
  return (
    (ts.isPropertyAccessExpression(parent) && parent.name === node) ||
    (ts.isPropertyAssignment(parent) && parent.name === node) ||
    (ts.isPropertySignature(parent) && parent.name === node) ||
    (ts.isPropertyDeclaration(parent) && parent.name === node) ||
    (ts.isMethodDeclaration(parent) && parent.name === node) ||
    (ts.isMethodSignature(parent) && parent.name === node) ||
    (ts.isGetAccessorDeclaration(parent) && parent.name === node) ||
    (ts.isSetAccessorDeclaration(parent) && parent.name === node) ||
    (ts.isEnumMember(parent) && parent.name === node) ||
    (ts.isBindingElement(parent) && parent.propertyName === node) ||
    (ts.isQualifiedName(parent) && parent.right === node)
  );
}

const DIRECT_CALL_HINT = (name: string) =>
  `the compiler registers memory only from a direct ${name}() call, so import ${name} by name from ${AGENT_PACKAGE}`;

/**
 * Rejects every reach to a memory authoring function other than an unaliased
 * import or export and a direct call, so a definition that executes is one
 * the compiler registered and vice versa.
 */
function assertMemoryFunctionsCalledDirectly(
  resolver: MemorySourceResolver,
  path: string,
): MemoryModuleBindings {
  const file = resolver.file(path);
  const bindings = resolver.bindingsOf(path);
  const visit = (node: ts.Node): void => {
    if (isTypeOnlyContext(node)) return;
    if (
      ts.isExportDeclaration(node) &&
      node.moduleSpecifier &&
      node.exportClause &&
      ts.isNamedExports(node.exportClause) &&
      ts.isStringLiteral(node.moduleSpecifier)
    ) {
      // export { a as b } from "...": an aliased re-export of an authoring
      // function would let importers call it under a name the compiler does
      // not register from.
      const from = resolver.exportsOf(
        resolver.target(path, node.moduleSpecifier.text),
      );
      for (const specifier of node.exportClause.elements) {
        if (specifier.isTypeOnly || !specifier.propertyName) continue;
        const imported = specifier.propertyName.text;
        const fn = from.functions.get(imported);
        if (fn && specifier.name.text !== imported) {
          throw new Error(
            `${path} exports ${imported} as ${specifier.name.text}; the compiler registers memory only from a direct ${fn}() call, so keep its name`,
          );
        }
      }
      return;
    }
    if (
      ts.isCallExpression(node) &&
      (node.expression.kind === ts.SyntaxKind.ImportKeyword ||
        (ts.isIdentifier(node.expression) &&
          node.expression.text === "require"))
    ) {
      const argument = node.arguments[0];
      if (argument && ts.isStringLiteralLike(argument)) {
        const from = resolver.exportsOf(resolver.target(path, argument.text));
        if (from.functions.size || from.namespaces.size) {
          throw new Error(
            `${path} imports ${argument.text} dynamically; the compiler registers memory only from a static import, so import defineMemory by name`,
          );
        }
      }
    }
    if (ts.isIdentifier(node) && !isPropertyNamePosition(node)) {
      const parent = node.parent;
      const fn = bindings.functions.get(node.text);
      if (fn) {
        const direct =
          (ts.isCallExpression(parent) && parent.expression === node) ||
          ((ts.isImportSpecifier(parent) || ts.isExportSpecifier(parent)) &&
            parent.name === node &&
            parent.propertyName === undefined);
        if (!direct) {
          if (ts.isImportSpecifier(parent) || ts.isExportSpecifier(parent)) {
            const verb = ts.isImportSpecifier(parent) ? "imports" : "exports";
            const imported = (parent.propertyName ?? parent.name).text;
            throw new Error(
              `${path} ${verb} ${imported} as ${parent.name.text}; the compiler registers memory only from a direct ${fn}() call, so keep its name`,
            );
          }
          throw new Error(
            `${path} uses ${node.text} other than as a direct ${node.text}() call; the compiler registers memory only from that call, so do not alias, wrap, or shadow it`,
          );
        }
      }
      if (
        bindings.namespaces.has(node.text) &&
        !ts.isNamespaceImport(parent) &&
        !(ts.isImportSpecifier(parent) && parent.name === node)
      ) {
        const namespace = node.text;
        if (
          ts.isPropertyAccessExpression(parent) &&
          parent.expression === node
        ) {
          const member = parent.name.text;
          if (MEMORY_AUTHORING_FUNCTIONS.has(member)) {
            const called =
              ts.isCallExpression(parent.parent) &&
              parent.parent.expression === parent;
            throw new Error(
              called
                ? `${path} calls ${namespace}.${member}(); ${DIRECT_CALL_HINT(member)}`
                : `${path} uses ${namespace}.${member} other than as a direct ${member}() call; ${DIRECT_CALL_HINT(member)}`,
            );
          }
          return;
        }
        if (
          ts.isElementAccessExpression(parent) &&
          parent.expression === node
        ) {
          const key = parent.argumentExpression;
          if (!ts.isStringLiteralLike(key)) {
            throw new Error(
              `${path} accesses ${namespace}[...] with a computed key; the compiler cannot tell whether that names a memory authoring function, so import what you need by name from ${AGENT_PACKAGE}`,
            );
          }
          if (MEMORY_AUTHORING_FUNCTIONS.has(key.text)) {
            const called =
              ts.isCallExpression(parent.parent) &&
              parent.parent.expression === parent;
            throw new Error(
              called
                ? `${path} calls ${namespace}[${JSON.stringify(key.text)}](); ${DIRECT_CALL_HINT(key.text)}`
                : `${path} uses ${namespace}[${JSON.stringify(key.text)}] other than as a direct ${key.text}() call; ${DIRECT_CALL_HINT(key.text)}`,
            );
          }
          return;
        }
        throw new Error(
          `${path} uses the namespace import ${namespace} other than as ${namespace}.<name>; the compiler registers memory only from a direct defineMemory() call, so import defineMemory by name from ${AGENT_PACKAGE}`,
        );
      }
    }
    ts.forEachChild(node, visit);
  };
  visit(file);
  return bindings;
}

/**
 * The properties of an object literal as name/value pairs, rejecting every
 * form whose value the compiler cannot read: spreads, shorthand, methods,
 * accessors and computed names. `identifiers` names properties whose value is
 * an identifier reference rather than a literal, allowed in shorthand form.
 */
function literalObjectEntries(
  object: ts.ObjectLiteralExpression,
  label: string,
  identifiers: readonly string[] = [],
): Array<[string, ts.Expression]> {
  return object.properties.map((property): [string, ts.Expression] => {
    if (ts.isSpreadAssignment(property)) {
      throw new Error(
        `${label} cannot spread ${property.expression.getText()}; write each option as a literal property`,
      );
    }
    if (ts.isShorthandPropertyAssignment(property)) {
      const name = property.name.text;
      if (identifiers.includes(name)) return [name, property.name];
      throw new Error(
        `${label} cannot use the shorthand property ${name}; write ${name} as a literal property`,
      );
    }
    if (!ts.isPropertyAssignment(property)) {
      throw new Error(
        `${label} cannot use methods or accessors; write each option as a literal property`,
      );
    }
    return [staticPropertyName(property.name, label), property.initializer];
  });
}

/** The single object-literal argument of an authoring call, or none. */
function literalCallArgument(
  call: ts.CallExpression,
  label: string,
): ts.ObjectLiteralExpression | undefined {
  if (call.arguments.length === 0) return undefined;
  const argument = call.arguments[0];
  if (
    call.arguments.length !== 1 ||
    !argument ||
    !ts.isObjectLiteralExpression(argument)
  ) {
    throw new Error(`${label} requires one object literal argument`);
  }
  return argument;
}

function memoryConnectionPolicy(
  expression: ts.Expression,
  label: string,
  connectionBindings: ReadonlyMap<string, HttpConnectionManifest>,
): HttpMemoryConnection {
  if (!ts.isIdentifier(expression)) {
    throw new Error(
      `${label} connection must reference a defineConnection() binding`,
    );
  }
  const connection = connectionBindings.get(expression.text);
  if (!connection) {
    throw new Error(
      `${label} references unknown connection ${expression.text}`,
    );
  }
  return {
    kind: "connection",
    id: connection.id,
    ...(connection.methods ? { methods: connection.methods } : {}),
    ...(connection.pathPrefix ? { pathPrefix: connection.pathPrefix } : {}),
  };
}

/** Runs a contract function on compile-time input, naming the file on error. */
function inSourceFile<T>(path: string, evaluate: () => T): T {
  try {
    return evaluate();
  } catch (error) {
    throw new Error(
      `${path} ${error instanceof Error ? error.message : String(error)}`,
    );
  }
}

/**
 * The provider a declaration names, produced by running `documentMemory()`
 * or `httpMemory()` on the literal options at the call site.
 */
function memoryProviderValue(
  expression: ts.Expression,
  path: string,
  declaration: string,
  bindings: MemoryModuleBindings,
  connectionBindings: ReadonlyMap<string, HttpConnectionManifest>,
): MemoryProvider {
  const callee =
    ts.isCallExpression(expression) && ts.isIdentifier(expression.expression)
      ? bindings.functions.get(expression.expression.text)
      : undefined;
  if (
    !ts.isCallExpression(expression) ||
    (callee !== "documentMemory" && callee !== "httpMemory")
  ) {
    throw new Error(
      `${path} ${declaration} provider must be an inline documentMemory() or httpMemory() call`,
    );
  }
  const label = `${path} ${declaration} ${callee}()`;
  const argument = literalCallArgument(expression, label);
  if (callee === "documentMemory") {
    const input: Record<string, unknown> = {};
    for (const [name, value] of argument
      ? literalObjectEntries(argument, label)
      : []) {
      input[name] = staticJsonValue(value, `${label} ${name}`);
    }
    return inSourceFile(path, () =>
      documentMemory(input as DocumentMemoryInput),
    );
  }
  if (!argument) {
    throw new Error(`${label} requires a connection`);
  }
  const input: Record<string, unknown> = {};
  for (const [name, value] of literalObjectEntries(argument, label, [
    "connection",
  ])) {
    input[name] =
      name === "connection"
        ? memoryConnectionPolicy(value, label, connectionBindings)
        : staticJsonValue(value, `${label} ${name}`);
  }
  if (!input.connection) {
    throw new Error(
      `${label} connection must reference a defineConnection() binding`,
    );
  }
  return inSourceFile(path, () =>
    httpMemory(input as unknown as HttpMemoryInput),
  );
}

function definedMemory(
  resolver: MemorySourceResolver,
  path: string,
  connectionBindings: ReadonlyMap<string, HttpConnectionManifest>,
): MemoryDeclaration[] {
  const file = resolver.file(path);
  const bindings = assertMemoryFunctionsCalledDirectly(resolver, path);
  const declarations: MemoryDeclaration[] = [];
  const visit = (node: ts.Node): void => {
    if (
      ts.isCallExpression(node) &&
      ts.isIdentifier(node.expression) &&
      bindings.functions.get(node.expression.text) === "defineMemory"
    ) {
      const label = `${path} defineMemory()`;
      const argument = literalCallArgument(node, label);
      if (!argument) {
        throw new Error(`${label} requires one object literal argument`);
      }
      const input: Record<string, unknown> = {};
      const entries = literalObjectEntries(argument, label);
      const idEntry = entries.find(([name]) => name === "id");
      const id = idEntry
        ? staticJsonValue(idEntry[1], `${label} id`)
        : undefined;
      const declaration =
        typeof id === "string" && id ? `Memory ${id}` : "defineMemory()";
      for (const [name, value] of entries) {
        input[name] =
          name === "provider"
            ? memoryProviderValue(
                value,
                path,
                declaration,
                bindings,
                connectionBindings,
              )
            : staticJsonValue(value, `${label} ${name}`);
      }
      const definition: MemoryDefinition = inSourceFile(path, () =>
        defineMemory(input as unknown as MemoryDefinitionInput),
      );
      declarations.push({
        id: definition.id,
        description: definition.description,
        provider: definition.provider,
      });
    }
    ts.forEachChild(node, visit);
  };
  visit(file);
  return declarations;
}

/**
 * Deduplicates declarations by id. Declarations sharing an id name the same
 * resource, so they must agree byte for byte; a difference is a build error
 * naming both origins.
 */
export function mergeMemoryDeclarations(
  entries: ReadonlyArray<{
    origin: string;
    memory: readonly MemoryDeclaration[];
  }>,
): MemoryDeclaration[] {
  const merged = new Map<
    string,
    { origin: string; declaration: MemoryDeclaration }
  >();
  for (const { origin, memory } of entries) {
    for (const declaration of memory) {
      const existing = merged.get(declaration.id);
      if (!existing) {
        merged.set(declaration.id, { origin, declaration });
        continue;
      }
      if (
        JSON.stringify(existing.declaration) !== JSON.stringify(declaration)
      ) {
        throw new Error(
          `Memory ${JSON.stringify(declaration.id)} is declared with different configuration in ${existing.origin} and ${origin}; declarations sharing an id name the same resource and must agree on the provider and its configuration`,
        );
      }
    }
  }
  return [...merged.values()]
    .map(({ declaration }) => declaration)
    .sort((left, right) => left.id.localeCompare(right.id));
}

function objectProperty(
  object: ts.ObjectLiteralExpression,
  name: string,
): ts.Expression | undefined {
  const property = object.properties.find(
    (candidate): candidate is ts.PropertyAssignment =>
      ts.isPropertyAssignment(candidate) &&
      ((ts.isIdentifier(candidate.name) && candidate.name.text === name) ||
        (ts.isStringLiteral(candidate.name) && candidate.name.text === name)),
  );
  return property?.initializer;
}

function literalStringValue(
  expression: ts.Expression | undefined,
  label: string,
): string {
  if (!expression || !ts.isStringLiteralLike(expression)) {
    throw new Error(`${label} must be a string literal`);
  }
  return expression.text;
}

function literalStringArray(
  expression: ts.Expression | undefined,
  label: string,
): string[] {
  if (!expression || !ts.isArrayLiteralExpression(expression)) {
    throw new Error(`${label} must be an array literal`);
  }
  return expression.elements.map((element) =>
    literalStringValue(element, `${label} item`),
  );
}

function staticPropertyName(name: ts.PropertyName, label: string): string {
  if (ts.isIdentifier(name) || ts.isStringLiteralLike(name)) return name.text;
  throw new Error(`${label} must use static property names`);
}

function defaultExportCall(
  source: string,
  path: string,
  helper: string,
): ts.CallExpression {
  const file = ts.createSourceFile(path, source, ts.ScriptTarget.Latest, true);
  const statement = file.statements.find(
    (candidate): candidate is ts.ExportAssignment =>
      ts.isExportAssignment(candidate) &&
      ts.isCallExpression(candidate.expression) &&
      ts.isIdentifier(candidate.expression.expression) &&
      candidate.expression.expression.text === helper,
  );
  if (!statement || !ts.isCallExpression(statement.expression)) {
    throw new Error(`${path} must default-export ${helper}()`);
  }
  return statement.expression;
}

function importedResourceId(
  source: string,
  path: string,
  localName: string,
  label: string,
): string {
  const file = ts.createSourceFile(path, source, ts.ScriptTarget.Latest, true);
  const declaration = file.statements.find(
    (statement): statement is ts.ImportDeclaration =>
      ts.isImportDeclaration(statement) &&
      statement.importClause?.name?.text === localName,
  );
  if (!declaration || !ts.isStringLiteralLike(declaration.moduleSpecifier)) {
    throw new Error(`${path} must default-import the ${label} definition`);
  }
  const module = basename(declaration.moduleSpecifier.text).replace(
    /\.(?:js|ts)$/,
    "",
  );
  if (!AGENT_ID_PATTERN.test(module)) {
    throw new Error(`${path} imports an invalid ${label} resource name`);
  }
  return module;
}

/** Shared across every provider: routing, display name, idle policy. */
function channelCommonManifest(
  input: ts.ObjectLiteralExpression,
  path: string,
): {
  displayName?: string;
  routing: { whenAmbiguous: "ask" };
  idle: { suspendAfterSeconds: number };
} {
  const routingExpression = objectProperty(input, "routing");
  if (routingExpression && !ts.isObjectLiteralExpression(routingExpression)) {
    throw new Error(`${path} routing must be an object literal`);
  }
  if (routingExpression) {
    const ambiguity = objectProperty(routingExpression, "whenAmbiguous");
    if (
      ambiguity &&
      literalStringValue(ambiguity, `${path} ambiguity policy`) !== "ask"
    ) {
      throw new Error(`${path} supports only routing.whenAmbiguous = "ask"`);
    }
  }
  let suspendAfterSeconds = 300;
  const idleExpression = objectProperty(input, "idle");
  if (idleExpression) {
    if (!ts.isObjectLiteralExpression(idleExpression)) {
      throw new Error(`${path} idle must be an object literal`);
    }
    const seconds = objectProperty(idleExpression, "suspendAfterSeconds");
    if (seconds) {
      if (!ts.isNumericLiteral(seconds)) {
        throw new Error(
          `${path} idle.suspendAfterSeconds must be a literal number`,
        );
      }
      suspendAfterSeconds = Number(seconds.text);
      if (
        !Number.isInteger(suspendAfterSeconds) ||
        suspendAfterSeconds < 30 ||
        suspendAfterSeconds > 86_400
      ) {
        throw new Error(
          `${path} idle.suspendAfterSeconds must be between 30 and 86400`,
        );
      }
    }
  }
  const displayNameExpression = objectProperty(input, "displayName");
  return {
    ...(displayNameExpression
      ? {
          displayName: literalStringValue(
            displayNameExpression,
            `${path} displayName`,
          ),
        }
      : {}),
    routing: { whenAmbiguous: "ask" as const },
    idle: { suspendAfterSeconds },
  };
}

/**
 * SMS and email address one participant, so their only destination is a reply
 * on the conversation the message arrived on. Declaring none is the common
 * case and yields a single `reply` destination.
 */
function replyDestinationsManifest(
  input: ts.ObjectLiteralExpression,
  path: string,
): Record<string, ChannelDestinationManifest> {
  const destinations: Record<string, ChannelDestinationManifest> = {};
  const expression = objectProperty(input, "destinations");
  if (expression) {
    if (!ts.isObjectLiteralExpression(expression)) {
      throw new Error(`${path} destinations must be an object literal`);
    }
    for (const property of expression.properties) {
      if (!ts.isPropertyAssignment(property)) {
        throw new Error(`${path} destinations cannot use spreads`);
      }
      const name = staticPropertyName(property.name, `${path} destination`);
      if (!AGENT_ID_PATTERN.test(name)) {
        throw new Error(`${path} has invalid destination ${name}`);
      }
      if (!ts.isObjectLiteralExpression(property.initializer)) {
        throw new Error(
          `${path} destination ${name} must be an object literal`,
        );
      }
      const type = literalStringValue(
        objectProperty(property.initializer, "type"),
        `${path} destination ${name} type`,
      );
      if (type !== "reply") {
        throw new Error(
          `${path} destination ${name} must be { type: "reply" }`,
        );
      }
      destinations[name] = { type: "reply" };
    }
  }
  if (!Object.keys(destinations).length) destinations.reply = { type: "reply" };
  return destinations;
}

function channelDefinition(
  source: string,
  path: string,
): ChannelDefinitionManifest {
  const call = defaultExportCall(source, path, "defineChannel");
  const input = call.arguments[0];
  if (!input || !ts.isObjectLiteralExpression(input)) {
    throw new Error(`${path} defineChannel() requires an object literal`);
  }
  const id = literalStringValue(
    objectProperty(input, "id"),
    `${path} channel id`,
  );
  if (basename(path, ".ts") !== id || !AGENT_ID_PATTERN.test(id)) {
    throw new Error(`${path} filename must match its valid channel id`);
  }
  const type = literalStringValue(
    objectProperty(input, "type"),
    `${path} channel type`,
  );
  const common = channelCommonManifest(input, path);

  if (type === "twilio" || type === "email") {
    return {
      id,
      type,
      ...common,
      events: ["message.inbound"],
      destinations: replyDestinationsManifest(input, path),
    };
  }

  if (type !== "slack") {
    throw new Error(
      `${path} has unsupported channel type ${JSON.stringify(type)}. Supported: slack, twilio, email`,
    );
  }

  const scopesExpression = objectProperty(input, "scopes");
  if (!scopesExpression || !ts.isObjectLiteralExpression(scopesExpression)) {
    throw new Error(`${path} scopes must be an object literal`);
  }
  const scopes = [
    ...new Set(
      literalStringArray(
        objectProperty(scopesExpression, "bot"),
        `${path} Slack bot scopes`,
      ),
    ),
  ].sort();
  const events = [
    ...new Set(
      objectProperty(input, "events")
        ? literalStringArray(objectProperty(input, "events"), `${path} events`)
        : [],
    ),
  ].sort();
  const allowedEvents = new Set(["app_mention", "message.im"]);
  if (events.some((event) => !allowedEvents.has(event))) {
    throw new Error(`${path} declares an unsupported Slack event`);
  }
  const requiredEventScopes: Record<string, string> = {
    app_mention: "app_mentions:read",
    "message.im": "im:history",
  };
  for (const event of events) {
    const required = requiredEventScopes[event]!;
    if (!scopes.includes(required)) {
      throw new Error(`${path} event ${event} requires bot scope ${required}`);
    }
  }
  const destinations: Record<string, ChannelDestinationManifest> = {};
  const destinationsExpression = objectProperty(input, "destinations");
  if (destinationsExpression) {
    if (!ts.isObjectLiteralExpression(destinationsExpression)) {
      throw new Error(`${path} destinations must be an object literal`);
    }
    for (const property of destinationsExpression.properties) {
      if (!ts.isPropertyAssignment(property)) {
        throw new Error(`${path} destinations cannot use spreads`);
      }
      const name = staticPropertyName(property.name, `${path} destination`);
      if (!AGENT_ID_PATTERN.test(name)) {
        throw new Error(`${path} has invalid destination ${name}`);
      }
      if (!ts.isObjectLiteralExpression(property.initializer)) {
        throw new Error(
          `${path} destination ${name} must be an object literal`,
        );
      }
      const destinationType = literalStringValue(
        objectProperty(property.initializer, "type"),
        `${path} destination ${name} type`,
      );
      const visibility = literalStringValue(
        objectProperty(property.initializer, "visibility"),
        `${path} destination ${name} visibility`,
      );
      if (
        destinationType !== "conversation" ||
        (visibility !== "public" && visibility !== "private")
      ) {
        throw new Error(`${path} destination ${name} is unsupported`);
      }
      const required =
        visibility === "private" ? "groups:read" : "channels:read";
      if (!scopes.includes(required) || !scopes.includes("chat:write")) {
        throw new Error(
          `${path} destination ${name} requires ${required} and chat:write`,
        );
      }
      destinations[name] = { type: "conversation", visibility };
    }
  }
  return {
    id,
    type: "slack",
    ...common,
    scopes: { bot: scopes },
    events,
    destinations,
  };
}

function channelRegistration(
  source: string,
  path: string,
  agentId: string,
  channels: ReadonlyMap<string, ChannelDefinitionManifest>,
): ChannelRegistrationManifest {
  const call = defaultExportCall(source, path, "registerChannel");
  const channelExpression = call.arguments[0];
  const input = call.arguments[1];
  if (!channelExpression || !ts.isIdentifier(channelExpression)) {
    throw new Error(`${path} must register an imported channel definition`);
  }
  if (!input || !ts.isObjectLiteralExpression(input)) {
    throw new Error(`${path} registerChannel() requires an object literal`);
  }
  const channelId = importedResourceId(
    source,
    path,
    channelExpression.text,
    "channel",
  );
  const channel = channels.get(channelId);
  if (!channel)
    throw new Error(`${path} references unknown channel ${channelId}`);
  const triggers = [
    ...new Set(
      literalStringArray(objectProperty(input, "on"), `${path} triggers`),
    ),
  ].sort();
  const triggerEvents: Record<string, string> = {
    mention: "app_mention",
    "direct-message": "message.im",
    message: "message.inbound",
  };
  const providerTriggers: Record<string, string[]> = {
    slack: ["mention", "direct-message"],
    twilio: ["message"],
    email: ["message"],
  };
  const supported = providerTriggers[channel.type] ?? [];
  for (const trigger of triggers) {
    if (!supported.includes(trigger)) {
      throw new Error(
        `${path} trigger ${trigger} is not available on a ${channel.type} channel (supported: ${supported.join(", ")})`,
      );
    }
    const event = triggerEvents[trigger];
    if (!event || !channel.events.includes(event)) {
      throw new Error(
        `${path} trigger ${trigger} is not declared by ${channelId}`,
      );
    }
  }
  return {
    agentId,
    channelId,
    triggers: triggers as ChannelRegistrationManifest["triggers"],
  };
}

function outboxDefinition(
  source: string,
  path: string,
  channels: ReadonlyMap<string, ChannelDefinitionManifest>,
): OutboxDefinitionManifest {
  const call = defaultExportCall(source, path, "defineOutbox");
  const input = call.arguments[0];
  if (!input || !ts.isObjectLiteralExpression(input)) {
    throw new Error(`${path} defineOutbox() requires an object literal`);
  }
  const id = literalStringValue(
    objectProperty(input, "id"),
    `${path} outbox id`,
  );
  if (basename(path, ".ts") !== id || !AGENT_ID_PATTERN.test(id)) {
    throw new Error(`${path} filename must match its valid outbox id`);
  }
  const delivery = objectProperty(input, "delivery");
  if (!delivery || !ts.isObjectLiteralExpression(delivery)) {
    throw new Error(`${path} delivery must be an object literal`);
  }
  const channelExpression = objectProperty(delivery, "channel");
  if (!channelExpression || !ts.isIdentifier(channelExpression)) {
    throw new Error(
      `${path} delivery.channel must reference an imported channel`,
    );
  }
  const channelId = importedResourceId(
    source,
    path,
    channelExpression.text,
    "channel",
  );
  const destination = literalStringValue(
    objectProperty(delivery, "destination"),
    `${path} destination`,
  );
  if (!channels.get(channelId)?.destinations[destination]) {
    throw new Error(
      `${path} references unknown destination ${destination} on ${channelId}`,
    );
  }
  return { id, channelId, destination };
}

function outboxRegistration(
  source: string,
  path: string,
  agentId: string,
  outboxes: ReadonlyMap<string, OutboxDefinitionManifest>,
): OutboxRegistrationManifest {
  const call = defaultExportCall(source, path, "registerOutbox");
  const expression = call.arguments[0];
  if (!expression || !ts.isIdentifier(expression)) {
    throw new Error(`${path} must register an imported outbox definition`);
  }
  const outboxId = importedResourceId(source, path, expression.text, "outbox");
  if (!outboxes.has(outboxId)) {
    throw new Error(`${path} references unknown outbox ${outboxId}`);
  }
  return { agentId, outboxId };
}

function staticJsonValue(expression: ts.Expression, label: string): unknown {
  expression = unwrapStatic(expression);
  if (ts.isStringLiteralLike(expression)) return expression.text;
  if (ts.isNumericLiteral(expression)) return Number(expression.text);
  if (
    ts.isPrefixUnaryExpression(expression) &&
    expression.operator === ts.SyntaxKind.MinusToken &&
    ts.isNumericLiteral(expression.operand)
  ) {
    return -Number(expression.operand.text);
  }
  if (expression.kind === ts.SyntaxKind.TrueKeyword) return true;
  if (expression.kind === ts.SyntaxKind.FalseKeyword) return false;
  if (expression.kind === ts.SyntaxKind.NullKeyword) return null;
  if (ts.isArrayLiteralExpression(expression)) {
    return expression.elements.map((element) => {
      if (ts.isSpreadElement(element)) {
        throw new Error(`${label} cannot use spreads`);
      }
      return staticJsonValue(element, label);
    });
  }
  if (ts.isObjectLiteralExpression(expression)) {
    const value: Record<string, unknown> = {};
    for (const property of expression.properties) {
      if (!ts.isPropertyAssignment(property)) {
        throw new Error(`${label} cannot use methods or spreads`);
      }
      value[staticPropertyName(property.name, label)] = staticJsonValue(
        property.initializer,
        label,
      );
    }
    return value;
  }
  throw new Error(`${label} must be a static JSON value`);
}

function scheduleDefinition(
  source: string,
  path: string,
  agentId: string,
): ScheduleDefinitionManifest {
  const call = defaultExportCall(source, path, "defineSchedule");
  const input = call.arguments[0];
  if (!input || !ts.isObjectLiteralExpression(input)) {
    throw new Error(`${path} defineSchedule() requires an object literal`);
  }
  const id = literalStringValue(
    objectProperty(input, "id"),
    `${path} schedule id`,
  );
  if (basename(path, ".ts") !== id || !AGENT_ID_PATTERN.test(id)) {
    throw new Error(`${path} filename must match its valid schedule id`);
  }
  const cron = literalStringValue(objectProperty(input, "cron"), `${path} cron`)
    .trim()
    .replace(/\s+/g, " ");
  if (cron.split(" ").length !== 5) {
    throw new Error(`${path} cron must contain exactly five fields`);
  }
  const timezoneExpression = objectProperty(input, "timezone");
  const timezone = timezoneExpression
    ? literalStringValue(timezoneExpression, `${path} timezone`)
    : "UTC";
  try {
    new Intl.DateTimeFormat("en-US", { timeZone: timezone }).format();
  } catch {
    throw new Error(`${path} timezone must be a valid IANA timezone`);
  }
  try {
    new Cron(cron, { timezone, paused: true });
  } catch {
    throw new Error(`${path} cron is invalid`);
  }
  const enabledExpression = objectProperty(input, "enabled");
  const enabled = [
    ...new Set(
      enabledExpression
        ? literalStringArray(enabledExpression, `${path} enabled environments`)
        : ["production"],
    ),
  ].sort();
  if (
    !enabled.length ||
    enabled.some(
      (environment) =>
        environment !== "default" &&
        environment !== "development" &&
        environment !== "production",
    )
  ) {
    throw new Error(`${path} enabled environments are invalid`);
  }
  const overlapExpression = objectProperty(input, "overlap");
  const overlap = overlapExpression
    ? literalStringValue(overlapExpression, `${path} overlap`)
    : "skip";
  if (overlap !== "skip" && overlap !== "allow") {
    throw new Error(`${path} overlap must be "skip" or "allow"`);
  }
  const dispatchExpression = objectProperty(input, "dispatch");
  if (
    !dispatchExpression ||
    !ts.isObjectLiteralExpression(dispatchExpression)
  ) {
    throw new Error(`${path} dispatch must be an object literal`);
  }
  const textExpression = objectProperty(dispatchExpression, "text");
  const text = textExpression
    ? literalStringValue(textExpression, `${path} dispatch text`).trim()
    : undefined;
  const payloadExpression = objectProperty(dispatchExpression, "payload");
  const payload = payloadExpression
    ? staticJsonValue(payloadExpression, `${path} dispatch payload`)
    : undefined;
  if (!text && payload === undefined) {
    throw new Error(`${path} dispatch requires text or payload`);
  }
  if (payload !== undefined && JSON.stringify(payload).length > 32 * 1024) {
    throw new Error(`${path} dispatch payload cannot exceed 32 KiB`);
  }
  return {
    id,
    agentId,
    cron,
    timezone,
    enabled: enabled as ScheduleDefinitionManifest["enabled"],
    overlap,
    dispatch: {
      ...(text ? { text } : {}),
      ...(payload === undefined ? {} : { payload }),
    },
  };
}

async function typescriptFiles(directory: string): Promise<string[]> {
  if (!(await exists(directory))) return [];
  return (await readdir(directory, { withFileTypes: true }))
    .filter((entry) => entry.isFile() && entry.name.endsWith(".ts"))
    .map((entry) => resolve(directory, entry.name))
    .sort();
}

const DATABASE_MIGRATION_NAME =
  /^\d{3,}_[a-z0-9]+(?:[a-z0-9_-]*[a-z0-9])?\.sql$/;
const MAX_DATABASE_MIGRATION_BYTES = 256 * 1024;
const MAX_DATABASE_MIGRATIONS_BYTES = 1024 * 1024;

async function databaseMigrations(
  opencomputer: string,
): Promise<DatabaseMigrationManifest[]> {
  const directory = resolve(opencomputer, "database", "migrations");
  if (!(await exists(directory))) return [];
  const entries = (await readdir(directory, { withFileTypes: true })).sort(
    (left, right) => left.name.localeCompare(right.name),
  );
  const migrations: DatabaseMigrationManifest[] = [];
  let totalBytes = 0;
  for (const entry of entries) {
    const path = resolve(directory, entry.name);
    if (!entry.isFile() || !DATABASE_MIGRATION_NAME.test(entry.name)) {
      throw new Error(
        `${path} must be a migration file named like 001_initial.sql`,
      );
    }
    const sql = await readFile(path, "utf8");
    const bytes = Buffer.byteLength(sql);
    if (!sql.trim()) throw new Error(`${path} must not be empty`);
    if (bytes > MAX_DATABASE_MIGRATION_BYTES) {
      throw new Error(`${path} cannot exceed 256 KiB`);
    }
    totalBytes += bytes;
    if (totalBytes > MAX_DATABASE_MIGRATIONS_BYTES) {
      throw new Error("Database migrations cannot exceed 1 MiB in total");
    }
    migrations.push({
      name: entry.name,
      checksum: createHash("sha256").update(sql).digest("hex"),
      sql,
    });
  }
  return migrations;
}

export async function readProjectResources(
  projectRoot: string,
): Promise<BuiltProjectResources> {
  const opencomputer = resolve(projectRoot, "opencomputer");
  const migrations = await databaseMigrations(opencomputer);
  const channelDefinitions = await Promise.all(
    (await typescriptFiles(resolve(opencomputer, "channels"))).map(
      async (path) => channelDefinition(await readFile(path, "utf8"), path),
    ),
  );
  const channels = new Map(
    channelDefinitions.map((channel) => [channel.id, channel]),
  );
  if (channels.size !== channelDefinitions.length) {
    throw new Error("Project channel IDs must be unique");
  }
  const outboxDefinitions = await Promise.all(
    (await typescriptFiles(resolve(opencomputer, "outboxes"))).map(
      async (path) =>
        outboxDefinition(await readFile(path, "utf8"), path, channels),
    ),
  );
  const outboxes = new Map(
    outboxDefinitions.map((outbox) => [outbox.id, outbox]),
  );
  if (outboxes.size !== outboxDefinitions.length) {
    throw new Error("Project outbox IDs must be unique");
  }
  const agents = await readProjectAgents(projectRoot);
  const channelRegistrations: ChannelRegistrationManifest[] = [];
  const outboxRegistrations: OutboxRegistrationManifest[] = [];
  const schedules: ScheduleDefinitionManifest[] = [];
  const gatedTools: GatedToolManifest[] = [];
  for (const agent of agents) {
    for (const path of await typescriptFiles(resolve(agent.root, "tools"))) {
      for (const tool of definedTools(await readFile(path, "utf8"), path)) {
        if (tool.gated) {
          gatedTools.push({ agentId: agent.localId, toolId: tool.id });
        }
      }
    }
    for (const path of await typescriptFiles(resolve(agent.root, "channels"))) {
      channelRegistrations.push(
        channelRegistration(
          await readFile(path, "utf8"),
          path,
          agent.localId,
          channels,
        ),
      );
    }
    for (const path of await typescriptFiles(resolve(agent.root, "outboxes"))) {
      outboxRegistrations.push(
        outboxRegistration(
          await readFile(path, "utf8"),
          path,
          agent.localId,
          outboxes,
        ),
      );
    }
    for (const path of await typescriptFiles(
      resolve(agent.root, "schedules"),
    )) {
      schedules.push(
        scheduleDefinition(await readFile(path, "utf8"), path, agent.localId),
      );
    }
  }
  const scheduleKeys = schedules.map(({ agentId, id }) => `${agentId}:${id}`);
  if (new Set(scheduleKeys).size !== scheduleKeys.length) {
    throw new Error("Agent schedule IDs must be unique within each agent");
  }
  const manifest: ProjectResourceManifest = {
    version: 1,
    channels: channelDefinitions.sort((left, right) =>
      left.id.localeCompare(right.id),
    ),
    channelRegistrations: channelRegistrations.sort((left, right) =>
      `${left.channelId}:${left.agentId}`.localeCompare(
        `${right.channelId}:${right.agentId}`,
      ),
    ),
    outboxes: outboxDefinitions.sort((left, right) =>
      left.id.localeCompare(right.id),
    ),
    outboxRegistrations: outboxRegistrations.sort((left, right) =>
      `${left.outboxId}:${left.agentId}`.localeCompare(
        `${right.outboxId}:${right.agentId}`,
      ),
    ),
    schedules: schedules.sort((left, right) =>
      `${left.agentId}:${left.id}`.localeCompare(
        `${right.agentId}:${right.id}`,
      ),
    ),
    ...(migrations.length ? { database: { migrations } } : {}),
    gatedTools: gatedTools.sort((left, right) =>
      `${left.agentId}:${left.toolId}`.localeCompare(
        `${right.agentId}:${right.toolId}`,
      ),
    ),
  };
  const serialized = JSON.stringify(manifest);
  return {
    manifest,
    digest: createHash("sha256").update(serialized).digest("hex"),
  };
}

/**
 * A secret reference, as written in source.
 *
 * The scope is read here rather than resolved later because the manifest is
 * the record of what an agent can reach: a reviewer should be able to see that
 * a credential is per-installation without running anything.
 */
function secretFromExpression(expression: ts.Expression): {
  name: string;
  scope?: "tenant" | "user";
} {
  if (
    !ts.isCallExpression(expression) ||
    !ts.isIdentifier(expression.expression) ||
    expression.expression.text !== "useSecret"
  ) {
    throw new Error("Connection secret headers must reference useSecret()");
  }
  const name = literalStringValue(expression.arguments[0], "useSecret name");
  const options = expression.arguments[1];
  if (!options) return { name };
  if (!ts.isObjectLiteralExpression(options)) {
    throw new Error("useSecret options must be an object literal");
  }
  const scope = objectProperty(options, "scope");
  if (!scope) return { name };
  const value = literalStringValue(scope, "useSecret scope");
  if (value !== "project" && value !== "tenant" && value !== "user") {
    throw new Error(`useSecret scope must be "project", "tenant" or "user"`);
  }
  return value === "project" ? { name } : { name, scope: value };
}

function connectionHeaderValue(
  expression: ts.Expression,
): HttpConnectionManifest["headers"][string] {
  if (ts.isStringLiteralLike(expression)) return expression.text;
  if (
    !ts.isCallExpression(expression) ||
    !ts.isIdentifier(expression.expression)
  ) {
    throw new Error(
      "Connection headers must be string literals, bearer(useSecret()), or secretHeader(useSecret())",
    );
  }
  const helper = expression.expression.text;
  if (helper === "bearer") {
    const secret = expression.arguments[0];
    if (!secret) throw new Error("bearer() requires useSecret()");
    return {
      kind: "secret",
      ...secretFromExpression(secret),
      prefix: "Bearer ",
    };
  }
  if (helper === "secretHeader") {
    const secret = expression.arguments[0];
    if (!secret) throw new Error("secretHeader() requires useSecret()");
    const result: {
      kind: "secret";
      name: string;
      scope?: "tenant" | "user";
      prefix?: string;
      suffix?: string;
    } = { kind: "secret", ...secretFromExpression(secret) };
    const options = expression.arguments[1];
    if (options) {
      if (!ts.isObjectLiteralExpression(options)) {
        throw new Error("secretHeader options must be an object literal");
      }
      const prefix = objectProperty(options, "prefix");
      const suffix = objectProperty(options, "suffix");
      if (prefix)
        result.prefix = literalStringValue(prefix, "secretHeader prefix");
      if (suffix)
        result.suffix = literalStringValue(suffix, "secretHeader suffix");
    }
    return result;
  }
  throw new Error(`Unsupported connection header helper: ${helper}`);
}

function definedHttpConnections(
  source: string,
  path: string,
): HttpConnectionManifest[] {
  const file = ts.createSourceFile(path, source, ts.ScriptTarget.Latest, true);
  const definitions: HttpConnectionManifest[] = [];
  const visit = (node: ts.Node): void => {
    if (
      ts.isCallExpression(node) &&
      ts.isIdentifier(node.expression) &&
      node.expression.text === "defineConnection"
    ) {
      const input = node.arguments[0];
      if (!input || !ts.isObjectLiteralExpression(input)) {
        throw new Error("defineConnection() requires an object literal");
      }
      if (objectProperty(input, "provider")) {
        ts.forEachChild(node, visit);
        return;
      }
      const id = literalStringValue(
        objectProperty(input, "id"),
        "connection id",
      );
      const originValue = literalStringValue(
        objectProperty(input, "origin"),
        `connection ${id} origin`,
      );
      const origin = new URL(originValue);
      if (origin.protocol !== "https:" || origin.pathname !== "/") {
        throw new Error(
          `Connection ${id} must use an HTTPS origin without a path`,
        );
      }
      const headers: HttpConnectionManifest["headers"] = {};
      const headerExpression = objectProperty(input, "headers");
      if (headerExpression) {
        if (!ts.isObjectLiteralExpression(headerExpression)) {
          throw new Error(`Connection ${id} headers must be an object literal`);
        }
        for (const property of headerExpression.properties) {
          if (!ts.isPropertyAssignment(property)) {
            throw new Error(`Connection ${id} headers cannot use spreads`);
          }
          const name =
            ts.isIdentifier(property.name) || ts.isStringLiteral(property.name)
              ? property.name.text
              : undefined;
          if (!name)
            throw new Error(`Connection ${id} has an invalid header name`);
          const value = connectionHeaderValue(property.initializer);
          if (
            [
              "api-key",
              "authorization",
              "cookie",
              "proxy-authorization",
              "x-api-key",
            ].includes(name.toLowerCase()) &&
            typeof value === "string"
          ) {
            throw new Error(
              `Connection ${id} header ${name} must use useSecret()`,
            );
          }
          headers[name] = value;
        }
      }
      const definition: HttpConnectionManifest = {
        id,
        origin: origin.origin,
        headers,
      };
      const methods = objectProperty(input, "methods");
      if (methods) {
        if (!ts.isArrayLiteralExpression(methods)) {
          throw new Error(`Connection ${id} methods must be an array literal`);
        }
        definition.methods = methods.elements.map((method) =>
          literalStringValue(method, `connection ${id} method`).toUpperCase(),
        );
      }
      const pathPrefix = objectProperty(input, "pathPrefix");
      if (pathPrefix) {
        definition.pathPrefix = literalStringValue(
          pathPrefix,
          `connection ${id} pathPrefix`,
        );
      }
      const redirectOrigins = objectProperty(input, "redirectOrigins");
      if (redirectOrigins) {
        if (!ts.isArrayLiteralExpression(redirectOrigins)) {
          throw new Error(
            `Connection ${id} redirectOrigins must be an array literal`,
          );
        }
        if (redirectOrigins.elements.length > 16) {
          throw new Error(
            `Connection ${id} may declare at most 16 redirect origins`,
          );
        }
        const policies = new Set<string>();
        definition.redirectOrigins = redirectOrigins.elements.map(
          (element, index) => {
            if (!ts.isObjectLiteralExpression(element)) {
              throw new Error(
                `Connection ${id} redirect origin ${index} must be an object literal`,
              );
            }
            const value = literalStringValue(
              objectProperty(element, "origin"),
              `connection ${id} redirect origin ${index}`,
            );
            const redirectOrigin = new URL(value);
            if (
              redirectOrigin.protocol !== "https:" ||
              redirectOrigin.pathname !== "/"
            ) {
              throw new Error(
                `Connection ${id} redirect origin ${index} must be an HTTPS origin without a path`,
              );
            }
            const redirectPathPrefix = objectProperty(element, "pathPrefix");
            const parsedPathPrefix = redirectPathPrefix
              ? literalStringValue(
                  redirectPathPrefix,
                  `connection ${id} redirect origin ${index} pathPrefix`,
                )
              : undefined;
            if (
              parsedPathPrefix !== undefined &&
              !parsedPathPrefix.startsWith("/")
            ) {
              throw new Error(
                `Connection ${id} redirect origin ${index} pathPrefix must start with /`,
              );
            }
            const policyKey = `${redirectOrigin.origin}\n${parsedPathPrefix ?? ""}`;
            if (policies.has(policyKey)) {
              throw new Error(
                `Connection ${id} redirect origin policies must be unique`,
              );
            }
            policies.add(policyKey);
            return {
              origin: redirectOrigin.origin,
              ...(parsedPathPrefix ? { pathPrefix: parsedPathPrefix } : {}),
            };
          },
        );
      }
      definitions.push(definition);
    }
    ts.forEachChild(node, visit);
  };
  visit(file);
  return definitions;
}

const GITHUB_APP_PERMISSION_KEYS = new Set([
  "actions",
  "checks",
  "contents",
  "issues",
  "metadata",
  "pull_requests",
]);

function definedGitHubConnections(
  source: string,
  path: string,
): GitHubConnectionManifest[] {
  const file = ts.createSourceFile(path, source, ts.ScriptTarget.Latest, true);
  const definitions: GitHubConnectionManifest[] = [];
  const visit = (node: ts.Node): void => {
    if (
      ts.isCallExpression(node) &&
      ts.isIdentifier(node.expression) &&
      node.expression.text === "defineConnection"
    ) {
      const input = node.arguments[0];
      if (!input || !ts.isObjectLiteralExpression(input)) {
        throw new Error("defineConnection() requires an object literal");
      }
      const providerExpression = objectProperty(input, "provider");
      if (!providerExpression) {
        ts.forEachChild(node, visit);
        return;
      }
      const id = literalStringValue(
        objectProperty(input, "id"),
        "connection id",
      );
      for (const property of input.properties) {
        if (!ts.isPropertyAssignment(property)) {
          throw new Error(
            `Connection ${id} cannot use spreads or shorthand properties`,
          );
        }
        const name = staticPropertyName(property.name, `Connection ${id}`);
        if (name !== "id" && name !== "provider") {
          throw new Error(
            `GitHub connection ${id} does not support the ${name} option`,
          );
        }
      }
      if (
        !ts.isCallExpression(providerExpression) ||
        !ts.isIdentifier(providerExpression.expression) ||
        providerExpression.expression.text !== "githubApp"
      ) {
        throw new Error(
          `Connection ${id} provider must be an inline githubApp() call`,
        );
      }
      const options = literalCallArgument(
        providerExpression,
        `Connection ${id} githubApp()`,
      );
      if (!options) {
        throw new Error(`Connection ${id} githubApp() requires permissions`);
      }
      for (const property of options.properties) {
        if (!ts.isPropertyAssignment(property)) {
          throw new Error(
            `Connection ${id} githubApp() options must be static`,
          );
        }
        if (
          staticPropertyName(property.name, `Connection ${id} githubApp()`) !==
          "permissions"
        ) {
          throw new Error(
            `Connection ${id} githubApp() only supports permissions`,
          );
        }
      }
      const permissionsExpression = objectProperty(options, "permissions");
      if (
        !permissionsExpression ||
        !ts.isObjectLiteralExpression(permissionsExpression)
      ) {
        throw new Error(
          `Connection ${id} githubApp() permissions must be an inline object literal`,
        );
      }
      const permissions: Record<string, GitHubAppPermission> = {};
      for (const property of permissionsExpression.properties) {
        if (!ts.isPropertyAssignment(property)) {
          throw new Error(
            `Connection ${id} githubApp() permissions must use literal properties`,
          );
        }
        const name = staticPropertyName(
          property.name,
          `Connection ${id} githubApp() permissions`,
        );
        if (!GITHUB_APP_PERMISSION_KEYS.has(name)) {
          throw new Error(
            `Connection ${id} githubApp() does not support the ${name} permission`,
          );
        }
        const level = literalStringValue(
          property.initializer,
          `Connection ${id} githubApp() permission ${name}`,
        );
        if (level !== "read" && level !== "write") {
          throw new Error(
            `Connection ${id} githubApp() permission ${name} must be "read" or "write"`,
          );
        }
        if (name === "metadata" && level !== "read") {
          throw new Error(
            `Connection ${id} githubApp() permission metadata must be "read"`,
          );
        }
        permissions[name] = level;
      }
      if (Object.keys(permissions).length === 0) {
        throw new Error(
          `Connection ${id} githubApp() requires at least one permission`,
        );
      }
      definitions.push({
        id,
        provider: {
          kind: "github-app",
          permissions: Object.fromEntries(
            Object.entries(permissions).sort(([left], [right]) =>
              left.localeCompare(right),
            ),
          ),
        },
      });
    }
    ts.forEachChild(node, visit);
  };
  visit(file);
  return definitions;
}

interface DefinedTool {
  readonly id: string;
  /** Has preview() and apply(), so the model's call is a proposal. */
  readonly gated: boolean;
  /** Declares `result: true`: its latest committed output is the session's result. */
  readonly result: boolean;
  /** The result tool's output schema as declared, pinned in the deployment for the host to validate against. */
  readonly output?: Record<string, unknown>;
}

interface ResultToolManifest {
  id: string;
  /** The output schema as written, pinned in the deployment for the host to validate against. */
  output: Record<string, unknown>;
}

/** Matches `preview: fn`, `preview(ctx) {}` and `async preview(ctx) {}` alike. */
function hasMember(object: ts.ObjectLiteralExpression, name: string): boolean {
  return object.properties.some((property) => {
    if (
      !ts.isPropertyAssignment(property) &&
      !ts.isMethodDeclaration(property) &&
      !ts.isShorthandPropertyAssignment(property)
    ) {
      return false;
    }
    const key = property.name;
    return (
      (!!key && ts.isIdentifier(key) && key.text === name) ||
      (!!key && ts.isStringLiteral(key) && key.text === name)
    );
  });
}

/** The member of an object literal named `name`, whatever its form. */
function objectMember(
  object: ts.ObjectLiteralExpression,
  name: string,
): ts.ObjectLiteralElementLike | undefined {
  return object.properties.find((property) => {
    const key = property.name;
    return (
      !!key &&
      ((ts.isIdentifier(key) && key.text === name) ||
        (ts.isStringLiteralLike(key) && key.text === name))
    );
  });
}

/**
 * The expression behind the syntax that only names a type: parentheses,
 * `as const`, `as T`, `satisfies T`, `<T>x` and `x!`. None of them changes
 * the value, and `as const` is how a schema literal keeps its literal types.
 */
function unwrapStatic(expression: ts.Expression): ts.Expression {
  let current = expression;
  for (;;) {
    if (ts.isParenthesizedExpression(current)) current = current.expression;
    else if (ts.isAsExpression(current)) current = current.expression;
    else if (ts.isSatisfiesExpression(current)) current = current.expression;
    else if (ts.isTypeAssertionExpression(current))
      current = current.expression;
    else if (ts.isNonNullExpression(current)) current = current.expression;
    else return current;
  }
}

interface LocalVariable {
  statement: ts.VariableStatement;
  declaration: ts.VariableDeclaration;
}

/** The top-level variable statement that declares `name` in `file`, if any. */
function localVariable(
  file: ts.SourceFile,
  name: string,
): LocalVariable | undefined {
  for (const statement of file.statements) {
    if (!ts.isVariableStatement(statement)) continue;
    const declaration = statement.declarationList.declarations.find(
      (candidate) =>
        ts.isIdentifier(candidate.name) && candidate.name.text === name,
    );
    if (declaration) return { statement, declaration };
  }
  return undefined;
}

/**
 * The object literal a `const` is initialized with. `let` and `var` are
 * refused because their value can change before the module is loaded, and
 * so is any initializer that is not a literal: the compiler does not run
 * code to learn a schema.
 */
function staticObjectInitializer(
  variable: LocalVariable,
  declaredPrefix: string,
  valuePrefix: string,
): ts.Expression {
  if (!(variable.statement.declarationList.flags & ts.NodeFlags.Const)) {
    throw new Error(
      `${declaredPrefix} declared with let or var; declare it as a const object literal`,
    );
  }
  const initializer = variable.declaration.initializer;
  if (!initializer) {
    throw new Error(
      `${declaredPrefix} declared without a value; declare it as a const object literal`,
    );
  }
  const value = unwrapStatic(initializer);
  if (!ts.isObjectLiteralExpression(value)) {
    throw new Error(
      `${valuePrefix} value is not a static object literal: ${initializer.getText()}`,
    );
  }
  return value;
}

const SCHEMA_FORMS =
  "an inline object literal, a const object literal declared in the same module, or a named import of such a const from a module inside the agent directory";

/**
 * The result tool's output schema as static JSON, from the forms the build
 * can read without evaluation. `resolver` is what reaches a const in this or
 * another module of the agent; without one, a referenced schema is left to
 * the build that has the whole module set.
 */
function declaredSchema(
  member: ts.ObjectLiteralElementLike | undefined,
  path: string,
  label: string,
  resolver: MemorySourceResolver | undefined,
): Record<string, unknown> | undefined {
  if (!member) {
    throw new Error(
      `${label.replace(/ output$/, "")} is the result tool and must declare output as ${SCHEMA_FORMS}`,
    );
  }
  const expression = ts.isShorthandPropertyAssignment(member)
    ? member.name
    : ts.isPropertyAssignment(member)
      ? unwrapStatic(member.initializer)
      : undefined;
  if (!expression) {
    throw new Error(
      `${label} must be ${SCHEMA_FORMS}, not a method or accessor`,
    );
  }
  if (ts.isObjectLiteralExpression(expression)) {
    return staticJsonValue(expression, label) as Record<string, unknown>;
  }
  if (ts.isIdentifier(expression)) {
    if (!resolver) return undefined;
    return staticJsonValue(
      resolver.staticObjectBinding(path, expression.text, label),
      label,
    ) as Record<string, unknown>;
  }
  throw new Error(
    `${label} must be ${SCHEMA_FORMS}, not ${expression.getText()}`,
  );
}

const DEFINE_TOOL_FORM_HINT =
  "the compiler reads name, result and output from the declaration itself and cannot see through anything else; write each option as a literal property";

/**
 * Every tool a module defines: its id, whether it waits for approval, and
 * whether it is the result tool with the output schema the host validates
 * against. One reading of each `defineTool()` call, from the syntax tree.
 *
 * Read from the syntax tree rather than by regex, because gated-ness is no
 * longer visible in the function's name; it is the presence of `preview` and
 * `apply` on the object literal. A textual match would see those words inside
 * a nested JSON Schema (a tool whose input has a property called `preview` is
 * perfectly legal) and declare an ordinary tool gated, which the runtime then
 * refuses to render at all.
 *
 * The result tool's output is read from the forms `declaredSchema` accepts;
 * `resolver` reaches a const declared in this or another module of the
 * agent, and the project-resource reading passes none because it needs only
 * gated-ness.
 *
 * A form the reading cannot see through fails the build. A spread, a computed
 * name or a `result` that is not the literal keyword could carry `result:
 * true` into the evaluated module while the manifest records an ordinary
 * tool, and the host would then never commit that tool's output as the
 * session's result; the diagnostic names the form so the fix is one edit.
 */
function definedTools(
  source: string,
  path: string,
  resolver?: MemorySourceResolver,
): DefinedTool[] {
  const file = resolver
    ? resolver.file(path)
    : ts.createSourceFile(path, source, ts.ScriptTarget.Latest, true);
  const tools: DefinedTool[] = [];
  const visit = (node: ts.Node): void => {
    if (
      ts.isCallExpression(node) &&
      ts.isIdentifier(node.expression) &&
      node.expression.text === "defineTool"
    ) {
      const argument = node.arguments[0];
      if (!argument || !ts.isObjectLiteralExpression(argument)) {
        throw new Error(`${path} defineTool() requires an object literal`);
      }
      const name = objectProperty(argument, "name");
      const label = `${path} defineTool(${name && ts.isStringLiteralLike(name) ? JSON.stringify(name.text) : ""})`;
      for (const property of argument.properties) {
        if (ts.isSpreadAssignment(property)) {
          throw new Error(
            `${label} cannot spread ...${property.expression.getText()}: ${DEFINE_TOOL_FORM_HINT}`,
          );
        }
        if (property.name && ts.isComputedPropertyName(property.name)) {
          throw new Error(
            `${label} cannot use the computed property name ${property.name.getText()}: ${DEFINE_TOOL_FORM_HINT}`,
          );
        }
      }
      const id = literalStringValue(name, `${path} tool name`);
      const resultMember = objectMember(argument, "result");
      let result = false;
      if (resultMember) {
        const reason = ts.isShorthandPropertyAssignment(resultMember)
          ? "the shorthand property result"
          : ts.isPropertyAssignment(resultMember)
            ? unwrapStatic(resultMember.initializer).kind ===
              ts.SyntaxKind.TrueKeyword
              ? undefined
              : unwrapStatic(resultMember.initializer).kind ===
                  ts.SyntaxKind.FalseKeyword
                ? undefined
                : resultMember.initializer.getText()
            : "a method or accessor";
        if (reason !== undefined) {
          throw new Error(
            `${label} result must be the literal true or false, not ${reason}`,
          );
        }
        result =
          unwrapStatic((resultMember as ts.PropertyAssignment).initializer)
            .kind === ts.SyntaxKind.TrueKeyword;
      }
      const output = result
        ? declaredSchema(
            objectMember(argument, "output"),
            path,
            `${label} output`,
            resolver,
          )
        : undefined;
      tools.push({
        id,
        // Either half marks it gated; defineTool() rejects a lone one at run
        // time. Treating a half-gate as ordinary here would let a tool that
        // means to wait be registered as one that does not.
        gated: hasMember(argument, "preview") || hasMember(argument, "apply"),
        result,
        ...(output ? { output } : {}),
      });
    }
    ts.forEachChild(node, visit);
  };
  visit(file);
  return tools.sort((left, right) => left.id.localeCompare(right.id));
}

function staticModelSelections(
  source: string,
): Array<{ provider: string; model: string }> {
  const file = ts.createSourceFile(
    "agent.ts",
    source,
    ts.ScriptTarget.Latest,
    true,
    ts.ScriptKind.TS,
  );
  const selections: Array<{ provider: string; model: string }> = [];
  const selectionValues = (
    value: ts.Expression,
  ): Array<{ provider: string; model: string }> | undefined => {
    if (ts.isStringLiteralLike(value)) {
      return [{ provider: "openrouter", model: value.text }];
    }
    if (ts.isObjectLiteralExpression(value)) {
      let provider: string | undefined;
      let model: string | undefined;
      for (const property of value.properties) {
        if (!ts.isPropertyAssignment(property)) continue;
        const name = ts.isIdentifier(property.name)
          ? property.name.text
          : ts.isStringLiteralLike(property.name)
            ? property.name.text
            : undefined;
        if (!name || !ts.isStringLiteralLike(property.initializer)) continue;
        if (name === "provider") provider = property.initializer.text;
        if (name === "model") model = property.initializer.text;
      }
      return provider && model ? [{ provider, model }] : undefined;
    }
    if (ts.isConditionalExpression(value)) {
      const whenTrue = selectionValues(value.whenTrue);
      const whenFalse = selectionValues(value.whenFalse);
      return whenTrue && whenFalse ? [...whenTrue, ...whenFalse] : undefined;
    }
    if (
      ts.isParenthesizedExpression(value) ||
      ts.isAsExpression(value) ||
      ts.isTypeAssertionExpression(value) ||
      ts.isSatisfiesExpression(value) ||
      ts.isNonNullExpression(value)
    ) {
      return selectionValues(value.expression);
    }
    return undefined;
  };
  const visit = (node: ts.Node): void => {
    if (
      ts.isCallExpression(node) &&
      ts.isIdentifier(node.expression) &&
      node.expression.text === "useModel"
    ) {
      const value = node.arguments[0];
      if (value) {
        const values = selectionValues(value);
        if (!values) {
          throw new Error(
            "useModel() must use a literal model selection or a conditional whose branches are literal selections",
          );
        }
        selections.push(...values);
      }
    }
    ts.forEachChild(node, visit);
  };
  visit(file);
  return selections
    .filter(
      (selection, index) =>
        selections.findIndex(
          (candidate) =>
            candidate.provider === selection.provider &&
            candidate.model === selection.model,
        ) === index,
    )
    .sort((left, right) =>
      `${left.provider}/${left.model}`.localeCompare(
        `${right.provider}/${right.model}`,
      ),
    );
}

/**
 * The compiled memory contract, inlined into the runtime so the artifact's
 * defineMemory() is the same code the compiler ran on the declaration.
 */
const MEMORY_CONTRACT_SOURCE = readFileSync(
  fileURLToPath(new URL("./memory.js", import.meta.url)),
  "utf8",
).replace(/^\/\/# sourceMappingURL=.*$/m, "");

/**
 * The `@opencomputer/agent` module the runtime evaluates, bundled into every
 * agent source module. `manifest.resultTool` is what the build recorded; the
 * shim's defineTool() checks the evaluated declaration against it, so a
 * module and its manifest can never disagree about which tool's output is
 * the session's result. Without a manifest (`null`) the check only refuses a
 * `result: true` the build did not record.
 */
export function agentApiRuntimeSource(
  manifest: { resultTool: string | null } = { resultTool: null },
): string {
  return `${MEMORY_CONTRACT_SOURCE}
const MANIFEST_RESULT_TOOL = ${JSON.stringify(manifest.resultTool)};
function hooks() {
  const value = globalThis[Symbol.for("opencomputer.agent-hooks")];
  if (!value) throw new Error("OpenComputer hooks can only run while rendering an agent");
  return value;
}
const OPENCOMPUTER_USER_AGENT = "OpenComputer-Agent/1 (+https://opencomputer.dev)";
function id(value, kind) {
  const normalized = String(value).trim();
  if (!normalized) throw new Error(kind + " requires a non-empty id");
  return normalized;
}
export const useSecret = (value, options = {}) => {
  const name = id(value, "useSecret");
  const scope = options.scope ?? "project";
  if (scope !== "project" && scope !== "tenant" && scope !== "user") throw new Error('A secret scope must be "project", "tenant" or "user"');
  if (!/^[A-Z][A-Z0-9_]{0,127}$/.test(name)) throw new Error("Invalid secret name " + JSON.stringify(name));
  return Object.freeze({ kind: "secret", id: name, scope });
};
export const secretHeader = (secret, options = {}) => Object.freeze({ kind: "secret-header", secret, ...options });
export const bearer = (secret) => secretHeader(secret, { prefix: "Bearer " });
export const githubApp = (options) => {
  const entries = Object.entries(options?.permissions || {});
  if (!entries.length) throw new Error("githubApp() requires at least one permission");
  const permissions = {};
  for (const [name, level] of entries) {
    if (!["actions", "checks", "contents", "issues", "metadata", "pull_requests"].includes(name)) throw new Error("githubApp() does not support the " + name + " permission");
    if (level !== "read" && level !== "write") throw new Error("githubApp() permission " + name + " must be read or write");
    if (name === "metadata" && level !== "read") throw new Error("githubApp() permission metadata must be read");
    permissions[name] = level;
  }
  return Object.freeze({ kind: "github-app", permissions: Object.freeze(permissions) });
};
export const ASK_TOOL = "ask";
export const callService = async (request) => {
  const base = globalThis.process?.env?.OPENCOMPUTER_CONNECTIONS_URL;
  const token = globalThis.process?.env?.OPENCOMPUTER_CONNECTION_TOKEN;
  if (!base || !token) throw new Error("OpenComputer managed connections are unavailable");
  if (!request?.path?.startsWith("/")) throw new Error("Service requests require an absolute path");
  const service = String(request.service ?? "").trim().toLowerCase();
  if (!service) throw new Error("A service request needs a service");
  const provider = service === "github" || service === "linear" ? service : "google";
  const root = base.endsWith("/") ? base.slice(0, -1) : base;
  const response = await fetch(root + "/" + provider + "/fetch", {
    method: "POST",
    headers: { authorization: "Bearer " + token, "content-type": "application/json" },
    body: JSON.stringify({
      service,
      ...(request.label ? { label: request.label } : {}),
      method: (request.method ?? "GET").toUpperCase(),
      path: request.path,
      ...(request.headers ? { headers: request.headers } : {}),
      ...(request.body === undefined ? {} : { body: request.body }),
    }),
    ...(request.signal ? { signal: request.signal } : {}),
  });
  // A managed connection answers with an envelope wrapped in a 200. Open it so
  // callers see the service's real status instead of the proxy's.
  if (!response.ok) return response;
  const envelope = await response.clone().json().catch(() => null);
  if (!envelope || typeof envelope.status !== "number" || typeof envelope.body !== "string") return response;
  const headers = {};
  for (const [name, value] of Object.entries(envelope.headers || {})) {
    if (typeof value === "string") headers[name] = value;
  }
  return new Response(envelope.body, { status: envelope.status, headers });
};

export const listServices = async (options = {}) => {
  const base = globalThis.process?.env?.OPENCOMPUTER_CONNECTIONS_URL;
  const token = globalThis.process?.env?.OPENCOMPUTER_CONNECTION_TOKEN;
  if (!base || !token) throw new Error("OpenComputer managed connections are unavailable");
  const root = base.endsWith("/") ? base.slice(0, -1) : base;
  const response = await fetch(root + "/opencomputer/fetch", {
    method: "POST",
    headers: { authorization: "Bearer " + token, "content-type": "application/json" },
    body: JSON.stringify({ action: "list" }),
    ...(options.signal ? { signal: options.signal } : {}),
  });
  if (!response.ok) throw new Error("Listing connected services failed: " + response.status + " " + (await response.text()).slice(0, 300));
  const body = await response.json();
  const provider = options.provider ? String(options.provider).trim().toLowerCase() : "";
  return (body.connections ?? []).filter((connection) =>
    (!provider || String(connection.provider ?? "").toLowerCase() === provider) &&
    (options.connectedOnly === false || connection.status === "connected"));
};

export const defineConnection = (input) => {
  const connectionId = id(input.id, "defineConnection");
  if (input.provider) {
    if (input.provider.kind !== "github-app") throw new Error("defineConnection() received an unsupported provider");
    return Object.freeze({ kind: "connection", id: connectionId, provider: input.provider });
  }
  const origin = new URL(input.origin);
  if (origin.protocol !== "https:" || origin.pathname !== "/") throw new Error("Connection origins must be HTTPS origins without a path");
  for (const [name, value] of Object.entries(input.headers || {})) {
    if (["api-key", "authorization", "cookie", "proxy-authorization", "x-api-key"].includes(name.toLowerCase()) && typeof value === "string") throw new Error(name + " must use useSecret()");
  }
  const redirectOrigins = (input.redirectOrigins || []).map((input) => {
    const redirectOrigin = new URL(input.origin);
    if (redirectOrigin.protocol !== "https:" || redirectOrigin.pathname !== "/") throw new Error("Connection redirect origins must be HTTPS origins without a path");
    if (input.pathPrefix != null && !input.pathPrefix.startsWith("/")) throw new Error("Connection redirect path prefixes must start with /");
    return Object.freeze({ origin: redirectOrigin.origin, ...(input.pathPrefix ? { pathPrefix: input.pathPrefix } : {}) });
  });
  if (redirectOrigins.length > 16) throw new Error("Connections may declare at most 16 redirect origins");
  if (new Set(redirectOrigins.map(({ origin, pathPrefix }) => origin + "\\n" + (pathPrefix || ""))).size !== redirectOrigins.length) throw new Error("Connection redirect origin policies must be unique");
  return Object.freeze({
    kind: "connection",
    ...input,
    id: connectionId,
    origin: origin.origin,
    headers: Object.freeze({ ...(input.headers || {}) }),
    ...(redirectOrigins.length ? { redirectOrigins: Object.freeze(redirectOrigins) } : {}),
    async fetch(path, init = {}) {
      const base = globalThis.process?.env?.OPENCOMPUTER_CONNECTIONS_URL;
      const token = globalThis.process?.env?.OPENCOMPUTER_CONNECTION_TOKEN;
      if (!base || !token) throw new Error("OpenComputer managed egress is unavailable");
      if (!path.startsWith("/")) throw new Error("Connection requests require an absolute path");
      const headers = {};
      new Headers(init.headers).forEach((value, name) => { headers[name] = value; });
      // Some APIs reject a request that carries no User-Agent — GitHub answers
      // 403 with an empty body, which is undiagnosable from the caller's side.
      // Default one unless the connection or the request already sets it.
      const declaresUserAgent = Object.keys(input.headers || {}).some((name) => name.toLowerCase() === "user-agent");
      if (!declaresUserAgent && !("user-agent" in headers)) headers["user-agent"] = OPENCOMPUTER_USER_AGENT;
      if (init.body != null && typeof init.body !== "string") throw new Error("Managed connection request bodies must currently be strings");
      if (typeof init.body === "string" && init.body.length > 5 * 1024 * 1024) throw new Error("Managed connection request bodies cannot exceed 5 MiB");
      return fetch(base.replace(/\\\/$/, "") + "/" + encodeURIComponent(connectionId) + "/fetch", {
        method: "POST",
        headers: { authorization: "Bearer " + token, "content-type": "application/json" },
        body: JSON.stringify({ method: (init.method || "GET").toUpperCase(), path, headers, ...(init.body == null ? {} : { body: init.body }) }),
        signal: init.signal,
      });
    },
  });
};
export const defineMcpServer = (input) => {
  const url = new URL(input.url);
  if (url.protocol !== "https:") throw new Error("MCP server URLs must use HTTPS");
  return Object.freeze({ kind: "mcp", ...input, id: id(input.id, "defineMcpServer"), url: url.toString() });
};
export const defineTool = (input) => {
  const toolId = id(input.name, "defineTool");
  if (!/^[a-zA-Z0-9_-]+$/.test(toolId)) throw new Error("Invalid tool id " + JSON.stringify(toolId));
  if (toolId === ASK_TOOL) throw new Error("Tool id " + JSON.stringify(ASK_TOOL) + " is the platform's question tool; select it with useTool(" + JSON.stringify(ASK_TOOL) + ") and rename this tool");
  if (!String(input.description).trim()) throw new Error("defineTool requires a non-empty description");
  if (input.input && typeof input.input !== "object") throw new Error("defineTool input must be a JSON Schema object");
  if (input.output && typeof input.output !== "object") throw new Error("defineTool output must be a JSON Schema object");
  const gated = typeof input.preview === "function" || typeof input.apply === "function";
  if (!gated) {
    if (typeof input.run !== "function") throw new Error("defineTool requires run(), or preview() and apply() for a tool that waits for approval");
    if (input.result !== undefined && typeof input.result !== "boolean") throw new Error("defineTool result must be true or false");
    if (input.result === true && !input.output) throw new Error("defineTool result tools require an output schema; the host validates every result against it before committing");
    // The build recorded the result tool from the declaration it could read;
    // what the module evaluates to must agree, or the host would commit the
    // wrong tool's output, or none. Refusing at load fails the deployment
    // instead of running the tool as an ordinary one.
    if (input.result === true && toolId !== MANIFEST_RESULT_TOOL) throw new Error("Tool " + toolId + " declares result: true, but the deployment records " + (MANIFEST_RESULT_TOOL ? MANIFEST_RESULT_TOOL + " as its result tool" : "no result tool") + "; the declaration was not readable at build time. Write result: true as a literal property of defineTool() and rebuild");
    if (toolId === MANIFEST_RESULT_TOOL && input.result !== true) throw new Error("Tool " + toolId + " is the deployment's result tool, but the module does not declare result: true; the build and the module disagree, rebuild the deployment");
    const { result, ...definition } = input;
    return Object.freeze({ kind: "tool", version: 1, ...definition, ...(result === true ? { result: true } : {}), id: toolId, name: toolId });
  }
  if ("result" in input) throw new Error("A tool that waits for approval cannot be the result tool");
  if (typeof input.preview !== "function") throw new Error("A tool with apply() also requires preview()");
  if (typeof input.apply !== "function") throw new Error("A tool with preview() also requires apply()");
  if (typeof input.run === "function") throw new Error("A tool has either run(), or preview() and apply() - not both; run() is written for you when the tool waits for approval");
  return Object.freeze({
    kind: "gated-tool", version: 1, ...input, id: toolId, name: toolId,
    async run(context) {
      const preview = approvalPreview(await input.preview(context), toolId);
      const result = await publishApproval(toolId, {
        input: context.input,
        preview,
        idempotencyKey: context.messageId,
      });
      return result.message;
    },
  });
};
const approvalPreview = (value, toolId) => {
  if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error("Tool " + toolId + " preview must return an object");
  if (typeof value.title !== "string" || !value.title.trim()) throw new Error("Tool " + toolId + " preview requires a non-empty title");
  if (value.summary !== undefined && typeof value.summary !== "string") throw new Error("Tool " + toolId + " preview summary must be a string");
  if (value.facts !== undefined) {
    if (!Array.isArray(value.facts)) throw new Error("Tool " + toolId + " preview facts must be an array");
    if (value.facts.length > 20) throw new Error("Tool " + toolId + " preview may carry at most 20 facts");
    for (const fact of value.facts) {
      if (!fact || typeof fact.label !== "string" || typeof fact.value !== "string") throw new Error("Tool " + toolId + " preview facts must each have a label and a value");
    }
  }
  return value;
};
export const publishApproval = async (tool, input) => {
  const toolId = id(typeof tool === "string" ? tool : tool.id, "publishApproval");
  const idempotencyKey = String(input.idempotencyKey).trim();
  if (!idempotencyKey || idempotencyKey.length > 256) throw new Error("Approval idempotency keys must contain 1 to 256 characters");
  const base = globalThis.process?.env?.OPENCOMPUTER_APPROVAL_URL;
  const token = globalThis.process?.env?.OPENCOMPUTER_APPROVAL_TOKEN;
  if (!base || !token) throw new Error("OpenComputer approvals are unavailable");
  const response = await fetch(base.replace(/\\/$/, ""), {
    method: "POST",
    headers: { authorization: "Bearer " + token, "content-type": "application/json" },
    body: JSON.stringify({ toolId, input: input.input, preview: input.preview, idempotencyKey }),
  });
  if (!response.ok) {
    const detail = await response.text().catch(() => "");
    let message = "";
    try { message = JSON.parse(detail)?.error?.message ?? ""; } catch {}
    throw new Error(message || ("Recording the approval failed with status " + response.status));
  }
  return await response.json();
};
export const publishOutbox = async (outbox, input) => {
  const outboxId = id(typeof outbox === "string" ? outbox : outbox.id, "publishOutbox");
  const type = String(input.type).trim();
  if (!/^[a-z0-9]+(?:[a-z0-9.-]*[a-z0-9])?$/.test(type)) throw new Error("Outbox event types must use lowercase dot notation");
  const idempotencyKey = String(input.idempotencyKey).trim();
  if (!idempotencyKey || idempotencyKey.length > 256) throw new Error("Outbox idempotency keys must contain 1 to 256 characters");
  const base = globalThis.process?.env?.OPENCOMPUTER_OUTBOX_URL;
  const token = globalThis.process?.env?.OPENCOMPUTER_OUTBOX_TOKEN;
  if (!base || !token) throw new Error("OpenComputer outbox delivery is unavailable");
  const response = await fetch(base.replace(/\\\/$/, "") + "/" + encodeURIComponent(outboxId) + "/items", {
    method: "POST",
    headers: { authorization: "Bearer " + token, "content-type": "application/json" },
    body: JSON.stringify({ type, content: input.content, idempotencyKey }),
  });
  if (!response.ok) throw new Error("Outbox publish failed with status " + response.status);
  return await response.json();
};
// The host resolves every session binding before the render and exposes the
// projections on its render scope as scope.memory[id]; the hook returns one
// and the host records the id in scope.selectedMemory, returned to it as
// selectedMemory next to enabledTools. An unbound id returns undefined.
export const useMemory = (memory) => {
  const resource = memoryId(typeof memory === "string" ? memory : memory && memory.id, "useMemory");
  return memoryProjection(resource, hooks().useMemory(resource));
};
export const useInput = () => hooks().useInput();
export const useCurrentInput = useInput;
export const useModel = (model) => hooks().useModel(model);
export const useTool = (tool) => hooks().useTool(tool);
export const useConnection = (connection) => hooks().useConnection(connection);
export const useService = (service) => hooks().useService?.(service);
export const useMcpServer = (server) => hooks().useMcpServer(server);
export const useSessionData = (key) => hooks().useSessionData(key);
`;
}

interface AgentSourceModule {
  path: string;
  source: string;
}

const AGENT_SOURCE_MODULE_PATTERN = /\.[cm]?[jt]sx?$/;

async function bundleAgentSourceModules(
  root: string,
  runtime: string,
  entries: string[],
  options: { shim: string; write: boolean },
): Promise<{ modules: AgentSourceModule[]; entryPaths: Set<string> }> {
  const entryPoints: Record<string, string> = {};
  const entryPaths = new Set<string>();
  for (const entry of entries) {
    const path = relative(root, resolve(entry)).split("\\").join("/");
    const outputPath = compiledModulePath(path);
    const outputName = outputPath.replace(/\.js$/, "");
    if (entryPoints[outputName]) {
      throw new Error(`Agent source modules emit the same path: ${outputPath}`);
    }
    entryPoints[outputName] = resolve(entry);
    entryPaths.add(path);
  }
  const result = await bundle({
    absWorkingDir: root,
    bundle: true,
    entryPoints,
    format: "esm",
    logLevel: "silent",
    metafile: true,
    outdir: runtime,
    platform: "node",
    target: "node22",
    write: false,
    plugins: [
      {
        name: "opencomputer-agent-runtime",
        setup(build) {
          build.onResolve({ filter: /^@opencomputer\/agent$/ }, () => ({
            path: "api",
            namespace: "opencomputer-agent-runtime",
          }));
          build.onLoad(
            { filter: /^api$/, namespace: "opencomputer-agent-runtime" },
            () => ({ contents: options.shim, loader: "js" }),
          );
        },
      },
    ],
  });

  const modules: AgentSourceModule[] = [];
  for (const input of Object.keys(result.metafile.inputs)) {
    if (input === "opencomputer-agent-runtime:api") continue;
    const absolute = resolve(root, input);
    const path = relative(root, absolute).split("\\").join("/");
    if (!path || path === ".." || path.startsWith("../")) {
      throw new Error(
        "Agent source modules must stay inside the agent directory",
      );
    }
    if (AGENT_SOURCE_MODULE_PATTERN.test(path)) {
      modules.push({ path, source: await readFile(absolute, "utf8") });
    }
  }
  for (const output of result.outputFiles) {
    const path = relative(runtime, output.path).split("\\").join("/");
    if (!path || path === ".." || path.startsWith("../")) {
      throw new Error("Agent compiler emitted a file outside the runtime");
    }
    if (!options.write) continue;
    await mkdir(dirname(output.path), { recursive: true });
    await writeFile(output.path, output.contents);
  }
  return {
    modules: modules.sort((left, right) => left.path.localeCompare(right.path)),
    entryPaths,
  };
}

function compiledModulePath(path: string): string {
  return path === "agent.ts" ? "agent.js" : path.replace(/\.[^.]+$/, ".js");
}

/**
 * Where an agent's compiled bundle goes: a cache under the app's
 * `node_modules`, never inside the agent's source directory, so the source
 * tree holds only what the user wrote and `doctor` never rescans a build.
 * An agent outside an app (no `opencomputer/project.ts` above it) caches
 * under its own directory.
 */
export async function agentRuntimeDirectory(
  agentRoot: string,
): Promise<string> {
  const root = resolve(agentRoot);
  let directory = root;
  let projectRoot: string | undefined;
  for (;;) {
    if (await exists(resolve(directory, "opencomputer", "project.ts"))) {
      projectRoot = directory;
      break;
    }
    const parent = dirname(directory);
    if (parent === directory) break;
    directory = parent;
  }
  return resolve(
    projectRoot ?? root,
    "node_modules",
    ".cache",
    "opencomputer",
    "agents",
    basename(root),
    "runtime",
  );
}

export async function prepareAgent(root: string): Promise<string> {
  const runtime = await agentRuntimeDirectory(root);
  await rm(runtime, { recursive: true, force: true });
  await mkdir(runtime, { recursive: true });
  const agentSource = await readFile(resolve(root, "agent.ts"), "utf8");
  const reactive = /export\s+default\s+(?:async\s+)?function\b/.test(
    agentSource,
  );
  if (!reactive) {
    throw new Error(
      "agent.ts must default-export a synchronous agent function",
    );
  }
  await writeFile(
    resolve(runtime, "AGENTS.md"),
    `# OpenComputer runtime identity

You are an OpenComputer agent. OpenCode is an internal execution detail, not
the product or support surface presented to users.

- Identify yourself and your environment as OpenComputer.
- Never direct users to OpenCode commands, settings, websites, repositories,
  issue trackers, or support channels.
- Use the question tool when structured clarification is useful. OpenComputer
  delivers it through the current chat and resumes when the user replies.

`,
  );
  const declaredModels = staticModelSelections(agentSource);
  const openCodeConfig = resolve(root, "opencode.json");
  const hasOpenCodeConfig = await exists(openCodeConfig);
  if (hasOpenCodeConfig || declaredModels.length === 1) {
    const parsed: unknown = hasOpenCodeConfig
      ? JSON.parse(await readFile(openCodeConfig, "utf8"))
      : {};
    if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
      throw new Error("opencode.json must contain a JSON object");
    }
    const config = parsed as Record<string, unknown>;
    const inferredModel =
      declaredModels.length === 1
        ? `${declaredModels[0]!.provider}/${declaredModels[0]!.model}`
        : undefined;
    const configuredTools =
      config.tools &&
      typeof config.tools === "object" &&
      !Array.isArray(config.tools)
        ? (config.tools as Record<string, unknown>)
        : {};
    const configuredPermission =
      config.permission &&
      typeof config.permission === "object" &&
      !Array.isArray(config.permission)
        ? (config.permission as Record<string, unknown>)
        : {};
    const questionDenied =
      configuredTools.question === false ||
      configuredPermission.question === "deny";
    await writeFile(
      resolve(runtime, "opencode.json"),
      `${JSON.stringify(
        {
          ...config,
          ...(config.model === undefined && inferredModel
            ? { model: inferredModel }
            : {}),
          // The skill tool is what loads a packaged skill's body. OpenCode
          // injects skill names and descriptions either way, so without this
          // an agent knows its skills exist and can never read one — which is
          // exactly how nine skills shipped in an artifact and none was used.
          tools: {
            use_skill: true,
            ...configuredTools,
            question: !questionDenied,
          },
          permission: {
            ...configuredPermission,
            ...(configuredPermission.calendar_create_time_off === "ask"
              ? { calendar_create_time_off: "allow" }
              : {}),
            question: questionDenied ? "deny" : "allow",
          },
        },
        null,
        2,
      )}\n`,
    );
  }
  const skills = resolve(root, "skills");
  if (await exists(skills)) {
    await mkdir(resolve(runtime, ".opencode"), { recursive: true });
    await cp(skills, resolve(runtime, ".opencode", "skills"), {
      recursive: true,
    });
  }
  const workspace = resolve(root, "workspace");
  if (await exists(workspace)) {
    await cp(workspace, runtime, { recursive: true });
  }
  await writeFile(
    resolve(runtime, "package.json"),
    `${JSON.stringify({ private: true, type: "module" }, null, 2)}\n`,
  );
  const sourceEntries = [resolve(root, "agent.ts")];
  const sourceTools = resolve(root, "tools");
  if (await exists(sourceTools)) {
    const entries = await readdir(sourceTools, { withFileTypes: true });
    for (const entry of entries) {
      if (!entry.isFile() || !/\.[cm]?[jt]s$/.test(entry.name)) continue;
      sourceEntries.push(resolve(sourceTools, entry.name));
    }
  }
  // Two passes. The first discovers the module set and writes nothing; the
  // declarations are read from it. The second emits the modules with the
  // shim that carries what the manifest recorded, so a tool module whose
  // evaluated metadata disagrees with the build fails at load instead of
  // running as an ordinary tool.
  const bundled = await bundleAgentSourceModules(root, runtime, sourceEntries, {
    shim: agentApiRuntimeSource(),
    write: false,
  });
  const sourceModules = bundled.modules;
  const toolSources = sourceModules.filter(
    (candidate) =>
      bundled.entryPaths.has(candidate.path) &&
      candidate.path.startsWith("tools/"),
  );
  const sourceResolver = new MemorySourceResolver(sourceModules);
  const reactiveTools: string[] = [];
  const gatedTools: string[] = [];
  const toolModules: string[] = [];
  const resultTools: Array<ResultToolManifest & { path: string }> = [];
  for (const candidate of toolSources) {
    // literalStringValue throws on a computed name, which is what used to be
    // caught by counting calls against extracted ids.
    const defined = definedTools(
      candidate.source,
      candidate.path,
      sourceResolver,
    );
    // `ask` is the platform's question tool: the host registers it, and a
    // defined tool of the same id would leave the model two tools under one
    // name. defineTool() refuses it at load too; this fails the build first.
    if (defined.some((tool) => tool.id === ASK_TOOL)) {
      throw new Error(
        `${candidate.path} defineTool(${JSON.stringify(ASK_TOOL)}): ${JSON.stringify(ASK_TOOL)} is the platform's question tool; select it with useTool(${JSON.stringify(ASK_TOOL)}) and rename this tool`,
      );
    }
    if (defined.length > 0) {
      reactiveTools.push(...defined.map((tool) => tool.id));
      gatedTools.push(
        ...defined.filter((tool) => tool.gated).map((tool) => tool.id),
      );
      toolModules.push(`../${compiledModulePath(candidate.path)}`);
      resultTools.push(
        ...defined
          .filter((tool) => tool.result)
          .map((tool) => ({
            id: tool.id,
            output: tool.output!,
            path: candidate.path,
          })),
      );
    }
  }
  const duplicateTool = reactiveTools.find(
    (id, index) => reactiveTools.indexOf(id) !== index,
  );
  if (duplicateTool) {
    throw new Error(
      `Tool id ${JSON.stringify(duplicateTool)} is defined more than once`,
    );
  }
  // One result per session, so one result tool per agent: a second one
  // would leave the host with two schemas and no rule for which output
  // becomes the session's result.
  if (resultTools.length > 1) {
    throw new Error(
      `An agent may declare one result tool; found ${resultTools
        .map((tool) => `${JSON.stringify(tool.id)} in ${tool.path}`)
        .join(" and ")}`,
    );
  }
  // A gated tool's run() is written by the platform and returns its sentence;
  // there is no output of its own to commit as the session's result.
  const gatedResultTool = resultTools.find((tool) =>
    gatedTools.includes(tool.id),
  );
  if (gatedResultTool) {
    throw new Error(
      `${gatedResultTool.path} defineTool(${JSON.stringify(gatedResultTool.id)}) waits for approval and cannot be the result tool`,
    );
  }
  const resultTool: ResultToolManifest | undefined = resultTools[0]
    ? { id: resultTools[0].id, output: resultTools[0].output }
    : undefined;
  const shim = agentApiRuntimeSource({ resultTool: resultTool?.id ?? null });
  await writeFile(resolve(runtime, "opencomputer-agent.js"), shim);
  await bundleAgentSourceModules(root, runtime, sourceEntries, {
    shim,
    write: true,
  });
  const httpConnections = sourceModules.flatMap((module) =>
    definedHttpConnections(module.source, module.path),
  );
  const githubConnections = sourceModules.flatMap((module) =>
    definedGitHubConnections(module.source, module.path),
  );
  const allConnections = [...httpConnections, ...githubConnections];
  const duplicateConnection = allConnections.find(
    (connection, index) =>
      allConnections.findIndex(
        (candidate) => candidate.id === connection.id,
      ) !== index,
  );
  if (duplicateConnection) {
    throw new Error(
      `Connection id ${JSON.stringify(duplicateConnection.id)} is defined more than once`,
    );
  }
  const connectionBindings = new Map<string, HttpConnectionManifest>();
  for (const { path: filename, source } of sourceModules) {
    for (const [name, definition] of definedConnectionBindings(
      source,
      filename,
    )) {
      const existing = connectionBindings.get(name);
      if (existing && existing.id !== definition.id) {
        throw new Error(
          `Connection binding ${JSON.stringify(name)} is defined more than once`,
        );
      }
      connectionBindings.set(name, definition);
    }
  }
  const mcpServerDefinitions = sourceModules.flatMap((module) =>
    definedMcpServers(module.source, module.path, connectionBindings),
  );
  const duplicateMcpServer = mcpServerDefinitions.find(
    (server, index) =>
      mcpServerDefinitions.findIndex(
        (candidate) => candidate.id === server.id,
      ) !== index,
  );
  if (duplicateMcpServer) {
    throw new Error(
      `MCP server id ${JSON.stringify(duplicateMcpServer.id)} is defined more than once`,
    );
  }
  const memory = mergeMemoryDeclarations(
    sourceModules.map((module) => ({
      origin: module.path,
      memory: definedMemory(sourceResolver, module.path, connectionBindings),
    })),
  );
  const declaredMemory = new Set(memory.map((declaration) => declaration.id));
  const tools = [
    ...new Set([
      ...reactiveTools,
      ...literalHookIds(agentSource, "useTool"),
      // useTool(ASK_TOOL), the exported constant, selects the same tool as
      // useTool("ask"); no defineTool() exists for it.
      ...(/\buseTool\(\s*ASK_TOOL\s*\)/.test(agentSource) ? [ASK_TOOL] : []),
    ]),
  ].sort();
  for (const id of literalHookIds(agentSource, "useMemory")) {
    if (!declaredMemory.has(id)) {
      throw new Error(
        `useMemory(${JSON.stringify(id)}) references a memory resource this agent does not declare; import its defineMemory() declaration`,
      );
    }
  }
  for (const declaration of memory) {
    const collision = memoryToolNames(declaration.provider).find((name) =>
      tools.includes(name),
    );
    if (collision) {
      throw new Error(
        `Tool id ${JSON.stringify(collision)} collides with the fixed tool name of memory ${declaration.id}; rename the tool`,
      );
    }
  }
  await mkdir(resolve(runtime, ".opencomputer"), { recursive: true });
  await writeFile(
    resolve(runtime, ".opencomputer", "reactive.json"),
    `${JSON.stringify(
      {
        version: 2,
        entry: "../agent.js",
        tools,
        gatedTools: [...gatedTools].sort(),
        toolModules: toolModules.sort(),
        // The result tool and the schema the host validates its output
        // against before committing it as the session's result.
        ...(resultTool ? { resultTool } : {}),
        // Declared HTTP connections AND managed-service grants: the platform
        // reads one list, and a provider grant absent from it makes every
        // connected mailbox invisible to listServices().
        connections: [
          ...new Set([
            ...allConnections.map((connection) => connection.id),
            ...declaredServiceProviders(agentSource),
          ]),
        ].sort(),
        httpConnections,
        githubConnections,
        mcpServers: [
          ...new Set([
            ...mcpServerDefinitions.map((server) => server.id),
            ...literalHookIds(agentSource, "useMcpServer"),
          ]),
        ].sort(),
        mcpServerDefinitions,
        memory,
        models: declaredModels,
      },
      null,
      2,
    )}\n`,
  );
  return runtime;
}

async function collectFiles(
  root: string,
  directory = root,
): Promise<Array<{ path: string; content: string }>> {
  const result: Array<{ path: string; content: string }> = [];
  for (const entry of (await readdir(directory, { withFileTypes: true })).sort(
    (left, right) => left.name.localeCompare(right.name),
  )) {
    const path = resolve(directory, entry.name);
    if (entry.isDirectory()) result.push(...(await collectFiles(root, path)));
    else if (entry.isFile()) {
      result.push({
        path: relative(root, path).split("\\").join("/"),
        content: (await readFile(path)).toString("base64"),
      });
    }
  }
  return result;
}

export async function buildAgentArtifact(
  root: string,
  agentId?: string,
): Promise<BuiltAgentArtifact> {
  const startedAt = performance.now();
  const manifest = await readManifest(root);
  const runtime = await prepareAgent(root);
  const reactive = JSON.parse(
    await readFile(resolve(runtime, ".opencomputer", "reactive.json"), "utf8"),
  ) as {
    connections?: string[];
    httpConnections?: HttpConnectionManifest[];
    githubConnections?: GitHubConnectionManifest[];
    memory?: MemoryDeclaration[];
    models?: Array<{ provider: string; model: string }>;
  };
  const connections = [...new Set(reactive.connections ?? [])].sort();
  const httpConnections = reactive.httpConnections ?? [];
  const githubConnections = reactive.githubConnections ?? [];
  const memory = reactive.memory ?? [];
  const models = reactive.models ?? [];
  const body = Buffer.from(
    JSON.stringify({
      version: 1,
      channels: [],
      files: await collectFiles(runtime),
    }),
  );
  return {
    agentId: agentId ?? manifest.id,
    name: manifest.name,
    channels: [],
    connections,
    httpConnections,
    githubConnections,
    memory,
    models,
    ...(manifest.region ? { region: manifest.region } : {}),
    ...(manifest.egress ? { egress: manifest.egress } : {}),
    ...(manifest.fixedIps ? { fixedIps: manifest.fixedIps } : {}),
    body,
    digest: createHash("sha256").update(body).digest("hex"),
    elapsedMs: Math.round(performance.now() - startedAt),
  };
}