Skip to content

Commit 01d10cd

Browse files
gregbergeclaude
andauthored
feat(cli): identify the coding agent driving the CLI (#367)
Argos cannot tell a command a person typed from one an agent ran on their behalf — the token signing the request is the same either way. Detect the agent with @vercel/detect-agent and send it as an `agent/<name>` token in the User-Agent, so the API can attribute the action to it. Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
1 parent 222412b commit 01d10cd

8 files changed

Lines changed: 237 additions & 5 deletions

File tree

‎packages/api-client/src/index.test.ts‎

Lines changed: 49 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,53 @@
1-
import { describe, expect, it } from "vitest";
1+
import { afterEach, describe, expect, it, vi } from "vitest";
22
import { APIError } from "./fetch";
3-
import { formatAPIError, throwAPIError } from "./index";
3+
import {
4+
createClient,
5+
formatAPIError,
6+
throwAPIError,
7+
type UserAgentOption,
8+
} from "./index";
9+
10+
describe("createClient", () => {
11+
afterEach(() => {
12+
vi.unstubAllGlobals();
13+
});
14+
15+
/**
16+
* Stub the global fetch (what `apiFetch` ultimately calls) and return the
17+
* `User-Agent` of the request it received.
18+
*/
19+
async function getSentUserAgent(
20+
userAgent: UserAgentOption,
21+
): Promise<string | null> {
22+
const fetchMock = vi.fn<(request: Request) => Promise<Response>>(
23+
async () => new Response("{}", { status: 200 }),
24+
);
25+
vi.stubGlobal("fetch", fetchMock);
26+
const client = createClient({
27+
baseUrl: "https://api.argos-ci.test/v2/",
28+
userAgent,
29+
});
30+
await client.GET("/me");
31+
const request = fetchMock.mock.calls[0]?.[0];
32+
return request?.headers.get("user-agent") ?? null;
33+
}
34+
35+
it("sends a static User-Agent", async () => {
36+
await expect(getSentUserAgent("argos-cli/6.7.0")).resolves.toBe(
37+
"argos-cli/6.7.0",
38+
);
39+
});
40+
41+
it("resolves a User-Agent supplied as an async function", async () => {
42+
await expect(
43+
getSentUserAgent(async () => "argos-cli/6.7.0 agent/claude"),
44+
).resolves.toBe("argos-cli/6.7.0 agent/claude");
45+
});
46+
47+
it("leaves the header alone when the resolver has no value yet", async () => {
48+
await expect(getSentUserAgent(() => undefined)).resolves.toBeNull();
49+
});
50+
});
451

552
describe("formatAPIError", () => {
653
it("formats a structured API error", () => {

‎packages/api-client/src/index.ts‎

Lines changed: 30 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,20 +8,48 @@ export { APIError } from "./fetch";
88

99
export type ArgosAPIClient = ReturnType<typeof createClient>;
1010

11+
/**
12+
* A `User-Agent` value, or a resolver for it. The resolver may be async and is
13+
* called per request, so a caller that only learns its identity asynchronously
14+
* (the CLI detecting the coding agent driving it) does not have to await that
15+
* before it can build a client.
16+
*/
17+
export type UserAgentOption =
18+
string | (() => string | undefined | Promise<string | undefined>);
19+
20+
/**
21+
* Wrap {@link apiFetch} so every request carries a `User-Agent`.
22+
*
23+
* The header is set on the request openapi-fetch just built for this call — no
24+
* one else observes it — and `apiFetch` copies the headers before retrying, so
25+
* every attempt keeps the value.
26+
*/
27+
function createUserAgentFetch(userAgent: UserAgentOption): typeof apiFetch {
28+
return async (input, options) => {
29+
const value =
30+
typeof userAgent === "function" ? await userAgent() : userAgent;
31+
if (value) {
32+
input.headers.set("user-agent", value);
33+
}
34+
return apiFetch(input, options);
35+
};
36+
}
37+
1138
/**
1239
* Create Argos API client.
1340
*/
1441
export function createClient(options?: {
1542
baseUrl?: string;
1643
authToken?: string;
44+
userAgent?: UserAgentOption;
1745
}) {
18-
const { baseUrl, authToken } = options || {};
46+
const { baseUrl, authToken, userAgent } = options || {};
1947
return createFetchClient<paths>({
2048
baseUrl: baseUrl || "https://api.argos-ci.com/v2/",
2149
headers: {
2250
Authorization: authToken ? `Bearer ${authToken}` : undefined,
2351
},
24-
fetch: apiFetch,
52+
fetch: userAgent ? createUserAgentFetch(userAgent) : apiFetch,
2553
});
2654
}
2755

‎packages/cli/package.json‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,7 @@
3636
"dependencies": {
3737
"@argos-ci/api-client": "workspace:*",
3838
"@argos-ci/core": "workspace:*",
39+
"@vercel/detect-agent": "^1.2.5",
3940
"commander": "^15.0.0",
4041
"open": "^11.0.0",
4142
"ora": "^9.4.1"

‎packages/cli/src/index.ts‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,12 +20,17 @@ import { testCommand } from "./commands/test";
2020
import { accountCommand } from "./commands/account";
2121
import { projectCommand } from "./commands/project";
2222
import { automationCommand } from "./commands/automation";
23+
import { initUserAgent } from "./lib/user-agent";
2324

2425
const __dirname = fileURLToPath(new URL(".", import.meta.url));
2526

2627
const rawPkg = await readFile(resolve(__dirname, "..", "package.json"), "utf8");
2728
const pkg = JSON.parse(rawPkg);
2829

30+
// Detect the coding agent driving the CLI, if any, before any command runs, so
31+
// every API request identifies it.
32+
await initUserAgent(pkg.version);
33+
2934
program
3035
.name(pkg.name)
3136
.description(

‎packages/cli/src/lib/api.ts‎

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,14 +5,22 @@ import {
55
type ArgosAPIClient,
66
} from "@argos-ci/api-client";
77

8+
import { getUserAgent } from "./user-agent";
9+
810
/** Optional override for the API base URL (used in tests and dev). */
911
export function getApiBaseUrl(): string | undefined {
1012
return process.env["ARGOS_API_BASE_URL"];
1113
}
1214

1315
/** Create an Argos API client authenticated with the given token. */
1416
export function createApiClient(authToken?: string): ArgosAPIClient {
15-
return createClient({ authToken, baseUrl: getApiBaseUrl() });
17+
return createClient({
18+
authToken,
19+
baseUrl: getApiBaseUrl(),
20+
// Read per request rather than captured here: agent detection is async and
21+
// resolves at startup, while clients are built synchronously all over.
22+
userAgent: getUserAgent,
23+
});
1624
}
1725

1826
/**
Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
import { describe, expect, it } from "vitest";
2+
import { formatUserAgent } from "./user-agent";
3+
4+
const NODE = `node/${process.versions.node}`;
5+
6+
describe("formatUserAgent", () => {
7+
it("identifies the CLI and the runtime", () => {
8+
expect(formatUserAgent({ version: "6.7.0" })).toBe(
9+
`argos-cli/6.7.0 ${NODE}`,
10+
);
11+
});
12+
13+
it("appends the agent when one drives the CLI", () => {
14+
expect(formatUserAgent({ version: "6.7.0", agent: "claude" })).toBe(
15+
`argos-cli/6.7.0 ${NODE} agent/claude`,
16+
);
17+
});
18+
19+
it.each([
20+
["Claude Code", "claude-code"],
21+
[" cursor-cli ", "cursor-cli"],
22+
["custom-agent@2.0", "custom-agent@2.0"],
23+
["MyAgent/1.0", "myagent-1.0"],
24+
["évadé", "vad"],
25+
])("normalizes %j into a header token", (agent, expected) => {
26+
expect(formatUserAgent({ version: "6.7.0", agent })).toBe(
27+
`argos-cli/6.7.0 ${NODE} agent/${expected}`,
28+
);
29+
});
30+
31+
it("truncates an overlong agent name", () => {
32+
const agent = "a".repeat(200);
33+
expect(formatUserAgent({ version: "6.7.0", agent })).toBe(
34+
`argos-cli/6.7.0 ${NODE} agent/${"a".repeat(64)}`,
35+
);
36+
});
37+
38+
it.each([
39+
["not set", undefined],
40+
["null", null],
41+
["empty", ""],
42+
["only separators", " -- "],
43+
["nothing usable", "🤖"],
44+
])("omits the agent token when it is %s", (_label, agent) => {
45+
expect(formatUserAgent({ version: "6.7.0", agent })).toBe(
46+
`argos-cli/6.7.0 ${NODE}`,
47+
);
48+
});
49+
50+
it("never emits a value that could inject a header", () => {
51+
const agent = "evil\r\nX-Injected: 1";
52+
expect(formatUserAgent({ version: "6.7.0", agent })).toBe(
53+
`argos-cli/6.7.0 ${NODE} agent/evil-x-injected-1`,
54+
);
55+
});
56+
});

‎packages/cli/src/lib/user-agent.ts‎

Lines changed: 78 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,78 @@
1+
import { determineAgent } from "@vercel/detect-agent";
2+
3+
/**
4+
* The `User-Agent` the CLI sends on every API request.
5+
*
6+
* Beyond the usual product token, it carries an `agent/<name>` token when a
7+
* coding agent is driving the CLI. That token is the only thing telling the API
8+
* apart a command a person typed from one an agent ran on their behalf — the
9+
* token signing the request is the same either way — and is what lets Argos
10+
* mark the resulting comment as agent-made.
11+
*/
12+
13+
/** Product token of the CLI itself, e.g. `argos-cli/6.7.0`. */
14+
const PRODUCT = "argos-cli";
15+
16+
/**
17+
* Longest agent name we forward. `AI_AGENT` is free-form, so a caller could put
18+
* anything in it; the API only needs enough to recognize the agent.
19+
*/
20+
const MAX_AGENT_LENGTH = 64;
21+
22+
/**
23+
* Reduce an agent name to a `token` as the HTTP grammar defines it (RFC 9110
24+
* §5.6.2), lowercased.
25+
*
26+
* `@vercel/detect-agent` returns the `AI_AGENT` environment variable verbatim
27+
* when it is set, so the value is user input: anything outside the allowed set —
28+
* spaces, and control characters that would otherwise let it inject a header —
29+
* becomes a hyphen. Returns `null` when nothing usable is left.
30+
*/
31+
function sanitizeAgentName(name: string): string | null {
32+
const sanitized = name
33+
.trim()
34+
.toLowerCase()
35+
.slice(0, MAX_AGENT_LENGTH)
36+
.replaceAll(/[^a-z0-9.@_-]+/g, "-")
37+
.replace(/^-+|-+$/g, "");
38+
return sanitized || null;
39+
}
40+
41+
/**
42+
* Format the `User-Agent` value, e.g.
43+
* `argos-cli/6.7.0 node/22.11.0 agent/claude`.
44+
*/
45+
export function formatUserAgent(input: {
46+
version: string;
47+
agent?: string | null | undefined;
48+
}): string {
49+
const tokens = [
50+
`${PRODUCT}/${input.version}`,
51+
`node/${process.versions.node}`,
52+
];
53+
const agent = input.agent ? sanitizeAgentName(input.agent) : null;
54+
if (agent) {
55+
tokens.push(`agent/${agent}`);
56+
}
57+
return tokens.join(" ");
58+
}
59+
60+
let userAgent: string | undefined;
61+
62+
/**
63+
* Detect the agent driving the CLI and build the `User-Agent` from it, once per
64+
* process. Called at startup, before any command runs.
65+
*/
66+
export async function initUserAgent(version: string): Promise<void> {
67+
const { agent } = await determineAgent();
68+
userAgent = formatUserAgent({ version, agent: agent?.name });
69+
}
70+
71+
/**
72+
* The `User-Agent` for API requests, `undefined` until {@link initUserAgent} has
73+
* run — the API client then falls back to the runtime's own default rather than
74+
* claiming a version we do not know.
75+
*/
76+
export function getUserAgent(): string | undefined {
77+
return userAgent;
78+
}

‎pnpm-lock.yaml‎

Lines changed: 9 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

0 commit comments

Comments
 (0)