@kapybara/zerosub 1.18.2 → 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,455 @@
1
+ import type { PluginSurfaceProps } from "@getpaseo/plugin/client";
2
+ import { Modal, TextInput, useToast } from "@getpaseo/plugin/client/react-native";
3
+ import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from "react";
4
+ import { Pressable, Text, View } from "react-native";
5
+ import { apiUsageLines } from "../shared/format";
6
+ import type { AccountView, ApiPrice, BedrockModels, BedrockSource } from "../shared/model";
7
+ import { addBedrockAccount, detectBedrockRegion, updateBedrockAccount } from "../shared/rpc";
8
+ import { describe, type ZeroSubStore } from "./store";
9
+ import { Button, IconButton, useText } from "./ui";
10
+
11
+ type Theme = PluginSurfaceProps["theme"];
12
+
13
+ /**
14
+ * AWS Bedrock accounts: Claude accounts that run Claude Code on Amazon Bedrock with AWS credentials:
15
+ * the host's own (an instance role, say), a named profile, or an access key kept on the host. A
16
+ * secret typed here never comes back from the host; the app sees only the key ID's last four characters.
17
+ */
18
+
19
+ const SOURCES: ReadonlyArray<{ value: BedrockSource; label: string }> = [
20
+ { value: "host", label: "Host's AWS credentials" },
21
+ { value: "profile", label: "AWS profile" },
22
+ { value: "keys", label: "Access key" },
23
+ ];
24
+
25
+ const MODEL_FIELDS: ReadonlyArray<{ field: keyof BedrockModels; title: string; placeholder: string }> = [
26
+ { field: "model", title: "Default model (ANTHROPIC_MODEL)", placeholder: "e.g. global.anthropic.claude-sonnet-4-5-20250929-v1:0" },
27
+ { field: "opus", title: "Opus (ANTHROPIC_DEFAULT_OPUS_MODEL)", placeholder: "Opus model or inference-profile ID" },
28
+ { field: "sonnet", title: "Sonnet (ANTHROPIC_DEFAULT_SONNET_MODEL)", placeholder: "Sonnet model or inference-profile ID" },
29
+ { field: "haiku", title: "Haiku (ANTHROPIC_DEFAULT_HAIKU_MODEL)", placeholder: "Haiku model or inference-profile ID" },
30
+ ];
31
+
32
+ const REGION_FROM: Record<"environment" | "config" | "instance", string> = {
33
+ environment: "From the daemon's AWS_REGION.",
34
+ config: "From the host's ~/.aws/config.",
35
+ instance: "From the EC2 instance the host runs on.",
36
+ };
37
+
38
+ /** The card's line about a Bedrock account: its region and where its credentials come from. */
39
+ export function bedrockCardDetails(account: AccountView): string | null {
40
+ const bedrock = account.bedrock;
41
+ if (!bedrock) return null;
42
+ const source =
43
+ bedrock.source === "profile"
44
+ ? `profile ${bedrock.profile ?? ""}`.trim()
45
+ : bedrock.source === "keys"
46
+ ? `access key${bedrock.keyHint ? ` …${bedrock.keyHint}` : ""}`
47
+ : "host's AWS credentials";
48
+ return `${bedrock.region} · ${source}`;
49
+ }
50
+
51
+ /** This month's tokens and estimated cost, in place of the usage bars of a subscription account. */
52
+ export function BedrockUsage({ theme, account, paidFallback }: { theme: Theme; account: AccountView; paidFallback: boolean }) {
53
+ const text = useText(theme);
54
+ if (!account.bedrock) return null;
55
+ const { tokens, cost, note } = apiUsageLines(account.bedrock);
56
+ return (
57
+ <View style={{ gap: 4 }}>
58
+ <Text style={text.small}>{tokens}</Text>
59
+ <Text style={text.small}>{cost}</Text>
60
+ {note ? <Text style={text.small}>{note}</Text> : null}
61
+ <Text style={text.small}>
62
+ {paidFallback
63
+ ? "Billed per token · used by itself only when every Claude subscription account is out, or when picked"
64
+ : "Billed per token · used only as the default or when picked for an agent"}
65
+ </Text>
66
+ </View>
67
+ );
68
+ }
69
+
70
+ interface PriceRow {
71
+ model: string;
72
+ input: string;
73
+ cachedInput: string;
74
+ cacheWrite: string;
75
+ output: string;
76
+ }
77
+
78
+ function toRows(prices: Readonly<Record<string, ApiPrice>>): PriceRow[] {
79
+ const show = (value: number | null) => (value === null ? "" : String(value));
80
+ return Object.entries(prices).map(([model, price]) => ({
81
+ model,
82
+ input: show(price.input),
83
+ cachedInput: show(price.cachedInput),
84
+ cacheWrite: show(price.cacheWrite),
85
+ output: show(price.output),
86
+ }));
87
+ }
88
+
89
+ /** The table typed in, or the first problem with it. */
90
+ function fromRows(rows: readonly PriceRow[]): Record<string, ApiPrice> | string {
91
+ const prices: Record<string, ApiPrice> = {};
92
+ for (const row of rows) {
93
+ const model = row.model.trim();
94
+ if (!model) continue;
95
+ const parse = (value: string): number | null | undefined => {
96
+ if (!value.trim()) return null;
97
+ const number = Number(value.trim());
98
+ return Number.isFinite(number) && number >= 0 ? number : undefined;
99
+ };
100
+ const price = { input: parse(row.input), cachedInput: parse(row.cachedInput), cacheWrite: parse(row.cacheWrite), output: parse(row.output) };
101
+ if (Object.values(price).some((value) => value === undefined)) return `Prices for ${model} must be numbers (USD per 1M tokens).`;
102
+ prices[model] = price as ApiPrice;
103
+ }
104
+ return prices;
105
+ }
106
+
107
+ /**
108
+ * The fields of an AWS Bedrock account. Adding asks for a name, the region (filled in from the host's
109
+ * own AWS setup when it names one, looked up as the form opens), where the credentials come from and
110
+ * optional model overrides; editing keeps a stored secret unless a new one is typed, and adds the
111
+ * price table the card's cost estimate comes from.
112
+ */
113
+ export function BedrockAccountForm({
114
+ theme,
115
+ store,
116
+ account,
117
+ paidFallback,
118
+ onDone,
119
+ onCancel,
120
+ }: {
121
+ theme: Theme;
122
+ store: ZeroSubStore;
123
+ /** The account being edited; absent when adding one. */
124
+ account?: AccountView;
125
+ /** Paid API accounts may take work over by themselves once every subscription is out. */
126
+ paidFallback: boolean;
127
+ onDone(accountId: string, warning: string | null): void;
128
+ onCancel(): void;
129
+ }) {
130
+ const text = useText(theme);
131
+ const current = account?.bedrock ?? null;
132
+ const editing = Boolean(account);
133
+ const [label, setLabel] = useState("");
134
+ const [region, setRegion] = useState(current?.region ?? "");
135
+ const [regionNote, setRegionNote] = useState<string | null>(null);
136
+ const [source, setSource] = useState<BedrockSource>(current?.source ?? "host");
137
+ const [profile, setProfile] = useState(current?.profile ?? "");
138
+ const [accessKeyId, setAccessKeyId] = useState("");
139
+ const [secret, setSecret] = useState("");
140
+ const [sessionToken, setSessionToken] = useState("");
141
+ const [models, setModels] = useState<BedrockModels>(current?.models ?? { model: "", opus: "", sonnet: "", haiku: "" });
142
+ const [rows, setRows] = useState<PriceRow[]>(() => toRows(current?.prices ?? {}));
143
+ const [saving, setSaving] = useState(false);
144
+ const [error, setError] = useState<string | null>(null);
145
+ /** The region was typed in, so a lookup answering late leaves it alone. */
146
+ const regionTyped = useRef(editing);
147
+
148
+ // The host's region is only looked up here, as the form opens: it can take a moment (an EC2 host's
149
+ // comes from its metadata service), and the field stays editable meanwhile.
150
+ useEffect(() => {
151
+ if (editing) return;
152
+ let live = true;
153
+ setRegionNote("Looking up the host's AWS region…");
154
+ store
155
+ .rpc(detectBedrockRegion, {})
156
+ .then((found) => {
157
+ if (!live) return;
158
+ if (found.region && found.source && !regionTyped.current) {
159
+ setRegion(found.region);
160
+ setRegionNote(REGION_FROM[found.source]);
161
+ } else setRegionNote(null);
162
+ })
163
+ .catch(() => live && setRegionNote(null));
164
+ return () => {
165
+ live = false;
166
+ };
167
+ }, [editing, store]);
168
+
169
+ // Editing an access key: the stored ID is only shown by its hint, so a new ID needs its secret too.
170
+ const keepsKey = editing && current?.source === "keys" && source === "keys" && !accessKeyId.trim();
171
+ const credentialsReady =
172
+ source === "host" || (source === "profile" ? Boolean(profile.trim()) : keepsKey || Boolean(accessKeyId.trim() && secret.trim()));
173
+ const ready = Boolean(region.trim()) && credentialsReady && (editing || Boolean(label.trim()));
174
+
175
+ const submit = useCallback(async () => {
176
+ if (!ready) return;
177
+ setSaving(true);
178
+ setError(null);
179
+ try {
180
+ const keys = source === "keys";
181
+ const fields = {
182
+ region: region.trim(),
183
+ source,
184
+ profile: source === "profile" ? profile.trim() : undefined,
185
+ accessKeyId: keys && accessKeyId.trim() ? accessKeyId.trim() : undefined,
186
+ secretAccessKey: keys && secret.trim() ? secret.trim() : undefined,
187
+ sessionToken: keys && sessionToken.trim() ? sessionToken.trim() : undefined,
188
+ models,
189
+ };
190
+ if (account) {
191
+ const prices = fromRows(rows);
192
+ if (typeof prices === "string") throw new Error(prices);
193
+ const result = await store.rpc(updateBedrockAccount, { accountId: account.id, ...fields, prices });
194
+ await store.refresh();
195
+ onDone(account.id, result.warning);
196
+ } else {
197
+ const result = await store.rpc(addBedrockAccount, { label: label.trim(), ...fields });
198
+ await store.refresh();
199
+ onDone(result.accountId, result.warning);
200
+ }
201
+ } catch (failure) {
202
+ setError(describe(failure));
203
+ } finally {
204
+ setSaving(false);
205
+ }
206
+ }, [ready, region, source, profile, accessKeyId, secret, sessionToken, models, account, rows, store, label, onDone]);
207
+
208
+ const inputStyle = useMemo(
209
+ () => ({
210
+ color: theme.colors.foreground,
211
+ backgroundColor: theme.colors.surface2,
212
+ borderColor: theme.colors.border,
213
+ borderWidth: 1,
214
+ borderRadius: 8,
215
+ paddingHorizontal: 12,
216
+ paddingVertical: 10,
217
+ fontSize: 14,
218
+ }),
219
+ [theme],
220
+ );
221
+ const input = (props: {
222
+ value: string;
223
+ onChangeText(value: string): void;
224
+ placeholder: string;
225
+ label: string;
226
+ /** As long as the RPC takes, so a longer value can't be typed in only to be refused. */
227
+ maxLength: number;
228
+ secure?: boolean;
229
+ autoFocus?: boolean;
230
+ flex?: number;
231
+ }) => (
232
+ <TextInput
233
+ value={props.value}
234
+ onChangeText={props.onChangeText}
235
+ maxLength={props.maxLength}
236
+ placeholder={props.placeholder}
237
+ placeholderTextColor={theme.colors.foregroundMuted}
238
+ autoCapitalize="none"
239
+ autoCorrect={false}
240
+ autoFocus={props.autoFocus}
241
+ secureTextEntry={props.secure}
242
+ style={props.flex ? [inputStyle, { flex: props.flex, minWidth: 0 }] : inputStyle}
243
+ accessibilityLabel={props.label}
244
+ />
245
+ );
246
+ const cell = (index: number, field: keyof PriceRow, placeholder: string, flex: number) =>
247
+ input({
248
+ value: rows[index]![field],
249
+ onChangeText: (value) => setRows((all) => all.map((row, at) => (at === index ? { ...row, [field]: value } : row))),
250
+ placeholder,
251
+ label: field === "model" ? "Model" : `${placeholder} price of ${rows[index]!.model}`,
252
+ maxLength: field === "model" ? 200 : 12,
253
+ flex,
254
+ });
255
+ const used = Object.keys(current?.usage?.models ?? {});
256
+
257
+ return (
258
+ <View style={{ gap: 12 }}>
259
+ {editing ? null : (
260
+ <Field theme={theme} title="Name">
261
+ {input({ value: label, onChangeText: setLabel, placeholder: "e.g. Bedrock", label: "Account name", maxLength: 40, autoFocus: true })}
262
+ </Field>
263
+ )}
264
+ <Field theme={theme} title="AWS region">
265
+ {input({
266
+ value: region,
267
+ onChangeText: (value) => {
268
+ regionTyped.current = true;
269
+ setRegion(value);
270
+ },
271
+ placeholder: "e.g. us-east-1",
272
+ label: "AWS region",
273
+ maxLength: 40,
274
+ })}
275
+ {regionNote ? <Text style={text.small}>{regionNote}</Text> : null}
276
+ </Field>
277
+ <Field theme={theme} title="Credentials">
278
+ <View style={{ flexDirection: "row", flexWrap: "wrap", gap: 6 }}>
279
+ {SOURCES.map((option) => (
280
+ <Pressable
281
+ key={option.value}
282
+ accessibilityRole="radio"
283
+ accessibilityState={{ checked: source === option.value }}
284
+ accessibilityLabel={option.label}
285
+ onPress={() => setSource(option.value)}
286
+ style={{
287
+ paddingHorizontal: 10,
288
+ paddingVertical: 6,
289
+ borderRadius: 8,
290
+ borderWidth: 1,
291
+ borderColor: source === option.value ? theme.colors.accent : theme.colors.border,
292
+ backgroundColor: source === option.value ? theme.colors.surface2 : "transparent",
293
+ }}
294
+ >
295
+ <Text style={{ color: theme.colors.foreground, fontSize: 13, fontWeight: source === option.value ? "600" : "400" }}>{option.label}</Text>
296
+ </Pressable>
297
+ ))}
298
+ </View>
299
+ {source === "host" ? (
300
+ <Text style={text.small}>
301
+ The AWS default chain on the host: the daemon's environment, ~/.aws, or an EC2 instance or ECS task role. Nothing is stored.
302
+ </Text>
303
+ ) : source === "profile" ? (
304
+ <>
305
+ {input({ value: profile, onChangeText: setProfile, placeholder: "Profile name in the host's ~/.aws config", label: "AWS profile", maxLength: 128 })}
306
+ <Text style={text.small}>Only the profile's name is stored; its credentials stay in ~/.aws.</Text>
307
+ </>
308
+ ) : (
309
+ <>
310
+ {input({
311
+ value: accessKeyId,
312
+ onChangeText: setAccessKeyId,
313
+ placeholder: current?.keyHint ? `Leave empty to keep …${current.keyHint}` : "Access key ID (AKIA… or ASIA…)",
314
+ label: "Access key ID",
315
+ maxLength: 128,
316
+ })}
317
+ {input({
318
+ value: secret,
319
+ onChangeText: setSecret,
320
+ placeholder: keepsKey ? "Leave empty to keep the current secret" : "Secret access key",
321
+ label: "Secret access key",
322
+ maxLength: 1024,
323
+ secure: true,
324
+ })}
325
+ {input({
326
+ value: sessionToken,
327
+ onChangeText: setSessionToken,
328
+ placeholder: keepsKey && current?.sessionToken ? "Leave empty to keep the current session token" : "Session token (optional, for temporary credentials)",
329
+ label: "Session token",
330
+ maxLength: 4096,
331
+ secure: true,
332
+ })}
333
+ <Text style={text.small}>Kept only in the account's folder on this host, readable only by you.</Text>
334
+ </>
335
+ )}
336
+ </Field>
337
+ <Field theme={theme} title="Models (optional)">
338
+ <Text style={text.small}>
339
+ Bedrock model or inference-profile IDs, as enabled in your AWS account. Empty uses Claude Code's own Bedrock defaults.
340
+ </Text>
341
+ {MODEL_FIELDS.map(({ field, title, placeholder }) => (
342
+ <View key={field} style={{ gap: 4 }}>
343
+ <Text style={text.small}>{title}</Text>
344
+ {input({ value: models[field], onChangeText: (value) => setModels((all) => ({ ...all, [field]: value })), placeholder, label: title, maxLength: 200 })}
345
+ </View>
346
+ ))}
347
+ </Field>
348
+ {editing ? (
349
+ <Field theme={theme} title="Prices (optional, USD per 1M tokens)">
350
+ <Text style={text.small}>
351
+ Per model, as Claude Code names it in its session files, for the cost estimate on the card. Without prices the card shows tokens only.
352
+ Cache reads or writes without a price count at the input price.
353
+ </Text>
354
+ {rows.map((row, index) => (
355
+ <View key={index} style={{ flexDirection: "row", alignItems: "center", gap: 6 }}>
356
+ {cell(index, "model", "Model", 2)}
357
+ {cell(index, "input", "Input", 1)}
358
+ {cell(index, "cachedInput", "Cache read", 1)}
359
+ {cell(index, "cacheWrite", "Cache write", 1)}
360
+ {cell(index, "output", "Output", 1)}
361
+ <IconButton
362
+ theme={theme}
363
+ icon="Trash2"
364
+ label="Remove price"
365
+ tooltip="Remove this model's prices"
366
+ onPress={() => setRows((all) => all.filter((_, at) => at !== index))}
367
+ />
368
+ </View>
369
+ ))}
370
+ <View style={{ flexDirection: "row" }}>
371
+ <Button
372
+ theme={theme}
373
+ size="small"
374
+ icon="Plus"
375
+ label="Add model"
376
+ tooltip="Add prices for another model"
377
+ tooltipAlign="start"
378
+ onPress={() =>
379
+ setRows((all) => [
380
+ ...all,
381
+ { model: used.find((model) => !all.some((row) => row.model === model)) ?? "", input: "", cachedInput: "", cacheWrite: "", output: "" },
382
+ ])
383
+ }
384
+ />
385
+ </View>
386
+ </Field>
387
+ ) : null}
388
+ <Text style={text.small}>
389
+ {paidFallback
390
+ ? "Billed per token by AWS. With paid API accounts turned on, ZeroSub moves Claude agents onto it by itself only when every Claude subscription account is out, and back once one has room; you can always pick it for an agent or make it the default."
391
+ : "Billed per token by AWS, so ZeroSub never moves agents onto it by itself: it's used only as the default or when you pick it for an agent."}{" "}
392
+ The credentials are checked with the host's aws command when it has one.
393
+ </Text>
394
+ {error ? <Text style={text.danger}>{error}</Text> : null}
395
+ <View style={{ flexDirection: "row", flexWrap: "wrap", gap: 8, justifyContent: "flex-end" }}>
396
+ <Button theme={theme} label="Cancel" tooltip={editing ? "Keep the current settings" : "Close without adding an account"} tooltipAlign="end" onPress={onCancel} />
397
+ <Button
398
+ theme={theme}
399
+ tone="primary"
400
+ label={editing ? "Save" : "Add account"}
401
+ tooltip={editing ? "Save these settings" : "Check the credentials and add this account"}
402
+ tooltipAlign="end"
403
+ busy={saving}
404
+ disabled={!ready}
405
+ onPress={() => void submit()}
406
+ />
407
+ </View>
408
+ </View>
409
+ );
410
+ }
411
+
412
+ /** Edits an AWS Bedrock account from its card: region, credentials, models and prices. */
413
+ export function BedrockAccountModal({
414
+ theme,
415
+ store,
416
+ account,
417
+ paidFallback,
418
+ onClose,
419
+ }: {
420
+ theme: Theme;
421
+ store: ZeroSubStore;
422
+ account: AccountView;
423
+ paidFallback: boolean;
424
+ onClose(): void;
425
+ }) {
426
+ const toast = useToast();
427
+ return (
428
+ <Modal title={`Bedrock settings for ${account.label}`} open onOpenChange={(open) => (open ? undefined : onClose())}>
429
+ <Modal.Content>
430
+ <BedrockAccountForm
431
+ theme={theme}
432
+ store={store}
433
+ account={account}
434
+ paidFallback={paidFallback}
435
+ onCancel={onClose}
436
+ onDone={(_, warning) => {
437
+ if (warning) toast.show(warning, { variant: "warning", durationMs: 8_000 });
438
+ else toast.show(`${account.label} updated. Agents started from now on use it.`, { variant: "success" });
439
+ onClose();
440
+ }}
441
+ />
442
+ </Modal.Content>
443
+ </Modal>
444
+ );
445
+ }
446
+
447
+ function Field({ theme, title, children }: { theme: Theme; title: string; children: ReactNode }) {
448
+ const text = useText(theme);
449
+ return (
450
+ <View style={{ gap: 6 }}>
451
+ <Text style={text.strong}>{title}</Text>
452
+ {children}
453
+ </View>
454
+ );
455
+ }
@@ -134,7 +134,7 @@ export function PreferencesScreen({ theme, host, onOpenAccounts }: PluginSurface
134
134
  />
135
135
  <SettingsSwitch
136
136
  label="Use paid API accounts when every subscription is out"
137
- hint="Off unless you turn it on. When every ChatGPT subscription account is at its limit, signed out or disabled, agents may move to an Azure OpenAI account, billed per token (after a banked reset, if those are used automatically). Off, it's used only as the default or when you pick it for an agent."
137
+ hint="Off unless you turn it on. When every subscription account of a provider is at its limit, signed out or disabled, agents may move to an Azure OpenAI account (ChatGPT) or an AWS Bedrock account (Claude), billed per token (after a banked reset, if those are used automatically), and Claude agents move back once a subscription has room. Off, those are used only as the default or when you pick one for an agent."
138
138
  value={settings.values.paidApiFallback}
139
139
  disabled={settings.saving}
140
140
  onValueChange={(paidApiFallback) => save({ paidApiFallback })}
@@ -21,6 +21,8 @@ function cause(row: SwitchRow): string | null {
21
21
  return `${row.to} is enabled again.`;
22
22
  case "default":
23
23
  return "The default account changed.";
24
+ case "room":
25
+ return `A ${FAMILY_LABEL[row.family]} subscription account has room again, so this agent leaves ${from}, a paid API.`;
24
26
  case "pacing":
25
27
  return `${from} is close to its 5-hour limit.`;
26
28
  default:
@@ -82,10 +84,10 @@ export function describeRow(row: SwitchRow): string {
82
84
  return `${lead}Moves to ${row.to} when its session next starts.${row.detail ? ` ${row.detail}` : ""}`;
83
85
  default: {
84
86
  const hidesFrom =
85
- row.reason === "limit" || row.reason === "signed_out" || row.reason === "disabled" || row.reason === "pacing";
87
+ row.reason === "limit" || row.reason === "signed_out" || row.reason === "disabled" || row.reason === "room" || row.reason === "pacing";
86
88
  const from = row.from && !hidesFrom ? `from ${row.from} ` : "";
87
89
  const place = row.sameConversation ? " in this conversation" : "";
88
- return `${lead}Switched ${from}to ${row.to}${place}${row.continued ? " and carried on" : ""}.`;
90
+ return `${lead}Switched ${from}to ${row.to}${place}${row.continued ? " and carried on" : ""}.${row.detail ? ` ${row.detail}` : ""}`;
89
91
  }
90
92
  }
91
93
  }
package/index.server.ts CHANGED
@@ -9,6 +9,7 @@ import { preferences } from "./shared/preferences";
9
9
  import {
10
10
  addApiAccount,
11
11
  addAzureAccount,
12
+ addBedrockAccount,
12
13
  cancelLogin,
13
14
  clearAccountLimit,
14
15
  getState,
@@ -29,6 +30,8 @@ import {
29
30
  submitLoginCode,
30
31
  updateApiAccount,
31
32
  updateAzureAccount,
33
+ updateBedrockAccount,
34
+ detectBedrockRegion,
32
35
  } from "./shared/rpc";
33
36
 
34
37
  export default function contribute(server: PluginServerContext) {
@@ -66,6 +69,17 @@ export default function contribute(server: PluginServerContext) {
66
69
  }
67
70
  });
68
71
 
72
+ // A new Claude agent's mode is carried to its first session, where Paseo can't say it yet. Creating
73
+ // the agent never fails for this: on any error the request goes on unchanged.
74
+ server.before("agent.create", async ({ request }, context) => {
75
+ try {
76
+ return await service.onAgentCreate(request, context);
77
+ } catch (error) {
78
+ console.error("[ZeroSub] could not note a new agent's mode", describe(error));
79
+ return undefined;
80
+ }
81
+ });
82
+
69
83
  server.on("agent.turn_started", (event, context) => {
70
84
  void service.onTurnStarted(event.agent, context).catch(() => undefined);
71
85
  });
@@ -123,6 +137,9 @@ export default function contribute(server: PluginServerContext) {
123
137
  });
124
138
  server.handle(addAzureAccount, (input) => service.addAzureAccount(input));
125
139
  server.handle(updateAzureAccount, async ({ accountId, ...input }) => ({ ok: true as const, ...(await service.updateAzureAccount(accountId, input)) }));
140
+ server.handle(addBedrockAccount, (input) => service.addBedrockAccount(input));
141
+ server.handle(updateBedrockAccount, async ({ accountId, ...input }) => ({ ok: true as const, ...(await service.updateBedrockAccount(accountId, input)) }));
142
+ server.handle(detectBedrockRegion, () => service.detectBedrockRegion());
126
143
  server.handle(setAccountProxy, async ({ accountId, proxy }) => ({ ok: true as const, proxy: await service.setProxy(accountId, proxy) }));
127
144
  server.handle(setClaudeHomesDir, async ({ dir }) => ({ ok: true as const, ...(await service.setClaudeHomesDir(dir)) }));
128
145
  server.handle(importAccount, async ({ path }) => ({ accountId: await service.importAccount(path) }));
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kapybara/zerosub",
3
- "version": "1.18.2",
3
+ "version": "1.19.0",
4
4
  "description": "ZeroSub: use several Claude and ChatGPT (Codex) subscriptions side by side in Paseo. Add accounts in-app, pick one per agent, and switch automatically when an account hits its limit.",
5
5
  "keywords": [
6
6
  "paseo",
@@ -6,20 +6,27 @@ import { Mutex, readJson, writeJsonAtomic } from "./json-file";
6
6
  import { dataDir } from "./paths";
7
7
 
8
8
  /**
9
- * Monthly token totals of the paid API accounts (Azure OpenAI under ChatGPT), counted per turn from
10
- * the CLI's own session files, in `$PASEO_HOME/zerosub/api-usage.json`. No keys, no text.
9
+ * Monthly token totals of the paid API accounts (Azure OpenAI under ChatGPT, AWS Bedrock under
10
+ * Claude), counted per turn from the CLIs' own session files, in `$PASEO_HOME/zerosub/api-usage.json`.
11
+ * No keys, no text.
11
12
  */
12
13
 
13
14
  /** What one Codex thread had used by the last time its tokens were counted (see `countThread`). */
14
15
  const ThreadMarkSchema = TokenCountSchema.extend({ at: z.string() });
16
+ /** The messages of one Claude Code session already counted (see `countMessages`). */
17
+ const MessageMarkSchema = z.object({ ids: z.array(z.string()).default([]), at: z.string() });
15
18
 
16
19
  export interface ApiUsageFile {
17
20
  accounts: Record<string, ApiMonth>;
18
21
  threads: Record<string, TokenCount & { at: string }>;
22
+ /** By Claude Code session id. Missing in files written before Bedrock accounts. */
23
+ messages?: Record<string, { ids: string[]; at: string }>;
19
24
  }
20
25
 
21
- /** A thread not counted for this long is forgotten (its next turn counts from what it had then). */
26
+ /** A thread or session not counted for this long is forgotten (a Codex thread's next turn counts from what it had then). */
22
27
  const MARK_KEEP_MS = 62 * 24 * 60 * 60_000;
28
+ /** Message ids kept per Claude Code session: far more than one turn writes. */
29
+ const MESSAGE_IDS_KEPT = 2_000;
23
30
 
24
31
  export const EMPTY_COUNT: TokenCount = { input: 0, cachedInput: 0, cacheWrite: 0, output: 0 };
25
32
 
@@ -89,7 +96,7 @@ export class ApiUsageStore {
89
96
  async read(): Promise<ApiUsageFile> {
90
97
  if (this.cached) return this.cached;
91
98
  const raw = (await readJson(this.path).catch(() => undefined)) as Partial<ApiUsageFile> | undefined;
92
- const file: ApiUsageFile = { accounts: {}, threads: {} };
99
+ const file: ApiUsageFile = { accounts: {}, threads: {}, messages: {} };
93
100
  for (const [id, value] of Object.entries(raw?.accounts ?? {})) {
94
101
  const parsed = ApiMonthSchema.safeParse(value);
95
102
  if (parsed.success) file.accounts[id] = parsed.data;
@@ -98,6 +105,10 @@ export class ApiUsageStore {
98
105
  const parsed = ThreadMarkSchema.safeParse(value);
99
106
  if (parsed.success) file.threads[id] = parsed.data;
100
107
  }
108
+ for (const [id, value] of Object.entries(raw?.messages ?? {})) {
109
+ const parsed = MessageMarkSchema.safeParse(value);
110
+ if (parsed.success) file.messages![id] = parsed.data;
111
+ }
101
112
  this.cached ??= file;
102
113
  return this.cached;
103
114
  }
@@ -105,9 +116,11 @@ export class ApiUsageStore {
105
116
  update(change: (draft: ApiUsageFile) => void): Promise<ApiUsageFile> {
106
117
  return this.mutex.run(async () => {
107
118
  const draft = structuredClone(await this.read());
119
+ draft.messages ??= {};
108
120
  change(draft);
109
121
  const now = Date.now();
110
122
  for (const [id, mark] of Object.entries(draft.threads)) if (now - Date.parse(mark.at) > MARK_KEEP_MS) delete draft.threads[id];
123
+ for (const [id, mark] of Object.entries(draft.messages)) if (now - Date.parse(mark.at) > MARK_KEEP_MS) delete draft.messages[id];
111
124
  await mkdir(dirname(this.path), { recursive: true, mode: 0o700 });
112
125
  await writeJsonAtomic(this.path, draft, { durable: false });
113
126
  this.cached = draft;
@@ -129,6 +142,36 @@ export class ApiUsageStore {
129
142
  return delta;
130
143
  }
131
144
 
145
+ /**
146
+ * Counts a Claude Code session's messages against `accountId`'s month, each once. A Claude
147
+ * conversation can move between accounts, so only the messages of turns run on the account are
148
+ * passed in, and one counted before (Claude Code can write a message's usage on more than one line,
149
+ * and a turn's file is read again at the next) is skipped. Returns how many were new.
150
+ */
151
+ async countMessages(
152
+ accountId: string,
153
+ sessionId: string,
154
+ messages: ReadonlyArray<{ id: string; model: string; count: TokenCount }>,
155
+ now = Date.now(),
156
+ ): Promise<number> {
157
+ let added = 0;
158
+ await this.update((draft) => {
159
+ const mark = draft.messages![sessionId] ?? { ids: [], at: new Date(now).toISOString() };
160
+ const seen = new Set(mark.ids);
161
+ for (const message of messages) {
162
+ if (seen.has(message.id)) continue;
163
+ seen.add(message.id);
164
+ mark.ids.push(message.id);
165
+ draft.accounts[accountId] = addApiTokens(draft.accounts[accountId], message.model, message.count, now);
166
+ added += 1;
167
+ }
168
+ mark.ids = mark.ids.slice(-MESSAGE_IDS_KEPT);
169
+ mark.at = new Date(now).toISOString();
170
+ draft.messages![sessionId] = mark;
171
+ });
172
+ return added;
173
+ }
174
+
132
175
  async noteUncounted(accountId: string, now = Date.now()): Promise<void> {
133
176
  await this.update((draft) => {
134
177
  draft.accounts[accountId] = addUncounted(draft.accounts[accountId], now);