@omercnet/paseo-omp 5.2.4 → 5.3.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,1088 @@
1
+ import { type ChildProcess, spawn } from "node:child_process";
2
+ import { randomUUID } from "node:crypto";
3
+ import { tmpdir } from "node:os";
4
+ import { createInterface } from "node:readline";
5
+ import { z } from "zod";
6
+ import {
7
+ OMP_ACCOUNTS_SETTING_PATHS,
8
+ type OmpAccount,
9
+ type OmpAccountLimit,
10
+ type OmpAccountProvider,
11
+ type OmpAccountSteering,
12
+ type OmpAccountsSettingPath,
13
+ type OmpAccountsSettings,
14
+ type OmpAccountsView,
15
+ type OmpBalancePreview,
16
+ type OmpLogin,
17
+ type OmpLoginStep,
18
+ } from "../shared/omp-accounts";
19
+ import type { OmpStore } from "../shared/omp-store";
20
+ import { SerialMutationQueue } from "./mutation-queue";
21
+ import { resolveOmpExecutable } from "./omp-settings";
22
+ import { currentOmpEnvironment } from "./paths";
23
+ import { OmpPublicError } from "./provider/security";
24
+ import { buildStatefulCommandEnv, defaultSpawn, runBounded } from "./provider-diagnostics";
25
+
26
+ /** Polls read OMP again at most this often; an explicit refresh reads it now. */
27
+ const SNAPSHOT_TTL_MS = 5 * 60_000;
28
+ const COMMAND_TIMEOUT_MS = 60_000;
29
+ const REDEEM_TIMEOUT_MS = 120_000;
30
+ const RPC_REQUEST_TIMEOUT_MS = 30_000;
31
+ const LOGIN_TIMEOUT_MS = 15 * 60_000;
32
+ const FINISHED_LOGIN_TTL_MS = 10 * 60_000;
33
+ const KILL_GRACE_MS = 1_000;
34
+ const MAX_OUTPUT_BYTES = 4 * 1024 * 1024;
35
+ const BALANCE_SAMPLES = "20";
36
+
37
+ /** A bare rpc session: no tools, extensions or context, nothing saved. Only account commands run. */
38
+ const RPC_ARGS = [
39
+ "--mode",
40
+ "rpc",
41
+ "--no-session",
42
+ "--no-ui",
43
+ "--no-tools",
44
+ "--no-extensions",
45
+ "--no-skills",
46
+ "--no-rules",
47
+ "--no-lsp",
48
+ "--no-title",
49
+ ];
50
+
51
+ export class OmpAccountsError extends OmpPublicError {}
52
+
53
+ interface OmpCommand {
54
+ executable: string;
55
+ env: NodeJS.ProcessEnv;
56
+ }
57
+
58
+ // Everything `omp` prints is read through these schemas. An entry that does not fit is left out,
59
+ // so one odd entry never hides the rest of the accounts.
60
+
61
+ function entries<T extends z.ZodType>(entry: T) {
62
+ return z.array(z.unknown()).transform((items) =>
63
+ items.flatMap((item) => {
64
+ const parsed = entry.safeParse(item);
65
+ return parsed.success ? [parsed.data] : [];
66
+ }),
67
+ );
68
+ }
69
+
70
+ const EpochMs = z.number().int();
71
+ /** Used share of a limit, 0-1 and above 1 past it. */
72
+ const UsedFraction = z.number().min(0).max(100);
73
+ const OptionalText = z.string().optional().catch(undefined);
74
+
75
+ const FrameSchema = z.object({
76
+ type: OptionalText,
77
+ id: OptionalText,
78
+ success: z.boolean().optional().catch(undefined),
79
+ data: z.unknown().optional(),
80
+ error: OptionalText,
81
+ method: OptionalText,
82
+ url: OptionalText,
83
+ instructions: OptionalText,
84
+ title: OptionalText,
85
+ message: OptionalText,
86
+ });
87
+ type Frame = z.infer<typeof FrameSchema>;
88
+
89
+ const LoginProvidersSchema = z.object({
90
+ providers: entries(
91
+ z.object({
92
+ id: z.string(),
93
+ name: z.string(),
94
+ available: z.boolean().optional().catch(undefined),
95
+ authenticated: z.boolean(),
96
+ }),
97
+ ),
98
+ });
99
+
100
+ const StoredAccountSchema = z.object({
101
+ credentialId: z.number().int(),
102
+ provider: z.string(),
103
+ label: z.string(),
104
+ type: z.string(),
105
+ });
106
+ type StoredAccount = z.infer<typeof StoredAccountSchema>;
107
+ const LogoutAccountsSchema = z.object({ accounts: entries(StoredAccountSchema) });
108
+
109
+ const UsageReportSchema = z.object({
110
+ provider: z.string(),
111
+ fetchedAt: EpochMs.nullish(),
112
+ limits: entries(
113
+ z.object({
114
+ id: z.string(),
115
+ label: z.string(),
116
+ window: z.object({ resetsAt: EpochMs.nullish() }).nullish(),
117
+ amount: z.object({ usedFraction: UsedFraction.nullish() }).nullish(),
118
+ }),
119
+ ).nullish(),
120
+ metadata: z.object({ accountId: z.string().nullish(), orgId: z.string().nullish() }).nullish(),
121
+ });
122
+ type UsageReport = z.infer<typeof UsageReportSchema>;
123
+ const UsageSchema = z.object({ reports: entries(UsageReportSchema).nullish() });
124
+
125
+ const ResetAccountSchema = z.object({
126
+ provider: z.string(),
127
+ credentialId: z.number().int(),
128
+ accountId: z.string().nullish(),
129
+ orgId: z.string().nullish(),
130
+ availableCount: z.number().int(),
131
+ redeemableCount: z.number().int(),
132
+ soonestExpiry: z.string().nullish(),
133
+ unavailableReason: z.string().nullish(),
134
+ /** OMP could not read this login's resets at all. */
135
+ error: z.string().nullish(),
136
+ });
137
+ type ResetAccount = z.infer<typeof ResetAccountSchema>;
138
+ const ResetsSchema = z.object({ accounts: entries(ResetAccountSchema).nullish() });
139
+
140
+ const HistoryEntrySchema = z.object({
141
+ recordedAt: EpochMs,
142
+ provider: z.string(),
143
+ accountId: z.string().nullish(),
144
+ limitId: z.string(),
145
+ label: z.string(),
146
+ usedFraction: UsedFraction.nullish(),
147
+ resetsAt: EpochMs.nullish(),
148
+ });
149
+ type HistoryEntry = z.infer<typeof HistoryEntrySchema>;
150
+ const HistorySchema = z.object({ entries: entries(HistoryEntrySchema).nullish() });
151
+
152
+ const ModelsSchema = z.object({
153
+ models: entries(z.object({ kind: z.string(), selector: z.string() })),
154
+ });
155
+
156
+ const BalanceSchema = z.object({
157
+ model: z.string(),
158
+ success: z.object({
159
+ accounts: entries(z.object({ account: z.string(), percent: z.number() })),
160
+ }),
161
+ });
162
+
163
+ /** `omp config list --json`: each setting's `{ value, … }` entry, read only where this module uses it. */
164
+ const ConfigSchema = z.record(z.string(), z.unknown());
165
+ type Config = z.infer<typeof ConfigSchema>;
166
+ const SettingValueSchema = z.object({ value: z.union([z.string(), z.number(), z.boolean()]) });
167
+
168
+ /** One `auth.accountPolicies` entry. Fields this module does not set are kept as written. */
169
+ const AccountPolicySchema = z
170
+ .object({
171
+ provider: z.string(),
172
+ account: z.object({ accountId: z.string(), orgId: z.string().optional() }).passthrough(),
173
+ priority: z.number().optional(),
174
+ reservePct: z.number().optional(),
175
+ reclaimAbovePct: z.number().optional(),
176
+ })
177
+ .passthrough();
178
+ type AccountPolicy = z.infer<typeof AccountPolicySchema>;
179
+ const PoliciesSchema = z.object({ value: entries(AccountPolicySchema).nullish().default([]) });
180
+
181
+ /** How OMP's account policies select a login. */
182
+ interface AccountKey {
183
+ provider: string;
184
+ accountId: string;
185
+ orgId: string | null;
186
+ }
187
+
188
+ /** Above OMP's default account priority of 0. */
189
+ const PREFERRED_PRIORITY = 100;
190
+ /** The preferred login takes agents back once it has this much more than its reserve left. */
191
+ const RECLAIM_MARGIN_PCT = 15;
192
+ const DEFAULT_RESERVE_PCT = 10;
193
+
194
+ /** What the client may see: the plugin's own messages, never a raw Node error or omp's stderr. */
195
+ function publicMessage(error: unknown): string {
196
+ return error instanceof OmpPublicError ? error.message : "omp did not answer";
197
+ }
198
+
199
+ function readOutput<T>(schema: z.ZodType<T>, value: unknown, command: string): T {
200
+ const parsed = schema.safeParse(value);
201
+ if (!parsed.success) throw new OmpAccountsError(`${command} gave output the plugin can't read`);
202
+ return parsed.data;
203
+ }
204
+
205
+ async function resolveCommand(): Promise<OmpCommand> {
206
+ const executable = await resolveOmpExecutable();
207
+ if (!executable) throw new OmpAccountsError("The omp command was not found on this host");
208
+ return { executable, env: buildStatefulCommandEnv(currentOmpEnvironment()) };
209
+ }
210
+
211
+ async function runOmp(
212
+ command: OmpCommand,
213
+ args: readonly string[],
214
+ timeoutMs = COMMAND_TIMEOUT_MS,
215
+ ) {
216
+ return runBounded(
217
+ defaultSpawn,
218
+ command.executable,
219
+ args,
220
+ command.env,
221
+ timeoutMs,
222
+ KILL_GRACE_MS,
223
+ MAX_OUTPUT_BYTES,
224
+ tmpdir(),
225
+ );
226
+ }
227
+
228
+ async function runJson<T>(command: OmpCommand, args: readonly string[], schema: z.ZodType<T>) {
229
+ const label = `omp ${args.join(" ")}`;
230
+ const run = await runOmp(command, args);
231
+ if (run.outcome !== "exited" || run.exitCode !== 0 || run.truncated) {
232
+ throw new OmpAccountsError(`${label} failed`);
233
+ }
234
+ let output: unknown;
235
+ try {
236
+ output = JSON.parse(run.stdout);
237
+ } catch {
238
+ output = undefined;
239
+ }
240
+ return readOutput(schema, output, label);
241
+ }
242
+
243
+ /** One short-lived `omp --mode rpc` process, spoken to in JSON lines. */
244
+ class OmpRpcProcess {
245
+ private readonly child: ChildProcess;
246
+ private readonly pending = new Map<
247
+ string,
248
+ { resolve(data: unknown): void; reject(error: Error): void }
249
+ >();
250
+ private nextId = 0;
251
+ private closed = false;
252
+ private killer: ReturnType<typeof setTimeout> | undefined;
253
+
254
+ constructor(
255
+ command: OmpCommand,
256
+ private readonly onUiRequest?: (frame: Frame) => void,
257
+ ) {
258
+ this.child = spawn(command.executable, RPC_ARGS, {
259
+ cwd: tmpdir(),
260
+ env: command.env,
261
+ stdio: ["pipe", "pipe", "pipe"],
262
+ });
263
+ this.child.stdin?.on("error", () => undefined);
264
+ this.child.stderr?.resume();
265
+ if (this.child.stdout) {
266
+ createInterface({ input: this.child.stdout }).on("line", (line) => this.receive(line));
267
+ }
268
+ this.child.on("error", (error) => this.failAll(error));
269
+ this.child.on("close", (code) => {
270
+ this.closed = true;
271
+ clearTimeout(this.killer);
272
+ const status = code === null ? "" : ` with code ${code}`;
273
+ this.failAll(new OmpAccountsError(`omp exited${status}`));
274
+ });
275
+ }
276
+
277
+ /** OMP's answer, still unchecked: callers read it through a schema. */
278
+ request(command: Record<string, unknown>, timeoutMs = RPC_REQUEST_TIMEOUT_MS): Promise<unknown> {
279
+ if (this.closed) {
280
+ return Promise.reject(new OmpAccountsError("omp is no longer running"));
281
+ }
282
+ const id = `paseo-omp-${++this.nextId}`;
283
+ const { promise, resolve, reject } = Promise.withResolvers<unknown>();
284
+ const timer = setTimeout(() => {
285
+ this.pending.delete(id);
286
+ reject(new OmpAccountsError(`omp did not answer ${String(command.type)} in time`));
287
+ }, timeoutMs);
288
+ this.pending.set(id, {
289
+ resolve: (data) => {
290
+ clearTimeout(timer);
291
+ resolve(data);
292
+ },
293
+ reject: (error) => {
294
+ clearTimeout(timer);
295
+ reject(error);
296
+ },
297
+ });
298
+ this.send({ ...command, id });
299
+ return promise;
300
+ }
301
+
302
+ send(frame: Record<string, unknown>): void {
303
+ this.child.stdin?.write(`${JSON.stringify(frame)}\n`);
304
+ }
305
+
306
+ close(): void {
307
+ if (this.closed) return;
308
+ this.closed = true;
309
+ this.child.kill();
310
+ // A login process that ignores TERM keeps OMP's fixed OAuth callback port.
311
+ this.killer = setTimeout(() => this.child.kill("SIGKILL"), KILL_GRACE_MS);
312
+ }
313
+
314
+ private receive(line: string): void {
315
+ let raw: unknown;
316
+ try {
317
+ raw = JSON.parse(line);
318
+ } catch {
319
+ return;
320
+ }
321
+ const parsed = FrameSchema.safeParse(raw);
322
+ if (!parsed.success) return;
323
+ const frame = parsed.data;
324
+ const waiter = frame.id ? this.pending.get(frame.id) : undefined;
325
+ if (frame.type === "response" && frame.id && waiter) {
326
+ this.pending.delete(frame.id);
327
+ if (frame.success) waiter.resolve(frame.data);
328
+ else waiter.reject(new OmpAccountsError(frame.error ?? "omp refused the request"));
329
+ } else if (frame.type === "extension_ui_request") {
330
+ this.onUiRequest?.(frame);
331
+ }
332
+ }
333
+
334
+ private failAll(error: Error): void {
335
+ for (const waiter of this.pending.values()) waiter.reject(error);
336
+ this.pending.clear();
337
+ }
338
+ }
339
+
340
+ interface Listing {
341
+ providers: OmpAccountProvider[];
342
+ accounts: StoredAccount[];
343
+ }
344
+
345
+ /** Every login in OMP's store, read through its rpc account commands. */
346
+ async function listStoredLogins(command: OmpCommand): Promise<Listing> {
347
+ const rpc = new OmpRpcProcess(command);
348
+ try {
349
+ const answer = await rpc.request({ type: "get_login_providers" });
350
+ const { providers } = readOutput(LoginProvidersSchema, answer, "omp get_login_providers");
351
+ const lists = await Promise.all(
352
+ providers
353
+ .filter((provider) => provider.authenticated)
354
+ .map(async (provider) => {
355
+ // One provider's failed or odd answer leaves out only that provider's logins.
356
+ const answer = await rpc
357
+ .request({ type: "get_logout_accounts", providerId: provider.id })
358
+ .catch(() => undefined);
359
+ const listed = LogoutAccountsSchema.safeParse(answer);
360
+ return listed.success ? listed.data.accounts : [];
361
+ }),
362
+ );
363
+ // Login aliases (`openai-codex-device`) list the same credentials as their target.
364
+ const accounts = new Map<string, StoredAccount>();
365
+ for (const account of lists.flat()) {
366
+ accounts.set(`${account.provider}/${account.credentialId}`, account);
367
+ }
368
+ return {
369
+ providers: providers
370
+ .filter((provider) => provider.available !== false)
371
+ .map(({ id, name, authenticated }) => ({ id, name, authenticated })),
372
+ accounts: [...accounts.values()],
373
+ };
374
+ } finally {
375
+ rpc.close();
376
+ }
377
+ }
378
+
379
+ function toLimits(report: UsageReport | undefined): OmpAccountLimit[] {
380
+ return (report?.limits ?? []).flatMap((limit) => {
381
+ const usedFraction = limit.amount?.usedFraction;
382
+ if (typeof usedFraction !== "number") return [];
383
+ return [
384
+ { id: limit.id, label: limit.label, usedFraction, resetsAt: limit.window?.resetsAt ?? null },
385
+ ];
386
+ });
387
+ }
388
+
389
+ interface RecordedUsage {
390
+ limits: OmpAccountLimit[];
391
+ at: number;
392
+ }
393
+
394
+ /** The newest recorded reading, for when OMP has no live one (for example the provider refused it). */
395
+ function lastRecorded(
396
+ history: readonly HistoryEntry[],
397
+ provider: string,
398
+ accountId: string,
399
+ ): RecordedUsage | null {
400
+ const rows = history.filter((row) => row.provider === provider && row.accountId === accountId);
401
+ if (rows.length === 0) return null;
402
+ const at = Math.max(...rows.map((row) => row.recordedAt));
403
+ const limits = rows.flatMap((row) => {
404
+ if (row.recordedAt !== at || typeof row.usedFraction !== "number") return [];
405
+ return [
406
+ {
407
+ id: row.limitId,
408
+ label: row.label,
409
+ usedFraction: row.usedFraction,
410
+ resetsAt: row.resetsAt ?? null,
411
+ },
412
+ ];
413
+ });
414
+ return limits.length > 0 ? { limits, at } : null;
415
+ }
416
+
417
+ function toResets(reset: ResetAccount | undefined): OmpAccount["resets"] {
418
+ if (!reset) return null;
419
+ if (reset.error) {
420
+ return {
421
+ available: 0,
422
+ usableNow: false,
423
+ blockedReason: "OMP could not read this login's resets",
424
+ soonestExpiry: null,
425
+ };
426
+ }
427
+ if (reset.availableCount <= 0) return null;
428
+ const usableNow = reset.redeemableCount > 0;
429
+ return {
430
+ available: reset.availableCount,
431
+ usableNow,
432
+ blockedReason: usableNow
433
+ ? null
434
+ : `OMP can't use a reset on this login right now (${reset.unavailableReason ?? "not redeemable"})`,
435
+ soonestExpiry: reset.soonestExpiry ?? null,
436
+ };
437
+ }
438
+
439
+ /** The ids OMP's account policies select this login by; only known for logins with a reset listing. */
440
+ function accountKey(reset: ResetAccount | undefined): AccountKey | null {
441
+ return reset?.accountId
442
+ ? { provider: reset.provider, accountId: reset.accountId, orgId: reset.orgId ?? null }
443
+ : null;
444
+ }
445
+
446
+ function selects(policy: AccountPolicy, key: AccountKey): boolean {
447
+ return (
448
+ policy.provider === key.provider &&
449
+ policy.account.accountId === key.accountId &&
450
+ (policy.account.orgId ?? null) === key.orgId
451
+ );
452
+ }
453
+
454
+ function steeringOf(policies: readonly AccountPolicy[], key: AccountKey): OmpAccountSteering {
455
+ const policy = policies.find((entry) => selects(entry, key));
456
+ return {
457
+ preferred: policy?.priority === PREFERRED_PRIORITY,
458
+ reservePct: policy?.reservePct ?? null,
459
+ };
460
+ }
461
+
462
+ interface SteeringChange {
463
+ preferred?: boolean;
464
+ reservePct?: number | null;
465
+ }
466
+
467
+ /**
468
+ * The policy list with `change` applied to the login `key` names. Other logins' policies are kept
469
+ * as written, except that at most one login per provider carries the plugin's preference. A policy
470
+ * left with nothing but its account is dropped, so OMP's config does not collect empty entries.
471
+ */
472
+ export function applySteering(
473
+ policies: readonly AccountPolicy[],
474
+ key: AccountKey,
475
+ change: SteeringChange,
476
+ defaultReservePct: number,
477
+ ): AccountPolicy[] {
478
+ const next = policies.map((policy) => ({ ...policy, account: { ...policy.account } }));
479
+ let target = next.find((policy) => selects(policy, key));
480
+ if (!target) {
481
+ target = {
482
+ provider: key.provider,
483
+ account: { accountId: key.accountId, ...(key.orgId ? { orgId: key.orgId } : {}) },
484
+ };
485
+ next.push(target);
486
+ }
487
+ if (change.preferred === true) {
488
+ for (const policy of next) {
489
+ if (policy.provider === key.provider && policy.priority === PREFERRED_PRIORITY) {
490
+ delete policy.priority;
491
+ delete policy.reclaimAbovePct;
492
+ }
493
+ }
494
+ target.priority = PREFERRED_PRIORITY;
495
+ } else if (change.preferred === false && target.priority === PREFERRED_PRIORITY) {
496
+ delete target.priority;
497
+ delete target.reclaimAbovePct;
498
+ }
499
+ if (change.reservePct === null) delete target.reservePct;
500
+ else if (typeof change.reservePct === "number") target.reservePct = change.reservePct;
501
+ return next
502
+ .map((policy) =>
503
+ policy.provider === key.provider
504
+ ? withReclaimThresholds([policy], defaultReservePct)[0]
505
+ : policy,
506
+ )
507
+ .filter(
508
+ (policy): policy is AccountPolicy => policy !== undefined && Object.keys(policy).length > 2,
509
+ );
510
+ }
511
+
512
+ /**
513
+ * The plugin's preferred policies with their reclaim threshold recomputed above the reserve that
514
+ * applies; OMP refuses a threshold at or below it. Policies the plugin did not prefer are untouched.
515
+ */
516
+ export function withReclaimThresholds(
517
+ policies: readonly AccountPolicy[],
518
+ defaultReservePct: number,
519
+ ): AccountPolicy[] {
520
+ return policies.map((policy) => {
521
+ if (policy.priority !== PREFERRED_PRIORITY) return policy;
522
+ const next = { ...policy };
523
+ const reserve = policy.reservePct ?? defaultReservePct;
524
+ if (reserve < 100) next.reclaimAbovePct = Math.min(100, reserve + RECLAIM_MARGIN_PCT);
525
+ else delete next.reclaimAbovePct;
526
+ return next;
527
+ });
528
+ }
529
+
530
+ function sameKey(a: AccountKey, b: AccountKey): boolean {
531
+ return a.provider === b.provider && a.accountId === b.accountId && a.orgId === b.orgId;
532
+ }
533
+
534
+ function readPolicies(config: Config | null): AccountPolicy[] {
535
+ const parsed = PoliciesSchema.safeParse(config?.["auth.accountPolicies"]);
536
+ return parsed.success ? (parsed.data.value ?? []) : [];
537
+ }
538
+
539
+ function readSettings(config: Config): OmpAccountsSettings {
540
+ const settings: OmpAccountsSettings = {};
541
+ for (const path of OMP_ACCOUNTS_SETTING_PATHS) {
542
+ const entry = SettingValueSchema.safeParse(config[path]);
543
+ if (entry.success) settings[path] = entry.data.value;
544
+ }
545
+ return settings;
546
+ }
547
+
548
+ /**
549
+ * Pairs each OAuth login with its usage report. Reports carry no credential id, so the match goes
550
+ * through the account id OMP's reset listing gives per credential; a provider with one login and
551
+ * one report needs no id. Without a live report, the newest recorded reading stands in.
552
+ */
553
+ export function joinAccounts(
554
+ stored: readonly StoredAccount[],
555
+ reports: readonly UsageReport[],
556
+ resets: readonly ResetAccount[],
557
+ history: readonly HistoryEntry[],
558
+ policies: readonly AccountPolicy[],
559
+ ): OmpAccount[] {
560
+ const accounts = stored.map((login): OmpAccount => {
561
+ if (login.type !== "oauth") {
562
+ return {
563
+ provider: login.provider,
564
+ credentialId: login.credentialId,
565
+ oauth: false,
566
+ label: login.label,
567
+ limits: [],
568
+ usageAt: null,
569
+ usageIsRecorded: false,
570
+ resets: null,
571
+ steering: null,
572
+ };
573
+ }
574
+ const reset = resets.find(
575
+ (entry) => entry.provider === login.provider && entry.credentialId === login.credentialId,
576
+ );
577
+ const candidates = reports.filter((report) => report.provider === login.provider);
578
+ const siblings = stored.filter(
579
+ (other) => other.type === "oauth" && other.provider === login.provider,
580
+ );
581
+ const sameIdentity = (report: UsageReport) =>
582
+ report.metadata?.accountId === reset?.accountId &&
583
+ (!reset?.orgId || !report.metadata?.orgId || report.metadata.orgId === reset.orgId);
584
+ const onlyCandidate =
585
+ siblings.length === 1 && candidates.length === 1 ? candidates[0] : undefined;
586
+ const report = reset?.accountId ? candidates.find(sameIdentity) : onlyCandidate;
587
+ const key = accountKey(reset);
588
+ const live = toLimits(report);
589
+ const recorded =
590
+ live.length === 0 && reset?.accountId
591
+ ? lastRecorded(history, login.provider, reset.accountId)
592
+ : null;
593
+ return {
594
+ provider: login.provider,
595
+ credentialId: login.credentialId,
596
+ oauth: true,
597
+ label: login.label,
598
+ limits: recorded?.limits ?? live,
599
+ usageAt: recorded?.at ?? report?.fetchedAt ?? null,
600
+ usageIsRecorded: recorded !== null,
601
+ resets: toResets(reset),
602
+ steering: key ? steeringOf(policies, key) : null,
603
+ };
604
+ });
605
+ return accounts.sort(
606
+ (a, b) => a.provider.localeCompare(b.provider) || a.credentialId - b.credentialId,
607
+ );
608
+ }
609
+
610
+ /** Where new sessions would go right now, by OMP's own balancer. */
611
+ async function previewBalance(
612
+ command: OmpCommand,
613
+ provider: string,
614
+ ): Promise<OmpBalancePreview | null> {
615
+ // Any chat model of the provider spreads over the same logins; OMP names the real selector.
616
+ const listed = await runJson(command, ["models", provider, "--json"], ModelsSchema).catch(
617
+ () => null,
618
+ );
619
+ const model = listed?.models.find((entry) => entry.kind === "chat")?.selector;
620
+ if (!model) return null;
621
+ // An answer without `success` (OMP could not balance) just leaves the line out.
622
+ const result = await runJson(
623
+ command,
624
+ ["dry-balance", model, "--count", BALANCE_SAMPLES, "--json"],
625
+ BalanceSchema,
626
+ ).catch(() => null);
627
+ if (!result) return null;
628
+ return {
629
+ provider,
630
+ model: result.model,
631
+ shares: result.success.accounts.map((share) => ({
632
+ label: share.account,
633
+ percent: share.percent,
634
+ })),
635
+ };
636
+ }
637
+
638
+ interface Snapshot {
639
+ providers: OmpAccountProvider[];
640
+ accounts: OmpAccount[];
641
+ balance: OmpBalancePreview[];
642
+ /** When the read producing this snapshot began; a read that began earlier never replaces it. */
643
+ startedAt: number;
644
+ settings: OmpAccountsSettings;
645
+ /** `provider/credentialId` to the ids OMP's account policies select that login by. */
646
+ identities: Map<string, AccountKey>;
647
+ fetchedAt: number;
648
+ error: string | null;
649
+ }
650
+
651
+ async function readSnapshot(
652
+ command: OmpCommand,
653
+ invalidate: boolean,
654
+ startedAt: number,
655
+ ): Promise<Snapshot> {
656
+ // Asks the providers again instead of answering from OMP's usage cache.
657
+ if (invalidate) await runOmp(command, ["usage", "invalidate"]);
658
+ const errors: string[] = [];
659
+ const [listing, usage, resets, history, config] = await Promise.all([
660
+ listStoredLogins(command),
661
+ runJson(command, ["usage", "--json"], UsageSchema).catch((error: unknown) => {
662
+ errors.push(`Usage: ${publicMessage(error)}`);
663
+ return { reports: [] };
664
+ }),
665
+ runJson(command, ["usage", "reset", "--json"], ResetsSchema).catch((error: unknown) => {
666
+ errors.push(`Resets: ${publicMessage(error)}`);
667
+ return { accounts: [] };
668
+ }),
669
+ // Local records only, so it is cheap; it stands in for a missing live reading.
670
+ runJson(command, ["usage", "--history", "--json", "--days", "1"], HistorySchema).catch(() => ({
671
+ entries: [],
672
+ })),
673
+ runJson(command, ["config", "list", "--json"], ConfigSchema).catch((error: unknown) => {
674
+ errors.push(`Settings: ${publicMessage(error)}`);
675
+ return null;
676
+ }),
677
+ ]);
678
+ const policies = readPolicies(config);
679
+ const accounts = joinAccounts(
680
+ listing.accounts,
681
+ usage.reports ?? [],
682
+ resets.accounts ?? [],
683
+ history.entries ?? [],
684
+ policies,
685
+ );
686
+ const crowded = [...new Set(accounts.map((account) => account.provider))].filter(
687
+ (provider) => accounts.filter((account) => account.provider === provider).length > 1,
688
+ );
689
+ const previews = await Promise.all(crowded.map((provider) => previewBalance(command, provider)));
690
+ return {
691
+ providers: listing.providers,
692
+ accounts,
693
+ balance: previews.filter((preview): preview is OmpBalancePreview => preview !== null),
694
+ settings: config ? readSettings(config) : {},
695
+ identities: new Map(
696
+ (resets.accounts ?? []).flatMap((reset) => {
697
+ const key = accountKey(reset);
698
+ return key ? [[`${reset.provider}/${reset.credentialId}`, key] as const] : [];
699
+ }),
700
+ ),
701
+ startedAt,
702
+ fetchedAt: Date.now(),
703
+ error: errors.length > 0 ? errors.join(" · ") : null,
704
+ };
705
+ }
706
+
707
+ interface LoginState {
708
+ id: string;
709
+ storeKey: string;
710
+ provider: string;
711
+ step: OmpLoginStep;
712
+ url: string | null;
713
+ instructions: string | null;
714
+ codePrompt: string | null;
715
+ message: string | null;
716
+ /** The pending `input` request OMP wants the pasted code for. */
717
+ promptId: string | null;
718
+ process: OmpRpcProcess | null;
719
+ endedAt: number | null;
720
+ }
721
+
722
+ function isOpen(step: OmpLoginStep): boolean {
723
+ return step === "starting" || step === "waiting" || step === "verifying";
724
+ }
725
+
726
+ function toLogin(login: LoginState): OmpLogin {
727
+ return {
728
+ id: login.id,
729
+ provider: login.provider,
730
+ step: login.step,
731
+ url: login.url,
732
+ instructions: login.instructions,
733
+ codePrompt: login.codePrompt,
734
+ message: login.message,
735
+ };
736
+ }
737
+
738
+ function storeKey(store: OmpStore | undefined): string {
739
+ return JSON.stringify(store ?? {});
740
+ }
741
+
742
+ function lastLine(text: string): string | undefined {
743
+ return text
744
+ .split("\n")
745
+ .map((line) => line.trim())
746
+ .filter(Boolean)
747
+ .at(-1);
748
+ }
749
+
750
+ /**
751
+ * Exposes OMP's own multi-account store. OMP balances its agents across these logins and moves off
752
+ * one that hits a limit by itself, so this only lists, adds, removes and resets them.
753
+ */
754
+ export class OmpAccounts {
755
+ private readonly snapshots = new Map<string, Snapshot>();
756
+ private readonly loading = new Map<string, Promise<Snapshot>>();
757
+ private readonly logins = new Map<string, LoginState>();
758
+ /** One config write at a time, so each one edits the list the previous one wrote. */
759
+ private readonly writes = new SerialMutationQueue();
760
+
761
+ async list(store: OmpStore | undefined, refresh: boolean): Promise<OmpAccountsView> {
762
+ const executable = await resolveOmpExecutable();
763
+ if (!executable) return this.view(store, null, null);
764
+ const key = storeKey(store);
765
+ const cached = this.snapshots.get(key);
766
+ const fresh = cached && Date.now() - cached.fetchedAt < SNAPSHOT_TTL_MS;
767
+ if (fresh && !refresh) return this.view(store, cached, null);
768
+ try {
769
+ return this.view(store, await this.load(store, refresh), null);
770
+ } catch (error) {
771
+ return this.view(
772
+ store,
773
+ cached ?? null,
774
+ `Could not read OMP's accounts: ${publicMessage(error)}`,
775
+ );
776
+ }
777
+ }
778
+
779
+ async startLogin(store: OmpStore | undefined, provider: string): Promise<OmpLogin> {
780
+ const command = await resolveCommand();
781
+ // OAuth callbacks listen on fixed local ports, so only one sign-in runs at a time.
782
+ for (const other of this.logins.values()) {
783
+ if (isOpen(other.step)) this.settle(other, "canceled", "A newer sign-in replaced this one");
784
+ }
785
+ for (const [id, login] of this.logins) {
786
+ if (login.endedAt !== null && Date.now() - login.endedAt > FINISHED_LOGIN_TTL_MS) {
787
+ this.logins.delete(id);
788
+ }
789
+ }
790
+ const login: LoginState = {
791
+ id: randomUUID(),
792
+ storeKey: storeKey(store),
793
+ provider,
794
+ step: "starting",
795
+ url: null,
796
+ instructions: null,
797
+ codePrompt: null,
798
+ message: null,
799
+ promptId: null,
800
+ process: null,
801
+ endedAt: null,
802
+ };
803
+ this.logins.set(login.id, login);
804
+ void this.runLogin(login, command, store);
805
+ return toLogin(login);
806
+ }
807
+
808
+ submitCode(loginId: string, code: string): OmpLogin {
809
+ const login = this.logins.get(loginId);
810
+ if (!login?.process || !isOpen(login.step)) {
811
+ throw new OmpAccountsError("This sign-in is no longer running. Start it again");
812
+ }
813
+ if (!login.promptId)
814
+ throw new OmpAccountsError("OMP isn't waiting for a code for this sign-in");
815
+ login.process.send({ type: "extension_ui_response", id: login.promptId, value: code });
816
+ login.promptId = null;
817
+ login.codePrompt = null;
818
+ login.step = "verifying";
819
+ return toLogin(login);
820
+ }
821
+
822
+ cancelLogin(loginId: string): OmpLogin | null {
823
+ const login = this.logins.get(loginId);
824
+ if (!login) return null;
825
+ if (isOpen(login.step)) this.settle(login, "canceled", "Sign-in was canceled");
826
+ return toLogin(login);
827
+ }
828
+
829
+ async remove(store: OmpStore | undefined, provider: string, credentialId: number): Promise<void> {
830
+ const command = await resolveCommand();
831
+ const key = this.snapshots.get(storeKey(store))?.identities.get(`${provider}/${credentialId}`);
832
+ const rpc = new OmpRpcProcess(command);
833
+ try {
834
+ await rpc.request({ type: "logout", providerId: provider, credentialId });
835
+ } finally {
836
+ rpc.close();
837
+ }
838
+ // A policy left behind would silently apply to a later login with the same account id. The
839
+ // logout has already happened, so a failed cleanup is not a failed removal.
840
+ if (key) {
841
+ await this.writes
842
+ .run(async () => {
843
+ const config = await runJson(command, ["config", "list", "--json"], ConfigSchema);
844
+ const kept = readPolicies(config).filter((policy) => !selects(policy, key));
845
+ await this.writeSetting(
846
+ command,
847
+ "auth.accountPolicies",
848
+ kept.length > 0 ? JSON.stringify(kept) : null,
849
+ );
850
+ })
851
+ .catch(() => undefined);
852
+ }
853
+ await this.refreshAfterChange(store);
854
+ }
855
+
856
+ async redeem(
857
+ store: OmpStore | undefined,
858
+ provider: string,
859
+ credentialId: number,
860
+ ): Promise<{ ok: boolean; message: string }> {
861
+ const command = await resolveCommand();
862
+ const account = this.snapshots
863
+ .get(storeKey(store))
864
+ ?.accounts.find(
865
+ (entry) => entry.provider === provider && entry.credentialId === credentialId,
866
+ );
867
+ if (account?.resets && !account.resets.usableNow) {
868
+ return { ok: false, message: account.resets.blockedReason ?? "OMP can't use a reset now" };
869
+ }
870
+ const run = await runOmp(
871
+ command,
872
+ ["usage", "reset", `${provider}/${credentialId}`],
873
+ REDEEM_TIMEOUT_MS,
874
+ );
875
+ const used = run.outcome === "exited" && run.exitCode === 0;
876
+ await this.refreshAfterChange(store);
877
+ if (run.outcome === "timeout") {
878
+ return {
879
+ ok: false,
880
+ message: "OMP did not finish in time; check its banked resets before trying again",
881
+ };
882
+ }
883
+ if (!used) return { ok: false, message: "OMP could not use the reset" };
884
+ return { ok: true, message: lastLine(run.stdout) ?? "Reset used" };
885
+ }
886
+
887
+ /** Edits the login's entry in OMP's own `auth.accountPolicies`, so terminal `omp` follows it too. */
888
+ async setSteering(
889
+ store: OmpStore | undefined,
890
+ provider: string,
891
+ credentialId: number,
892
+ change: SteeringChange,
893
+ ): Promise<void> {
894
+ const command = await resolveCommand();
895
+ await this.writes.run(async () => {
896
+ const snapshot = this.snapshots.get(storeKey(store)) ?? (await this.load(store, false));
897
+ const key = snapshot.identities.get(`${provider}/${credentialId}`);
898
+ if (!key) {
899
+ throw new OmpAccountsError(
900
+ "OMP doesn't say which account this login belongs to, so its policies can't select it",
901
+ );
902
+ }
903
+ // OMP refuses a policy that matches two stored logins, which would take the provider down.
904
+ const twins = [...snapshot.identities.entries()].filter(
905
+ ([ref, other]) => ref !== `${provider}/${credentialId}` && sameKey(other, key),
906
+ );
907
+ if (twins.length > 0) {
908
+ throw new OmpAccountsError(
909
+ "Two logins share this account id, so a policy for it would be ambiguous",
910
+ );
911
+ }
912
+ const config = await runJson(command, ["config", "list", "--json"], ConfigSchema);
913
+ const reserve = SettingValueSchema.safeParse(config["retry.usageReservePct"]);
914
+ const defaultReserve =
915
+ reserve.success && typeof reserve.data.value === "number"
916
+ ? reserve.data.value
917
+ : DEFAULT_RESERVE_PCT;
918
+ const next = applySteering(readPolicies(config), key, change, defaultReserve);
919
+ await this.writeSetting(
920
+ command,
921
+ "auth.accountPolicies",
922
+ next.length > 0 ? JSON.stringify(next) : null,
923
+ );
924
+ });
925
+ await this.refreshAfterChange(store);
926
+ }
927
+
928
+ async setSetting(
929
+ store: OmpStore | undefined,
930
+ path: OmpAccountsSettingPath,
931
+ value: string | number | boolean | null,
932
+ ): Promise<void> {
933
+ const command = await resolveCommand();
934
+ await this.writes.run(async () => {
935
+ // A new default reserve can sit at or above a preferred login's reclaim threshold, which OMP
936
+ // refuses to load, so the thresholds move with it in the same write.
937
+ if (path === "retry.usageReservePct") {
938
+ const config = await runJson(command, ["config", "list", "--json"], ConfigSchema);
939
+ const current = SettingValueSchema.safeParse(config["retry.usageReservePct"]);
940
+ const currentDefault =
941
+ current.success && typeof current.data.value === "number"
942
+ ? current.data.value
943
+ : DEFAULT_RESERVE_PCT;
944
+ const nextDefault = typeof value === "number" ? value : DEFAULT_RESERVE_PCT;
945
+ const policies = withReclaimThresholds(readPolicies(config), nextDefault);
946
+ const policiesJson = policies.length > 0 ? JSON.stringify(policies) : null;
947
+ // OMP must never see a reclaim threshold at or below the default in force between the two
948
+ // writes: raise thresholds before a higher default, lower them after a lower default.
949
+ if (nextDefault >= currentDefault) {
950
+ await this.writeSetting(command, "auth.accountPolicies", policiesJson);
951
+ await this.writeSetting(command, path, value === null ? null : JSON.stringify(value));
952
+ } else {
953
+ await this.writeSetting(command, path, value === null ? null : JSON.stringify(value));
954
+ await this.writeSetting(command, "auth.accountPolicies", policiesJson);
955
+ }
956
+ return;
957
+ }
958
+ await this.writeSetting(command, path, value === null ? null : JSON.stringify(value));
959
+ });
960
+ await this.refreshAfterChange(store);
961
+ }
962
+
963
+ /** `omp config set <path> --json -- <json>`, or `config reset` for null; OMP validates the value. */
964
+ private async writeSetting(
965
+ command: OmpCommand,
966
+ path: string,
967
+ json: string | null,
968
+ ): Promise<void> {
969
+ const args =
970
+ json === null ? ["config", "reset", path] : ["config", "set", path, "--json", "--", json];
971
+ const run = await runOmp(command, args);
972
+ if (run.outcome !== "exited" || run.exitCode !== 0) {
973
+ throw new OmpAccountsError(`OMP rejected the change to ${path}`);
974
+ }
975
+ }
976
+
977
+ stop(): void {
978
+ for (const login of this.logins.values()) {
979
+ if (isOpen(login.step)) this.settle(login, "canceled", null);
980
+ }
981
+ }
982
+
983
+ private view(
984
+ store: OmpStore | undefined,
985
+ snapshot: Snapshot | null,
986
+ error: string | null,
987
+ ): OmpAccountsView {
988
+ const key = storeKey(store);
989
+ return {
990
+ installed: snapshot !== null || error !== null,
991
+ providers: snapshot?.providers ?? [],
992
+ accounts: snapshot?.accounts ?? [],
993
+ logins: [...this.logins.values()].filter((login) => login.storeKey === key).map(toLogin),
994
+ balance: snapshot?.balance ?? [],
995
+ settings: snapshot?.settings ?? {},
996
+ fetchedAt: snapshot?.fetchedAt ?? null,
997
+ error: error ?? snapshot?.error ?? null,
998
+ };
999
+ }
1000
+
1001
+ /** One read at a time per store; an explicit refresh starts a new one even while a poll runs. */
1002
+ private load(store: OmpStore | undefined, invalidate: boolean): Promise<Snapshot> {
1003
+ const key = storeKey(store);
1004
+ const running = this.loading.get(key);
1005
+ if (running && !invalidate) return running;
1006
+ const startedAt = Date.now();
1007
+ const next = resolveCommand()
1008
+ .then((command) => readSnapshot(command, invalidate, startedAt))
1009
+ .then((snapshot) => {
1010
+ // A read that began before a later write must not overwrite what that write produced.
1011
+ const current = this.snapshots.get(key);
1012
+ if (!current || current.startedAt <= startedAt) this.snapshots.set(key, snapshot);
1013
+ return this.snapshots.get(key) ?? snapshot;
1014
+ })
1015
+ .finally(() => {
1016
+ if (this.loading.get(key) === next) this.loading.delete(key);
1017
+ });
1018
+ this.loading.set(key, next);
1019
+ return next;
1020
+ }
1021
+
1022
+ /**
1023
+ * After a change OMP has already applied: start a fresh read (never one that began before the
1024
+ * change), and if it fails drop the cached snapshot so the next read goes to OMP.
1025
+ */
1026
+ private async refreshAfterChange(store: OmpStore | undefined): Promise<void> {
1027
+ const key = storeKey(store);
1028
+ try {
1029
+ await this.load(store, true);
1030
+ } catch {
1031
+ this.snapshots.delete(key);
1032
+ }
1033
+ }
1034
+
1035
+ private async runLogin(
1036
+ login: LoginState,
1037
+ command: OmpCommand,
1038
+ store: OmpStore | undefined,
1039
+ ): Promise<void> {
1040
+ try {
1041
+ const rpc = new OmpRpcProcess(command, (frame) => this.onLoginUiRequest(login, frame));
1042
+ if (!isOpen(login.step)) {
1043
+ rpc.close();
1044
+ return;
1045
+ }
1046
+ login.process = rpc;
1047
+ await rpc.request({ type: "login", providerId: login.provider }, LOGIN_TIMEOUT_MS);
1048
+ if (!isOpen(login.step)) return;
1049
+ login.step = "verifying";
1050
+ login.codePrompt = null;
1051
+ // refreshAfterChange never throws, so a failed refresh cannot mark a stored login failed;
1052
+ // settling after it means the listing already shows the new login when "done" appears.
1053
+ await this.refreshAfterChange(store);
1054
+ this.settle(login, "done", null);
1055
+ } catch (error) {
1056
+ if (isOpen(login.step)) this.settle(login, "failed", publicMessage(error));
1057
+ }
1058
+ }
1059
+
1060
+ private onLoginUiRequest(login: LoginState, frame: Frame): void {
1061
+ if (!isOpen(login.step)) return;
1062
+ if (frame.method === "open_url") {
1063
+ login.url = frame.url ?? null;
1064
+ login.instructions = frame.instructions ?? null;
1065
+ login.step = "waiting";
1066
+ } else if (frame.method === "input" && frame.id) {
1067
+ // Asked again after a paste: OMP did not accept what was pasted.
1068
+ if (login.step === "verifying") {
1069
+ login.message = "OMP didn't accept that. Paste the code or the full redirect URL again";
1070
+ }
1071
+ login.promptId = frame.id;
1072
+ login.codePrompt = frame.title ?? "Paste the authorization code";
1073
+ login.step = "waiting";
1074
+ } else if (frame.method === "notify" && frame.message) {
1075
+ login.message = frame.message;
1076
+ }
1077
+ }
1078
+
1079
+ private settle(login: LoginState, step: OmpLoginStep, message: string | null): void {
1080
+ login.step = step;
1081
+ login.message = message;
1082
+ login.codePrompt = null;
1083
+ login.promptId = null;
1084
+ login.endedAt = Date.now();
1085
+ login.process?.close();
1086
+ login.process = null;
1087
+ }
1088
+ }