@kapybara/zerosub 1.5.0 → 1.18.2
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/README.md +222 -27
- package/client/accounts-surface.tsx +344 -110
- package/client/add-account.tsx +335 -23
- package/client/api-account.tsx +250 -0
- package/client/azure-account.tsx +311 -0
- package/client/commands.ts +44 -8
- package/client/composer-item.tsx +203 -0
- package/client/fork-confirm.tsx +71 -0
- package/client/fork-settings.tsx +148 -0
- package/client/pace.tsx +196 -0
- package/client/pi-accounts.tsx +571 -0
- package/client/pills.ts +63 -25
- package/client/reset-confirm.tsx +12 -3
- package/client/settings-screen.tsx +48 -9
- package/client/store.ts +148 -19
- package/client/switch-row.tsx +28 -8
- package/client/ui.tsx +11 -0
- package/index.client.tsx +4 -1
- package/index.server.ts +53 -10
- package/package.json +5 -2
- package/server/account-identity.ts +11 -0
- package/server/adapter.ts +115 -8
- package/server/api-usage.ts +144 -0
- package/server/azure.ts +346 -0
- package/server/binaries.ts +41 -3
- package/server/claude.ts +276 -21
- package/server/codex-same-conversation.ts +71 -0
- package/server/codex.ts +35 -7
- package/server/continuations.ts +128 -18
- package/server/cursor.ts +222 -0
- package/server/families.ts +105 -8
- package/server/grok.ts +225 -0
- package/server/handoff.ts +221 -30
- package/server/homes.ts +1263 -35
- package/server/json-file.ts +39 -8
- package/server/launchers.ts +319 -0
- package/server/limits.ts +80 -3
- package/server/main-proxy.ts +238 -0
- package/server/modes.ts +20 -4
- package/server/paths.ts +81 -1
- package/server/pi.ts +528 -0
- package/server/placement.ts +133 -0
- package/server/process.ts +18 -1
- package/server/processes.ts +66 -0
- package/server/provider-env.ts +28 -0
- package/server/proxy.ts +282 -0
- package/server/reopen.ts +50 -8
- package/server/routing.ts +337 -30
- package/server/service.ts +4320 -803
- package/server/state.ts +305 -24
- package/server/usage.ts +2 -0
- package/shared/format.ts +170 -2
- package/shared/model.ts +339 -2
- package/shared/preferences.ts +22 -1
- package/shared/rpc.ts +130 -8
- package/shared/timeline.ts +11 -0
package/server/state.ts
CHANGED
|
@@ -1,7 +1,8 @@
|
|
|
1
|
-
import { copyFile } from "node:fs/promises";
|
|
1
|
+
import { chmod, copyFile, readdir, rm } from "node:fs/promises";
|
|
2
|
+
import { dirname, join } from "node:path";
|
|
2
3
|
import { z } from "zod";
|
|
3
|
-
import { AccountKindSchema, FamilySchema, type Family } from "../shared/model";
|
|
4
|
-
import { Mutex, readJson, writeJsonAtomic } from "./json-file";
|
|
4
|
+
import { AccountKindSchema, ApiProviderSchema, AuthKindSchema, FamilySchema, type Family } from "../shared/model";
|
|
5
|
+
import { Mutex, readJson, readText, writeJsonAtomic } from "./json-file";
|
|
5
6
|
import { statePath } from "./paths";
|
|
6
7
|
|
|
7
8
|
export const StoredAccountSchema = z.object({
|
|
@@ -11,6 +12,13 @@ export const StoredAccountSchema = z.object({
|
|
|
11
12
|
/** The label was generated from the email and may be replaced when the identity is learned. */
|
|
12
13
|
autoLabel: z.boolean().default(true),
|
|
13
14
|
kind: AccountKindSchema,
|
|
15
|
+
/** How it signs in. `api` accounts (added Pi accounts) are only used when chosen, never by automatic routing. */
|
|
16
|
+
auth: AuthKindSchema.default("subscription"),
|
|
17
|
+
/**
|
|
18
|
+
* The paid API an `api` account stands in for a subscription on (an Azure OpenAI account's
|
|
19
|
+
* `azure`), set when it's added. Missing for every other account, API-key ones included.
|
|
20
|
+
*/
|
|
21
|
+
provider: ApiProviderSchema.optional(),
|
|
14
22
|
/** Credential home (`CLAUDE_CONFIG_DIR` / `CODEX_HOME`). `null` for the CLI's own login. */
|
|
15
23
|
home: z.string().nullable(),
|
|
16
24
|
email: z.string().nullable().default(null),
|
|
@@ -31,6 +39,11 @@ export const StoredAccountSchema = z.object({
|
|
|
31
39
|
* saved by earlier versions, which count as a turn's.
|
|
32
40
|
*/
|
|
33
41
|
limitSource: z.enum(["turn", "reading"]).optional(),
|
|
42
|
+
/**
|
|
43
|
+
* Limits of one model's own window ("Weekly · Fable"), keyed by the lowercase scope name. They keep
|
|
44
|
+
* agents on that model off the account; the account itself stays usable for every other model.
|
|
45
|
+
*/
|
|
46
|
+
modelLimits: z.record(z.string(), z.object({ until: z.string(), at: z.string(), source: z.enum(["turn", "reading"]) })).default({}),
|
|
34
47
|
createdAt: z.string(),
|
|
35
48
|
});
|
|
36
49
|
export type StoredAccount = z.infer<typeof StoredAccountSchema>;
|
|
@@ -55,7 +68,73 @@ export const LiveSessionSchema = z.object({
|
|
|
55
68
|
});
|
|
56
69
|
export type LiveSession = z.infer<typeof LiveSessionSchema>;
|
|
57
70
|
|
|
58
|
-
const TimelineMarkSchema = z.object({ epoch: z.string(), seq: z.number().int().nonnegative() });
|
|
71
|
+
export const TimelineMarkSchema = z.object({ epoch: z.string(), seq: z.number().int().nonnegative() });
|
|
72
|
+
export type TimelineMark = z.infer<typeof TimelineMarkSchema>;
|
|
73
|
+
|
|
74
|
+
/** An OpenCode fork of one source agent: where the work continues and how much of the source it has. */
|
|
75
|
+
export const OpenCodeForkSchema = z.object({
|
|
76
|
+
/** The OpenCode agent carrying the source's work. */
|
|
77
|
+
forkAgentId: z.string(),
|
|
78
|
+
/** How much of the source the fork has already received. */
|
|
79
|
+
seen: TimelineMarkSchema.optional(),
|
|
80
|
+
/**
|
|
81
|
+
* Written before a create or a send. An uncertain dispatch must never start a second fork or send
|
|
82
|
+
* a second copy: retry it exactly, or reconcile its receipt. Only IDs, marks, digests and the
|
|
83
|
+
* create configuration are stored; no transcript text or credentials.
|
|
84
|
+
*/
|
|
85
|
+
pending: z
|
|
86
|
+
.object({
|
|
87
|
+
stage: z.enum(["creating", "sending"]),
|
|
88
|
+
targetId: z.string(),
|
|
89
|
+
messageId: z.string(),
|
|
90
|
+
seen: TimelineMarkSchema,
|
|
91
|
+
/** The exact create configuration (`provider` is Paseo's `provider/model` string). */
|
|
92
|
+
config: z
|
|
93
|
+
.object({
|
|
94
|
+
provider: z.string(),
|
|
95
|
+
modeId: z.string(),
|
|
96
|
+
thinkingOptionId: z.string().optional(),
|
|
97
|
+
/**
|
|
98
|
+
* Original request identity and location, checked against the created target before its
|
|
99
|
+
* handoff is sent. A create that never landed is built again from current settings.
|
|
100
|
+
*/
|
|
101
|
+
workspaceId: z.string().nullable().optional(),
|
|
102
|
+
cwd: z.string().nullable().optional(),
|
|
103
|
+
parentId: z.string().nullable().optional(),
|
|
104
|
+
title: z.string().optional(),
|
|
105
|
+
/**
|
|
106
|
+
* The exact generic reason the first prompt gave for this fork, frozen with it: a retry
|
|
107
|
+
* must rebuild the same prompt, whatever trigger the retry itself came from. Missing on
|
|
108
|
+
* reservations saved by earlier versions, which then stay uncertain rather than guess.
|
|
109
|
+
*/
|
|
110
|
+
why: z.string().optional(),
|
|
111
|
+
})
|
|
112
|
+
.optional(),
|
|
113
|
+
/** SHA-256 of the exact sent text, so a receipt survives a provider reload. */
|
|
114
|
+
sentDigest: z.string().optional(),
|
|
115
|
+
/**
|
|
116
|
+
* The create was seen to fail. Paseo keeps a failed request under its idempotency key, so a
|
|
117
|
+
* retry with another request needs new IDs. Without it, the outcome is unknown and only the
|
|
118
|
+
* reserved request may be sent again.
|
|
119
|
+
*/
|
|
120
|
+
createFailed: z.boolean().optional(),
|
|
121
|
+
/** Paseo answered the create's key with outcome unknown, which it keeps for good: that key can never land. */
|
|
122
|
+
createOutcomeUnknown: z.boolean().optional(),
|
|
123
|
+
})
|
|
124
|
+
.optional(),
|
|
125
|
+
});
|
|
126
|
+
export type OpenCodeFork = z.infer<typeof OpenCodeForkSchema>;
|
|
127
|
+
|
|
128
|
+
/**
|
|
129
|
+
* Set when recovery lost a source's OpenCode fork record (key: the source agent ID), or every
|
|
130
|
+
* source's (key `*`, when the registry couldn't be read at all). Until that source has a record
|
|
131
|
+
* again, nothing is sent or forked for it automatically; a manual fork asks once (`told`) first.
|
|
132
|
+
* The next OpenCode fork settles `*`: each source with an OpenCode continuation gets its own hold,
|
|
133
|
+
* and `*` goes.
|
|
134
|
+
*/
|
|
135
|
+
export const OpenCodeHoldSchema = z.object({ at: z.string(), told: z.boolean().optional() });
|
|
136
|
+
export const ALL_SOURCES = "*";
|
|
137
|
+
|
|
59
138
|
const ContinuationMemberSchema = z.object({
|
|
60
139
|
accountId: z.string(),
|
|
61
140
|
identity: z.string().nullable(),
|
|
@@ -77,25 +156,89 @@ export const ContinuationChainSchema = z.object({
|
|
|
77
156
|
seen: z.record(z.string(), TimelineMarkSchema),
|
|
78
157
|
stage: z.enum(["creating", "sending"]).default("sending"),
|
|
79
158
|
replaceHistory: z.array(z.string()).optional(),
|
|
159
|
+
/** The agent a new tab is created under. A retried creation must repeat its first request. */
|
|
160
|
+
parent: z.string().optional(),
|
|
80
161
|
}).optional(),
|
|
81
162
|
});
|
|
82
163
|
export type ContinuationChain = z.infer<typeof ContinuationChainSchema>;
|
|
83
164
|
|
|
165
|
+
/** A one-time choice: the next new agent of this family starts on this account (until it expires). */
|
|
166
|
+
export const NextAgentPickSchema = z.object({ accountId: z.string(), until: z.string() });
|
|
167
|
+
export type NextAgentPick = z.infer<typeof NextAgentPickSchema>;
|
|
168
|
+
|
|
169
|
+
/** A home to sign out and delete once nothing runs on it any more. */
|
|
170
|
+
export const CleanupSchema = z.object({
|
|
171
|
+
family: FamilySchema,
|
|
172
|
+
/** The account it was (or was going to be) the home of; its agents' sessions name this ID. */
|
|
173
|
+
accountId: z.string(),
|
|
174
|
+
/** `removed`: the user removed the account. `unfinished`: a new account whose sign-in hasn't been saved yet. */
|
|
175
|
+
why: z.enum(["removed", "unfinished"]),
|
|
176
|
+
at: z.string(),
|
|
177
|
+
});
|
|
178
|
+
export type Cleanup = z.infer<typeof CleanupSchema>;
|
|
179
|
+
|
|
180
|
+
/**
|
|
181
|
+
* Where a family's added accounts' homes are kept: `dir` (null for the default, beside their
|
|
182
|
+
* scripts), and folders picked before whose accounts still move to it.
|
|
183
|
+
*/
|
|
184
|
+
export const HomesSchema = z.object({
|
|
185
|
+
dir: z.string().nullable().default(null),
|
|
186
|
+
from: z.array(z.string()).default([]),
|
|
187
|
+
});
|
|
188
|
+
export type Homes = z.infer<typeof HomesSchema>;
|
|
189
|
+
|
|
190
|
+
/**
|
|
191
|
+
* A home being moved, written before anything moves, so a move cut short is finished from here.
|
|
192
|
+
* `family`: whose home it is (missing in records of earlier versions; the account says whose).
|
|
193
|
+
*/
|
|
194
|
+
export const MoveSchema = z.object({ from: z.string(), to: z.string(), at: z.string(), family: FamilySchema.optional() });
|
|
195
|
+
export type Move = z.infer<typeof MoveSchema>;
|
|
196
|
+
|
|
84
197
|
export const StoredStateSchema = z.object({
|
|
85
198
|
version: z.literal(1).default(1),
|
|
86
199
|
accounts: z.array(StoredAccountSchema).default([]),
|
|
87
200
|
defaults: z
|
|
88
|
-
.object({
|
|
89
|
-
|
|
201
|
+
.object({
|
|
202
|
+
claude: z.string().nullable().default(null),
|
|
203
|
+
codex: z.string().nullable().default(null),
|
|
204
|
+
pi: z.string().nullable().default(null),
|
|
205
|
+
// Families added later than Pi may be absent (none chosen), so registries and fixtures written before them load as they are.
|
|
206
|
+
grok: z.string().nullable().optional(),
|
|
207
|
+
cursor: z.string().nullable().optional(),
|
|
208
|
+
})
|
|
209
|
+
.default({ claude: null, codex: null, pi: null }),
|
|
90
210
|
/** Per-agent overrides of the default account. */
|
|
91
211
|
bindings: z.record(z.string(), BindingSchema).default({}),
|
|
92
212
|
/** Which account each agent's live provider session was opened with. */
|
|
93
213
|
sessions: z.record(z.string(), LiveSessionSchema).default({}),
|
|
94
214
|
continuations: z.record(z.string(), ContinuationChainSchema).default({}),
|
|
215
|
+
/** Per-source OpenCode fork records. OpenCode is a harness, not an account provider. */
|
|
216
|
+
opencodeForks: z.record(z.string(), OpenCodeForkSchema).default({}),
|
|
217
|
+
opencodeHolds: z.record(z.string(), OpenCodeHoldSchema).default({}),
|
|
218
|
+
/**
|
|
219
|
+
* Homes to clean up, by path. Only these are ever signed out or deleted: a home missing from
|
|
220
|
+
* `accounts` may just be missing from a damaged or hand-edited registry.
|
|
221
|
+
*/
|
|
222
|
+
cleanup: z.record(z.string(), CleanupSchema).default({}),
|
|
223
|
+
nextAgent: z
|
|
224
|
+
.object({
|
|
225
|
+
claude: NextAgentPickSchema.nullable().default(null),
|
|
226
|
+
codex: NextAgentPickSchema.nullable().default(null),
|
|
227
|
+
pi: NextAgentPickSchema.nullable().default(null),
|
|
228
|
+
grok: NextAgentPickSchema.nullable().optional(),
|
|
229
|
+
cursor: NextAgentPickSchema.nullable().optional(),
|
|
230
|
+
})
|
|
231
|
+
.default({ claude: null, codex: null, pi: null }),
|
|
232
|
+
/** Where added Pi accounts' homes are kept: `dir` (null: `~/.pi-config`), and folders picked before whose accounts still move to it. */
|
|
233
|
+
piHomes: HomesSchema.default({ dir: null, from: [] }),
|
|
234
|
+
/** Where added Claude accounts' homes are kept, as for Pi's (`dir` null: `~/.claude-config`). */
|
|
235
|
+
claudeHomes: HomesSchema.default({ dir: null, from: [] }),
|
|
236
|
+
/** Homes being moved, by account (see `Service.placeHomes`). */
|
|
237
|
+
moves: z.record(z.string(), MoveSchema).default({}),
|
|
95
238
|
});
|
|
96
239
|
export type StoredState = z.infer<typeof StoredStateSchema>;
|
|
97
240
|
|
|
98
|
-
export const MAIN_ACCOUNT_ID: Record<Family, string> = { claude: "claude-main", codex: "codex-main" };
|
|
241
|
+
export const MAIN_ACCOUNT_ID: Record<Family, string> = { claude: "claude-main", codex: "codex-main", pi: "pi-main", grok: "grok-main", cursor: "cursor-main" };
|
|
99
242
|
|
|
100
243
|
export function emptyState(): StoredState {
|
|
101
244
|
return StoredStateSchema.parse({});
|
|
@@ -127,7 +270,7 @@ export function salvageState(raw: unknown): { state: StoredState; dropped: boole
|
|
|
127
270
|
}
|
|
128
271
|
return result;
|
|
129
272
|
};
|
|
130
|
-
const defaults = keep(StoredStateSchema.shape.defaults, source.defaults) ?? { claude: null, codex: null };
|
|
273
|
+
const defaults = keep(StoredStateSchema.shape.defaults, source.defaults) ?? { claude: null, codex: null, pi: null };
|
|
131
274
|
return {
|
|
132
275
|
state: {
|
|
133
276
|
version: 1,
|
|
@@ -136,17 +279,63 @@ export function salvageState(raw: unknown): { state: StoredState; dropped: boole
|
|
|
136
279
|
bindings: records(BindingSchema, source.bindings),
|
|
137
280
|
sessions: records(LiveSessionSchema, source.sessions),
|
|
138
281
|
continuations: records(ContinuationChainSchema, source.continuations),
|
|
282
|
+
opencodeForks: records(OpenCodeForkSchema, source.opencodeForks),
|
|
283
|
+
opencodeHolds: records(OpenCodeHoldSchema, source.opencodeHolds),
|
|
284
|
+
cleanup: records(CleanupSchema, source.cleanup),
|
|
285
|
+
nextAgent: { claude: null, codex: null, pi: null },
|
|
286
|
+
piHomes: keep(HomesSchema, source.piHomes ?? {}) ?? { dir: null, from: [] },
|
|
287
|
+
claudeHomes: keep(HomesSchema, source.claudeHomes ?? {}) ?? { dir: null, from: [] },
|
|
288
|
+
moves: records(MoveSchema, source.moves),
|
|
139
289
|
},
|
|
140
290
|
dropped: true,
|
|
141
291
|
};
|
|
142
292
|
}
|
|
143
293
|
|
|
144
|
-
/**
|
|
294
|
+
/**
|
|
295
|
+
* Which snapshots of the registry are kept: the last few writes, which a damaged registry is
|
|
296
|
+
* restored from, then the last one of each recent hour and day, to undo a mistake noticed later.
|
|
297
|
+
* Buckets are prefixes of the snapshot's name (`state-2026-10-28T09-15-02-123Z.json`).
|
|
298
|
+
*/
|
|
299
|
+
const SNAPSHOT_TIERS = [
|
|
300
|
+
{ count: 5, bucket: (name: string) => name },
|
|
301
|
+
{ count: 12, bucket: (name: string) => name.slice(0, "state-2026-10-28T09".length) },
|
|
302
|
+
{ count: 7, bucket: (name: string) => name.slice(0, "state-2026-10-28".length) },
|
|
303
|
+
];
|
|
304
|
+
const SNAPSHOT_NAME = /^state-\d{4}-\d{2}-\d{2}T\d{2}-\d{2}-\d{2}-\d{3}Z\.json$/;
|
|
305
|
+
|
|
306
|
+
function snapshotName(at: Date): string {
|
|
307
|
+
return `state-${at.toISOString().replace(/[:.]/g, "-")}.json`;
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
/** The snapshots rotation keeps, out of `names`; at most the sum of the tiers' counts. */
|
|
311
|
+
export function snapshotsToKeep(names: readonly string[]): Set<string> {
|
|
312
|
+
const newestFirst = [...names].sort().reverse();
|
|
313
|
+
const keep = new Set<string>();
|
|
314
|
+
for (const { count, bucket } of SNAPSHOT_TIERS) {
|
|
315
|
+
const buckets = new Set<string>();
|
|
316
|
+
for (const name of newestFirst) {
|
|
317
|
+
const key = bucket(name);
|
|
318
|
+
if (buckets.has(key)) continue;
|
|
319
|
+
if (buckets.size === count) break;
|
|
320
|
+
buckets.add(key);
|
|
321
|
+
keep.add(name);
|
|
322
|
+
}
|
|
323
|
+
}
|
|
324
|
+
return keep;
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
/**
|
|
328
|
+
* The registry: small, read on every session open, written atomically. Every write also leaves a
|
|
329
|
+
* snapshot in `backups/` beside it, which a damaged or missing registry is restored from.
|
|
330
|
+
*/
|
|
145
331
|
export class StateStore {
|
|
146
332
|
private cached: StoredState | null = null;
|
|
147
333
|
private readonly mutex = new Mutex();
|
|
334
|
+
private readonly backups: string;
|
|
148
335
|
|
|
149
|
-
constructor(private readonly path: string = statePath()) {
|
|
336
|
+
constructor(private readonly path: string = statePath()) {
|
|
337
|
+
this.backups = join(dirname(path), "backups");
|
|
338
|
+
}
|
|
150
339
|
|
|
151
340
|
async read(): Promise<StoredState> {
|
|
152
341
|
if (this.cached) return this.cached;
|
|
@@ -163,35 +352,127 @@ export class StateStore {
|
|
|
163
352
|
const draft = structuredClone(current);
|
|
164
353
|
change(draft);
|
|
165
354
|
const next = StoredStateSchema.parse(draft);
|
|
166
|
-
await
|
|
355
|
+
await this.write(next);
|
|
167
356
|
this.cached = next;
|
|
168
357
|
return next;
|
|
169
358
|
});
|
|
170
359
|
}
|
|
171
360
|
|
|
172
|
-
|
|
361
|
+
private async write(state: StoredState): Promise<void> {
|
|
362
|
+
await writeJsonAtomic(this.path, state);
|
|
363
|
+
// The registry itself is saved; a snapshot that can't be written only costs a backup.
|
|
364
|
+
await this.snapshot(state).catch((error: unknown) => console.error("[ZeroSub] could not back up the state file", message(error)));
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
private async snapshot(state: StoredState): Promise<void> {
|
|
368
|
+
// Not synced: one lost to a crash doesn't parse and is skipped, and the registry itself is.
|
|
369
|
+
await writeJsonAtomic(join(this.backups, snapshotName(new Date())), state, { durable: false });
|
|
370
|
+
const names = await this.snapshotNames();
|
|
371
|
+
const keep = snapshotsToKeep(names);
|
|
372
|
+
for (const name of names) if (!keep.has(name)) await rm(join(this.backups, name), { force: true });
|
|
373
|
+
}
|
|
374
|
+
|
|
375
|
+
private async snapshotNames(): Promise<string[]> {
|
|
376
|
+
return (await readdir(this.backups).catch(() => [] as string[])).filter((name) => SNAPSHOT_NAME.test(name));
|
|
377
|
+
}
|
|
378
|
+
|
|
379
|
+
/** The newest snapshot that parses, with its contents if they validate whole. */
|
|
380
|
+
private async newestSnapshot(): Promise<{ path: string; raw: unknown; whole: StoredState | null } | null> {
|
|
381
|
+
for (const name of (await this.snapshotNames()).sort().reverse()) {
|
|
382
|
+
const path = join(this.backups, name);
|
|
383
|
+
const raw = await readJson(path).catch(() => undefined);
|
|
384
|
+
if (raw === undefined) continue;
|
|
385
|
+
const whole = StoredStateSchema.safeParse(raw);
|
|
386
|
+
return { path, raw, whole: whole.success ? whole.data : null };
|
|
387
|
+
}
|
|
388
|
+
return null;
|
|
389
|
+
}
|
|
390
|
+
|
|
391
|
+
/**
|
|
392
|
+
* A registry that is missing, empty, not JSON, or has records that don't validate is replaced by
|
|
393
|
+
* the newest snapshot, and a damaged file kept aside, rather than carrying on with fewer accounts
|
|
394
|
+
* or none. Throws on a transient read error so nothing overwrites a file that couldn't be read.
|
|
395
|
+
*/
|
|
173
396
|
private async load(): Promise<StoredState> {
|
|
397
|
+
const text = await readText(this.path);
|
|
174
398
|
let raw: unknown;
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
399
|
+
if (text?.trim()) {
|
|
400
|
+
try {
|
|
401
|
+
raw = JSON.parse(text);
|
|
402
|
+
} catch {
|
|
403
|
+
// Recovered below.
|
|
404
|
+
}
|
|
181
405
|
}
|
|
182
|
-
if (raw
|
|
183
|
-
|
|
184
|
-
|
|
406
|
+
if (raw !== undefined) {
|
|
407
|
+
const whole = StoredStateSchema.safeParse(raw);
|
|
408
|
+
if (whole.success) return whole.data;
|
|
409
|
+
}
|
|
410
|
+
const snapshot = await this.newestSnapshot();
|
|
411
|
+
if (text === undefined && !snapshot) return emptyState(); // A new install.
|
|
412
|
+
const problem = text === undefined ? "missing" : !text.trim() ? "empty" : raw === undefined ? "not valid JSON" : "partly invalid";
|
|
413
|
+
const kept = text === undefined ? null : await this.keepAside();
|
|
414
|
+
let state: StoredState;
|
|
415
|
+
let outcome: string;
|
|
416
|
+
if (snapshot?.whole) {
|
|
417
|
+
state = snapshot.whole;
|
|
418
|
+
outcome = `restored it from ${snapshot.path}`;
|
|
419
|
+
} else if (raw !== undefined) {
|
|
420
|
+
// No snapshot yet, or the newest one doesn't validate either, so another version wrote them
|
|
421
|
+
// (say, before a downgrade): the file is the newest record, and its valid entries are kept.
|
|
422
|
+
state = salvageState(raw).state;
|
|
423
|
+
outcome = "continued with the records that were still valid";
|
|
424
|
+
} else if (snapshot) {
|
|
425
|
+
state = salvageState(snapshot.raw).state;
|
|
426
|
+
outcome = `continued with the records of ${snapshot.path} that were still valid`;
|
|
427
|
+
} else {
|
|
428
|
+
state = emptyState();
|
|
429
|
+
outcome = "continued with an empty registry, as there is no backup";
|
|
430
|
+
}
|
|
431
|
+
// OpenCode fork records are the registry's own journal of what was sent. A snapshot can lag the
|
|
432
|
+
// file (it's written second, and its failure is tolerated), so its records are never restored:
|
|
433
|
+
// only the file's valid ones stay, and every record that was lost becomes a hold.
|
|
434
|
+
Object.assign(state, recoveredForks(raw, new Date().toISOString()));
|
|
435
|
+
console.error(`[ZeroSub] ${this.path} was ${problem}${kept ? `; kept it as ${kept}` : ""}; ${outcome}`);
|
|
436
|
+
await this.write(state).catch((error: unknown) => console.error("[ZeroSub] could not save the recovered state file", message(error)));
|
|
185
437
|
return state;
|
|
186
438
|
}
|
|
187
439
|
|
|
188
|
-
|
|
440
|
+
/** Copies a damaged registry aside before it's replaced, so a hand edit isn't lost. */
|
|
441
|
+
private async keepAside(): Promise<string> {
|
|
189
442
|
const copy = `${this.path}.bad-${Date.now()}`;
|
|
190
|
-
await copyFile(this.path, copy)
|
|
191
|
-
|
|
443
|
+
await copyFile(this.path, copy);
|
|
444
|
+
await chmod(copy, 0o600);
|
|
445
|
+
return copy;
|
|
192
446
|
}
|
|
193
447
|
}
|
|
194
448
|
|
|
449
|
+
/**
|
|
450
|
+
* The file's own valid fork records and holds, plus a fresh hold for each record or hold that
|
|
451
|
+
* couldn't be kept. A lost record is a new event, so an earlier acknowledgement doesn't carry over;
|
|
452
|
+
* a list that can't be read at all holds every source.
|
|
453
|
+
*/
|
|
454
|
+
function recoveredForks(raw: unknown, at: string): Pick<StoredState, "opencodeForks" | "opencodeHolds"> {
|
|
455
|
+
const all = { opencodeForks: {}, opencodeHolds: { [ALL_SOURCES]: { at } } };
|
|
456
|
+
if (!isRecord(raw)) return all;
|
|
457
|
+
const { opencodeForks, opencodeHolds } = salvageState(raw).state;
|
|
458
|
+
for (const list of [raw.opencodeForks, raw.opencodeHolds]) {
|
|
459
|
+
if (list !== undefined && !isRecord(list)) return { opencodeForks, opencodeHolds: { ...opencodeHolds, ...all.opencodeHolds } };
|
|
460
|
+
}
|
|
461
|
+
const forks = (raw.opencodeForks ?? {}) as Record<string, unknown>;
|
|
462
|
+
const holds = (raw.opencodeHolds ?? {}) as Record<string, unknown>;
|
|
463
|
+
for (const source of Object.keys(forks)) if (!opencodeForks[source]) opencodeHolds[source] = { at };
|
|
464
|
+
for (const source of Object.keys(holds)) if (!opencodeHolds[source]) opencodeHolds[source] = { at };
|
|
465
|
+
return { opencodeForks, opencodeHolds };
|
|
466
|
+
}
|
|
467
|
+
|
|
468
|
+
function isRecord(value: unknown): value is Record<string, unknown> {
|
|
469
|
+
return Boolean(value) && typeof value === "object" && !Array.isArray(value);
|
|
470
|
+
}
|
|
471
|
+
|
|
472
|
+
function message(error: unknown): string {
|
|
473
|
+
return error instanceof Error ? error.message : String(error);
|
|
474
|
+
}
|
|
475
|
+
|
|
195
476
|
export function findAccount(state: StoredState, accountId: string | null | undefined): StoredAccount | undefined {
|
|
196
477
|
return accountId ? state.accounts.find((account) => account.id === accountId) : undefined;
|
|
197
478
|
}
|
package/server/usage.ts
CHANGED
|
@@ -44,6 +44,8 @@ export function mergeUsage(previous: Usage | undefined, next: Usage): Usage {
|
|
|
44
44
|
if (!previous || previous.windows.length === 0) return next;
|
|
45
45
|
if (next.windows.length === 0) return { ...previous, error: next.error };
|
|
46
46
|
if (next.cached && Date.parse(next.fetchedAt) <= Date.parse(previous.fetchedAt)) return previous;
|
|
47
|
+
// A spend read can clear extra usage with null; reads without spend keep the last value.
|
|
48
|
+
if (next.extraUsage === undefined && previous.extraUsage != null) return { ...next, extraUsage: previous.extraUsage };
|
|
47
49
|
return next;
|
|
48
50
|
}
|
|
49
51
|
|
package/shared/format.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
import type
|
|
1
|
+
import { estimateApiCost, totalTokens, type AccountView, type PaceView, type AgentRoute, type AzureSummary, type Credits, type Egress, type ExtraUsage, type UsageWindow } from "./model";
|
|
2
|
+
import type { ReopenSummary } from "./rpc";
|
|
2
3
|
|
|
3
4
|
/** "in 2h 14m", "in 3d 4h", "now". */
|
|
4
5
|
export function formatResetIn(resetsAt: string | null, now: number = Date.now()): string | null {
|
|
@@ -32,7 +33,57 @@ export function formatCredits(credits: Credits): string {
|
|
|
32
33
|
return `${whole} ChatGPT credit${whole === "1" ? "" : "s"} left`;
|
|
33
34
|
}
|
|
34
35
|
|
|
35
|
-
|
|
36
|
+
const CURRENCY_SIGNS: Record<string, string> = { USD: "$", EUR: "€", GBP: "£" };
|
|
37
|
+
|
|
38
|
+
/** An amount in minor units of `currency` (cents for USD): "$12.34", "1,234.50 CAD". */
|
|
39
|
+
function formatMoney(minor: number, currency: string | null): string {
|
|
40
|
+
const [whole, cents] = (Math.max(0, minor) / 100).toFixed(2).split(".") as [string, string];
|
|
41
|
+
const amount = `${whole.replace(/\B(?=(\d{3})+(?!\d))/g, ",")}.${cents}`;
|
|
42
|
+
const sign = currency ? CURRENCY_SIGNS[currency.toUpperCase()] : undefined;
|
|
43
|
+
if (sign) return `${sign}${amount}`;
|
|
44
|
+
return currency ? `${amount} ${currency.toUpperCase()}` : amount;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
* "Extra usage on · $12.34 of $50.00 this month", "Extra usage on · $12.34 spent this month", or
|
|
49
|
+
* "Extra usage on" when the spend isn't known. `null` when it's off: nothing to show then.
|
|
50
|
+
*/
|
|
51
|
+
export function formatExtraUsage(extra: ExtraUsage): string | null {
|
|
52
|
+
if (!extra.enabled) return null;
|
|
53
|
+
if (extra.spend === null) return "Extra usage on";
|
|
54
|
+
const spent = formatMoney(extra.spend, extra.currency);
|
|
55
|
+
return extra.limit === null
|
|
56
|
+
? `Extra usage on · ${spent} spent this month`
|
|
57
|
+
: `Extra usage on · ${spent} of ${formatMoney(extra.limit, extra.currency)} this month`;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/** Claude's 5-hour and weekly windows, and Codex's two (see `parseUsage`, `parseRateLimits`). */
|
|
61
|
+
const ACCOUNT_WINDOWS = new Set(["five_hour", "seven_day", "primary", "secondary"]);
|
|
62
|
+
|
|
63
|
+
/**
|
|
64
|
+
* Whether a full window stops the whole account. The others only cap one model or surface, such as
|
|
65
|
+
* Claude's "Weekly · Opus": the account still works with the rest, and a turn that does hit one
|
|
66
|
+
* says so itself. Windows ZeroSub doesn't know count as the narrower kind.
|
|
67
|
+
*/
|
|
68
|
+
export function capsAccount(window: UsageWindow): boolean {
|
|
69
|
+
return ACCOUNT_WINDOWS.has(window.id);
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/**
|
|
73
|
+
* The model or surface a narrower window belongs to, lowercase: "fable" for "Weekly · Fable", else
|
|
74
|
+
* the window's id. It names the key of an account's `modelLimits`.
|
|
75
|
+
*/
|
|
76
|
+
export function windowScope(window: UsageWindow): string {
|
|
77
|
+
const named = window.label.match(/^Weekly\s*·\s*(.+)$/i)?.[1]?.trim();
|
|
78
|
+
return (named || window.id).toLowerCase();
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/** The busiest window that caps the whole account: how much room it has left for any model. */
|
|
82
|
+
export function accountPeak(windows: readonly UsageWindow[]): UsageWindow | null {
|
|
83
|
+
return peakUsage(windows.filter(capsAccount));
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/** The busiest of `windows`, whatever it caps. */
|
|
36
87
|
export function peakUsage(windows: readonly UsageWindow[]): UsageWindow | null {
|
|
37
88
|
let peak: UsageWindow | null = null;
|
|
38
89
|
for (const limit of windows) {
|
|
@@ -73,6 +124,60 @@ export function shortLabel(account: Pick<AccountView, "label">, max = 18): strin
|
|
|
73
124
|
return label.length <= max ? label : `${label.slice(0, max - 1)}…`;
|
|
74
125
|
}
|
|
75
126
|
|
|
127
|
+
const MOVES_WHEN: Record<NonNullable<AgentRoute["waiting"]>, string> = {
|
|
128
|
+
idle: "once it's idle",
|
|
129
|
+
turn: "when its current turn ends",
|
|
130
|
+
background: "once the background work it left running stops",
|
|
131
|
+
restart: "when its session next starts",
|
|
132
|
+
};
|
|
133
|
+
|
|
134
|
+
/**
|
|
135
|
+
* A composer pill's label and tooltip for an agent routed to `account`. While its session still
|
|
136
|
+
* runs on another account, both are named, so the pill never claims an account the agent isn't
|
|
137
|
+
* using yet, and the tooltip says when the move happens.
|
|
138
|
+
*/
|
|
139
|
+
export function pillText(
|
|
140
|
+
account: Pick<AccountView, "label" | "email">,
|
|
141
|
+
running: Pick<AccountView, "label"> | null,
|
|
142
|
+
waiting: AgentRoute["waiting"],
|
|
143
|
+
): { label: string; title: string } {
|
|
144
|
+
const named = `${account.label}${account.email && account.email !== account.label ? ` (${account.email})` : ""}`;
|
|
145
|
+
if (!running) return { label: shortLabel(account), title: `Account: ${named}` };
|
|
146
|
+
return {
|
|
147
|
+
label: `${shortLabel(running, 12)} → ${shortLabel(account, 12)}`,
|
|
148
|
+
title: `Account: ${running.label}, moving to ${named} ${MOVES_WHEN[waiting ?? "idle"]}`,
|
|
149
|
+
};
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
/** What moving agents came to, after `prefix`: "work is now the default · 2 agent(s) switched · …". */
|
|
153
|
+
export function describeReopen(prefix: string, summary: ReopenSummary): string {
|
|
154
|
+
const parts = [prefix];
|
|
155
|
+
if (summary.continuedIn) parts.push(`continuing in “${summary.continuedIn.title}”`);
|
|
156
|
+
if (summary.reopened.length > 0) parts.push(`${summary.reopened.length} agent(s) switched`);
|
|
157
|
+
if (summary.pending.length > 0) parts.push(`${summary.pending.length} still switching (their timelines will say when)`);
|
|
158
|
+
if (summary.deferred.length > 0) parts.push(`${summary.deferred.length} will switch after their current turn`);
|
|
159
|
+
if (summary.failed.length > 0) parts.push(`${summary.failed.length} couldn't be reloaded and will switch when their session next starts`);
|
|
160
|
+
return parts.join(" · ");
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
/** Why moving one agent to `to` didn't happen now, for its account button and `/account`; null when it did or will by itself. */
|
|
164
|
+
export function moveProblem(summary: ReopenSummary, to: string): string | null {
|
|
165
|
+
const failed = summary.failed[0];
|
|
166
|
+
if (!failed) return null;
|
|
167
|
+
return `Couldn't reload this agent onto ${to} (${failed.error.replace(/\.$/, "")}), so it moves when its session next starts.`;
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
/** Why an agent can't be moved onto an account at its limit while automatic switching is on. */
|
|
171
|
+
export function limitedPick(label: string): string {
|
|
172
|
+
return `${label} is at its limit, and with automatic switching on the agent would move straight off it again. Pick another account, or mark ${label} as available again on its card in Accounts if it has room.`;
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
/** Why an agent can't be moved onto an account whose limit for its model is reached, while others can run there. */
|
|
176
|
+
export function limitedModelPick(label: string, scope: string): string {
|
|
177
|
+
const name = scope.charAt(0).toUpperCase() + scope.slice(1);
|
|
178
|
+
return `${label} has reached its ${name} limit, so this agent's model can't run there now. Pick another account or another model.`;
|
|
179
|
+
}
|
|
180
|
+
|
|
76
181
|
/** One line summarising an account's headroom, e.g. "42% of 5-hour used · resets in 2h". */
|
|
77
182
|
/**
|
|
78
183
|
* The line under an account's name: its email, plus its organization when that adds something.
|
|
@@ -96,6 +201,18 @@ export function formatAge(at: string, now: number = Date.now()): string {
|
|
|
96
201
|
return hours < 48 ? `${hours}h ago` : `${Math.round(hours / 24)}d ago`;
|
|
97
202
|
}
|
|
98
203
|
|
|
204
|
+
/** How old an address may get before it says so: checks run every half hour. */
|
|
205
|
+
const EGRESS_FRESH_MS = 60 * 60_000;
|
|
206
|
+
|
|
207
|
+
/** "IP: 203.0.113.7 (US)", with its age once that's an hour; null before the first check. */
|
|
208
|
+
export function egressText(egress: Egress | null, now: number = Date.now()): string | null {
|
|
209
|
+
if (!egress) return null;
|
|
210
|
+
if (!egress.ip) return egress.error ? "IP: couldn't check" : null;
|
|
211
|
+
const old = egress.checkedAt && now - Date.parse(egress.checkedAt) >= EGRESS_FRESH_MS ? formatAge(egress.checkedAt, now) : null;
|
|
212
|
+
const notes = [egress.country, old].filter(Boolean).join(", ");
|
|
213
|
+
return `IP: ${egress.ip}${notes ? ` (${notes})` : ""}`;
|
|
214
|
+
}
|
|
215
|
+
|
|
99
216
|
export function usageSummary(account: AccountView, now: number = Date.now()): string | null {
|
|
100
217
|
if (account.status === "disabled") return "Disabled for now";
|
|
101
218
|
if (account.status === "limited") {
|
|
@@ -108,3 +225,54 @@ export function usageSummary(account: AccountView, now: number = Date.now()): st
|
|
|
108
225
|
const base = `${formatPercent(peak.usedPercent)} of ${peak.label.toLowerCase()} used`;
|
|
109
226
|
return reset ? `${base} · resets ${reset}` : base;
|
|
110
227
|
}
|
|
228
|
+
|
|
229
|
+
/** The note over state the daemon stopped answering for: "Showing data from 3m ago · couldn't refresh: …". */
|
|
230
|
+
export function staleNotice(updatedAt: number | null, error: string, now: number = Date.now()): string {
|
|
231
|
+
if (updatedAt === null) return `Couldn't refresh: ${error}`;
|
|
232
|
+
const age = formatAge(new Date(updatedAt).toISOString(), now);
|
|
233
|
+
return `Showing data from ${age === "just now" ? "a moment ago" : age} · couldn't refresh: ${error}`;
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
/** "1,234", "56.7K", "8.90M" tokens. */
|
|
237
|
+
export function formatTokens(count: number): string {
|
|
238
|
+
if (count < 10_000) return Math.round(count).toLocaleString("en-US");
|
|
239
|
+
if (count < 1_000_000) return `${(count / 1_000).toFixed(count < 100_000 ? 1 : 0)}K`;
|
|
240
|
+
return `${(count / 1_000_000).toFixed(count < 100_000_000 ? 2 : 0)}M`;
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
/**
|
|
244
|
+
* A paid API account's month, as its card shows it: its tokens, and the cost estimated from its price
|
|
245
|
+
* table ("cost unknown" while no model that used tokens has a price).
|
|
246
|
+
*/
|
|
247
|
+
export function apiUsageLines(account: Pick<AzureSummary, "prices" | "usage">, now: number = Date.now()): { tokens: string; cost: string; note: string | null } {
|
|
248
|
+
const month = account.usage;
|
|
249
|
+
const name = new Date(now).toLocaleString("en-US", { month: "long", timeZone: "UTC" });
|
|
250
|
+
const total = totalTokens(month);
|
|
251
|
+
const cache = total.cacheWrite > 0 ? `${formatTokens(total.cachedInput)} cache read, ${formatTokens(total.cacheWrite)} cache write` : `${formatTokens(total.cachedInput)} cached`;
|
|
252
|
+
const tokens = `${name}: ${formatTokens(total.input)} input (${cache}) · ${formatTokens(total.output)} output tokens`;
|
|
253
|
+
const { usd, complete } = estimateApiCost(month, account.prices);
|
|
254
|
+
const cost =
|
|
255
|
+
usd === null
|
|
256
|
+
? total.input + total.output > 0
|
|
257
|
+
? "Cost unknown: add prices for its models in the account's settings"
|
|
258
|
+
: "No tokens used yet this month"
|
|
259
|
+
: `≈ $${usd.toFixed(usd < 10 ? 2 : 0)} this month${complete ? "" : " (some models have no price yet)"}`;
|
|
260
|
+
const uncounted = month?.uncounted ?? 0;
|
|
261
|
+
const note = uncounted > 0 ? `${uncounted} turn${uncounted === 1 ? "" : "s"} couldn't be counted (no session file found), so these totals are short.` : null;
|
|
262
|
+
return { tokens, cost, note };
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
/** Weekly use at which an account counts as nearly used up. */
|
|
266
|
+
const WEEK_NEARLY_USED = 90;
|
|
267
|
+
|
|
268
|
+
/** What pacing makes of an account, in a few words for a menu row. `next`: pacing picks it for the next new agent. */
|
|
269
|
+
export function paceVerdict(pace: PaceView, next: boolean): string {
|
|
270
|
+
if (next) return "Picks next";
|
|
271
|
+
if (pace.gated) return "Held back: busy hour";
|
|
272
|
+
if (pace.weeklyUsed !== null && pace.weeklyUsed >= WEEK_NEARLY_USED) return "Week nearly used";
|
|
273
|
+
// The same standing as the account card's `describePace`.
|
|
274
|
+
if (pace.weeklyUsed !== null && pace.weekElapsed !== null && Math.round(pace.weeklyUsed + pace.pendingWeekly) > Math.round(pace.weekElapsed)) {
|
|
275
|
+
return "Using week fast";
|
|
276
|
+
}
|
|
277
|
+
return "Room to spare";
|
|
278
|
+
}
|