Files
PaperClipAI/packages/adapter-utils
Stefan Lendl c9edffe605 fix(claude-local): label ACP usage rows from the run's AI connection (#20955)
## 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
2026-11-24 15:39:10 -06:00
..

@paperclipai/adapter-utils

Shared utilities for Paperclip adapters: process spawning, environment injection, sandbox/SSH transport, workspace sync, and the round-trip helpers that move code between the local execution-workspace cwd and wherever the agent actually runs.

For the adapter-author guide see docs/adapters/creating-an-adapter.md and the in-repo notes at packages/adapters/AUTHORING.md.

Sandbox bridge deadlines

Command-managed bridge control operations (queue reads, input delivery, setup, and cleanup) have a host-enforced deadline of at most 30 seconds per shell command. A shorter configured timeout still applies. These operations cannot inherit the agent run's hours-long lifetime or wait forever on a provider that ignores its timeout. Long-lived agent session commands keep their own limits.

A control timeout reports a transport failure. It does not prove that the remote command stopped and does not replay an uncertain write. The process session closes failed input delivery and uses its existing shutdown path; normal execution settlement must still verify termination.

Native archive transfer deadlines

Native syncIn and syncOut calls accept an optional minimumTimeoutMs budget. The server validates this budget and extends the worker RPC deadline. Providers can honor this field for file transfers without changing their configuration. Daytona uses the larger of this minimum and its configured timeout. Other providers keep their existing behavior. The minimum is limited to 30 minutes and does not change sandbox lifetimes, stored settings or the timeout for other commands.

The remote-workspace archive path uses the verified capture size for downloads and the local archive size for uploads. Large archives get one second per MiB plus 60 seconds, capped at 30 minutes. Small archives keep the existing provider timeout when that calculation is no greater than five minutes. Archive size, checksum, confinement and host space checks still apply.

An exact retained-sandbox resume keeps its recorded provider timeout and RPC overhead. It uses the normal one-minute fallback only when no timeout was recorded. A five-minute cold restore must not be cut off by that fallback. Resume still targets the recorded allocation and does not acquire a replacement.

No-remote-git contract

The local execution-workspace cwd is the only persistence boundary across runs. No adapter may depend on a git remote for cross-run state.

Adapters that run the agent on a different host should use the SSH round-trip helpers in src/ssh.ts:

  • prepareWorkspaceForSshExecution({ spec, localDir, remoteDir }) — bundles the local cwd (tracked files, dirty edits, untracked additions, and the git history needed to reconstruct it) to remoteDir before the run starts. Runs with no git remote configured.
  • restoreWorkspaceFromSshExecution({ spec, localDir, remoteDir, ... }) — syncs the remote cwd back into localDir after the run, including any new commits the agent created. Also runs with no git remote configured.

prepareRemoteManagedRuntime in src/remote-managed-runtime.ts wraps both calls for adapters that want a per-run remote workspace and an automatic restoreWorkspace() finally hook.

The invariant is pinned by the no-remote-git contract case in src/ssh-fixture.test.ts, which asserts that a remote-only commit propagates to the local worktree through the prepare → restore round-trip with no git remote configured at any point. Do not regress that test.