From c9edffe60529c9b2bad7e72542be9324399a83f5 Mon Sep 17 00:00:00 2001 From: Stefan Lendl <1321542+stfl@users.noreply.github.com> Date: Tue, 24 Nov 2026 22:39:10 +0100 Subject: [PATCH] fix(claude-local): label ACP usage rows from the run's AI connection (#20955) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - A `claude_local` agent can run on a managed AI connection. The connection supplies the credentials and the routing, for example OpenRouter or a gateway. > - Each run writes usage rows to the cost ledger. The rows carry a provider, a biller, a billing type and a model. > - The ACP lane of the Claude adapter finds the billing identity from the agent environment only. It treats a run as API-billed only when `ANTHROPIC_API_KEY` is set. > - A managed connection with bearer auth sets `ANTHROPIC_AUTH_TOKEN` and `ANTHROPIC_BASE_URL`. It does not set `ANTHROPIC_API_KEY`. The run is therefore labeled `anthropic` with the subscription billing type, and the ledger records zero cost. > - The ACP bridge also reports its own model alias (for example `opus`) as the current model. The usage row then names that alias, not the model that the endpoint received. > - This pull request resolves the billing identity from the managed AI connection first. It also names the requested model on usage rows for those runs. > - The benefit is that runs on an api_key connection show as metered API usage with the correct provider and model in Costs. ## Linked Issues or Issue Description Refs #18540 This pull request fixes the labels for the ACP lane. The Claude CLI lane (`resolveClaudeBillingType`) and the price estimate stay open. Related pull requests that I found. None of them changes the ACP billing identity: - #12000 (`fix(claude-local): distrust gateway-reported costs`) is open. It touches the Claude CLI lane and the cost estimate. - #11420 (`fix(pi-local): report a real billing type instead of hardcoding unknown`) is open. It fixes the same kind of label problem in the Pi adapter. The report in #18540 also names a second problem. Claude Code estimates the price with Anthropic list prices. This pull request does not change that estimate. ## What Changed - `claude-local/src/server/acp-billing.ts` (new): `resolveManagedApiKeyBilling` reads the managed AI connection. For an `api_key` connection it returns the billing type `metered_api`. The provider and the biller are the connection provider. Bedrock routing bills `aws_bedrock`. `resolveEnvBillingIdentity` holds the existing env-based classification, moved out of `acp.ts` unchanged. This keeps `acp.ts` under 1,000 lines. - `claude-local/src/server/acp.ts`: `resolveClaudeAcpBillingIdentity` tries the managed connection first. Other runs, subscription connections included, keep the env-based result. - `adapter-utils/src/acpx-engine/execute.ts`: the ACPX billing identity gets an optional `preferRequestedModel` flag. The two accounting-model calls pass it on. - `adapter-utils/src/acpx-engine/accounting-model.ts`: `acpxAccountingModel` takes an options argument. With `preferRequested`, it returns the requested model, or `null` when the run requested none. - Tests: `acp.test.ts` covers gateway, OpenRouter, local, Bedrock and subscription connections. `accounting-model.test.ts` covers the new option. `execute.test.ts` checks that the usage row and the result name the requested model with the flag, and the bridge model without it. ## Verification - `corepack pnpm install --frozen-lockfile`: succeeded. - `corepack pnpm vitest run src/acpx-engine/accounting-model.test.ts src/acpx-engine/execute.test.ts` (in `packages/adapter-utils`): 2 files, 271 tests passed. - `corepack pnpm vitest run src/server/acp.test.ts` (in `packages/adapters/claude-local`): 1 file, 46 tests passed. - `corepack pnpm --filter @paperclipai/adapter-utils typecheck`: passed. - `corepack pnpm --filter @paperclipai/adapter-claude-local typecheck`: passed. - I did not run the full repository test suite. I did not run a live run against OpenRouter. ## Risks - Low risk. The new path applies only when the run config has a managed `api_key` connection. All other runs keep their current labels. A test checks the subscription case. - A run on an api_key connection whose config names no model now records no model on its usage row. Before, the row carried the bridge alias. - A connection that projects `ANTHROPIC_API_KEY` resolved to `api` before and resolves to `metered_api` now. `normalizeLedgerBillingType` in `server/src/services/heartbeat/run-state.ts` maps both values to `metered_api`, and the Anthropic and Codex pricing accept both. The ledger result is the same. - Runs on an api_key connection change from `subscription_included` to `metered_api`. Their cost is no longer forced to zero. Claude Code still supplies the cost estimate. For a routed model, that amount can differ from the amount that the provider bills. > For core feature work, check [`ROADMAP.md`](ROADMAP.md) first and discuss it in `#dev` before opening the PR. Feature PRs that overlap with planned core work may need to be redirected — check the roadmap first. See `CONTRIBUTING.md`. ## Model Used - Claude Code (Anthropic) with tool use (shell, file edits, test runs). Claude Fable 5.2 (`claude-fable-5-2`) directed the work. Claude Sonnet 5.5 (`claude-sonnet-5-5`) ported the change to current master and ran the tests. Claude Opus 5.5 (`claude-opus-5-5`) reviewed it. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [ ] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge --- .../src/acpx-engine/accounting-model.test.ts | 10 +++ .../src/acpx-engine/accounting-model.ts | 8 ++- .../src/acpx-engine/execute.test.ts | 28 ++++++++ .../adapter-utils/src/acpx-engine/execute.ts | 5 +- .../claude-local/src/server/acp-billing.ts | 33 +++++++++ .../claude-local/src/server/acp.test.ts | 68 +++++++++++++++++++ .../adapters/claude-local/src/server/acp.ts | 18 ++--- 7 files changed, 154 insertions(+), 16 deletions(-) create mode 100644 packages/adapters/claude-local/src/server/acp-billing.ts diff --git a/packages/adapter-utils/src/acpx-engine/accounting-model.test.ts b/packages/adapter-utils/src/acpx-engine/accounting-model.test.ts index e7bc77e6982..6f989a1252a 100644 --- a/packages/adapter-utils/src/acpx-engine/accounting-model.test.ts +++ b/packages/adapter-utils/src/acpx-engine/accounting-model.test.ts @@ -15,4 +15,14 @@ describe("ACP accounting model", () => { it("does not price a turn that changed models as one model", () => { expect(acpxAccountingModel("gpt-6.1-sol", selected("gpt-6.1-sol"), selected("gpt-6-astra"))).toBeNull(); }); + it("names the requested model over the bridge's alias when the run asks for it", () => { + const options = { preferRequested: true }; + expect(acpxAccountingModel("acme-claude-sonnet-gw", selected("opus"), selected("opus"), options)).toBe("acme-claude-sonnet-gw"); + expect(acpxAccountingModel("acme-claude-sonnet-gw", selected("opus"), selected("sonnet"), options)).toBe("acme-claude-sonnet-gw"); + }); + it("never names the bridge's current model when the run asked for none", () => { + const options = { preferRequested: true }; + expect(acpxAccountingModel("", selected("opus"), selected("opus"), options)).toBeNull(); + expect(acpxAccountingModel(" ", null, selected("opus"), options)).toBeNull(); + }); }); diff --git a/packages/adapter-utils/src/acpx-engine/accounting-model.ts b/packages/adapter-utils/src/acpx-engine/accounting-model.ts index df181bc6bca..94f12c0d330 100644 --- a/packages/adapter-utils/src/acpx-engine/accounting-model.ts +++ b/packages/adapter-utils/src/acpx-engine/accounting-model.ts @@ -2,7 +2,13 @@ import type { AcpRuntimeStatus } from "acpx/runtime"; /** Use provider-selected IDs, including its default. A mid-turn model change * cannot be priced as a single-model receipt; never guess from a display name. */ -export function acpxAccountingModel(requested: string, before: AcpRuntimeStatus | null, after: AcpRuntimeStatus | null): string | null { +export function acpxAccountingModel( + requested: string, + before: AcpRuntimeStatus | null, + after: AcpRuntimeStatus | null, + options: { preferRequested?: boolean } = {}, +): string | null { + if (options.preferRequested) return requested.trim() || null; const pre = before?.models?.currentModelId?.trim(); const post = after?.models?.currentModelId?.trim(); if (pre && post && pre !== post) return null; diff --git a/packages/adapter-utils/src/acpx-engine/execute.test.ts b/packages/adapter-utils/src/acpx-engine/execute.test.ts index 74f3d01a97b..10019f58c2b 100644 --- a/packages/adapter-utils/src/acpx-engine/execute.test.ts +++ b/packages/adapter-utils/src/acpx-engine/execute.test.ts @@ -1641,6 +1641,34 @@ describe("shared ACPX engine runtime behavior", () => { expect(statusLine?.text).toContain('"cost"'); }); + it.each([ + { preferRequestedModel: true, expected: "acme-claude-sonnet-gw" }, + { preferRequestedModel: undefined, expected: "opus" }, + ])("labels usage with the model $expected when preferRequestedModel is $preferRequestedModel", async ({ preferRequestedModel, expected }) => { + const root = await makeTempRoot(); + const onUsage = vi.fn(); + const execute = createAcpxEngineExecutor({ + createRuntime: () => ({ + ...buildRuntime(), + getStatus: async () => ({ models: { currentModelId: "opus", availableModelIds: [] } }), + }) as never, + resolveBillingIdentity: () => ({ provider: "anthropic", biller: "anthropic", billingType: "api", preferRequestedModel }), + }); + const result = await execute({ + runId: "run-requested-model", + onUsage, + agent: { id: "agent-1", companyId: "company-1" }, + runtime: {}, + config: { agent: "custom", agentCommand: "node ./fake-acp.js", stateDir: path.join(root, "state"), model: "acme-claude-sonnet-gw" }, + context: {}, + onLog: async () => {}, + onMeta: async () => {}, + } as never); + expect(result.exitCode).toBe(0); + expect(result.model).toBe(expected); + expect(onUsage).toHaveBeenLastCalledWith(expect.objectContaining({ model: expected, complete: true })); + }); + it.each(["checkpoint", "terminal"])("returns received usage after the %s receipt sink rejects and still closes the runtime", async (failedSave) => { const root = await makeTempRoot(); const close = vi.fn(async () => {}); diff --git a/packages/adapter-utils/src/acpx-engine/execute.ts b/packages/adapter-utils/src/acpx-engine/execute.ts index 6f0dc54eb4c..7a5f8a7fdef 100644 --- a/packages/adapter-utils/src/acpx-engine/execute.ts +++ b/packages/adapter-utils/src/acpx-engine/execute.ts @@ -286,6 +286,7 @@ export interface AcpxEngineBillingIdentity { provider?: string | null; biller?: string | null; billingType?: AdapterBillingType | null; + preferRequestedModel?: boolean; } /** @@ -5162,7 +5163,7 @@ export function createAcpxEngineExecutor(deps: AcpxEngineExecutorOptions = {}) { // Snapshot pre-turn usage so cumulative agent-reported cost can be // attributed to this run alone. preTurnStatus = await readRuntimeStatus(runtime, sessionHandle); - accountingModel = acpxAccountingModel(prepared.requestedModel, preTurnStatus, null); + accountingModel = acpxAccountingModel(prepared.requestedModel, preTurnStatus, null, { preferRequested: billingIdentity?.preferRequestedModel }); // The prepare phase (prompt build + usage snapshot) finished; the turn // phase starts next. await emitPhase("prepare_turn", preparePhaseStart, "ok"); @@ -5454,7 +5455,7 @@ export function createAcpxEngineExecutor(deps: AcpxEngineExecutorOptions = {}) { const turnSucceeded = terminal.status === "completed" && !timedOut && !channelLost; // Read usage before the settlement can discard runtime state. const postTurnStatus = await readRuntimeStatus(runtime, sessionHandle); - accountingModel = acpxAccountingModel(prepared.requestedModel, preTurnStatus, postTurnStatus); + accountingModel = acpxAccountingModel(prepared.requestedModel, preTurnStatus, postTurnStatus, { preferRequested: billingIdentity?.preferRequestedModel }); const turnUsage = summarizeAcpxTurnUsage({ preStatus: preTurnStatus, postStatus: postTurnStatus, diff --git a/packages/adapters/claude-local/src/server/acp-billing.ts b/packages/adapters/claude-local/src/server/acp-billing.ts new file mode 100644 index 00000000000..e3323dcda47 --- /dev/null +++ b/packages/adapters/claude-local/src/server/acp-billing.ts @@ -0,0 +1,33 @@ +import type { AdapterBillingType } from "@paperclipai/adapter-utils"; +import { parseObject } from "@paperclipai/adapter-utils/server-utils"; + +export function resolveManagedApiKeyBilling( + config: Record, +): { provider: string; biller: string; billingType: AdapterBillingType; preferRequestedModel: true } | null { + const connection = parseObject(config.managedAiConnection); + const provider = typeof connection.provider === "string" ? connection.provider.trim() : ""; + if (connection.method !== "api_key" || !provider) return null; + return { + provider, + biller: parseObject(config.managedAiRouting).kind === "bedrock" ? "aws_bedrock" : provider, + billingType: "metered_api", + preferRequestedModel: true, + }; +} + +export function resolveEnvBillingIdentity( + readEnvValue: (key: string) => string, +): { provider: string; biller: string; billingType: AdapterBillingType } { + const bedrockFlag = readEnvValue("CLAUDE_CODE_USE_BEDROCK"); + const bedrock = bedrockFlag === "1" || bedrockFlag === "true" || Boolean(readEnvValue("ANTHROPIC_BEDROCK_BASE_URL")); + const billingType: AdapterBillingType = bedrock + ? "metered_api" + : readEnvValue("ANTHROPIC_API_KEY") + ? "api" + : "subscription"; + return { + provider: "anthropic", + biller: bedrock ? "aws_bedrock" : "anthropic", + billingType, + }; +} diff --git a/packages/adapters/claude-local/src/server/acp.test.ts b/packages/adapters/claude-local/src/server/acp.test.ts index c5102a71aee..f966b4f4d9f 100644 --- a/packages/adapters/claude-local/src/server/acp.test.ts +++ b/packages/adapters/claude-local/src/server/acp.test.ts @@ -1842,6 +1842,74 @@ describe("resolveClaudeAcpBillingIdentity", () => { }); }); + describe("with a managed AI connection", () => { + const attribution = (overrides: Record) => ({ + connectionId: "conn-1", grantId: "grant-1", mode: "shared", responsibleUserId: null, ...overrides, + }); + + it("labels a gateway api_key connection from the connection, whatever credential env it projects", () => { + delete process.env.ANTHROPIC_API_KEY; + expect( + resolveClaudeAcpBillingIdentity({ + config: { + model: "acme-claude-sonnet-gw", + managedAiConnection: attribution({ provider: "anthropic", method: "api_key" }), + managedAiRouting: { kind: "gateway", auth: "bearer", baseUrl: "https://gateway.example.test", protocol: "messages" }, + env: { ANTHROPIC_AUTH_TOKEN: "token", ANTHROPIC_BASE_URL: "https://gateway.example.test" }, + }, + }), + ).toEqual({ provider: "anthropic", biller: "anthropic", billingType: "metered_api", preferRequestedModel: true }); + }); + + it("bills an OpenRouter connection to OpenRouter", () => { + expect( + resolveClaudeAcpBillingIdentity({ + config: { + managedAiConnection: attribution({ provider: "openrouter", method: "api_key" }), + managedAiRouting: { kind: "openrouter", auth: "bearer" }, + }, + }), + ).toEqual({ provider: "openrouter", biller: "openrouter", billingType: "metered_api", preferRequestedModel: true }); + }); + + it("bills a local-routing connection to its provider", () => { + expect( + resolveClaudeAcpBillingIdentity({ + config: { + managedAiConnection: attribution({ provider: "anthropic", method: "api_key" }), + managedAiRouting: { kind: "local", auth: "none" }, + }, + }), + ).toEqual({ provider: "anthropic", biller: "anthropic", billingType: "metered_api", preferRequestedModel: true }); + }); + + it("keeps Bedrock routing metered", () => { + expect( + resolveClaudeAcpBillingIdentity({ + config: { + managedAiConnection: attribution({ provider: "anthropic", method: "api_key" }), + managedAiRouting: { kind: "bedrock", region: "eu-central-1" }, + }, + }), + ).toEqual({ provider: "anthropic", biller: "aws_bedrock", billingType: "metered_api", preferRequestedModel: true }); + }); + + it("leaves a subscription connection with the labels it always got", () => { + delete process.env.ANTHROPIC_API_KEY; + delete process.env.CLAUDE_CODE_USE_BEDROCK; + delete process.env.ANTHROPIC_BEDROCK_BASE_URL; + const identity = resolveClaudeAcpBillingIdentity({ + config: { + model: "claude-sonnet-5-5", + managedAiConnection: attribution({ provider: "anthropic", method: "subscription" }), + env: { ANTHROPIC_API_KEY: "" }, + }, + }); + expect(identity).toEqual({ provider: "anthropic", biller: "anthropic", billingType: "subscription" }); + expect(identity).not.toHaveProperty("preferRequestedModel"); + }); + }); + it("ignores host env for remote execution targets", () => { process.env.ANTHROPIC_API_KEY = "sk-ant-host-only"; expect( diff --git a/packages/adapters/claude-local/src/server/acp.ts b/packages/adapters/claude-local/src/server/acp.ts index 1a653c05f42..e7494ac5685 100644 --- a/packages/adapters/claude-local/src/server/acp.ts +++ b/packages/adapters/claude-local/src/server/acp.ts @@ -40,6 +40,7 @@ import { asString, parseObject, } from "@paperclipai/adapter-utils/server-utils"; +import { resolveEnvBillingIdentity, resolveManagedApiKeyBilling } from "./acp-billing.js"; import { materializeRemoteClaudeConfig, overrideRemoteClaudeLocalPermissionMode, @@ -177,7 +178,9 @@ export function buildClaudeAcpConfig( export function resolveClaudeAcpBillingIdentity( ctx: Pick & Partial>, -): { provider: string; biller: string; billingType: AdapterBillingType } { +): { provider: string; biller: string; billingType: AdapterBillingType; preferRequestedModel?: true } { + const connection = resolveManagedApiKeyBilling(ctx.config); + if (connection) return connection; const envConfig = parseObject(parseObject(ctx.config).env); const target = readAdapterExecutionTarget({ executionTarget: ctx.executionTarget, @@ -190,18 +193,7 @@ export function resolveClaudeAcpBillingIdentity( const fromHost = considerHostEnv ? process.env[key] : undefined; return typeof fromHost === "string" ? fromHost.trim() : ""; }; - const bedrockFlag = readEnvValue("CLAUDE_CODE_USE_BEDROCK"); - const bedrock = bedrockFlag === "1" || bedrockFlag === "true" || Boolean(readEnvValue("ANTHROPIC_BEDROCK_BASE_URL")); - const billingType: AdapterBillingType = bedrock - ? "metered_api" - : readEnvValue("ANTHROPIC_API_KEY") - ? "api" - : "subscription"; - return { - provider: "anthropic", - biller: bedrock ? "aws_bedrock" : "anthropic", - billingType, - }; + return resolveEnvBillingIdentity(readEnvValue); } /**