@modelprofile.com/authswitch 6.1.0 → 6.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.
@@ -70,7 +70,7 @@ export class CodexPreuse {
70
70
  } catch {
71
71
  throw new PreuseError(requestStarted
72
72
  ? 'Preuse did not complete. Tokens may already have been consumed; no automatic retry was made. Check the account status before trying again.'
73
- : 'Preuse was cancelled before the prompt was sent.');
73
+ : 'Preuse was cancelled before the prompt was sent.', requestStarted);
74
74
  }
75
75
  }
76
76
  }
@@ -6,6 +6,7 @@ import type {
6
6
  THarnessName,
7
7
  } from './interfaces.js';
8
8
  import { writeSecretFileAtomically } from './helpers.js';
9
+ import { codexIdentityFromRaw } from './classes.codexauth.js';
9
10
 
10
11
  const AUTH_FILE_NAME = 'auth.json';
11
12
  const META_FILE_NAME = 'stash.json';
@@ -105,6 +106,27 @@ export class StashStore {
105
106
  return entry;
106
107
  }
107
108
 
109
+ /**
110
+ * Replaces the credential of an existing stash and leaves its metadata exactly as it is.
111
+ *
112
+ * Codex refreshes the login it is running on its own schedule, so a saved copy of that login holds older
113
+ * tokens until something writes the rotation back. Doing so is an update of one account's credential, not a
114
+ * new save: the record keeps its account, its enrollments and the moment it was saved, which `write()` would
115
+ * stamp anew. The credential must belong to the account the metadata names -- the same guard `write()`
116
+ * applies -- so a mirror can never move one account's login into another account's record.
117
+ */
118
+ public replaceAuth(emailArg: string, rawAuthArg: string): void {
119
+ const meta = this.readMeta(emailArg);
120
+ if (!meta) {
121
+ throw new Error(`no stash for "${emailArg}" whose credential could be replaced`);
122
+ }
123
+ const identity = codexIdentityFromRaw(rawAuthArg);
124
+ if (!identity || identity.email !== meta.email || identity.accountId !== meta.accountId || identity.kind !== meta.kind) {
125
+ throw new Error('the credential does not belong to the account this stash holds; refusing to replace it');
126
+ }
127
+ writeSecretFileAtomically(plugins.path.join(this.entryDir(emailArg), AUTH_FILE_NAME), rawAuthArg);
128
+ }
129
+
108
130
  /**
109
131
  * Reads a stash back and confirms it matches what was meant to be written.
110
132
  * Callers use this before clearing the active credential, so a stash is only
package/ts/classes.tui.ts CHANGED
@@ -1,10 +1,16 @@
1
1
  import * as plugins from './plugins.js';
2
- import type { IAuthHarness, IHarnessOutcome, IHarnessProcess, IHarnessState, IHarnessStopOutcome } from './interfaces.harness.js';
2
+ import type { IAuthHarness, IHarnessAccount, IHarnessOutcome, IHarnessProcess, IHarnessState, IHarnessStopOutcome } from './interfaces.harness.js';
3
3
  import { accountBadge, accountDetails, accountPlan, accountQuotaSummary, accountResets, accountState, accountUsageWindows, usageWindowName, until, readAccountRows, type IAccountRow } from './accounts.js';
4
+ import { defaultPreusePrompt, preuseAccounts, preuseCountsText, preuseTargets, type TPreuseAccountResult } from './preuse.js';
4
5
  import { plainText } from './formatting.js';
5
6
  import { AuthSwitchOperations, authSwitchMutationReplacesLogin, type TAuthSwitchMutation } from './classes.operations.js';
6
7
  import { describeHarnessProcesses, describeStopOutcome } from './classes.harnessprocesses.js';
7
8
 
9
+ /** One account's preuse result, as the dashboard's activity log and footer report it. */
10
+ const preuseResultLine = (resultArg: TPreuseAccountResult): string => resultArg.outcome === 'completed'
11
+ ? `${plainText(resultArg.account.label)}: completed with ${plainText(resultArg.result.model)}, ${resultArg.result.totalTokens ?? 'unreported'} tokens.`
12
+ : `${plainText(resultArg.account.label)}: ${resultArg.reason}`;
13
+
8
14
  /** Owns account-management actions; terminal rendering and interaction belong to smartconsole. */
9
15
  export class AuthSwitchTui {
10
16
  constructor(private readonly harnesses: readonly IAuthHarness[], private readonly out: plugins.smartconsole.SmartConsole, private readonly operations = new AuthSwitchOperations()) {}
@@ -126,6 +132,30 @@ export class AuthSwitchTui {
126
132
  await refresh(screen);
127
133
  if (showOutcome(outcome)) ui.logs.append(`Now active: ${plainText(target.label)}${badge}`);
128
134
  };
135
+ /**
136
+ * Send one preuse prompt through each of these accounts, after one confirmation that names the cost.
137
+ *
138
+ * The prompt consumes the account's own quota, so nothing is sent before consent, the accounts run
139
+ * one at a time through the shared runner, and the footer follows the run account by account. Closing
140
+ * the dashboard aborts it before the next account starts. Nothing is switched, saved or written.
141
+ */
142
+ const preuse = async (screen: plugins.smartconsole.ITuiContext, accountsArg: readonly IHarnessAccount[]): Promise<void> => {
143
+ if (!harness.preuseAccount) { footer.setText(`${plainText(harness.label)} does not support preuse.`); return; }
144
+ if (!accountsArg.length) { footer.setText('Select an account to preuse.'); return; }
145
+ const message = accountsArg.length === 1
146
+ ? `Send one preuse prompt through ${plainText(accountsArg[0].label)}? This consumes its quota.`
147
+ : `Send one preuse prompt through each of these ${accountsArg.length} ${plainText(harness.label)} accounts? This consumes quota on every one of them.`;
148
+ if (!await screen.confirm(message, { confirmLabel: 'Preuse' })) return;
149
+ if (screen.signal.aborted) return;
150
+ const summary = await preuseAccounts(harness, accountsArg, { prompt: defaultPreusePrompt, signal: screen.signal }, event => {
151
+ if (event.kind === 'started') footer.setText(`Preusing ${plainText(event.account.label)} (${event.index + 1}/${event.total})…`);
152
+ else { const line = preuseResultLine(event.result); ui.logs.append(line); footer.setText(line); }
153
+ void screen.invalidate();
154
+ });
155
+ // The prompts moved usage and reset deadlines, so the table is read again before the counts are shown.
156
+ await refresh(screen);
157
+ footer.setText(`Preuse: ${preuseCountsText(summary)}.`);
158
+ };
129
159
  const remove = async (screen: plugins.smartconsole.ITuiContext): Promise<void> => {
130
160
  const selected = table.selected;
131
161
  if (!selected || (!selected.account.isStashed && selected.account.savedAt === null)) { footer.setText('Select an account with a saved copy.'); return; }
@@ -156,7 +186,7 @@ export class AuthSwitchTui {
156
186
  return ui.column([
157
187
  ui.text('authswitch · account management', { height: 1 }),
158
188
  this.harnesses.length > 1 ? ui.row([ui.panel('Harnesses', harnessTable, { width: 23 }), accountView]) : accountView,
159
- ui.text('Enter switch · a save · c save+clear · d remove · r refresh · g diagnose · Tab focus · q quit', { height: 2 }),
189
+ ui.text(`Enter switch · a save · c save+clear · d remove${harness.preuseAccount ? ' · p preuse · P preuse all' : ''} · r refresh · g diagnose · Tab focus · q quit`, { height: 2 }),
160
190
  footer,
161
191
  ]);
162
192
  },
@@ -167,6 +197,13 @@ export class AuthSwitchTui {
167
197
  a: screen => perform(screen, () => save(screen, true)),
168
198
  c: screen => perform(screen, () => save(screen, false)),
169
199
  d: screen => perform(screen, () => remove(screen)),
200
+ // The key map is fixed for the session while the harness selector can change the harness, so both
201
+ // preuse keys are always bound and the action itself reports a harness that does not support it.
202
+ p: screen => perform(screen, async () => {
203
+ const selected = table.selected?.account.id;
204
+ await preuse(screen, preuseTargets((await harness.readState()).accounts).filter(account => account.id === selected));
205
+ }),
206
+ P: screen => perform(screen, async () => { await preuse(screen, preuseTargets((await harness.readState()).accounts)); }),
170
207
  g: screen => perform(screen, async () => { showOutcome(await harness.diagnose()); }),
171
208
  },
172
209
  });
package/ts/preuse.ts CHANGED
@@ -1,9 +1,19 @@
1
- import type { IHarnessPreuseOptions } from './interfaces.harness.js';
1
+ import { orderedUsageWindows } from './accounts.js';
2
+ import type { IAuthHarness, IHarnessAccount, IHarnessPreuseOptions, IHarnessPreuseResult, IHarnessUsageWindow } from './interfaces.harness.js';
2
3
 
3
4
  export const defaultPreusePrompt = 'Write 2000 words about strawberries.';
4
5
 
5
- /** Only fixed local messages may cross the inference error boundary. */
6
- export class PreuseError extends Error {}
6
+ /**
7
+ * Only fixed local messages may cross the inference error boundary.
8
+ *
9
+ * `requestStarted` says whether the prompt may already have reached the provider. False is a refusal that
10
+ * sent nothing -- an unsupported login, a missing credential, a model catalog that could not be read before
11
+ * the prompt -- so the account's quota is untouched. True, and any error that is not a `PreuseError` at all,
12
+ * means tokens may have been consumed, and such a request is never repeated automatically.
13
+ */
14
+ export class PreuseError extends Error {
15
+ constructor(messageArg: string, public readonly requestStarted = false) { super(messageArg); }
16
+ }
7
17
 
8
18
  export const validatePreuseOptions = (optionsArg: IHarnessPreuseOptions): void => {
9
19
  if (typeof optionsArg.prompt !== 'string' || !optionsArg.prompt.trim() || Buffer.byteLength(optionsArg.prompt, 'utf8') > 16_384) {
@@ -13,3 +23,131 @@ export const validatePreuseOptions = (optionsArg: IHarnessPreuseOptions): void =
13
23
  throw new PreuseError('The preuse model must be a valid model identifier of at most 128 characters.');
14
24
  }
15
25
  };
26
+
27
+ /**
28
+ * What one account's turn in a run did.
29
+ *
30
+ * `skipped` is a refusal that sent nothing and consumed nothing, with the reason the adapter stated.
31
+ * `failed` and `interrupted` may both have consumed tokens, so neither is ever retried by the runner.
32
+ */
33
+ export type TPreuseOutcome = 'completed' | 'skipped' | 'failed' | 'interrupted';
34
+
35
+ /**
36
+ * The reset schedule read after a prompt completed.
37
+ *
38
+ * `reported` carries what the provider answered, which may be no window at all; `unavailable` is a lookup
39
+ * that failed, and `notRead` is a run the user interrupted before it asked. None of them says anything
40
+ * about the completed prompt, which is never repeated because its schedule could not be confirmed.
41
+ */
42
+ export type TPreuseSchedule =
43
+ | { kind: 'reported'; windows: readonly IHarnessUsageWindow[] }
44
+ | { kind: 'unavailable' }
45
+ | { kind: 'notRead' };
46
+
47
+ export type TPreuseAccountResult =
48
+ | { account: IHarnessAccount; outcome: 'completed'; result: IHarnessPreuseResult; schedule: TPreuseSchedule }
49
+ | { account: IHarnessAccount; outcome: Exclude<TPreuseOutcome, 'completed'>; reason: string };
50
+
51
+ /** One account starting, and that account's result. A run reports nothing else, and never the generated prose. */
52
+ export type TPreuseRunEvent =
53
+ | { kind: 'started'; index: number; total: number; account: IHarnessAccount }
54
+ | { kind: 'finished'; index: number; total: number; result: TPreuseAccountResult };
55
+
56
+ export interface IPreuseRunSummary {
57
+ results: readonly TPreuseAccountResult[];
58
+ counts: Readonly<Record<TPreuseOutcome, number>>;
59
+ /** Accounts an abort kept the run from reaching. Nothing was sent for them. */
60
+ notRun: readonly IHarnessAccount[];
61
+ }
62
+
63
+ /**
64
+ * Every account a run may preuse, in the order the harness lists them, each at most once.
65
+ *
66
+ * A harness reports an active login and that login's saved record as one account -- Codex keys both by
67
+ * email, the file harness merges the active login into its saved record by account id -- so the walk is
68
+ * the account list itself. The seen set keeps a repeated id from being charged twice regardless.
69
+ */
70
+ export const preuseTargets = (accountsArg: readonly IHarnessAccount[]): IHarnessAccount[] => {
71
+ const seen = new Set<string>();
72
+ const targets: IHarnessAccount[] = [];
73
+ for (const account of accountsArg) {
74
+ if (seen.has(account.id)) continue;
75
+ seen.add(account.id);
76
+ targets.push(account);
77
+ }
78
+ return targets;
79
+ };
80
+
81
+ /**
82
+ * A run's counts in one line, for a command's closing line and for the dashboard footer.
83
+ *
84
+ * Completed accounts are always named, including none of them; every other count appears only when it
85
+ * happened, so a clean run reads as one fact rather than as four.
86
+ */
87
+ export const preuseCountsText = (summaryArg: IPreuseRunSummary): string => [
88
+ `${summaryArg.counts.completed} completed`,
89
+ ...(summaryArg.counts.skipped ? [`${summaryArg.counts.skipped} skipped`] : []),
90
+ ...(summaryArg.counts.failed ? [`${summaryArg.counts.failed} failed`] : []),
91
+ ...(summaryArg.counts.interrupted ? [`${summaryArg.counts.interrupted} interrupted`] : []),
92
+ ...(summaryArg.notRun.length ? [`${summaryArg.notRun.length} not run`] : []),
93
+ ].join(', ');
94
+
95
+ /** An adapter's own fixed message, or the fixed local text for an error that crossed the boundary unnamed. */
96
+ const preuseReason = (errorArg: unknown): string => errorArg instanceof PreuseError
97
+ ? errorArg.message
98
+ : 'Preuse failed. Tokens may already have been consumed; check account status before trying again.';
99
+
100
+ /**
101
+ * The account's reset schedule, read after its prompt completed, exactly as the single-account command reads it.
102
+ *
103
+ * The read never activates or writes a login, and its failure never turns a completed prompt into a failed
104
+ * one: there is nothing to undo and nothing worth repeating. An interrupted run does not ask at all.
105
+ */
106
+ const readPreuseSchedule = async (harnessArg: IAuthHarness, accountArg: IHarnessAccount, signalArg: AbortSignal): Promise<TPreuseSchedule> => {
107
+ if (signalArg.aborted) return { kind: 'notRead' };
108
+ try {
109
+ const status = await harnessArg.readAccountStatus(accountArg.id, { signal: signalArg });
110
+ return { kind: 'reported', windows: orderedUsageWindows(status.summary?.usageWindows) };
111
+ } catch { return { kind: 'unavailable' }; }
112
+ };
113
+
114
+ /**
115
+ * Send one preuse prompt through each account in turn, and report what each one did.
116
+ *
117
+ * Accounts run strictly one after another, each with exactly one inference request and no retry, because
118
+ * every request costs the account's own quota. An aborted signal stops the run before the next account
119
+ * starts, and an account already in flight is reported as interrupted: its tokens may be gone either way,
120
+ * which is why nothing is repeated. Nothing is switched, refreshed, stopped or written anywhere.
121
+ */
122
+ export const preuseAccounts = async (
123
+ harnessArg: IAuthHarness,
124
+ accountsArg: readonly IHarnessAccount[],
125
+ optionsArg: { prompt: string; model?: string; signal: AbortSignal },
126
+ reportArg: (eventArg: TPreuseRunEvent) => void,
127
+ ): Promise<IPreuseRunSummary> => {
128
+ const preuseAccount = harnessArg.preuseAccount?.bind(harnessArg);
129
+ if (!preuseAccount) throw new PreuseError('This harness does not support preuse.');
130
+ validatePreuseOptions(optionsArg);
131
+ const results: TPreuseAccountResult[] = [];
132
+ const counts: Record<TPreuseOutcome, number> = { completed: 0, skipped: 0, failed: 0, interrupted: 0 };
133
+ const notRun: IHarnessAccount[] = [];
134
+ const total = accountsArg.length;
135
+ for (const [index, account] of accountsArg.entries()) {
136
+ if (optionsArg.signal.aborted) { notRun.push(account); continue; }
137
+ reportArg({ kind: 'started', index, total, account });
138
+ let result: TPreuseAccountResult;
139
+ try {
140
+ const completed = await preuseAccount(account.id, { prompt: optionsArg.prompt, model: optionsArg.model, signal: optionsArg.signal });
141
+ result = { account, outcome: 'completed', result: completed, schedule: await readPreuseSchedule(harnessArg, account, optionsArg.signal) };
142
+ } catch (error) {
143
+ // A cancelled account is interrupted whether or not its prompt went out; its reason says which.
144
+ const outcome = optionsArg.signal.aborted ? 'interrupted'
145
+ : error instanceof PreuseError && !error.requestStarted ? 'skipped' : 'failed';
146
+ result = { account, outcome, reason: preuseReason(error) };
147
+ }
148
+ results.push(result);
149
+ counts[result.outcome]++;
150
+ reportArg({ kind: 'finished', index, total, result });
151
+ }
152
+ return { results, counts, notRun };
153
+ };