llm-to-bedrock — скилл для Claude Code: что делает и как установить
Скилл llm-to-bedrock для Claude Code переписывает обращения к API OpenAI, Gemini и Anthropic на Amazon Bedrock. Переносит вызовы SDK или помогает открыть доступ к нужным моделям.
Apache-2.0 579 установок ★ 3 536 обновлён 2026-11-20
npx skills add aws/agent-toolkit-for-aws --skill llm-to-bedrock -a claude-codeЧто делает llm-to-bedrock
Скилл заменяет прямые вызовы к API OpenAI, Anthropic и Gemini/Google AI на Amazon Bedrock. В режиме полной миграции инструмент анализирует кодовую базу, переписывает SDK-клиенты, проверяет качество ответов Bedrock и готовит отдельную ветку под слияние в репозиторий.
Второй режим — доступ к моделям. Агент не трогает исходный код, а проверяет статус конкретных нейросетей в AWS и помогает по шагам запросить к ним доступ через Bedrock.
Для запуска скилла в системе обязателен менеджер пакетов uv. Для полной миграции рядом должен стоять скилл gcp-to-aws или azure-to-aws: их логику сканирования llm-to-bedrock читает напрямую. Без одной из этих зависимостей полная переработка кода сразу остановится, но режим проверки доступа сработает автономно.
Какие задачи решает
- переписать вызовы OpenAI, Anthropic или Gemini на SDK Amazon Bedrock
- запросить доступ к моделям в консоли Bedrock без правок исходников
- сравнить ответы Bedrock с исходными моделями перед слиянием
- подготовить готовую Git-ветку с перенесёнными интеграциями
Примеры запросов агенту
- Перепиши вызовы OpenAI на Amazon Bedrock в этом репозитории
- Помоги запросить доступ к моделям Claude в Amazon Bedrock
- Проверь, какие модели включены в Bedrock, без изменения кода
Как установить llm-to-bedrock
1Через Skills CLI (Vercel)
npx skills add aws/agent-toolkit-for-aws --skill llm-to-bedrock -a claude-code2Вручную: положить файлы
~/.claude/skills/llm-to-bedrock/SKILL.mdПапка скилла целиком; для одного проекта — .claude/skills/llm-to-bedrock/
1Через Skills CLI (Vercel)
npx skills add aws/agent-toolkit-for-aws --skill llm-to-bedrock -a codex2Вручную: положить файлы
.agents/skills/llm-to-bedrock/SKILL.mdДля всех проектов — ~/.agents/skills/
1Через Skills CLI (Vercel)
npx skills add aws/agent-toolkit-for-aws --skill llm-to-bedrock -a cursor2Вручную: положить файлы
.cursor/skills/llm-to-bedrock/SKILL.mdCursor читает и .agents/skills/, и .claude/skills/
1GitHub CLI
gh skill install aws/agent-toolkit-for-aws plugins/aws-startup-advisor/skills/llm-to-bedrock2Вручную: положить файлы
.github/skills/llm-to-bedrock/SKILL.md1Через Skills CLI (Vercel)
npx skills add aws/agent-toolkit-for-aws --skill llm-to-bedrock -a gemini-cli2Командой платформы
gemini skills install https://github.com/aws/agent-toolkit-for-aws --path plugins/aws-startup-advisor/skills/llm-to-bedrockВручную: положить файлы
.devin/skills/llm-to-bedrock/SKILL.mdСтарый путь .windsurf/skills/ тоже читается
Через Skills CLI (Vercel)
npx skills add aws/agent-toolkit-for-aws --skill llm-to-bedrock -a opencodeClaude.ai
Упакуйте папку в zip и загрузите в Settings → Capabilities → Skills
По шагам, с командами для каждой платформы: Как установить скилл в Claude Code: пять способов
Вопросы о llm-to-bedrock
Как установить llm-to-bedrock в Claude Code?
Выполните команду npx skills add aws/agent-toolkit-for-aws --skill llm-to-bedrock -a claude-code в терминале.
Что делает скилл llm-to-bedrock?
Он автоматически переводит интеграции сторонних LLM на сервисы Amazon Bedrock либо настраивает права доступа к моделям в AWS.
Что нужно для работы llm-to-bedrock?
В системе должен быть установлен uv. Для полного переноса кода также требуется установленный рядом скилл gcp-to-aws или azure-to-aws.
Исходный текст
SKILL.md · Apache-2.0
---
name: llm-to-bedrock
description: "Use to migrate code that calls OpenAI, Gemini/Google AI, or the Anthropic API to Amazon Bedrock — a pure model/SDK rewrite. End-to-end: assesses the codebase, optionally captures OpenAI, OpenRouter, or Anthropic cost and token usage through consent-gated provider APIs, rewrites SDK calls, evaluates output quality against Bedrock, and delivers a ready-to-merge branch. Also has an access-only mode for checking or enabling Bedrock model access for specific models (e.g. 'request access to Claude on Bedrock', 'which models do I turn on') with no code migration — it checks each model and walks the access step, then stops. Not for agent runtime selection or agent migration planning (use agent-advisor), self-hosted LLM batch inference (use self-hosted-llm-batch-inference), nor standalone cost estimates or infra-only migration. The full migration REQUIRES gcp-to-aws OR azure-to-aws installed alongside this skill (gcp-to-aws preferred when both are present); access-only mode needs neither."
---
# Migrate to Bedrock (Assess + Execute)
Single-command AI migration: OpenAI / Gemini / Anthropic → Amazon Bedrock.
**Requires the `gcp-to-aws` OR the `azure-to-aws` skill installed alongside this one.** This
skill has no standalone Assess implementation — Phase A below runs Assess by directly reading
and executing whichever of those two skills is present's own phase instruction files in this
same session (the same inline-execution pattern `agent-advisor` uses for its `migration-plan`
phase: no cross-skill tool call, no turn boundary, and no dependency on your agent supporting a
Skill/subagent dispatch mechanism — reading a file works on any agent). There is no fallback
path that performs Assess itself if neither sibling is present. If you installed this skill on
its own (e.g. a single-skill `npx skills add`), install `gcp-to-aws` or `azure-to-aws` too
before using it.
The skill base directory is given in the "Base directory for this skill: X" line the harness
emits at load time. Call it `<SKILL_BASE>`. Derived paths:
- `$SCRIPTS` = `<SKILL_BASE>/scripts`
- `$HELPERS` = `<SKILL_BASE>/references/helpers` (the former helper skills, now references)
- `$ASSESS_SKILL` / `$ASSESS_BASE` — resolved once, in Step 0b: `$ASSESS_SKILL` is whichever of
`gcp-to-aws` / `azure-to-aws` is installed alongside this skill (`gcp-to-aws` preferred when
both are present), and `$ASSESS_BASE` = `<SKILL_BASE>/../$ASSESS_SKILL` — that sibling skill's
own directory. Phase A reads its instruction files directly off this path; every relative
reference inside an `$ASSESS_SKILL` file (`references/shared/...`, `references/phases/...`,
etc.) resolves under `$ASSESS_BASE`, exactly as it would if `$ASSESS_SKILL` were running
standalone.
---
## Optional usage telemetry
Before starting or resuming, load `references/vendored/telemetry/PROTOCOL.md` and
run its read-only status check. Use the returned reporting mode rather than the
model's identity. Complete the existing notice exchange only when that protocol
requires it; unavailable or declined telemetry never blocks this skill.
## Step 0 — Check prerequisites
### 0a. Check that `uv` is available
```bash
uv --version 2>/dev/null || echo "MISSING"
```
If missing: "Install uv first — see the official install guide: https://docs.astral.sh/uv/getting-started/installation/ (e.g. `brew install uv` or `pipx install uv`)". Stop.
### 0a-bis. Route: full migration vs. access-only
This skill has two modes. Decide which the user wants **before** the Assess-sibling check (0b)
— the access-only mode does not use `gcp-to-aws`/`azure-to-aws` at all, so requiring one of them
there would block a user who only wants access enablement.
If the user wants the Claude apps themselves (Claude Desktop or Claude Code) running on Bedrock,
with no application code to migrate, stop and use `claude-apps-to-bedrock` instead. It calls this
skill's Access-only mode for the model-access step when both are installed.
Route to **Access-only mode** (jump to the "## Access-only mode" section below, skip 0b and
Steps 1+) when either is true:
- `$ARGUMENTS` contains an explicit access-request phrase — `model access`, `request access`,
`enable model access`, `just access`, or `preflight` (and no source-code path). Do **not** route
on the bare words `enable` or `access` alone — "enable the Bedrock rewrite" is a full migration,
not an access request. When in doubt, use the AskUserQuestion below rather than the keyword. **Or**
- the user's request is about *getting Bedrock model access enabled* rather than rewriting code —
e.g. "help me request access to Claude on Bedrock", "enable GPT models on Bedrock", "which
models do I need to turn on", "I just want access, my engineers will do the migration".
If it is ambiguous (the user mentions both a codebase and access), **AskUserQuestion**:
> "Two things I can do — which do you want?
> [Full migration] Rewrite your OpenAI/Gemini/Anthropic calls for Bedrock end-to-end.
> [Just model access] Check and walk you through enabling Bedrock access for specific models,
> no code changes."
`[Just model access]` → Access-only mode. `[Full migration]` → continue to 0b.
Otherwise (a code path / clear rewrite intent) → continue to 0b for the full migration.
### 0b. Check that a gcp-to-aws or azure-to-aws sibling skill is installed
Phase A below runs Assess by directly reading and executing `$ASSESS_SKILL`'s own phase
instruction files (Discover → Clarify → Design → Estimate, AI-only path) in this same
session — there is no Assess logic in this skill to fall back to. `gcp-to-aws` and
`azure-to-aws` are **separate skills**, not bundled inside this one — a single-skill install
(e.g. `npx skills add ... --skill llm-to-bedrock`) does not bring either along automatically.
Check for them now, before promising the user an Assess phase this deployment cannot run:
```bash
if [ -f "<SKILL_BASE>/../gcp-to-aws/SKILL.md" ]; then
ASSESS_SKILL=gcp-to-aws
elif [ -f "<SKILL_BASE>/../azure-to-aws/SKILL.md" ]; then
ASSESS_SKILL=azure-to-aws
else
echo ASSESS_SIBLING_MISSING
fi
```
`$ASSESS_BASE` = `<SKILL_BASE>/../$ASSESS_SKILL`. This checks the sibling directories relative
to `<SKILL_BASE>` (defined above), which works under any install path — native plugin install
and `npx skills add --skill '*'` both place `gcp-to-aws`/`azure-to-aws` as siblings of this
skill's own directory. It does **not** depend on `${CLAUDE_PLUGIN_ROOT}`. **When both are
installed, `gcp-to-aws` wins** — it is this skill's original, more deeply tested integration,
so this preserves today's default behavior for every existing user with both skills installed.
- `$ASSESS_SKILL` resolved (either value) → proceed to Step 1.
- `ASSESS_SIBLING_MISSING` → **stop here — do not proceed.** Tell the user:
> "This migration needs either the `gcp-to-aws` or the `azure-to-aws` skill installed
> alongside this one — it handles code scanning, AI-workload detection, and Bedrock model
> design; I can't do that part myself without it. Both ship in the same `aws-startup-advisor`
> plugin as this skill, so if you installed the whole plugin one of them should already be
> next to me — it looks like only some of the plugin's skills were installed. Install the pair
> together with:
> `npx skills add aws/agent-toolkit-for-aws/plugins/aws-startup-advisor/skills --skill llm-to-bedrock --skill gcp-to-aws`
> (or substitute `azure-to-aws` if your source infra runs on Azure; use the same `--agent` and
> `--global`/project scope you used for this skill), or run that same `npx skills add` command
> with `--skill '*'` instead of naming individual skills to get every skill at once. Then
> restart your agent and ask me to migrate again."
**Do not** perform the Assess phase yourself as a workaround — Phase A below is explicit that
Assess logic lives only in `$ASSESS_SKILL`; re-implementing it here would drift out of sync
with that skill's Discover/Clarify/Design logic over time. There is no standalone Assess for
this skill — this check exists to fail fast and clearly, not to unlock alternate behavior.
Phase A reads `$ASSESS_SKILL`'s files directly off disk rather than invoking it as a skill, so
there is no separate agent-capability requirement here — any agent that can read a file and
run Bash can execute this. (An earlier version of this skill invoked `gcp-to-aws` via a
cross-skill Skill-tool call; that mechanism is Claude-Code-specific and unverified elsewhere,
which is exactly why Phase A no longer uses it.)
---
## Step 1 — Collect source code path
Before using a path from `$ARGUMENTS` or asking for one, tell the user once:
> I need your source repository to identify call sites, capabilities, and migration
> behavior. You do not need to export provider usage reports manually: for direct
> OpenAI, OpenRouter, and direct Anthropic workloads, the assessment can also offer
> consent-gated provider API discovery for aggregate cost and token usage. The
> provider-specific consent screen appears before any API call.
Then continue immediately. This notice advertises the optional capability; it is not
consent and does not replace any provider-specific consent gate.
If `$ARGUMENTS` contains a path, use it as `$REPO`. Otherwise use **AskUserQuestion**:
"Where is your source code? Enter a local path or GitHub URL."
If a GitHub URL, `git clone` it to a temp dir; use that path as `$REPO`.
**Checks on $REPO:**
1. **Git-root check** (compare resolved paths — on macOS `/tmp` resolves to `/private/tmp`,
so a raw string comparison false-positives):
```bash
[ "$(git -C <REPO> rev-parse --show-toplevel 2>/dev/null)" = "$(cd <REPO> && pwd -P)" ] && echo GIT_ROOT_OK || echo GIT_ROOT_MISMATCH
```
- `GIT_ROOT_OK` → proceed.
- `GIT_ROOT_MISMATCH` and the command errored (not a git repo at all) → tell the user the
path must be a git repository (the deliverable is a git branch); re-ask.
- `GIT_ROOT_MISMATCH` but inside a repo (user pointed at a subdirectory) → AskUserQuestion:
"Use the repo root instead" (recommended) / "Continue with this subdirectory" / "Abort".
2. **Dirty-tree check:**
```bash
git -C <REPO> status --porcelain
```
If uncommitted changes exist, show them and AskUserQuestion: "Continue anyway" or "Let me clean up first".
Record `$REPO` for all subsequent steps.
---
## Step 1.5 — Check for an existing usage profile
Before Phase A begins, check whether a prior Discover run (from either `gcp-to-aws` or
`azure-to-aws`) already captured real OpenAI/OpenRouter/Anthropic usage-API spend for this
repo — if so, reuse it as the cost baseline instead of later falling back to golden-dataset
extrapolation. Phase A's own `$MIGRATION_DIR` resolution and resume logic start fresh each
time Phase A is entered, so this step must run strictly before that to have a chance to
short-circuit it.
1. **Glob** every `.migration/<run-dir>/<provider>-usage-profile.json` under `$REPO`,
excluding this skill's own output directory:
```bash
for p in anthropic openai openrouter; do
find "$REPO/.migration" -mindepth 2 -maxdepth 2 -name "${p}-usage-profile.json" \
-not -path "*/.bedrock-*/*" 2>/dev/null
done
```
`-mindepth 2 -maxdepth 2` matches exactly `.migration/<run-dir>/<provider>-usage-profile.json`.
`-not -path "*/.bedrock-*/*"` excludes llm-to-bedrock's own `$BEDROCK_RUN_DIR`
(`.migration/.bedrock-<id>/`) — that directory is this skill's OWN output, never a
gcp/azure Discover output. This glob is provider-named, not skill-named — it finds a
profile regardless of whether `gcp-to-aws`'s or `azure-to-aws`'s Discover wrote it, since
both write to the same filename convention under the same `$REPO/.migration/` tree.
2. **Zero matches across all three** → no change to current behavior; proceed to Phase A
exactly as today.
3. **Determine which run's artifact to use (deterministic tiebreak, source-run status
surfaced):** for each distinct run directory with at least one match, read that
directory's `.phase-status.json` → `last_updated` (a full ISO-8601 timestamp, which DOES
carry the year) and use it as the **primary** sort key — the greatest `last_updated` wins.
**Do not treat the directory's own `<MMDD-HHMM>` name as chronological on its own:** a
plain lexicographic comparison of `<MMDD-HHMM>` is only chronological WITHIN a single
calendar year — `1231-1200` (Dec 31) lexicographically sorts after `0102-1200` (Jan 2) of
the FOLLOWING, objectively later year, so using the name alone can pick a stale run. Fall
back to the `<MMDD-HHMM>` directory name ONLY when a candidate's `last_updated` is
missing or unparseable, and when you do, say so explicitly — that fallback is a same-year
assumption, not a general chronological guarantee, and must never be presented to the user
as equivalent to a real timestamp comparison. Use `.phase-status.json` → `current_phase`
as a secondary piece of information to SURFACE to the user (not to break ties) — e.g. a
run whose `current_phase` shows Discover never advanced past Clarify tells the user this
was likely an abandoned/declined session, even though its usage-profile file is still the
most recent one. **State both pieces to the user explicitly before adopting the
figures:** *"Found an existing [provider] usage profile from your `<MMDD-HHMM>` run
(status: `<current_phase>`) — using that one."* If a run directory's `.phase-status.json`
is missing/unparseable entirely, still allow it as a candidate via the `<MMDD-HHMM>`
fallback, but surface `status: unknown` instead of a phase name. **Genuine tie or
ambiguity** (two or more candidates all lack a usable `last_updated`, so only the
same-year-limited `<MMDD-HHMM>` fallback is available for them, or their `last_updated`
values are otherwise ambiguous): do NOT silently guess — surface every ambiguous candidate
to the user (directory name + whatever status is known for each) and ask which one is
actually the one to use, reusing the "state both pieces to the user explicitly" pattern
above rather than picking one automatically.
4. For the winning run directory, read **every** usage-profile file present in it (a run can
have multiple providers' profiles simultaneously — including a mix of gcp-produced and
azure-produced profiles — B1 does not need to distinguish which skill wrote which file,
since the profile schema itself is identical regardless of producer).
5. For each profile: check `metadata.capture_warnings` first. A warning that names
`usage-completions-hourly.json`, `usage-completions-minute.json`,
`usage-messages-hourly.json`, `usage-messages-minute.json`, or
`analytics-hourly.json` means the peak is uncertain. Keep that profile's daily
volume and cost. Any other non-empty warning means some endpoint failed and
that category's volume is UNKNOWN, not zero; propagate the caveat forward.
6. Compute `summary.monthly_cost_usd` SUMMED across every profile in the winning run (never
max/pick-one, reusing `estimate-ai.md`'s documented SUM discipline from both skills —
gcp's and azure's `estimate-ai.md` apply the identical rule), combining `usage_by_model[]`
with the same normalization rules (OpenRouter `prompt_tokens`/`completion_tokens` →
`input_tokens`/`output_tokens`; Anthropic `cache_read_tokens` stay in the volume
sum. `cache_creation_tokens` is NOT folded into `input_tokens`. When the row has
`cache_creation_5m_tokens` and `cache_creation_1h_tokens`, copy both onto the
baseline row as `cache_write_5m` and `cache_write_1h`. They are the split of
`cache_creation_tokens`; do not add them on top of that sum. When only the
aggregate `cache_creation_tokens` is present (an older profile), copy it as
`cache_write_unsplit` and do not price it at the ordinary input rate. OpenAI
`input_tokens` already includes `input_cache_write_tokens`. When that field is
present, subtract it from the baseline row's `input_tokens` and copy it to
`cache_write_unsplit`. Do not leave those tokens in `input_tokens`, and do not
add them on top. The usage response does not name a 5-minute or 1-hour write
duration, so this stays the unpriced component rather than an ordinary-input
price. `input_cached_tokens` stay inside `input_tokens`. See
`estimate-ai.md`'s Prerequisites section in either sibling skill for the
`uncached_input_tokens + cache_read_input_tokens + cache_creation_input_tokens`
contract). Apply the
`metadata.partial_window` exception: a
partial-window profile's figures are a reference figure labeled with `active_days`, never
blended into the monthly baseline (schema consequence specified below). **Second, parallel
exception — `metadata.cost_status` (written by the Anthropic usage profile and by
bedrock-migration-assessment's OpenAI usage profile):** a profile whose `cost_status` is `"cost_unavailable"` has `null` for
`summary.monthly_cost_usd` — EXCLUDE it from this dollar SUM entirely (never add `null`,
never substitute `0`), but STILL include its `usage_by_model[]` token totals in
`usage_by_model[]` below — usage succeeded for that profile, only its cost side failed. This
mirrors the `partial_window` exception's shape (one disqualifies dollars only, the other
disqualifies dollars only) but is a distinct, independent condition — a profile can be
`partial_window: false` and still `cost_status: "cost_unavailable"`. **Third exception —
OpenRouter BYOK/overlap de-duplication:** when BOTH an `openrouter-usage-profile.json` and
a direct provider profile (`anthropic-usage-profile.json` or `openai-usage-profile.json`)
exist in the winning run directory, resolve the overlap. Match models across the two
profiles the same way regardless of which branch below applies — OpenRouter's
`usage_by_model[].model` uses a `provider/model-name` form (e.g. `"openai/gpt-4.1"`); a
model is "the same" as the direct profile's bare model name (e.g. `"claude-sonnet-5"`) if
the direct name equals the OpenRouter model name's substring after its last `/`.
**Gate on field presence, not on the profile-level value, for backward compatibility:**
if the OpenRouter profile has NO `usage_by_model[].cost_provenance` field at all (an OLD
profile written before per-model detection existed), fall straight into the pre-existing
blanket-unknown behavior described below — do not require the per-model field to be
present, since old `.migration/` run directories on disk will not have it. If the field
IS present (a new-format profile), use the **per-model branch** instead:
- For each OpenRouter `usage_by_model[]` row whose model name-matches a model on the direct
profile:
- row's `cost_provenance` is `"byok_passthrough"` → EXCLUDE this row's dollar AND token
figures from this SUM entirely (not dollars alone — the direct profile already counts
that traffic's tokens, so including OpenRouter's figures too would double-count both;
the same underlying provider spend would otherwise be counted twice — once via the
direct provider's own usage API, once via OpenRouter routing the same traffic). Prefer
the direct provider's own figure for this model as ground truth. **Exception —
OpenRouter's own router/credit fee is a REAL, distinct charge, not a duplicate:** a
pure-BYOK row's `monthly_cost_usd` is OpenRouter's own `/activity.usage` field (per
https://openrouter.ai/docs/api/api-reference/analytics/get-user-activity.md,
`usage` = "Total cost in USD (OpenRouter credits spent)"), which is SEPARATE from the
external provider's own inference bill (`/activity.byok_usage_inference` — "BYOK
inference cost in USD (external credits spent)") that the direct profile already
counts. Excluding the row's TOKEN figures is always correct (the direct profile already
counts those tokens). But if this row's `monthly_cost_usd` (i.e. its summed `usage`) is
nonzero, that dollar amount is OpenRouter's router fee, NOT the duplicated inference
cost — dropping it silently would undercount by exactly that fee. When excluding a
`byok_passthrough` row with a nonzero `monthly_cost_usd`, append a
`capture_warnings` entry (reusing the exact mechanism round 4's `"mixed"`-row
disclosure already established): `"<model> classified byok_passthrough — its $<amount>
OpenRouter router/credit fee was excluded from this baseline along with its (correctly
excluded, already-duplicated) token figures; this fee is a real charge NOT reflected in
the figure above."` When `monthly_cost_usd` is zero (or negligible, same $0.005
threshold `discover-openrouter-api.md`'s classification already uses), no disclosure is
needed — there is no fee to lose, matching today's behavior exactly. When the row
has `byok_fees_usd` greater than the same $0.005 threshold, ADD `byok_fees_usd` to
the dollar sum and do not emit the exclusion warning for that amount: tokens stay
excluded (they are already on the direct profile) and `byok_fees_usd` is the router
fee alone, which `monthly_cost_usd` is not. When `byok_fees_usd` is absent — a
profile written before that field — Do NOT add this fee back INTO the baseline sum.
That older `monthly_cost_usd` is one combined figure, so disclosure is the accurate
fix and adding it would double-count inference.
- row's `cost_provenance` is `"mixed"` → EXCLUDE this row's dollar AND token figures from
this SUM entirely, for the same double-counting reason as `byok_passthrough` above.
**UNLIKE `byok_passthrough`, do NOT silently drop the independent portion:** a `"mixed"`
row has BOTH BYOK-passthrough traffic (already counted via the direct profile) AND
genuinely independent, OpenRouter-credit-funded traffic that this exclusion also removes
with no other home — that independent portion is real spend missing from the baseline,
not spend double-counted elsewhere. Carry an explicit undercount disclosure for every
excluded `"mixed"` row into both the computed baseline's warnings (append to
`capture_warnings` — see below) and the user-facing summary: `"<model> classified mixed
(BYOK + independent OpenRouter usage) — excluded entirely to avoid double-counting the
BYOK portion, but this also drops its independent OpenRouter-funded usage from the
baseline, which is NOT reflected in the figure above."` Do NOT attempt to estimate or
back out the independent portion's dollar/token split from the enum alone — the enum has
no signal for how much of the row's usage is which; only disclose that it is missing.
If `byok_request_count` and `analytics_request_count` are both present, you may state
the request share in that same disclosure. Do not apply that ratio to tokens or to
inference dollars. Do
NOT make any unsupported "complete cost" or "savings" claim when this warning fires —
match the honest-disclosure pattern already used for `cost_unavailable`/
`partial_window` above.
- row's `cost_provenance` is `"no_byok"` → do **NOT** exclude; this is a confirmed
non-overlapping-provider case, so OpenRouter's own figures for this model are the
correct spend to sum (more precise than the blanket-unknown fallback below).
- row's `cost_provenance` is `"unknown"` → fall back to the conservative "match by name,
exclude everything that matches" behavior for this row only (same as the old-profile
path below), and keep the same caveat sentence, but scope it to just the rows that
actually used the fallback this run (not every overlapping model, since some may have
resolved via `no_byok`/`byok_passthrough`/`mixed`).
- row's `cost_provenance` is `"uncertain"` → apply the SAME conservative handling as
`"unknown"` immediately above: EXCLUDE this row's dollar AND token figures from this
SUM entirely (match-by-name exclusion), using the identical caveat sentence scoped to
rows that used this fallback this run. Do NOT reuse `"mixed"`'s undercount-disclosure
branch — `"uncertain"` means at least one contributing permaslug had NO Analytics
signal (partial verification), not a confirmed independent OpenRouter-funded portion
like `"mixed"` has; there is nothing concrete to disclose beyond what
`discover-openrouter-api.md`'s own `capture_warnings` entry for this model already
states at capture time. Reusing `"unknown"`'s policy here, rather than inventing a
distinct `"uncertain"` rule, keeps the SAME double-counting protection for a value that
is strictly less certain than `"unknown"`'s already-conservative default.
- Keep every OpenRouter-only model (no match on the direct profile) in the sum as before.
- The profile-level `metadata.cost_provenance` field is NOT read to decide whether this
per-model branch runs — only the presence of the per-model field decides that (see gate
above).
**Old-profile fallback (no per-model field present):** there is no reliable signal to
resolve the overlap automatically — match models across the two profiles (same name-match
rule above). For every OpenRouter `usage_by_model[]` row whose model matches a model present
on the direct profile, EXCLUDE that row's dollar AND token figures from this SUM entirely.
Keep every OpenRouter-only model (no match on the direct profile) in the sum as before. Flag
the exclusion in the summary presented to the user as "OpenRouter and \<provider\> usage
profiles both present; N overlapping model(s) excluded from OpenRouter's totals to avoid
double-counting BYOK traffic — provenance is unknown, so this exclusion assumes full overlap
for those models, which may undercount if OpenRouter is only partially BYOK-routing them."
7. **Hold these computed figures — do not write them yet.** `$BEDROCK_RUN_DIR` does not exist
at this point in the document (it is only established in "### A3 — Locate Assess output,
then establish this skill's own run state" below, after Phase A runs); writing to it here
would write to a directory variable that is not yet assigned. Carry the computed
`source_run_dir`, `source_profiles`,
`captured_at`, `capture_warnings`, `windows`, `summary`, and `usage_by_model[]` values
forward (the shape is specified in "New artifact" below) and present the short summary now:
*"Found existing usage data: $X/month across N models (source: [provider list], captured
`<date>`). I'll use this as your current-cost baseline instead of estimating from sampled
golden-dataset traffic."* The actual file write happens in A3, immediately after
`$BEDROCK_RUN_DIR` is set — see the cross-reference there.
8. **This step never prompts for consent** — it only reads a file a prior, already-consented
run already wrote. No new attack surface; no new consent gate needed.
9. **Idempotency:** this step is safe to re-run on every Phase-B start, including a resumed
session (A2's resume path). It performs read-only file operations only — the actual write
of `usage-baseline.json` happens later, in A3 (see step 7 above), and that write is itself
idempotent — overwriting `usage-baseline.json` on a rerun with the same inputs produces the
same output, and a rerun with DIFFERENT inputs (e.g. a newer profile appeared since the
last run) correctly re-resolves and overwrites. Re-running this step on a resume where it
already ran is therefore harmless; it is not gated behind any "already ran" check.
### New artifact: `$BEDROCK_RUN_DIR/usage-baseline.json`
Written to `$BEDROCK_RUN_DIR` (`$REPO/.migration/.bedrock-<id>/`) in "### A3 — Locate Assess
output, then establish this skill's own run state" below, immediately after
`$BEDROCK_RUN_DIR` is set — **not** at Step 1.5 itself, since `$BEDROCK_RUN_DIR` does not
exist yet when Step 1.5 runs (Step 1.5's steps 1–6 above still run here, before Phase A, so
Phase A1's own fresh-Discover fallback decision can short-circuit correctly; only the file
WRITE is deferred). This gives Phase C's report-generator a stable, already-resolved place
to read from without re-globbing `.migration/*/` itself (that glob belongs only to this
step).
**Schema (per-provider window-status map, so a mixed partial/full combination is
representable):**
```json
{
"source_run_dir": ".migration/0315-1030",
"source_profiles": ["anthropic-usage-profile.json", "openai-usage-profile.json"],
"captured_at": "<ISO 8601, max across source profiles>",
"capture_warnings": [],
"windows": {
"anthropic": { "window_days": 30, "active_days": 12, "partial_window": true, "cost_status": "partial_window" },
"openai": { "window_days": 30, "active_days": 30, "partial_window": false, "cost_status": "complete" }
},
"summary": {
"monthly_cost_usd": 0.0,
"monthly_cost_usd_is_blended_estimate": true,
"currency": "USD",
"models_seen": 0
},
"usage_by_model": [
{
"model": "string",
"provider": "openai|anthropic|openrouter",
"partial_window": true,
"input_tokens": 0,
"output_tokens": 0,
"cache_write_5m": 0,
"cache_write_1h": 0,
"cache_write_unsplit": 0,
"num_model_requests": 0
}
]
}
```
**Validation rules:**
- `source_profiles` is non-empty (the file is only written when this step found at least one
profile — absence of the file, not an empty array, signals "no existing profile found").
- `windows` is keyed by every provider contributing to `usage_by_model[]`; a provider absent
from `windows` must not appear in `usage_by_model[]` either.
- `usage_by_model[].provider` disambiguates...
© aws · Apache-2.0 · aws/agent-toolkit-for-aws