Skip to content

Open-source AI coworkers that each get a computer of their own: a browser, files and tools, with every action decided before it happens and recorded after. Bring any AG-UI agent.

5.5 KB
Raw Blame
import { and, eq, isNotNull, isNull, or } from "drizzle-orm";
import type { ManagedAgentConfig } from "../config";
import { type RegisteredAgent, registeredAgentFromRow } from "../copilot";
import type { CredentialSecretReader } from "../credentials";
import type { Database } from "../db/client";
import {
  agentProfiles,
  agents,
  channelAgents,
  channelMemberships,
  channels,
} from "../db/schema";
import { teamBotAccess } from "../team-bots/access";
import { agentAuthHeaders, authFromConfiguration } from "./auth-header";
import { isManagedEndpoint } from "./managed-endpoint";
import type { AgentActor } from "./profile-types";

/**
 * Read the agents one person may run, on every request.
 *
 * The filtering is in the query, not in JavaScript afterwards: a private coworker must never be
 * read into the process for an actor who cannot see it, and "we fetched it but did not show it" is
 * the shape most accidental disclosures take.
 */
export function createRuntimeAgentLoader(
  database: Database,
  /** Resolves a customer agent's key at load time. Absent means no agent can carry one. */
  vault?: { reader: CredentialSecretReader; encryptionKey: string },
  /** Secret for the deployment-managed Bot. Never sent to customer-owned endpoints. */
  managedAgent?: ManagedAgentConfig,
) {
  return async (actor: AgentActor): Promise<RegisteredAgent[]> => {
    const [active, tombstones] = await Promise.all([
      selectActiveAgents(database, actor),
      selectTombstoneAgents(database, actor),
    ]);

    // A row whose configuration cannot be understood is skipped rather than mounted as a broken
    // agent. Tombstones are appended after, and never overwrite a live agent of the same id.
    const registered = new Map<string, RegisteredAgent>();
    for (const row of active) {
      const agent = registeredAgentFromRow(row);
      if (!agent) continue;
      const isRemoteAgent =
        agent.type === "remote_ag_ui" || agent.type === "remote_mastra";
      // The key is resolved per load, rather than being cached on the row: revoking a
      // credential then takes effect on the next run rather than on the next restart.
      if (isRemoteAgent && vault) {
        const headers = await agentAuthHeaders({
          reader: vault.reader,
          encryptionKey: vault.encryptionKey,
          auth: authFromConfiguration(row.configuration),
        });
        if (headers) agent.headers = headers;
      }
      /*
       * Every endpoint this deployment runs gets the token, not just the first one.
       *
       * Matching a single endpoint left the harness picked during setup without it: registered,
       * addressable, routed to, and answering `401 unauthorised` to everything. Its container is
       * this deployment's own, started on a port this deployment chose with this token in its
       * environment, so it is the same relationship the Bot in the box has.
       */
      if (isRemoteAgent && managedAgent) {
        // Config parses URLs, while package rows retain their original spelling. Compare both
        // in canonical form so scheme/host case cannot silently drop the deployment token.
        const ours = isManagedEndpoint(agent.endpoint, [
          managedAgent.endpoint,
          managedAgent.alsoRun,
        ]);
        if (ours) {
          agent.headers = {
            ...agent.headers,
            "x-openbot-agent-token": managedAgent.token,
          };
        }
      }
      registered.set(agent.id, agent);
    }
    for (const row of tombstones) {
      if (registered.has(row.id)) continue;
      registered.set(row.id, {
        id: row.id,
        name: row.name,
        type: "unavailable",
        reason: `${row.name} has been deleted and can no longer run. Its conversations remain readable.`,
      });
    }

    return [...registered.values()];
  };
}

function selectActiveAgents(database: Database, actor: AgentActor) {
  return database
    .select({
      id: agents.id,
      name: agents.name,
      type: agents.type,
      configuration: agents.configuration,
      title: agentProfiles.title,
      roleDescription: agentProfiles.roleDescription,
    })
    .from(agents)
    .innerJoin(agentProfiles, eq(agentProfiles.agentId, agents.id))
    .where(
      and(
        isNull(agentProfiles.deletedAt),
        actor.role === "admin"
          ? undefined
          : or(
              eq(agentProfiles.visibility, "public"),
              eq(agentProfiles.ownerUserId, actor.id),
              // The same Team Bot rule as the roster: see team-bots/access.ts.
              teamBotAccess(actor.id, agentProfiles.agentId),
            ),
      ),
    );
}

/**
 * Deleted coworkers the caller still has history with.
 *
 * Registered so Intelligence can restore the thread the person is reading. Membership of a channel
 * the agent worked in is what authorizes this, not the profile's visibility, which is why deleting
 * a coworker leaves its conversations readable instead of erasing them.
 */
function selectTombstoneAgents(database: Database, actor: AgentActor) {
  return database
    .selectDistinct({ id: agents.id, name: agents.name })
    .from(agents)
    .innerJoin(agentProfiles, eq(agentProfiles.agentId, agents.id))
    .innerJoin(channelAgents, eq(channelAgents.agentId, agents.id))
    .innerJoin(
      channels,
      and(eq(channels.id, channelAgents.channelId), isNull(channels.deletedAt)),
    )
    .innerJoin(
      channelMemberships,
      and(
        eq(channelMemberships.channelId, channelAgents.channelId),
        eq(channelMemberships.userId, actor.id),
      ),
    )
    .where(isNotNull(agentProfiles.deletedAt));
}