sideby 0.35.9 → 0.36.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 (66) hide show
  1. package/dist/build.json +1 -1
  2. package/dist/src/cli/commands.d.ts +12 -0
  3. package/dist/src/cli/commands.js +480 -6
  4. package/dist/src/cli/format.d.ts +12 -1
  5. package/dist/src/cli/format.js +23 -3
  6. package/dist/src/cli/json-schemas.js +166 -1
  7. package/dist/src/cli/main.js +18 -4
  8. package/dist/src/core/advisor.d.ts +176 -0
  9. package/dist/src/core/advisor.js +472 -0
  10. package/dist/src/core/browser-profiles.d.ts +16 -0
  11. package/dist/src/core/browser-profiles.js +45 -0
  12. package/dist/src/core/cli-commands.js +25 -1
  13. package/dist/src/core/config.d.ts +29 -0
  14. package/dist/src/core/config.js +25 -0
  15. package/dist/src/core/handoff-select.d.ts +13 -2
  16. package/dist/src/core/handoff-select.js +6 -2
  17. package/dist/src/core/launch.d.ts +4 -0
  18. package/dist/src/core/launch.js +7 -0
  19. package/dist/src/core/limit-reset.d.ts +198 -0
  20. package/dist/src/core/limit-reset.js +299 -0
  21. package/dist/src/core/quota-fetch.d.ts +57 -2
  22. package/dist/src/core/quota-fetch.js +291 -13
  23. package/dist/src/core/quota-levels.d.ts +70 -0
  24. package/dist/src/core/quota-levels.js +80 -0
  25. package/dist/src/core/quota-store.d.ts +15 -1
  26. package/dist/src/core/quota-store.js +26 -1
  27. package/dist/src/core/same-login.d.ts +8 -0
  28. package/dist/src/core/same-login.js +39 -2
  29. package/dist/src/core/search-catalog.js +38 -0
  30. package/dist/src/families/claude/index.js +2 -0
  31. package/dist/src/families/codex/index.js +3 -1
  32. package/dist/src/families/codex/quota.d.ts +23 -1
  33. package/dist/src/families/codex/quota.js +122 -21
  34. package/dist/src/families/grok/quota-log.d.ts +1 -0
  35. package/dist/src/menubar/script.js +70 -18
  36. package/dist/src/menubar/snapshot.d.ts +33 -1
  37. package/dist/src/menubar/snapshot.js +79 -11
  38. package/dist/src/menubar/strings.d.ts +16 -0
  39. package/dist/src/menubar/strings.js +16 -0
  40. package/dist/src/panel/handler.d.ts +21 -0
  41. package/dist/src/panel/handler.js +111 -9
  42. package/dist/src/panel/i18n.d.ts +87 -0
  43. package/dist/src/panel/i18n.js +174 -0
  44. package/dist/src/panel/page-logic.d.ts +17 -0
  45. package/dist/src/panel/page-logic.js +23 -0
  46. package/dist/src/panel/page-script.js +440 -19
  47. package/dist/src/panel/page-styles.js +38 -2
  48. package/dist/src/plugins/loader.d.ts +2 -0
  49. package/dist/src/plugins/loader.js +27 -0
  50. package/dist/src/runtime.d.ts +63 -1
  51. package/dist/src/runtime.js +529 -9
  52. package/dist/src/types.d.ts +67 -0
  53. package/package.json +1 -1
  54. package/schemas/advisor.json +332 -0
  55. package/schemas/config.json +22 -0
  56. package/schemas/error.json +4 -0
  57. package/schemas/menubar-reset.json +93 -0
  58. package/schemas/menubar-snapshot.json +70 -2
  59. package/schemas/quota-reset.json +369 -0
  60. package/schemas/quota.json +30 -0
  61. package/schemas/update.json +4 -0
  62. package/skills/sideby/SKILL.md +6 -2
  63. package/skills/sideby/references/ai-tasks.md +1 -1
  64. package/skills/sideby/references/panel.md +14 -0
  65. package/skills/sideby/references/quota.md +27 -0
  66. package/skills/sideby/references/update.md +1 -1
@@ -15,10 +15,27 @@ const isWindow = (w) => {
15
15
  (v.name === undefined || typeof v.name === 'string') &&
16
16
  typeof v.windowMinutes === 'number' &&
17
17
  typeof v.usedPercent === 'number' &&
18
- typeof v.resetsAt === 'string');
18
+ typeof v.resetsAt === 'string' &&
19
+ (v.observedAt === undefined || typeof v.observedAt === 'string') &&
20
+ (v.source === undefined || typeof v.source === 'string'));
19
21
  };
22
+ const isTime = (v) => typeof v === 'string' && Number.isFinite(Date.parse(v));
23
+ /** The Limit Resets of a reading with only the fields sideby keeps, or undefined when it is not a count. */
24
+ export function keptLimitResets(v) {
25
+ const r = v;
26
+ if (typeof r !== 'object' || r === null)
27
+ return undefined;
28
+ if (!Number.isInteger(r.available) || r.available < 0 || !isTime(r.observedAt))
29
+ return undefined;
30
+ return {
31
+ available: r.available,
32
+ observedAt: r.observedAt,
33
+ ...(isTime(r.nextExpiresAt) ? { nextExpiresAt: r.nextExpiresAt } : {}),
34
+ };
35
+ }
20
36
  /** Only the fields a Quota reading may carry, so a plugin's extra fields never reach the file. */
21
37
  export function keptQuota(q) {
38
+ const limitResets = keptLimitResets(q.limitResets);
22
39
  return {
23
40
  status: 'ok',
24
41
  windows: q.windows.filter(isWindow).map((w) => ({
@@ -27,10 +44,14 @@ export function keptQuota(q) {
27
44
  windowMinutes: w.windowMinutes,
28
45
  usedPercent: w.usedPercent,
29
46
  resetsAt: w.resetsAt,
47
+ // A window's own time and source only where they differ from the Quota's (ADR-0073).
48
+ ...(w.observedAt && w.observedAt !== q.observedAt ? { observedAt: w.observedAt } : {}),
49
+ ...(w.source && w.source !== q.source ? { source: w.source } : {}),
30
50
  })),
31
51
  observedAt: q.observedAt,
32
52
  source: q.source,
33
53
  ...(typeof q.plan === 'string' && q.plan ? { plan: q.plan } : {}),
54
+ ...(limitResets ? { limitResets } : {}),
34
55
  };
35
56
  }
36
57
  /** The kept answer, or null when there is none or the file is not one sideby wrote. */
@@ -52,11 +73,15 @@ export async function readQuotaStore(file) {
52
73
  return {
53
74
  version: 1,
54
75
  attemptedAt: e.attemptedAt,
76
+ ...(isTime(e.startedAt) ? { startedAt: e.startedAt } : {}),
55
77
  ...(quota ? { quota } : {}),
56
78
  ...(typeof e.error === 'string' ? { error: e.error } : {}),
57
79
  ...(typeof e.loginExpiredAt === 'string' && Number.isFinite(Date.parse(e.loginExpiredAt))
58
80
  ? { loginExpiredAt: e.loginExpiredAt }
59
81
  : {}),
82
+ ...(Array.isArray(e.resetAsked) && e.resetAsked.some(isTime)
83
+ ? { resetAsked: [...new Set(e.resetAsked.filter(isTime))] }
84
+ : {}),
60
85
  };
61
86
  }
62
87
  export async function writeQuotaStore(file, entry) {
@@ -21,6 +21,14 @@ export interface LoginMember {
21
21
  * of `LOGIN_KEY_FAMILIES` both must also have a Login Key, and the keys must be equal.
22
22
  */
23
23
  export declare function isSameLogin(a: LoginMember, b: LoginMember): boolean;
24
+ /**
25
+ * Everything two Accounts must have equal to be the same login, as one string: the Family, the email, the
26
+ * organization and, in a Family of `LOGIN_KEY_FAMILIES`, the Login Key. Undefined when the login cannot be told: not
27
+ * a subscription, no email, or no Login Key where one is needed. Any Family with an Identity has one, also one whose
28
+ * Accounts never group. Only for comparing inside the Runtime: it holds the Login Key and the Identity, so it is
29
+ * never put into an output, an error or a file as it is (a Limit Reset record keeps a salted digest of it, ADR-0072).
30
+ */
31
+ export declare function loginComparisonKey(m: Omit<LoginMember, 'ref'>): string | undefined;
24
32
  /** Ref → the other refs of its Same Login, in the order given; Accounts without one are left out. */
25
33
  export declare function sameLoginGroups(members: readonly LoginMember[]): Map<string, string[]>;
26
34
  /**
@@ -24,6 +24,24 @@ export function isSameLogin(a, b) {
24
24
  return false;
25
25
  return norm(a.identity?.org) === norm(b.identity?.org);
26
26
  }
27
+ /**
28
+ * Everything two Accounts must have equal to be the same login, as one string: the Family, the email, the
29
+ * organization and, in a Family of `LOGIN_KEY_FAMILIES`, the Login Key. Undefined when the login cannot be told: not
30
+ * a subscription, no email, or no Login Key where one is needed. Any Family with an Identity has one, also one whose
31
+ * Accounts never group. Only for comparing inside the Runtime: it holds the Login Key and the Identity, so it is
32
+ * never put into an output, an error or a file as it is (a Limit Reset record keeps a salted digest of it, ADR-0072).
33
+ */
34
+ export function loginComparisonKey(m) {
35
+ if (m.kind !== 'subscription')
36
+ return undefined;
37
+ const email = norm(m.identity?.email);
38
+ if (!email)
39
+ return undefined;
40
+ const keyed = LOGIN_KEY_FAMILIES.has(m.family);
41
+ if (keyed && !m.loginKey)
42
+ return undefined;
43
+ return JSON.stringify([m.family, email, norm(m.identity?.org) ?? '', keyed ? m.loginKey : '']);
44
+ }
27
45
  /** Ref → the other refs of its Same Login, in the order given; Accounts without one are left out. */
28
46
  export function sameLoginGroups(members) {
29
47
  const out = new Map();
@@ -34,6 +52,8 @@ export function sameLoginGroups(members) {
34
52
  }
35
53
  return out;
36
54
  }
55
+ /** How much older than the reading shown a count of Limit Resets from another reading of the login may be. */
56
+ const RESETS_CARRY_MS = 60 * 60_000;
37
57
  /**
38
58
  * The Quota an Account of a Same Login shows: the freshest `ok` reading of the group (its own wins a tie), marked
39
59
  * with `from` when it is another member's. Without any `ok` reading the Account keeps its own result.
@@ -53,8 +73,25 @@ export function sharedQuota(ref, readings, peers, localFallbackOnly = false) {
53
73
  if (!best || rank > best.rank || (rank === best.rank && t > best.t))
54
74
  best = { ref: r, q, t, rank };
55
75
  }
56
- if (!best || best.ref === ref)
76
+ if (!best)
57
77
  return own;
78
+ // The count of Limit Resets belongs to the login. A reading that does not tell it (kept by a sideby from before
79
+ // the count was read, which may still run in an open session) takes the newest count another reading of the login
80
+ // tells, while that count was read within the hour; it carries its own read time.
81
+ let resets = best.q.limitResets;
82
+ if (!resets)
83
+ for (const r of [ref, ...peers]) {
84
+ const q = readings.get(r);
85
+ const c = q?.status === 'ok' ? q.limitResets : undefined;
86
+ const at = Date.parse(c?.observedAt ?? '');
87
+ if (!c || !(best.t - at <= RESETS_CARRY_MS))
88
+ continue;
89
+ if (!resets || at > Date.parse(resets.observedAt))
90
+ resets = c;
91
+ }
92
+ const carried = resets && !best.q.limitResets ? { limitResets: resets } : {};
93
+ if (best.ref === ref)
94
+ return { ...own, ...carried };
58
95
  const { from: _from, ...reading } = best.q;
59
- return { ...reading, from: best.ref };
96
+ return { ...reading, ...carried, from: best.ref };
60
97
  }
@@ -186,6 +186,25 @@ const ENTRIES = [
186
186
  target: { settings: 'accounts', find: 'rc' },
187
187
  cliCommand: 'sideby remote-control',
188
188
  },
189
+ {
190
+ id: 'setting.advisor',
191
+ kind: 'setting',
192
+ title: { en: 'Advisor', zh: '顾问模型(Advisor)' },
193
+ synonyms: [
194
+ '/advisor',
195
+ 'advisor model',
196
+ 'stronger model',
197
+ 'second opinion',
198
+ 'fable',
199
+ 'opus',
200
+ '顾问',
201
+ '请教',
202
+ '更强的模型',
203
+ ],
204
+ panel: at(SET, ACCOUNTS),
205
+ target: { settings: 'accounts', find: 'advisor' },
206
+ cliCommand: 'sideby advisor',
207
+ },
189
208
  {
190
209
  id: 'setting.quota-checks',
191
210
  kind: 'setting',
@@ -249,6 +268,25 @@ const ENTRIES = [
249
268
  target: { action: 'new-account', write: true },
250
269
  cliCommand: 'sideby new <family> --next',
251
270
  },
271
+ {
272
+ id: 'action.limit-reset',
273
+ kind: 'action',
274
+ title: { en: 'Use a limit reset', zh: '使用一次重置' },
275
+ synonyms: [
276
+ 'reset quota',
277
+ 'reset limit',
278
+ 'reset credit',
279
+ 'restore quota',
280
+ 'usage reset',
281
+ '重置额度',
282
+ '重置次数',
283
+ '恢复额度',
284
+ '用重置',
285
+ ],
286
+ panel: at(ACCOUNTS, { en: "an account's menu", zh: '账号的菜单' }),
287
+ target: { action: 'limit-reset', write: true },
288
+ cliCommand: 'sideby quota reset <account>',
289
+ },
252
290
  {
253
291
  id: 'action.remote-control-off',
254
292
  kind: 'action',
@@ -136,6 +136,8 @@ export const claudeFamily = {
136
136
  readUsage: readClaudeUsage,
137
137
  readTuning: readClaudeTuning,
138
138
  quotaSetup: claudeStatusline,
139
+ // Claude Code cannot spend a Limit Reset or tell how many an Account holds: only the vendor's page can (ADR-0072).
140
+ limitReset: { vendorPage: 'https://claude.ai/settings/usage' },
139
141
  resumedSession: resumeFlagSession,
140
142
  sessionWrittenAt: (account, id) => groupedEntryWrittenAt(join(account.dir, 'projects'), `${id}.jsonl`, 'file'),
141
143
  // Claude Code makes this directory for SessionStart hooks before the first message is saved (ADR-0009).
@@ -6,7 +6,7 @@ import { nestedFileWrittenAt, resumeSubcommandSession } from '../shared/sessions
6
6
  import { topLevelTomlString } from '../shared/toml.js';
7
7
  import { codexHandoff } from './handoff.js';
8
8
  import { codexModelChoice } from './model.js';
9
- import { codexQuotaFetch } from './quota.js';
9
+ import { codexQuotaFetch, useCodexLimitReset } from './quota.js';
10
10
  import { readCodexQuota, readCodexUsage } from './rollout.js';
11
11
  import { readCodexTuning } from './tuning.js';
12
12
  const FILE_STORE_KEY = 'cli_auth_credentials_store';
@@ -89,6 +89,8 @@ export const codexFamily = {
89
89
  identity: codexIdentity,
90
90
  readQuota: (account) => readCodexQuota(account.dir),
91
91
  fetchQuota: codexQuotaFetch,
92
+ // Spending a Limit Reset the Account holds, only after the user confirmed it (ADR-0072).
93
+ limitReset: { use: useCodexLimitReset },
92
94
  readUsage: (account, ctx) => readCodexUsage(account.dir, ctx.now),
93
95
  readTuning: readCodexTuning,
94
96
  resumedSession: resumeSubcommandSession,
@@ -1,3 +1,25 @@
1
- import type { Account, QuotaFetch, QuotaFetchContext, QuotaResult } from '../../types.ts';
1
+ import type { Account, LimitResetContext, LimitResetOutcome, LimitResets, QuotaFetch, QuotaFetchContext, QuotaResult } from '../../types.ts';
2
+ /**
3
+ * The Limit Resets the answer tells (`rateLimitResetCredits`, ADR-0072), or undefined when it does not tell: the
4
+ * field is missing or null, or its count is not a whole number. `availableCount` is the count; the detail rows may be
5
+ * missing or cut short, so the next expiry is kept only when they cover every available credit. No credit id, title
6
+ * or description is kept.
7
+ */
8
+ export declare function limitResetsOf(raw: unknown, observedAt: string): LimitResets | undefined;
2
9
  export declare function fetchCodexQuota(account: Account, ctx: QuotaFetchContext): Promise<QuotaResult>;
10
+ /**
11
+ * A spend that got no final answer. `sent` says whether the request left sideby: false means the Host never got it,
12
+ * so nothing was spent; true means the outcome is unknown and only the same idempotency key may ask again.
13
+ */
14
+ export declare class CodexLimitResetError extends Error {
15
+ readonly sent: boolean;
16
+ constructor(message: string, sent: boolean);
17
+ }
18
+ /**
19
+ * Spends one Limit Reset of the Account through its own `codex app-server` (ADR-0072): the stable request
20
+ * `account/rateLimitResetCredit/consume` with the idempotency key and no `creditId`, so the vendor picks the credit.
21
+ * The Host sends it with its own login; no credential is read and nothing of the answer but its outcome is kept.
22
+ * Throws when the Host gave no final outcome.
23
+ */
24
+ export declare function useCodexLimitReset(account: Account, ctx: LimitResetContext): Promise<LimitResetOutcome>;
3
25
  export declare const codexQuotaFetch: QuotaFetch;
@@ -1,10 +1,36 @@
1
- // Current quota through Codex's documented app-server protocol (ADR-0038). The Host handles its own login;
2
- // no thread, model turn, credential extraction or direct HTTP request.
1
+ // Current quota through Codex's documented app-server protocol (ADR-0038), and the one request that spends a Limit
2
+ // Reset (ADR-0072). The Host handles its own login; no thread, model turn, credential extraction or direct HTTP request.
3
3
  import { spawn } from 'node:child_process';
4
4
  import { tmpdir } from 'node:os';
5
5
  import { createInterface } from 'node:readline';
6
6
  import { isObj, rateLimits } from './rate-limits.js';
7
7
  const failed = (detail) => ({ status: 'unavailable', reason: 'fetch-failed', detail });
8
+ /**
9
+ * The Limit Resets the answer tells (`rateLimitResetCredits`, ADR-0072), or undefined when it does not tell: the
10
+ * field is missing or null, or its count is not a whole number. `availableCount` is the count; the detail rows may be
11
+ * missing or cut short, so the next expiry is kept only when they cover every available credit. No credit id, title
12
+ * or description is kept.
13
+ */
14
+ export function limitResetsOf(raw, observedAt) {
15
+ if (!isObj(raw))
16
+ return undefined;
17
+ const available = raw.availableCount;
18
+ if (typeof available !== 'number' || !Number.isInteger(available) || available < 0)
19
+ return undefined;
20
+ const out = { available, observedAt };
21
+ const rows = raw.credits;
22
+ if (available === 0 || !Array.isArray(rows))
23
+ return out;
24
+ const open = rows.filter((c) => isObj(c) && c.status === 'available');
25
+ if (open.length < available)
26
+ return out;
27
+ const expiries = open
28
+ .map((c) => (isObj(c) ? c.expiresAt : null))
29
+ .filter((t) => typeof t === 'number' && Number.isFinite(t) && t > 0);
30
+ if (expiries.length)
31
+ out.nextExpiresAt = new Date(Math.min(...expiries) * 1000).toISOString();
32
+ return out;
33
+ }
8
34
  /** Prefer the general Codex bucket; a model-specific bucket is not the account's general quota. */
9
35
  function quotaAnswer(result) {
10
36
  if (!isObj(result))
@@ -30,16 +56,24 @@ function quotaAnswer(result) {
30
56
  });
31
57
  if (!parsed)
32
58
  return failed('Codex returned an unrecognized quota; update Codex, then refresh');
59
+ const observedAt = new Date().toISOString();
60
+ const limitResets = limitResetsOf(result.rateLimitResetCredits, observedAt);
33
61
  return {
34
62
  status: 'ok',
35
63
  ...parsed,
36
- observedAt: new Date().toISOString(),
64
+ observedAt,
37
65
  source: 'codex app-server account/rateLimits/read',
66
+ ...(limitResets ? { limitResets } : {}),
38
67
  };
39
68
  }
40
- export async function fetchCodexQuota(account, ctx) {
69
+ /**
70
+ * One request to the Account's own `codex app-server`: starts it with the Account's launch environment, initializes,
71
+ * sends `request` and resolves with its answer. Only this short-lived process is ended afterwards, never a session.
72
+ * `sent` is called once the request has been written, so a caller can tell "never sent" from "sent, no answer".
73
+ */
74
+ function askAppServer(account, ctx, request, sent) {
41
75
  if (ctx.signal.aborted)
42
- return failed('the Codex quota check was stopped; refresh to try again');
76
+ return Promise.resolve({ ok: false, why: 'stopped' });
43
77
  const args = [...(!account.isMain ? ['-c', 'cli_auth_credentials_store="file"'] : []), 'app-server'];
44
78
  const child = spawn('codex', args, {
45
79
  cwd: tmpdir(),
@@ -54,7 +88,7 @@ export async function fetchCodexQuota(account, ctx) {
54
88
  if (child.exitCode === null && child.signalCode === null)
55
89
  child.kill('SIGTERM');
56
90
  };
57
- const settle = (q) => {
91
+ const settle = (a) => {
58
92
  if (done)
59
93
  return;
60
94
  done = true;
@@ -65,18 +99,17 @@ export async function fetchCodexQuota(account, ctx) {
65
99
  const timer = setTimeout(stop, 1000);
66
100
  timer.unref();
67
101
  child.once('close', () => clearTimeout(timer));
68
- resolve(q);
102
+ resolve(a);
69
103
  };
104
+ const fail = (why) => settle({ ok: false, why });
70
105
  const abort = () => {
71
106
  stop();
72
- settle(failed('the Codex quota check was stopped; refresh to try again'));
107
+ fail('stopped');
73
108
  };
74
- const send = (request) => child.stdin.write(`${JSON.stringify(request)}\n`);
75
- child.stdin.on('error', () => settle(failed('Codex closed the quota query; refresh to try again')));
76
- child.on('error', (err) => settle(failed(err.code === 'ENOENT'
77
- ? 'Codex is not installed or not on PATH; install Codex, then refresh'
78
- : 'could not start Codex; check its installation, then refresh')));
79
- child.on('close', () => settle(failed('Codex exited without answering; update Codex, then refresh')));
109
+ const send = (message) => child.stdin.write(`${JSON.stringify(message)}\n`);
110
+ child.stdin.on('error', () => fail('closed'));
111
+ child.on('error', (err) => fail(err.code === 'ENOENT' ? 'not-installed' : 'no-start'));
112
+ child.on('close', () => fail('exited'));
80
113
  ctx.signal.addEventListener('abort', abort, { once: true });
81
114
  lines.on('line', (line) => {
82
115
  if (done)
@@ -91,19 +124,17 @@ export async function fetchCodexQuota(account, ctx) {
91
124
  if (!isObj(msg) || msg.id !== pending)
92
125
  return;
93
126
  if (isObj(msg.error)) {
94
- // Never include the Host's raw error: it may contain credentials or account identifiers.
95
- const detail = msg.error.code === -32601
96
- ? 'this Codex version cannot report quota; update Codex, then refresh'
97
- : `Codex could not read quota; refresh or run \`sideby login ${account.ref}\` if signed out`;
98
- settle(failed(detail));
127
+ // Never keep the Host's raw error: it may contain credentials or account identifiers.
128
+ fail(msg.error.code === -32601 ? 'unsupported' : pending === 1 ? 'refused' : 'error');
99
129
  }
100
130
  else if (pending === 1) {
101
131
  pending = 2;
102
132
  send({ method: 'initialized' });
103
- send({ id: 2, method: 'account/rateLimits/read' });
133
+ send({ id: 2, ...request });
134
+ sent?.();
104
135
  }
105
136
  else {
106
- settle(quotaAnswer(msg.result));
137
+ settle({ ok: true, result: msg.result });
107
138
  }
108
139
  });
109
140
  send({
@@ -115,6 +146,76 @@ export async function fetchCodexQuota(account, ctx) {
115
146
  abort();
116
147
  });
117
148
  }
149
+ export async function fetchCodexQuota(account, ctx) {
150
+ const a = await askAppServer(account, ctx, { method: 'account/rateLimits/read' });
151
+ if (a.ok)
152
+ return quotaAnswer(a.result);
153
+ switch (a.why) {
154
+ case 'stopped':
155
+ return failed('the Codex quota check was stopped; refresh to try again');
156
+ case 'not-installed':
157
+ return failed('Codex is not installed or not on PATH; install Codex, then refresh');
158
+ case 'no-start':
159
+ return failed('could not start Codex; check its installation, then refresh');
160
+ case 'closed':
161
+ return failed('Codex closed the quota query; refresh to try again');
162
+ case 'exited':
163
+ return failed('Codex exited without answering; update Codex, then refresh');
164
+ case 'unsupported':
165
+ return failed('this Codex version cannot report quota; update Codex, then refresh');
166
+ default:
167
+ return failed(`Codex could not read quota; refresh or run \`sideby login ${account.ref}\` if signed out`);
168
+ }
169
+ }
170
+ const CONSUME = 'account/rateLimitResetCredit/consume';
171
+ const OUTCOMES = {
172
+ reset: 'reset',
173
+ nothingToReset: 'nothing-to-reset',
174
+ noCredit: 'none-left',
175
+ alreadyRedeemed: 'already-done',
176
+ };
177
+ /**
178
+ * A spend that got no final answer. `sent` says whether the request left sideby: false means the Host never got it,
179
+ * so nothing was spent; true means the outcome is unknown and only the same idempotency key may ask again.
180
+ */
181
+ export class CodexLimitResetError extends Error {
182
+ sent;
183
+ constructor(message, sent) {
184
+ super(message);
185
+ this.sent = sent;
186
+ }
187
+ }
188
+ /**
189
+ * Spends one Limit Reset of the Account through its own `codex app-server` (ADR-0072): the stable request
190
+ * `account/rateLimitResetCredit/consume` with the idempotency key and no `creditId`, so the vendor picks the credit.
191
+ * The Host sends it with its own login; no credential is read and nothing of the answer but its outcome is kept.
192
+ * Throws when the Host gave no final outcome.
193
+ */
194
+ export async function useCodexLimitReset(account, ctx) {
195
+ let sent = false;
196
+ const a = await askAppServer(account, ctx, { method: CONSUME, params: { idempotencyKey: ctx.idempotencyKey } }, () => {
197
+ sent = true;
198
+ });
199
+ if (a.ok) {
200
+ const outcome = isObj(a.result) && typeof a.result.outcome === 'string' ? OUTCOMES[a.result.outcome] : undefined;
201
+ if (outcome)
202
+ return outcome;
203
+ throw new CodexLimitResetError('Codex answered the reset with something sideby does not know; update sideby', true);
204
+ }
205
+ const why = {
206
+ stopped: 'Codex did not answer in time',
207
+ 'not-installed': 'Codex is not installed or not on PATH; install Codex',
208
+ 'no-start': 'could not start Codex; check its installation',
209
+ closed: 'Codex closed the connection before answering',
210
+ exited: 'Codex exited without answering',
211
+ unsupported: 'this Codex version cannot use a limit reset; update Codex',
212
+ refused: `Codex did not start the connection; run \`sideby login ${account.ref}\` if signed out`,
213
+ error: `Codex refused the reset; run \`sideby login ${account.ref}\` if signed out`,
214
+ };
215
+ // An error answer to the request itself is final for this attempt but not an outcome: the Host did not say whether
216
+ // it spent one, so it stays unresolved like a lost answer. A method the Host does not know was never run.
217
+ throw new CodexLimitResetError(why[a.why], sent && a.why !== 'unsupported');
218
+ }
118
219
  export const codexQuotaFetch = {
119
220
  everyMinutes: 15,
120
221
  summary: 'Ask Codex for each account’s current quota every 15 minutes',
@@ -22,6 +22,7 @@ export declare const grokQuotaMemo: FileMemo<{
22
22
  observedAt: string;
23
23
  source: string;
24
24
  plan?: string;
25
+ limitResets?: import("../../types.ts").LimitResets;
25
26
  from?: string;
26
27
  fetched?: boolean;
27
28
  fetchError?: string;