Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 29 additions & 0 deletions apps/backend/db/migrations/20260813191611_comment-agent.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
/**
* Record which coding agent posted a comment, when one did.
*
* An agent acts with its user's own credentials, so a comment it writes is
* indistinguishable from one the person typed. This is what lets the UI say
* "posted through Claude Code" next to the author's avatar, rather than
* silently attributing the agent's words to them.
*
* A plain string, not a foreign key: the value is an id from the curated
* registry in `src/agent/registry.ts` (or `unknown` for an agent we can't put a
* name to), which lives in code because adding an agent is a display decision,
* not data anyone edits. `NULL` means a person acted directly.
*
* @param {import('knex').Knex} knex
*/
export const up = async (knex) => {
await knex.schema.alterTable("comments", (table) => {
table.string("agent");
});
};

/**
* @param {import('knex').Knex} knex
*/
export const down = async (knex) => {
await knex.schema.alterTable("comments", (table) => {
table.dropColumn("agent");
});
};
8 changes: 5 additions & 3 deletions apps/backend/db/structure.sql
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
-- PostgreSQL database dump
--

\restrict SJMOjW7fwlbG5V9h9dOw91WWYjjnPhrNmOhMNNy0ftDq9k87kzZthcc2phDVXnb
\restrict 8WS8KvWTX1NC5mccR9MIC9lXebzpzWv8u6YEgWIomHaGpKkaShrQhTYIWaa3QEM

-- Dumped from database version 18.4
-- Dumped by pg_dump version 18.4 (Homebrew)
Expand Down Expand Up @@ -701,6 +701,7 @@ CREATE TABLE public.comments (
"testId" bigint,
"mediaId" bigint,
"mediaVersionId" bigint,
agent character varying(255),
CONSTRAINT comments_anchor_requires_target CHECK (((anchor IS NULL) OR ("screenshotDiffId" IS NOT NULL) OR ("mediaId" IS NOT NULL))),
CONSTRAINT comments_media_target_scope CHECK ((("mediaId" IS NULL) OR (("buildReviewId" IS NULL) AND ("screenshotDiffId" IS NULL)))),
CONSTRAINT comments_media_version_requires_media CHECK ((("mediaVersionId" IS NULL) OR ("mediaId" IS NOT NULL))),
Expand Down Expand Up @@ -6234,7 +6235,7 @@ ALTER TABLE ONLY public.users
-- PostgreSQL database dump complete
--

\unrestrict SJMOjW7fwlbG5V9h9dOw91WWYjjnPhrNmOhMNNy0ftDq9k87kzZthcc2phDVXnb
\unrestrict 8WS8KvWTX1NC5mccR9MIC9lXebzpzWv8u6YEgWIomHaGpKkaShrQhTYIWaa3QEM

-- Knex migrations

Expand Down Expand Up @@ -6477,4 +6478,5 @@ INSERT INTO public.knex_migrations(name, batch, migration_time) VALUES ('2026080
INSERT INTO public.knex_migrations(name, batch, migration_time) VALUES ('20260808130000_media.js', 1, NOW());
INSERT INTO public.knex_migrations(name, batch, migration_time) VALUES ('20260808140000_comment-media.js', 1, NOW());
INSERT INTO public.knex_migrations(name, batch, migration_time) VALUES ('20260809203017_media-branch.js', 1, NOW());
INSERT INTO public.knex_migrations(name, batch, migration_time) VALUES ('20260811133709_media-diffs.js', 1, NOW());
INSERT INTO public.knex_migrations(name, batch, migration_time) VALUES ('20260811133709_media-diffs.js', 1, NOW());
INSERT INTO public.knex_migrations(name, batch, migration_time) VALUES ('20260813191611_comment-agent.js', 1, NOW());
106 changes: 106 additions & 0 deletions apps/backend/src/agent/registry.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
/**
* Curated registry of the coding agents that act on Argos through the CLI or
* the MCP server.
*
* An agent reaches the API with its user's own credentials, so the identity of
* the *tool* is self-asserted: the CLI forwards what `@vercel/detect-agent`
* found (ultimately the `AI_AGENT` environment variable, which anyone can set),
* and an MCP client picks its own OAuth registration metadata. Nothing here is
* a trust decision — it only decides which name and logo we show next to a
* comment. Anything unrecognized still counts as an agent and renders as a
* generic bot.
*
* Ids are shared with `oauth/known-apps.ts` where the same product appears in
* both, so the frontend keys a single logo map by them.
*/

type AgentDefinition = {
/** Stable id; also the key the frontend uses to pick the bundled logo. */
id: string;
displayName: string;
};

const AGENTS: AgentDefinition[] = [
{ id: "claude-code", displayName: "Claude Code" },
{ id: "claude", displayName: "Claude" },
{ id: "openai-codex", displayName: "OpenAI Codex" },
{ id: "cursor", displayName: "Cursor" },
{ id: "vscode", displayName: "Visual Studio Code" },
{ id: "windsurf", displayName: "Windsurf" },
{ id: "zed", displayName: "Zed" },
{ id: "gemini-cli", displayName: "Gemini CLI" },
{ id: "github-copilot", displayName: "GitHub Copilot" },
{ id: "devin", displayName: "Devin" },
{ id: "replit", displayName: "Replit" },
{ id: "antigravity", displayName: "Antigravity" },
{ id: "augment-cli", displayName: "Augment CLI" },
{ id: "opencode", displayName: "OpenCode" },
{ id: "v0", displayName: "v0" },
];

/**
* Id stored for an agent we could not put a name to — an unrecognized MCP
* client, or a CLI run under a custom `AI_AGENT`. The action is still known to
* be agent-made, which is what the bot marker conveys; only the brand is
* missing. Self-asserted names are deliberately *not* stored under their own
* id: they would render as a name nobody vetted.
*/
export const UNKNOWN_AGENT_ID = "unknown";

/**
* Names the CLI reports that differ from our id.
*
* These are the slugs `@vercel/detect-agent` returns, which are shorter than
* ours and, for `claude`, ambiguous: the CLI only ever runs under Claude *Code*
* — `claude` as a registry id is the desktop/web app, which reaches us over MCP
* instead. Keeping this map on the CLI side of the resolution is what lets the
* same word mean the right product on each side.
*/
const REPORTED_AGENT_ALIASES: Record<string, string> = {
claude: "claude-code",
claudecode: "claude-code",
cowork: "claude-code",
codex: "openai-codex",
"cursor-cli": "cursor",
gemini: "gemini-cli",
copilot: "github-copilot",
"github-copilot-cli": "github-copilot",
};

const AGENT_BY_ID = new Map(AGENTS.map((agent) => [agent.id, agent]));

/**
* Strip the version an agent may append to its name, leaving the product.
*
* Two shapes occur in the wild: the `@` separator the `AI_AGENT` convention
* documents (`devin@1`, `custom-agent@2.0`), and the `_` one Claude Code
* actually emits (`claude-code_2-1-227_agent`). A hyphen is *not* a separator —
* it is what the convention uses inside a name, as in `cursor-cli`.
*/
function stripAgentVersion(name: string): string {
return name.split("@")[0]!.split("_")[0]!;
}

/**
* Resolve the name an agent reported for itself (the CLI's `agent/` token) to a
* registry id, falling back to {@link UNKNOWN_AGENT_ID}.
*/
export function resolveReportedAgentId(name: string): string {
const normalized = stripAgentVersion(name.trim().toLowerCase());
const id = REPORTED_AGENT_ALIASES[normalized] ?? normalized;
return AGENT_BY_ID.has(id) ? id : UNKNOWN_AGENT_ID;
}

/**
* Whether an id names an agent in this registry — used to tell the well-known
* OAuth apps that are agents (Claude, Cursor, …) from the ones that are not
* (the Argos CLI itself).
*/
export function isAgentId(id: string): boolean {
return AGENT_BY_ID.has(id);
}

/** Display name of an agent id, `null` for an id outside the registry. */
export function getAgentDisplayName(id: string): string | null {
return AGENT_BY_ID.get(id)?.displayName ?? null;
}
118 changes: 118 additions & 0 deletions apps/backend/src/agent/request.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,118 @@
import type { Request } from "express";
import { describe, expect, it } from "vitest";

import type {
AuthOAuthPayload,
AuthPATPayload,
AuthProjectPayload,
} from "@/auth/payload";

import { parseUserAgentAgentName, resolveRequestAgentId } from "./request";

/** A request carrying just the header the resolver reads. */
function req(userAgent?: string): Request {
return {
get: (name: string) =>
name.toLowerCase() === "user-agent" ? userAgent : undefined,
} as Request;
}

/** An OAuth payload with only the fields the resolver reads. */
function oauth(input: {
clientId: string;
knownAppId: string | null;
}): AuthOAuthPayload {
return { type: "oauth", ...input } as AuthOAuthPayload;
}

const PAT = { type: "pat" } as AuthPATPayload;
const PROJECT = { type: "project" } as AuthProjectPayload;

describe("parseUserAgentAgentName", () => {
it.each([
["argos-cli/6.7.0 node/22.11.0 agent/claude", "claude"],
["argos-cli/6.7.0 agent/custom-agent@2.0", "custom-agent@2.0"],
["agent/devin", "devin"],
["argos-cli/6.7.0 agent/cursor some-proxy/1.0", "cursor"],
])("reads the agent token of %j", (userAgent, expected) => {
expect(parseUserAgentAgentName(userAgent)).toBe(expected);
});

it.each([
["no header", undefined],
["no agent token", "argos-cli/6.7.0 node/22.11.0"],
["a token that only looks like one", "myagent/claude"],
["an empty agent token", "argos-cli/6.7.0 agent/"],
["a name outside the token grammar", "argos-cli/6.7.0 agent/(claude)"],
])("returns null for %s", (_label, userAgent) => {
expect(parseUserAgentAgentName(userAgent)).toBeNull();
});
});

describe("resolveRequestAgentId", () => {
it.each([
// The slugs `@vercel/detect-agent` returns for its own detections.
["claude", "claude-code"],
["codex", "openai-codex"],
["cursor-cli", "cursor"],
["gemini", "gemini-cli"],
// Versioned names: `_` is what Claude Code actually puts in `AI_AGENT`,
// `@` is what the convention documents.
["claude-code_2-1-227_agent", "claude-code"],
["devin@1", "devin"],
])("resolves the reported name %j to %j", (reported, expected) => {
expect(
resolveRequestAgentId(req(`argos-cli/6.7.0 agent/${reported}`), PAT),
).toBe(expected);
});

it("keeps an unrecognized agent as an agent", () => {
expect(
resolveRequestAgentId(req("argos-cli/6.7.0 agent/homemade"), PAT),
).toBe("unknown");
});

it("prefers the reported agent over the OAuth client", () => {
expect(
resolveRequestAgentId(
req("argos-cli/6.7.0 agent/cursor"),
oauth({ clientId: "argos-cli", knownAppId: "argos-cli" }),
),
).toBe("cursor");
});

it("resolves a well-known MCP client from its OAuth registration", () => {
expect(
resolveRequestAgentId(
req("node"),
oauth({ clientId: "oc_abc", knownAppId: "claude-code" }),
),
).toBe("claude-code");
});

it("treats an unrecognized OAuth client as an agent", () => {
expect(
resolveRequestAgentId(
req("node"),
oauth({ clientId: "oc_abc", knownAppId: null }),
),
).toBe("unknown");
});

it("does not take the CLI itself for an agent", () => {
expect(
resolveRequestAgentId(
req("argos-cli/6.7.0 node/22.11.0"),
oauth({ clientId: "argos-cli", knownAppId: "argos-cli" }),
),
).toBeNull();
});

it.each([
["a personal access token", PAT],
["a project token", PROJECT],
["no authentication", null],
])("resolves no agent for %s without an agent token", (_label, auth) => {
expect(resolveRequestAgentId(req("Mozilla/5.0"), auth)).toBeNull();
});
});
81 changes: 81 additions & 0 deletions apps/backend/src/agent/request.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
/**
* Works out whether an API request was made by a coding agent, and which one.
*
* Agents never call the API directly — they drive the CLI or the MCP server —
* so each surface carries the identity differently:
*
* - **CLI**: an `agent/<name>` token in the `User-Agent`, from the agent
* detection the CLI runs at startup.
* - **MCP**: the OAuth client holding the access token. OAuth exists here to
* serve the CLI and MCP clients, and MCP is an agent protocol — so an OAuth
* client that isn't the CLI is taken to be an agent even when the curated
* known-apps registry doesn't recognize it.
*
* A request with neither is a person acting directly (the web app, a script, a
* personal access token) and resolves to `null`.
*/
import type { Request } from "express";

import type {
AuthOAuthPayload,
AuthPATPayload,
AuthProjectPayload,
} from "@/auth/payload";
import { getKnownApp } from "@/oauth/known-apps";

import {
isAgentId,
resolveReportedAgentId,
UNKNOWN_AGENT_ID,
} from "./registry";

/**
* The `agent/<name>` product token of a `User-Agent`. The CLI already
* sanitizes the name into an HTTP token, and this only accepts that shape, so a
* hand-crafted header can't smuggle anything else through.
*/
const AGENT_TOKEN_REGEX = /(?:^|\s)agent\/([\w.@-]{1,64})(?:\s|$)/i;

/** The agent name a `User-Agent` reports, if it reports one. */
export function parseUserAgentAgentName(
userAgent: string | undefined,
): string | null {
const match = userAgent ? AGENT_TOKEN_REGEX.exec(userAgent) : null;
return match?.[1] ?? null;
}

type RequestAuth =
| AuthProjectPayload
| AuthPATPayload
| AuthOAuthPayload
| null;

/**
* Resolve the agent behind a request to a registry id, or `null` when a person
* made it directly.
*
* The `User-Agent` wins over the OAuth client: an agent driving the CLI is more
* specific than "the CLI", which is the only thing the client id says.
*/
export function resolveRequestAgentId(
request: Request,
auth: RequestAuth,
): string | null {
const reported = parseUserAgentAgentName(request.get("user-agent"));
if (reported) {
return resolveReportedAgentId(reported);
}

if (auth?.type !== "oauth") {
return null;
}

// A first-party client id we control (`argos-cli`) names the tool, not an
// agent — an agent driving it identifies itself in the `User-Agent` above.
const knownApp = getKnownApp(auth.knownAppId);
if (knownApp && !isAgentId(knownApp.id)) {
return null;
}

return knownApp?.id ?? UNKNOWN_AGENT_ID;
}
Loading