@kapybara/zerosub 1.18.3 → 1.19.1

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.
package/server/service.ts CHANGED
@@ -2,6 +2,7 @@ import { createHash, randomBytes, randomUUID } from "node:crypto";
2
2
  import { lstat, readdir, readFile } from "node:fs/promises";
3
3
  import { basename, dirname, join, resolve } from "node:path";
4
4
  import type {
5
+ PluginBeforeRequests,
5
6
  PluginHookContext,
6
7
  PluginLifecycleEvents,
7
8
  PluginSessionOpenRequest,
@@ -21,7 +22,11 @@ import {
21
22
  type ApiSummary,
22
23
  ApiSummarySchema,
23
24
  type AzureSummary,
25
+ type BedrockModels,
26
+ type BedrockSource,
27
+ type BedrockSummary,
24
28
  isAzureAccount,
29
+ isBedrockAccount,
25
30
  type AgentRoute,
26
31
  type ApiKeyKind,
27
32
  type Egress,
@@ -64,13 +69,28 @@ import {
64
69
  readAzureAccount,
65
70
  writeAzureAccount,
66
71
  } from "./azure";
72
+ import {
73
+ HOST_AWS,
74
+ bedrockIdentity,
75
+ bedrockSummary,
76
+ findClaudeSession,
77
+ isBedrockHome,
78
+ normalizeRegion,
79
+ parseClaudeSession,
80
+ readBedrockAccount,
81
+ writeBedrockAccount,
82
+ type BedrockAccount,
83
+ type BedrockCheck,
84
+ type BedrockHost,
85
+ type RegionSource,
86
+ } from "./bedrock";
67
87
  import { codexHandoffMode, encryptedResumeFailure, sameWorkspace, turnFailedText } from "./codex-same-conversation";
68
88
  import { CodexContinuations, MESSAGE_PREFIX, UnresolvableEpochError, fitInstructions, matchesTransfer, readUpdates, ready, sentDigestOf, snapshot, transferMarker, waitForCreated, waitForSource, type Agent } from "./continuations";
69
89
  import { CONTINUED_FROM_LABEL, PARENT_LABEL, buildTranscript, continueInNewAgent, continuationPrompt, promptInstruction, updatePrompt, type Continuation } from "./handoff";
70
- import { PI_ACCOUNT_FILE, codexSessionsShared, crossesInheritedProxy, isAccountHome, moveHome, normalizeBaseUrl, plainHttp, readPiAccount, readPiAccountForAgents, removeHome, sentInTheClear } from "./homes";
71
90
  import { launcherDir, launcherNames, piLauncherDir, writeLaunchers, type LauncherAccount, type LauncherKind } from "./launchers";
91
+ import { PI_ACCOUNT_FILE, codexSessionsShared, prepareClaudeHome, crossesInheritedProxy, isAccountHome, moveHome, normalizeBaseUrl, plainHttp, readPiAccount, readPiAccountForAgents, removeHome, sentInTheClear } from "./homes";
72
92
  import { Mutex } from "./json-file";
73
- import { detectAzureLimit, detectAzureSignOut, turnRows } from "./limits";
93
+ import { detectAzureLimit, detectAzureSignOut, detectBedrockAutoModeRefusal, detectBedrockLimit, detectBedrockModelUnavailable, detectBedrockRefusal, turnRows } from "./limits";
74
94
  import { canSignInWithBrowser } from "./machine";
75
95
  import { equivalentMode, withinMode } from "./modes";
76
96
  import { homesDir, inHomesDir, isOwnHome, shownPath } from "./paths";
@@ -136,6 +156,8 @@ const OPENCODE_AVAILABLE_MS = 60_000;
136
156
  const ROUTING_WAIT_MS = 5_000;
137
157
  /** How long the end of a turn waits for Paseo to page the agent's timeline. The SDK itself waits 60 s. */
138
158
  const TURN_READ_MS = 10_000;
159
+ /** How long routing waits for Paseo to say an agent's mode before taking it for Auto (see `paidFor`). */
160
+ const MODE_READ_MS = 3_000;
139
161
  /** An agent whose move to an account didn't land isn't moved there again for this long. */
140
162
  const ALIGN_RETRY_MS = 30 * 60_000;
141
163
  /**
@@ -224,6 +246,8 @@ interface AgentInfo {
224
246
  updatedAt: number;
225
247
  /** Shells and monitors it left running after its turn (Paseo 0.16+; 0 before). A reload cancels them. */
226
248
  backgroundWork: number;
249
+ /** Its permission mode now, as Paseo names it (Claude's `auto`, say), or null when Paseo gives none. */
250
+ modeId: string | null;
227
251
  /** Its metadata holds its own ID (see `AGENT_METADATA_KEY`). Null when Paseo sends no metadata (before 0.16). */
228
252
  named: boolean | null;
229
253
  /** The model the agent runs, when Paseo says (a limit of one model's own window depends on it). */
@@ -417,6 +441,22 @@ function takesAgentMetadata(paseo: PaseoApi): boolean {
417
441
  }
418
442
  }
419
443
 
444
+ /**
445
+ * Agent metadata (Paseo 0.16 and later) carrying the permission mode a new Claude agent was created
446
+ * in, from `agent.create` to its first session: Paseo can't say the mode of an agent it hasn't made
447
+ * yet, and Bedrock can't run Claude's Auto mode (see `paidFor`). Only read when that session opens.
448
+ */
449
+ const CREATED_MODE_METADATA_KEY = "zerosub.created-mode";
450
+
451
+ type AgentCreateRequest = PluginBeforeRequests["agent.create"];
452
+
453
+ /** The mode a new agent's create request stashed in its metadata (see `CREATED_MODE_METADATA_KEY`). */
454
+ function createdMode(request: PluginSessionOpenRequest): string | undefined {
455
+ const { metadata } = request as { metadata?: Readonly<Record<string, unknown>> | null };
456
+ const value = metadata?.[CREATED_MODE_METADATA_KEY];
457
+ return typeof value === "string" && value ? value : undefined;
458
+ }
459
+
420
460
  /**
421
461
  * The account named in a new agent's metadata: the one its composer's account control was set to
422
462
  * before the agent existed. A Paseo before 0.16 sends no metadata.
@@ -467,6 +507,8 @@ export class Service {
467
507
  private readonly unrouted = new Set<string>();
468
508
  /** When each agent's last turn started or ended; see `noteTurn`. */
469
509
  private readonly turnAt = new Map<string, number>();
510
+ /** When each agent's current or last turn started, to count a Bedrock turn's messages (see `countBedrockTurn`). */
511
+ private readonly turnStartedAt = new Map<string, number>();
470
512
  /**
471
513
  * The account a Codex agent reloaded off, until the first turn after that reload ends. A decrypt
472
514
  * or resume failure pins it back and opens today's new tab. Any other ending drops the record.
@@ -523,6 +565,8 @@ export class Service {
523
565
  private readonly redeeming = new Set<string>();
524
566
  private readonly browserSignIn = canSignInWithBrowser();
525
567
  private agentCache: { at: number; agents: Promise<AgentInfo[]> } | null = null;
568
+ /** Each agent's permission mode as last seen, for routing that can't take some modes (Bedrock and Claude's Auto mode). */
569
+ private readonly agentModes = new Map<string, string | null>();
526
570
  /**
527
571
  * The model each agent runs, as last seen. Routing, alignment and the account button all decide
528
572
  * with this one value, so a session that opens somewhere is never moved again by another reading.
@@ -552,6 +596,8 @@ export class Service {
552
596
  private readonly families = new FamilyResolver(),
553
597
  private readonly reopener = new Reopener(),
554
598
  private readonly apiUsage = new ApiUsageStore(),
599
+ /** The host's AWS setup, for Bedrock accounts: its region and the credential check. */
600
+ private readonly aws: BedrockHost = HOST_AWS,
555
601
  ) {
556
602
  this.adapters = Object.fromEntries(FAMILIES.map((family) => [family, adapters[family] ?? missingAdapter(family)])) as Record<Family, FamilyAdapter>;
557
603
  this.continuations = new CodexContinuations(store);
@@ -840,10 +886,12 @@ export class Service {
840
886
  // An API account (every Pi one) is saved, and its entry dropped, in one write (see `addApiAccount`):
841
887
  // an entry left means it never became an account, so its home goes, key and all, though Claude
842
888
  // Code calls a home with a key signed in.
843
- // So is an Azure OpenAI account's (its home holds azure.json): nothing in it signs in.
889
+ // So is an Azure OpenAI or AWS Bedrock account's (its home holds azure.json or bedrock.json):
890
+ // nothing in it signs in.
844
891
  const apiHome =
845
892
  entry.family === "pi" ||
846
893
  (entry.family === "codex" && isAzureHome(home)) ||
894
+ (entry.family === "claude" && isBedrockHome(home)) ||
847
895
  (await this.adapters[entry.family].api?.(home).catch(() => null)) != null;
848
896
  const earlier = entry.why === "unfinished" && !apiHome && !this.endedHere(home);
849
897
  let deleteFolder = true;
@@ -936,6 +984,21 @@ export class Service {
936
984
  * routing fails, or `abandoned` says Paseo stopped waiting for it, Paseo opens an interactive
937
985
  * session as it asked: on the CLI login. Then nothing routing recorded for it stands.
938
986
  */
987
+ /**
988
+ * Before Paseo creates an agent: a new Claude agent's mode goes into its metadata, so routing knows
989
+ * it when the first session opens (see `CREATED_MODE_METADATA_KEY`). Only while paid fallback could
990
+ * put it on Bedrock, and only on a Paseo that keeps metadata (0.16 and later, where the request
991
+ * always carries it); otherwise the request is left as it is.
992
+ */
993
+ async onAgentCreate(request: AgentCreateRequest, context: PluginHookContext): Promise<AgentCreateRequest | undefined> {
994
+ const { metadata } = request as { metadata?: Record<string, unknown> | null };
995
+ const modeId = request.config.modeId;
996
+ if (!metadata || typeof metadata !== "object" || typeof modeId !== "string" || !modeId) return undefined;
997
+ if (!this.prefs.paidApiFallback || !(await this.store.read()).accounts.some((account) => isBedrockAccount(account))) return undefined;
998
+ if ((await this.families.resolve(context.paseo))[request.config.provider] !== "claude") return undefined;
999
+ return { ...request, metadata: { ...metadata, [CREATED_MODE_METADATA_KEY]: modeId } } as AgentCreateRequest;
1000
+ }
1001
+
939
1002
  async onSessionOpen(
940
1003
  request: PluginSessionOpenRequest,
941
1004
  context: PluginHookContext,
@@ -1107,7 +1170,17 @@ export class Service {
1107
1170
  pendingOf: (id) => this.pendingOn(id, now),
1108
1171
  model: this.agentModels.get(request.agentId) ?? null,
1109
1172
  };
1110
- const first = chooseAccount(state, input);
1173
+ let first = chooseAccount(state, input);
1174
+ // Paid fallback would put a Claude agent on Bedrock by itself: not one in Auto mode, which Bedrock
1175
+ // can't run (see `paidFor`). Its mode is asked for only then.
1176
+ if (first && family === "claude" && input.paidFallback && isBedrockAccount(first.account)) {
1177
+ const unpaid = chooseAccount(state, { ...input, paidFallback: false });
1178
+ if (unpaid?.account.id !== first.account.id && runsAutoMode(await this.modeAtOpen(context.paseo, request))) {
1179
+ console.log(`[ZeroSub] ${request.agentId} not routed to ${first.account.label}: it's in Claude's Auto mode, which Bedrock can't run`);
1180
+ input.paidFallback = false;
1181
+ first = unpaid;
1182
+ }
1183
+ }
1111
1184
  if (!first) return undefined;
1112
1185
  if (first.bind?.source === "balance") this.logPlacement(state, family, request.agentId, first.account, now, "new agent");
1113
1186
  // Recorded before any await, so concurrent creates see each other's placements, and moved below
@@ -1192,7 +1265,7 @@ export class Service {
1192
1265
 
1193
1266
  /** A turn uses the account from its first token, so a long one keeps its usage fresh too. */
1194
1267
  async onTurnStarted(agent: { id: string; provider: string }, context: PluginHookContext): Promise<void> {
1195
- this.noteTurn(agent.id);
1268
+ this.turnStartedAt.set(agent.id, this.noteTurn(agent.id));
1196
1269
  this.attach(context.paseo);
1197
1270
  const family = (await this.families.resolve(context.paseo))[agent.provider];
1198
1271
  if (!family) return;
@@ -1212,11 +1285,16 @@ export class Service {
1212
1285
  const ranOn = await this.store.read();
1213
1286
  const accountId = this.runningOn(ranOn, agentId, family) ?? null;
1214
1287
  if (accountId) this.activeAt.set(accountId, Date.now());
1215
- // An Azure OpenAI account fails on the API's errors, not the ChatGPT plan's notices, and only a
1216
- // failed turn's (see `detectAzureLimit`).
1288
+ // An Azure OpenAI or AWS Bedrock account fails on the API's errors, not the subscription's
1289
+ // notices, and only a failed turn's (see `detectAzureLimit` and `detectBedrockLimit`).
1217
1290
  const ranAccount = findAccount(ranOn, accountId);
1218
1291
  const azure = ranAccount !== undefined && isAzureAccount(ranAccount);
1292
+ const bedrock = ranAccount !== undefined && isBedrockAccount(ranAccount);
1219
1293
  if (azure && accountId) void this.countAzureTurn(context.paseo, agentId, accountId).catch((error: unknown) => log(`could not count the tokens of ${agentId}'s turn`, error));
1294
+ if (bedrock && accountId) {
1295
+ const startedAt = this.turnStartedAt.get(agentId) ?? endedAt - 60 * 60_000;
1296
+ void this.countBedrockTurn(context.paseo, agentId, accountId, startedAt).catch((error: unknown) => log(`could not count the tokens of ${agentId}'s turn`, error));
1297
+ }
1220
1298
  if (event.outcome.kind === "completed") this.sameConversationBlocked.delete(agentId);
1221
1299
  const probe = this.sameConversationProbe.get(agentId);
1222
1300
  if (event.outcome.kind !== "canceled") {
@@ -1231,10 +1309,30 @@ export class Service {
1231
1309
  if (probe) this.sameConversationProbe.delete(agentId);
1232
1310
  // A hand-off quotes the whole conversation, not just this turn. Paseo 0.13 sends none, so the hand-off pages it.
1233
1311
  const conversation = event.timeline.length > 0 ? event.timeline : undefined;
1234
- const hit = azure ? detectAzureLimit(turn) : adapter.detectLimit(turn);
1312
+ // A model the account's region doesn't offer is that model's problem, not the account's: the
1313
+ // agent stays, and its timeline says how to fix it (see `detectBedrockModelUnavailable`).
1314
+ // Paseo refuses Claude's Auto mode on Bedrock. The account is fine: the agent's mode isn't.
1315
+ const autoRefused = bedrock ? detectBedrockAutoModeRefusal(turn) : null;
1316
+ if (autoRefused && ranAccount) {
1317
+ console.log(`[ZeroSub] ${agentId} can't run in Auto mode on ${ranAccount.label}: ${autoRefused}`);
1318
+ this.agentModes.set(agentId, CLAUDE_AUTO_MODE);
1319
+ await this.noteBedrockTurn(context.paseo, agentId, ranAccount, autoModeRefusedNote(ranAccount.label));
1320
+ if (this.deferred.has(agentId)) await this.finishDeferred(context.paseo, agentId, family);
1321
+ return;
1322
+ }
1323
+ const unavailable = bedrock ? detectBedrockModelUnavailable(turn) : null;
1324
+ if (unavailable && ranAccount) {
1325
+ console.log(`[ZeroSub] ${agentId}'s model isn't available on ${ranAccount.label}: ${unavailable.message}`);
1326
+ await this.noteBedrockTurn(context.paseo, agentId, ranAccount, bedrockModelNote(ranAccount.label, unavailable.model));
1327
+ if (this.deferred.has(agentId)) await this.finishDeferred(context.paseo, agentId, family);
1328
+ return;
1329
+ }
1330
+ const hit = azure ? detectAzureLimit(turn) : bedrock ? detectBedrockLimit(turn) : adapter.detectLimit(turn);
1331
+ const bedrockRefusal = bedrock ? detectBedrockRefusal(turn) : null;
1332
+ const refusal = azure ? detectAzureSignOut(turn) : bedrock ? (bedrockRefusal?.message ?? null) : adapter.detectSignOut(turn);
1235
1333
  const problem: Problem | null = hit
1236
1334
  ? { kind: "limit", hit }
1237
- : (azure ? detectAzureSignOut(turn) : adapter.detectSignOut(turn)) && (await this.confirmSignedOut(accountId))
1335
+ : refusal && (await this.confirmSignedOut(accountId, refusal, bedrockRefusal?.model === true))
1238
1336
  ? { kind: "signed_out" }
1239
1337
  : null;
1240
1338
  if (problem) {
@@ -1316,6 +1414,7 @@ export class Service {
1316
1414
  this.failedMoves.delete(agentId);
1317
1415
  this.unrouted.delete(agentId);
1318
1416
  this.turnAt.delete(agentId);
1417
+ this.turnStartedAt.delete(agentId);
1319
1418
  this.sameConversationProbe.delete(agentId);
1320
1419
  this.sameConversationBlocked.delete(agentId);
1321
1420
  this.switchGuard.forget(agentId);
@@ -1327,21 +1426,47 @@ export class Service {
1327
1426
  });
1328
1427
  }
1329
1428
 
1429
+ /** A note in the agent's timeline about a turn its Bedrock account couldn't run, which leaves the account as it is. */
1430
+ private async noteBedrockTurn(paseo: PaseoApi, agentId: string, account: StoredAccount, detail: string): Promise<void> {
1431
+ await this.appendRow(paseo, agentId, {
1432
+ family: "claude",
1433
+ from: account.label,
1434
+ to: account.label,
1435
+ reason: "manual",
1436
+ resetsAt: null,
1437
+ continued: false,
1438
+ continuedIn: null,
1439
+ toFamily: null,
1440
+ toProvider: null,
1441
+ outcome: "stayed",
1442
+ detail,
1443
+ at: new Date().toISOString(),
1444
+ });
1445
+ }
1446
+
1330
1447
  /** Re-checks the account an agent was using; true when it really is signed out now. */
1331
- private async confirmSignedOut(accountId: string | null): Promise<boolean> {
1448
+ private async confirmSignedOut(accountId: string | null, refusal?: string | boolean, checked = false): Promise<boolean> {
1332
1449
  if (!accountId) return false;
1333
1450
  const state = await this.store.read();
1334
1451
  const account = findAccount(state, accountId);
1335
1452
  if (account?.auth === "api") {
1336
- // An Azure key is asked about first: the 401 or 403 in the turn may be another service's (an MCP
1337
- // server's, say). Only Azure refusing it now signs the account out; a check that can't get an
1338
- // answer (the network, another status) leaves it as it is. Other keys have nothing to re-check
1339
- // against: the refusal itself is the answer.
1453
+ // An Azure key or AWS credentials are asked about first: the 401 or 403 (or AccessDenied) in the
1454
+ // turn may be another service's (an MCP server's, say). Only Azure or AWS refusing them now signs
1455
+ // the account out; a check that can't get an answer (the network, no aws command, another
1456
+ // status) leaves it as it is. A model Bedrock names as not enabled or invalid needs no check
1457
+ // (`checked`, see `detectBedrockRefusal`). Other keys have nothing to re-check against: the
1458
+ // refusal itself is the answer.
1340
1459
  if (isAzureAccount(account) && !(await this.azureRefusesKey(account))) return false;
1460
+ if (isBedrockAccount(account) && !checked) {
1461
+ const refused = await this.bedrockRefusesCredentials(account);
1462
+ if (refused === null) return false;
1463
+ refusal = refused;
1464
+ }
1341
1465
  await this.store.update((draft) => {
1342
1466
  const target = findAccount(draft, accountId);
1343
1467
  if (target) {
1344
1468
  target.signedIn = false;
1469
+ if (typeof refusal === "string" && isLastResort(target)) target.apiError = refusal.slice(0, 300);
1345
1470
  dropNextPick(draft, target);
1346
1471
  }
1347
1472
  });
@@ -1361,6 +1486,23 @@ export class Service {
1361
1486
  return check.fatal;
1362
1487
  }
1363
1488
 
1489
+ /**
1490
+ * What AWS says about a Bedrock account's credentials now (see `checkBedrock`): its refusal when it
1491
+ * refuses them, or null when they work or the check couldn't get an answer (no aws command, the
1492
+ * network, a role that can't list inference profiles), which leaves the account as it is.
1493
+ */
1494
+ private async bedrockRefusesCredentials(account: StoredAccount): Promise<string | null> {
1495
+ const settings = account.home ? await readBedrockAccount(account.home).catch(() => null) : null;
1496
+ if (!settings) return "Its AWS settings (bedrock.json) are missing.";
1497
+ const check = await this.aws.check(settings).catch((error: unknown): BedrockCheck => ({ ok: false, fatal: false, message: error instanceof Error ? error.message : String(error) }));
1498
+ if (check.ok) return null;
1499
+ if (!check.fatal) {
1500
+ console.log(`[ZeroSub] ${account.label}'s turn failed on what looked like refused AWS credentials, but they couldn't be checked: ${check.message} It stays usable.`);
1501
+ return null;
1502
+ }
1503
+ return check.message;
1504
+ }
1505
+
1364
1506
  /**
1365
1507
  * Carries out a switch that waited for the agent's turn to end, unless it's no longer wanted. While
1366
1508
  * another move has the agent, or a default change is pinning open agents, it keeps waiting, and
@@ -1565,9 +1707,10 @@ export class Service {
1565
1707
  }
1566
1708
  return;
1567
1709
  }
1568
- const move = adapter.portable ? this.nextAccount(latest, agentId, family, account.id) : null;
1569
- // Another subscription account comes first, then a banked reset (free), and a paid Azure account
1570
- // (with `paidApiFallback` on) only once neither is to be had.
1710
+ // Another subscription account comes first, then a banked reset (free), and a paid Azure or
1711
+ // Bedrock account (with `paidApiFallback` on) only once neither is to be had.
1712
+ let move = adapter.portable ? this.nextAccount(latest, agentId, family, account.id, false) : null;
1713
+ let autoModeSkip: string | null = null;
1571
1714
  let next = adapter.portable ? move?.account : mostAvailable(latest, family, (id) => this.usage.get(id), now, new Set([account.id]), false, this.pacing(now), this.agentModels.get(agentId));
1572
1715
  if (!next) {
1573
1716
  if (problem.kind === "limit" && problem.hit.kind === "window" && !problem.hit.scope && this.prefs.autoRedeem && !account.disabled && account.auth !== "api") {
@@ -1598,7 +1741,17 @@ export class Service {
1598
1741
  }
1599
1742
  console.log(`[ZeroSub] no automatic reset for ${account.label}: ${reply.message}`);
1600
1743
  }
1601
- if (!adapter.portable && this.prefs.paidApiFallback) {
1744
+ if (adapter.portable && this.prefs.paidApiFallback) {
1745
+ move = this.nextAccount(await this.store.read(), agentId, family, account.id, true);
1746
+ next = move?.account;
1747
+ // Bedrock can't run Claude's Auto mode: an agent in it would fail every turn there.
1748
+ if (next && isBedrockAccount(next) && runsAutoMode(await this.modeOf(paseo, agentId))) {
1749
+ console.log(`[ZeroSub] not moving ${agentId} onto ${next.label}: it's in Claude's Auto mode, which Bedrock can't run`);
1750
+ autoModeSkip = autoModeSkipNote(next.label);
1751
+ move = undefined;
1752
+ next = undefined;
1753
+ }
1754
+ } else if (this.prefs.paidApiFallback) {
1602
1755
  next = mostAvailable(await this.store.read(), family, (id) => this.usage.get(id), Date.now(), new Set([account.id]), true, undefined, this.agentModels.get(agentId));
1603
1756
  }
1604
1757
  }
@@ -1628,7 +1781,7 @@ export class Service {
1628
1781
  continuedIn: result.fork,
1629
1782
  outcome: result.delivery === "sent" ? "continued" : "stayed",
1630
1783
  delivery: result.delivery,
1631
- detail: result.detail ?? null,
1784
+ detail: joinDetails(autoModeSkip, result.detail ?? null),
1632
1785
  });
1633
1786
  return;
1634
1787
  }
@@ -1637,14 +1790,16 @@ export class Service {
1637
1790
  } else if (otherFamily && mostAvailable(latest, otherFamily, (id) => this.usage.get(id), now, new Set(), this.prefs.paidApiFallback)) {
1638
1791
  detail = `Or continue on ${FAMILY_LABEL[otherFamily]} in a new agent from the account button.`;
1639
1792
  }
1640
- await this.appendRow(paseo, agentId, { ...base, to: account.label, reason: "exhausted", outcome: "stayed", detail });
1793
+ await this.appendRow(paseo, agentId, { ...base, to: account.label, reason: "exhausted", outcome: "stayed", detail: joinDetails(autoModeSkip, detail) });
1641
1794
  return;
1642
1795
  }
1643
1796
 
1644
1797
  if (!adapter.portable && (await this.keptSameConversation(paseo, agentId, account, next, problem, base, reason, endedAt))) return;
1645
1798
 
1646
1799
  if (adapter.portable) {
1647
- if (move?.pin) await this.pin(agentId, next.id, latest.bindings[agentId]);
1800
+ // Never pinned to a paid stand-in (Bedrock): it's only there until a subscription account has
1801
+ // room, and routing and alignment take the agent back then.
1802
+ if (move?.pin && !isLastResort(next)) await this.pin(agentId, next.id, latest.bindings[agentId]);
1648
1803
  // Only a Claude agent moves here. A ChatGPT hand-off's new agent counts itself as it opens.
1649
1804
  this.notePlacement(next.id, now);
1650
1805
  this.switchGuard.note(agentId, now);
@@ -1657,7 +1812,7 @@ export class Service {
1657
1812
  reason,
1658
1813
  continued,
1659
1814
  outcome: result.outcome === "reopened" ? "switched" : "pending",
1660
- detail: result.outcome === "failed" ? failureDetail(result) : null,
1815
+ detail: result.outcome === "failed" ? failureDetail(result) : isLastResort(next) ? paidFallbackNote(next) : null,
1661
1816
  },
1662
1817
  agentId,
1663
1818
  );
@@ -1693,7 +1848,7 @@ export class Service {
1693
1848
  continued: true,
1694
1849
  continuedIn: continuation,
1695
1850
  outcome: "continued",
1696
- detail: paid ? azureFallbackNote(next.label) : null,
1851
+ detail: paid ? paidFallbackNote(next) : null,
1697
1852
  });
1698
1853
  } catch (error) {
1699
1854
  log(`could not continue ${agentId} on ${next.label}`, error);
@@ -1969,16 +2124,57 @@ export class Service {
1969
2124
  return info !== null && !info.archived && info.status !== "closed";
1970
2125
  }
1971
2126
 
2127
+ /**
2128
+ * Whether a paid stand-in may take this agent by itself (`paidApiFallback`). Bedrock can't run
2129
+ * Claude's Auto mode (Paseo refuses to start the turn: "Claude Auto mode requires the Anthropic
2130
+ * API"), so a Claude agent in Auto mode never goes there by itself, nor one whose mode isn't known
2131
+ * yet: Auto is Paseo's default Claude mode. Picking Bedrock by hand, or as the default, still works.
2132
+ */
2133
+ private paidFor(family: Family, agentId: string): boolean {
2134
+ return this.prefs.paidApiFallback && !(family === "claude" && runsAutoMode(this.agentModes.get(agentId)));
2135
+ }
2136
+
2137
+ /**
2138
+ * The mode of an agent whose session is opening. Paseo can't say a brand-new agent's (it doesn't
2139
+ * exist yet), so that comes from what its create request stashed, when there is one.
2140
+ */
2141
+ private async modeAtOpen(paseo: PaseoApi, request: PluginSessionOpenRequest): Promise<string | null> {
2142
+ const stashed = request.reason === "create" ? createdMode(request) : undefined;
2143
+ if (stashed === undefined) return this.modeOf(paseo, request.agentId);
2144
+ this.agentModes.set(request.agentId, stashed);
2145
+ return stashed;
2146
+ }
2147
+
2148
+ /** The agent's permission mode now (null when it can't be told), noted for `paidFor`. */
2149
+ private async modeOf(paseo: PaseoApi, agentId: string): Promise<string | null> {
2150
+ const info = await deadline(agentInfo(paseo, agentId), MODE_READ_MS, "Paseo didn't say the agent's mode in time").catch(() => null);
2151
+ const modeId = info?.modeId ?? null;
2152
+ this.agentModes.set(agentId, modeId);
2153
+ return modeId;
2154
+ }
2155
+
1972
2156
  /**
1973
2157
  * Where an agent moves off an `exhausted` account: where it's routed now when that's another
1974
2158
  * account as chosen (one picked for it, perhaps while its turn ran, or the default it follows),
1975
- * else the roomiest other one, which it's then pinned to. Undefined when there's none.
2159
+ * else the roomiest other one, which it's then pinned to. Undefined when there's none. `paid`: a
2160
+ * paid stand-in (Bedrock) may be chosen by itself, as `paidApiFallback` allows; failover asks
2161
+ * without it first, so a banked reset comes before one (see `failover`). Where it's routed only
2162
+ * counts when that account can take it now: with every subscription out, a throttled stand-in's
2163
+ * route is the limited subscription it stood in for, and its agents stay put rather than go back.
2164
+ * Moving idle agents off an account (`moveIdleAgentsOff`) asks here too.
1976
2165
  */
1977
- private nextAccount(state: StoredState, agentId: string, family: Family, exhausted: string): { account: StoredAccount; pin: boolean } | undefined {
1978
- const routed = this.routeFor(state, agentId, family, exhausted);
1979
- if (routed && routed.account.id !== exhausted && !routed.skipped) return { account: routed.account, pin: false };
2166
+ private nextAccount(
2167
+ state: StoredState,
2168
+ agentId: string,
2169
+ family: Family,
2170
+ exhausted: string,
2171
+ paid = this.paidFor(family, agentId),
2172
+ ): { account: StoredAccount; pin: boolean } | undefined {
1980
2173
  const now = Date.now();
1981
- const roomiest = mostAvailable(state, family, (id) => this.usage.get(id), now, new Set([exhausted]), this.prefs.paidApiFallback, this.pacing(now), this.agentModels.get(agentId));
2174
+ const model = this.agentModels.get(agentId);
2175
+ const routed = this.routeFor(state, agentId, family, exhausted, paid);
2176
+ if (routed && routed.account.id !== exhausted && !routed.skipped && isUsable(routed.account, now, model)) return { account: routed.account, pin: false };
2177
+ const roomiest = mostAvailable(state, family, (id) => this.usage.get(id), now, new Set([exhausted]), paid, this.pacing(now), model);
1982
2178
  return roomiest && { account: roomiest, pin: true };
1983
2179
  }
1984
2180
 
@@ -2032,6 +2228,7 @@ export class Service {
2032
2228
  hasBackgroundWork(info) ||
2033
2229
  (reason === "pacing" ? !this.cacheCold(info, Date.now()) : this.recentlyActive(info, Date.now()))
2034
2230
  ) continue;
2231
+ this.agentModes.set(agentId, info.modeId);
2035
2232
  // Left for its own failover, or alone when that can't be told.
2036
2233
  if ((await this.lastTurnHitLimit(paseo, agentId, family)) !== false) continue;
2037
2234
  const release = this.tryClaim(agentId);
@@ -2060,7 +2257,7 @@ export class Service {
2060
2257
  if (!move) return;
2061
2258
  const next = move.account;
2062
2259
  this.notePlacement(next.id, now);
2063
- if (move.pin) await this.pin(agentId, next.id, latest.bindings[agentId]);
2260
+ if (move.pin && !isLastResort(next)) await this.pin(agentId, next.id, latest.bindings[agentId]);
2064
2261
  this.switchGuard.note(agentId, now);
2065
2262
  const row: SwitchRow = {
2066
2263
  family,
@@ -2073,7 +2270,7 @@ export class Service {
2073
2270
  toFamily: null,
2074
2271
  toProvider: null,
2075
2272
  outcome: "switched",
2076
- detail: null,
2273
+ detail: isLastResort(next) ? paidFallbackNote(next) : null,
2077
2274
  at: new Date(now).toISOString(),
2078
2275
  };
2079
2276
  await this.noteOutcome(paseo, agentId, row, await this.reopenAgent(paseo, agentId, { row, background: true }));
@@ -2113,7 +2310,7 @@ export class Service {
2113
2310
  toFamily: other,
2114
2311
  toProvider: null,
2115
2312
  delivery: "sent",
2116
- ...(isLastResort(earlierAccount) ? { detail: azureFallbackNote(earlierAccount.label) } : {}),
2313
+ ...(isLastResort(earlierAccount) ? { detail: paidFallbackNote(earlierAccount) } : {}),
2117
2314
  };
2118
2315
  }
2119
2316
 
@@ -2163,6 +2360,12 @@ export class Service {
2163
2360
  skipped: `${name} has no mode as careful as this agent's${current ? ` (“${current}”)` : ""}, so ZeroSub didn't continue it there.`,
2164
2361
  };
2165
2362
  }
2363
+ // A fork in Claude's Auto mode can't run on Bedrock (see `paidFor`): a subscription account, or none.
2364
+ if (other === "claude" && isBedrockAccount(account) && runsAutoMode(modeId)) {
2365
+ const subscription = mostAvailable(state, other, (id) => this.usage.get(id), now, new Set(), false, this.pacing(now));
2366
+ if (!subscription) return { skipped: autoModeSkipNote(account.label) };
2367
+ account = subscription;
2368
+ }
2166
2369
 
2167
2370
  // Every check that can refuse has passed, so the stale reservation goes now.
2168
2371
  if (reservation) {
@@ -2180,9 +2383,12 @@ export class Service {
2180
2383
  parentId: await this.continuations.parentFor(paseo, agentId),
2181
2384
  bind: async (newAgentId) => {
2182
2385
  await this.store.update((draft) => {
2386
+ // A fork that lands on a paid stand-in (Bedrock) isn't the user's pick, even when they asked
2387
+ // for the fork: it's held there only until a subscription account can take it (see `chooseAccount`).
2388
+ const portable = this.adapters[other].portable;
2183
2389
  draft.bindings[newAgentId] = {
2184
2390
  accountId: account.id,
2185
- source: source === "user" ? "user" : this.adapters[other].portable ? "auto" : "thread",
2391
+ source: portable && isLastResort(account) ? "auto" : source === "user" ? "user" : portable ? "auto" : "thread",
2186
2392
  at: new Date().toISOString(),
2187
2393
  };
2188
2394
  });
@@ -2195,7 +2401,7 @@ export class Service {
2195
2401
  toFamily: other,
2196
2402
  toProvider: null,
2197
2403
  delivery: "sent",
2198
- ...(isLastResort(account) ? { detail: azureFallbackNote(account.label) } : {}),
2404
+ ...(isLastResort(account) ? { detail: paidFallbackNote(account) } : {}),
2199
2405
  };
2200
2406
  }
2201
2407
 
@@ -3033,7 +3239,7 @@ export class Service {
3033
3239
  * How routing would open this agent's next session now, including skipping exhausted accounts.
3034
3240
  * `current` is the account its session runs on, which it keeps while that can stand in.
3035
3241
  */
3036
- private routeFor(state: StoredState, agentId: string, family: Family, current?: string): RouteDecision | null {
3242
+ private routeFor(state: StoredState, agentId: string, family: Family, current?: string, paid = this.paidFor(family, agentId)): RouteDecision | null {
3037
3243
  const now = Date.now();
3038
3244
  return chooseAccount(state, {
3039
3245
  agentId,
@@ -3042,7 +3248,7 @@ export class Service {
3042
3248
  now,
3043
3249
  autoSwitch: this.prefs.autoSwitch,
3044
3250
  balanceNewAgents: this.prefs.balanceNewAgents,
3045
- paidFallback: this.prefs.paidApiFallback,
3251
+ paidFallback: paid,
3046
3252
  autoRedeem: this.prefs.autoRedeem,
3047
3253
  portable: this.adapters[family].portable,
3048
3254
  usageOf: (id) => this.usage.get(id),
@@ -3434,6 +3640,11 @@ export class Service {
3434
3640
  private movesUnattended(state: StoredState, agent: AgentInfo, family: Family, current: string, target: string, now: number): boolean {
3435
3641
  const reason = this.driftReason(state, agent.id, current, target, now);
3436
3642
  const stranded = !this.adapters[family].portable && agent.hasHistory;
3643
+ // A throttled paid stand-in (Bedrock) is no reason to move: the target can only be an account
3644
+ // that is out too, so the agent would just be reopened where it can't work.
3645
+ const from = findAccount(state, current);
3646
+ const to = findAccount(state, target);
3647
+ if (from && isLastResort(from) && isLimited(from, now) && (!to || !isUsable(to, now, this.agentModels.get(agent.id)))) return false;
3437
3648
  return stranded || (reason !== "manual" && reason !== "default");
3438
3649
  }
3439
3650
 
@@ -3444,9 +3655,22 @@ export class Service {
3444
3655
  if (!from.signedIn) return "signed_out";
3445
3656
  if (from.disabled) return "disabled";
3446
3657
  if (isLimitedFor(from, now, this.agentModels.get(agentId))) return "limit";
3658
+ if (this.leavesPaid(state, current, target)) return "room";
3447
3659
  return state.bindings[agentId]?.accountId === target ? "manual" : "default";
3448
3660
  }
3449
3661
 
3662
+ /**
3663
+ * Whether a move takes an agent off a paid stand-in (Bedrock) onto a subscription account: routing
3664
+ * sends it back once its own account, or the default it follows, has room again, and alignment makes
3665
+ * that move by itself, so the agent doesn't stay on the bill. One the user put on the stand-in
3666
+ * (picked for it, or made the default) is routed there anyway, so it never comes to this.
3667
+ */
3668
+ private leavesPaid(state: StoredState, current: string, target: string): boolean {
3669
+ const from = findAccount(state, current);
3670
+ const to = findAccount(state, target);
3671
+ return Boolean(from && to && isLastResort(from) && !isLastResort(to));
3672
+ }
3673
+
3450
3674
  private async appendRow(paseo: PaseoApi, agentId: string, row: SwitchRow): Promise<void> {
3451
3675
  try {
3452
3676
  await paseo.agents.ref(agentId).timeline.append({
@@ -3649,6 +3873,7 @@ export class Service {
3649
3873
  const proxies = new Map<string, ProxyState>();
3650
3874
  const apis = new Map<string, ApiSummary | null>();
3651
3875
  const azures = new Map<string, AzureSummary>();
3876
+ const bedrocks = new Map<string, BedrockSummary>();
3652
3877
  const apiMonths: ApiUsageFile = await this.apiUsage.read().catch(() => ({ accounts: {}, threads: {} }));
3653
3878
  const external = new Set<string>();
3654
3879
  await Promise.all(
@@ -3668,6 +3893,11 @@ export class Service {
3668
3893
  const settings = await readAzureAccount(account.home).catch(() => null);
3669
3894
  if (settings) azures.set(account.id, azureSummary(settings, currentMonth(apiMonths.accounts[account.id], now)));
3670
3895
  }
3896
+ if (isBedrockAccount(account)) {
3897
+ // Never the secret or session token, only the key ID's hint (see bedrockSummary).
3898
+ const settings = await readBedrockAccount(account.home).catch(() => null);
3899
+ if (settings) bedrocks.set(account.id, bedrockSummary(settings, currentMonth(apiMonths.accounts[account.id], now)));
3900
+ }
3671
3901
  }),
3672
3902
  );
3673
3903
  // A proxy kept in the user's file (Pi's own login's in its settings) is also the one every added
@@ -3706,8 +3936,8 @@ export class Service {
3706
3936
  home: account.home,
3707
3937
  auth: account.auth,
3708
3938
  api: apiView(apis.get(account.id)),
3709
- // An Azure account's endpoint and key have their own form (see `azure`).
3710
- apiEditable: (account.auth === "api" && !isAzureAccount(account)) || (account.kind === "main" && this.adapters[account.family].mainApi === true),
3939
+ // Azure and Bedrock accounts have forms of their own (see `azure`, `bedrock`).
3940
+ apiEditable: (account.auth === "api" && !isLastResort(account)) || (account.kind === "main" && this.adapters[account.family].mainApi === true),
3711
3941
  proxy: proxy?.own ? maskProxy(proxy.own) : null,
3712
3942
  proxyEditable: proxy !== undefined,
3713
3943
  proxyBlocked: proxy?.blocked ?? null,
@@ -3722,6 +3952,8 @@ export class Service {
3722
3952
  ? paceView(this.usage.get(account.id), this.pendingOn(account.id, now), now)
3723
3953
  : null,
3724
3954
  azure: azures.get(account.id) ?? null,
3955
+ bedrock: bedrocks.get(account.id) ?? null,
3956
+ apiError: !account.signedIn && isLastResort(account) ? (account.apiError ?? null) : null,
3725
3957
  };
3726
3958
  });
3727
3959
 
@@ -3818,7 +4050,10 @@ export class Service {
3818
4050
  private cachedAgents(paseo: PaseoApi): Promise<AgentInfo[]> {
3819
4051
  if (this.agentCache && Date.now() - this.agentCache.at < AGENT_LIST_MS) return this.agentCache.agents;
3820
4052
  const agents = listAgents(paseo, false).then((result) => {
3821
- for (const agent of result.agents) this.noteModel(agent);
4053
+ for (const agent of result.agents) {
4054
+ this.agentModes.set(agent.id, agent.modeId);
4055
+ this.noteModel(agent);
4056
+ }
3822
4057
  return result.agents;
3823
4058
  });
3824
4059
  this.agentCache = { at: Date.now(), agents };
@@ -3912,7 +4147,7 @@ export class Service {
3912
4147
  if (portable && !this.prefs.moveAgentsOnDefaultChange) {
3913
4148
  // The new default is for what comes next: open agents stay on the account they run on. If they
3914
4149
  // can't be kept, the old default comes back, or alignment would move them all to the new one.
3915
- const { kept, moving } = await this.keepOpenAgents(paseo, account.family, account.id).catch(async (error: unknown) => {
4150
+ const { kept, moving } = await this.keepOpenAgents(paseo, account.family, account.id, previous).catch(async (error: unknown) => {
3916
4151
  await this.store.update((draft) => {
3917
4152
  if (draft.defaults[account.family] === account.id) draft.defaults[account.family] = previous;
3918
4153
  });
@@ -4014,11 +4249,15 @@ export class Service {
4014
4249
  * that opened under the old one just before is kept too, even if its session was still being
4015
4250
  * routed. Agents already on the new default keep following it. An account that's gone, signed
4016
4251
  * out, disabled or at its limit is no place to keep work, so those agents come back in `moving`.
4252
+ * One on a paid stand-in (Bedrock) is kept there as the user's pick when that was the old default
4253
+ * (`previous`), which they chose; otherwise it was only standing in, and an "auto" binding there
4254
+ * lets it go once a subscription account can take it (see `chooseAccount`).
4017
4255
  */
4018
4256
  private async keepOpenAgents(
4019
4257
  paseo: PaseoApi,
4020
4258
  family: Family,
4021
4259
  newDefault: string,
4260
+ previous: string | null = null,
4022
4261
  ): Promise<{ kept: number; moving: string[] }> {
4023
4262
  // A session being routed may have gone by the old default: let it record where it opens first.
4024
4263
  if (this.routing.size > 0) await withTimeout(Promise.allSettled(this.routing.keys()), ROUTING_WAIT_MS);
@@ -4046,7 +4285,7 @@ export class Service {
4046
4285
  if (!current || current.family !== family || !isUsable(current, now, this.agentModels.get(agent.id))) moving.push(agent.id);
4047
4286
  else if (current.id !== newDefault) {
4048
4287
  // "auto", like a limit switch, so the account button still offers "Follow default".
4049
- draft.bindings[agent.id] = { accountId: current.id, source: "auto", at };
4288
+ draft.bindings[agent.id] = { accountId: current.id, source: isLastResort(current) && current.id === previous ? "user" : "auto", at };
4050
4289
  kept += 1;
4051
4290
  }
4052
4291
  }
@@ -4224,7 +4463,7 @@ export class Service {
4224
4463
  }
4225
4464
  this.setUsage(accountId, null);
4226
4465
  this.egress.delete(accountId);
4227
- if (isAzureAccount(account)) await this.apiUsage.forget(accountId).catch((error: unknown) => log(`could not forget ${account.label}'s token counts`, error));
4466
+ if (isLastResort(account)) await this.apiUsage.forget(accountId).catch((error: unknown) => log(`could not forget ${account.label}'s token counts`, error));
4228
4467
  if (account.home && kept) console.log(`[ZeroSub] removed ${account.label} from ZeroSub only: ${account.home} isn't a folder ZeroSub made in ${homesDir()}, so its files and script stay`);
4229
4468
  // Its script is released rather than deleted when its home stays (see writeLaunchers).
4230
4469
  await this.refreshLaunchers(account.home && !kept ? [account.home] : []).catch((error: unknown) => log("could not write the shell launchers", error));
@@ -4323,7 +4562,10 @@ export class Service {
4323
4562
  if (!target) return;
4324
4563
  target.identity = azureIdentity(endpoint, key);
4325
4564
  // A new key or endpoint is worth trying again even if the old one was refused.
4326
- if (changed) target.signedIn = true;
4565
+ if (changed) {
4566
+ target.signedIn = true;
4567
+ target.apiError = null;
4568
+ }
4327
4569
  });
4328
4570
  return { warning };
4329
4571
  });
@@ -4353,6 +4595,146 @@ export class Service {
4353
4595
  console.log(`[ZeroSub] couldn't find the Codex session file of ${agentId}, so its last turn's tokens aren't counted`);
4354
4596
  }
4355
4597
 
4598
+ // ------------------------------------------------------------------ AWS Bedrock accounts
4599
+
4600
+ /**
4601
+ * The region the host's own AWS setup names, to fill in the Bedrock form. Only the form asks, when it
4602
+ * opens: on a host that isn't an EC2 instance the metadata service never answers, so this is never
4603
+ * looked up at startup or for the state view (see `detectHostRegion`).
4604
+ */
4605
+ async detectBedrockRegion(): Promise<{ region: string | null; source: RegionSource | null }> {
4606
+ return this.aws.detectRegion().catch(() => ({ region: null, source: null }));
4607
+ }
4608
+
4609
+ /**
4610
+ * Adds an AWS Bedrock account under Claude: a region, where its AWS credentials come from (the host's
4611
+ * own default chain, a named profile, or an access key kept in its home), and optional model
4612
+ * overrides. The credentials are checked first (see `checkBedrock`): refused ones aren't saved, and
4613
+ * `warning` says when they couldn't be checked. Secrets go only to the home's `bedrock.json`, and
4614
+ * the account is marked `provider: "bedrock"`.
4615
+ */
4616
+ async addBedrockAccount(input: BedrockInput & { label: string }): Promise<{ accountId: string; warning: string | null }> {
4617
+ const account = bedrockFromInput(input, null);
4618
+ const identity = bedrockIdentity(account);
4619
+ const duplicate = accountsOf(await this.store.read(), "claude").find((entry) => entry.identity === identity);
4620
+ if (duplicate) throw new Error(`Those AWS credentials in ${account.region} are already added as "${duplicate.label}".`);
4621
+ const check = await this.aws.check(account);
4622
+ if (!check.ok && check.fatal) throw new Error(check.message);
4623
+
4624
+ const id = `claude-${randomBytes(6).toString("hex")}`;
4625
+ const home = join(homesDir(), id);
4626
+ this.creatingHomes.add(home);
4627
+ try {
4628
+ await this.store.update((draft) => {
4629
+ draft.cleanup[home] = { family: "claude", accountId: id, why: "unfinished", at: new Date().toISOString() };
4630
+ });
4631
+ await writeBedrockAccount(home, account);
4632
+ await this.adapters.claude.prepareHome(home);
4633
+ await this.store.update((draft) => {
4634
+ const twin = accountsOf(draft, "claude").find((entry) => entry.identity === identity);
4635
+ if (twin) throw new Error(`Those AWS credentials in ${account.region} are already added as "${twin.label}".`);
4636
+ const stored = newAccount({ id, family: "claude", kind: "managed", home, auth: "api", provider: "bedrock" });
4637
+ stored.label = input.label.trim();
4638
+ stored.autoLabel = false;
4639
+ stored.identity = identity;
4640
+ stored.plan = "AWS Bedrock";
4641
+ draft.accounts.push(stored);
4642
+ delete draft.cleanup[home];
4643
+ });
4644
+ } catch (error) {
4645
+ const removed = await removeHome(home).then(
4646
+ () => true,
4647
+ (failure: unknown) => (log(`could not delete the half-made home ${home}; the cleanup pass tries again`, failure), false),
4648
+ );
4649
+ if (removed) await this.store.update((draft) => void delete draft.cleanup[home]).catch(() => undefined);
4650
+ throw error;
4651
+ } finally {
4652
+ this.creatingHomes.delete(home);
4653
+ }
4654
+ console.log(`[ZeroSub] added AWS Bedrock account ${input.label.trim()} (${account.region}, ${account.source} credentials)${check.ok ? "" : "; its credentials couldn't be checked"}`);
4655
+ return { accountId: id, warning: check.ok ? null : `Saved, but ${lowerFirst(check.message)}` };
4656
+ }
4657
+
4658
+ /**
4659
+ * Changes a Bedrock account's region, credentials (an access key's secret left empty keeps it, for
4660
+ * the same key ID), model overrides or price table. Changed credentials or region are checked as when
4661
+ * adding, and its `settings.json` is remade at once.
4662
+ */
4663
+ async updateBedrockAccount(accountId: string, input: Partial<BedrockInput> & { prices?: Record<string, ApiPrice> }): Promise<{ warning: string | null }> {
4664
+ return this.onAccount(accountId, async (stored) => {
4665
+ if (!stored || !stored.home) throw new Error("That account no longer exists.");
4666
+ if (!isBedrockAccount(stored)) throw new Error(`${stored.label} isn't an AWS Bedrock account.`);
4667
+ const home = stored.home;
4668
+ const current = await readBedrockAccount(home);
4669
+ const source = input.source ?? current.source;
4670
+ const account = bedrockFromInput(
4671
+ {
4672
+ region: input.region ?? current.region,
4673
+ source,
4674
+ profile: input.profile ?? current.profile ?? undefined,
4675
+ // The stored key ID is only shown by its hint, so an empty one keeps it.
4676
+ accessKeyId: input.accessKeyId?.trim() || (current.source === "keys" ? (current.accessKeyId ?? undefined) : undefined),
4677
+ secretAccessKey: input.secretAccessKey,
4678
+ sessionToken: input.sessionToken,
4679
+ models: input.models ?? current.models,
4680
+ },
4681
+ current,
4682
+ );
4683
+ if (input.prices) {
4684
+ account.prices = Object.fromEntries(Object.entries(input.prices).map(([model, price]) => [model.trim(), price] as const).filter(([model]) => model !== ""));
4685
+ }
4686
+ const identity = bedrockIdentity(account);
4687
+ const credentialsChanged =
4688
+ identity !== bedrockIdentity(current) || account.secretAccessKey !== current.secretAccessKey || account.sessionToken !== current.sessionToken;
4689
+ let warning: string | null = null;
4690
+ if (credentialsChanged) {
4691
+ const duplicate = accountsOf(await this.store.read(), "claude").find((entry) => entry.id !== accountId && entry.identity === identity);
4692
+ if (duplicate) throw new Error(`Those AWS credentials in ${account.region} are already added as "${duplicate.label}".`);
4693
+ const check = await this.aws.check(account);
4694
+ if (!check.ok && check.fatal) throw new Error(check.message);
4695
+ if (!check.ok) warning = `Saved, but ${lowerFirst(check.message)}`;
4696
+ }
4697
+ if (!(await this.stillHas(stored)())) throw new Error("That account no longer exists.");
4698
+ await writeBedrockAccount(home, account);
4699
+ // Its settings.json follows bedrock.json (see bedrockSettings): remade now, not at the next sync.
4700
+ await prepareClaudeHome(home, true, this.stillHas(stored)).catch((error: unknown) => log(`could not refresh the home of ${stored.label}`, error));
4701
+ await this.store.update((draft) => {
4702
+ const target = findAccount(draft, accountId);
4703
+ if (!target) return;
4704
+ target.identity = identity;
4705
+ // New credentials, a region or models are worth trying again even if the last ones were refused.
4706
+ target.signedIn = true;
4707
+ target.apiError = null;
4708
+ });
4709
+ return { warning };
4710
+ });
4711
+ }
4712
+
4713
+ /**
4714
+ * Counts the tokens an agent's turn on a Bedrock account used, from its Claude Code session file
4715
+ * (shared by every Claude home): the assistant messages written since the turn started, each counted
4716
+ * once, since a Claude conversation can move between accounts and its earlier messages may have run
4717
+ * elsewhere. Claude Code writes the file as the turn goes, so this waits a moment after the turn
4718
+ * ends. A turn whose file can't be found is noted as uncounted, so the card says its totals are short.
4719
+ */
4720
+ private async countBedrockTurn(paseo: PaseoApi, agentId: string, accountId: string, startedAt: number): Promise<void> {
4721
+ await delay(1_500);
4722
+ if (this.stopped) return;
4723
+ const agent = (await paseo.agents.ref(agentId).refresh().catch(() => null))?.agent as
4724
+ | { persistence?: { sessionId?: string; nativeHandle?: string } | null }
4725
+ | undefined;
4726
+ const ids = [agent?.persistence?.sessionId, agent?.persistence?.nativeHandle].filter((id): id is string => typeof id === "string" && id !== "");
4727
+ for (const sessionId of new Set(ids)) {
4728
+ const path = await findClaudeSession(sessionId);
4729
+ if (!path) continue;
4730
+ // A little slack for the clocks of the hook and of Claude Code's own timestamps.
4731
+ await this.apiUsage.countMessages(accountId, sessionId, parseClaudeSession(await readFile(path, "utf8"), startedAt - 5_000));
4732
+ return;
4733
+ }
4734
+ await this.apiUsage.noteUncounted(accountId);
4735
+ console.log(`[ZeroSub] couldn't find the Claude Code session file of ${agentId}, so its last turn's tokens aren't counted`);
4736
+ }
4737
+
4356
4738
  // ------------------------------------------------------------------ Pi accounts
4357
4739
 
4358
4740
  /**
@@ -4401,10 +4783,17 @@ export class Service {
4401
4783
  }
4402
4784
  }
4403
4785
 
4404
- /** Added accounts of `kind`, which each get a `<kind>-<account>.sh` script. */
4786
+ /**
4787
+ * Added accounts of `kind`, which each get a `<kind>-<account>.sh` script. An AWS Bedrock account
4788
+ * gets none: its credentials (an access key's secret) reach its sessions in their environment, which
4789
+ * a script would have to read from bedrock.json, so a terminal would run on whatever AWS credentials
4790
+ * the shell has instead.
4791
+ */
4405
4792
  private launcherAccounts(state: StoredState, kind: LauncherKind = "claude"): LauncherAccount[] {
4406
4793
  return state.accounts.flatMap((account) =>
4407
- account.family === kind && account.kind === "managed" && account.home ? [{ id: account.id, label: account.label, home: account.home }] : [],
4794
+ account.family === kind && account.kind === "managed" && account.home && !isBedrockAccount(account)
4795
+ ? [{ id: account.id, label: account.label, home: account.home }]
4796
+ : [],
4408
4797
  );
4409
4798
  }
4410
4799
 
@@ -4659,6 +5048,7 @@ export class Service {
4659
5048
  return;
4660
5049
  }
4661
5050
  if (isAzureAccount(account)) throw new Error(`${account.label} is an Azure OpenAI account: change its key from its own settings.`);
5051
+ if (isBedrockAccount(account)) throw new Error(`${account.label} is an AWS Bedrock account: change its credentials from its own settings.`);
4662
5052
  if (account.auth !== "api" || !account.home || !adapter.setApi) throw new Error(`${account.label} signs in with a subscription, not an API key.`);
4663
5053
  // A kept key stays on its base URL (the adapter refuses to move it), so its identity holds.
4664
5054
  const identity = key ? apiIdentity(baseUrl, keyDigest(key)) : null;
@@ -4695,6 +5085,9 @@ export class Service {
4695
5085
  const home = await chooseImportedHome(input, (await this.store.read()).accounts);
4696
5086
  const shown = shownPath(home);
4697
5087
  if ([...this.logins.values()].some((login) => login.home === home && !login.finishedAt)) throw new Error(`${shown} is being signed in right now.`);
5088
+ // A removed AWS Bedrock account's home, waiting in `homes/` to be deleted: it isn't signed in to a
5089
+ // subscription, and its sessions would run on Bedrock under a subscription account's name.
5090
+ if (isBedrockHome(home)) throw new Error(`${shown} is an AWS Bedrock account's folder, not one signed in with a Claude subscription. Add it again with "AWS Bedrock" instead.`);
4698
5091
  const identity = await this.adapters.claude.identity(home).catch((error: unknown) => {
4699
5092
  throw new Error(`ZeroSub couldn't tell whether ${shown} is signed in: ${describe(error)}`);
4700
5093
  });
@@ -4911,6 +5304,9 @@ export class Service {
4911
5304
  for (const account of accountsOf(state, family)) {
4912
5305
  const home = account.home;
4913
5306
  if (account.kind !== "managed" || !home || state.moves[account.id]) continue;
5307
+ // An AWS Bedrock account's home stays in `homes/`: removing it then deletes its bedrock.json
5308
+ // (an access key's secret) with it, rather than leaving it in a folder of the user's.
5309
+ if (isBedrockAccount(account)) continue;
4914
5310
  const folder = dirname(resolve(home));
4915
5311
  if (folder === dir || !sources.has(folder)) continue;
4916
5312
  if ((await lstat(home).catch(() => null))?.isDirectory()) due.push({ ...account, home });
@@ -5095,6 +5491,7 @@ export class Service {
5095
5491
  const state = await this.store.read();
5096
5492
  const existing = accountId ? findAccount(state, accountId) : undefined;
5097
5493
  if (accountId && (!existing || existing.family !== family)) throw new Error("That account no longer exists.");
5494
+ if (existing && isBedrockAccount(existing)) throw new Error(`${existing.label} uses AWS credentials. Change them from its card instead.`);
5098
5495
  if (existing?.auth === "api") throw new Error(`${existing.label} uses an API key. Change the key from its card instead.`);
5099
5496
  // The CLI would sign in into the folder the account is leaving, and the sign-in go with it.
5100
5497
  if (existing && (this.moving.has(existing.id) || state.moves[existing.id])) {
@@ -5279,6 +5676,62 @@ export class Service {
5279
5676
 
5280
5677
  // -------------------------------------------------------------------- helpers
5281
5678
 
5679
+ /** What the add and edit forms send for a Bedrock account. */
5680
+ interface BedrockInput {
5681
+ region: string;
5682
+ source: BedrockSource;
5683
+ profile?: string;
5684
+ accessKeyId?: string;
5685
+ /** Empty keeps the stored one, for the same access key ID. */
5686
+ secretAccessKey?: string;
5687
+ /** Empty keeps the stored one along with a kept secret; a new secret drops it unless one is typed with it. */
5688
+ sessionToken?: string;
5689
+ models?: Partial<BedrockModels>;
5690
+ }
5691
+
5692
+ /** A Bedrock account's settings from a form, checked; `current` supplies a kept secret (same key ID only) and the prices. */
5693
+ function bedrockFromInput(input: BedrockInput, current: BedrockAccount | null): BedrockAccount {
5694
+ const region = normalizeRegion(input.region);
5695
+ const trim = (value: string | undefined) => value?.trim() || null;
5696
+ const models: BedrockModels = { model: "", opus: "", sonnet: "", haiku: "" };
5697
+ for (const field of Object.keys(models) as Array<keyof BedrockModels>) {
5698
+ const model = input.models?.[field]?.trim() ?? "";
5699
+ if (model && !/^[\w.:/-]{3,200}$/.test(model)) throw new Error(`"${model}" doesn't look like a Bedrock model or inference-profile ID`);
5700
+ models[field] = model;
5701
+ }
5702
+ const account: BedrockAccount = {
5703
+ region,
5704
+ source: input.source,
5705
+ profile: null,
5706
+ accessKeyId: null,
5707
+ secretAccessKey: null,
5708
+ sessionToken: null,
5709
+ models,
5710
+ prices: current?.prices ?? {},
5711
+ };
5712
+ if (input.source === "profile") {
5713
+ const profile = trim(input.profile);
5714
+ if (!profile || !/^[\w.+@=,-]{1,128}$/.test(profile)) throw new Error("Enter the name of an AWS profile in the host's ~/.aws config");
5715
+ account.profile = profile;
5716
+ } else if (input.source === "keys") {
5717
+ const keyId = trim(input.accessKeyId);
5718
+ if (!keyId || !/^[A-Z0-9]{16,128}$/.test(keyId)) throw new Error("Enter the access key ID (like AKIA… or ASIA…)");
5719
+ const typed = trim(input.secretAccessKey);
5720
+ const kept = current?.source === "keys" && current.accessKeyId === keyId;
5721
+ const secret = typed ?? (kept ? current.secretAccessKey : null);
5722
+ if (!secret) throw new Error(kept ? "Enter the secret access key" : "Enter the secret access key for this access key ID");
5723
+ account.accessKeyId = keyId;
5724
+ account.secretAccessKey = secret;
5725
+ // A session token belongs to its secret: kept only with a kept secret.
5726
+ account.sessionToken = trim(input.sessionToken) ?? (typed ? null : (current?.sessionToken ?? null));
5727
+ }
5728
+ return account;
5729
+ }
5730
+
5731
+ function lowerFirst(text: string): string {
5732
+ return `${text.charAt(0).toLowerCase()}${text.slice(1)}`;
5733
+ }
5734
+
5282
5735
  /** An adapter's API summary as the app shows it, the key kind and switches filled in. */
5283
5736
  function apiView(api: ApiSummary | null | undefined): AccountView["api"] {
5284
5737
  return api ? ApiSummarySchema.parse(api) : null;
@@ -5296,9 +5749,40 @@ function trafficSwitches(input: Partial<TrafficSwitches>): TrafficSwitches {
5296
5749
  };
5297
5750
  }
5298
5751
 
5299
- /** The timeline's word on work that moved onto a paid Azure account by itself (with `paidApiFallback` on). */
5300
- function azureFallbackNote(label: string): string {
5301
- return `Every ChatGPT subscription account is out, so this runs on ${label}: Azure OpenAI, a paid API billed per token. New agents go back to a ChatGPT account once one has room.`;
5752
+ /** Claude's Auto mode, as Paseo names it: Paseo's default Claude mode, which Bedrock can't run. */
5753
+ const CLAUDE_AUTO_MODE = "auto";
5754
+
5755
+ /** Whether a Claude agent runs in Auto mode. One whose mode isn't known counts too: Auto is Paseo's default. */
5756
+ function runsAutoMode(modeId: string | null | undefined): boolean {
5757
+ return modeId === undefined || modeId === null || modeId === CLAUDE_AUTO_MODE;
5758
+ }
5759
+
5760
+ /** The timeline's word when paid fallback left Bedrock out for an agent in Auto mode. */
5761
+ function autoModeSkipNote(label: string): string {
5762
+ return `${label} (AWS Bedrock) wasn't used: Bedrock can't run Claude's Auto mode, which needs the Anthropic API. Switch this agent to another mode (Accept File Edits, say) to let it move there.`;
5763
+ }
5764
+
5765
+ /** The timeline's word when Paseo refused Auto mode on a Bedrock account the agent was put on by hand or as the default. */
5766
+ function autoModeRefusedNote(label: string): string {
5767
+ return `Claude's Auto mode can't run on ${label}: on AWS Bedrock it needs the Anthropic API, so Paseo didn't start the turn. Pick another mode for this agent (Accept File Edits, say), or move it to a Claude subscription account. ${label} stays usable.`;
5768
+ }
5769
+
5770
+ function joinDetails(...details: Array<string | null>): string | null {
5771
+ const text = details.filter((detail): detail is string => !!detail).join(" ");
5772
+ return text || null;
5773
+ }
5774
+
5775
+ /** What to do when Claude Code finds the agent's model missing in a Bedrock account's region. */
5776
+ function bedrockModelNote(label: string, model: string): string {
5777
+ return `Bedrock in ${label}'s region doesn't offer ${model}, which Claude Code picked for this agent's model. Claude Code's built-in Bedrock defaults for the opus, sonnet and haiku aliases can be older than a region offers: set the Opus, Sonnet and Haiku models in ${label}'s Bedrock settings (an inference profile your AWS account has, such as global.anthropic.claude-sonnet-5-5), or pick another model for this agent. ${label} stays usable for other models.`;
5778
+ }
5779
+
5780
+ /** The timeline's word on work that moved onto a paid Azure or Bedrock account by itself (with `paidApiFallback` on). */
5781
+ function paidFallbackNote(account: StoredAccount): string {
5782
+ if (isBedrockAccount(account)) {
5783
+ return `Every Claude subscription account is out, so this runs on ${account.label}: AWS Bedrock, a paid API billed per token. It moves back to a Claude account once one has room.`;
5784
+ }
5785
+ return `Every ChatGPT subscription account is out, so this runs on ${account.label}: Azure OpenAI, a paid API billed per token. New agents go back to a ChatGPT account once one has room.`;
5302
5786
  }
5303
5787
 
5304
5788
  /** What tells an API key's account from another: where the key goes, and a short hash of the key. */
@@ -5429,6 +5913,7 @@ function toAgentInfo(agent: AgentSnapshot): AgentInfo {
5429
5913
  lastMessageAt: Date.parse(agent.lastUserMessageAt ?? "") || 0,
5430
5914
  updatedAt: Date.parse(agent.updatedAt) || 0,
5431
5915
  backgroundWork: (agent as { backgroundWork?: { count?: number } }).backgroundWork?.count ?? 0,
5916
+ modeId: agent.currentModeId ?? null,
5432
5917
  named: metadata ? metadata[AGENT_METADATA_KEY] === agent.id : null,
5433
5918
  model: agent.model ?? agent.runtimeInfo?.model ?? null,
5434
5919
  };