Skip to content
Draft
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
3 changes: 3 additions & 0 deletions src/server/claude-messages.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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
Expand Down
10 changes: 10 additions & 0 deletions src/server/request-log-conversation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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).
Expand Down
7 changes: 7 additions & 0 deletions src/server/request-log.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down Expand Up @@ -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. */
Expand Down Expand Up @@ -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 }
: {}),
Expand Down Expand Up @@ -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 } : {}),
Expand Down Expand Up @@ -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 } : {}),
Expand Down
3 changes: 3 additions & 0 deletions src/usage/log.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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 } : {}),
Expand Down
27 changes: 27 additions & 0 deletions tests/claude-integration/claude-native-passthrough.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
Loading