diff --git a/src/server/claude-messages.ts b/src/server/claude-messages.ts index 9b5a5d9df06..efc4471e1e3 100644 --- a/src/server/claude-messages.ts +++ b/src/server/claude-messages.ts @@ -94,6 +94,7 @@ import type { OcxConfig } from "../types"; import { readJsonRequestBody, resolveInboundBodyLimitBytes } from "./request-decompress"; import { addFinalRequestLog, httpStatusForRequestLogTerminal, httpStatusFromTerminalError, recordFirstOutput, recordKeyWireAttemptUsage, type RequestLogContext, type RequestLogEntry } from "./request-log"; import { + agentIdFromHeaders, conversationIdFromClaudeMetadata, getOrAllocateRequestSessionLane, linkRequestSessionLane, @@ -932,6 +933,8 @@ async function handleClaudeMessagesWithBudget( ); if (claudeConversationId) logCtx.conversationId = claudeConversationId; } + const agentId = agentIdFromHeaders(req.headers); + if (agentId) logCtx.agentId = agentId; // A fast row blocks passthrough, unlike the chat case: native passthrough forwards the // caller's body with the caller's credential and never runs the Anthropic adapter, so the // proxy-owned `speed` + beta (anthropic-speed wire) and its usage.speed observation would be diff --git a/src/server/request-log-conversation.ts b/src/server/request-log-conversation.ts index c69f5773ba1..ffe664dc442 100644 --- a/src/server/request-log-conversation.ts +++ b/src/server/request-log-conversation.ts @@ -37,6 +37,16 @@ export function normalizeLogConversationId(raw: string | undefined | null): stri return createHash("sha256").update(trimmed).digest("hex").slice(0, LOG_CONVERSATION_ID_LEN); } +/** + * Claude Code sends `x-claude-code-agent-id` on subagent/teammate requests only; the session id and + * metadata.user_id are shared with the parent, so this is the one signal that names the caller. + * Shape-checked, since a header is client-controlled and the value reaches usage.jsonl. + */ +export function agentIdFromHeaders(headers: Headers): string | undefined { + const id = headers.get("x-claude-code-agent-id")?.trim(); + return id && /^a[\w-]{1,80}$/.test(id) ? id : undefined; +} + /** * Filter match: accept either the persisted digest or the original preimage * (so pasting from Logs detail or the client-facing session id both work). diff --git a/src/server/request-log.ts b/src/server/request-log.ts index 8de6eb2c4a0..b2a4c5bad2b 100644 --- a/src/server/request-log.ts +++ b/src/server/request-log.ts @@ -132,6 +132,8 @@ export interface RequestLogContext { firstOutputMs?: number; /** Best-effort chat/session correlation for Logs grouping (#330). Opaque; omit when unknown. */ conversationId?: string; + /** `x-claude-code-agent-id` of a Claude Code subagent/teammate request; absent on the main agent. */ + agentId?: string; surface?: "claude" | "claude-desktop" | "grok"; /** The matched configured key's id. Set ONLY for admissionKind "configured" — * never a sentinel, so a hand-edited entry whose id happens to be "loopback" @@ -298,6 +300,8 @@ export interface RequestLogEntry { accountLogLabel?: string; /** Best-effort chat/session correlation for Logs grouping (#330). */ conversationId?: string; + /** `x-claude-code-agent-id` of a Claude Code subagent/teammate request; absent on the main agent. */ + agentId?: string; requestedModel?: string; requestedAlias?: string; /** Original bare helper model when the opt-in shadow-call route rewrote this request. */ @@ -458,6 +462,7 @@ export function requestLogEntryFromPersistedUsage(entry: PersistedUsageEntry): R ...(entry.firstOutputMs !== undefined ? { firstOutputMs: entry.firstOutputMs } : {}), ...(isKnownUsageSurface(entry.surface) ? { surface: entry.surface } : {}), ...(entry.conversationId ? { conversationId: entry.conversationId } : {}), + ...(entry.agentId ? { agentId: entry.agentId } : {}), ...(isCodexUsageAccountLogLabel(entry.accountLogLabel) ? { accountLogLabel: entry.accountLogLabel } : {}), @@ -640,6 +645,7 @@ export function addRequestLog(entry: RequestLogEntry) { ? { accountLogLabel: entry.accountLogLabel } : {}), ...(entry.conversationId ? { conversationId: entry.conversationId } : {}), + ...(entry.agentId ? { agentId: entry.agentId } : {}), ...(entry.resolvedModel ? { resolvedModel: entry.resolvedModel } : {}), ...(entry.servedModel ? { servedModel: entry.servedModel } : {}), ...(entry.wireModel ? { wireModel: entry.wireModel } : {}), @@ -1582,6 +1588,7 @@ export function addFinalRequestLog( ? { accountLogLabel: logCtx.accountLogLabel } : {}), ...(logCtx.conversationId ? { conversationId: logCtx.conversationId } : {}), + ...(logCtx.agentId ? { agentId: logCtx.agentId } : {}), ...(logCtx.requestedModel ? { requestedModel: logCtx.requestedModel } : {}), ...(logCtx.requestedAlias ? { requestedAlias: logCtx.requestedAlias } : {}), ...(shadowCallRewrittenFrom ? { shadowCallRewrittenFrom } : {}), diff --git a/src/usage/log.ts b/src/usage/log.ts index e5aba9030f8..19c8676f371 100644 --- a/src/usage/log.ts +++ b/src/usage/log.ts @@ -355,6 +355,8 @@ export interface PersistedUsageEntry { accountLogLabel?: CodexUsageAccountLogLabel; /** Best-effort chat/session correlation for Logs grouping (#330). */ conversationId?: string; + /** Claude Code subagent/teammate id (x-claude-code-agent-id); absent on the main agent. */ + agentId?: string; resolvedModel?: string; /** Model the upstream actually served (openai-model header or response body). */ servedModel?: string; @@ -1037,6 +1039,7 @@ function normalizeUsageEntry(entry: PersistedUsageEntry): PersistedUsageEntry { ...(typeof entry.conversationId === "string" && entry.conversationId.trim() ? { conversationId: entry.conversationId.trim().slice(0, 128) } : {}), + ...(typeof entry.agentId === "string" && entry.agentId.trim() ? { agentId: entry.agentId.trim().slice(0, 128) } : {}), ...(resolvedModel ? { resolvedModel } : {}), ...(servedModel ? { servedModel } : {}), ...(entry.wireModel ? { wireModel: entry.wireModel } : {}), diff --git a/tests/claude-integration/claude-native-passthrough.test.ts b/tests/claude-integration/claude-native-passthrough.test.ts index fe7b1ccb20f..016ba20e0f1 100644 --- a/tests/claude-integration/claude-native-passthrough.test.ts +++ b/tests/claude-integration/claude-native-passthrough.test.ts @@ -185,6 +185,33 @@ test("native passthrough persists conversationId from metadata.user_id", async ( } }); +test("native passthrough logs agentId from x-claude-code-agent-id, only when well-formed", async () => { + const { clearRequestLogsForTests } = await import("../../src/server/request-log"); + const { readUsageEntries } = await import("../../src/usage/log"); + clearRequestLogsForTests(); + const upstream = mockAnthropicUpstream([]); + saveConfig(cfg(upstream.url.toString().replace(/\/$/, ""))); + const server = startServer(0); + try { + // main agent (no header), a subagent, and a malformed value that must not reach the log + for (const agent of [undefined, "a1b2c3d4e5f60718", "a bad value"]) { + const res = await fetch(new URL("/v1/messages?beta=true", server.url), { + method: "POST", + headers: { ...OAUTH_HEADERS, ...(agent ? { "x-claude-code-agent-id": agent } : {}) }, + body: JSON.stringify(claudeBody()), + }); + expect(res.status).toBe(200); + await res.text(); + } + const logs = logsFromApiBody<{ agentId?: string }>(await (await fetch(new URL("/api/logs?tail=3", server.url))).json()); + expect(logs.map(l => l.agentId)).toEqual([undefined, "a1b2c3d4e5f60718", undefined]); + expect(readUsageEntries().map(e => e.agentId)).toEqual([undefined, "a1b2c3d4e5f60718", undefined]); + } finally { + await server.stop(true); + upstream.stop(true); + } +}); + test("count_tokens passes through with native credentials", async () => { const captured: Captured[] = []; const upstream = mockAnthropicUpstream(captured);