@modelprofile.com/authswitch 3.3.0 → 5.0.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.
Files changed (87) hide show
  1. package/dist_ts/00_commitinfo_data.js +3 -3
  2. package/dist_ts/accounts.d.ts +52 -15
  3. package/dist_ts/accounts.js +110 -27
  4. package/dist_ts/classes.accountlist.d.ts +0 -25
  5. package/dist_ts/classes.accountlist.js +2 -216
  6. package/dist_ts/classes.claudecodeharness.d.ts +81 -2
  7. package/dist_ts/classes.claudecodeharness.js +208 -14
  8. package/dist_ts/classes.claudecodelocks.d.ts +38 -0
  9. package/dist_ts/classes.claudecodelocks.js +118 -0
  10. package/dist_ts/classes.claudestatus.d.ts +15 -2
  11. package/dist_ts/classes.claudestatus.js +100 -83
  12. package/dist_ts/classes.claudetokenrefresh.d.ts +32 -0
  13. package/dist_ts/classes.claudetokenrefresh.js +77 -0
  14. package/dist_ts/classes.cli.d.ts +14 -7
  15. package/dist_ts/classes.cli.js +126 -66
  16. package/dist_ts/classes.codexharness.d.ts +4 -0
  17. package/dist_ts/classes.codexharness.js +5 -1
  18. package/dist_ts/classes.codexstatus.d.ts +7 -2
  19. package/dist_ts/classes.codexstatus.js +49 -21
  20. package/dist_ts/classes.credentialstore.d.ts +43 -2
  21. package/dist_ts/classes.credentialstore.js +60 -13
  22. package/dist_ts/classes.fileharness.d.ts +45 -21
  23. package/dist_ts/classes.fileharness.js +64 -26
  24. package/dist_ts/classes.limits.d.ts +46 -7
  25. package/dist_ts/classes.limits.js +94 -36
  26. package/dist_ts/classes.listrenderer.d.ts +17 -0
  27. package/dist_ts/classes.listrenderer.js +313 -0
  28. package/dist_ts/classes.login.d.ts +1 -1
  29. package/dist_ts/classes.login.js +1 -1
  30. package/dist_ts/classes.opencodeharness.d.ts +4 -0
  31. package/dist_ts/classes.opencodeharness.js +8 -4
  32. package/dist_ts/classes.operations.js +3 -2
  33. package/dist_ts/classes.tui.js +4 -3
  34. package/dist_ts/classes.watch.d.ts +108 -0
  35. package/dist_ts/classes.watch.js +219 -0
  36. package/dist_ts/classes.watchlock.d.ts +33 -0
  37. package/dist_ts/classes.watchlock.js +118 -0
  38. package/dist_ts/claudehttp.d.ts +39 -0
  39. package/dist_ts/claudehttp.js +83 -0
  40. package/dist_ts/cliargs.d.ts +36 -0
  41. package/dist_ts/cliargs.js +60 -0
  42. package/dist_ts/consoletable.d.ts +21 -0
  43. package/dist_ts/consoletable.js +63 -0
  44. package/dist_ts/helpers.d.ts +7 -0
  45. package/dist_ts/helpers.js +16 -1
  46. package/dist_ts/index.d.ts +3 -0
  47. package/dist_ts/index.js +4 -1
  48. package/dist_ts/interfaces.harness.d.ts +60 -11
  49. package/dist_ts/interfaces.list.d.ts +3 -1
  50. package/dist_ts/plugins.d.ts +7 -0
  51. package/dist_ts/plugins.js +6 -1
  52. package/dist_ts/ratelimit.d.ts +8 -0
  53. package/dist_ts/ratelimit.js +13 -0
  54. package/dist_ts/watchpolicy.d.ts +44 -0
  55. package/dist_ts/watchpolicy.js +82 -0
  56. package/package.json +5 -3
  57. package/readme.md +349 -115
  58. package/ts/00_commitinfo_data.ts +3 -3
  59. package/ts/accounts.ts +122 -35
  60. package/ts/classes.accountlist.ts +2 -219
  61. package/ts/classes.claudecodeharness.ts +199 -13
  62. package/ts/classes.claudecodelocks.ts +133 -0
  63. package/ts/classes.claudestatus.ts +100 -65
  64. package/ts/classes.claudetokenrefresh.ts +85 -0
  65. package/ts/classes.cli.ts +114 -54
  66. package/ts/classes.codexharness.ts +4 -0
  67. package/ts/classes.codexstatus.ts +40 -18
  68. package/ts/classes.credentialstore.ts +78 -10
  69. package/ts/classes.fileharness.ts +76 -34
  70. package/ts/classes.limits.ts +110 -36
  71. package/ts/classes.listrenderer.ts +328 -0
  72. package/ts/classes.login.ts +1 -1
  73. package/ts/classes.opencodeharness.ts +7 -3
  74. package/ts/classes.operations.ts +2 -1
  75. package/ts/classes.tui.ts +3 -2
  76. package/ts/classes.watch.ts +263 -0
  77. package/ts/classes.watchlock.ts +100 -0
  78. package/ts/claudehttp.ts +92 -0
  79. package/ts/cliargs.ts +71 -0
  80. package/ts/consoletable.ts +62 -0
  81. package/ts/helpers.ts +14 -0
  82. package/ts/index.ts +3 -0
  83. package/ts/interfaces.harness.ts +60 -5
  84. package/ts/interfaces.list.ts +3 -1
  85. package/ts/plugins.ts +9 -0
  86. package/ts/ratelimit.ts +14 -0
  87. package/ts/watchpolicy.ts +121 -0
@@ -2,7 +2,7 @@
2
2
  * autocreated commitinfo by @push.rocks/commitinfo
3
3
  */
4
4
  export const commitinfo = {
5
- name: '@modelprofile.com/authswitch',
6
- version: '3.3.0',
7
- description: 'Manage Codex, OpenCode and Claude Code accounts with guided switching and live usage status'
5
+ name: "@modelprofile.com/authswitch",
6
+ version: "5.0.0",
7
+ description: "Manage Codex, OpenCode and Claude Code accounts with guided switching and live usage status"
8
8
  }
package/ts/accounts.ts CHANGED
@@ -1,4 +1,4 @@
1
- import type { IAccountType, IAuthHarness, IHarnessAccount, IHarnessAccountStatus, IHarnessCredentialDrift, IHarnessState, IHarnessUsageWindow } from './interfaces.harness.js';
1
+ import type { IAccountType, IAuthHarness, IHarnessAccount, IHarnessAccountStatus, IHarnessCredentialDrift, IHarnessState, IHarnessStatusOptions, IHarnessUsageWindow } from './interfaces.harness.js';
2
2
  import { plainText } from './formatting.js';
3
3
 
4
4
  export interface IAccountRow {
@@ -6,7 +6,23 @@ export interface IAccountRow {
6
6
  account: IHarnessAccount;
7
7
  status?: IHarnessAccountStatus;
8
8
  }
9
+ /** A provider window length or a whole-minute bound: `5h`, `7d`, `2m`. */
9
10
  export const duration = (secondsArg: number): string => secondsArg % 86400 === 0 ? `${secondsArg / 86400}d` : secondsArg % 3600 === 0 ? `${secondsArg / 3600}h` : `${secondsArg / 60}m`;
11
+ /** The same for a chosen duration that need not be whole minutes: `90s` reads `1m 30s`, never `1.5m`. */
12
+ export const durationText = (secondsArg: number): string => secondsArg % 60 === 0 ? duration(secondsArg)
13
+ : secondsArg < 60 ? `${secondsArg}s` : `${Math.floor(secondsArg / 60)}m ${secondsArg % 60}s`;
14
+ /** The window lengths that have a name of their own; every other length is named by its compact duration. */
15
+ const WINDOW_PERIODS: ReadonlyMap<number, string> = new Map([[18000, 'five-hour'], [86400, 'daily'], [604800, 'weekly'], [2592000, 'monthly'], [31536000, 'annual']]);
16
+ /**
17
+ * How every adapter names a usage window in a label: by the window's length alone, so `Codex weekly` and
18
+ * `Claude weekly` mean the same thing and no label repeats a provider's internal slot name. These are the
19
+ * lengths Codex names in 0.155.0 too (`five-hour`, `daily`, `weekly`, `monthly`, `annual`), and a slot a
20
+ * window arrives in says nothing about how long it is. A length with no name of its own keeps its compact
21
+ * form (`90m`), which is honest about a window this vocabulary does not know rather than rounding it.
22
+ *
23
+ * The narrow table cells stay on the compact form throughout (`5h 37% · 2h 13m`); a column is not a label.
24
+ */
25
+ export const usageWindowPeriod = (secondsArg: number): string => WINDOW_PERIODS.get(secondsArg) ?? duration(secondsArg);
10
26
  /** A countdown is a snapshot of the provider's deadline, not proof a quota has reset. */
11
27
  export const until = (timestampArg: string | null, nowArg: number): string => {
12
28
  if (timestampArg === null) return 'Not scheduled';
@@ -54,19 +70,63 @@ export const compactSince = (timestampArg: string | null, nowArg: number, unavai
54
70
  if (!Number.isFinite(elapsed)) return unavailableArg;
55
71
  return elapsed < 60000 ? '<1m' : twoUnits(elapsed);
56
72
  };
73
+ const twoDigits = (valueArg: number): string => String(valueArg).padStart(2, '0');
74
+ /**
75
+ * A timestamp in local calendar time: `2026-10-08`, or `2026-10-08 23:14` with the time. Human output never prints
76
+ * a raw ISO timestamp; an unknown or unparseable one reads as the caller's unavailable marker.
77
+ */
78
+ const localTimestamp = (timestampArg: string | null, withTimeArg: boolean, unavailableArg: string): string => {
79
+ const time = timestampArg === null ? Number.NaN : Date.parse(timestampArg);
80
+ if (!Number.isFinite(time)) return unavailableArg;
81
+ const date = new Date(time);
82
+ const day = `${date.getFullYear()}-${twoDigits(date.getMonth() + 1)}-${twoDigits(date.getDate())}`;
83
+ return withTimeArg ? `${day} ${twoDigits(date.getHours())}:${twoDigits(date.getMinutes())}` : day;
84
+ };
85
+ export const localDate = (timestampArg: string | null, unavailableArg = 'n/a'): string => localTimestamp(timestampArg, false, unavailableArg);
86
+ export const localDateTime = (timestampArg: string | null, unavailableArg = 'n/a'): string => localTimestamp(timestampArg, true, unavailableArg);
87
+ /** A moment's local time of day with seconds, `14:02:07`, for a log line whose date is implied. */
88
+ export const localTime = (timeArg: number): string => {
89
+ const date = new Date(timeArg);
90
+ return [date.getHours(), date.getMinutes(), date.getSeconds()].map(twoDigits).join(':');
91
+ };
92
+ const ISO_TIMESTAMP = /\b\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(?::\d{2}(?:\.\d+)?)?(?:Z|[+-]\d{2}:?\d{2})/g;
93
+ /** Provider text with every ISO 8601 timestamp in it rewritten as local date and time. */
94
+ export const localiseTimestamps = (textArg: string): string => textArg.replace(ISO_TIMESTAMP, match => localDateTime(match, match));
95
+
57
96
  /**
58
97
  * One sentence for a credential file that no longer holds the account the last switch wrote.
59
98
  *
60
- * It names what the file holds now and how to put the intended account back, because the usual
61
- * cause -- a harness instance that kept running through the switch and then refreshed its
62
- * in-memory login -- leaves no other trace.
63
- */
64
- export const credentialDriftNote = (harnessIdArg: string, driftArg: IHarnessCredentialDrift): string =>
65
- 'The credential file changed since the last switch (likely a running instance refreshed the previous login). '
66
- + (driftArg.currentLabel === null ? 'No login is active in that slot now. '
67
- : `It now holds ${plainText(driftArg.currentLabel)}${driftArg.currentIsSaved ? ', which is saved' : ', which is not saved'}. `)
68
- + (driftArg.expectedLabel === null ? 'Switch to the intended account again.'
69
- : `Run authswitch ${plainText(harnessIdArg)} use ${plainText(driftArg.expectedLabel)} again.`);
99
+ * It names what the file holds now and how to keep or undo that. A harness that picks up swaps live is only ever
100
+ * changed by a new login; one that does not can also have a running instance write its previous login back.
101
+ */
102
+ export const credentialDriftNote = (harnessArg: Pick<IAuthHarness, 'id' | 'liveSwap'>, driftArg: IHarnessCredentialDrift): string => {
103
+ const id = plainText(harnessArg.id);
104
+ const cause = harnessArg.liveSwap === true ? 'for example a new login' : 'for example a new login, or a running instance that wrote its previous login back';
105
+ const now = driftArg.currentLabel === null ? 'No login is active in that slot now'
106
+ : `It now holds ${plainText(driftArg.currentLabel)}, which is ${driftArg.currentIsSaved ? '' : 'not '}saved`;
107
+ const keep = driftArg.currentLabel !== null && !driftArg.currentIsSaved ? `authswitch ${id} stash --keep saves it, and ` : '';
108
+ const back = driftArg.expectedLabel === null ? 'switching to the intended account restores it' : `authswitch ${id} use ${plainText(driftArg.expectedLabel)} switches back`;
109
+ return `The active login changed outside authswitch since the last switch (${cause}). ${now}; ${keep}${back}.`;
110
+ };
111
+ /**
112
+ * The same finding as one table cell: which account was expected, what the slot holds now, and then every action
113
+ * that resolves it, one per line -- the same actions the sentence names, so the two views advise the same thing in a
114
+ * cell that has to stay narrow.
115
+ */
116
+ export const credentialDriftProblem = (harnessIdArg: string, driftArg: IHarnessCredentialDrift): string => {
117
+ const id = plainText(harnessIdArg);
118
+ const expected = driftArg.expectedLabel === null ? 'a login that is no longer saved' : plainText(driftArg.expectedLabel);
119
+ const now = driftArg.currentLabel === null ? 'none' : `${plainText(driftArg.currentLabel)} (${driftArg.currentIsSaved ? 'saved' : 'not saved'})`;
120
+ const actions = [
121
+ ...(driftArg.currentLabel !== null && !driftArg.currentIsSaved ? [`authswitch ${id} stash --keep saves it`] : []),
122
+ driftArg.expectedLabel === null ? 'switching to the intended account restores it' : `authswitch ${id} use ${plainText(driftArg.expectedLabel)} switches back`,
123
+ ];
124
+ return [`Active login changed outside authswitch: expected ${expected},`, `now ${now}`, ...actions.map(action => `— ${action}`)].join('\n');
125
+ };
126
+
127
+ /** An account as prompts and reports name it: its label, qualified by its credential slot when it has one. */
128
+ export const accountName = (accountArg: Pick<IHarnessAccount, 'label' | 'slotId'>): string =>
129
+ `${plainText(accountArg.label)}${accountArg.slotId ? ` (${plainText(accountArg.slotId)})` : ''}`;
70
130
 
71
131
  /**
72
132
  * How every view marks a plan that comes from the saved login because the provider did not confirm it: the
@@ -88,14 +148,32 @@ export const accountPlan = (rowArg: IAccountRow): string =>
88
148
  accountTypeText(rowArg.status?.summary?.subscription) ?? (rowArg.status ? 'Unavailable' : 'Loading');
89
149
  type TAccountStatusRow = Pick<IAccountRow, 'status'>;
90
150
  /**
91
- * How a single-value summary names a window among the windows it shows. An account window is named by
92
- * its period while it is the only shown account window of that period; a feature window, or an account
93
- * window sharing its period with another, is named by its own label, so no meter reads as another's.
151
+ * Whether a window among the shown ones is named by its label. An account window is named by its period while it is
152
+ * the only shown account window of that period; a feature window, or an account window sharing its period with
153
+ * another, is named by its own label, so no meter reads as another's.
154
+ */
155
+ const namedByLabel = (windowArg: IHarnessUsageWindow, shownArg: readonly IHarnessUsageWindow[]): boolean =>
156
+ windowArg.scope === 'feature' || shownArg.some(other => other !== windowArg && other.scope !== 'feature' && other.durationSeconds === windowArg.durationSeconds);
157
+ const periodName = (secondsArg: number): string => secondsArg === 604800 ? 'weekly' : duration(secondsArg);
158
+ /** How a single-value summary names a window among the windows it shows: `Weekly`, `5h`, or its label. */
159
+ export const usageWindowName = (windowArg: IHarnessUsageWindow, shownArg: readonly IHarnessUsageWindow[]): string => {
160
+ if (namedByLabel(windowArg, shownArg)) return plainText(windowArg.label);
161
+ const period = periodName(windowArg.durationSeconds);
162
+ return `${period.charAt(0).toUpperCase()}${period.slice(1)}`;
163
+ };
164
+ /**
165
+ * How every view prints a provider's usage reading: the nearest whole percent, except that a window the provider
166
+ * reports below 100% never reads as `100%` -- that is the one reading acted on as exhausted, and a window with
167
+ * capacity left must not claim it. The tables, the switch badge and the watch share this text, so none of them
168
+ * shows a different number for the same window.
94
169
  */
95
- export const usageWindowName = (windowArg: IHarnessUsageWindow, shownArg: readonly IHarnessUsageWindow[]): string =>
96
- windowArg.scope === 'feature' || shownArg.some(other => other !== windowArg && other.scope !== 'feature' && other.durationSeconds === windowArg.durationSeconds)
97
- ? plainText(windowArg.label)
98
- : windowArg.durationSeconds === 604800 ? 'Weekly' : duration(windowArg.durationSeconds);
170
+ export const usagePercentText = (usedPercentArg: number): string => {
171
+ const whole = Math.round(usedPercentArg);
172
+ return `${whole >= 100 && usedPercentArg < 100 ? 99 : whole}%`;
173
+ };
174
+ /** A shown window in one compact line: `weekly 4% · 5d 1h`, `Fable weekly 100% · 2d`. */
175
+ export const compactUsageLine = (windowArg: IHarnessUsageWindow, shownArg: readonly IHarnessUsageWindow[], nowArg: number): string =>
176
+ `${namedByLabel(windowArg, shownArg) ? plainText(windowArg.label) : periodName(windowArg.durationSeconds)} ${usagePercentText(windowArg.usedPercent)} · ${compactUntil(windowArg.resetAt, nowArg)}`;
99
177
  /** Order by scope and actual duration: a provider's primary slot need not be five hours. */
100
178
  export const orderedUsageWindows = (windowsArg: readonly IHarnessUsageWindow[] = []): IHarnessUsageWindow[] => [...windowsArg].sort((left, right) =>
101
179
  Number(left.scope === 'feature') - Number(right.scope === 'feature') ||
@@ -141,7 +219,7 @@ const badgeWindow = (windowsArg: readonly IHarnessUsageWindow[], secondsArg: num
141
219
  /**
142
220
  * What a switch activates, in one line: ` (type:Max) (5h:63%) (w:88%)`, appended to the account label.
143
221
  *
144
- * Each part is the provider's own reading, rounded to a whole percent, and is omitted when it was not
222
+ * Each part is the provider's own reading as a whole percent, and is omitted when it was not
145
223
  * reported; with no part known the badge is empty, so a missing reading never reads as zero usage.
146
224
  */
147
225
  export const accountBadge = (statusArg: IHarnessAccountStatus | undefined): string => {
@@ -151,21 +229,22 @@ export const accountBadge = (statusArg: IHarnessAccountStatus | undefined): stri
151
229
  ...(type === null ? [] : [`type:${type}`]),
152
230
  ...BADGE_WINDOWS.flatMap(([name, seconds]) => {
153
231
  const window = badgeWindow(windows, seconds);
154
- return window === undefined ? [] : [`${name}:${Math.round(window.usedPercent)}%`];
232
+ return window === undefined ? [] : [`${name}:${usagePercentText(window.usedPercent)}`];
155
233
  }),
156
234
  ].map(part => ` (${part})`).join('');
157
235
  };
158
236
  /** How many accounts' statuses are read at once, so a long account list never floods a provider. */
159
237
  const STATUS_LOOKUP_CONCURRENCY = 4;
160
238
  /**
161
- * Read-only, bounded status lookups: at most four accounts at a time, started in order, each handed the
162
- * caller's signal. A lookup that fails reports undefined; once the signal aborts, no further lookup starts.
163
- * A callback that throws rejects the call, and no other lookup starts after it.
239
+ * Bounded status lookups: at most four accounts at a time, started in order, each handed the caller's signal.
240
+ * A lookup that fails reports undefined; once the signal aborts, no further lookup starts. A callback that throws
241
+ * rejects the call, and no other lookup starts after it. No lookup activates, switches or clears a login, though an
242
+ * adapter may renew the tokens of the saved copy it reads (`IAuthHarness.readAccountStatus`).
164
243
  */
165
244
  const lookupStatuses = async (
166
245
  harnessArg: IAuthHarness,
167
246
  accountIdsArg: readonly string[],
168
- optionsArg: { signal?: AbortSignal; onStatus: (indexArg: number, statusArg: IHarnessAccountStatus | undefined) => void | Promise<void> },
247
+ optionsArg: IHarnessStatusOptions & { onStatus: (indexArg: number, statusArg: IHarnessAccountStatus | undefined) => void | Promise<void> },
169
248
  ): Promise<void> => {
170
249
  let next = 0;
171
250
  let failed = false;
@@ -173,7 +252,7 @@ const lookupStatuses = async (
173
252
  while (!failed && next < accountIdsArg.length && !optionsArg.signal?.aborted) {
174
253
  const index = next++;
175
254
  let status: IHarnessAccountStatus | undefined;
176
- try { status = await harnessArg.readAccountStatus(accountIdsArg[index], { signal: optionsArg.signal }); }
255
+ try { status = await harnessArg.readAccountStatus(accountIdsArg[index], { signal: optionsArg.signal, session: optionsArg.session }); }
177
256
  catch { status = undefined; }
178
257
  try { await optionsArg.onStatus(index, status); }
179
258
  catch (error) { failed = true; throw error; }
@@ -186,7 +265,7 @@ const ACCOUNT_BADGE_TIMEOUT_MS = 2500;
186
265
  /**
187
266
  * The badge of every named account whose status answered before one shared deadline.
188
267
  *
189
- * Read-only and never fatal: a switch must not wait on a provider past this deadline, nor fail because
268
+ * Never fatal, and it never changes which account is in use: a switch must not wait on a provider past this deadline, nor fail because
190
269
  * usage could not be read, so a lookup that fails or misses the deadline contributes no badge and the
191
270
  * caller shows the label alone. At the deadline every lookup still running is cancelled, so no request
192
271
  * outlives the call and keeps the command from exiting.
@@ -212,22 +291,30 @@ export const readAccountBadges = async (
212
291
  export const accountState = (rowArg: IAccountRow): string => `${rowArg.account.isActive ? '* active, ' : ''}${rowArg.account.isStashed ? 'saved' : 'not saved'}`;
213
292
  export const accountDetails = (rowArg: IAccountRow): string => [
214
293
  plainText(rowArg.account.label), accountState(rowArg),
215
- ...(rowArg.account.savedAt ? ['Saved: ' + plainText(rowArg.account.savedAt)] : []),
294
+ ...(rowArg.account.savedAt ? ['Saved: ' + localDateTime(rowArg.account.savedAt)] : []),
216
295
  ...rowArg.account.details.map(plainText),
217
- ...(rowArg.status?.facts.map(factArg => `${plainText(factArg.label)}: ${plainText(factArg.value)}`) ?? ['Loading account status…']),
296
+ ...(rowArg.status?.facts.map(factArg => `${plainText(factArg.label)}: ${localiseTimestamps(plainText(factArg.value))}`) ?? ['Loading account status…']),
218
297
  ...(rowArg.status?.problems.map(problemArg => `Unavailable: ${plainText(problemArg)}`) ?? []),
219
298
  ].join('\n');
220
299
 
221
- /** Read-only, bounded parallel status lookup. No account is switched to inspect it; the signal cancels lookups in flight. */
222
- export const readAccountRows = async (
223
- harnessArg: IAuthHarness,
224
- optionsArg: { signal?: AbortSignal; onUpdate?: (rowsArg: IAccountRow[], stateArg: IHarnessState) => void | Promise<void> } = {},
225
- ): Promise<{ rows: IAccountRow[]; state: IHarnessState }> => {
300
+ export interface IAccountRowsOptions extends IHarnessStatusOptions {
301
+ onUpdate?: (rowsArg: IAccountRow[], stateArg: IHarnessState) => void | Promise<void>;
302
+ /** Which accounts' statuses to read; every account by default. A row that is not read keeps no status. */
303
+ lookup?: (accountArg: IHarnessAccount) => boolean;
304
+ }
305
+
306
+ /**
307
+ * Bounded parallel status lookup. No account is activated, switched or cleared to inspect it -- an adapter may renew
308
+ * the tokens of the saved copy it reads, and nothing else; the signal cancels lookups in flight, and a session lets
309
+ * the adapters reuse slow-changing lookups across repeated reads.
310
+ */
311
+ export const readAccountRows = async (harnessArg: IAuthHarness, optionsArg: IAccountRowsOptions = {}): Promise<{ rows: IAccountRow[]; state: IHarnessState }> => {
226
312
  const state = await harnessArg.readState();
227
313
  const rows = state.accounts.map(account => ({ harness: harnessArg, account } as IAccountRow));
314
+ const read = rows.filter(row => optionsArg.lookup?.(row.account) ?? true);
228
315
  await optionsArg.onUpdate?.(rows, state);
229
- await lookupStatuses(harnessArg, rows.map(row => row.account.id), { signal: optionsArg.signal, onStatus: async (index, status) => {
230
- rows[index].status = status ?? { facts: [], problems: ['Could not read account status.'] };
316
+ await lookupStatuses(harnessArg, read.map(row => row.account.id), { signal: optionsArg.signal, session: optionsArg.session, onStatus: async (index, status) => {
317
+ read[index].status = status ?? { facts: [], problems: ['Could not read account status.'] };
231
318
  if (!optionsArg.signal?.aborted) await optionsArg.onUpdate?.(rows, state);
232
319
  } });
233
320
  return { rows, state };
@@ -1,12 +1,6 @@
1
- import * as plugins from './plugins.js';
2
- import { accountQuotaSummary, accountTypeText, orderedUsageWindows, readAccountRows, duration, until } from './accounts.js';
3
- import type { IAuthHarness, IHarnessAccountStatus, IHarnessStatusFact } from './interfaces.harness.js';
1
+ import { readAccountRows } from './accounts.js';
2
+ import type { IAuthHarness, IHarnessAccountStatus } from './interfaces.harness.js';
4
3
  import type { IAccountList, IHarnessAccountList } from './interfaces.list.js';
5
- import { bold, dim, orange, plainText } from './formatting.js';
6
-
7
- type TListedAccount = IHarnessAccountList['accounts'][number];
8
- type TNamedAccount = TListedAccount & { name: string };
9
- interface IDisplayFact { account: number; label: string; value: string; }
10
4
 
11
5
  /** Allowlist the public data contract: never serialize a harness or its credential-bearing internals. */
12
6
  const publicStatus = (statusArg: IHarnessAccountStatus): IHarnessAccountStatus => {
@@ -50,214 +44,3 @@ export const readAccountList = async (harnessesArg: IAuthHarness[]): Promise<IAc
50
44
  harnesses,
51
45
  };
52
46
  };
53
-
54
- export const consoleWidth = (): number => process.stdout.columns ?? 100;
55
- export const consoleHeading = (textArg: string): void => { process.stdout.write(`\n${bold(textArg)}\n`); };
56
-
57
- /**
58
- * One table implementation for every command, including the label-per-line fallback on narrow terminals.
59
- *
60
- * `groupsArg` is smartconsole's optional visual grouping: a divider between runs of consecutive rows with
61
- * different keys, and a colour line along the left edge per run. Keys are identities, never display labels,
62
- * and the caller orders the rows so that every group is one run. Below 40 columns the fallback separates
63
- * divider runs with one dim rule line; it has no left edge, so it draws no colour line, and it repeats a
64
- * spanning cell on every row it covers. A column's `render` content is what both layouts show.
65
- */
66
- export const consoleTable = async <TRow>(
67
- outArg: plugins.smartconsole.SmartConsole,
68
- rowsArg: TRow[],
69
- columnsArg: plugins.smartconsole.IBackendTableColumn<TRow>[],
70
- groupsArg?: NoInfer<plugins.smartconsole.IBackendTableGroups<TRow>>,
71
- ): Promise<void> => {
72
- if (!rowsArg.length) return;
73
- const width = consoleWidth();
74
- if (width < 40) {
75
- // smartconsole's run semantics: null and undefined are the same key.
76
- const dividerKeys = rowsArg.map(row => groupsArg?.divider?.(row) ?? null);
77
- const rule = ` ${dim('─'.repeat(Math.max(1, width - 4)))}\n\n`;
78
- const content = (column: plugins.smartconsole.IBackendTableColumn<TRow>, row: TRow): string => column.render
79
- ? plugins.smartconsole.color.plain(column.render(row)) : String(column.value(row) ?? 'Unavailable');
80
- rowsArg.forEach((row, index) => {
81
- if (index > 0 && dividerKeys[index] !== dividerKeys[index - 1]) process.stdout.write(rule);
82
- process.stdout.write(columnsArg.map(column => ` ${column.title}: ${content(column, row).replace(/\n/g, '\n ')}`).join('\n') + '\n\n');
83
- });
84
- return;
85
- }
86
- await outArg.table(rowsArg, {
87
- columns: columnsArg, overflow: 'wrap', groups: groupsArg,
88
- theme: { header: { bold: true, foreground: 'cyan' }, border: { dim: true } },
89
- });
90
- };
91
-
92
- /** List tables that repeat one account across rows divide it from the next account by its id. */
93
- const accountDividers: plugins.smartconsole.IBackendTableGroups<{ accountId: string | null }> = { divider: row => row.accountId };
94
-
95
- /**
96
- * Names every account of one harness by its label, numbering each later account that repeats a label
97
- * (`alice@example.com (2)`), so all tables name an account alike and the metric columns stay distinct.
98
- */
99
- const nameAccounts = (accountsArg: TListedAccount[]): TNamedAccount[] => {
100
- const labels = accountsArg.map(account => plainText(account.label));
101
- const taken = new Set(labels);
102
- return accountsArg.map((account, index) => {
103
- const label = labels[index];
104
- let name = label;
105
- if (labels.indexOf(label) < index) {
106
- for (let ordinal = 2; taken.has(name); ordinal++) name = `${label} (${ordinal})`;
107
- taken.add(name);
108
- }
109
- return { ...account, name };
110
- });
111
- };
112
-
113
- /** Shared, provider-independent list presentation. Adapters supply grouping metadata. */
114
- export class AccountListRenderer {
115
- constructor(private readonly out: plugins.smartconsole.SmartConsole) {}
116
- private get width(): number { return consoleWidth(); }
117
- private heading(textArg: string): void { consoleHeading(textArg); }
118
-
119
- public async render(listArg: IAccountList): Promise<void> {
120
- const now = Date.parse(listArg.generatedAt);
121
- if (!listArg.harnesses.length) process.stdout.write('No harnesses registered.\n');
122
- for (const harness of listArg.harnesses) {
123
- this.heading(plainText(harness.label));
124
- if (harness.problems.length) {
125
- for (const problem of harness.problems) process.stdout.write(`${orange('Unavailable')}: ${plainText(problem)}\n`);
126
- continue;
127
- }
128
- if (!harness.accounts.length) {
129
- process.stdout.write(`${dim(plainText(harness.saveUnavailableReason ?? 'No known accounts. ' + harness.loginHint))}\n`);
130
- continue;
131
- }
132
- const accounts = nameAccounts(harness.accounts);
133
- await this.overview(accounts, now);
134
- const schedules = accounts.flatMap(account => orderedUsageWindows(account.status.summary?.usageWindows).map(window => ({ accountId: account.id, account: account.name, window })));
135
- for (const feature of [false, true]) {
136
- const scopedSchedules = schedules.filter(row => (row.window.scope === 'feature') === feature);
137
- if (!scopedSchedules.length) continue;
138
- this.heading(feature ? 'Feature-specific limits' : 'Usage & reset schedule');
139
- await consoleTable(this.out, scopedSchedules, [
140
- { key: 'account', title: 'Account', value: row => row.account },
141
- { key: 'window', title: 'Window', value: row => `${plainText(row.window.label)} (${duration(row.window.durationSeconds)})` },
142
- { key: 'usage', title: 'Usage', value: row => `${row.window.usedPercent}% used\n${Math.max(0, 100 - row.window.usedPercent)}% left` },
143
- { key: 'reset', title: 'Reset in', value: row => until(row.window.resetAt, now) },
144
- ], accountDividers);
145
- }
146
- const resets = accounts.flatMap(account => (account.status.summary?.resets?.details ?? []).map(reset => ({ accountId: account.id, account: account.name, reset })));
147
- if (resets.length) {
148
- this.heading('Earned reset details');
149
- await consoleTable(this.out, resets, [
150
- { key: 'account', title: 'Account', value: row => row.account },
151
- { key: 'kind', title: 'Type', value: row => plainText(row.reset.kind) },
152
- { key: 'status', title: 'Status', value: row => plainText(row.reset.status) },
153
- { key: 'expiry', title: 'Expires (UTC)', value: row => row.reset.expiresAt === null ? 'Not reported' : plainText(row.reset.expiresAt).replace('T', '\n').replace('.000Z', '').replace(/Z$/, '') },
154
- ], accountDividers);
155
- }
156
- const groups = new Map<string, IDisplayFact[]>();
157
- const add = (section: string, fact: IDisplayFact) => { const group = groups.get(section) ?? []; group.push(fact); groups.set(section, group); };
158
- accounts.forEach((account, index) => {
159
- for (const fact of account.status.facts) {
160
- if (!this.covered(fact, account.status)) add(plainText(fact.section ?? 'Additional information'), { account: index, label: plainText(fact.label), value: plainText(fact.value) });
161
- }
162
- });
163
- for (const [section, facts] of groups) await this.facts(section, facts, accounts);
164
- const saved = accounts.flatMap((account, index) => [
165
- ...(account.savedAt ? [{ account: index, label: 'Saved (UTC)', value: plainText(account.savedAt) }] : []),
166
- ...account.details.map((detail, detailIndex) => ({ account: index, label: `Note ${detailIndex + 1}`, value: plainText(detail) })),
167
- ]);
168
- await this.facts('Saved logins', saved, accounts);
169
- const issues: { accountId: string | null; account: string; issue: string }[] = accounts.flatMap(account =>
170
- account.status.problems.map(problem => ({ accountId: account.id, account: account.name, issue: plainText(problem) })));
171
- if (harness.saveUnavailableReason) issues.push({ accountId: null, account: 'Harness', issue: plainText(harness.saveUnavailableReason) });
172
- if (issues.length) {
173
- this.heading('Availability & actions');
174
- await consoleTable(this.out, issues, [
175
- { key: 'account', title: 'Account', value: row => row.account },
176
- { key: 'issue', title: 'Unavailable / action needed', value: row => row.issue },
177
- ], accountDividers);
178
- }
179
- }
180
- }
181
-
182
- private async overview(accountsArg: TNamedAccount[], nowArg: number): Promise<void> {
183
- const rows = accountsArg;
184
- const state = (account: TListedAccount) => `${account.isActive ? '* active\n' : ''}${account.isStashed ? 'saved' : 'not saved'}${account.status.problems.length ? '\n! partial status' : ''}`;
185
- const plan = (account: TListedAccount) => accountTypeText(account.status.summary?.subscription) ?? 'Unavailable';
186
- const billing = (account: TListedAccount) => {
187
- const info = account.status.summary?.billing;
188
- if (!info) return 'Unavailable';
189
- const dates = [
190
- ...(info.renewsAt ? [`${info.autoRenew === true ? 'Renews' : 'Renewal boundary'}: ${plainText(info.renewsAt)}`] : []),
191
- ...(info.cancelsAt ? [`Cancels: ${plainText(info.cancelsAt)}`] : []),
192
- ...(info.expiresAt ? [`Expires: ${plainText(info.expiresAt)}`] : []),
193
- ];
194
- return [...(info.hasActiveSubscription === undefined ? [] : [info.hasActiveSubscription ? 'Subscription active' : 'No active subscription']),
195
- info.autoRenew === true ? 'Auto-renew on' : info.autoRenew === false ? 'Auto-renew off' : 'Auto-renew unknown', ...dates,
196
- ...(!dates.length ? ['Date unavailable'] : [])].join('\n');
197
- };
198
- const resets = (account: TListedAccount) => account.status.summary?.resets === undefined ? 'Unavailable' : String(account.status.summary.resets.available);
199
- const usage = (account: TListedAccount) => accountQuotaSummary(account, nowArg);
200
- const columns: plugins.smartconsole.IBackendTableColumn<typeof rows[number]>[] = [
201
- { key: 'account', title: 'Account', value: row => row.name, style: row => ({ bold: row.isActive }) },
202
- ];
203
- if (this.width >= 100) columns.push(
204
- { key: 'state', title: 'Login', value: state, style: row => ({ foreground: row.isStashed ? 'green' : 'orange' }) },
205
- { key: 'plan', title: 'Plan', value: plan },
206
- { key: 'usage', title: 'Usage / reset', value: usage },
207
- { key: 'resets', title: 'Resets', value: resets, align: 'right' },
208
- );
209
- if (this.width >= 120) columns.splice(3, 0, { key: 'billing', title: 'Renewal / cancellation', value: billing });
210
- else if (this.width >= 100) columns[2] = { key: 'plan', title: 'Plan / billing', value: row => `${plan(row)}\n${row.status.summary?.billing ? billing(row) : 'Billing unavailable'}` };
211
- else if (this.width >= 60) columns.push(
212
- { key: 'login', title: 'Login / plan', value: row => `${state(row)}\n${plan(row)}\n${row.status.summary?.billing ? billing(row) : 'Billing unavailable'}` },
213
- { key: 'usage', title: 'Usage / resets', value: row => `${usage(row)}\nEarned resets: ${resets(row)}` },
214
- );
215
- else columns.push({ key: 'status', title: 'Status', value: row => `${state(row)}\nPlan: ${plan(row)}\nBilling: ${billing(row)}\nUsage: ${usage(row)}\nEarned resets: ${resets(row)}` });
216
- await consoleTable(this.out, rows, columns);
217
- }
218
-
219
- private covered(factArg: IHarnessStatusFact, statusArg: IHarnessAccountStatus): boolean {
220
- const summary = statusArg.summary;
221
- if (!summary) return false;
222
- switch (factArg.summaryKey) {
223
- case 'subscription': return summary.subscription !== undefined;
224
- case 'billing': return summary.billing !== undefined;
225
- case 'usageWindows': return summary.usageWindows !== undefined;
226
- case 'resets': return summary.resets !== undefined;
227
- case 'resetDetails': return summary.resets?.details !== undefined;
228
- default: return false;
229
- }
230
- }
231
-
232
- /** Compare like metrics across accounts, keeping duplicate labels as separate rows. */
233
- private async facts(titleArg: string, factsArg: IDisplayFact[], accountsArg: TNamedAccount[]): Promise<void> {
234
- if (!factsArg.length) return;
235
- this.heading(titleArg);
236
- const valueBudget = Math.max(10, Math.min(40, Math.max(...factsArg.map(fact => Math.max(fact.value.length, accountsArg[fact.account].name.length))) + 3));
237
- const perPage = Math.max(1, Math.min(6, Math.floor((this.width - 30) / valueBudget)));
238
- const accountIndices = accountsArg.map((_, index) => index).filter(index => factsArg.some(fact => fact.account === index));
239
- for (let start = 0; start < accountIndices.length; start += perPage) {
240
- const indices = accountIndices.slice(start, start + perPage);
241
- const metrics = new Map<string, { label: string; values: Map<number, string> }>();
242
- const occurrences = new Map<string, number>();
243
- for (const fact of factsArg.filter(fact => indices.includes(fact.account))) {
244
- const occurrenceKey = JSON.stringify([fact.account, fact.label]);
245
- const occurrence = occurrences.get(occurrenceKey) ?? 0;
246
- occurrences.set(occurrenceKey, occurrence + 1);
247
- const key = JSON.stringify([fact.label, occurrence]);
248
- const metric = metrics.get(key) ?? { label: fact.label, values: new Map<number, string>() };
249
- metric.values.set(fact.account, fact.value);
250
- metrics.set(key, metric);
251
- }
252
- if (this.width < 40) {
253
- for (const index of indices) {
254
- process.stdout.write(` Account: ${accountsArg[index].name}\n`);
255
- for (const metric of metrics.values()) if (metric.values.has(index)) process.stdout.write(` - ${metric.label}: ${metric.values.get(index)}\n`);
256
- }
257
- } else await consoleTable(this.out, [...metrics.values()], [
258
- { key: 'metric', title: 'Metric', value: row => row.label },
259
- ...indices.map(index => ({ key: String(index), title: accountsArg[index].name, value: (row: { values: Map<number, string> }) => row.values.get(index) ?? 'Not reported' })),
260
- ]);
261
- }
262
- }
263
- }