From 34a451db0f5039b1f6d150e5bd8ee87b5a833d4c Mon Sep 17 00:00:00 2001 From: Rob E Date: Fri, 13 Nov 2026 09:28:36 +1000 Subject: [PATCH 1/8] feat: detect AI coding agents in the user agent Report the AI agent driving the client as its own User-Agent token, between the library and the requesting app: ts-octopusdeploy AIAgent/ClaudeCode GitHubActions (release;deploy;v3) Callers that know the agent from a protocol, such as an MCP server with the connected client's clientInfo, can pass it as `aiAgent` in the client configuration. That takes precedence over AI_AGENT, which takes precedence over vendor-specific environment variables. Only a normalised agent name is sent. The agent list is ported from go-octopusdeploy, which is the reference implementation. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01T4ijpGHFpAqBBMhn5WKUq2 --- src/adapters/axiosAdapter.ts | 7 +- src/adapters/createUserAgent.test.ts | 25 ++++++ src/adapters/createUserAgent.ts | 6 ++ src/aiAgent.test.ts | 103 +++++++++++++++++++++++++ src/aiAgent.ts | 109 +++++++++++++++++++++++++++ src/clientConfiguration.ts | 6 ++ 6 files changed, 251 insertions(+), 5 deletions(-) create mode 100644 src/adapters/createUserAgent.test.ts create mode 100644 src/adapters/createUserAgent.ts create mode 100644 src/aiAgent.test.ts create mode 100644 src/aiAgent.ts diff --git a/src/adapters/axiosAdapter.ts b/src/adapters/axiosAdapter.ts index 3392f60..0b0a150 100644 --- a/src/adapters/axiosAdapter.ts +++ b/src/adapters/axiosAdapter.ts @@ -4,6 +4,7 @@ import type { Adapter, AdapterResponse } from "../adapter"; import { AdapterError } from "../adapter"; import { ClientOptions } from "../clientOptions"; import { createRequestHeaders } from "./createRequestHeaders"; +import { createUserAgent } from "./createUserAgent"; export class AxiosAdapter implements Adapter { public async execute(options: ClientOptions): Promise> { @@ -21,11 +22,7 @@ export class AxiosAdapter implements Adapter { }; if (typeof XMLHttpRequest === "undefined") { if (config.headers) { - let userAgent = "ts-octopusdeploy"; - if (options.configuration.userAgentApp) { - userAgent = `${userAgent} ${options.configuration.userAgentApp}`; - } - config.headers["User-Agent"] = userAgent; + config.headers["User-Agent"] = createUserAgent(options.configuration); } } const response = await axios.request(config); diff --git a/src/adapters/createUserAgent.test.ts b/src/adapters/createUserAgent.test.ts new file mode 100644 index 0000000..45c7dfa --- /dev/null +++ b/src/adapters/createUserAgent.test.ts @@ -0,0 +1,25 @@ +import { ClientConfiguration } from "../clientConfiguration"; +import { createUserAgent } from "./createUserAgent"; + +describe("createUserAgent", () => { + const configuration: ClientConfiguration = { + instanceURL: "https://my.octopus.app", + userAgentApp: "GitHubActions (release;deploy;v3)", + }; + + test("is unchanged when no agent is detected", () => { + expect(createUserAgent(configuration, {})).toBe("ts-octopusdeploy GitHubActions (release;deploy;v3)"); + }); + + test("places the agent between the library and the requesting app", () => { + expect(createUserAgent(configuration, { CLAUDECODE: "1" })).toBe("ts-octopusdeploy AIAgent/ClaudeCode GitHubActions (release;deploy;v3)"); + }); + + test("uses the caller-supplied agent", () => { + expect(createUserAgent({ ...configuration, aiAgent: "claude-code" }, {})).toBe("ts-octopusdeploy AIAgent/ClaudeCode GitHubActions (release;deploy;v3)"); + }); + + test("omits an empty requesting app", () => { + expect(createUserAgent({ ...configuration, userAgentApp: "" }, {})).toBe("ts-octopusdeploy"); + }); +}); diff --git a/src/adapters/createUserAgent.ts b/src/adapters/createUserAgent.ts new file mode 100644 index 0000000..56c39ca --- /dev/null +++ b/src/adapters/createUserAgent.ts @@ -0,0 +1,6 @@ +import { getAiAgentUserAgentToken } from "../aiAgent"; +import type { ClientConfiguration } from "../clientConfiguration"; + +export function createUserAgent(configuration: ClientConfiguration, env?: Record): string { + return ["ts-octopusdeploy", getAiAgentUserAgentToken(configuration.aiAgent, env), configuration.userAgentApp].filter((part) => !!part).join(" "); +} diff --git a/src/aiAgent.test.ts b/src/aiAgent.test.ts new file mode 100644 index 0000000..7bfb313 --- /dev/null +++ b/src/aiAgent.test.ts @@ -0,0 +1,103 @@ +import { getAiAgentUserAgentToken } from "./aiAgent"; + +describe("getAiAgentUserAgentToken", () => { + test("returns undefined when no agent is detected", () => { + expect(getAiAgentUserAgentToken(undefined, {})).toBeUndefined(); + }); + + test.each([ + ["CLAUDECODE", "1", "AIAgent/ClaudeCode"], + ["CLAUDE_CODE_ENTRYPOINT", "cli", "AIAgent/ClaudeCode"], + ["CURSOR_AGENT", "1", "AIAgent/Cursor"], + ["CURSOR_EXTENSION_HOST_ROLE", "agent-exec", "AIAgent/Cursor"], + ["CODEX_SANDBOX", "seatbelt", "AIAgent/Codex"], + ["CODEX_THREAD_ID", "abc", "AIAgent/Codex"], + ["GEMINI_CLI", "1", "AIAgent/GeminiCLI"], + ["COPILOT_CLI", "1", "AIAgent/GitHubCopilot"], + ["OPENCODE", "1", "AIAgent/OpenCode"], + ["OPENCODE_CLIENT", "cli", "AIAgent/OpenCode"], + ["ANTIGRAVITY_AGENT", "1", "AIAgent/Antigravity"], + ["GOOSE_TERMINAL", "1", "AIAgent/Goose"], + ["AGENT", "goose", "AIAgent/Goose"], + ["AGENT", "amp", "AIAgent/Amp"], + ["CLINE_ACTIVE", "true", "AIAgent/Cline"], + ["ROO_CODE_TASK_ID", "abc", "AIAgent/RooCode"], + ["AUGMENT_AGENT", "1", "AIAgent/Augment"], + ["QWEN_CODE", "1", "AIAgent/QwenCode"], + ["DROID_CLI", "1", "AIAgent/FactoryDroid"], + ["KIMI_CLI", "1", "AIAgent/KimiCLI"], + ["TRAE_AI_SHELL_ID", "abc", "AIAgent/Trae"], + ["OR_APP_NAME", "aider", "AIAgent/Aider"], + ["OR_APP_NAME", "OpenHands", "AIAgent/OpenHands"], + ])("detects %s=%s as %s", (variable, value, expected) => { + expect(getAiAgentUserAgentToken(undefined, { [variable]: value })).toBe(expected); + }); + + test.each([ + ["CURSOR_EXTENSION_HOST_ROLE", "user"], + ["OPENCODE", "0"], + ["AGENT", "teamcity-agent-01"], + ["OR_APP_NAME", "SomethingElse"], + ])("requires a matching value for %s", (variable, value) => { + expect(getAiAgentUserAgentToken(undefined, { [variable]: value })).toBeUndefined(); + }); + + test.each(["CURSOR_TRACE_ID", "COPILOT_GITHUB_TOKEN", "GOOSE_PROVIDER", "REPL_ID", "ZED_TERM"])("ignores %s, which is set without an agent", (variable) => { + expect(getAiAgentUserAgentToken(undefined, { [variable]: "1" })).toBeUndefined(); + }); + + test("the first known agent wins when agents are nested", () => { + expect(getAiAgentUserAgentToken(undefined, { CURSOR_AGENT: "1", CLAUDECODE: "1" })).toBe("AIAgent/ClaudeCode"); + }); + + test.each([ + ["claude-code_2-1-322_agent", "AIAgent/ClaudeCode"], + ["claude-code", "AIAgent/ClaudeCode"], + ["Claude-Code", "AIAgent/ClaudeCode"], + ["cursor-cli", "AIAgent/Cursor"], + ["github_copilot_vscode_agent", "AIAgent/GitHubCopilot"], + ["github-copilot-cli", "AIAgent/GitHubCopilot"], + ["devin@1", "AIAgent/Devin"], + ["custom-agent@2.0", "AIAgent/Other"], + ])("maps AI_AGENT=%s to %s", (value, expected) => { + expect(getAiAgentUserAgentToken(undefined, { AI_AGENT: value })).toBe(expected); + }); + + test("AI_AGENT takes precedence over vendor variables", () => { + expect(getAiAgentUserAgentToken(undefined, { CURSOR_AGENT: "1", AI_AGENT: "claude-code_2-1-322_agent" })).toBe("AIAgent/ClaudeCode"); + }); + + test("an unrecognised AI_AGENT falls back to the vendor name", () => { + expect(getAiAgentUserAgentToken(undefined, { GEMINI_CLI: "1", AI_AGENT: "gcli" })).toBe("AIAgent/GeminiCLI"); + }); + + test.each([ + [" evil) agent\r\nX-Injected: 1 ", "AIAgent/Other"], + [" \t ", undefined], + ])("never includes the raw AI_AGENT value (%j)", (value, expected) => { + expect(getAiAgentUserAgentToken(undefined, { AI_AGENT: value })).toBe(expected); + }); + + describe("caller-supplied agent", () => { + test("is mapped to a known name", () => { + expect(getAiAgentUserAgentToken("claude-code", {})).toBe("AIAgent/ClaudeCode"); + }); + + test("takes precedence over AI_AGENT and vendor variables", () => { + expect(getAiAgentUserAgentToken("cursor-vscode", { AI_AGENT: "claude-code", CLAUDECODE: "1" })).toBe("AIAgent/Cursor"); + }); + + test("falls back to AI_AGENT, then vendor variables, when not recognised", () => { + expect(getAiAgentUserAgentToken("some-mcp-client", { AI_AGENT: "claude-code" })).toBe("AIAgent/ClaudeCode"); + expect(getAiAgentUserAgentToken("some-mcp-client", { CLAUDECODE: "1" })).toBe("AIAgent/ClaudeCode"); + }); + + test("reports as Other when nothing is recognised", () => { + expect(getAiAgentUserAgentToken("some-mcp-client", {})).toBe("AIAgent/Other"); + }); + + test("matches names containing spaces", () => { + expect(getAiAgentUserAgentToken("Claude Code", {})).toBe("AIAgent/ClaudeCode"); + }); + }); +}); diff --git a/src/aiAgent.ts b/src/aiAgent.ts new file mode 100644 index 0000000..b4ae1ef --- /dev/null +++ b/src/aiAgent.ts @@ -0,0 +1,109 @@ +// The agent list is maintained in go-octopusdeploy and ported from there; keep in sync. +// https://github.com/OctopusDeploy/go-octopusdeploy/blob/main/pkg/services/api/ai_agent_provider.go +// +// Detection relies on self-reported values, so it is suitable for analytics but must not be relied on for +// security decisions. + +type EnvironmentVariables = Record; + +interface AgentRule { + variable: string; + // When set, the variable's value must match (case-insensitive). Otherwise any non-empty value matches. + value?: string; +} + +// The emerging cross-vendor convention for an agent to identify itself. +// https://github.com/vercel/vercel/tree/main/packages/detect-agent +const aiAgentVariable = "AI_AGENT"; + +const otherAgentName = "Other"; + +// Ordered: the first agent with a matching rule wins, so the result is deterministic when several agents' +// variables are present (e.g. one agent running another). +// +// Variables that are commonly present without an agent driving the process are deliberately excluded: +// CURSOR_TRACE_ID (any Cursor terminal), COPILOT_GITHUB_TOKEN and GOOSE_PROVIDER (user configuration), +// REPL_ID (any Replit workspace) and ZED_TERM (any Zed terminal). +const knownAgents: ReadonlyArray<{ name: string; rules: AgentRule[] }> = [ + { name: "ClaudeCode", rules: [{ variable: "CLAUDECODE" }, { variable: "CLAUDE_CODE_ENTRYPOINT" }] }, + { name: "Cursor", rules: [{ variable: "CURSOR_AGENT" }, { variable: "CURSOR_EXTENSION_HOST_ROLE", value: "agent-exec" }] }, + { name: "Codex", rules: [{ variable: "CODEX_SANDBOX" }, { variable: "CODEX_THREAD_ID" }, { variable: "CODEX_CI" }] }, + { name: "GeminiCLI", rules: [{ variable: "GEMINI_CLI" }] }, + { name: "GitHubCopilot", rules: [{ variable: "COPILOT_CLI" }, { variable: "COPILOT_AGENT" }, { variable: "GITHUB_COPILOT_CLI_MODE" }] }, + { name: "OpenCode", rules: [{ variable: "OPENCODE", value: "1" }, { variable: "OPENCODE_CLIENT" }, { variable: "OPENCODE_AI" }] }, + { name: "Antigravity", rules: [{ variable: "ANTIGRAVITY_AGENT" }] }, + { name: "Goose", rules: [{ variable: "GOOSE_TERMINAL" }, { variable: "AGENT", value: "goose" }] }, + { name: "Amp", rules: [{ variable: "AGENT", value: "amp" }] }, + { name: "Cline", rules: [{ variable: "CLINE_ACTIVE" }, { variable: "CLINE_TASK_ID" }] }, + { name: "RooCode", rules: [{ variable: "ROO_CODE_TASK_ID" }] }, + { name: "Augment", rules: [{ variable: "AUGMENT_AGENT" }] }, + { name: "QwenCode", rules: [{ variable: "QWEN_CODE" }] }, + { name: "FactoryDroid", rules: [{ variable: "DROID_CLI" }] }, + { name: "KimiCLI", rules: [{ variable: "KIMI_CLI" }] }, + { name: "Trae", rules: [{ variable: "TRAE_AI_SHELL_ID" }] }, + { name: "Aider", rules: [{ variable: "OR_APP_NAME", value: "Aider" }] }, + { name: "OpenHands", rules: [{ variable: "OR_APP_NAME", value: "OpenHands" }] }, +]; + +// Maps the start of a normalised self-reported agent identifier to a known agent name. Vendors don't agree on a +// format (e.g. "claude-code_2-1-322_agent", "github_copilot_vscode_agent", "devin@1"), so values are lowercased +// and underscores and spaces replaced with hyphens before matching. +const agentNamePrefixes: ReadonlyArray<{ prefix: string; name: string }> = [ + { prefix: "claude-code", name: "ClaudeCode" }, + { prefix: "cursor", name: "Cursor" }, + { prefix: "codex", name: "Codex" }, + { prefix: "gemini", name: "GeminiCLI" }, + { prefix: "github-copilot", name: "GitHubCopilot" }, + { prefix: "opencode", name: "OpenCode" }, + { prefix: "antigravity", name: "Antigravity" }, + { prefix: "goose", name: "Goose" }, + { prefix: "amp", name: "Amp" }, + { prefix: "cline", name: "Cline" }, + { prefix: "augment", name: "Augment" }, + { prefix: "devin", name: "Devin" }, + { prefix: "replit", name: "Replit" }, + { prefix: "v0", name: "V0" }, +]; + +/** + * Returns a User-Agent token naming the AI agent driving this client (e.g. "AIAgent/ClaudeCode"), or undefined + * when none is detected. + * + * Self-reported identifiers are checked first, in order: an identifier supplied by the caller (for example an MCP + * server passing the connected client's `clientInfo.name`), then the `AI_AGENT` environment variable. If neither is + * recognised, vendor-specific environment variables are checked. An identifier that is present but not recognised + * reports as "AIAgent/Other". Only the normalised name is reported: raw identifiers are free-form, so they are used + * for matching and never included in the output. + */ +export function getAiAgentUserAgentToken(callerSuppliedAgent?: string, env: EnvironmentVariables = readProcessEnvironment()): string | undefined { + const selfReported = [callerSuppliedAgent, env[aiAgentVariable]].map((value) => value?.trim()).filter((value): value is string => !!value); + + const name = + selfReported.map(nameFromIdentifier).find((n): n is string => n !== undefined) ?? + nameFromVendorVariables(env) ?? + (selfReported.length > 0 ? otherAgentName : undefined); + + return name ? `AIAgent/${name}` : undefined; +} + +function nameFromIdentifier(identifier: string): string | undefined { + const normalised = identifier.toLowerCase().replace(/[_\s]+/g, "-"); + return agentNamePrefixes.find((p) => normalised.startsWith(p.prefix))?.name; +} + +function nameFromVendorVariables(env: EnvironmentVariables): string | undefined { + return knownAgents.find((agent) => + agent.rules.some((rule) => { + const value = env[rule.variable]; + if (!value) { + return false; + } + return rule.value === undefined || value.toLowerCase() === rule.value.toLowerCase(); + }) + )?.name; +} + +function readProcessEnvironment(): EnvironmentVariables { + // The client also runs in browsers, where there is no process environment to read. + return typeof process !== "undefined" && process.env ? process.env : {}; +} diff --git a/src/clientConfiguration.ts b/src/clientConfiguration.ts index 04e3440..04a5c3c 100644 --- a/src/clientConfiguration.ts +++ b/src/clientConfiguration.ts @@ -3,6 +3,12 @@ import { Logger } from "./logger"; export interface ClientConfiguration { userAgentApp: string; + /** + * Identifies the AI agent driving this client, when the caller knows it. For example, an MCP server can pass + * the connected client's `clientInfo.name`. It is mapped to a known agent name for the User-Agent header and + * takes precedence over agents detected from environment variables. The raw value is never sent. + */ + aiAgent?: string; httpsAgent?: Agent; apiKey?: string; accessToken?: string; From 6548877b7a7d4d0e2dae8948b99eb418714bd76b Mon Sep 17 00:00:00 2001 From: Rob E Date: Fri, 13 Nov 2026 09:41:19 +1000 Subject: [PATCH 2/8] remove unecessary comments --- src/clientConfiguration.ts | 5 ----- 1 file changed, 5 deletions(-) diff --git a/src/clientConfiguration.ts b/src/clientConfiguration.ts index 04a5c3c..18dbf8a 100644 --- a/src/clientConfiguration.ts +++ b/src/clientConfiguration.ts @@ -3,11 +3,6 @@ import { Logger } from "./logger"; export interface ClientConfiguration { userAgentApp: string; - /** - * Identifies the AI agent driving this client, when the caller knows it. For example, an MCP server can pass - * the connected client's `clientInfo.name`. It is mapped to a known agent name for the User-Agent header and - * takes precedence over agents detected from environment variables. The raw value is never sent. - */ aiAgent?: string; httpsAgent?: Agent; apiKey?: string; From ce0cc05beae8771e15914be18985e3ccf9819f13 Mon Sep 17 00:00:00 2001 From: Rob E Date: Thu, 19 Nov 2026 06:13:20 +1000 Subject: [PATCH 3/8] refactor: list each AI agent once Merge the identifier prefix table into the agent list so each agent is one entry, keeping two lookups (prefix, then vendor variables) so a self-reported identity still wins. Replace the chained fallback with an explicit return. Behaviour is unchanged, matching review on the .NET port. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01T4ijpGHFpAqBBMhn5WKUq2 --- src/aiAgent.ts | 106 +++++++++++++++++++++++++------------------------ 1 file changed, 55 insertions(+), 51 deletions(-) diff --git a/src/aiAgent.ts b/src/aiAgent.ts index b4ae1ef..f5294ba 100644 --- a/src/aiAgent.ts +++ b/src/aiAgent.ts @@ -18,51 +18,54 @@ const aiAgentVariable = "AI_AGENT"; const otherAgentName = "Other"; -// Ordered: the first agent with a matching rule wins, so the result is deterministic when several agents' -// variables are present (e.g. one agent running another). +interface KnownAgent { + name: string; + // When set, matches the start of a normalised self-reported identifier. Vendors don't agree on a format + // (e.g. "claude-code_2-1-322_agent", "github_copilot_vscode_agent", "devin@1"), so identifiers are lowercased + // and runs of underscores and whitespace replaced with a single hyphen before matching. + aiAgentPrefix?: string; + // Vendor-specific environment variables that identify the agent. + variables?: AgentRule[]; +} + +// Each agent is listed once, and can be recognised from a self-reported identifier (by prefix), from its vendor +// variables, or both. Self-reported identifiers are checked against the whole list before any vendor variables, so a +// self-reported identity wins (e.g. Claude Code running inside Cursor). Within each lookup the first match wins, so +// the result is deterministic when several agents' variables are present. // // Variables that are commonly present without an agent driving the process are deliberately excluded: // CURSOR_TRACE_ID (any Cursor terminal), COPILOT_GITHUB_TOKEN and GOOSE_PROVIDER (user configuration), // REPL_ID (any Replit workspace) and ZED_TERM (any Zed terminal). -const knownAgents: ReadonlyArray<{ name: string; rules: AgentRule[] }> = [ - { name: "ClaudeCode", rules: [{ variable: "CLAUDECODE" }, { variable: "CLAUDE_CODE_ENTRYPOINT" }] }, - { name: "Cursor", rules: [{ variable: "CURSOR_AGENT" }, { variable: "CURSOR_EXTENSION_HOST_ROLE", value: "agent-exec" }] }, - { name: "Codex", rules: [{ variable: "CODEX_SANDBOX" }, { variable: "CODEX_THREAD_ID" }, { variable: "CODEX_CI" }] }, - { name: "GeminiCLI", rules: [{ variable: "GEMINI_CLI" }] }, - { name: "GitHubCopilot", rules: [{ variable: "COPILOT_CLI" }, { variable: "COPILOT_AGENT" }, { variable: "GITHUB_COPILOT_CLI_MODE" }] }, - { name: "OpenCode", rules: [{ variable: "OPENCODE", value: "1" }, { variable: "OPENCODE_CLIENT" }, { variable: "OPENCODE_AI" }] }, - { name: "Antigravity", rules: [{ variable: "ANTIGRAVITY_AGENT" }] }, - { name: "Goose", rules: [{ variable: "GOOSE_TERMINAL" }, { variable: "AGENT", value: "goose" }] }, - { name: "Amp", rules: [{ variable: "AGENT", value: "amp" }] }, - { name: "Cline", rules: [{ variable: "CLINE_ACTIVE" }, { variable: "CLINE_TASK_ID" }] }, - { name: "RooCode", rules: [{ variable: "ROO_CODE_TASK_ID" }] }, - { name: "Augment", rules: [{ variable: "AUGMENT_AGENT" }] }, - { name: "QwenCode", rules: [{ variable: "QWEN_CODE" }] }, - { name: "FactoryDroid", rules: [{ variable: "DROID_CLI" }] }, - { name: "KimiCLI", rules: [{ variable: "KIMI_CLI" }] }, - { name: "Trae", rules: [{ variable: "TRAE_AI_SHELL_ID" }] }, - { name: "Aider", rules: [{ variable: "OR_APP_NAME", value: "Aider" }] }, - { name: "OpenHands", rules: [{ variable: "OR_APP_NAME", value: "OpenHands" }] }, -]; - -// Maps the start of a normalised self-reported agent identifier to a known agent name. Vendors don't agree on a -// format (e.g. "claude-code_2-1-322_agent", "github_copilot_vscode_agent", "devin@1"), so values are lowercased -// and underscores and spaces replaced with hyphens before matching. -const agentNamePrefixes: ReadonlyArray<{ prefix: string; name: string }> = [ - { prefix: "claude-code", name: "ClaudeCode" }, - { prefix: "cursor", name: "Cursor" }, - { prefix: "codex", name: "Codex" }, - { prefix: "gemini", name: "GeminiCLI" }, - { prefix: "github-copilot", name: "GitHubCopilot" }, - { prefix: "opencode", name: "OpenCode" }, - { prefix: "antigravity", name: "Antigravity" }, - { prefix: "goose", name: "Goose" }, - { prefix: "amp", name: "Amp" }, - { prefix: "cline", name: "Cline" }, - { prefix: "augment", name: "Augment" }, - { prefix: "devin", name: "Devin" }, - { prefix: "replit", name: "Replit" }, - { prefix: "v0", name: "V0" }, +const knownAgents: ReadonlyArray = [ + { name: "ClaudeCode", aiAgentPrefix: "claude-code", variables: [{ variable: "CLAUDECODE" }, { variable: "CLAUDE_CODE_ENTRYPOINT" }] }, + { name: "Cursor", aiAgentPrefix: "cursor", variables: [{ variable: "CURSOR_AGENT" }, { variable: "CURSOR_EXTENSION_HOST_ROLE", value: "agent-exec" }] }, + { name: "Codex", aiAgentPrefix: "codex", variables: [{ variable: "CODEX_SANDBOX" }, { variable: "CODEX_THREAD_ID" }, { variable: "CODEX_CI" }] }, + { name: "GeminiCLI", aiAgentPrefix: "gemini", variables: [{ variable: "GEMINI_CLI" }] }, + { + name: "GitHubCopilot", + aiAgentPrefix: "github-copilot", + variables: [{ variable: "COPILOT_CLI" }, { variable: "COPILOT_AGENT" }, { variable: "GITHUB_COPILOT_CLI_MODE" }], + }, + { + name: "OpenCode", + aiAgentPrefix: "opencode", + variables: [{ variable: "OPENCODE", value: "1" }, { variable: "OPENCODE_CLIENT" }, { variable: "OPENCODE_AI" }], + }, + { name: "Antigravity", aiAgentPrefix: "antigravity", variables: [{ variable: "ANTIGRAVITY_AGENT" }] }, + { name: "Goose", aiAgentPrefix: "goose", variables: [{ variable: "GOOSE_TERMINAL" }, { variable: "AGENT", value: "goose" }] }, + { name: "Amp", aiAgentPrefix: "amp", variables: [{ variable: "AGENT", value: "amp" }] }, + { name: "Cline", aiAgentPrefix: "cline", variables: [{ variable: "CLINE_ACTIVE" }, { variable: "CLINE_TASK_ID" }] }, + { name: "RooCode", variables: [{ variable: "ROO_CODE_TASK_ID" }] }, + { name: "Augment", aiAgentPrefix: "augment", variables: [{ variable: "AUGMENT_AGENT" }] }, + { name: "QwenCode", variables: [{ variable: "QWEN_CODE" }] }, + { name: "FactoryDroid", variables: [{ variable: "DROID_CLI" }] }, + { name: "KimiCLI", variables: [{ variable: "KIMI_CLI" }] }, + { name: "Trae", variables: [{ variable: "TRAE_AI_SHELL_ID" }] }, + { name: "Aider", variables: [{ variable: "OR_APP_NAME", value: "Aider" }] }, + { name: "OpenHands", variables: [{ variable: "OR_APP_NAME", value: "OpenHands" }] }, + { name: "Devin", aiAgentPrefix: "devin" }, + { name: "Replit", aiAgentPrefix: "replit" }, + { name: "V0", aiAgentPrefix: "v0" }, ]; /** @@ -78,29 +81,30 @@ const agentNamePrefixes: ReadonlyArray<{ prefix: string; name: string }> = [ export function getAiAgentUserAgentToken(callerSuppliedAgent?: string, env: EnvironmentVariables = readProcessEnvironment()): string | undefined { const selfReported = [callerSuppliedAgent, env[aiAgentVariable]].map((value) => value?.trim()).filter((value): value is string => !!value); - const name = - selfReported.map(nameFromIdentifier).find((n): n is string => n !== undefined) ?? - nameFromVendorVariables(env) ?? - (selfReported.length > 0 ? otherAgentName : undefined); + // Vendor variables also cover an agent that self-reports in a format that isn't recognised. + const agent = selfReported.map(findAgentByPrefix).find((a): a is KnownAgent => a !== undefined) ?? findAgentByVariables(env); + if (agent) { + return `AIAgent/${agent.name}`; + } - return name ? `AIAgent/${name}` : undefined; + return selfReported.length > 0 ? `AIAgent/${otherAgentName}` : undefined; } -function nameFromIdentifier(identifier: string): string | undefined { +function findAgentByPrefix(identifier: string): KnownAgent | undefined { const normalised = identifier.toLowerCase().replace(/[_\s]+/g, "-"); - return agentNamePrefixes.find((p) => normalised.startsWith(p.prefix))?.name; + return knownAgents.find((agent) => agent.aiAgentPrefix !== undefined && normalised.startsWith(agent.aiAgentPrefix)); } -function nameFromVendorVariables(env: EnvironmentVariables): string | undefined { +function findAgentByVariables(env: EnvironmentVariables): KnownAgent | undefined { return knownAgents.find((agent) => - agent.rules.some((rule) => { + (agent.variables ?? []).some((rule) => { const value = env[rule.variable]; if (!value) { return false; } return rule.value === undefined || value.toLowerCase() === rule.value.toLowerCase(); }) - )?.name; + ); } function readProcessEnvironment(): EnvironmentVariables { From f115bce9984a8857fe183f2adab4bf837470a3ea Mon Sep 17 00:00:00 2001 From: Rob E Date: Thu, 19 Nov 2026 06:14:23 +1000 Subject: [PATCH 4/8] refactor: name the AI_AGENT value as in the Go and .NET clients Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01T4ijpGHFpAqBBMhn5WKUq2 --- src/aiAgent.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/aiAgent.ts b/src/aiAgent.ts index f5294ba..6a4db8e 100644 --- a/src/aiAgent.ts +++ b/src/aiAgent.ts @@ -79,7 +79,8 @@ const knownAgents: ReadonlyArray = [ * for matching and never included in the output. */ export function getAiAgentUserAgentToken(callerSuppliedAgent?: string, env: EnvironmentVariables = readProcessEnvironment()): string | undefined { - const selfReported = [callerSuppliedAgent, env[aiAgentVariable]].map((value) => value?.trim()).filter((value): value is string => !!value); + const aiAgentNameFromEnvVar = env[aiAgentVariable]; + const selfReported = [callerSuppliedAgent, aiAgentNameFromEnvVar].map((value) => value?.trim()).filter((value): value is string => !!value); // Vendor variables also cover an agent that self-reports in a format that isn't recognised. const agent = selfReported.map(findAgentByPrefix).find((a): a is KnownAgent => a !== undefined) ?? findAgentByVariables(env); From ff9343c8e7c9d96dde6210fa28a21558f78e3fb5 Mon Sep 17 00:00:00 2001 From: Rob E Date: Thu, 19 Nov 2026 07:18:36 +1000 Subject: [PATCH 5/8] test: cover AI_AGENT names containing spaces Match the Go and .NET AI_AGENT mapping cases. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01T4ijpGHFpAqBBMhn5WKUq2 --- src/aiAgent.test.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/src/aiAgent.test.ts b/src/aiAgent.test.ts index 7bfb313..b1bd734 100644 --- a/src/aiAgent.test.ts +++ b/src/aiAgent.test.ts @@ -54,6 +54,7 @@ describe("getAiAgentUserAgentToken", () => { ["claude-code_2-1-322_agent", "AIAgent/ClaudeCode"], ["claude-code", "AIAgent/ClaudeCode"], ["Claude-Code", "AIAgent/ClaudeCode"], + ["Claude Code", "AIAgent/ClaudeCode"], ["cursor-cli", "AIAgent/Cursor"], ["github_copilot_vscode_agent", "AIAgent/GitHubCopilot"], ["github-copilot-cli", "AIAgent/GitHubCopilot"], From d85d3318cb0a5d4a262083982e4e93ddc7a0083c Mon Sep 17 00:00:00 2001 From: Rob E Date: Thu, 19 Nov 2026 10:17:52 +1000 Subject: [PATCH 6/8] test: trim AI agent tests to edge cases Keep edge cases that guard real behaviour plus a happy path, and drop the per-agent table that restated the agent list. The same cases are used in the Go, .NET and TypeScript clients. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01T4ijpGHFpAqBBMhn5WKUq2 --- src/adapters/createUserAgent.test.ts | 4 -- src/aiAgent.test.ts | 58 +++++----------------------- 2 files changed, 9 insertions(+), 53 deletions(-) diff --git a/src/adapters/createUserAgent.test.ts b/src/adapters/createUserAgent.test.ts index 45c7dfa..3c5eb1b 100644 --- a/src/adapters/createUserAgent.test.ts +++ b/src/adapters/createUserAgent.test.ts @@ -18,8 +18,4 @@ describe("createUserAgent", () => { test("uses the caller-supplied agent", () => { expect(createUserAgent({ ...configuration, aiAgent: "claude-code" }, {})).toBe("ts-octopusdeploy AIAgent/ClaudeCode GitHubActions (release;deploy;v3)"); }); - - test("omits an empty requesting app", () => { - expect(createUserAgent({ ...configuration, userAgentApp: "" }, {})).toBe("ts-octopusdeploy"); - }); }); diff --git a/src/aiAgent.test.ts b/src/aiAgent.test.ts index b1bd734..9201f0e 100644 --- a/src/aiAgent.test.ts +++ b/src/aiAgent.test.ts @@ -5,44 +5,20 @@ describe("getAiAgentUserAgentToken", () => { expect(getAiAgentUserAgentToken(undefined, {})).toBeUndefined(); }); + test("detects an agent from a vendor variable", () => { + expect(getAiAgentUserAgentToken(undefined, { CLAUDECODE: "1" })).toBe("AIAgent/ClaudeCode"); + }); + test.each([ - ["CLAUDECODE", "1", "AIAgent/ClaudeCode"], - ["CLAUDE_CODE_ENTRYPOINT", "cli", "AIAgent/ClaudeCode"], - ["CURSOR_AGENT", "1", "AIAgent/Cursor"], ["CURSOR_EXTENSION_HOST_ROLE", "agent-exec", "AIAgent/Cursor"], - ["CODEX_SANDBOX", "seatbelt", "AIAgent/Codex"], - ["CODEX_THREAD_ID", "abc", "AIAgent/Codex"], - ["GEMINI_CLI", "1", "AIAgent/GeminiCLI"], - ["COPILOT_CLI", "1", "AIAgent/GitHubCopilot"], - ["OPENCODE", "1", "AIAgent/OpenCode"], - ["OPENCODE_CLIENT", "cli", "AIAgent/OpenCode"], - ["ANTIGRAVITY_AGENT", "1", "AIAgent/Antigravity"], - ["GOOSE_TERMINAL", "1", "AIAgent/Goose"], - ["AGENT", "goose", "AIAgent/Goose"], + ["CURSOR_EXTENSION_HOST_ROLE", "user", undefined], ["AGENT", "amp", "AIAgent/Amp"], - ["CLINE_ACTIVE", "true", "AIAgent/Cline"], - ["ROO_CODE_TASK_ID", "abc", "AIAgent/RooCode"], - ["AUGMENT_AGENT", "1", "AIAgent/Augment"], - ["QWEN_CODE", "1", "AIAgent/QwenCode"], - ["DROID_CLI", "1", "AIAgent/FactoryDroid"], - ["KIMI_CLI", "1", "AIAgent/KimiCLI"], - ["TRAE_AI_SHELL_ID", "abc", "AIAgent/Trae"], - ["OR_APP_NAME", "aider", "AIAgent/Aider"], - ["OR_APP_NAME", "OpenHands", "AIAgent/OpenHands"], - ])("detects %s=%s as %s", (variable, value, expected) => { + ["AGENT", "teamcity-agent-01", undefined], + ])("requires a matching value for %s=%s", (variable, value, expected) => { expect(getAiAgentUserAgentToken(undefined, { [variable]: value })).toBe(expected); }); - test.each([ - ["CURSOR_EXTENSION_HOST_ROLE", "user"], - ["OPENCODE", "0"], - ["AGENT", "teamcity-agent-01"], - ["OR_APP_NAME", "SomethingElse"], - ])("requires a matching value for %s", (variable, value) => { - expect(getAiAgentUserAgentToken(undefined, { [variable]: value })).toBeUndefined(); - }); - - test.each(["CURSOR_TRACE_ID", "COPILOT_GITHUB_TOKEN", "GOOSE_PROVIDER", "REPL_ID", "ZED_TERM"])("ignores %s, which is set without an agent", (variable) => { + test.each(["CURSOR_TRACE_ID", "COPILOT_GITHUB_TOKEN"])("ignores %s, which is set without an agent", (variable) => { expect(getAiAgentUserAgentToken(undefined, { [variable]: "1" })).toBeUndefined(); }); @@ -52,12 +28,8 @@ describe("getAiAgentUserAgentToken", () => { test.each([ ["claude-code_2-1-322_agent", "AIAgent/ClaudeCode"], - ["claude-code", "AIAgent/ClaudeCode"], - ["Claude-Code", "AIAgent/ClaudeCode"], ["Claude Code", "AIAgent/ClaudeCode"], - ["cursor-cli", "AIAgent/Cursor"], ["github_copilot_vscode_agent", "AIAgent/GitHubCopilot"], - ["github-copilot-cli", "AIAgent/GitHubCopilot"], ["devin@1", "AIAgent/Devin"], ["custom-agent@2.0", "AIAgent/Other"], ])("maps AI_AGENT=%s to %s", (value, expected) => { @@ -80,25 +52,13 @@ describe("getAiAgentUserAgentToken", () => { }); describe("caller-supplied agent", () => { - test("is mapped to a known name", () => { - expect(getAiAgentUserAgentToken("claude-code", {})).toBe("AIAgent/ClaudeCode"); - }); - test("takes precedence over AI_AGENT and vendor variables", () => { expect(getAiAgentUserAgentToken("cursor-vscode", { AI_AGENT: "claude-code", CLAUDECODE: "1" })).toBe("AIAgent/Cursor"); }); - test("falls back to AI_AGENT, then vendor variables, when not recognised", () => { + test("falls back to AI_AGENT when not recognised, and reports as Other when nothing is", () => { expect(getAiAgentUserAgentToken("some-mcp-client", { AI_AGENT: "claude-code" })).toBe("AIAgent/ClaudeCode"); - expect(getAiAgentUserAgentToken("some-mcp-client", { CLAUDECODE: "1" })).toBe("AIAgent/ClaudeCode"); - }); - - test("reports as Other when nothing is recognised", () => { expect(getAiAgentUserAgentToken("some-mcp-client", {})).toBe("AIAgent/Other"); }); - - test("matches names containing spaces", () => { - expect(getAiAgentUserAgentToken("Claude Code", {})).toBe("AIAgent/ClaudeCode"); - }); }); }); From 8387af0f55450eb42160b69e84dab2c95449a18d Mon Sep 17 00:00:00 2001 From: Rob E Date: Thu, 19 Nov 2026 14:51:09 +1000 Subject: [PATCH 7/8] fix: require a separator after an AI agent prefix A self-reported identifier now only matches an agent's prefix when the prefix is followed by the end of the identifier or a separator (-, @, .) or digit. Previously a short prefix such as "amp" matched an unrelated identifier such as "amplitude-mcp", and because self-reported identifiers take precedence, that also hid a correct match from vendor variables. Applied the same way in the Go, .NET and TypeScript clients. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01T4ijpGHFpAqBBMhn5WKUq2 --- src/aiAgent.test.ts | 1 + src/aiAgent.ts | 12 +++++++++++- 2 files changed, 12 insertions(+), 1 deletion(-) diff --git a/src/aiAgent.test.ts b/src/aiAgent.test.ts index 9201f0e..566587c 100644 --- a/src/aiAgent.test.ts +++ b/src/aiAgent.test.ts @@ -32,6 +32,7 @@ describe("getAiAgentUserAgentToken", () => { ["github_copilot_vscode_agent", "AIAgent/GitHubCopilot"], ["devin@1", "AIAgent/Devin"], ["custom-agent@2.0", "AIAgent/Other"], + ["amplitude-mcp", "AIAgent/Other"], ])("maps AI_AGENT=%s to %s", (value, expected) => { expect(getAiAgentUserAgentToken(undefined, { AI_AGENT: value })).toBe(expected); }); diff --git a/src/aiAgent.ts b/src/aiAgent.ts index 6a4db8e..e1ca1ce 100644 --- a/src/aiAgent.ts +++ b/src/aiAgent.ts @@ -93,7 +93,17 @@ export function getAiAgentUserAgentToken(callerSuppliedAgent?: string, env: Envi function findAgentByPrefix(identifier: string): KnownAgent | undefined { const normalised = identifier.toLowerCase().replace(/[_\s]+/g, "-"); - return knownAgents.find((agent) => agent.aiAgentPrefix !== undefined && normalised.startsWith(agent.aiAgentPrefix)); + return knownAgents.find((agent) => agent.aiAgentPrefix !== undefined && matchesPrefix(normalised, agent.aiAgentPrefix)); +} + +// Whether the identifier starts with the prefix followed by the end of the identifier, or by a separator ("-", "@", ".") +// or digit, so a short prefix such as "amp" doesn't match an unrelated identifier such as "amplitude-mcp". +function matchesPrefix(identifier: string, prefix: string): boolean { + if (!identifier.startsWith(prefix)) { + return false; + } + const next = identifier.charAt(prefix.length); + return next === "" || /^[-@.0-9]$/.test(next); } function findAgentByVariables(env: EnvironmentVariables): KnownAgent | undefined { From c1f7c5ff98f261cce8fb895408059837456eb447 Mon Sep 17 00:00:00 2001 From: Rob E Date: Thu, 19 Nov 2026 21:46:08 +1000 Subject: [PATCH 8/8] feat: report the AI agent as a trailing (ai-agent=Name) comment Report the agent as an RFC 9110 comment, (ai-agent=Name), appended at the very end of the User-Agent. Everything before it is byte-for-byte what the client sent before, so servers and tools that match on the start of the header keep working (Octopus Server identifies the local MCP server by the "ts-octopusdeploy octopus-mcp-server" prefix). A comment also avoids presenting the agent as a product/version pair. Applied the same way in the Go, .NET and TypeScript clients. Also ignore a caller-supplied aiAgent that isn't a string, and never fail a request if the environment can't be read. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01T4ijpGHFpAqBBMhn5WKUq2 --- src/adapters/createUserAgent.test.ts | 19 ++++++++++++---- src/adapters/createUserAgent.ts | 4 +++- src/aiAgent.test.ts | 32 +++++++++++++------------- src/aiAgent.ts | 34 ++++++++++++++++++++-------- 4 files changed, 57 insertions(+), 32 deletions(-) diff --git a/src/adapters/createUserAgent.test.ts b/src/adapters/createUserAgent.test.ts index 3c5eb1b..a3caefc 100644 --- a/src/adapters/createUserAgent.test.ts +++ b/src/adapters/createUserAgent.test.ts @@ -4,18 +4,27 @@ import { createUserAgent } from "./createUserAgent"; describe("createUserAgent", () => { const configuration: ClientConfiguration = { instanceURL: "https://my.octopus.app", - userAgentApp: "GitHubActions (release;deploy;v3)", + userAgentApp: "octopus-mcp-server/1.2.3 (claude-code/2.1.42)", }; test("is unchanged when no agent is detected", () => { - expect(createUserAgent(configuration, {})).toBe("ts-octopusdeploy GitHubActions (release;deploy;v3)"); + expect(createUserAgent(configuration, {})).toBe("ts-octopusdeploy octopus-mcp-server/1.2.3 (claude-code/2.1.42)"); }); - test("places the agent between the library and the requesting app", () => { - expect(createUserAgent(configuration, { CLAUDECODE: "1" })).toBe("ts-octopusdeploy AIAgent/ClaudeCode GitHubActions (release;deploy;v3)"); + test("keeps the existing header and appends the agent", () => { + const withoutAgent = createUserAgent(configuration, {}); + expect(createUserAgent(configuration, { CLAUDECODE: "1" })).toBe(`${withoutAgent} (ai-agent=ClaudeCode)`); }); test("uses the caller-supplied agent", () => { - expect(createUserAgent({ ...configuration, aiAgent: "claude-code" }, {})).toBe("ts-octopusdeploy AIAgent/ClaudeCode GitHubActions (release;deploy;v3)"); + expect(createUserAgent({ ...configuration, aiAgent: "claude-code" }, {})).toBe( + "ts-octopusdeploy octopus-mcp-server/1.2.3 (claude-code/2.1.42) (ai-agent=ClaudeCode)" + ); + }); + + test("ignores a caller-supplied agent that isn't a string", () => { + // eslint-disable-next-line @typescript-eslint/consistent-type-assertions + const aiAgent = 42 as unknown as string; + expect(createUserAgent({ ...configuration, aiAgent }, {})).toBe("ts-octopusdeploy octopus-mcp-server/1.2.3 (claude-code/2.1.42)"); }); }); diff --git a/src/adapters/createUserAgent.ts b/src/adapters/createUserAgent.ts index 56c39ca..0e357be 100644 --- a/src/adapters/createUserAgent.ts +++ b/src/adapters/createUserAgent.ts @@ -2,5 +2,7 @@ import { getAiAgentUserAgentToken } from "../aiAgent"; import type { ClientConfiguration } from "../clientConfiguration"; export function createUserAgent(configuration: ClientConfiguration, env?: Record): string { - return ["ts-octopusdeploy", getAiAgentUserAgentToken(configuration.aiAgent, env), configuration.userAgentApp].filter((part) => !!part).join(" "); + // The agent is appended last so everything before it is unchanged: Octopus Server matches on the start of this header, + // e.g. "ts-octopusdeploy octopus-mcp-server" for the local MCP server. + return ["ts-octopusdeploy", configuration.userAgentApp, getAiAgentUserAgentToken(configuration.aiAgent, env)].filter((part) => !!part).join(" "); } diff --git a/src/aiAgent.test.ts b/src/aiAgent.test.ts index 566587c..5d2e1ff 100644 --- a/src/aiAgent.test.ts +++ b/src/aiAgent.test.ts @@ -6,13 +6,13 @@ describe("getAiAgentUserAgentToken", () => { }); test("detects an agent from a vendor variable", () => { - expect(getAiAgentUserAgentToken(undefined, { CLAUDECODE: "1" })).toBe("AIAgent/ClaudeCode"); + expect(getAiAgentUserAgentToken(undefined, { CLAUDECODE: "1" })).toBe("(ai-agent=ClaudeCode)"); }); test.each([ - ["CURSOR_EXTENSION_HOST_ROLE", "agent-exec", "AIAgent/Cursor"], + ["CURSOR_EXTENSION_HOST_ROLE", "agent-exec", "(ai-agent=Cursor)"], ["CURSOR_EXTENSION_HOST_ROLE", "user", undefined], - ["AGENT", "amp", "AIAgent/Amp"], + ["AGENT", "amp", "(ai-agent=Amp)"], ["AGENT", "teamcity-agent-01", undefined], ])("requires a matching value for %s=%s", (variable, value, expected) => { expect(getAiAgentUserAgentToken(undefined, { [variable]: value })).toBe(expected); @@ -23,30 +23,30 @@ describe("getAiAgentUserAgentToken", () => { }); test("the first known agent wins when agents are nested", () => { - expect(getAiAgentUserAgentToken(undefined, { CURSOR_AGENT: "1", CLAUDECODE: "1" })).toBe("AIAgent/ClaudeCode"); + expect(getAiAgentUserAgentToken(undefined, { CURSOR_AGENT: "1", CLAUDECODE: "1" })).toBe("(ai-agent=ClaudeCode)"); }); test.each([ - ["claude-code_2-1-322_agent", "AIAgent/ClaudeCode"], - ["Claude Code", "AIAgent/ClaudeCode"], - ["github_copilot_vscode_agent", "AIAgent/GitHubCopilot"], - ["devin@1", "AIAgent/Devin"], - ["custom-agent@2.0", "AIAgent/Other"], - ["amplitude-mcp", "AIAgent/Other"], + ["claude-code_2-1-322_agent", "(ai-agent=ClaudeCode)"], + ["Claude Code", "(ai-agent=ClaudeCode)"], + ["github_copilot_vscode_agent", "(ai-agent=GitHubCopilot)"], + ["devin@1", "(ai-agent=Devin)"], + ["custom-agent@2.0", "(ai-agent=Other)"], + ["amplitude-mcp", "(ai-agent=Other)"], ])("maps AI_AGENT=%s to %s", (value, expected) => { expect(getAiAgentUserAgentToken(undefined, { AI_AGENT: value })).toBe(expected); }); test("AI_AGENT takes precedence over vendor variables", () => { - expect(getAiAgentUserAgentToken(undefined, { CURSOR_AGENT: "1", AI_AGENT: "claude-code_2-1-322_agent" })).toBe("AIAgent/ClaudeCode"); + expect(getAiAgentUserAgentToken(undefined, { CURSOR_AGENT: "1", AI_AGENT: "claude-code_2-1-322_agent" })).toBe("(ai-agent=ClaudeCode)"); }); test("an unrecognised AI_AGENT falls back to the vendor name", () => { - expect(getAiAgentUserAgentToken(undefined, { GEMINI_CLI: "1", AI_AGENT: "gcli" })).toBe("AIAgent/GeminiCLI"); + expect(getAiAgentUserAgentToken(undefined, { GEMINI_CLI: "1", AI_AGENT: "gcli" })).toBe("(ai-agent=GeminiCLI)"); }); test.each([ - [" evil) agent\r\nX-Injected: 1 ", "AIAgent/Other"], + [" evil) agent\r\nX-Injected: 1 ", "(ai-agent=Other)"], [" \t ", undefined], ])("never includes the raw AI_AGENT value (%j)", (value, expected) => { expect(getAiAgentUserAgentToken(undefined, { AI_AGENT: value })).toBe(expected); @@ -54,12 +54,12 @@ describe("getAiAgentUserAgentToken", () => { describe("caller-supplied agent", () => { test("takes precedence over AI_AGENT and vendor variables", () => { - expect(getAiAgentUserAgentToken("cursor-vscode", { AI_AGENT: "claude-code", CLAUDECODE: "1" })).toBe("AIAgent/Cursor"); + expect(getAiAgentUserAgentToken("cursor-vscode", { AI_AGENT: "claude-code", CLAUDECODE: "1" })).toBe("(ai-agent=Cursor)"); }); test("falls back to AI_AGENT when not recognised, and reports as Other when nothing is", () => { - expect(getAiAgentUserAgentToken("some-mcp-client", { AI_AGENT: "claude-code" })).toBe("AIAgent/ClaudeCode"); - expect(getAiAgentUserAgentToken("some-mcp-client", {})).toBe("AIAgent/Other"); + expect(getAiAgentUserAgentToken("some-mcp-client", { AI_AGENT: "claude-code" })).toBe("(ai-agent=ClaudeCode)"); + expect(getAiAgentUserAgentToken("some-mcp-client", {})).toBe("(ai-agent=Other)"); }); }); }); diff --git a/src/aiAgent.ts b/src/aiAgent.ts index e1ca1ce..edcb14d 100644 --- a/src/aiAgent.ts +++ b/src/aiAgent.ts @@ -69,26 +69,40 @@ const knownAgents: ReadonlyArray = [ ]; /** - * Returns a User-Agent token naming the AI agent driving this client (e.g. "AIAgent/ClaudeCode"), or undefined + * Returns a User-Agent comment naming the AI agent driving this client (e.g. "(ai-agent=ClaudeCode)"), or undefined * when none is detected. * * Self-reported identifiers are checked first, in order: an identifier supplied by the caller (for example an MCP * server passing the connected client's `clientInfo.name`), then the `AI_AGENT` environment variable. If neither is * recognised, vendor-specific environment variables are checked. An identifier that is present but not recognised - * reports as "AIAgent/Other". Only the normalised name is reported: raw identifiers are free-form, so they are used + * reports as "(ai-agent=Other)". Only the normalised name is reported: raw identifiers are free-form, so they are used * for matching and never included in the output. */ -export function getAiAgentUserAgentToken(callerSuppliedAgent?: string, env: EnvironmentVariables = readProcessEnvironment()): string | undefined { - const aiAgentNameFromEnvVar = env[aiAgentVariable]; - const selfReported = [callerSuppliedAgent, aiAgentNameFromEnvVar].map((value) => value?.trim()).filter((value): value is string => !!value); +export function getAiAgentUserAgentToken(callerSuppliedAgent?: string, env?: EnvironmentVariables): string | undefined { + try { + const variables = env ?? readProcessEnvironment(); + const aiAgentNameFromEnvVar = variables[aiAgentVariable]; + const selfReported = [callerSuppliedAgent, aiAgentNameFromEnvVar] + .map((value) => (typeof value === "string" ? value.trim() : undefined)) + .filter((value): value is string => !!value); - // Vendor variables also cover an agent that self-reports in a format that isn't recognised. - const agent = selfReported.map(findAgentByPrefix).find((a): a is KnownAgent => a !== undefined) ?? findAgentByVariables(env); - if (agent) { - return `AIAgent/${agent.name}`; + // Vendor variables also cover an agent that self-reports in a format that isn't recognised. + const agent = selfReported.map(findAgentByPrefix).find((a): a is KnownAgent => a !== undefined) ?? findAgentByVariables(variables); + if (agent) { + return aiAgentComment(agent.name); + } + + return selfReported.length > 0 ? aiAgentComment(otherAgentName) : undefined; + } catch { + // Detection is best-effort and must never fail a request, e.g. where reading the environment isn't permitted. + return undefined; } +} - return selfReported.length > 0 ? `AIAgent/${otherAgentName}` : undefined; +// Formats the agent as an RFC 9110 comment, so it describes the request rather than claiming to be a product in the +// User-Agent. +function aiAgentComment(name: string): string { + return `(ai-agent=${name})`; } function findAgentByPrefix(identifier: string): KnownAgent | undefined {