Skip to content

An open-source, faster Devin alternative

TypeScript
137 KB
Raw Blame
import { getAutumnCustomer } from "./autumn_webhook";
import { FREE_CREDITS_PAYWALL } from "./billing_onramp";
import { computerFamily } from "./computer";
import { computerApiFamily } from "./computer_api";
import type { RouteFamily } from "./route_family";

export interface ManagedAgentsEnv {
  /** Computer rollout (work 052): see computerEnabledFor. */
  COMPUTER_ENABLED_FOR_ALL?: string;
  COMPUTER_ENABLED_ORGS?: string;
  MANAGED_AGENTS_API_URL?: string;
  OC_MANAGED_AGENTS_SECRET?: string;
  OPENCOMPUTER_DB?: D1Database;
  AUTUMN_SECRET_KEY?: string;
  AUTUMN_BASE_URL?: string;
  /** Per-IP cap on the public CLI connect route (work 082). */
  COMPUTER_CONNECT_RATE_LIMIT?: RateLimit;
  WORKER_ENV?: string;
  /** The wire Worker's HTTP base (work 084); default https://wire.opencomputer.dev. */
  WIRE_HTTP_URL?: string;
  /** Extra browser origins for /api/managed-agents/computer, comma-separated. */
  COMPUTER_API_CORS_ORIGINS?: string;
}

/**
 * The API key a request authenticated with (work 084), asserted to managed
 * agents so the computer API can apply the key's scopes and name the key.
 * Absent for dashboard sessions, which blue reads as "session credential,
 * all scopes".
 */
export interface AssertedAPIKey {
  id: string;
  /** SHA-256 hex of the key; the key itself never leaves the edge. */
  hash: string;
  name: string;
  kind: "user" | "project";
  /** The raw `scopes` column, split on commas (legacy keys: `sandbox:*`). */
  scopes: string[];
  expiresAt: string | null;
  createdAt: string;
}

export interface ManagedAgentsCaller {
  orgID: string;
  userID: string | null;
  role?: string;
  /** The organization's computer (work 080); absent for people's keys. */
  principal?: "computer";
  /** The computer session (Slack thread) the key was minted for. */
  sessionKey?: string;
  /** Set only when the caller authenticated with an API key (work 084). */
  key?: AssertedAPIKey;
  /** The key creator's (or the dashboard member's) name and email, when the auth read loaded them. */
  userName?: string | null;
  userEmail?: string | null;
}

const DEFAULT_MANAGED_AGENTS_API_URL = "https://managedagents.opencomputer.dev";
const DASHBOARD_MANAGED_AGENTS_PREFIX = "/api/dashboard/managed-agents";
const MAX_AGENT_SOURCE_BYTES = 10 * 1024 * 1024;

export async function hasBYOKPlanAccess(
  env: ManagedAgentsEnv,
  orgID: string,
): Promise<boolean> {
  if (!env.OPENCOMPUTER_DB) return false;
  const org = await env.OPENCOMPUTER_DB.prepare(
    "SELECT plan, billing_provider FROM orgs WHERE id = ?1",
  )
    .bind(orgID)
    .first<{ plan: string; billing_provider: string }>();
  if (!org) return false;
  if (org.billing_provider !== "autumn") {
    return org.plan === "pro" || org.plan === "max";
  }
  if (!env.AUTUMN_SECRET_KEY) {
    throw new Error("Autumn billing is not configured");
  }
  const customer = await getAutumnCustomer(
    {
      AUTUMN_SECRET_KEY: env.AUTUMN_SECRET_KEY,
      AUTUMN_BASE_URL: env.AUTUMN_BASE_URL,
    },
    orgID,
  );
  // Every plan that allows BYOK grants this feature (trial, pro, max);
  // the plan check covers a customer read before the flag existed.
  if (customer?.flags?.byo_model_subscriptions) return true;
  return (
    customer?.subscriptions?.some(
      (subscription) =>
        (!subscription.status || subscription.status === "active") &&
        (subscription.plan_id === "pro" || subscription.plan_id === "max"),
    ) === true
  );
}

function byokPlanRequired(): Response {
  return Response.json(
    {
      error: {
        code: "model_access_plan_required",
        message: "Upgrade to Pro ($200/mo) to connect or enable a BYOK account.",
      },
    },
    { status: 403 },
  );
}

function b64url(value: ArrayBuffer | Uint8Array): string {
  const bytes = value instanceof Uint8Array ? value : new Uint8Array(value);
  let encoded = "";
  for (const byte of bytes) encoded += String.fromCharCode(byte);
  return btoa(encoded)
    .replace(/\+/g, "-")
    .replace(/\//g, "_")
    .replace(/=+$/, "");
}

export async function mintManagedAgentsAssertion(
  secret: string,
  caller: ManagedAgentsCaller,
): Promise<string> {
  const now = Math.floor(Date.now() / 1000);
  const header = { alg: "HS256", typ: "JWT" };
  const payload: Record<string, unknown> = {
    iss: "opencomputer-edge",
    aud: "managedagents",
    sub: caller.orgID,
    org_id: caller.orgID,
    iat: now,
    exp: now + 120,
  };
  if (caller.userID) payload.user_id = caller.userID;
  if (caller.role) payload.role = caller.role;
  if (caller.principal) payload.principal = caller.principal;
  if (caller.principal && caller.sessionKey) payload.session_key = caller.sessionKey;
  if (caller.key) {
    payload.key_id = caller.key.id;
    payload.key_hash = caller.key.hash;
    payload.key_name = caller.key.name;
    payload.key_kind = caller.key.kind;
    payload.key_scopes = caller.key.scopes;
    payload.key_expires_at = caller.key.expiresAt;
    payload.key_created_at = caller.key.createdAt;
  }
  // A key's creator, or a dashboard session's member (work tracking 3.10).
  if (caller.userName) payload.user_name = caller.userName;
  if (caller.userEmail) payload.user_email = caller.userEmail;
  const encoder = new TextEncoder();
  const signingInput =
    `${b64url(encoder.encode(JSON.stringify(header)))}.` +
    b64url(encoder.encode(JSON.stringify(payload)));
  const key = await crypto.subtle.importKey(
    "raw",
    encoder.encode(secret),
    { name: "HMAC", hash: "SHA-256" },
    false,
    ["sign"],
  );
  const signature = await crypto.subtle.sign(
    "HMAC",
    key,
    encoder.encode(signingInput),
  );
  return `${signingInput}.${b64url(signature)}`;
}

function copyRequestHeaders(request: Request): Headers {
  const headers = new Headers();
  for (const name of [
    "accept",
    "content-type",
    "idempotency-key",
    "last-event-id",
  ]) {
    const value = request.headers.get(name);
    if (value) headers.set(name, value);
  }
  headers.set("x-request-id", crypto.randomUUID());
  return headers;
}

// Automated Slack setup (docs/agents/channels.mdx "Connect Slack"). The
// backend's codes are stable; the messages are written here so a provider
// phrase never reaches the dashboard.
const SLACK_SETUP_ERROR_MESSAGES: Record<string, string> = {
  slack_setup_conflict:
    "This setup request was already used with a different bot name or target. Start a new setup.",
  slack_setup_active:
    "A Slack setup is already in progress for this agent and environment. Resume it instead of starting another.",
  slack_already_connected:
    "Slack is already connected for this agent and environment. Disconnect it before creating another app.",
  slack_setup_unavailable:
    "Automatic Slack setup is not available right now. Set up the app manually instead.",
  slack_setup_not_found: "That Slack setup does not exist.",
  slack_configuration_token_invalid:
    "Slack rejected the configuration access token. Generate a new token at api.slack.com/apps and try again.",
  slack_configuration_token_expired:
    "The configuration access token has expired. Generate a new one at api.slack.com/apps and try again.",
  slack_manifest_rejected:
    "Slack rejected the generated app manifest. Check the channel's declared scopes and events.",
  slack_app_limit_reached:
    "This Slack workspace has reached its app limit. Remove an unused app in Slack or choose another workspace.",
  slack_rate_limited:
    "Slack is rate limiting app creation. Wait a moment and try again.",
  slack_provider_unavailable:
    "Slack is temporarily unavailable. Try again shortly.",
  slack_creation_uncertain:
    "Slack may have created the app, but the result was lost. Check your Slack app list before creating another.",
  slack_exchange_uncertain:
    "The installation could not be confirmed. Authorize the app again.",
  slack_exchange_failed:
    "Slack did not confirm the installation. Authorize the app again.",
  slack_setup_not_authorizable:
    "This setup cannot be authorized in its current state. Reload to see its next step.",
  slack_setup_connected:
    "This setup is already connected and cannot be cancelled. Disconnect the Slack connection instead.",
  slack_setup_busy:
    "This Slack setup is in progress. Wait for it to finish before cancelling.",
  slack_setup_cancelled:
    "This Slack setup was cancelled. The Slack app may still appear in your workspace's app list and can be removed there.",
  slack_manual_completion_blocked:
    "Manual completion is blocked: cancel the automated setup for this connection, then generate a new manifest (Reconnect) before entering credentials.",
  slack_connection_changed:
    "This connection changed while the request was in flight. Reload the page to see its current state before trying again.",
  slack_authorization_denied:
    "The Slack installation was declined. Authorize the app again when you are ready.",
  slack_authorization_expired:
    "The Slack authorization link expired. Authorize the app again.",
  slack_app_mismatch:
    "Slack installed a different app than the one created for this agent. Authorize the generated app again.",
  slack_workspace_mismatch:
    "The app was installed to a different Slack workspace than the one already connected.",
  slack_scope_missing:
    "The installed app is missing a permission the deployment declares. Authorize it again to reinstall with the current manifest.",
  slack_enterprise_install_unsupported:
    "Organization-wide Slack installations are not supported. Install the app into a single workspace.",
  slack_setup_superseded:
    "This setup no longer owns the connection. Use Set up manually or start again.",
};

const DEPLOYMENT_SOURCE_ERROR_MESSAGES: Record<string, string> = {
  invalid_deployment_source:
    "Choose a GitHub connection, a repository, and a branch name.",
  branch_not_found:
    "That branch was not found in the repository, or the GitHub connection cannot read it.",
  deployment_source_not_found:
    "Connect a repository and branch before deploying.",
  preview_not_found: "That preview no longer exists.",
  invalid_preview: "Preview names look like pr-<number>.",
};

/** Fixed public wording per workspace export code; upstream messages may
 * name buckets or object keys and are never forwarded. */
const WORKSPACE_EXPORT_ERROR_MESSAGES: Record<string, string> = {
  artifact_path_invalid: "The workspace path is not exportable.",
  artifact_not_found: "The workspace file was not found.",
  artifact_symlink_rejected: "Symbolic links are not exported.",
  artifact_not_regular_file: "Only regular files can be exported.",
  artifact_too_large: "The workspace file is too large to export.",
  artifact_changed_during_snapshot:
    "The workspace file changed during export; retry.",
  artifact_size_mismatch:
    "The workspace file size differs from the expected byte count.",
  artifact_digest_mismatch:
    "The workspace file digest differs from the expected SHA-256.",
  artifact_media_type_mismatch:
    "The workspace file media type differs from the expected one.",
  export_idempotency_conflict:
    "The Idempotency-Key was already used for a different export request.",
  export_in_progress: "An export with this Idempotency-Key is still running.",
  export_expired:
    "The export expired before completing; use a new Idempotency-Key.",
  workspace_unavailable: "The session workspace is not available.",
  workspace_export_failed: "The workspace export failed.",
};

async function publicErrorResponse(
  upstream: Response,
  suffix?: string,
): Promise<Response> {
  const body: unknown = await upstream.json().catch(() => null);
  const backendError =
    body &&
    typeof body === "object" &&
    "error" in body &&
    (body as { error?: unknown }).error &&
    typeof (body as { error: unknown }).error === "object"
      ? (body as { error: Record<string, unknown> }).error
      : null;
  const backendErrorType =
    typeof backendError?.code === "string"
      ? backendError.code
      : typeof backendError?.type === "string"
        ? backendError.type
        : "";
  const backendCode = /^[a-z][a-z0-9_]{0,63}$/.test(backendErrorType)
    ? backendErrorType
    : "agent_request_failed";
  const backendMessage =
    typeof backendError?.message === "string" ? backendError.message : "";
  const missingTemplateManifest =
    backendCode === "template_sync_failed" &&
    backendMessage.includes("oc-template.toml") &&
    backendMessage.includes("expected a regular file");
  const workspaceExportError =
    backendCode.startsWith("artifact_") ||
    backendCode.startsWith("export_") ||
    backendCode.startsWith("workspace_");
  // Only the documented export codes pass through; anything else from that
  // family collapses to the generic code so no upstream detail leaks.
  const publicCode = missingTemplateManifest
    ? "template_manifest_missing"
    : workspaceExportError &&
        !Object.hasOwn(WORKSPACE_EXPORT_ERROR_MESSAGES, backendCode)
      ? "workspace_export_failed"
      : backendCode;
  let message = "The agent request could not be completed.";
  const slackSetupMessage = Object.hasOwn(
    SLACK_SETUP_ERROR_MESSAGES,
    backendCode,
  )
    ? SLACK_SETUP_ERROR_MESSAGES[backendCode]
    : undefined;
  const deploymentSourceMessage = Object.hasOwn(
    DEPLOYMENT_SOURCE_ERROR_MESSAGES,
    backendCode,
  )
    ? DEPLOYMENT_SOURCE_ERROR_MESSAGES[backendCode]
    : undefined;
  const linearMessage = Object.hasOwn(LINEAR_ERROR_MESSAGES, backendCode)
    ? LINEAR_ERROR_MESSAGES[backendCode]
    : suffix !== undefined &&
        isLinearRouteSuffix(suffix) &&
        Object.hasOwn(LINEAR_ROUTE_ERROR_MESSAGES, backendCode)
      ? LINEAR_ROUTE_ERROR_MESSAGES[backendCode]
      : undefined;
  const familyMessage =
    suffix !== undefined
      ? routeFamilyFor(suffix, DASHBOARD_MANAGED_AGENTS_PREFIX)?.errorMessage(
          backendCode,
          upstream.status,
          suffix,
          backendMessage,
        )
      : undefined;
  if (familyMessage) {
    message = familyMessage;
  } else if (slackSetupMessage) {
    message = slackSetupMessage;
  } else if (deploymentSourceMessage) {
    message = deploymentSourceMessage;
  } else if (linearMessage) {
    message = linearMessage;
  } else if (missingTemplateManifest) {
    message =
      "This is not a valid template: oc-template.toml is missing from the repository root.";
  } else if (upstream.status === 400) {
    message =
      backendCode === "invalid_agent_name"
        ? "Agent names must use lowercase letters, numbers, and hyphens."
        : backendCode === "invalid_external_reference"
          ? "externalReference must be a non-empty string of at most 256 bytes of UTF-8 without control characters."
          : backendCode === "invalid_cursor"
            ? "The cursor is invalid or was issued for different filters. Start again from the first page."
            : backendCode === "unsupported_region"
              ? 'The region in opencomputer.toml is not supported. Use a Modal region, such as "us", "eu-west" or "au".'
              : backendCode === "invalid_egress"
                ? 'The [egress] allow list in opencomputer.toml is invalid. Use domains ("api.github.com", "*.example.com"), IP addresses or CIDRs, at most 64 of each.'
                : backendCode === "invalid_fixed_ips"
                  ? 'The [egress] fixed_ips region in opencomputer.toml is not supported. https://managedagents.opencomputer.dev/v1/egress-ips lists the regions, such as "au".'
                  : "The agent request was invalid.";
  } else if (upstream.status === 401 || upstream.status === 403) {
    message = "The agent request was not authorized.";
  } else if (upstream.status === 404) {
    message = "The requested agent resource was not found.";
  } else if (upstream.status === 409) {
    if (backendCode === "project_archived") {
      message = "Restore this project before starting new work.";
    } else if (backendCode === "invalid_model_selection") {
      message =
        backendMessage || "The deployment selects an unavailable model.";
    } else if (backendCode === "database_not_provisioned") {
      message = "Redeploy this project to provision its database.";
    } else if (backendCode === "question_stale") {
      message =
        "That question is no longer open. Read the session's current question and answer that one.";
    } else if (backendCode === "destination_verification_failed") {
      if (
        backendMessage === "Invite the Slack app to this conversation first"
      ) {
        message = backendMessage;
      } else if (backendMessage === "Slack conversation is archived") {
        message = "That Slack conversation is archived.";
      } else if (backendMessage.includes("channel_not_found")) {
        message =
          "Slack could not find that conversation. Check its ID and invite the app first.";
      } else if (backendMessage.includes("missing_scope")) {
        message =
          "The Slack app is missing a required permission. Reinstall it from the current manifest.";
      } else {
        message =
          "Slack could not verify that conversation. Check its ID and app membership.";
      }
    } else if (backendCode === "fixed_ips_unsupported") {
      message = "This deployment's fixed IPs need a Modal sandbox.";
    } else {
      message = "The agent request conflicts with the current state.";
    }
  } else if (upstream.status === 429) {
    message = "Too many agent requests. Try again shortly.";
  } else if (upstream.status === 402) {
    message =
      backendCode === "insufficient_credits"
        ? FREE_CREDITS_PAYWALL
        : "The agent request requires additional prepaid credits.";
  } else if (upstream.status >= 500) {
    message =
      backendCode === "fixed_ips_unavailable"
        ? "Fixed IPs are not available in this region right now. Try again shortly."
        : "The agent service is temporarily unavailable.";
  }
  const headers = new Headers({ "content-type": "application/json" });
  const retryAfter = upstream.headers.get("retry-after");
  if (retryAfter) headers.set("retry-after", retryAfter);
  // The one extra field an error may carry: the id of the setup already in
  // progress for the target, so the caller can resume it.
  const setupId =
    backendCode === "slack_setup_active" &&
    typeof backendError?.setupId === "string" &&
    /^[A-Za-z0-9_-]{1,128}$/.test(backendError.setupId)
      ? { setupId: backendError.setupId }
      : {};
  // A Linear conflict names the connection it concerns, so the caller can
  // continue from it (disconnect it, or list and resume).
  const linearConnection =
    (backendCode === "linear_already_connected" ||
      backendCode === "linear_connection_changed") &&
    typeof backendError?.connectionId === "string" &&
    /^[A-Za-z0-9_-]{1,128}$/.test(backendError.connectionId)
      ? { connectionId: backendError.connectionId }
      : {};
  // Workspace export refusals say whether the same Idempotency-Key may be
  // retried and which export record the refusal was written to.
  const exportOutcome: Record<string, unknown> = {};
  if (workspaceExportError) {
    if (typeof backendError?.retrySafe === "boolean") {
      exportOutcome.retrySafe = backendError.retrySafe;
    }
    if (
      typeof backendError?.exportId === "string" &&
      /^wsexp_[a-f0-9]{32}$/.test(backendError.exportId)
    ) {
      exportOutcome.exportId = backendError.exportId;
    }
    message = WORKSPACE_EXPORT_ERROR_MESSAGES[publicCode];
  }
  return new Response(
    JSON.stringify({
      error: {
        code: publicCode,
        message,
        ...setupId,
        ...linearConnection,
        ...exportOutcome,
      },
    }),
    { status: upstream.status, headers },
  );
}

function record(value: unknown): Record<string, unknown> | null {
  return value && typeof value === "object" && !Array.isArray(value)
    ? (value as Record<string, unknown>)
    : null;
}

function strings(value: unknown): string[] {
  return Array.isArray(value)
    ? value.filter((item): item is string => typeof item === "string")
    : [];
}

// Project memory (docs/agents/document-memory.mdx, "Management API"). The
// backend mirrors the public routes one-to-one, so the edge passes the
// documented bodies, status codes, error envelope and the conditional
// headers (`ETag`, `If-Match`, `If-None-Match`) through untouched.
// The resource inventory is the durable list of an environment's resources,
// independent of what the current deployments declare: `declared` says
// whether an active deployment still names the resource, `documents` counts
// its live documents.
const MEMORY_RESOURCES_ROUTE = /^\/projects\/[^/]+\/memory$/;
const MEMORY_DOCUMENTS_ROUTE = /^\/projects\/[^/]+\/memory\/[^/]+\/documents$/;
const MEMORY_DOCUMENT_ROUTE =
  /^\/projects\/[^/]+\/memory\/[^/]+\/documents\/[^/]+$/;
const MEMORY_CONDITIONAL_REQUEST_HEADERS = ["if-match", "if-none-match"];

function isMemoryRoute(method: string, suffix: string): boolean {
  if (
    method === "GET" &&
    (MEMORY_RESOURCES_ROUTE.test(suffix) || MEMORY_DOCUMENTS_ROUTE.test(suffix))
  ) {
    return true;
  }
  return (
    (method === "GET" ||
      method === "PUT" ||
      method === "PATCH" ||
      method === "DELETE") &&
    MEMORY_DOCUMENT_ROUTE.test(suffix)
  );
}

function publicMemoryWriter(value: unknown): Record<string, unknown> {
  const writer = record(value) ?? {};
  return writer.kind === "agent"
    ? { kind: "agent", sessionId: writer.sessionId }
    : { kind: "owner" };
}

function publicMemoryDocumentMeta(value: unknown): Record<string, unknown> {
  const document = record(value) ?? {};
  return {
    id: document.id,
    title: document.title,
    summary: document.summary,
    agentWrites: document.agentWrites,
    revision: document.revision,
    bytes: document.bytes,
    maxBytes: document.maxBytes,
    updatedAt: document.updatedAt,
    writer: publicMemoryWriter(document.writer),
  };
}

function publicMemoryDocument(value: unknown): Record<string, unknown> {
  const document = record(value) ?? {};
  return { ...publicMemoryDocumentMeta(document), text: document.text };
}

function publicMemoryResource(value: unknown): Record<string, unknown> {
  const resource = record(value) ?? {};
  const provider = record(resource.provider) ?? {};
  return {
    id: resource.id,
    provider: { kind: provider.kind, maxBytes: provider.maxBytes },
    declared: resource.declared === true,
    documents: typeof resource.documents === "number" ? resource.documents : 0,
  };
}

// Memory errors are the documented `{ error: { code, message } }` envelope
// with user-facing messages (stale revision, oversized text, missing
// condition header), so client errors pass through as the backend wrote them.
// Server errors keep the generic redaction every other route gets.
async function memoryResponse(
  upstream: Response,
  method: string,
  suffix: string,
): Promise<Response> {
  const headers = new Headers({ "cache-control": "no-store" });
  const etag = upstream.headers.get("etag");
  if (etag) headers.set("etag", etag);
  if (upstream.status === 204 || upstream.status === 304) {
    return new Response(null, { status: upstream.status, headers });
  }
  if (!upstream.ok) {
    if (upstream.status >= 500) return publicErrorResponse(upstream);
    const body = record(
      await upstream
        .clone()
        .json()
        .catch(() => null),
    );
    const error = record(body?.error);
    const code =
      typeof error?.code === "string" &&
      /^[a-z][a-z0-9_]{0,63}$/.test(error.code)
        ? error.code
        : null;
    const message =
      typeof error?.message === "string" ? error.message.slice(0, 1_000) : null;
    if (!code || message === null) return publicErrorResponse(upstream);
    headers.set("content-type", "application/json");
    return new Response(JSON.stringify({ error: { code, message } }), {
      status: upstream.status,
      headers,
    });
  }
  const body = record(await upstream.json().catch(() => null)) ?? {};
  headers.set("content-type", "application/json");
  const value =
    method === "GET" && MEMORY_RESOURCES_ROUTE.test(suffix)
      ? {
          resources: Array.isArray(body.resources)
            ? body.resources.map(publicMemoryResource)
            : [],
        }
      : method === "GET" && MEMORY_DOCUMENTS_ROUTE.test(suffix)
        ? {
            documents: Array.isArray(body.documents)
              ? body.documents.map(publicMemoryDocumentMeta)
              : [],
            nextCursor:
              typeof body.nextCursor === "string" ? body.nextCursor : null,
          }
        : publicMemoryDocument(body);
  return new Response(JSON.stringify(value), {
    status: upstream.status,
    headers,
  });
}

// A memory resource the deployment declares (docs/agents/document-memory.mdx,
// "Configuration"): what the Memory page and `memory export` enumerate.
function publicMemoryDeclaration(value: unknown): Record<string, unknown> {
  const declaration = record(value) ?? {};
  const provider = record(declaration.provider) ?? {};
  return {
    id: declaration.id,
    description: declaration.description,
    provider: { kind: provider.kind, maxBytes: provider.maxBytes },
  };
}

/** A deployment's egress allowlist as the service returns it, or undefined. */
function publicEgress(value: unknown): { domains: string[]; cidrs: string[] } | undefined {
  if (!value || typeof value !== "object" || Array.isArray(value)) return undefined;
  const egress = value as { domains?: unknown; cidrs?: unknown };
  return { domains: strings(egress.domains), cidrs: strings(egress.cidrs) };
}

function publicDeployment(value: unknown): Record<string, unknown> {
  const deployment = record(value) ?? {};
  return {
    id: deployment.id,
    agentId: deployment.agentId,
    alias: deployment.alias,
    channels: strings(deployment.channels),
    connections: strings(deployment.connections),
    createdAt: deployment.createdAt,
    ...(typeof deployment.region === "string" ? { region: deployment.region } : {}),
    ...(publicEgress(deployment.egress) ? { egress: publicEgress(deployment.egress)! } : {}),
    ...(typeof deployment.fixedIps === "string" ? { fixedIps: deployment.fixedIps } : {}),
    ...(Array.isArray(deployment.models)
      ? {
          models: deployment.models.flatMap((value) => {
            const model = record(value);
            return model &&
              typeof model.provider === "string" &&
              typeof model.model === "string"
              ? [{ provider: model.provider, model: model.model }]
              : [];
          }),
        }
      : {}),
    ...(record(deployment.defaultModel)
      ? {
          defaultModel: {
            provider: record(deployment.defaultModel)?.provider,
            model: record(deployment.defaultModel)?.model,
          },
        }
      : {}),
    ...(Array.isArray(deployment.memory)
      ? { memory: deployment.memory.map(publicMemoryDeclaration) }
      : {}),
    ...(deployment.projectDeployment
      ? { projectDeployment: stripPrivateValues(deployment.projectDeployment) }
      : {}),
  };
}

function publicAgent(value: unknown): Record<string, unknown> {
  const agent = record(value) ?? {};
  return {
    id: agent.id,
    // An agent that was never named falls back to its id, so the dashboard
    // always has something to render.
    name: typeof agent.name === "string" && agent.name ? agent.name : agent.id,
    activeAlias: agent.activeAlias,
    activeDeploymentId: agent.activeDeploymentId,
    deploymentCount: agent.deploymentCount,
    createdAt: agent.createdAt,
    updatedAt: agent.updatedAt,
  };
}

function publicProject(value: unknown): Record<string, unknown> {
  const project = record(value) ?? {};
  const agentId =
    typeof project.agentId === "string" ? project.agentId : undefined;
  const agents = Array.isArray(project.agents)
    ? project.agents.flatMap((value) => {
        const agent = record(value);
        return agent && typeof agent.id === "string"
          ? [
              {
                id: agent.id,
                name: typeof agent.name === "string" ? agent.name : agent.id,
              },
            ]
          : [];
      })
    : agentId
      ? [
          {
            id: agentId,
            name: `Hello ${typeof project.name === "string" ? project.name : agentId}`.slice(
              0,
              80,
            ),
          },
        ]
      : [];
  return {
    id: project.id,
    slug: project.slug,
    name: project.name,
    ...(agentId ? { agentId } : {}),
    // Projects that predate the mode column are legacy dual-environment
    // projects; a single-mode project is only ever reported as such.
    environmentMode: project.environmentMode === "single" ? "single" : "legacy",
    environments: Array.isArray(project.environments)
      ? stripPrivateValues(project.environments)
      : [],
    agents,
    ...(typeof project.archivedAt === "string"
      ? { archivedAt: project.archivedAt }
      : {}),
    createdAt: project.createdAt,
    updatedAt: project.updatedAt,
  };
}

function publicConnection(value: unknown): Record<string, unknown> {
  const connection = record(value) ?? {};
  return {
    id: connection.id,
    kind: connection.kind,
    provider: connection.provider,
    label: connection.label,
    agentId: connection.agentId,
    alias: connection.alias,
    displayName: connection.displayName,
    scopes: strings(connection.scopes),
    status: connection.status,
    createdAt: connection.createdAt,
    updatedAt: connection.updatedAt,
  };
}

function publicProjectServiceAttachment(
  value: unknown,
): Record<string, unknown> {
  const attachment = record(value) ?? {};
  return {
    projectId: attachment.projectId,
    service: attachment.service,
    provider: attachment.provider,
    label: attachment.label,
    connectionId: attachment.connectionId,
    connection: publicConnection(attachment.connection),
    createdAt: attachment.createdAt,
    updatedAt: attachment.updatedAt,
  };
}

function publicModelAccessConnection(
  value: unknown,
  includeAdminMetadata: boolean,
): Record<string, unknown> {
  const connection = record(value) ?? {};
  return {
    id: connection.id,
    provider: connection.provider,
    kind: connection.kind,
    label: connection.label,
    baseUrl: connection.baseUrl,
    status: connection.status,
    checkedAt: connection.checkedAt,
    createdAt: connection.createdAt,
    updatedAt: connection.updatedAt,
    ...(includeAdminMetadata
      ? {
          organizationId: connection.organizationId,
          connectedByUserId: connection.connectedByUserId,
          externalAccountHint: connection.externalAccountHint,
        }
      : {}),
  };
}

function publicModelRoute(value: unknown): Record<string, unknown> {
  const route = record(value) ?? {};
  return {
    id: route.id,
    projectId: route.projectId,
    environment: route.environment,
    agentId: route.agentId,
    connectionId: route.connectionId,
    model: route.model,
    fallback: route.fallback,
    revision: route.revision,
    createdAt: route.createdAt,
    updatedAt: route.updatedAt,
  };
}

function publicModelAccessBinding(value: unknown): Record<string, unknown> {
  const binding = record(value) ?? {};
  return {
    projectId: binding.projectId,
    environment: binding.environment,
    provider: binding.provider,
    connectionId: binding.connectionId,
    enabled: binding.enabled,
    createdAt: binding.createdAt,
    updatedAt: binding.updatedAt,
  };
}

function publicChannel(value: unknown): Record<string, unknown> {
  const channel = record(value) ?? {};
  const lastDelivery = record(channel.lastDelivery);
  const lastError = record(channel.lastError);
  const publicLastDelivery =
    lastDelivery &&
    (lastDelivery.status === "delivered" || lastDelivery.status === "failed") &&
    typeof lastDelivery.at === "string"
      ? { status: lastDelivery.status, at: lastDelivery.at }
      : undefined;
  const publicLastError =
    lastError &&
    typeof lastError.category === "string" &&
    typeof lastError.at === "string"
      ? { category: lastError.category, at: lastError.at }
      : undefined;
  return {
    id: channel.id,
    channel: "slack",
    channelId: channel.channelId,
    agentId: channel.agentId,
    alias: channel.alias,
    appName: channel.appName,
    appId: channel.appId,
    teamName: channel.teamName,
    verifiedAt: channel.verifiedAt,
    verificationError: channel.verificationError,
    ...(typeof channel.lastEventAt === "string"
      ? { lastEventAt: channel.lastEventAt }
      : {}),
    ...(publicLastDelivery ? { lastDelivery: publicLastDelivery } : {}),
    ...(publicLastError ? { lastError: publicLastError } : {}),
    status: channel.status,
    createdAt: channel.createdAt,
    updatedAt: channel.updatedAt,
    ...(Array.isArray(channel.destinations)
      ? { destinations: channel.destinations.map(stripPrivateValues) }
      : {}),
    // The agents whose registrations consume this channel in the
    // connection's environment; what Project Connections lists as consumers.
    ...(Array.isArray(channel.agents)
      ? { agents: strings(channel.agents) }
      : {}),
  };
}

const SLACK_SETUP_ACTIONS = new Set([
  "create",
  "authorize",
  "manual",
  "cancel",
]);
const SLACK_SETUPS_ROUTE = /^\/channels\/slack\/setups$/;
const SLACK_SETUP_ROUTE = /^\/channels\/slack\/setups\/[^/]+$/;
const SLACK_SETUP_AUTHORIZE_ROUTE =
  /^\/channels\/slack\/setups\/[^/]+\/authorize$/;
const SLACK_SETUP_CANCEL_ROUTE = /^\/channels\/slack\/setups\/[^/]+\/cancel$/;

/**
 * The automated Slack setup record. Redaction is by whitelist: the backend
 * row also carries the generated app credentials, the manifest snapshot and
 * the webhook identity, none of which the dashboard needs to resume.
 */
function isSlackSetupRoute(method: string, suffix: string): boolean {
  return (
    ((method === "GET" || method === "POST") &&
      SLACK_SETUPS_ROUTE.test(suffix)) ||
    (method === "GET" && SLACK_SETUP_ROUTE.test(suffix)) ||
    (method === "POST" &&
      (SLACK_SETUP_AUTHORIZE_ROUTE.test(suffix) ||
        SLACK_SETUP_CANCEL_ROUTE.test(suffix)))
  );
}

function publicSlackSetup(value: unknown): Record<string, unknown> {
  const setup = record(value) ?? {};
  const app = record(setup.app);
  const workspace = record(setup.workspace);
  const error = record(setup.error);
  return {
    id: setup.id,
    requestKey: setup.requestKey,
    projectId: setup.projectId,
    agentId: setup.agentId,
    alias: setup.alias,
    channelId: setup.channelId,
    name: setup.name,
    connectionId: setup.connectionId,
    phase: setup.phase,
    ...(app ? { app: { id: app.id, name: app.name } } : {}),
    ...(workspace
      ? { workspace: { id: workspace.id, name: workspace.name } }
      : {}),
    ...(typeof setup.botUserId === "string"
      ? { botUserId: setup.botUserId }
      : {}),
    ...(error
      ? {
          error: {
            code: error.code,
            message:
              typeof error.code === "string" &&
              Object.hasOwn(SLACK_SETUP_ERROR_MESSAGES, error.code)
                ? SLACK_SETUP_ERROR_MESSAGES[error.code]
                : "The last Slack setup step did not complete.",
            recoverable: error.recoverable === true,
            ...(typeof error.retryAfterMs === "number"
              ? { retryAfterMs: error.retryAfterMs }
              : {}),
            ...(typeof error.pointer === "string"
              ? { pointer: error.pointer }
              : {}),
            at: error.at,
          },
        }
      : {}),
    actions: strings(setup.actions).filter((action) =>
      SLACK_SETUP_ACTIONS.has(action),
    ),
    createdAt: setup.createdAt,
    updatedAt: setup.updatedAt,
  };
}

// Linear agent connections (work 037, design 018 "Connection"). One
// connection per (project, environment, agent); the webhook URL carries the
// connection's secret token, so every response is no-store.
const LINEAR_PROJECT_CONNECTIONS_ROUTE =
  /^\/projects\/[^/]+\/linear\/connections$/;
const LINEAR_CONNECTION_ROUTE = /^\/linear\/connections\/[^/]+$/;
const LINEAR_CREDENTIALS_ROUTE = /^\/linear\/connections\/[^/]+\/credentials$/;
const LINEAR_AUTHORIZE_ROUTE = /^\/linear\/connections\/[^/]+\/authorize$/;

function isLinearConnectionRoute(method: string, suffix: string): boolean {
  return (
    ((method === "GET" || method === "POST") &&
      LINEAR_PROJECT_CONNECTIONS_ROUTE.test(suffix)) ||
    (method === "PUT" && LINEAR_CREDENTIALS_ROUTE.test(suffix)) ||
    (method === "POST" && LINEAR_AUTHORIZE_ROUTE.test(suffix)) ||
    (method === "DELETE" && LINEAR_CONNECTION_ROUTE.test(suffix))
  );
}

function isLinearRouteSuffix(suffix: string): boolean {
  return (
    suffix.startsWith("/linear/") ||
    /^\/projects\/[^/]+\/linear(?:\/|$)/.test(suffix)
  );
}

const LINEAR_ERROR_MESSAGES: Record<string, string> = {
  linear_connector_unavailable:
    "Linear connections are not available right now.",
  linear_connection_not_found: "That Linear connection does not exist.",
  linear_already_connected:
    "This agent already has a Linear connection in this environment. Disconnect it before creating another.",
  linear_connection_changed:
    "This connection changed while the request was in flight. List the connections and continue from there.",
  linear_credentials_required:
    "Paste the app's client ID, client secret and webhook signing secret before authorizing.",
  invalid_linear_credentials:
    "Expected clientId, clientSecret and signingSecret as copied from the Linear app.",
  linear_app_already_connected:
    "This Linear app is already connected to another agent or environment. Create a separate app for each.",
  linear_connection_connected:
    "This connection is authorized with a different Linear app. Disconnect it first.",
  invalid_linear_app_name: "The Linear app name must be 1 to 64 characters.",
  linear_app_name_reserved:
    'Linear does not allow app names that contain "Linear". Choose another name.',
};

// Shared codes worded for the Linear connection routes that return them.
const LINEAR_ROUTE_ERROR_MESSAGES: Record<string, string> = {
  forbidden:
    "Project-scoped API keys cannot create or change Linear connections. Use an organization API key.",
  project_not_found: "That project does not exist.",
  project_archived: "Restore this project before connecting Linear.",
};

/** A Linear connection by whitelist: never its credentials or account. */
function publicLinearConnection(value: unknown): Record<string, unknown> {
  const connection = record(value) ?? {};
  const teams = record(connection.teams);
  const health = record(connection.health);
  return {
    id: connection.id,
    projectId: connection.projectId,
    environment: connection.environment,
    agentId: connection.agentId,
    name: connection.name,
    status: connection.status,
    clientId: connection.clientId,
    appUserId: connection.appUserId,
    organizationId: connection.organizationId,
    webhookUrl: connection.webhookUrl,
    createAppUrl: connection.createAppUrl,
    verifiedAt: connection.verifiedAt,
    verificationError: connection.verificationError,
    lastEventAt: connection.lastEventAt,
    ...(teams
      ? { teams: { allPublic: teams.allPublic === true, teamIds: strings(teams.teamIds) } }
      : {}),
    ...(health
      ? {
          health: {
            state: health.state,
            message: health.message,
            lastEventAt: health.lastEventAt,
          },
        }
      : {}),
    revision: connection.revision,
    createdAt: connection.createdAt,
    updatedAt: connection.updatedAt,
  };
}

function publicOutboxItem(value: unknown): Record<string, unknown> {
  const item = record(value) ?? {};
  const content = record(item.contentPreview) ?? {};
  return {
    id: item.id,
    outboxId: item.outboxId,
    eventType: item.eventType,
    sessionId: item.sessionId,
    contentPreview: {
      ...(typeof content.title === "string" ? { title: content.title } : {}),
      ...(typeof content.body === "string" ? { body: content.body } : {}),
      ...(typeof content.url === "string" ? { url: content.url } : {}),
    },
    status: item.status,
    destination: item.destination,
    attemptCount: item.attemptCount,
    ...(item.error ? { error: "Delivery failed." } : {}),
    createdAt: item.createdAt,
    updatedAt: item.updatedAt,
  };
}

function publicOutbox(value: unknown): Record<string, unknown> {
  const outbox = record(value) ?? {};
  return {
    id: outbox.id,
    channelId: outbox.channelId,
    channelName: outbox.channelName,
    destination: outbox.destination,
    readiness: outbox.readiness,
    targetDisplayName: outbox.targetDisplayName,
    items: Array.isArray(outbox.items)
      ? outbox.items.map(publicOutboxItem)
      : [],
  };
}

function publicSchedule(value: unknown): Record<string, unknown> {
  const schedule = record(value) ?? {};
  return {
    id: schedule.id,
    projectId: schedule.projectId,
    environment: schedule.environment,
    agentId: schedule.agentId,
    deploymentId: schedule.deploymentId,
    cron: schedule.cron,
    timezone: schedule.timezone,
    overlap: schedule.overlap,
    dispatch: stripPrivateValues(schedule.dispatch),
    nextRunAt: schedule.nextRunAt,
    lastRunAt: schedule.lastRunAt,
    status: schedule.status,
  };
}

function publicScheduleRun(value: unknown): Record<string, unknown> {
  const run = record(value) ?? {};
  return {
    id: run.id,
    scheduleId: run.scheduleId,
    projectId: run.projectId,
    environment: run.environment,
    deploymentId: run.deploymentId,
    scheduledAt: run.scheduledAt,
    manual: run.manual,
    attempt: run.attempt,
    outcome: run.outcome,
    sessionId: run.sessionId,
    ...(run.error ? { error: "The scheduled run could not be started." } : {}),
    createdAt: run.createdAt,
  };
}

function stripPrivateValues(value: unknown): unknown {
  if (Array.isArray(value)) return value.map(stripPrivateValues);
  const source = record(value);
  if (!source) return value;
  return Object.fromEntries(
    Object.entries(source)
      .filter(([key]) => !PRIVATE_EVENT_KEYS.has(key))
      .map(([key, child]) => [key, stripPrivateValues(child)]),
  );
}

function publicRuntimeVariable(value: unknown): Record<string, unknown> {
  const variable = record(value) ?? {};
  return {
    name: variable.name,
    projectId: variable.projectId,
    environment: variable.environment,
    ...(typeof variable.agentId === "string"
      ? { agentId: variable.agentId }
      : {}),
    createdAt: variable.createdAt,
    updatedAt: variable.updatedAt,
  };
}

function publicWebhook(
  value: unknown,
  publicOrigin?: string,
): Record<string, unknown> {
  const webhook = record(value) ?? {};
  const id = typeof webhook.id === "string" ? webhook.id : "";
  return {
    id: webhook.id,
    projectId: webhook.projectId,
    environment: webhook.environment,
    agentId: webhook.agentId,
    name: webhook.name,
    enabled: webhook.enabled,
    ...(typeof webhook.identity === "string"
      ? { identity: webhook.identity }
      : {}),
    // The token is the credential; when this response carries it (create,
    // rotate), the URL carries it too and is shown once. Listings never do.
    ...(publicOrigin && id
      ? {
          invocationUrl:
            `${publicOrigin}/api/agent-webhooks/${encodeURIComponent(id)}` +
            (typeof webhook.token === "string"
              ? `/${encodeURIComponent(webhook.token)}`
              : ""),
        }
      : {}),
    ...(typeof webhook.token === "string" ? { token: webhook.token } : {}),
    createdAt: webhook.createdAt,
    updatedAt: webhook.updatedAt,
    lastInvokedAt: webhook.lastInvokedAt,
  };
}

function publicWebhookRequest(value: unknown): Record<string, unknown> {
  const request = record(value) ?? {};
  return {
    id: request.id,
    webhookId: request.webhookId,
    projectId: request.projectId,
    environment: request.environment,
    agentId: request.agentId,
    deploymentId: request.deploymentId,
    sessionId: request.sessionId,
    outcome: request.outcome,
    ...(typeof request.attempt === "number"
      ? { attempt: request.attempt }
      : {}),
    ...(request.terminal === true ? { terminal: true } : {}),
    ...(request.error
      ? { error: "The webhook request could not start a session." }
      : {}),
    createdAt: request.createdAt,
    updatedAt: request.updatedAt,
  };
}

// Event subscriptions (docs/agents/api.mdx, "Event subscriptions"): the
// backend owns the body and the object, so both pass through as written,
// less who created it. Fields the edge does not know (the environment scope,
// for one) are the backend's to validate and are kept.
const EVENT_SUBSCRIPTIONS_ROUTE = /^\/projects\/[^/]+\/event-subscriptions$/;
const EVENT_SUBSCRIPTION_ROUTE =
  /^\/projects\/[^/]+\/event-subscriptions\/[^/]+$/;

function isEventSubscriptionRoute(method: string, suffix: string): boolean {
  return (
    ((method === "GET" || method === "POST") &&
      EVENT_SUBSCRIPTIONS_ROUTE.test(suffix)) ||
    ((method === "GET" || method === "DELETE") &&
      EVENT_SUBSCRIPTION_ROUTE.test(suffix))
  );
}

function publicEventSubscription(value: unknown): unknown {
  const subscription = record(stripPrivateValues(value));
  if (!subscription) return value;
  const { createdBy: _createdBy, ...rest } = subscription;
  return rest;
}

// A delivery's `error` is the backend's terminal verdict when it is one of
// its codes; any other text is an operator message and is not public.
const DELIVERY_ERROR_CODES = new Set([
  "subscription_unavailable",
  "target_missing",
  "target_ended",
]);

function publicDelivery(value: unknown): Record<string, unknown> {
  const delivery = record(value) ?? {};
  const receipt = record(delivery.receipt);
  return {
    id: delivery.id,
    subscriptionId: delivery.subscriptionId,
    eventId: delivery.eventId,
    eventType: delivery.eventType,
    destination: stripPrivateValues(delivery.destination),
    status: delivery.status,
    attempt: delivery.attempt,
    ...(receipt
      ? { receipt: { sessionId: receipt.sessionId, turnId: receipt.turnId } }
      : {}),
    ...(typeof delivery.nextAttemptAt === "string"
      ? { nextAttemptAt: delivery.nextAttemptAt }
      : {}),
    ...(typeof delivery.error === "string"
      ? {
          error: DELIVERY_ERROR_CODES.has(delivery.error)
            ? delivery.error
            : "delivery_failed",
        }
      : {}),
    updatedAt: delivery.updatedAt,
  };
}

/**
 * Session labels are the owner's own strings under the owner's own keys.
 * They are read from the source, never from a stripped copy, so a label the
 * owner happened to call `user_id` or `runtime_id` is kept.
 */
function ownerLabels(source: Record<string, unknown>): Record<string, string> {
  const labels = record(source.labels) ?? {};
  return Object.fromEntries(
    Object.entries(labels).filter(
      (entry): entry is [string, string] => typeof entry[1] === "string",
    ),
  );
}

/**
 * The session's result as documented: the call that reported it and its
 * `data` verbatim. `data` is the application's own JSON, so nothing inside
 * it is inspected or renamed; `null` when no turn has reported one.
 */
function publicSessionResult(value: unknown): unknown {
  const result = record(value);
  if (!result) return null;
  return {
    turnId: result.turnId,
    callId: result.callId,
    reportedAt: result.reportedAt,
    data: result.data,
  };
}

/**
 * Platform-internal fields of the session envelope that no public route
 * documents: the runtime generation counter, the name of the memory object
 * the bindings were admitted against, and the creation intent the platform
 * compares on an idempotent replay. Dropped by position, since the name
 * filter is for the fields it lists.
 */
const PRIVATE_SESSION_FIELDS = new Set([
  "runtimeEpoch",
  "memoryObject",
  "creation",
]);

/**
 * One turn of the snapshot. `payload` is the caller's own JSON and passes
 * through untouched; `deliveries` are platform records with their own public
 * shape; the rest of the turn is platform envelope and keeps the name strip.
 */
function publicTurn(entry: unknown): unknown {
  const turn = record(entry);
  if (!turn) return entry;
  return Object.fromEntries(
    Object.entries(turn).flatMap(([key, child]): Array<[string, unknown]> => {
      if (key === "payload") return [[key, child]];
      if (key === "deliveries") {
        return [
          [key, Array.isArray(child) ? child.map(publicDelivery) : child],
        ];
      }
      if (PRIVATE_EVENT_KEYS.has(key)) return [];
      return [[key, stripPrivateValues(child)]];
    }),
  );
}

/**
 * The public session. Redaction is by position: the platform envelope (the
 * session's own fields, memory bindings, turn records, deliveries) is
 * stripped of private fields, while the positions that hold application
 * data, `labels`, `result.data` and each turn's `payload`, are copied
 * verbatim. A recursive strip over the whole object used to remove keys
 * such as `userId` or `runtimeId` from inside an application's result,
 * which the list row (assembled separately) kept, so the same session
 * answered two routes with two different results.
 */
function publicSessionSnapshot(value: unknown): unknown {
  const source = record(value);
  if (!source) return value;
  return Object.fromEntries(
    Object.entries(source).flatMap(([key, child]): Array<[string, unknown]> => {
      if (key === "labels") return [[key, ownerLabels(source)]];
      if (key === "result") return [[key, publicSessionResult(child)]];
      if (key === "turns") {
        return [
          [
            key,
            Array.isArray(child)
              ? child.map(publicTurn)
              : stripPrivateValues(child),
          ],
        ];
      }
      if (PRIVATE_EVENT_KEYS.has(key) || PRIVATE_SESSION_FIELDS.has(key))
        return [];
      return [[key, stripPrivateValues(child)]];
    }),
  );
}

/**
 * The caller's own `externalReference`, when the session has one. The value is
 * the caller's opaque string and is read from the source, never from a
 * stripped copy, for the same reason labels are.
 */
function ownerExternalReference(
  source: Record<string, unknown>,
): { externalReference: string } | Record<never, never> {
  return typeof source.externalReference === "string"
    ? { externalReference: source.externalReference }
    : {};
}

/** One list row as documented: nothing private is in it, and the labels and result are the owner's. */
function publicSessionSummary(value: unknown): unknown {
  const source = record(value);
  const row = record(stripPrivateValues(value));
  if (!row || !source) return row ?? value;
  return {
    id: row.id,
    projectId: row.projectId,
    agentId: row.agentId,
    deploymentId: row.deploymentId,
    environment: row.environment ?? null,
    source: row.source,
    status: row.status,
    labels: ownerLabels(source),
    ...ownerExternalReference(source),
    createdAt: row.createdAt,
    updatedAt: row.updatedAt,
    revision: row.revision,
    activity: row.activity,
    result: publicSessionResult(source.result),
  };
}

const PRIVATE_EVENT_KEYS = new Set([
  "accountId",
  "account_id",
  "ownerUserId",
  "owner_user_id",
  "userId",
  "user_id",
  "artifact",
  "bucket",
  "imageArn",
  "image_arn",
  "imageVersion",
  "image_version",
  "microvmId",
  "microvm_id",
  "runtimeId",
  "runtime_id",
  "runtimeToken",
  "runtime_token",
  "platformInstructions",
  "platform_instructions",
]);

export type PublicFailureCode =
  | "interrupted"
  | "session_ended"
  | "runtime_lost"
  | "runtime_failed"
  | "deployment_invalid"
  | "model_unavailable"
  | "model_rejected"
  | "context_too_long"
  | "tool_failed"
  | "sandbox_timeout"
  | "sandbox_failed"
  | "model_stream_failed"
  | "agent_failed";

/**
 * What a `turn.failed` or `session.failed` event says in public: a stable
 * code, a fixed sentence, and at most one validated parameter. The runtime's
 * own error text is written for operators and can carry anything (paths,
 * internal URLs, credentials, stack frames), so it is classified here and
 * never forwarded. A failure no rule recognizes is `agent_failed`.
 */
export interface PublicFailure {
  code: PublicFailureCode;
  message: string;
  /** The model the agent asked for, when the runtime rejected it by id. */
  model?: string;
  /** The tool that failed, when the runtime named it. */
  tool?: string;
}

const GENERIC_FAILURE_MESSAGE = "The agent could not complete this request.";

const PUBLIC_FAILURE_MESSAGES: Record<PublicFailureCode, string> = {
  interrupted: "The turn was interrupted before it finished.",
  session_ended: "The session ended before the turn finished.",
  runtime_lost:
    "The agent runtime stopped responding and the turn was abandoned.",
  runtime_failed: "The agent runtime failed before the turn finished.",
  deployment_invalid: "The deployment could not be loaded by the runtime.",
  model_unavailable: "The requested model is not available to this agent.",
  model_rejected: "The model provider rejected the request.",
  context_too_long:
    "The conversation is too long for the model's context window.",
  tool_failed: "A tool failed.",
  sandbox_timeout: "A sandbox command did not finish in time.",
  sandbox_failed: "The sandbox could not run this turn.",
  model_stream_failed: "The model call failed before it finished.",
  agent_failed: GENERIC_FAILURE_MESSAGE,
};

// The typed reasons the session records itself, ahead of any runtime text.
const FAILURE_REASON_CODES: Record<string, PublicFailureCode> = {
  interrupted: "interrupted",
  runtime_interrupted: "interrupted",
  session_ended: "session_ended",
  runtime_lost: "runtime_lost",
};

// A parameter is the only runtime-derived text a public failure carries, so
// it must look like what it claims to be; anything else is dropped.
const MODEL_ID = /^(?:[a-z][a-z0-9-]{0,31}\/)?[a-z0-9][a-z0-9._:-]{0,63}$/i;
const TOOL_ID = /^[a-z0-9_][a-z0-9_.-]{0,63}$/i;
const CREDENTIAL_SHAPED =
  /^(?:sk|osb|ghp|gho|ghs|ghu|ghr|github_pat|xox[abprs]|key|token|secret)[-_]/i;

function validParameter(pattern: RegExp, value: string | undefined) {
  return value !== undefined &&
    pattern.test(value) &&
    !CREDENTIAL_SHAPED.test(value)
    ? value
    : undefined;
}

// The runtime's word that the conversation outgrew the model's window, in
// the provider's text.
const CONTEXT_TOO_LONG =
  /context (?:length|window|overflow)|too long|exceeds? the (?:maximum )?(?:context|token)|ContextOverflow/i;

// Message rules, first match wins. Each names the runtime error family it
// recognizes; the captured group, if any, is the parameter.
const FAILURE_MESSAGE_RULES: ReadonlyArray<{
  code: PublicFailureCode;
  pattern: RegExp;
  parameter?: "model" | "tool";
}> = [
  {
    code: "model_unavailable",
    pattern: /rejects any useModel other than \S+ \(requested (\S+)\)/,
    parameter: "model",
  },
  {
    code: "model_unavailable",
    pattern: /^Model unavailable: (\S+?)\.?(?:\s|$)/,
    parameter: "model",
  },
  {
    code: "model_unavailable",
    pattern:
      /\bmodel (?:is )?not (?:found|available|supported)\b|ModelNotFound/i,
  },
  { code: "context_too_long", pattern: CONTEXT_TOO_LONG },
  {
    code: "model_rejected",
    pattern:
      /\b(?:401|403|429)\b|unauthori[sz]ed|invalid (?:x-)?api[ _-]?key|authentication|rate limit|quota|overloaded|insufficient(?: |_)(?:credits|quota)|APICallError|provider (?:rejected|error)/i,
  },
  {
    code: "tool_failed",
    pattern:
      /^Tool (?:module exported an unregistered tool|is defined more than once): (\S+)$/,
    parameter: "tool",
  },
  {
    code: "tool_failed",
    pattern:
      /^(?:Unknown tool|Tool) "?([A-Za-z0-9_.-]+)"? (?:failed|is not (?:available|registered)|threw)/,
    parameter: "tool",
  },
  { code: "tool_failed", pattern: /^The tool has no edge implementation/ },
  { code: "sandbox_timeout", pattern: /^Sandbox operation timed out/ },
  {
    code: "sandbox_failed",
    pattern: /^(?:Sandbox|The sandbox|Cannot terminate the sandbox)\b/,
  },
  {
    code: "deployment_invalid",
    pattern:
      /^(?:The deployment is missing|The Workerd agent artifact|The Workerd session has no pinned deployment|This Workerd slice requires|Agent must return instructions|Invalid artifact module path|The (?:private artifact service|Dynamic Worker Loader) is not configured|Artifact service returned)/,
  },
  {
    code: "runtime_failed",
    pattern:
      /^(?:Runtime harness|OpenCode|The (?:Workerd|reactive) (?:runtime|harness)|Prestarted OpenCode|Workerd runtime|Agent (?:render|tool metadata) returned|Render commit returned|Session state returned|Agent selected an unregistered)/,
  },
];

// A model call's failure by the provider's typed class, as the runtime
// records it in the failure's `failure` fields. A rejection stays one, a
// route with no model is unavailable, and everything that failed in flight
// (the transport, the provider, a broken or malformed response) is
// `model_stream_failed`.
const PROVIDER_FAILURE_CODES: Record<string, PublicFailureCode> = {
  auth: "model_rejected",
  quota: "model_rejected",
  "content-filter": "model_rejected",
  "rate-limit": "model_rejected",
  "invalid-request": "model_rejected",
  "no-route": "model_unavailable",
  transport: "model_stream_failed",
  internal: "model_stream_failed",
  "invalid-output": "model_stream_failed",
  unknown: "model_stream_failed",
};

/**
 * The public failure from the typed fields the runtime recorded, when it
 * recorded a provider failure: `{ class: "provider", subtype, model?,
 * retry: { attempts } }`. The provider's text decides one thing only, on
 * an invalid request: whether the conversation outgrew the model's window.
 * The retry is named only when one happened; a call that bypasses the
 * runtime's retry (compaction, titling) fails on its first attempt.
 */
function structuredFailure(
  data: Record<string, unknown>,
  firstLine: string,
): PublicFailure | undefined {
  const failure = record(data.failure);
  if (!failure || failure.class !== "provider") return undefined;
  const subtype = typeof failure.subtype === "string" ? failure.subtype : "";
  const code = PROVIDER_FAILURE_CODES[subtype];
  if (!code) return undefined;
  if (subtype === "invalid-request" && CONTEXT_TOO_LONG.test(firstLine)) {
    return {
      code: "context_too_long",
      message: PUBLIC_FAILURE_MESSAGES.context_too_long,
    };
  }
  const model = validParameter(
    MODEL_ID,
    typeof failure.model === "string" ? failure.model : undefined,
  );
  if (code === "model_unavailable" && model) {
    return {
      code,
      message: `The model ${model} is not available to this agent.`,
      model,
    };
  }
  if (code === "model_stream_failed") {
    const retry = record(failure.retry);
    const retried = typeof retry?.attempts === "number" && retry.attempts > 1;
    return {
      code,
      message: `The model call${model ? ` to ${model}` : ""} failed before it finished${retried ? " and its retry failed too" : ""}.`,
      ...(model ? { model } : {}),
    };
  }
  return { code, message: PUBLIC_FAILURE_MESSAGES[code] };
}

export function publicFailure(value: unknown): PublicFailure {
  const data = record(value) ?? {};
  const reason = typeof data.reason === "string" ? data.reason : "";
  const known = FAILURE_REASON_CODES[reason];
  if (known) return { code: known, message: PUBLIC_FAILURE_MESSAGES[known] };
  const message = typeof data.message === "string" ? data.message : reason;
  // Classification reads only the first line: the sentence the runtime
  // wrote, before any stack frame or cause chain.
  const firstLine = message.split(/\r?\n/, 1)[0].trim();
  // The runtime's typed fields come first; the text rules serve runtimes
  // that recorded none.
  const structured = structuredFailure(data, firstLine);
  if (structured) return structured;
  for (const rule of FAILURE_MESSAGE_RULES) {
    const match = firstLine.match(rule.pattern);
    if (!match) continue;
    if (rule.parameter === "model") {
      const model = validParameter(MODEL_ID, match[1]);
      if (model) {
        return {
          code: rule.code,
          message: `The model ${model} is not available to this agent.`,
          model,
        };
      }
    }
    if (rule.parameter === "tool") {
      const tool = validParameter(TOOL_ID, match[1]);
      if (tool) {
        return { code: rule.code, message: `Tool ${tool} failed.`, tool };
      }
    }
    return { code: rule.code, message: PUBLIC_FAILURE_MESSAGES[rule.code] };
  }
  return { code: "agent_failed", message: GENERIC_FAILURE_MESSAGE };
}

function publicEventData(
  type: string,
  value: unknown,
): Record<string, unknown> {
  if (type.startsWith("runtime.") && type !== "runtime.log") return {};
  if (type === "session.failed") {
    return {
      ...publicFailure(value),
      ...ownerExternalReference(record(value) ?? {}),
    };
  }
  if (type === "turn.failed") {
    return { ...publicFailure(value) };
  }
  const data = record(value) ?? {};
  return Object.fromEntries(
    Object.entries(data).filter(([key]) => !PRIVATE_EVENT_KEYS.has(key)),
  );
}

export function publicEvent(value: unknown): Record<string, unknown> {
  const event = record(value) ?? {};
  const type = typeof event.type === "string" ? event.type : "";
  return {
    id: event.id,
    seq: event.seq,
    timestamp: event.timestamp,
    sessionId: event.sessionId,
    turnId: event.turnId,
    type,
    data: publicEventData(type, event.data),
  };
}

const SESSION_CONNECT_ROUTE = /^\/sessions\/[^/]+\/connect$/;

// Live session stream. The browser opens a WebSocket against the edge; the
// edge opens the backend's client socket and relays frames, applying the same
// redaction as GET /events to every event. Only keepalive pings travel
// upstream: turns are admitted over REST, where the credit gate lives.
function relaySessionSocket(upstream: WebSocket): Response {
  const pair = new WebSocketPair();
  const [client, server] = Object.values(pair) as [WebSocket, WebSocket];
  server.accept();
  upstream.accept();

  const closeBoth = (code: number, reason: string) => {
    for (const socket of [server, upstream]) {
      try {
        socket.close(code, reason);
      } catch {
        // Already closed.
      }
    }
  };

  upstream.addEventListener("message", (message) => {
    let frame: Record<string, unknown> | null = null;
    try {
      frame = record(
        JSON.parse(
          typeof message.data === "string"
            ? message.data
            : new TextDecoder().decode(message.data as ArrayBuffer),
        ),
      );
    } catch {
      return;
    }
    if (!frame) return;
    if (frame.type === "event") {
      server.send(
        JSON.stringify({ type: "event", event: publicEvent(frame.event) }),
      );
    } else if (frame.type === "ready" || frame.type === "pong") {
      server.send(JSON.stringify(frame));
    } else if (frame.type === "error") {
      server.send(
        JSON.stringify({
          type: "error",
          code: typeof frame.code === "string" ? frame.code : "stream_error",
          message: "The session stream reported an error.",
        }),
      );
    }
  });
  upstream.addEventListener("close", (event) =>
    closeBoth(
      event.code === 1005 || event.code === 1006 ? 1000 : event.code,
      event.reason,
    ),
  );
  upstream.addEventListener("error", () => closeBoth(1011, "upstream error"));

  server.addEventListener("message", (message) => {
    if (typeof message.data !== "string") return;
    let frame: Record<string, unknown> | null = null;
    try {
      frame = record(JSON.parse(message.data));
    } catch {
      return;
    }
    if (frame?.type === "ping") upstream.send(JSON.stringify({ type: "ping" }));
  });
  server.addEventListener("close", (event) =>
    closeBoth(
      event.code === 1005 || event.code === 1006 ? 1000 : event.code,
      event.reason,
    ),
  );
  server.addEventListener("error", () => closeBoth(1011, "client error"));

  return new Response(null, { status: 101, webSocket: client });
}

function publicTemplateInspection(value: unknown): Record<string, unknown> {
  const inspection = record(value) ?? {};
  if (inspection.status === "preparing") {
    return {
      id: inspection.id,
      status: "preparing",
      repositoryUrl: inspection.repositoryUrl,
      retryAfterMs: inspection.retryAfterMs,
    };
  }
  const repository = record(inspection.repository) ?? {};
  const template = record(inspection.template) ?? {};
  const firstRun = record(template.firstRun);
  const requirements = record(inspection.requirements) ?? {};
  return {
    id: inspection.id,
    repository: {
      url: repository.url,
      fullName: repository.fullName,
      defaultBranch: repository.defaultBranch,
      commitSha: repository.commitSha,
    },
    template: {
      name: template.name,
      description: template.description,
      ...(template.documentation
        ? { documentation: template.documentation }
        : {}),
      ...(template.defaultProjectName
        ? { defaultProjectName: template.defaultProjectName }
        : {}),
      ...(firstRun
        ? { firstRun: { agent: firstRun.agent, prompt: firstRun.prompt } }
        : {}),
    },
    agents: Array.isArray(inspection.agents)
      ? inspection.agents.map((value) => {
          const agent = record(value) ?? {};
          return { id: agent.id, name: agent.name };
        })
      : [],
    requirements: {
      secrets: Array.isArray(requirements.secrets)
        ? requirements.secrets.map((value) => {
            const requirement = record(value) ?? {};
            return {
              name: requirement.name,
              description: requirement.description,
              documentation: requirement.documentation,
              ...(typeof requirement.required === "boolean"
                ? { required: requirement.required }
                : {}),
              agentId: requirement.agentId,
              allowedOrigins: strings(requirement.allowedOrigins),
            };
          })
        : [],
      runtimeVariables: Array.isArray(requirements.runtimeVariables)
        ? requirements.runtimeVariables.map((value) => {
            const requirement = record(value) ?? {};
            return {
              name: requirement.name,
              description: requirement.description,
              documentation: requirement.documentation,
              required: requirement.required === true,
              example: requirement.example,
              agentId: requirement.agentId,
            };
          })
        : [],
      connections: Array.isArray(requirements.connections)
        ? requirements.connections.map((value) => {
            const requirement = record(value) ?? {};
            return {
              id: requirement.id,
              description: requirement.description,
              provider: requirement.provider,
              permissions: strings(requirement.permissions),
            };
          })
        : [],
    },
    expiresAt: inspection.expiresAt,
  };
}

function publicTemplateInstallation(value: unknown): Record<string, unknown> {
  const installation = record(value) ?? {};
  const error = record(installation.error);
  return {
    id: installation.id,
    inspectionId: installation.inspectionId,
    projectId: installation.projectId,
    projectAgentId: installation.projectAgentId,
    projectUrl: installation.projectUrl,
    state: installation.state,
    ...(error ? { error: { stage: error.stage, message: error.message } } : {}),
  };
}

function publicSuccessBody(
  method: string,
  suffix: string,
  value: unknown,
  publicOrigin?: string,
  includeAdminMetadata = false,
): unknown {
  const body = record(value) ?? {};
  if (method === "GET" && suffix === "/account/runtime-profile") {
    return {
      customized: body.customized === true,
      displayName:
        typeof body.displayName === "string" && body.displayName.trim()
          ? body.displayName
          : "OpenComputer default",
    };
  }
  if (method === "GET" && suffix === "/agents") {
    return {
      agents: Array.isArray(body.agents) ? body.agents.map(publicAgent) : [],
    };
  }
  if (method === "GET" && suffix === "/projects") {
    return {
      projects: Array.isArray(body.projects)
        ? body.projects.map(publicProject)
        : [],
    };
  }
  if (method === "POST" && suffix === "/projects") {
    return publicProject(body);
  }
  if (
    method === "POST" &&
    /^\/projects\/[^/]+\/(archive|restore)$/.test(suffix)
  ) {
    return publicProject(body);
  }
  if (
    method === "POST" &&
    /^\/projects\/[^/]+\/database\/query$/.test(suffix)
  ) {
    const result = record(body.result) ?? {};
    const columns = strings(result.columns);
    return {
      environment: body.environment,
      result: {
        columns,
        rows: Array.isArray(result.rows)
          ? result.rows.map((value) => {
              const row = record(value) ?? {};
              return Object.fromEntries(
                columns.map((column) => {
                  const cell = row[column];
                  return [
                    column,
                    typeof cell === "string" || typeof cell === "number"
                      ? cell
                      : null,
                  ];
                }),
              );
            })
          : [],
        rowsAffected:
          typeof result.rowsAffected === "number" ? result.rowsAffected : 0,
        truncated: result.truncated === true,
      },
    };
  }
  if (
    /^\/github(?:\/connect)?$/.test(suffix) ||
    /^\/projects\/[^/]+\/github(?:\/(?:connect|attach|repositories))?$/.test(
      suffix,
    ) ||
    /^\/projects\/[^/]+\/deployment-source(?:\/(?:branches|repositories|deploy))?$/.test(
      suffix,
    )
  ) {
    return stripPrivateValues(body);
  }
  if (
    (method === "GET" || method === "PUT") &&
    /^\/projects\/[^/]+\/secrets(?:\/[^/]+)?$/.test(suffix)
  ) {
    return stripPrivateValues(body);
  }
  if (
    method === "GET" &&
    /^\/projects\/[^/]+\/service-connections$/.test(suffix)
  ) {
    return {
      attachments: Array.isArray(body.attachments)
        ? body.attachments.map(publicProjectServiceAttachment)
        : [],
    };
  }
  if (
    method === "POST" &&
    /^\/projects\/[^/]+\/service-connections$/.test(suffix)
  ) {
    return publicProjectServiceAttachment(body);
  }
  if (method === "GET" && /^\/projects\/[^/]+\/webhooks$/.test(suffix)) {
    return {
      webhooks: Array.isArray(body.webhooks)
        ? body.webhooks.map((value) => publicWebhook(value, publicOrigin))
        : [],
    };
  }
  if (
    (method === "POST" || method === "PATCH") &&
    /^\/projects\/[^/]+\/webhooks(?:\/[^/]+(?:\/rotate-token)?)?$/.test(suffix)
  ) {
    return { webhook: publicWebhook(body.webhook, publicOrigin) };
  }
  if (
    method === "GET" &&
    /^\/projects\/[^/]+\/webhooks\/[^/]+\/requests$/.test(suffix)
  ) {
    return {
      requests: Array.isArray(body.requests)
        ? body.requests.map(publicWebhookRequest)
        : [],
    };
  }
  if (method === "GET" && EVENT_SUBSCRIPTIONS_ROUTE.test(suffix)) {
    return {
      subscriptions: Array.isArray(body.subscriptions)
        ? body.subscriptions.map(publicEventSubscription)
        : [],
    };
  }
  if (
    (method === "POST" && EVENT_SUBSCRIPTIONS_ROUTE.test(suffix)) ||
    (method === "GET" && EVENT_SUBSCRIPTION_ROUTE.test(suffix))
  ) {
    return { subscription: publicEventSubscription(body.subscription) };
  }
  if (
    (method === "GET" || method === "PUT") &&
    /^\/projects\/[^/]+\/runtime-variables(?:\/[^/]+)?$/.test(suffix)
  ) {
    return Array.isArray(body.variables)
      ? { variables: body.variables.map(publicRuntimeVariable) }
      : publicRuntimeVariable(body);
  }
  if (method === "GET" && suffix === "/logs") {
    return stripPrivateValues(body);
  }
  if (method === "GET" && /^\/projects\/[^/]+$/.test(suffix)) {
    const project = publicProject(body.project);
    const templateSource = record(body.templateSource);
    return {
      project,
      ...(templateSource &&
      typeof templateSource.repositoryUrl === "string" &&
      typeof templateSource.commitSha === "string"
        ? {
            templateSource: {
              repositoryUrl: templateSource.repositoryUrl,
              commitSha: templateSource.commitSha,
              cloneReady: templateSource.cloneReady === true,
            },
          }
        : {}),
      sessions: stripPrivateValues(body.sessions ?? []),
      deployments: Array.isArray(body.deployments)
        ? body.deployments.map(publicDeployment)
        : [],
      connections: Array.isArray(body.connections)
        ? body.connections.map(publicConnection)
        : [],
      channels: Array.isArray(body.channels)
        ? body.channels.map(publicChannel)
        : [],
      schedules: stripPrivateValues(body.schedules ?? []),
      files: stripPrivateValues(body.files ?? []),
      schema: stripPrivateValues(body.schema ?? {}),
    };
  }
  if (method === "GET" && suffix === "/me") {
    return stripPrivateValues(body);
  }
  if (method === "POST" && suffix === "/template-inspections") {
    return publicTemplateInspection(body);
  }
  if (
    (method === "POST" && suffix === "/template-installations") ||
    (method === "GET" && /^\/template-installations\/[^/]+$/.test(suffix)) ||
    (method === "POST" &&
      /^\/template-installations\/[^/]+\/finalize$/.test(suffix))
  ) {
    return publicTemplateInstallation(body);
  }
  if (method === "GET" && suffix === "/model-access/connections") {
    return {
      data: Array.isArray(body.data)
        ? body.data.map((value) =>
            publicModelAccessConnection(value, includeAdminMetadata),
          )
        : [],
    };
  }
  if (method === "POST" && suffix === "/model-access/connections") {
    if (!body.connection) {
      return publicModelAccessConnection(body, includeAdminMetadata);
    }
    return {
      connection: publicModelAccessConnection(
        body.connection,
        includeAdminMetadata,
      ),
      status: body.status,
      authorize_url: body.authorize_url,
      expires_at: body.expires_at,
    };
  }
  if (
    (method === "POST" || method === "DELETE") &&
    /^\/model-access\/connections\/[^/]+(\/validate|\/complete)?$/.test(suffix)
  ) {
    return publicModelAccessConnection(body, includeAdminMetadata);
  }
  if (
    method === "GET" &&
    /^\/projects\/[^/]+\/model-access\/bindings$/.test(suffix)
  ) {
    return {
      data: Array.isArray(body.data)
        ? body.data.map(publicModelAccessBinding)
        : [],
    };
  }
  if (
    method === "PUT" &&
    /^\/projects\/[^/]+\/model-access\/bindings\/[^/]+\/[^/]+$/.test(suffix)
  ) {
    return publicModelAccessBinding(body);
  }
  if (method === "GET" && /^\/projects\/[^/]+\/model-routes$/.test(suffix)) {
    return {
      data: Array.isArray(body.data) ? body.data.map(publicModelRoute) : [],
    };
  }
  if (
    method === "PUT" &&
    /^\/projects\/[^/]+\/model-routes\/[^/]+$/.test(suffix)
  ) {
    return publicModelRoute(body);
  }
  if (method === "POST" && suffix === "/deployments") {
    return publicDeployment(body);
  }
  if (method === "POST" && suffix === "/benchmarks/warm-pool") {
    return stripPrivateValues(body);
  }
  if (method === "POST" && suffix === "/channel-connections/claim") {
    return {
      authorizationUrl: body.authorizationUrl,
      expiresAt: body.expiresAt,
      status: body.status,
    };
  }
  if (method === "GET" && suffix === "/deployments") {
    return {
      deployments: Array.isArray(body.deployments)
        ? body.deployments.map(publicDeployment)
        : [],
    };
  }
  if (method === "GET" && /^\/deployments\/[^/]+$/.test(suffix)) {
    return publicDeployment(body);
  }
  if (method === "GET" && suffix === "/connections") {
    return {
      connections: Array.isArray(body.connections)
        ? body.connections.map(publicConnection)
        : [],
    };
  }
  if (method === "GET" && suffix === "/channels") {
    return {
      channels: Array.isArray(body.connections)
        ? body.connections.map(publicChannel)
        : [],
    };
  }
  if (method === "GET" && suffix === "/outboxes") {
    return {
      agentId: body.agentId,
      environment: body.environment,
      deploymentId: body.deploymentId,
      outboxes: Array.isArray(body.outboxes)
        ? body.outboxes.map(publicOutbox)
        : [],
    };
  }
  if (method === "GET" && suffix === "/schedules") {
    return {
      schedules: Array.isArray(body.schedules)
        ? body.schedules.map(publicSchedule)
        : [],
    };
  }
  if (method === "GET" && suffix === "/schedule-runs") {
    return {
      runs: Array.isArray(body.runs) ? body.runs.map(publicScheduleRun) : [],
    };
  }
  if (method === "POST" && /^\/schedules\/[^/]+\/run$/.test(suffix)) {
    return { run: publicScheduleRun(body.run) };
  }
  if (method === "POST" && LINEAR_PROJECT_CONNECTIONS_ROUTE.test(suffix)) {
    return {
      connectionId: body.connectionId,
      webhookUrl: body.webhookUrl,
      createAppUrl: body.createAppUrl,
      connection: publicLinearConnection(body.connection),
    };
  }
  if (method === "GET" && LINEAR_PROJECT_CONNECTIONS_ROUTE.test(suffix)) {
    return {
      connections: Array.isArray(body.connections)
        ? body.connections.map(publicLinearConnection)
        : [],
    };
  }
  if (method === "PUT" && LINEAR_CREDENTIALS_ROUTE.test(suffix)) {
    return { connection: publicLinearConnection(body.connection) };
  }
  if (method === "POST" && LINEAR_AUTHORIZE_ROUTE.test(suffix)) {
    return { authorizeUrl: body.authorizeUrl, expiresAt: body.expiresAt };
  }
  if (method === "DELETE" && LINEAR_CONNECTION_ROUTE.test(suffix)) {
    return {
      connection: publicLinearConnection(body.connection),
      revoked: body.revoked === true,
    };
  }
  if (method === "POST" && suffix === "/channels/slack/connections") {
    return {
      connection: publicChannel(body.connection),
      manifest: stripPrivateValues(body.manifest),
      createUrl: body.createUrl,
      steps: strings(body.steps),
    };
  }
  if (
    (method === "PUT" || method === "DELETE") &&
    /^\/channels\/slack\/connections\/[^/]+$/.test(suffix)
  ) {
    return publicChannel(body);
  }
  if (
    (method === "POST" && SLACK_SETUPS_ROUTE.test(suffix)) ||
    (method === "GET" && SLACK_SETUP_ROUTE.test(suffix)) ||
    (method === "POST" && SLACK_SETUP_CANCEL_ROUTE.test(suffix))
  ) {
    return { setup: publicSlackSetup(body.setup) };
  }
  if (method === "GET" && SLACK_SETUPS_ROUTE.test(suffix)) {
    // Lookup by target: the latest resumable setup, or null.
    return { setup: record(body.setup) ? publicSlackSetup(body.setup) : null };
  }
  if (method === "POST" && SLACK_SETUP_AUTHORIZE_ROUTE.test(suffix)) {
    return {
      authorizationUrl: body.authorizationUrl,
      expiresAt: body.expiresAt,
    };
  }
  if (suffix.startsWith("/channels/slack/setups")) {
    // Every setup response is shaped explicitly above; nothing under this
    // prefix may fall through to the generic key filter.
    throw new Error("Unsupported managed agents response");
  }
  if (
    (method === "GET" && suffix.startsWith("/connections")) ||
    (method === "POST" && suffix.startsWith("/connections")) ||
    (method === "PUT" && suffix.startsWith("/connections")) ||
    (method === "DELETE" && suffix.startsWith("/connections")) ||
    (method === "GET" && suffix.startsWith("/channels")) ||
    (method === "POST" && suffix.startsWith("/channels")) ||
    (method === "PUT" && suffix.startsWith("/channels")) ||
    (method === "DELETE" && suffix.startsWith("/channels"))
  ) {
    return stripPrivateValues(body);
  }
  if (method === "POST" && suffix === "/sessions") {
    const session = record(body.session) ?? {};
    return {
      session: {
        id: session.id,
        executionMode: session.executionMode,
        status: session.status,
        createdAt: session.createdAt,
        ...ownerExternalReference(session),
      },
      deployment: body.deployment
        ? publicDeployment(body.deployment)
        : undefined,
    };
  }
  if (method === "GET" && /^\/sessions\/[^/]+\/events$/.test(suffix)) {
    return {
      events: Array.isArray(body.events) ? body.events.map(publicEvent) : [],
    };
  }
  if (method === "POST" && /\/turns$/.test(suffix)) {
    // An input held behind an open question has no turn yet: its receipt
    // names the question instead (status "held", or "discarded" after a stop).
    return {
      ...(typeof body.turnId === "string" ? { turnId: body.turnId } : {}),
      status: body.status,
      duplicate: body.duplicate,
      ...(typeof body.questionId === "string" ? { questionId: body.questionId } : {}),
      ...(typeof body.heldId === "string" ? { heldId: body.heldId } : {}),
    };
  }
  if (method === "GET" && suffix === "/billing/sessions") {
    return stripPrivateValues(body);
  }
  if (method === "POST" && /\/suspend$/.test(suffix)) {
    return {
      id: body.id,
      status: body.status,
      updatedAt: body.updatedAt,
    };
  }
  if (method === "GET" && suffix === "/sessions") {
    return {
      sessions: Array.isArray(body.sessions)
        ? body.sessions.map(publicSessionSummary)
        : [],
      nextCursor: typeof body.nextCursor === "string" ? body.nextCursor : null,
    };
  }
  if (
    (method === "GET" && /^\/sessions\/[^/]+$/.test(suffix)) ||
    (method === "PATCH" && /^\/sessions\/[^/]+\/labels$/.test(suffix)) ||
    (method === "POST" &&
      /^\/sessions\/[^/]+\/(resume|end|terminate|interrupt)$/.test(suffix)) ||
    (method === "POST" &&
      /^\/sessions\/[^/]+\/questions\/[^/]+\/dismiss$/.test(suffix))
  ) {
    return publicSessionSnapshot(body);
  }
  if (
    method === "GET" &&
    /^\/sessions\/[^/]+\/workspace\/files$/.test(suffix)
  ) {
    return {
      files: Array.isArray(body.files)
        ? body.files.map(publicWorkspaceFile)
        : [],
      nextCursor: typeof body.nextCursor === "string" ? body.nextCursor : null,
    };
  }
  if (
    (method === "GET" || method === "POST") &&
    /^\/sessions\/[^/]+\/workspace\/download$/.test(suffix)
  ) {
    const url = typeof body.url === "string" ? new URL(body.url) : null;
    if (
      !url ||
      url.protocol !== "https:" ||
      url.username ||
      url.password ||
      typeof body.path !== "string" ||
      typeof body.size !== "number" ||
      typeof body.expiresAt !== "string"
    ) {
      throw new Error("Invalid workspace download authorization");
    }
    return {
      path: body.path,
      size: body.size,
      etag: typeof body.etag === "string" ? body.etag : null,
      versionId: typeof body.versionId === "string" ? body.versionId : null,
      lastModified:
        typeof body.lastModified === "string" ? body.lastModified : null,
      mediaType:
        typeof body.mediaType === "string"
          ? body.mediaType
          : "application/octet-stream",
      url: url.toString(),
      expiresAt: body.expiresAt,
    };
  }
  if (
    method === "GET" &&
    /^\/sessions\/[^/]+\/workspace\/exports$/.test(suffix)
  ) {
    return {
      artifacts: Array.isArray(body.artifacts)
        ? body.artifacts.map(publicWorkspaceArtifact)
        : [],
      exports: Array.isArray(body.exports)
        ? body.exports.map(publicWorkspaceExport)
        : [],
    };
  }
  if (
    (method === "POST" &&
      /^\/sessions\/[^/]+\/workspace\/exports$/.test(suffix)) ||
    (method === "GET" &&
      /^\/sessions\/[^/]+\/workspace\/exports\/[^/]+$/.test(suffix))
  ) {
    return {
      ...(body.export !== undefined
        ? { export: publicWorkspaceExport(body.export) }
        : {}),
      artifact: body.artifact ? publicWorkspaceArtifact(body.artifact) : null,
    };
  }
  if (
    method === "GET" &&
    /^\/sessions\/[^/]+\/workspace\/exports\/[^/]+\/download$/.test(suffix)
  ) {
    const url = typeof body.url === "string" ? new URL(body.url) : null;
    if (
      !url ||
      url.protocol !== "https:" ||
      url.username ||
      url.password ||
      typeof body.expiresAt !== "string"
    ) {
      throw new Error("Invalid workspace download authorization");
    }
    return { url: url.toString(), expiresAt: body.expiresAt };
  }
  if (method === "POST" && AUTOMATIONS_REPOSITORY_CREDENTIAL_ROUTE.test(suffix)) {
    // A one-hour push credential for the organization's automations
    // repository (work 067): the remote carries no credential of its own.
    const remote =
      typeof body.remoteUrl === "string" ? new URL(body.remoteUrl) : null;
    if (
      !remote ||
      remote.protocol !== "https:" ||
      remote.username ||
      remote.password ||
      typeof body.username !== "string" ||
      typeof body.password !== "string" ||
      typeof body.expiresAt !== "string"
    ) {
      throw new Error("Invalid automations repository credential");
    }
    return {
      remoteUrl: remote.toString(),
      username: body.username,
      password: body.password,
      expiresAt: body.expiresAt,
    };
  }
  throw new Error("Unsupported managed agents response");
}

const AUTOMATIONS_REPOSITORY_CREDENTIAL_ROUTE =
  /^\/automations\/repository\/credentials$/;

function publicWorkspaceFile(value: unknown): Record<string, unknown> {
  const file = record(value) ?? {};
  return {
    path: file.path,
    size: file.size,
    lastModified: file.lastModified ?? null,
    etag: file.etag ?? null,
  };
}

/** The manifest a caller verifies against: id, path, size, sha256 and the
 * retained object's etags. Where the provider retains it (bucket and object
 * key) is not part of the public contract. */
function publicWorkspaceArtifact(value: unknown): Record<string, unknown> {
  const artifact = record(value) ?? {};
  const receipt = record(artifact.receipt) ?? {};
  const retention = record(artifact.retention);
  return {
    id: artifact.id,
    exportId: artifact.exportId ?? null,
    sessionId: artifact.sessionId,
    projectId: artifact.projectId ?? null,
    agentId: artifact.agentId ?? null,
    deploymentId: artifact.deploymentId ?? null,
    environment: artifact.environment ?? null,
    path: artifact.path,
    size: artifact.size,
    sha256: artifact.sha256,
    mediaType: artifact.mediaType ?? "application/octet-stream",
    snapshotId:
      artifact.snapshotId ??
      receipt.sourceVersionId ??
      receipt.sourceEtag ??
      null,
    receipt: {
      etag: receipt.etag ?? null,
      sourceEtag: receipt.sourceEtag ?? null,
      sourceVersionId: receipt.sourceVersionId ?? null,
    },
    retention: retention
      ? { policy: retention.policy, expiresAt: retention.expiresAt ?? null }
      : { policy: "until_deleted", expiresAt: null },
    exportedAt: artifact.exportedAt,
  };
}

/** One export attempt: its state, what the caller expected, the artifact it
 * produced or the error it ended in. The request digest is internal. */
function publicWorkspaceExport(value: unknown): Record<string, unknown> {
  const exported = record(value) ?? {};
  const error = record(exported.error);
  const expected = record(exported.expected);
  return {
    id: exported.id,
    sessionId: exported.sessionId,
    projectId: exported.projectId ?? null,
    agentId: exported.agentId ?? null,
    deploymentId: exported.deploymentId ?? null,
    environment: exported.environment ?? null,
    path: exported.path,
    state: exported.state,
    idempotencyKey: exported.idempotencyKey ?? null,
    expected: expected
      ? {
          ...(expected.bytes !== undefined ? { bytes: expected.bytes } : {}),
          ...(expected.sha256 !== undefined ? { sha256: expected.sha256 } : {}),
          ...(expected.mediaType !== undefined
            ? { mediaType: expected.mediaType }
            : {}),
        }
      : null,
    artifactId: exported.artifactId ?? null,
    error: error
      ? {
          code:
            typeof error.code === "string" &&
            Object.hasOwn(WORKSPACE_EXPORT_ERROR_MESSAGES, error.code)
              ? error.code
              : "workspace_export_failed",
          message:
            (typeof error.code === "string" &&
              WORKSPACE_EXPORT_ERROR_MESSAGES[error.code]) ||
            WORKSPACE_EXPORT_ERROR_MESSAGES.workspace_export_failed,
          retrySafe: error.retrySafe === true,
        }
      : null,
    createdAt: exported.createdAt,
    completedAt: exported.completedAt ?? null,
  };
}

const WORKSPACE_ARTIFACT_CONTENT_ROUTE =
  /^\/sessions\/[^/]+\/workspace\/exports\/[^/]+\/content$/;

async function publicSuccessResponse(
  upstream: Response,
  method: string,
  suffix: string,
  publicOrigin?: string,
  includeAdminMetadata = false,
): Promise<Response> {
  const value: unknown = await upstream.json();
  const headers = new Headers({ "content-type": "application/json" });
  const cacheControl = upstream.headers.get("cache-control");
  if (cacheControl) headers.set("cache-control", cacheControl);
  if (
    suffix.includes("/webhooks") ||
    suffix.includes("/event-subscriptions") ||
    suffix.startsWith("/channels/slack/setups") ||
    isLinearRouteSuffix(suffix) ||
    AUTOMATIONS_REPOSITORY_CREDENTIAL_ROUTE.test(suffix)
  ) {
    headers.set("cache-control", "no-store");
  }
  return new Response(
    JSON.stringify(
      publicSuccessBody(
        method,
        suffix,
        value,
        publicOrigin,
        includeAdminMetadata,
      ),
    ),
    {
      status: upstream.status,
      headers,
    },
  );
}

function invalidDeploymentResponse(message: string): Response {
  return Response.json(
    { error: { code: "invalid_deployment", message } },
    { status: 400 },
  );
}

async function sha256Hex(value: Uint8Array): Promise<string> {
  const digest = await crypto.subtle.digest("SHA-256", value);
  return Array.from(new Uint8Array(digest))
    .map((byte) => byte.toString(16).padStart(2, "0"))
    .join("");
}

function deploymentModelsFromArtifact(
  source: string,
): Array<{ provider: string; model: string }> | null {
  let bundle: unknown;
  try {
    bundle = JSON.parse(source);
  } catch {
    return null;
  }
  const files = record(bundle)?.files;
  if (!Array.isArray(files)) return null;
  const manifestFile = files.find(
    (value) => record(value)?.path === ".opencomputer/reactive.json",
  );
  if (!manifestFile) return [];
  const content = record(manifestFile)?.content;
  if (typeof content !== "string") return null;
  let manifest: unknown;
  try {
    manifest = JSON.parse(atob(content));
  } catch {
    return null;
  }
  const models = record(manifest)?.models;
  if (!Array.isArray(models) || models.length > 100) return null;
  const result: Array<{ provider: string; model: string }> = [];
  for (const value of models) {
    const model = record(value);
    if (
      !model ||
      typeof model.provider !== "string" ||
      typeof model.model !== "string" ||
      !model.provider ||
      !model.model
    ) {
      return null;
    }
    if (
      !result.some(
        (candidate) =>
          candidate.provider === model.provider &&
          candidate.model === model.model,
      )
    ) {
      result.push({ provider: model.provider, model: model.model });
    }
  }
  return result.sort((left, right) =>
    `${left.provider}/${left.model}`.localeCompare(
      `${right.provider}/${right.model}`,
    ),
  );
}

async function deploySourceAgent(
  request: Request,
  base: string,
  upstreamHeaders: Headers,
): Promise<Response> {
  const body = record(await request.json().catch(() => null));
  const source = record(body?.source);
  if (
    !body ||
    typeof body.agentId !== "string" ||
    typeof body.alias !== "string" ||
    !source ||
    typeof source.digest !== "string" ||
    typeof source.size !== "number" ||
    typeof source.contentType !== "string" ||
    typeof source.body !== "string"
  ) {
    return invalidDeploymentResponse("The agent deployment was invalid.");
  }
  const bytes = new TextEncoder().encode(source.body);
  if (
    bytes.byteLength !== source.size ||
    bytes.byteLength > MAX_AGENT_SOURCE_BYTES ||
    (await sha256Hex(bytes)) !== source.digest
  ) {
    return invalidDeploymentResponse(
      "The agent source size or digest did not match.",
    );
  }
  const models = deploymentModelsFromArtifact(source.body);
  if (!models) {
    return invalidDeploymentResponse(
      "The agent artifact contains an invalid reactive model registry.",
    );
  }

  const uploadHeaders = new Headers(upstreamHeaders);
  uploadHeaders.set("content-type", "application/json");
  const uploadResponse = await fetch(`${base}/v1/deployment-uploads`, {
    method: "POST",
    headers: uploadHeaders,
    body: JSON.stringify({
      agentId: body.agentId,
      digest: source.digest,
      size: source.size,
      contentType: source.contentType,
    }),
    redirect: "manual",
  });
  if (!uploadResponse.ok) return publicErrorResponse(uploadResponse);
  const upload = record(await uploadResponse.json().catch(() => null));
  const artifact = record(upload?.artifact);
  const uploadURL =
    typeof upload?.uploadUrl === "string" ? new URL(upload.uploadUrl) : null;
  if (
    !uploadURL ||
    uploadURL.protocol !== "https:" ||
    upload?.method !== "PUT" ||
    !artifact
  ) {
    return Response.json(
      { error: "managed agents service is unavailable" },
      { status: 502 },
    );
  }
  const stored = await fetch(uploadURL, {
    method: "PUT",
    headers: { "content-type": source.contentType },
    body: bytes,
    redirect: "manual",
  });
  if (!stored.ok) {
    return Response.json(
      { error: "managed agents service is unavailable" },
      { status: 502 },
    );
  }

  const deploymentResponse = await fetch(`${base}/v1/deployments`, {
    method: "POST",
    headers: uploadHeaders,
    body: JSON.stringify({
      agentId: body.agentId,
      name:
        typeof body.name === "string" && body.name.trim()
          ? body.name.trim()
          : body.agentId,
      alias: body.alias,
      channels: strings(body.channels),
      connections: strings(body.connections),
      httpConnections: Array.isArray(body.httpConnections)
        ? body.httpConnections
        : [],
      githubConnections: Array.isArray(body.githubConnections)
        ? body.githubConnections
        : [],
      memory: Array.isArray(body.memory) ? body.memory : [],
      models,
      // Validated by the service, which answers 400 unsupported_region (work 057).
      ...(body.region !== undefined ? { region: body.region } : {}),
      // Validated by the service, which answers 400 invalid_egress (work 057).
      ...(body.egress !== undefined ? { egress: body.egress } : {}),
      // Validated by the service, which answers 400 invalid_fixed_ips (work 073).
      ...(body.fixedIps !== undefined ? { fixedIps: body.fixedIps } : {}),
      ...(body.projectDeployment && typeof body.projectDeployment === "object"
        ? { projectDeployment: body.projectDeployment }
        : {}),
      artifact,
    }),
    redirect: "manual",
  });
  if (!deploymentResponse.ok) {
    return publicErrorResponse(deploymentResponse);
  }
  return publicSuccessResponse(deploymentResponse, "POST", "/deployments");
}

// Routes that create, attach, grant or revoke a credential (work 080). A
// computer key may read and use connections (`POST /connections/:service/fetch`)
// but never change who can reach what: a thread can ask, only a person grants.
// Reads stay open; so do the automation routes the computer needs (work 067).
const COMPUTER_FETCH_ROUTE = /^\/connections\/[^/]+\/fetch$/;

export function isGrantRoute(method: string, suffix: string): boolean {
  if (method === "GET" || method === "HEAD") return false;
  if (/^\/connections(?:\/|$)/.test(suffix)) {
    return !(method === "POST" && COMPUTER_FETCH_ROUTE.test(suffix));
  }
  return (
    /^\/projects\/[^/]+\/service-connections$/.test(suffix) ||
    /^\/(?:projects\/[^/]+\/)?model-access(?:\/|$)/.test(suffix) ||
    isLinearRouteSuffix(suffix) ||
    /^\/channels(?:\/|$)/.test(suffix) ||
    suffix === "/channel-connections/claim" ||
    suffix === "/github/connect" ||
    /^\/projects\/[^/]+\/github(?:\/(?:connect|attach))?$/.test(suffix)
  );
}

// The route families the proxy dispatches to as a unit (see route_family.ts).
// Only the organization's computer so far: its dashboard surface (work 052)
// on the dashboard mount and its session API (work 084) on the API mount; the
// other surfaces keep their branches below until each is ported.
const ROUTE_FAMILIES: ReadonlyArray<RouteFamily> = [
  computerFamily,
  computerApiFamily,
];

function routeFamilyFor(
  suffix: string,
  publicPrefix: string,
): RouteFamily | undefined {
  const dashboard = publicPrefix === DASHBOARD_MANAGED_AGENTS_PREFIX;
  return (
    ROUTE_FAMILIES.find(
      (family) =>
        family.owns(suffix) &&
        (dashboard ? !family.apiOnly : !family.dashboardOnly),
    ) ?? ROUTE_FAMILIES.find((family) => family.owns(suffix))
  );
}

function isAllowedManagedAgentsRoute(
  method: string,
  suffix: string,
  publicPrefix: string,
): boolean {
  const family = routeFamilyFor(suffix, publicPrefix);
  if (family) return family.allows(method, suffix);
  if (method === "GET" && suffix === "/account/runtime-profile") return true;
  if (method === "POST" && suffix === "/template-inspections") return true;
  if (method === "POST" && suffix === "/template-installations") return true;
  if (method === "GET" && /^\/template-installations\/[^/]+$/.test(suffix)) {
    return true;
  }
  if (
    method === "POST" &&
    /^\/template-installations\/[^/]+\/finalize$/.test(suffix)
  ) {
    return true;
  }
  if (method === "GET" && suffix === "/agents") return true;
  if (method === "GET" && suffix === "/me") return true;
  if ((method === "GET" || method === "POST") && suffix === "/projects") {
    return true;
  }
  if (method === "GET" && suffix === "/github") return true;
  if (method === "POST" && suffix === "/github/connect") return true;
  if (method === "GET" && /^\/projects\/[^/]+$/.test(suffix)) return true;
  if (
    method === "POST" &&
    /^\/projects\/[^/]+\/(archive|restore)$/.test(suffix)
  ) {
    return true;
  }
  if (
    method === "POST" &&
    /^\/projects\/[^/]+\/database\/query$/.test(suffix)
  ) {
    return true;
  }
  if (method === "GET" && /^\/projects\/[^/]+\/source-archive$/.test(suffix)) {
    return true;
  }
  if (method === "POST" && AUTOMATIONS_REPOSITORY_CREDENTIAL_ROUTE.test(suffix)) {
    return true;
  }
  if (
    (method === "GET" || method === "DELETE") &&
    /^\/projects\/[^/]+\/github$/.test(suffix)
  ) {
    return true;
  }
  if (
    method === "GET" &&
    /^\/projects\/[^/]+\/github\/repositories$/.test(suffix)
  ) {
    return true;
  }
  if (
    method === "POST" &&
    /^\/projects\/[^/]+\/github\/(connect|attach)$/.test(suffix)
  ) {
    return true;
  }
  if (
    (method === "GET" || method === "PUT" || method === "DELETE") &&
    /^\/projects\/[^/]+\/deployment-source$/.test(suffix)
  ) {
    return true;
  }
  if (
    method === "GET" &&
    /^\/projects\/[^/]+\/deployment-source\/(branches|repositories)$/.test(
      suffix,
    )
  ) {
    return true;
  }
  if (
    method === "POST" &&
    /^\/projects\/[^/]+\/deployment-source\/deploy$/.test(suffix)
  ) {
    return true;
  }
  if (
    method === "DELETE" &&
    /^\/projects\/[^/]+\/deployment-source\/previews\/[^/]+$/.test(suffix)
  ) {
    return true;
  }
  if (
    (method === "GET" || method === "PUT" || method === "DELETE") &&
    /^\/projects\/[^/]+\/secrets(?:\/[^/]+)?$/.test(suffix)
  ) {
    return true;
  }
  if (
    (method === "GET" || method === "POST" || method === "DELETE") &&
    /^\/projects\/[^/]+\/service-connections$/.test(suffix)
  ) {
    return true;
  }
  if (
    (method === "GET" || method === "PUT" || method === "DELETE") &&
    /^\/projects\/[^/]+\/model-routes(?:\/[^/]+)?$/.test(suffix)
  ) {
    return true;
  }
  if (
    (method === "GET" || method === "POST") &&
    /^\/projects\/[^/]+\/webhooks$/.test(suffix)
  ) {
    return true;
  }
  if (
    (method === "PATCH" || method === "DELETE") &&
    /^\/projects\/[^/]+\/webhooks\/[^/]+$/.test(suffix)
  ) {
    return true;
  }
  if (
    (method === "POST" &&
      /^\/projects\/[^/]+\/webhooks\/[^/]+\/rotate-token$/.test(suffix)) ||
    (method === "GET" &&
      /^\/projects\/[^/]+\/webhooks\/[^/]+\/requests$/.test(suffix))
  ) {
    return true;
  }
  if (isMemoryRoute(method, suffix)) return true;
  if (isEventSubscriptionRoute(method, suffix)) return true;
  if (
    (method === "GET" || method === "PUT" || method === "DELETE") &&
    /^\/projects\/[^/]+\/runtime-variables(?:\/[^/]+)?$/.test(suffix)
  ) {
    return true;
  }
  if (method === "GET" && suffix === "/logs") return true;
  if (method === "POST" && suffix === "/deployments") return true;
  if (method === "POST" && suffix === "/benchmarks/warm-pool") return true;
  if (method === "POST" && suffix === "/channel-connections/claim") {
    return true;
  }
  if (method === "GET" && suffix === "/deployments") return true;
  if (method === "GET" && /^\/deployments\/[^/]+$/.test(suffix)) return true;
  if (method === "GET" && suffix === "/outboxes") return true;
  if (method === "GET" && suffix === "/schedules") return true;
  if (method === "GET" && suffix === "/schedule-runs") return true;
  if (method === "POST" && /^\/schedules\/[^/]+\/run$/.test(suffix))
    return true;
  // Linear agent connections: only the contract's routes.
  if (isLinearRouteSuffix(suffix)) return isLinearConnectionRoute(method, suffix);
  // Automated Slack setup: only the contract's routes, before the /channels
  // catch-all below can admit anything else under the prefix.
  if (suffix.startsWith("/channels/slack/setups")) {
    return isSlackSetupRoute(method, suffix);
  }
  if (
    (method === "GET" &&
      (/^\/connections(?:\/.*)?$/.test(suffix) ||
        /^\/channels(?:\/.*)?$/.test(suffix))) ||
    ((method === "POST" || method === "PUT" || method === "DELETE") &&
      (/^\/connections(?:\/.*)?$/.test(suffix) ||
        /^\/channels(?:\/.*)?$/.test(suffix)))
  )
    return true;
  // Model access (work 011): org-owned Codex subscription connections and their
  // project-environment bindings.
  if (
    (method === "GET" || method === "POST") &&
    suffix === "/model-access/connections"
  ) {
    return true;
  }
  if (
    (method === "POST" || method === "DELETE") &&
    /^\/model-access\/connections\/[^/]+(\/validate|\/complete)?$/.test(suffix)
  ) {
    return true;
  }
  if (
    (method === "GET" || method === "PUT" || method === "DELETE") &&
    /^\/projects\/[^/]+\/model-access\/bindings(?:\/[^/]+\/[^/]+)?$/.test(
      suffix,
    )
  ) {
    return true;
  }
  if (suffix.startsWith("/openrouter/")) return true;
  if (method === "POST" && suffix === "/sessions") return true;
  if (method === "GET" && suffix === "/sessions") return true;
  if (method === "GET" && suffix === "/billing/sessions") return true;
  if (method === "GET" && /^\/sessions\/[^/]+$/.test(suffix)) return true;
  if (method === "PATCH" && /^\/sessions\/[^/]+\/labels$/.test(suffix)) {
    return true;
  }
  if (method === "GET" && /^\/sessions\/[^/]+\/events$/.test(suffix)) {
    return true;
  }
  if (method === "GET" && SESSION_CONNECT_ROUTE.test(suffix)) return true;
  if (
    method === "GET" &&
    /^\/sessions\/[^/]+\/workspace\/files$/.test(suffix)
  ) {
    return true;
  }
  if (
    (method === "GET" || method === "POST") &&
    /^\/sessions\/[^/]+\/workspace\/download$/.test(suffix)
  ) {
    return true;
  }
  if (
    (method === "GET" || method === "POST") &&
    /^\/sessions\/[^/]+\/workspace\/exports$/.test(suffix)
  ) {
    return true;
  }
  if (
    method === "GET" &&
    /^\/sessions\/[^/]+\/workspace\/exports\/[^/]+(?:\/(?:content|download))?$/.test(
      suffix,
    )
  ) {
    return true;
  }
  // Closes the open question without an answer.
  if (
    method === "POST" &&
    /^\/sessions\/[^/]+\/questions\/[^/]+\/dismiss$/.test(suffix)
  ) {
    return true;
  }
  return (
    method === "POST" &&
    /^\/sessions\/[^/]+\/(turns|suspend|resume|end|terminate|interrupt)$/.test(
      suffix,
    )
  );
}

export async function handleManagedGitHubCallback(
  request: Request,
  env: ManagedAgentsEnv,
): Promise<Response> {
  if (request.method !== "GET") {
    return new Response("Method not allowed", { status: 405 });
  }
  const requestURL = new URL(request.url);
  const base = (
    env.MANAGED_AGENTS_API_URL ?? DEFAULT_MANAGED_AGENTS_API_URL
  ).replace(/\/+$/, "");
  const target = new URL(`${base}/v1/github/callback${requestURL.search}`);
  if (target.protocol !== "https:" && target.hostname !== "localhost") {
    return new Response("GitHub connection is unavailable", { status: 503 });
  }
  try {
    const upstream = await fetch(target, { redirect: "manual" });
    const headers = new Headers();
    for (const name of [
      "content-type",
      "cache-control",
      "content-security-policy",
      "referrer-policy",
      "x-content-type-options",
      "x-frame-options",
    ]) {
      const value = upstream.headers.get(name);
      if (value) headers.set(name, value);
    }
    headers.set("cache-control", "no-store");
    return new Response(upstream.body, {
      status: upstream.status,
      statusText: upstream.statusText,
      headers,
    });
  } catch {
    return new Response("GitHub connection is temporarily unavailable", {
      status: 502,
      headers: { "content-type": "text/plain; charset=utf-8" },
    });
  }
}

/**
 * GitHub App webhook deliveries (push and pull_request) for repositories
 * connected as a project's deployment source. The raw body and GitHub's
 * signature headers are forwarded untouched; the backend verifies the HMAC
 * against the webhook secret before acting, so nothing is trusted here.
 */
export async function handleManagedGitHubWebhook(
  request: Request,
  env: ManagedAgentsEnv,
): Promise<Response> {
  if (request.method !== "POST") {
    return new Response("Method not allowed", { status: 405 });
  }
  const base = (
    env.MANAGED_AGENTS_API_URL ?? DEFAULT_MANAGED_AGENTS_API_URL
  ).replace(/\/+$/, "");
  const target = new URL(`${base}/v1/github/webhooks`);
  if (target.protocol !== "https:" && target.hostname !== "localhost") {
    return new Response("GitHub webhooks are unavailable", { status: 503 });
  }
  const headers = new Headers();
  for (const name of [
    "content-type",
    "x-github-event",
    "x-github-delivery",
    "x-github-hook-id",
    "x-github-hook-installation-target-id",
    "x-github-hook-installation-target-type",
    "x-hub-signature-256",
  ]) {
    const value = request.headers.get(name);
    if (value) headers.set(name, value);
  }
  try {
    const upstream = await fetch(target, {
      method: "POST",
      headers,
      body: await request.arrayBuffer(),
    });
    return new Response(upstream.body, {
      status: upstream.status,
      headers: {
        "content-type":
          upstream.headers.get("content-type") ?? "application/json",
        "cache-control": "no-store",
      },
    });
  } catch {
    return new Response(
      JSON.stringify({ error: { code: "github_webhook_unavailable" } }),
      {
        status: 502,
        headers: { "content-type": "application/json" },
      },
    );
  }
}

/**
 * A provider's OAuth redirect, forwarded to the backend's callback. The exact
 * public URL is registered with the provider, so the query goes through
 * verbatim and is never reinterpreted. The backend resolves the single-use
 * state and answers with a redirect into the project's Connections tab, or
 * a no-store HTML page for a malformed state; both pass through unchanged.
 */
async function forwardProviderCallback(
  request: Request,
  env: ManagedAgentsEnv,
  upstreamPath: string,
  provider: string,
): Promise<Response> {
  if (request.method !== "GET") {
    return new Response("Method not allowed", { status: 405 });
  }
  const requestURL = new URL(request.url);
  const base = (
    env.MANAGED_AGENTS_API_URL ?? DEFAULT_MANAGED_AGENTS_API_URL
  ).replace(/\/+$/, "");
  const target = new URL(`${base}${upstreamPath}${requestURL.search}`);
  if (target.protocol !== "https:" && target.hostname !== "localhost") {
    return new Response(`${provider} connection is unavailable`, {
      status: 503,
    });
  }
  try {
    const upstream = await fetch(target, { redirect: "manual" });
    const headers = new Headers();
    for (const name of [
      "content-type",
      "cache-control",
      "content-security-policy",
      "referrer-policy",
      "x-content-type-options",
      "x-frame-options",
    ]) {
      const value = upstream.headers.get(name);
      if (value) headers.set(name, value);
    }
    if (upstream.status >= 300 && upstream.status < 400) {
      const location = upstream.headers.get("location");
      if (location) headers.set("location", location);
    }
    headers.set("cache-control", "no-store");
    return new Response(upstream.body, {
      status: upstream.status,
      statusText: upstream.statusText,
      headers,
    });
  } catch {
    return new Response(`${provider} connection is temporarily unavailable`, {
      status: 502,
      headers: { "content-type": "text/plain; charset=utf-8" },
    });
  }
}

/** Slack's OAuth redirect for apps created by the automated setup. */
export async function handleManagedSlackCallback(
  request: Request,
  env: ManagedAgentsEnv,
): Promise<Response> {
  return forwardProviderCallback(
    request,
    env,
    "/v1/channels/slack/oauth/callback",
    "Slack",
  );
}

/**
 * Linear's OAuth redirect for a project's Linear agent connection. The
 * backend builds this URL into every authorize link (its default is the
 * Slack callback's sibling, `/api/managed-agents/linear/callback`).
 */
export async function handleManagedLinearCallback(
  request: Request,
  env: ManagedAgentsEnv,
): Promise<Response> {
  return forwardProviderCallback(
    request,
    env,
    "/v1/linear/oauth/callback",
    "Linear",
  );
}

/**
 * Slack's OAuth redirect for the organization-level OpenComputer Slack app
 * (work 052). The backend binds the workspace to the organization named by
 * its single-use state and redirects to `/computer?slack=connected` or
 * `/computer?slack=error&reason=<code>`; the redirect passes through as is.
 */
export async function handleComputerSlackCallback(
  request: Request,
  env: ManagedAgentsEnv,
): Promise<Response> {
  return forwardProviderCallback(
    request,
    env,
    "/v1/computer/slack/callback",
    "Slack",
  );
}

const COMPUTER_SLACK_WEBHOOK_PATHS = {
  events: "/v1/webhooks/computer/slack/events",
  interactivity: "/v1/webhooks/computer/slack/interactivity",
} as const;

/**
 * Slack Events API and interactivity deliveries for the organization-level
 * Slack app. Slack signs the exact body bytes with the request timestamp, and
 * the backend verifies that signature, so the body is forwarded byte for byte
 * with Slack's signature, timestamp and retry headers and nothing is trusted
 * here. The backend's answer (a URL verification challenge, an interactivity
 * response action, or an empty acknowledgement) goes back to Slack unchanged.
 */
export async function handleComputerSlackWebhook(
  request: Request,
  env: ManagedAgentsEnv,
  kind: keyof typeof COMPUTER_SLACK_WEBHOOK_PATHS,
): Promise<Response> {
  if (request.method !== "POST") {
    return new Response("Method not allowed", { status: 405 });
  }
  const base = (
    env.MANAGED_AGENTS_API_URL ?? DEFAULT_MANAGED_AGENTS_API_URL
  ).replace(/\/+$/, "");
  const target = new URL(`${base}${COMPUTER_SLACK_WEBHOOK_PATHS[kind]}`);
  if (target.protocol !== "https:" && target.hostname !== "localhost") {
    return new Response("Slack events are unavailable", { status: 503 });
  }
  const headers = new Headers();
  for (const name of [
    "content-type",
    "x-slack-signature",
    "x-slack-request-timestamp",
    "x-slack-retry-num",
    "x-slack-retry-reason",
  ]) {
    const value = request.headers.get(name);
    if (value) headers.set(name, value);
  }
  try {
    const upstream = await fetch(target, {
      method: "POST",
      headers,
      body: await request.arrayBuffer(),
      redirect: "manual",
    });
    const responseHeaders = new Headers({ "cache-control": "no-store" });
    const contentType = upstream.headers.get("content-type");
    if (contentType) responseHeaders.set("content-type", contentType);
    return new Response(upstream.body, {
      status: upstream.status,
      headers: responseHeaders,
    });
  } catch {
    return new Response(
      JSON.stringify({ error: { code: "slack_events_unavailable" } }),
      {
        status: 502,
        headers: { "content-type": "application/json" },
      },
    );
  }
}

// Work 082: the backend bounds the body the same way (CODEX_BODY_MAX_BYTES:
// twice the 64 KiB auth.json cap, plus room for the code and provider).
// Blue verifies the subscription with its provider before answering.
const COMPUTER_AGENT_CONNECT_TIMEOUT_MS = 30_000;
const COMPUTER_AGENT_CONNECT_RETRY_SEC = 60;
export const COMPUTER_AGENT_CONNECT_MAX_BYTES = 2 * 64 * 1024 + 1024;
// `oc_` + 16 Crockford base32 characters (short enough to keep the command
// on one line); anything else is refused here so garbage never reaches the
// backend. People retype codes: the edge only trims and takes either case,
// blue (the authority) normalizes the rest (I/L to 1, O to 0, upper case).
const CONNECT_CODE = /^oc_[0-9A-Za-z]{16}$/;

function connectProblem(status: number, code: string, message: string) {
  return Response.json(
    { error: { code, message } },
    { status, headers: { "cache-control": "no-store" } },
  );
}

/** Reads at most `max` bytes; null when the body is longer. */
async function boundedBody(
  request: Request,
  max: number,
): Promise<Uint8Array | null> {
  const declared = Number(request.headers.get("content-length") ?? "");
  if (Number.isFinite(declared) && declared > max) return null;
  if (!request.body) return new Uint8Array();
  const reader = request.body.getReader();
  const chunks: Uint8Array[] = [];
  let size = 0;
  for (;;) {
    const { done, value } = await reader.read();
    if (done) break;
    size += value.byteLength;
    if (size > max) {
      await reader.cancel().catch(() => {});
      return null;
    }
    chunks.push(value);
  }
  const out = new Uint8Array(size);
  let offset = 0;
  for (const chunk of chunks) {
    out.set(chunk, offset);
    offset += chunk.byteLength;
  }
  return out;
}

/**
 * The CLI's one-command connect (work 082): `opencomputer model connect
 * claude|codex --code <code>` posts `{code, provider, token|authJson}` here
 * with no OpenComputer credentials; the dashboard-minted code is the only
 * auth. It goes to one fixed backend route with only a JSON content type
 * (no cookies or other headers), the body byte for byte, and the backend's
 * answer comes back as is. The edge only bounds the size and refuses a body
 * whose code cannot be one, so this is no open proxy and no oracle.
 */
export async function handleComputerAgentConnect(
  request: Request,
  env: ManagedAgentsEnv,
): Promise<Response> {
  const startedAt = Date.now();
  // In prod the rate limit is meant to be bound; say so when it is not.
  const rateLimitUnbound =
    env.WORKER_ENV === "prod" && !env.COMPUTER_CONNECT_RATE_LIMIT;
  const finish = (
    response: Response,
    result: string,
    details: Record<string, string> = {},
  ): Response => {
    // One line per attempt: the funnel from command run to connected, and
    // what the edge refused before blue saw it.
    console.log(
      JSON.stringify({
        event: "computer_agent_connect",
        result,
        http_status: response.status,
        duration_ms: Date.now() - startedAt,
        ...(rateLimitUnbound ? { rate_limit: "unbound" } : {}),
        ...details,
      }),
    );
    return response;
  };
  if (request.method !== "POST") {
    const response = connectProblem(
      405,
      "method_not_allowed",
      "Send the connect request with POST.",
    );
    response.headers.set("allow", "POST");
    return finish(response, "method");
  }
  // Codes carry 80 bits, so this caps load on blue rather than guessing.
  // Without the binding (tests, a misconfigured env) the route stays open:
  // blue still refuses anything but a live code.
  if (env.COMPUTER_CONNECT_RATE_LIMIT) {
    const ip = request.headers.get("CF-Connecting-IP")?.trim();
    const key = ip && ip.length <= 64 ? ip : "unknown";
    const allowed = await env.COMPUTER_CONNECT_RATE_LIMIT.limit({ key }).then(
      (r) => r.success,
      () => true,
    );
    if (!allowed) {
      const response = connectProblem(
        429,
        "rate_limited",
        "Too many connect attempts. Wait a minute and try again.",
      );
      response.headers.set(
        "retry-after",
        String(COMPUTER_AGENT_CONNECT_RETRY_SEC),
      );
      return finish(response, "rate_limited");
    }
  }
  const contentType = request.headers.get("content-type") ?? "";
  if (!/^application\/json\s*(;|$)/i.test(contentType)) {
    return finish(
      connectProblem(
        415,
        "invalid_request",
        "Send the connect request as application/json.",
      ),
      "content_type",
    );
  }
  const bytes = await boundedBody(request, COMPUTER_AGENT_CONNECT_MAX_BYTES);
  if (!bytes) {
    return finish(
      connectProblem(413, "invalid_request", "The request is too large."),
      "too_large",
    );
  }
  let parsed: { code?: unknown } | null;
  try {
    parsed = JSON.parse(new TextDecoder().decode(bytes)) as {
      code?: unknown;
    } | null;
  } catch {
    return finish(
      connectProblem(400, "invalid_request", "The request is not JSON."),
      "not_json",
    );
  }
  const code = typeof parsed?.code === "string" ? parsed.code.trim() : null;
  if (code === null || !CONNECT_CODE.test(code)) {
    return finish(
      connectProblem(
        401,
        "computer_connect_code_invalid",
        "That connect code is not valid. Get a new one from the dashboard.",
      ),
      "malformed_code",
    );
  }
  // The body goes on byte for byte, unless the code needed trimming.
  const body =
    code === parsed?.code
      ? bytes
      : new TextEncoder().encode(JSON.stringify({ ...parsed, code }));
  const base = (
    env.MANAGED_AGENTS_API_URL ?? DEFAULT_MANAGED_AGENTS_API_URL
  ).replace(/\/+$/, "");
  const target = new URL(`${base}/v1/computer/agent/connect`);
  if (target.protocol !== "https:" && target.hostname !== "localhost") {
    return finish(
      connectProblem(
        503,
        "computer_not_configured",
        "Connecting a subscription isn't available yet. Try again shortly.",
      ),
      "not_configured",
    );
  }
  try {
    const upstream = await fetch(target, {
      method: "POST",
      headers: { "content-type": "application/json" },
      body,
      redirect: "manual",
      signal: AbortSignal.timeout(COMPUTER_AGENT_CONNECT_TIMEOUT_MS),
    });
    // A redirect is not followed and has no body the CLI could read: it
    // means blue is not where it should be, which is the same as down.
    if (upstream.status >= 300 && upstream.status < 400) {
      return finish(connectUnavailable(), "upstream_redirect", {
        upstream_status: String(upstream.status),
      });
    }
    const headers = new Headers({ "cache-control": "no-store" });
    const upstreamType = upstream.headers.get("content-type");
    if (upstreamType) headers.set("content-type", upstreamType);
    return finish(
      new Response(upstream.body, { status: upstream.status, headers }),
      upstream.ok ? "connected" : "refused_upstream",
    );
  } catch (error) {
    // The name tells a timeout (TimeoutError) from a connection failure;
    // the message could carry the body, so it stays out.
    return finish(connectUnavailable(), "upstream_unavailable", {
      error_name: error instanceof Error ? error.name : "NonError",
    });
  }
}

function connectUnavailable() {
  return connectProblem(
    502,
    "computer_unavailable",
    "Connecting a subscription isn't available right now. Try again shortly.",
  );
}

function channelConnectionPage(
  action: string,
  status: number,
  error?: string,
): Response {
  const message = error
    ? `<p role="alert">${error}</p>`
    : `<p>Continue to securely connect an account to this agent in Slack.</p>
       <form method="post" action="${action}">
         <button type="submit">Continue</button>
       </form>`;
  return new Response(
    `<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><meta name="referrer" content="no-referrer"><title>Connect account · OpenComputer</title><style>body{font:16px system-ui,sans-serif;max-width:34rem;margin:12vh auto;padding:2rem;color:#171717}h1{font-size:1.7rem}p{line-height:1.55;color:#555}button{font:inherit;background:#171717;color:#fff;border:0;border-radius:8px;padding:.8rem 1.2rem;cursor:pointer}</style></head><body><h1>Connect account</h1>${message}</body></html>`,
    {
      status,
      headers: {
        "content-type": "text/html; charset=utf-8",
        "cache-control": "no-store",
        "referrer-policy": "no-referrer",
        "x-content-type-options": "nosniff",
        "content-security-policy":
          "default-src 'none'; style-src 'unsafe-inline'; base-uri 'none'; frame-ancestors 'none'",
      },
    },
  );
}

export async function handleManagedAgentChannelConnection(
  request: Request,
  env: ManagedAgentsEnv,
): Promise<Response> {
  const url = new URL(request.url);
  const match = url.pathname.match(
    /^\/api\/managed-agents\/channel-connections\/([^/]+)\/([a-f0-9]{32})$/i,
  );
  if (!match) {
    return channelConnectionPage(
      url.pathname,
      404,
      "This connection link is invalid.",
    );
  }
  const accountId = decodeURIComponent(match[1]);
  const token = match[2];
  if (!/^[A-Za-z0-9._:-]{1,200}$/.test(accountId)) {
    return channelConnectionPage(
      url.pathname,
      404,
      "This connection link is invalid.",
    );
  }
  if (request.method === "GET" || request.method === "HEAD") {
    const response = channelConnectionPage(url.pathname, 200);
    return request.method === "HEAD"
      ? new Response(null, {
          status: response.status,
          headers: response.headers,
        })
      : response;
  }
  if (request.method !== "POST") {
    return channelConnectionPage(
      url.pathname,
      405,
      "This request is not supported.",
    );
  }
  const internal = new Request(
    new URL("/api/managed-agents/channel-connections/claim", url.origin),
    {
      method: "POST",
      headers: { "content-type": "application/json" },
      body: JSON.stringify({ token }),
    },
  );
  const response = await proxyManagedAgents(
    internal,
    env,
    { orgID: accountId, userID: null },
    "/api/managed-agents",
  );
  if (!response.ok) {
    return channelConnectionPage(
      url.pathname,
      response.status === 404 ? 404 : 502,
      response.status === 404
        ? "This connection link has expired or was already used. Ask the agent for a new one."
        : "OpenComputer could not start the connection. Please try again.",
    );
  }
  const body = record(await response.json().catch(() => null));
  if (body?.status === "connected") {
    return channelConnectionPage(
      url.pathname,
      200,
      "This account is already connected. You can return to Slack.",
    );
  }
  let authorizationUrl: URL | null = null;
  if (typeof body?.authorizationUrl === "string") {
    try {
      authorizationUrl = new URL(body.authorizationUrl);
    } catch {
      authorizationUrl = null;
    }
  }
  if (!authorizationUrl || authorizationUrl.protocol !== "https:") {
    return channelConnectionPage(
      url.pathname,
      502,
      "OpenComputer could not start the connection. Please try again.",
    );
  }
  return new Response(null, {
    status: 303,
    headers: {
      location: authorizationUrl.toString(),
      "cache-control": "no-store",
      "referrer-policy": "no-referrer",
      "x-content-type-options": "nosniff",
    },
  });
}

// A webhook may read its delivery identity from any request header the
// sender chose at configuration time, so the sender's headers pass through
// except credentials, transport headers, and anything the backend trusts
// from this edge. The backend rejects identity sources naming these headers
// (`bluecode/src/edge/webhook-input.ts`); change both together.
const WEBHOOK_HEADERS_NOT_FORWARDED = new Set([
  "authorization",
  "cookie",
  "host",
  "content-length",
  "connection",
  "transfer-encoding",
  "x-request-id",
  "x-api-key",
]);
const WEBHOOK_HEADER_PREFIXES_NOT_FORWARDED = [
  "x-oc-",
  "cf-",
  "x-forwarded-",
  "x-real-",
];

function forwardableWebhookHeader(name: string): boolean {
  const lower = name.toLowerCase();
  return (
    !WEBHOOK_HEADERS_NOT_FORWARDED.has(lower) &&
    !WEBHOOK_HEADER_PREFIXES_NOT_FORWARDED.some((prefix) =>
      lower.startsWith(prefix),
    )
  );
}

export async function handleAgentWebhookInvocation(
  request: Request,
  env: ManagedAgentsEnv,
): Promise<Response> {
  const url = new URL(request.url);
  const match = url.pathname.match(
    /^\/api\/agent-webhooks\/([^/]+)(?:\/([^/]+))?$/,
  );
  if (!match?.[1] || request.method !== "POST") {
    return Response.json(
      { error: { code: "not_found", message: "Webhook not found." } },
      { status: 404 },
    );
  }
  const webhookId = match[1];
  const pathToken = match[2];
  if (
    !/^wh_[a-f0-9]{32}$/.test(webhookId) ||
    (pathToken !== undefined && !/^[A-Za-z0-9_-]{16,128}$/.test(pathToken))
  ) {
    return Response.json(
      { error: { code: "not_found", message: "Webhook not found." } },
      { status: 404 },
    );
  }
  // The credential is the token: in the path, or as a bearer header for
  // senders that can set one. Providers that can do neither use the URL.
  const authorization = request.headers.get("authorization");
  if (!pathToken && !authorization?.startsWith("Bearer ")) {
    return Response.json(
      {
        error: {
          code: "unauthorized",
          message: "Webhook credentials are required.",
        },
      },
      { status: 401 },
    );
  }
  const base = (
    env.MANAGED_AGENTS_API_URL ?? DEFAULT_MANAGED_AGENTS_API_URL
  ).replace(/\/+$/, "");
  const target = new URL(
    `${base}/v1/agent-webhooks/${encodeURIComponent(webhookId)}` +
      (pathToken ? `/${encodeURIComponent(pathToken)}` : ""),
  );
  if (target.protocol !== "https:" && target.hostname !== "localhost") {
    return Response.json(
      {
        error: {
          code: "unavailable",
          message: "Webhook service is unavailable.",
        },
      },
      { status: 503 },
    );
  }
  const headers = new Headers({
    "content-type": request.headers.get("content-type") ?? "application/json",
    "x-request-id": crypto.randomUUID(),
  });
  if (authorization) headers.set("authorization", authorization);
  for (const [name, value] of request.headers) {
    if (forwardableWebhookHeader(name) && !headers.has(name))
      headers.set(name, value);
  }
  try {
    const upstream = await fetch(target, {
      method: "POST",
      headers,
      body: request.body,
      redirect: "manual",
    });
    if (!upstream.ok) return publicErrorResponse(upstream);
    const body = record(await upstream.json()) ?? {};
    const webhookRequest = publicWebhookRequest(body.request);
    const projectId = webhookRequest.projectId;
    const agentId = webhookRequest.agentId;
    const environment = webhookRequest.environment;
    const sessionId = webhookRequest.sessionId;
    const sessionUrl =
      typeof projectId === "string" &&
      typeof agentId === "string" &&
      typeof environment === "string" &&
      typeof sessionId === "string"
        ? `${url.origin}/projects/${encodeURIComponent(projectId)}/sessions/${encodeURIComponent(sessionId)}?agent=${encodeURIComponent(agentId)}${
            // The single `default` scope is the dashboard's environmentless URL.
            environment === "default"
              ? ""
              : `&environment=${encodeURIComponent(environment)}`
          }`
        : undefined;
    return Response.json(
      {
        request: webhookRequest,
        duplicate: body.duplicate === true,
        ...(sessionUrl ? { sessionUrl } : {}),
      },
      { status: 202 },
    );
  } catch (error) {
    console.error(
      JSON.stringify({
        level: "error",
        event: "agent_webhook.upstream_failed",
        webhookId,
        message: error instanceof Error ? error.message : String(error),
      }),
    );
    return Response.json(
      {
        error: {
          code: "unavailable",
          message: "Webhook service is unavailable.",
        },
      },
      { status: 502 },
    );
  }
}

// Anonymous template preview: the dashboard shows a template's deploy form
// before sign-up, so inspection is proxied without an org assertion to the
// backend's public route. Installation still requires an authenticated caller.
export async function proxyPublicTemplateInspection(
  request: Request,
  env: ManagedAgentsEnv,
): Promise<Response> {
  if (request.method.toUpperCase() !== "POST") {
    return Response.json({ error: "method not allowed" }, { status: 405 });
  }
  const base = (
    env.MANAGED_AGENTS_API_URL ?? DEFAULT_MANAGED_AGENTS_API_URL
  ).replace(/\/+$/, "");
  const target = new URL(`${base}/v1/public/template-inspections`);
  if (target.protocol !== "https:" && target.hostname !== "localhost") {
    return Response.json(
      { error: "managed agents upstream must use HTTPS" },
      { status: 503 },
    );
  }
  try {
    const upstream = await fetch(target, {
      method: "POST",
      headers: copyRequestHeaders(request),
      body: request.body,
      redirect: "manual",
    });
    if (!upstream.ok) return publicErrorResponse(upstream);
    return publicSuccessResponse(
      upstream,
      "POST",
      "/template-inspections",
      new URL(request.url).origin,
    );
  } catch (error) {
    console.error(
      JSON.stringify({
        level: "error",
        event: "managed_agents.upstream_failed",
        message: error instanceof Error ? error.message : String(error),
      }),
    );
    return Response.json(
      { error: "managed agents service is unavailable" },
      { status: 502 },
    );
  }
}

export async function proxyManagedAgents(
  request: Request,
  env: ManagedAgentsEnv,
  caller: ManagedAgentsCaller,
  publicPrefix: string,
): Promise<Response> {
  const requestURL = new URL(request.url);
  const requestedSuffix = requestURL.pathname.slice(publicPrefix.length);
  const suffix =
    requestedSuffix === "/v1"
      ? ""
      : requestedSuffix.startsWith("/v1/")
        ? requestedSuffix.slice(3)
        : requestedSuffix;
  if (
    requestURL.pathname !== publicPrefix &&
    !requestURL.pathname.startsWith(`${publicPrefix}/`)
  ) {
    return Response.json({ error: "route not found" }, { status: 404 });
  }
  if (
    !isAllowedManagedAgentsRoute(
      request.method.toUpperCase(),
      suffix,
      publicPrefix,
    )
  ) {
    return Response.json({ error: "route not found" }, { status: 404 });
  }
  if (
    caller.principal === "computer" &&
    isGrantRoute(request.method.toUpperCase(), suffix)
  ) {
    return Response.json(
      {
        error: {
          code: "computer_key_forbidden",
          message:
            "The computer cannot connect, attach or grant credentials; a person does that from Slack or the dashboard.",
        },
      },
      { status: 403 },
    );
  }
  const family = routeFamilyFor(suffix, publicPrefix);
  if (
    family &&
    ((family.dashboardOnly &&
      publicPrefix !== DASHBOARD_MANAGED_AGENTS_PREFIX) ||
      (family.apiOnly && publicPrefix === DASHBOARD_MANAGED_AGENTS_PREFIX) ||
      family.enabledFor?.(env, caller.orgID) === false)
  ) {
    return Response.json({ error: "route not found" }, { status: 404 });
  }
  if (!env.OC_MANAGED_AGENTS_SECRET) {
    return Response.json(
      { error: "managed agents are not configured" },
      { status: 503 },
    );
  }
  if (
    request.method.toUpperCase() === "POST" &&
    suffix === "/model-access/connections"
  ) {
    const payload = record(
      await request
        .clone()
        .json()
        .catch(() => null),
    );
    if (
      payload?.provider !== "openai" &&
      payload?.provider !== "anthropic" &&
      payload?.provider !== "openrouter" &&
      payload?.provider !== "openai_compatible"
    ) {
      return Response.json(
        {
          error: {
            code: "unsupported_provider",
            message:
              "Supported providers are Codex, Claude, OpenRouter, and OpenAI-compatible APIs.",
          },
        },
        { status: 400 },
      );
    }
  }
  const method = request.method.toUpperCase();
  const modelAccessConnectionWrite =
    method === "POST" &&
    (suffix === "/model-access/connections" ||
      /^\/model-access\/connections\/[^/]+\/(validate|complete)$/.test(suffix));
  const modelAccessBindingEnable =
    method === "PUT" &&
    /^\/projects\/[^/]+\/model-access\/bindings\/[^/]+\/[^/]+$/.test(suffix) &&
    record(
      await request
        .clone()
        .json()
        .catch(() => null),
    )?.enabled === true;
  const modelRouteWrite =
    (method === "PUT" || method === "DELETE") &&
    /^\/projects\/[^/]+\/model-routes\/[^/]+$/.test(suffix);
  if (
    modelAccessConnectionWrite ||
    modelAccessBindingEnable ||
    modelRouteWrite
  ) {
    try {
      if (!(await hasBYOKPlanAccess(env, caller.orgID))) {
        return byokPlanRequired();
      }
    } catch (error) {
      console.error(
        JSON.stringify({
          level: "error",
          event: "managed_agents.byok_entitlement_failed",
          orgId: caller.orgID,
          message: error instanceof Error ? error.message : String(error),
        }),
      );
      return Response.json(
        {
          error: {
            code: "billing_unavailable",
            message: "BYOK plan eligibility could not be verified.",
          },
        },
        { status: 503 },
      );
    }
  }
  const base = (
    env.MANAGED_AGENTS_API_URL ?? DEFAULT_MANAGED_AGENTS_API_URL
  ).replace(/\/+$/, "");
  const target = new URL(`${base}/v1${suffix}${requestURL.search}`);
  if (target.protocol !== "https:" && target.hostname !== "localhost") {
    return Response.json(
      { error: "managed agents upstream must use HTTPS" },
      { status: 503 },
    );
  }
  const headers = copyRequestHeaders(request);
  if (method === "GET" && SESSION_CONNECT_ROUTE.test(suffix)) {
    if (request.headers.get("upgrade")?.toLowerCase() !== "websocket") {
      return Response.json(
        { error: "expected a WebSocket upgrade" },
        { status: 426 },
      );
    }
    target.searchParams.set("role", "client");
    headers.set("upgrade", "websocket");
    headers.set(
      "x-opencomputer-agent-token",
      await mintManagedAgentsAssertion(env.OC_MANAGED_AGENTS_SECRET, caller),
    );
    try {
      const upstream = await fetch(target, { method: "GET", headers });
      if (upstream.status !== 101 || !upstream.webSocket) {
        return publicErrorResponse(upstream);
      }
      return relaySessionSocket(upstream.webSocket);
    } catch (error) {
      console.error(
        JSON.stringify({
          level: "error",
          event: "managed_agents.upstream_failed",
          message: error instanceof Error ? error.message : String(error),
        }),
      );
      return Response.json(
        { error: "managed agents service is unavailable" },
        { status: 502 },
      );
    }
  }
  const memoryRoute = isMemoryRoute(method, suffix);
  if (memoryRoute) {
    for (const name of MEMORY_CONDITIONAL_REQUEST_HEADERS) {
      const value = request.headers.get(name);
      if (value) headers.set(name, value);
    }
  }
  headers.set(
    "x-opencomputer-agent-token",
    await mintManagedAgentsAssertion(env.OC_MANAGED_AGENTS_SECRET, caller),
  );
  if (family?.forward) {
    return family.forward({ request, method, suffix, target, headers });
  }
  if (request.method.toUpperCase() === "POST" && suffix === "/deployments") {
    try {
      return await deploySourceAgent(request, base, headers);
    } catch (error) {
      console.error(
        JSON.stringify({
          level: "error",
          event: "managed_agents.deployment_failed",
          message: error instanceof Error ? error.message : String(error),
        }),
      );
      return Response.json(
        { error: "managed agents service is unavailable" },
        { status: 502 },
      );
    }
  }
  const init: RequestInit = {
    method: request.method,
    headers,
    redirect: "manual",
  };
  if (request.method !== "GET" && request.method !== "HEAD") {
    init.body = request.body;
  }
  try {
    const upstream = await fetch(target, init);
    if (memoryRoute) return memoryResponse(upstream, method, suffix);
    if (
      method === "GET" &&
      /^\/sessions\/[^/]+\/workspace\/download$/.test(suffix) &&
      upstream.status === 302
    ) {
      const value = upstream.headers.get("location");
      let location: URL;
      try {
        location = new URL(value ?? "");
      } catch {
        throw new Error("Invalid workspace download redirect");
      }
      if (
        location.protocol !== "https:" ||
        location.username ||
        location.password
      ) {
        throw new Error("Invalid workspace download redirect");
      }
      return new Response(null, {
        status: 302,
        headers: {
          location: location.toString(),
          "cache-control": "private, no-store",
          "referrer-policy": "no-referrer",
        },
      });
    }
    if (!upstream.ok) return publicErrorResponse(upstream, suffix);
    if (upstream.status === 204) return new Response(null, { status: 204 });
    if (family) return await family.shapeSuccess(method, suffix, upstream);
    if (
      /^\/projects\/[^/]+\/source-archive$/.test(suffix) ||
      WORKSPACE_ARTIFACT_CONTENT_ROUTE.test(suffix)
    ) {
      const responseHeaders = new Headers();
      for (const name of [
        "content-type",
        "content-length",
        "content-disposition",
        "etag",
        "x-workspace-artifact-id",
        "x-workspace-artifact-sha256",
        "x-workspace-artifact-size",
      ]) {
        const value = upstream.headers.get(name);
        if (value) responseHeaders.set(name, value);
      }
      responseHeaders.set("cache-control", "private, no-store");
      return new Response(upstream.body, {
        status: upstream.status,
        statusText: upstream.statusText,
        headers: responseHeaders,
      });
    }
    if (suffix.startsWith("/openrouter/")) {
      return upstream;
    }
    return publicSuccessResponse(
      upstream,
      request.method.toUpperCase(),
      suffix,
      requestURL.origin,
      caller.role === "admin",
    );
  } catch (error) {
    console.error(
      JSON.stringify({
        level: "error",
        event: "managed_agents.upstream_failed",
        message: error instanceof Error ? error.message : String(error),
      }),
    );
    return Response.json(
      { error: "managed agents service is unavailable" },
      { status: 502 },
    );
  }
}