@kapybara/zerosub 1.18.3 → 1.19.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,437 @@
1
+ import { createHash } from "node:crypto";
2
+ import { existsSync } from "node:fs";
3
+ import { mkdir, readdir, readFile } from "node:fs/promises";
4
+ import { request } from "node:http";
5
+ import { homedir } from "node:os";
6
+ import { join } from "node:path";
7
+ import {
8
+ BedrockModelsSchema,
9
+ BedrockSourceSchema,
10
+ type ApiMonth,
11
+ type ApiPrice,
12
+ type BedrockModels,
13
+ type BedrockSource,
14
+ type BedrockSummary,
15
+ type TokenCount,
16
+ } from "../shared/model";
17
+ import type { EnvPatch } from "./adapter";
18
+ import { cleanPrices } from "./api-usage";
19
+ import { readJson, writeJsonAtomic } from "./json-file";
20
+ import { mainClaudeDir } from "./paths";
21
+ import { run, type RunResult } from "./process";
22
+ import { providerEnv } from "./provider-env";
23
+
24
+ /**
25
+ * AWS Bedrock accounts: a Claude account that runs Claude Code on Amazon Bedrock instead of a Claude
26
+ * subscription. Its home is a Claude home like any added account's (shared entries linked, settings
27
+ * generated), with no sign-in in it, except:
28
+ *
29
+ * - `bedrock.json` (mode 600) holds the region, where its AWS credentials come from, model overrides
30
+ * and the price table, and, only for an access key, the key. It's private to every Claude home, so
31
+ * none links it in from `~/.claude`, and nothing in it is ever logged or sent to the app.
32
+ * - Each session gets `CLAUDE_CODE_USE_BEDROCK=1` and the AWS variables of its source (see
33
+ * `bedrockEnv`), and the generated `settings.json` is made to agree (see `bedrockSettings`).
34
+ */
35
+
36
+ export const BEDROCK_FILE = "bedrock.json";
37
+
38
+ export interface BedrockAccount {
39
+ region: string;
40
+ source: BedrockSource;
41
+ profile: string | null;
42
+ accessKeyId: string | null;
43
+ secretAccessKey: string | null;
44
+ sessionToken: string | null;
45
+ models: BedrockModels;
46
+ prices: Record<string, ApiPrice>;
47
+ }
48
+
49
+ /** Claude Code's model variables, by the override they come from. */
50
+ export const MODEL_ENV: Readonly<Record<keyof BedrockModels, string>> = {
51
+ model: "ANTHROPIC_MODEL",
52
+ opus: "ANTHROPIC_DEFAULT_OPUS_MODEL",
53
+ sonnet: "ANTHROPIC_DEFAULT_SONNET_MODEL",
54
+ haiku: "ANTHROPIC_DEFAULT_HAIKU_MODEL",
55
+ };
56
+
57
+ /** AWS credentials from the environment, which the default chain reads before a profile. */
58
+ const AWS_KEY_ENV = ["AWS_ACCESS_KEY_ID", "AWS_SECRET_ACCESS_KEY", "AWS_SESSION_TOKEN"] as const;
59
+ /** A Bedrock API key, which Claude Code uses before any AWS credentials. */
60
+ const AWS_BEARER_ENV = "AWS_BEARER_TOKEN_BEDROCK";
61
+ /**
62
+ * What would send a Bedrock account's sessions to another Claude provider, sign them in with a key
63
+ * or token instead, or skip AWS auth: blanked for every session, and in its settings.
64
+ */
65
+ const OTHER_PROVIDER_ENV = [
66
+ "ANTHROPIC_API_KEY",
67
+ "ANTHROPIC_AUTH_TOKEN",
68
+ "CLAUDE_CODE_OAUTH_TOKEN",
69
+ "ANTHROPIC_BASE_URL",
70
+ "ANTHROPIC_CUSTOM_HEADERS",
71
+ "CLAUDE_CODE_USE_VERTEX",
72
+ "CLAUDE_CODE_USE_FOUNDRY",
73
+ "CLAUDE_CODE_USE_ANTHROPIC_AWS",
74
+ "CLAUDE_CODE_USE_ANTHROPIC_GOOGLE_CLOUD",
75
+ "CLAUDE_CODE_USE_MANTLE",
76
+ "CLAUDE_CODE_SKIP_BEDROCK_AUTH",
77
+ ] as const;
78
+
79
+ const REGION = /^[a-z]{2}(?:-[a-z]+)+-\d{1,2}$/;
80
+
81
+ /**
82
+ * Whether `home` is an AWS Bedrock account's (it has `bedrock.json`), for the Claude adapter, which
83
+ * only sees homes. The registry marks the account itself (`provider: "bedrock"`), and that's what
84
+ * routing and the app go by. No other Claude home can have the file: it's never linked in.
85
+ */
86
+ export function isBedrockHome(home: string | null | undefined): home is string {
87
+ return Boolean(home) && existsSync(join(home!, BEDROCK_FILE));
88
+ }
89
+
90
+ /** An AWS region code, like `us-east-1` or `eu-central-1`. */
91
+ export function normalizeRegion(input: string): string {
92
+ const region = input.trim().toLowerCase();
93
+ if (!REGION.test(region)) throw new Error("Enter the AWS region as a code, like eu-central-1");
94
+ return region;
95
+ }
96
+
97
+ function text(value: unknown): string | null {
98
+ return typeof value === "string" && value.trim() ? value.trim() : null;
99
+ }
100
+
101
+ const NO_MODELS: BedrockModels = { model: "", opus: "", sonnet: "", haiku: "" };
102
+
103
+ /** The account's settings; throws when the file is missing or unusable. */
104
+ export async function readBedrockAccount(home: string): Promise<BedrockAccount> {
105
+ const raw = await readJson(join(home, BEDROCK_FILE)).catch(() => undefined);
106
+ const value = raw && typeof raw === "object" ? (raw as Record<string, unknown>) : null;
107
+ const region = text(value?.region);
108
+ const source = BedrockSourceSchema.safeParse(value?.source);
109
+ if (!region || !REGION.test(region) || !source.success) throw new Error(`${home} has no readable ${BEDROCK_FILE}`);
110
+ const account: BedrockAccount = {
111
+ region,
112
+ source: source.data,
113
+ profile: text(value?.profile),
114
+ accessKeyId: text(value?.accessKeyId),
115
+ secretAccessKey: text(value?.secretAccessKey),
116
+ sessionToken: text(value?.sessionToken),
117
+ models: BedrockModelsSchema.safeParse(value?.models ?? {}).data ?? { ...NO_MODELS },
118
+ prices: cleanPrices(value?.prices),
119
+ };
120
+ if (account.source === "profile" && !account.profile) throw new Error(`${home}'s ${BEDROCK_FILE} names no profile`);
121
+ if (account.source === "keys" && (!account.accessKeyId || !account.secretAccessKey)) throw new Error(`${home}'s ${BEDROCK_FILE} has no access key`);
122
+ return account;
123
+ }
124
+
125
+ /** Writes the account's settings, readable only by the user. Only the fields its source uses are kept. */
126
+ export async function writeBedrockAccount(home: string, account: BedrockAccount): Promise<void> {
127
+ await mkdir(home, { recursive: true, mode: 0o700 });
128
+ const value: Record<string, unknown> = { region: account.region, source: account.source, models: account.models, prices: account.prices };
129
+ if (account.source === "profile") value.profile = account.profile;
130
+ if (account.source === "keys") {
131
+ value.accessKeyId = account.accessKeyId;
132
+ value.secretAccessKey = account.secretAccessKey;
133
+ if (account.sessionToken) value.sessionToken = account.sessionToken;
134
+ }
135
+ await writeJsonAtomic(join(home, BEDROCK_FILE), value, { mode: 0o600 });
136
+ }
137
+
138
+ /** What the app may see of the account: never the secret or session token, only the access key ID's last four characters. */
139
+ export function bedrockSummary(account: BedrockAccount, usage: ApiMonth | null): BedrockSummary {
140
+ return {
141
+ region: account.region,
142
+ source: account.source,
143
+ profile: account.source === "profile" ? account.profile : null,
144
+ keyHint: account.source === "keys" && account.accessKeyId ? account.accessKeyId.slice(-4) : null,
145
+ sessionToken: account.source === "keys" && Boolean(account.sessionToken),
146
+ models: account.models,
147
+ prices: account.prices,
148
+ usage,
149
+ };
150
+ }
151
+
152
+ /** Tells two Bedrock accounts apart without storing a secret: region and source (a key by a short hash of its ID). */
153
+ export function bedrockIdentity(account: Pick<BedrockAccount, "region" | "source" | "profile" | "accessKeyId">): string {
154
+ const who =
155
+ account.source === "profile"
156
+ ? `profile:${account.profile}`
157
+ : account.source === "keys"
158
+ ? `key:${createHash("sha256").update(account.accessKeyId ?? "").digest("hex").slice(0, 16)}`
159
+ : "host";
160
+ return `bedrock|${account.region}|${who}`;
161
+ }
162
+
163
+ /**
164
+ * A session's environment on the account: Claude Code on Bedrock in its region, with the AWS
165
+ * credentials of its source, and nothing that would send it elsewhere. Variables another source would
166
+ * read first are blanked: environment keys outrank a profile, and a Bedrock API key outranks both.
167
+ * The host source leaves the AWS variables the daemon has as they are (that's its default chain).
168
+ * A model without an override is blanked too, so Claude Code's own Bedrock defaults apply rather than
169
+ * a first-party model ID the daemon names for subscriptions.
170
+ */
171
+ export function bedrockEnv(account: BedrockAccount): EnvPatch {
172
+ const patch: EnvPatch = { CLAUDE_CODE_USE_BEDROCK: "1", AWS_REGION: account.region, AWS_DEFAULT_REGION: account.region };
173
+ for (const key of OTHER_PROVIDER_ENV) patch[key] = "";
174
+ if (account.source === "profile") {
175
+ patch.AWS_PROFILE = account.profile ?? "";
176
+ for (const key of AWS_KEY_ENV) patch[key] = "";
177
+ patch[AWS_BEARER_ENV] = "";
178
+ } else if (account.source === "keys") {
179
+ patch.AWS_ACCESS_KEY_ID = account.accessKeyId ?? "";
180
+ patch.AWS_SECRET_ACCESS_KEY = account.secretAccessKey ?? "";
181
+ patch.AWS_SESSION_TOKEN = account.sessionToken ?? "";
182
+ patch.AWS_PROFILE = "";
183
+ patch[AWS_BEARER_ENV] = "";
184
+ }
185
+ for (const [field, name] of Object.entries(MODEL_ENV) as Array<[keyof BedrockModels, string]>) patch[name] = account.models[field].trim();
186
+ return patch;
187
+ }
188
+
189
+ type Json = Record<string, unknown>;
190
+
191
+ /**
192
+ * The account's generated `settings.json` (main's with the account's own overrides, as for any added
193
+ * account: see `accountSettings` in homes.ts), made to agree with its sessions' environment. Claude
194
+ * Code applies `env` from settings over what it's started with, so main's `env` could otherwise turn
195
+ * Bedrock off, send it to another provider, or put other AWS credentials or model IDs in place of the
196
+ * account's: those are blanked or set here, as #65 does for API-key accounts. `apiKeyHelper` goes too
197
+ * (it would sign the account in with a key instead), and, unless the account uses the host's own AWS
198
+ * setup, `awsAuthRefresh` and `awsCredentialExport`, which fetch credentials of their own. A proxy
199
+ * the account has of its own (and its no-proxy list) stays. Secrets never go in here: an access key
200
+ * reaches a session only through its environment.
201
+ */
202
+ export function bedrockSettings(generated: Json, account: BedrockAccount): Json {
203
+ const settings: Json = { ...generated };
204
+ delete settings.apiKeyHelper;
205
+ if (account.source !== "host") {
206
+ delete settings.awsAuthRefresh;
207
+ delete settings.awsCredentialExport;
208
+ }
209
+ const env: Json = settings.env && typeof settings.env === "object" && !Array.isArray(settings.env) ? { ...(settings.env as Json) } : {};
210
+ for (const key of OTHER_PROVIDER_ENV) env[key] = "";
211
+ env.CLAUDE_CODE_USE_BEDROCK = "1";
212
+ env.AWS_REGION = account.region;
213
+ delete env.AWS_DEFAULT_REGION;
214
+ if (account.source === "profile") {
215
+ env.AWS_PROFILE = account.profile ?? "";
216
+ for (const key of AWS_KEY_ENV) env[key] = "";
217
+ env[AWS_BEARER_ENV] = "";
218
+ } else if (account.source === "keys") {
219
+ // Left out, never blanked: a blank here would beat the key the session is started with.
220
+ for (const key of AWS_KEY_ENV) delete env[key];
221
+ env.AWS_PROFILE = "";
222
+ env[AWS_BEARER_ENV] = "";
223
+ }
224
+ for (const [field, name] of Object.entries(MODEL_ENV) as Array<[keyof BedrockModels, string]>) {
225
+ const model = account.models[field].trim();
226
+ if (model) env[name] = model;
227
+ else delete env[name];
228
+ }
229
+ settings.env = env;
230
+ return settings;
231
+ }
232
+
233
+ // --------------------------------------------------------------------------- checking credentials
234
+
235
+ export type BedrockCheck = { ok: true; detail: string | null } | { ok: false; fatal: boolean; message: string };
236
+
237
+ /** The AWS CLI's (and AWS's) words for credentials that are missing, wrong or refused. */
238
+ const AWS_AUTH_FAILURE =
239
+ /Unable to locate credentials|InvalidClientTokenId|SignatureDoesNotMatch|ExpiredToken|UnrecognizedClientException|InvalidSignatureException|AuthFailure|security token included in the request is (?:invalid|expired)|The config profile \(.+\) could not be found|Error loading SSO Token|Token has expired|AccessDenied/i;
240
+ const AWS_NETWORK_FAILURE = /Could not connect|EndpointConnectionError|Connect timeout|Read timeout|timed out|Name or service not known|getaddrinfo|ENOTFOUND|ECONNREFUSED|ProxyConnectionError/i;
241
+
242
+ export type AwsRunner = (args: readonly string[], env: NodeJS.ProcessEnv) => Promise<RunResult>;
243
+
244
+ const awsCli: AwsRunner = (args, env) => run("aws", args, { env, timeoutMs: 20_000 });
245
+
246
+ /** The environment the `aws` CLI checks the account with: the daemon's (and Paseo's for Claude), with the account's AWS variables. */
247
+ export function checkEnv(account: BedrockAccount, base: NodeJS.ProcessEnv = { ...process.env, ...providerEnv("claude") }): NodeJS.ProcessEnv {
248
+ const env: NodeJS.ProcessEnv = { ...base, AWS_PAGER: "" };
249
+ for (const [key, value] of Object.entries(bedrockEnv(account))) {
250
+ if (!key.startsWith("AWS_")) continue;
251
+ if (value === null || value === "") delete env[key];
252
+ else env[key] = value;
253
+ }
254
+ return env;
255
+ }
256
+
257
+ /** The last lines of the CLI's answer, without the secret or session token. */
258
+ function scrub(message: string, account: BedrockAccount): string {
259
+ let out = message.trim().split("\n").filter(Boolean).slice(-2).join(" ");
260
+ for (const secret of [account.secretAccessKey, account.sessionToken]) if (secret) out = out.replaceAll(secret, "…");
261
+ return out.slice(0, 400);
262
+ }
263
+
264
+ /**
265
+ * Checks the account's credentials with the `aws` CLI, if the host has it: `sts get-caller-identity`
266
+ * (who they are), then `bedrock list-inference-profiles` in the region (that Bedrock answers them).
267
+ * Missing, wrong or expired credentials are `fatal`. Anything else (no CLI, the network, a role that
268
+ * may call Claude models but not list profiles) is only a warning: the first turn tells for sure.
269
+ */
270
+ export async function checkBedrock(account: BedrockAccount, runner: AwsRunner = awsCli): Promise<BedrockCheck> {
271
+ const env = checkEnv(account);
272
+ const who = await runner(["sts", "get-caller-identity", "--output", "json", "--region", account.region], env);
273
+ if (who.code === null && /ENOENT|not found/i.test(who.stderr)) {
274
+ return { ok: false, fatal: false, message: "The aws command isn't installed here, so the credentials weren't checked; the first agent turn will tell." };
275
+ }
276
+ if (who.timedOut) return { ok: false, fatal: false, message: "AWS didn't answer in time, so the credentials weren't checked." };
277
+ if (who.code !== 0) {
278
+ const detail = scrub(who.stderr || who.stdout, account);
279
+ if (AWS_NETWORK_FAILURE.test(detail)) return { ok: false, fatal: false, message: `AWS couldn't be reached, so the credentials weren't checked: ${detail}` };
280
+ if (AWS_AUTH_FAILURE.test(detail)) return { ok: false, fatal: true, message: `AWS refused the credentials: ${detail}` };
281
+ return { ok: false, fatal: false, message: `Couldn't check the credentials: ${detail}` };
282
+ }
283
+ let arn: string | null = null;
284
+ try {
285
+ arn = text((JSON.parse(who.stdout) as { Arn?: unknown }).Arn);
286
+ } catch {
287
+ // Only shown.
288
+ }
289
+ const profiles = await runner(["bedrock", "list-inference-profiles", "--max-results", "1", "--region", account.region, "--output", "json"], env);
290
+ if (profiles.code !== 0) {
291
+ const detail = scrub(profiles.stderr || profiles.stdout, account);
292
+ const why = profiles.timedOut || AWS_NETWORK_FAILURE.test(detail) ? "Bedrock couldn't be reached" : "Bedrock didn't list inference profiles for them";
293
+ return { ok: false, fatal: false, message: `The credentials work${arn ? ` (${arn})` : ""}, but ${why}: ${detail || "no answer"}` };
294
+ }
295
+ return { ok: true, detail: arn };
296
+ }
297
+
298
+ // --------------------------------------------------------------------------- the host's region
299
+
300
+ /** Where a region the host names came from. */
301
+ export type RegionSource = "environment" | "config" | "instance";
302
+
303
+ export interface RegionLookup {
304
+ /** The daemon's environment, for AWS_REGION, AWS_DEFAULT_REGION, AWS_PROFILE and AWS_CONFIG_FILE. */
305
+ env?: NodeJS.ProcessEnv;
306
+ /** Asks the EC2 instance metadata service, giving up after `timeoutMs`. */
307
+ instance?: (timeoutMs: number) => Promise<string | null>;
308
+ /** How long the whole lookup may take. */
309
+ timeoutMs?: number;
310
+ }
311
+
312
+ /** How long the Bedrock form waits for the host's region before leaving the field for the user. */
313
+ export const REGION_LOOKUP_MS = 1_500;
314
+
315
+ /** The region in the AWS config file for the profile the daemon would use. */
316
+ async function configRegion(env: NodeJS.ProcessEnv): Promise<string | null> {
317
+ const path = env.AWS_CONFIG_FILE?.trim() || join(homedir(), ".aws", "config");
318
+ const config = await readFile(path, "utf8").catch(() => "");
319
+ const profile = env.AWS_PROFILE?.trim() || "default";
320
+ const escaped = profile.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
321
+ const header = profile === "default" ? /^\s*\[\s*(?:default|profile\s+default)\s*\]/ : new RegExp(`^\\s*\\[\\s*profile\\s+${escaped}\\s*\\]`);
322
+ let inSection = false;
323
+ for (const line of config.split("\n")) {
324
+ if (/^\s*\[/.test(line)) inSection = header.test(line);
325
+ else if (inSection) {
326
+ const match = /^\s*region\s*=\s*([a-z0-9-]+)/.exec(line);
327
+ if (match?.[1] && REGION.test(match[1])) return match[1];
328
+ }
329
+ }
330
+ return null;
331
+ }
332
+
333
+ /** The EC2 instance's region, from its metadata service (IMDSv2), when the host is one. */
334
+ export function instanceRegion(timeoutMs: number): Promise<string | null> {
335
+ const call = (method: string, path: string, headers: Record<string, string>) =>
336
+ new Promise<string | null>((resolve) => {
337
+ const req = request({ host: "169.254.169.254", path, method, headers, timeout: timeoutMs }, (res) => {
338
+ let body = "";
339
+ res.setEncoding("utf8");
340
+ res.on("data", (chunk: string) => (body += chunk));
341
+ res.on("end", () => resolve(res.statusCode === 200 ? body : null));
342
+ res.on("error", () => resolve(null));
343
+ });
344
+ req.on("timeout", () => req.destroy());
345
+ req.on("error", () => resolve(null));
346
+ req.end();
347
+ });
348
+ return (async () => {
349
+ const token = await call("PUT", "/latest/api/token", { "X-aws-ec2-metadata-token-ttl-seconds": "60" });
350
+ const region = (await call("GET", "/latest/meta-data/placement/region", token ? { "X-aws-ec2-metadata-token": token } : {}))?.trim();
351
+ return region && REGION.test(region) ? region : null;
352
+ })();
353
+ }
354
+
355
+ /**
356
+ * The region the host's own AWS setup names, to fill in the Bedrock form: the daemon's environment,
357
+ * then the AWS config file, then (on an EC2 instance) its metadata service. Only asked for when that
358
+ * form opens, never at startup, and given up on after `timeoutMs`: off EC2 the metadata service
359
+ * never answers, so the field is left for the user to fill.
360
+ */
361
+ export async function detectHostRegion(lookup: RegionLookup = {}): Promise<{ region: string | null; source: RegionSource | null }> {
362
+ const env = lookup.env ?? process.env;
363
+ const timeoutMs = lookup.timeoutMs ?? REGION_LOOKUP_MS;
364
+ const named = env.AWS_REGION?.trim().toLowerCase() || env.AWS_DEFAULT_REGION?.trim().toLowerCase();
365
+ if (named && REGION.test(named)) return { region: named, source: "environment" };
366
+ const configured = await configRegion(env).catch(() => null);
367
+ if (configured) return { region: configured, source: "config" };
368
+ let timer: ReturnType<typeof setTimeout> | undefined;
369
+ const late = new Promise<null>((resolve) => {
370
+ timer = setTimeout(() => resolve(null), timeoutMs);
371
+ timer.unref?.();
372
+ });
373
+ const instance = await Promise.race([(lookup.instance ?? instanceRegion)(Math.max(100, timeoutMs / 2)).catch(() => null), late]).finally(() =>
374
+ clearTimeout(timer),
375
+ );
376
+ return instance ? { region: instance, source: "instance" } : { region: null, source: null };
377
+ }
378
+
379
+ /** What the service uses to look at the host's AWS setup; tests put stand-ins in its place. */
380
+ export interface BedrockHost {
381
+ detectRegion(): Promise<{ region: string | null; source: RegionSource | null }>;
382
+ check(account: BedrockAccount): Promise<BedrockCheck>;
383
+ }
384
+
385
+ export const HOST_AWS: BedrockHost = {
386
+ detectRegion: () => detectHostRegion(),
387
+ check: (account) => checkBedrock(account),
388
+ };
389
+
390
+ // --------------------------------------------------------------------------- tokens
391
+
392
+ function count(value: unknown): number {
393
+ return typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : 0;
394
+ }
395
+
396
+ /**
397
+ * The assistant messages in a Claude Code session file written at or after `since` (ms), with their
398
+ * usage, one entry per message (Claude Code can write a message's usage on several lines; the last
399
+ * wins). `input` counts every input token: Anthropic's `input_tokens` plus cache reads and writes.
400
+ */
401
+ export function parseClaudeSession(text: string, since: number): Array<{ id: string; model: string; count: TokenCount }> {
402
+ const messages = new Map<string, { id: string; model: string; count: TokenCount }>();
403
+ for (const line of text.split("\n")) {
404
+ if (!line.includes('"usage"')) continue;
405
+ let entry: { type?: unknown; timestamp?: unknown; message?: { id?: unknown; model?: unknown; usage?: Record<string, unknown> } };
406
+ try {
407
+ entry = JSON.parse(line) as typeof entry;
408
+ } catch {
409
+ continue;
410
+ }
411
+ if (entry.type !== "assistant" || !entry.message?.usage) continue;
412
+ const at = typeof entry.timestamp === "string" ? Date.parse(entry.timestamp) : Number.NaN;
413
+ if (!Number.isFinite(at) || at < since) continue;
414
+ const id = typeof entry.message.id === "string" ? entry.message.id : null;
415
+ const model = typeof entry.message.model === "string" ? entry.message.model : "unknown";
416
+ if (!id || model === "<synthetic>") continue;
417
+ const usage = entry.message.usage;
418
+ const cachedInput = count(usage.cache_read_input_tokens);
419
+ const cacheWrite = count(usage.cache_creation_input_tokens);
420
+ messages.set(id, {
421
+ id,
422
+ model,
423
+ count: { input: count(usage.input_tokens) + cachedInput + cacheWrite, cachedInput, cacheWrite, output: count(usage.output_tokens) },
424
+ });
425
+ }
426
+ return [...messages.values()];
427
+ }
428
+
429
+ /** Where Claude Code keeps a session: `projects/<project>/<session id>.jsonl`, shared by every Claude home. */
430
+ export async function findClaudeSession(sessionId: string, projects = join(mainClaudeDir(), "projects")): Promise<string | null> {
431
+ if (!/^[\w-]{8,}$/.test(sessionId)) return null;
432
+ for (const project of await readdir(projects).catch(() => [] as string[])) {
433
+ const path = join(projects, project, `${sessionId}.jsonl`);
434
+ if (existsSync(path)) return path;
435
+ }
436
+ return null;
437
+ }
package/server/claude.ts CHANGED
@@ -15,6 +15,7 @@ import {
15
15
  type RedeemReply,
16
16
  type UsageRead,
17
17
  } from "./adapter";
18
+ import { bedrockEnv, bedrockIdentity, isBedrockHome, readBedrockAccount } from "./bedrock";
18
19
  import { browserCaptureScript, providerCommand } from "./binaries";
19
20
  import { CLAUDE_RESET_PROGRAM, describeResetBlock, parseClaudeResets, readClaimReply } from "./claude-resets";
20
21
  import { claudeClearTextProxy, claudeHomeHoldsAccount, prepareClaudeHome, readAccountApi, readAccountProxy, writeAccountApi, writeAccountProxy, type ApiConfig } from "./homes";
@@ -83,6 +84,9 @@ export class ClaudeAdapter implements FamilyAdapter {
83
84
  // daemon itself runs with CLAUDE_SECURESTORAGE_CONFIG_DIR set.
84
85
  const patch: EnvPatch = { CLAUDE_CONFIG_DIR: home, CLAUDE_SECURESTORAGE_CONFIG_DIR: home };
85
86
  for (const key of OVERRIDING_AUTH) if (process.env[key]) patch[key] = "";
87
+ // An AWS Bedrock account: Claude Code on Bedrock with its AWS credentials (see bedrock.ts). Throws
88
+ // when its settings can't be read, so the session isn't opened without them.
89
+ if (isBedrockHome(home)) Object.assign(patch, bedrockEnv(await readBedrockAccount(home)));
86
90
  return patch;
87
91
  }
88
92
 
@@ -108,6 +112,8 @@ export class ClaudeAdapter implements FamilyAdapter {
108
112
  }
109
113
 
110
114
  egress(home: string | null): Promise<{ ip: string; country: string | null } | null> {
115
+ // Bedrock's requests go to AWS, not Anthropic, so Anthropic's edge has nothing to say about them.
116
+ if (isBedrockHome(home)) return Promise.resolve(null);
111
117
  return claudeEgress(home);
112
118
  }
113
119
 
@@ -125,6 +131,11 @@ export class ClaudeAdapter implements FamilyAdapter {
125
131
  }
126
132
 
127
133
  async identity(home: string | null): Promise<Identity> {
134
+ if (isBedrockHome(home)) {
135
+ // Nothing signs in: the credentials are checked when they're saved, and a refusal is learned from a turn.
136
+ const account = await readBedrockAccount(home);
137
+ return { signedIn: true, email: null, plan: "AWS Bedrock", organization: null, identity: bedrockIdentity(account) };
138
+ }
128
139
  const { command, prefix } = await providerCommand("claude");
129
140
  const result = await run(command, [...prefix, "auth", "status", "--json"], {
130
141
  env: spawnEnv(await this.env(home), "claude"),
@@ -151,6 +162,8 @@ export class ClaudeAdapter implements FamilyAdapter {
151
162
 
152
163
  async usage(home: string | null, options: { renewLogin?: boolean } = {}): Promise<UsageRead> {
153
164
  const fetchedAt = new Date().toISOString();
165
+ // No plan windows: its tokens are counted per turn instead (see Service.countBedrockTurn).
166
+ if (isBedrockHome(home)) return { fetchedAt, windows: [], error: null, cached: false, resets: null, credits: null };
154
167
  let credentials = await readCredentials(home).catch(() => null);
155
168
  if (!isFresh(credentials) && options.renewLogin) credentials = await this.renewLogin(home);
156
169
  const profileScope = !credentials?.scopes || credentials.scopes.includes("user:profile");
@@ -227,6 +240,7 @@ export class ClaudeAdapter implements FamilyAdapter {
227
240
  }
228
241
 
229
242
  async redeemReset(home: string | null, options: { onlyAtLimit?: boolean } = {}): Promise<RedeemReply> {
243
+ if (isBedrockHome(home)) return { outcome: "none", message: "AWS Bedrock accounts have no banked resets.", left: 0 };
230
244
  let credentials = await readCredentials(home).catch(() => null);
231
245
  if (!isFresh(credentials)) credentials = await this.renewLogin(home);
232
246
  const token = credentials?.accessToken;
@@ -293,6 +307,7 @@ export class ClaudeAdapter implements FamilyAdapter {
293
307
  }
294
308
 
295
309
  async login(home: string | null, _method: LoginMethod): Promise<LoginHandle> {
310
+ if (isBedrockHome(home)) throw new Error("AWS Bedrock accounts use AWS credentials: change them from the account's card.");
296
311
  const { command, prefix } = await providerCommand("claude");
297
312
  const shim = await browserCaptureScript();
298
313
  const capture = join(tmpdir(), `zerosub-login-${randomBytes(6).toString("hex")}.url`);
@@ -305,6 +320,8 @@ export class ClaudeAdapter implements FamilyAdapter {
305
320
  }
306
321
 
307
322
  async logout(home: string): Promise<void> {
323
+ // Nothing is signed in: deleting the home (and its bedrock.json) is all removing it takes.
324
+ if (isBedrockHome(home)) return;
308
325
  const { command, prefix } = await providerCommand("claude");
309
326
  const result = await run(command, [...prefix, "auth", "logout"], { env: spawnEnv(await this.env(home), "claude"), timeoutMs: 30_000 });
310
327
  if (process.platform !== "darwin") return; // Elsewhere the login lives in the home itself.
package/server/codex.ts CHANGED
@@ -71,7 +71,7 @@ class AppServer {
71
71
  try {
72
72
  await server.request(
73
73
  "initialize",
74
- { clientInfo: { name: CLIENT_NAME, title: "Paseo ZeroSub", version: "1.18.3" }, capabilities: { experimentalApi: false } },
74
+ { clientInfo: { name: CLIENT_NAME, title: "Paseo ZeroSub", version: "1.19.0" }, capabilities: { experimentalApi: false } },
75
75
  60_000,
76
76
  );
77
77
  server.send({ method: "initialized" });
package/server/homes.ts CHANGED
@@ -3,6 +3,7 @@ import { randomBytes } from "node:crypto";
3
3
  import { basename, dirname, isAbsolute, join, relative, resolve } from "node:path";
4
4
  import type { ApiKeyKind, ApiSummary, Family, TrafficSwitches } from "../shared/model";
5
5
  import { AZURE_FILE, isAzureHome, syncAzureConfig } from "./azure";
6
+ import { BEDROCK_FILE, bedrockSettings, isBedrockHome, readBedrockAccount } from "./bedrock";
6
7
  import { Mutex, readJson } from "./json-file";
7
8
  import { NO_PROXY_KEYS, PROXY_KEYS, REQUIRED_NO_PROXY, bypassesProxy, maskProxy, noProxyFromEnv, proxyFromEnv, withClaudeNoProxy, withoutClaudeDomains } from "./proxy";
8
9
  import { providerEnv } from "./provider-env";
@@ -213,6 +214,8 @@ const GENERATED_SETTINGS = ".settings.generated.json";
213
214
  */
214
215
  const CLAUDE_PRIVATE = new Set([
215
216
  ".credentials.json",
217
+ // An AWS Bedrock account's region, credential source and (for an access key) key: never linked in from `~/.claude`.
218
+ BEDROCK_FILE,
216
219
  "settings.json",
217
220
  ACCOUNT_SETTINGS,
218
221
  GENERATED_SETTINGS,
@@ -551,7 +554,11 @@ async function syncClaudeSettings(home: string): Promise<void> {
551
554
  // Homes from earlier versions link to main's file; replace the link, never write through it.
552
555
  if (current?.isSymbolicLink()) await unlink(target);
553
556
  const inherited = { ...process.env, ...providerEnv("claude") };
554
- const next = `${JSON.stringify(accountSettings(main, account, inherited), null, 2)}\n`;
557
+ // An AWS Bedrock account's settings are made to agree with its sessions' environment (see bedrock.ts);
558
+ // one whose bedrock.json can't be read keeps its last ones, as for overrides that don't parse.
559
+ const bedrock = isBedrockHome(home) ? await readBedrockAccount(home) : null;
560
+ const generatedSettings = accountSettings(main, account, inherited);
561
+ const next = `${JSON.stringify(bedrock ? bedrockSettings(generatedSettings, bedrock) : generatedSettings, null, 2)}\n`;
555
562
  const generated = join(home, GENERATED_SETTINGS);
556
563
  if (current?.isFile() && (await readFile(target, "utf8").catch(() => null)) === next) {
557
564
  if ((await readFile(generated, "utf8").catch(() => null)) !== next) await writeJsonAtomically(generated, JSON.parse(next));
package/server/limits.ts CHANGED
@@ -205,6 +205,117 @@ export function detectAzureSignOut(event: TurnEvent): string | null {
205
205
  return null;
206
206
  }
207
207
 
208
+ // --------------------------------------------------------------------------- AWS Bedrock (Claude on AWS)
209
+
210
+ /** How long a Bedrock account is set aside after throttling (`ThrottlingException`, 429, "Too many tokens"). */
211
+ export const BEDROCK_THROTTLE_MS = 60_000;
212
+ /** How long after an exceeded service quota, which usually lifts within minutes. */
213
+ export const BEDROCK_QUOTA_MS = 5 * 60_000;
214
+
215
+ const BEDROCK_QUOTA = /ServiceQuotaExceeded|service quota|quota exceeded/i;
216
+ const BEDROCK_THROTTLED = /ThrottlingException|Too many (?:tokens|requests)|\b429\b|rate (?:exceeded|limit)/i;
217
+ /**
218
+ * Bedrock naming the model as one the account can't use: not enabled for it ("You don't have access
219
+ * to the model with the specified model ID"), a wrong ID ("The provided model identifier is invalid")
220
+ * or one that needs an inference profile. AWS's own wording, which no other service in a turn prints,
221
+ * so the account is marked without asking AWS about its credentials again.
222
+ */
223
+ const BEDROCK_MODEL_REFUSED =
224
+ /don['’]t have access to the model with the specified model ID|provided model identifier is invalid|Invocation of model ID .{1,200} with on-demand throughput isn['’]t supported/i;
225
+ /**
226
+ * Credentials or access refused. Only a hint: an AccessDenied or a 403 can be another service's (an
227
+ * MCP server's, a tool's), so the service asks AWS about the credentials before taking the account
228
+ * for signed out (see `confirmSignedOut`).
229
+ */
230
+ const BEDROCK_REFUSED =
231
+ /AccessDeniedException|not authorized to perform|UnrecognizedClientException|InvalidSignatureException|security token included in the request is (?:invalid|expired)|ExpiredToken|Could not load credentials|Unable to locate credentials|\b40[13]\b/i;
232
+ /** How Claude Code words an API failure in its reply: "API Error: 429 …", "API Error (model): 400 …". */
233
+ const API_ERROR = /^(?:\[System Error\]\s*)?API Error\b/i;
234
+
235
+ /**
236
+ * Notices from a turn on Bedrock. A failed turn gives its failure and error rows. Either kind gives
237
+ * Claude Code's own error replies: of the turn's last two replies (the window main's Claude detectors
238
+ * read, see `notices`), those that start "API Error", as Claude Code words an API failure. Paseo before
239
+ * 0.16 reports such a turn as completed, so a completed turn is read for them too. Nothing else in a
240
+ * completed turn counts: its warnings and error rows (an MCP server's "HTTP 401 Unauthorized" while it
241
+ * starts, an AccessDenied in a tool's output) are other services', and an ordinary reply that only
242
+ * mentions a 429 isn't an error at all.
243
+ */
244
+ function apiNotices(event: TurnEvent): string[] {
245
+ const found = event.outcome.kind === "failed" ? notices(event, false) : [];
246
+ const timeline = event.turnId === null ? [] : event.timeline;
247
+ let replies = 0;
248
+ for (let index = timeline.length - 1; index >= 0 && replies < 2; index -= 1) {
249
+ const item = timeline[index];
250
+ if (!item) continue;
251
+ if (isTurnPrompt(item)) break;
252
+ if (item.type !== "assistant_message") continue;
253
+ replies += 1;
254
+ if (API_ERROR.test(item.text)) found.push(clean(item.text));
255
+ }
256
+ return found.filter((text) => text.length > 0 && text.length <= MAX_NOTICE);
257
+ }
258
+
259
+ /**
260
+ * A turn on an AWS Bedrock account that failed throttled or over a service quota (see `apiNotices`). Bedrock has no 5-hour
261
+ * or weekly windows, so either is a short cooldown, as for Azure (see `detectAzureLimit`).
262
+ */
263
+ export function detectBedrockLimit(event: TurnEvent, now: Date = new Date()): LimitHit | null {
264
+ for (const text of apiNotices(event)) {
265
+ if (BEDROCK_QUOTA.test(text)) return { kind: "budget", message: firstLine(text), resetsAt: new Date(now.getTime() + BEDROCK_QUOTA_MS).toISOString() };
266
+ if (BEDROCK_THROTTLED.test(text)) return { kind: "window", message: firstLine(text), resetsAt: new Date(now.getTime() + BEDROCK_THROTTLE_MS).toISOString() };
267
+ }
268
+ return null;
269
+ }
270
+
271
+ /**
272
+ * A turn on an AWS Bedrock account that failed because its credentials, access or model were refused
273
+ * (see `apiNotices`): what AWS said, and whether it named the model (`model`), which needs no check of
274
+ * the credentials.
275
+ */
276
+ export function detectBedrockRefusal(event: TurnEvent): { message: string; model: boolean } | null {
277
+ const texts = apiNotices(event).filter((text) => !BEDROCK_THROTTLED.test(text) && !BEDROCK_QUOTA.test(text));
278
+ for (const text of texts) if (BEDROCK_MODEL_REFUSED.test(text)) return { message: firstLine(text), model: true };
279
+ for (const text of texts) if (BEDROCK_REFUSED.test(text)) return { message: firstLine(text), model: false };
280
+ return null;
281
+ }
282
+
283
+ /**
284
+ * Claude Code's own words when the model it was asked for isn't offered in the account's region: "The
285
+ * model eu.anthropic.claude-sonnet-4-5-20250929-v1:0 is not available on your bedrock deployment. Try
286
+ * --model to switch to …". It says so for a model alias (`sonnet`) whose built-in Bedrock default is
287
+ * older than what the region has, so only that model is out, not the account.
288
+ */
289
+ const BEDROCK_MODEL_UNAVAILABLE = /^The model (\S{1,200}) is not available on your bedrock deployment\b/i;
290
+
291
+ /**
292
+ * A turn on an AWS Bedrock account whose model Claude Code found missing in the account's region (see
293
+ * `BEDROCK_MODEL_UNAVAILABLE`), and the model it named. Read like main's Claude notices: the failure,
294
+ * error rows and the last two replies, of a failed or completed turn. The wording is Claude Code's
295
+ * own, anchored at the start, so no other service's message or ordinary reply matches.
296
+ */
297
+ export function detectBedrockModelUnavailable(event: TurnEvent): { message: string; model: string } | null {
298
+ for (const text of notices(event, true)) {
299
+ const line = firstLine(text);
300
+ const match = line.match(BEDROCK_MODEL_UNAVAILABLE);
301
+ if (match?.[1]) return { message: line, model: match[1] };
302
+ }
303
+ return null;
304
+ }
305
+
306
+ /** Paseo refusing to start a turn in Claude's Auto mode where Claude Code runs on Bedrock (`CLAUDE_CODE_USE_BEDROCK`). */
307
+ const BEDROCK_AUTO_MODE = /Claude Auto mode requires the Anthropic API/i;
308
+
309
+ /**
310
+ * A turn on an AWS Bedrock account Paseo wouldn't start because the agent is in Claude's Auto mode,
311
+ * which needs the Anthropic API: Paseo's message. Read like main's Claude notices (the failure, error
312
+ * rows and the last two replies, of a failed or completed turn); the wording is Paseo's own.
313
+ */
314
+ export function detectBedrockAutoModeRefusal(event: TurnEvent): string | null {
315
+ for (const text of notices(event, true)) if (BEDROCK_AUTO_MODE.test(text)) return firstLine(text);
316
+ return null;
317
+ }
318
+
208
319
  // --------------------------------------------------------------------------- reset times
209
320
 
210
321
  const MONTHS = ["jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec"];