diff --git a/desktop/src-tauri/Cargo.lock b/desktop/src-tauri/Cargo.lock index af7e5d3066a..afb2b6025f0 100644 --- a/desktop/src-tauri/Cargo.lock +++ b/desktop/src-tauri/Cargo.lock @@ -2541,7 +2541,7 @@ dependencies = [ [[package]] name = "opencodex-desktop" -version = "2.65.0-vadymhimself.24" +version = "2.65.0-vadymhimself.25" dependencies = [ "dbus", "reqwest 0.12.24", diff --git a/desktop/src-tauri/Cargo.toml b/desktop/src-tauri/Cargo.toml index fa1760977d8..c00988a9f46 100644 --- a/desktop/src-tauri/Cargo.toml +++ b/desktop/src-tauri/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "opencodex-desktop" -version = "2.65.0-vadymhimself.24" +version = "2.65.0-vadymhimself.25" description = "OpenCodex desktop shell" authors = ["OpenCodex contributors"] license = "MIT" diff --git a/desktop/src-tauri/tauri.conf.json b/desktop/src-tauri/tauri.conf.json index e0cc4bb837a..f40d1abe373 100644 --- a/desktop/src-tauri/tauri.conf.json +++ b/desktop/src-tauri/tauri.conf.json @@ -1,7 +1,7 @@ { "$schema": "https://schema.tauri.app/config/2", "productName": "OpenCodex", - "version": "2.65.0-vadymhimself.24", + "version": "2.65.0-vadymhimself.25", "identifier": "com.opencodex.desktop", "build": { "frontendDist": "../ui", diff --git a/package.json b/package.json index 2887ec10ef0..07206250ca4 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@bitkyc08/opencodex", - "version": "2.65.0-vadymhimself.24", + "version": "2.65.0-vadymhimself.25", "description": "Universal provider proxy for OpenAI Codex & Claude Code — use any LLM with Codex CLI/App/SDK and Claude Code", "type": "module", "main": "./bin/package-main.mjs", diff --git a/scripts/test-layout/layout.json b/scripts/test-layout/layout.json index b39f261ccb7..950879770b7 100644 --- a/scripts/test-layout/layout.json +++ b/scripts/test-layout/layout.json @@ -1805,7 +1805,8 @@ "zz-ci-api-usage-isolation.test.ts": "ci-workflows", "zz-ci-storage-policy-isolation.test.ts": "ci-workflows", "zz-pr-coderabbit-readiness-revalidation.test.ts": "ci-workflows", - "upstream-refusal-log.test.ts": "lib" + "upstream-refusal-log.test.ts": "lib", + "call-usage-line-log.test.ts": "lib" }, "migrated": [ "adapters", diff --git a/src/lib/usage-line-log.ts b/src/lib/usage-line-log.ts new file mode 100644 index 00000000000..a23165ae5fc --- /dev/null +++ b/src/lib/usage-line-log.ts @@ -0,0 +1,79 @@ +import { createHash } from "node:crypto"; +import { baseProviderLabel } from "../providers/label"; +import { sanitizeLogMetadataString } from "./redact"; + +/** + * One structured log line per finished model call, so an operator can work out, per calling key, + * the share of calls and tokens on each model from the process log alone. + * + * The line carries only the HTTP status, the provider and model ids, three token counts, an 8-hex + * hash of the gateway API key's record id and the duration. It never carries message text, a + * request or response body, a header, a secret key value, an account label or an email: the input is + * the fork's own final request record, and only the fields named below are read from it. + * + * It is written only on an AgentRadar gateway (`OPENCODEX_AGENTRADAR=1`, the condition the + * `[ar-acct]` line uses), so a self-hosted gateway gains no new output. + */ + +/** Each id is cut to this many characters, newlines and control characters removed. */ +export const USAGE_LOG_ID_MAX_CHARS = 80; + +/** The fields of the final request record this line reads. Nothing else is looked at. */ +export interface UsageLogInput { + status: number; + provider?: string; + model?: string; + usage?: { + inputTokens?: number; + outputTokens?: number; + cachedInputTokens?: number; + cacheReadInputTokens?: number; + }; + /** The configured key's record id (never the secret key value). Absent for environment or loopback admission. */ + apiKeyId?: string; + durationMs?: number; +} + +/** The OAuth (`o`) and API-key (`k`) account labels `baseProviderLabel` leaves in place. */ +const ACCOUNT_SUFFIX_RE = /-(?:o[a-f0-9]{6}|k[a-f0-9]{32})$/; + +function idField(value: string | undefined): string { + return JSON.stringify(sanitizeLogMetadataString(value, USAGE_LOG_ID_MAX_CHARS) ?? "-"); +} + +/** + * A pooled provider is logged with the serving account's label as a suffix (`anthropic-p2e22d0`). + * That label names one account, which this line must not, so the suffix is dropped. + */ +function providerField(value: string | undefined): string { + const base = typeof value === "string" && value !== "" ? baseProviderLabel(value).replace(ACCOUNT_SUFFIX_RE, "") : value; + return idField(base); +} + +function count(value: number | undefined): string { + return typeof value === "number" && Number.isFinite(value) && value >= 0 ? String(Math.round(value)) : "-"; +} + +/** First 8 hex of sha256 of the key record id, or "-" when the call carried no configured key. */ +export function hashedKeyId(apiKeyId: string | undefined): string { + if (typeof apiKeyId !== "string" || apiKeyId === "") return "-"; + return createHash("sha256").update(apiKeyId).digest("hex").slice(0, 8); +} + +/** The line, without writing it. */ +export function usageLogLine(input: UsageLogInput): string { + const { usage } = input; + const status = Number.isInteger(input.status) ? String(input.status) : "-"; + return `[usage] status=${status} provider=${providerField(input.provider)} model=${idField(input.model)}` + + ` in=${count(usage?.inputTokens)} out=${count(usage?.outputTokens)}` + + ` cached=${count(usage?.cacheReadInputTokens ?? usage?.cachedInputTokens)}` + + ` key=${hashedKeyId(input.apiKeyId)} ms=${count(input.durationMs)}`; +} + +/** Write the one line, on an AgentRadar gateway only. Never throws: logging must not fail a request. */ +export function logUsageLine(input: UsageLogInput): void { + if (process.env.OPENCODEX_AGENTRADAR !== "1") return; + try { + console.info(usageLogLine(input)); + } catch { /* request logging must never fail a user request */ } +} diff --git a/src/server/request-log.ts b/src/server/request-log.ts index 8de6eb2c4a0..6e64da8c6b0 100644 --- a/src/server/request-log.ts +++ b/src/server/request-log.ts @@ -27,6 +27,7 @@ import type { RequestSpendSettlement } from "./responses/request-spend"; import type { AdapterTierMetadata } from "../providers/fastwire"; import { UPSTREAM_RESET_REPLAY_REFUSED_CODE } from "../lib/upstream-retry"; import { redactSecretString, sanitizeLogMetadataString } from "../lib/redact"; +import { logUsageLine } from "../lib/usage-line-log"; import { appendUsageEntry, classifyCacheTelemetryProvenance, @@ -608,6 +609,9 @@ export function addRequestLog(entry: RequestLogEntry) { else if (retained !== entry) delete retained.claudeCompatibility; entry = retained; retainRequestLogEntry(entry); + // The one per-call usage line (model, tokens, hashed key id; no text). This is the single sink + // every finished request row passes through, on the same record the usage ledger persists below. + logUsageLine(entry); for (const observer of requestLogObserversForTests) { try { observer(entry); } catch { /* test observation must never fail request logging */ } } diff --git a/structure/transports/byte-accounting.md b/structure/transports/byte-accounting.md index 2749459e550..4d6cbd22725 100644 --- a/structure/transports/byte-accounting.md +++ b/structure/transports/byte-accounting.md @@ -175,3 +175,5 @@ The [compaction routing override](responses-failover.md#compaction-routing-overr ## Refusal-shape log line `src/lib/upstream-refusal-log.ts` writes one `[upstream-refusal]` line per upstream 4xx so an operator can see which parameter or size limit a provider refuses. `providerFetch`'s physical send in `src/server/responses/fetch-helpers.ts` is the single hook: every adapter and route answers through it, after any dispatch override has rebuilt the request. The line holds the status, provider id, model id, the envelope's `type`, `code` and `param` (each cut to 80 characters, control characters removed) and the outgoing body size in bytes. It never holds the message text, a body, a header, a credential or an account id, and it is skipped for 401 and 429, which the `[key-failover]` and `[anthropic-pool]` lines already report. The envelope is read from a clone, bounded to 64 KiB, off the request path; a body that is not JSON logs the status, ids and size only. The fork's own `translation_buffer_limit` 413s log through the same module with `where=request|response|stream`, the size where known and the cap. `runAdmittedBodyWork` logs `[inbound-size]` for a JSON route POST whose declared Content-Length is above 5 MiB (a chunked body has no declared length and is not logged). `tests/lib/upstream-refusal-log.test.ts` covers it against recorded samples under `fixtures/external/`. + +`src/lib/usage-line-log.ts` writes one `[usage]` line per finished model call: `status`, `provider`, `model`, `in`, `out`, `cached` (token counts, `-` when unreported), `key` (first 8 hex of sha256 of the gateway API key's record id, never the secret; `-` when the call used no configured key) and `ms`. `addRequestLog` in `src/server/request-log.ts` is the hook: every final request row (`addFinalRequestLog`, on every inbound route) passes through it, on the same record the usage ledger persists, so the line sees the final counts and the key id. Ids are sanitized, quoted and cut to 80 characters; a pooled provider label drops its account suffix. It never holds message text, a body, a header, a secret, an account label or an email. It is written only when `OPENCODEX_AGENTRADAR=1`, so a self-hosted gateway logs nothing new. `tests/lib/call-usage-line-log.test.ts` covers it from the fork's own request record, with no provider payload. diff --git a/tests/fixtures/test-layout-expected.json b/tests/fixtures/test-layout-expected.json index b60a01f5dfb..77ea139b89e 100644 --- a/tests/fixtures/test-layout-expected.json +++ b/tests/fixtures/test-layout-expected.json @@ -1636,5 +1636,6 @@ "command-code-tool-text-prose-split.test.ts": "providers", "cli-effort-slug.test.ts": "cli", "grok-47-build-fast-metadata.test.ts": "providers/xai", - "upstream-refusal-log.test.ts": "lib" + "upstream-refusal-log.test.ts": "lib", + "call-usage-line-log.test.ts": "lib" } diff --git a/tests/lib/call-usage-line-log.test.ts b/tests/lib/call-usage-line-log.test.ts new file mode 100644 index 00000000000..778d6eb9786 --- /dev/null +++ b/tests/lib/call-usage-line-log.test.ts @@ -0,0 +1,160 @@ +import { afterEach, beforeEach, describe, expect, spyOn, test } from "bun:test"; +import { createHash } from "node:crypto"; +import { mkdtempSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { hashedKeyId, logUsageLine, usageLogLine, USAGE_LOG_ID_MAX_CHARS } from "../../src/lib/usage-line-log"; +import { addFinalRequestLog, clearRequestLogsForTests, type RequestLogContext } from "../../src/server/request-log"; +import { resetUsageReadCacheForTests } from "../../src/usage/log"; +import { removeTreeWithRetry } from "../helpers/remove-tree"; + +// Shaped as test sentinels so the privacy scan knows they are fake. +const PROMPT_TEXT = "DISTINCTIVE-PROMPT-TEXT-7731"; +const API_KEY_SECRET = "sk-test-9942distinctive"; +const AUTH_HEADER = "Bearer access-token-5531distinctive"; +const KEY_ID = "key-record-1"; + +const LINE_RE = /^\[usage\] status=\d+ provider="[^"]*" model="[^"]*" in=(?:\d+|-) out=(?:\d+|-) cached=(?:\d+|-) key=(?:[0-9a-f]{8}|-) ms=(?:\d+|-)$/; + +let infos: string[]; +let restoreEnv: () => void; +let restoreSpy: () => void; + +beforeEach(() => { + infos = []; + const spy = spyOn(console, "info").mockImplementation((...args: unknown[]) => { infos.push(args.map(String).join(" ")); }); + restoreSpy = () => spy.mockRestore(); + const previous = process.env.OPENCODEX_AGENTRADAR; + process.env.OPENCODEX_AGENTRADAR = "1"; + restoreEnv = () => { + if (previous === undefined) delete process.env.OPENCODEX_AGENTRADAR; + else process.env.OPENCODEX_AGENTRADAR = previous; + }; +}); +afterEach(() => { restoreSpy(); restoreEnv(); }); + +const usageLines = () => infos.filter(line => line.startsWith("[usage]")); + +describe("usage line", () => { + test("carries status, ids, counts, hashed key id and duration", () => { + logUsageLine({ + status: 200, provider: "anthropic", model: "claude-test-1", + usage: { inputTokens: 1200, outputTokens: 340, cacheReadInputTokens: 900 }, + apiKeyId: KEY_ID, durationMs: 2150, + }); + const expectedHash = createHash("sha256").update(KEY_ID).digest("hex").slice(0, 8); + expect(usageLines()).toEqual([ + `[usage] status=200 provider="anthropic" model="claude-test-1" in=1200 out=340 cached=900 key=${expectedHash} ms=2150`, + ]); + expect(LINE_RE.test(usageLines()[0]!)).toBe(true); + }); + + test("cached falls back to cachedInputTokens and the key hash is stable per id", () => { + expect(usageLogLine({ status: 200, usage: { inputTokens: 5, outputTokens: 1, cachedInputTokens: 4 }, apiKeyId: KEY_ID })).toContain("cached=4"); + expect(hashedKeyId(KEY_ID)).toBe(hashedKeyId(KEY_ID)); + expect(hashedKeyId(KEY_ID)).not.toBe(hashedKeyId("key-record-2")); + }); + + test("missing counts, key and duration log as a dash", () => { + logUsageLine({ status: 502 }); + expect(usageLines()).toEqual(['[usage] status=502 provider="-" model="-" in=- out=- cached=- key=- ms=-']); + expect(hashedKeyId(undefined)).toBe("-"); + expect(hashedKeyId("")).toBe("-"); + const odd = usageLogLine({ status: 200, usage: { inputTokens: Number.NaN, outputTokens: -3 } }); + expect(odd).toContain("in=- out=- cached=-"); + }); + + test("ids with newlines or 200 characters stay on one bounded line", () => { + logUsageLine({ + status: 200, provider: "prov\r\nider\n[usage] status=200 forged", model: `m${"x".repeat(200)}\nsecond line`, + usage: { inputTokens: 1, outputTokens: 1 }, + }); + const [line] = usageLines(); + expect(line).toBeDefined(); + expect(line).not.toMatch(/[\r\n]/); + expect(infos).toHaveLength(1); + const model = /model="([^"]*)"/.exec(line!)![1]!; + expect(model.length).toBeLessThanOrEqual(USAGE_LOG_ID_MAX_CHARS); + expect(LINE_RE.test(line!)).toBe(true); + }); + + test("a pooled provider label drops the account suffix", () => { + expect(usageLogLine({ status: 200, provider: "anthropic-p2e22d0" })).toContain('provider="anthropic"'); + expect(usageLogLine({ status: 200, provider: "xai-oabcdef" })).toContain('provider="xai"'); + expect(usageLogLine({ status: 200, provider: `acme-k${"a".repeat(32)}` })).toContain('provider="acme"'); + expect(usageLogLine({ status: 200, provider: "opencode-go" })).toContain('provider="opencode-go"'); + }); + + test("a key-shaped token in a provider label is redacted, not logged", () => { + logUsageLine({ status: 200, provider: `relay-${API_KEY_SECRET}`, model: "gpt-test", apiKeyId: KEY_ID }); + const line = usageLines()[0]!; + expect(line).not.toContain(API_KEY_SECRET); + expect(LINE_RE.test(line)).toBe(true); + }); + + test("is silent unless the AgentRadar mode is on", () => { + delete process.env.OPENCODEX_AGENTRADAR; + logUsageLine({ status: 200, provider: "anthropic", model: "claude-test-1" }); + process.env.OPENCODEX_AGENTRADAR = "0"; + logUsageLine({ status: 200, provider: "anthropic", model: "claude-test-1" }); + expect(infos).toEqual([]); + }); +}); + +describe("usage line from the final request record", () => { + test("every finished call emits one line, and no text, secret or header reaches it", () => { + const home = mkdtempSync(join(tmpdir(), "ocx-usage-line-")); + const previousHome = process.env.OPENCODEX_HOME; + process.env.OPENCODEX_HOME = home; + clearRequestLogsForTests(); + resetUsageReadCacheForTests(); + try { + const ctx: RequestLogContext = { + model: "claude-test-1", + provider: "anthropic-p2e22d0", + apiKeyId: KEY_ID, + admissionKind: "configured", + usage: { inputTokens: 800, outputTokens: 120, cacheReadInputTokens: 600 }, + // Fields that must never be read into the line. + conversationId: PROMPT_TEXT, + upstreamError: `${PROMPT_TEXT} ${API_KEY_SECRET} ${AUTH_HEADER}`, + accountLogLabel: "p2e22d0", + servedAccountId: "acct-distinctive-1@example.test", + }; + addFinalRequestLog("ocx-usage-line-1", Date.now() - 50, ctx, 200, { closeReason: "non_stream" }); + const [line] = usageLines(); + expect(usageLines()).toHaveLength(1); + expect(LINE_RE.test(line!)).toBe(true); + expect(line).toContain('provider="anthropic" model="claude-test-1"'); + expect(line).toContain(`key=${hashedKeyId(KEY_ID)}`); + for (const secret of [PROMPT_TEXT, API_KEY_SECRET, AUTH_HEADER, "Bearer", "acct-distinctive", "example.test", "p2e22d0", KEY_ID]) { + expect(line).not.toContain(secret); + } + } finally { + if (previousHome === undefined) delete process.env.OPENCODEX_HOME; + else process.env.OPENCODEX_HOME = previousHome; + clearRequestLogsForTests(); + resetUsageReadCacheForTests(); + removeTreeWithRetry(home); + } + }); + + test("a call with no usage and no configured key still logs one line with dashes", () => { + const home = mkdtempSync(join(tmpdir(), "ocx-usage-line-")); + const previousHome = process.env.OPENCODEX_HOME; + process.env.OPENCODEX_HOME = home; + clearRequestLogsForTests(); + resetUsageReadCacheForTests(); + try { + addFinalRequestLog("ocx-usage-line-2", Date.now(), { model: "gpt-test", provider: "openai", admissionKind: "loopback" }, 499, { closeReason: "client_cancel" }); + expect(usageLines()).toHaveLength(1); + expect(usageLines()[0]).toMatch(/^\[usage\] status=499 provider="openai" model="gpt-test" in=- out=- cached=- key=- ms=\d+$/); + } finally { + if (previousHome === undefined) delete process.env.OPENCODEX_HOME; + else process.env.OPENCODEX_HOME = previousHome; + clearRequestLogsForTests(); + resetUsageReadCacheForTests(); + removeTreeWithRetry(home); + } + }); +});