aegiscode 6.8.11 → 6.8.13

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/caps.js CHANGED
@@ -35,6 +35,17 @@
35
35
  * face 'native' | 'edges' — the quartile edges ▐▛▜▌▝▘
36
36
  * star 'native' | 'narrow' — ✦ as a single-cell glyph, or stencilled to `*`
37
37
  * depth 24 | 8 | 4 | 0 — truecolor by default
38
+ * background 'dark' | 'light' — the terminal's OWN background, which is not
39
+ * a rendering axis: it selects which of the
40
+ * two legible palettes "Auto (match terminal)"
41
+ * resolves to. Read from the terminal itself —
42
+ * an OSC 11 query at startup (`COLORFGBG`/
43
+ * `TERM_BACKGROUND`/`AEGIS_BACKGROUND` win if
44
+ * any of them is set, and in a pipe nothing is
45
+ * asked at all), never guessed from the
46
+ * platform. `backgroundKnown` says whether the
47
+ * terminal actually reported it or it is just
48
+ * the dark default.
38
49
  * vt boolean — cursor/erase escapes (on by default)
39
50
  * cols/rows — the frame, with `AEGIS_WIDTH`/`COLUMNS` over
40
51
  * the reported size and a stable 80 fallback,
@@ -45,6 +56,8 @@
45
56
  *
46
57
  * Overrides (all read from the environment, all documented in README.md):
47
58
  * AEGIS_ART=unicode|ascii AEGIS_ASCII=1 AEGIS_UNICODE=0|1
59
+ * AEGIS_BACKGROUND=dark|light (also TERM_BACKGROUND, COLORFGBG)
60
+ * AEGIS_BACKGROUND_PROBE=0 (never ask the terminal — env signals still read)
48
61
  * AEGIS_STAR=native|narrow AEGIS_COLOR=0|1|2|3
49
62
  * AEGIS_VT=0|1 AEGIS_WIDTH=<cols> AEGIS_WIDE_RUNES=<runes>
50
63
  * AEGIS_FORCE_TRUECOLOR=0 NO_COLOR FORCE_COLOR=0|1|2|3
@@ -176,6 +189,291 @@ function resolveGlyphs(env, platform) {
176
189
  };
177
190
  }
178
191
 
192
+ /**
193
+ * The terminal's own background brightness: `'dark'` or `'light'`.
194
+ *
195
+ * This is NOT a rendering axis. Nothing about the mark, the colour *depth*, the
196
+ * glyph set or the control sequences moves with it. It exists for one decision
197
+ * only — which of the two palettes that are actually legible on the screen in
198
+ * front of the user the theme picker's "Auto (match terminal)" row resolves to —
199
+ * and getting it wrong is not a subtle difference: the dark palette's primary
200
+ * text is `RGB(255,255,255)`, so on a white terminal every word of the product
201
+ * is white-on-white. That is a blank screen, not an off-brand one.
202
+ *
203
+ * `theme.js` used to admit the hole in its own comment ("this client has no
204
+ * terminal-background probe and so resolves 'Auto' to the dark palette"), which
205
+ * meant the one row whose entire job was to match the terminal could not match
206
+ * it, and every user was silently assumed to be on a dark terminal.
207
+ *
208
+ * The signal, in order — each one written by the terminal about *itself*, so
209
+ * none of them is a platform guess:
210
+ *
211
+ * · `AEGIS_BACKGROUND=dark|light` / `AEGIS_THEME_BACKGROUND` — the explicit
212
+ * override, for a terminal that reports nothing (and for a bug report that
213
+ * wants the light palette without changing the terminal).
214
+ * · `TERM_BACKGROUND=dark|light` — kitty, WezTerm and a few others set it
215
+ * directly.
216
+ * · `COLORFGBG=fg;bg` — the classic xterm/rxvt report, also emitted by
217
+ * Konsole, Mint's GNOME Terminal and the other VTE terminals. Only the LAST
218
+ * field (the background's ANSI index) is read. Index 7 is light gray; 11–15
219
+ * are the bright half of the table, and a bright background is one white
220
+ * text disappears into. 0–6 and 8–10 are dark.
221
+ *
222
+ * · **the terminal's own answer to an OSC 11 query** — `probeBackground()`
223
+ * asks ("what is your background?") and the terminal replies with its real
224
+ * colour, which is the one signal that is neither an environment variable
225
+ * nor a guess. It exists because the variables above are simply absent on
226
+ * the terminals people actually run: Alacritty, for one, sets no
227
+ * `COLORFGBG` and no `TERM_BACKGROUND`, so it reported *nothing* and a
228
+ * Catppuccin-Mocha Alacritty (`#1e1e2e`) was recorded as "dark" by accident
229
+ * — right answer, no evidence. The answer is passed in by the async entry
230
+ * point (`probeTerminalBackground()`), never read here, so this function
231
+ * stays synchronous, instant and testable.
232
+ *
233
+ * Anything else — no signal at all, which is every pipe, every CI run and the
234
+ * terminals that refuse to answer — resolves to `'dark'` with `known: false`.
235
+ * The flag matters: `dark` from a real report is evidence, `dark` from silence
236
+ * is a default, and only the caller can decide what to do about the difference.
237
+ * A session that reports nothing therefore renders exactly as it did before any
238
+ * of this existed.
239
+ *
240
+ * @param {object} [env] defaults to `process.env`
241
+ * @param {{background: 'dark'|'light', reason: string}} [probed] the terminal's
242
+ * own OSC 11 answer, when one was obtained (`probeTerminalBackground()`)
243
+ * @returns {{background: 'dark'|'light', known: boolean, reason: string}}
244
+ */
245
+ function resolveBackground(env = process.env, probed = null) {
246
+ const override = String(env.AEGIS_BACKGROUND || env.AEGIS_THEME_BACKGROUND || '').trim().toLowerCase();
247
+ if (override === 'light') return { background: 'light', known: true, reason: 'AEGIS_BACKGROUND=light' };
248
+ if (override === 'dark') return { background: 'dark', known: true, reason: 'AEGIS_BACKGROUND=dark' };
249
+
250
+ const declared = String(env.TERM_BACKGROUND || '').trim().toLowerCase();
251
+ if (declared === 'light' || declared === 'dark') {
252
+ return { background: declared, known: true, reason: `TERM_BACKGROUND=${declared}` };
253
+ }
254
+
255
+ const fgbg = String(env.COLORFGBG || '').trim();
256
+ if (fgbg) {
257
+ const parts = fgbg.split(/[;:]/);
258
+ const bg = Number(parts[parts.length - 1]);
259
+ if (Number.isInteger(bg) && bg >= 0 && bg <= 15) {
260
+ const light = bg === 7 || bg >= 11;
261
+ return { background: light ? 'light' : 'dark', known: true, reason: `COLORFGBG=${fgbg}` };
262
+ }
263
+ }
264
+
265
+ if (probed && (probed.background === 'light' || probed.background === 'dark')) {
266
+ return { background: probed.background, known: true, reason: probed.reason || `osc11 ${probed.background}` };
267
+ }
268
+
269
+ return { background: 'dark', known: false, reason: 'no terminal background reported (dark default)' };
270
+ }
271
+
272
+ // ── the terminal's own answer (OSC 11) ───────────────────────────────────────
273
+
274
+ /**
275
+ * How long to wait for a terminal to answer "what is your background?".
276
+ *
277
+ * The query is written at startup and abandoned after this, so the deadline is
278
+ * a *startup* latency on the terminals that never answer, and nothing else. It
279
+ * is spent only when no environment variable already decided the axis — a
280
+ * `COLORFGBG`/`TERM_BACKGROUND`/`AEGIS_BACKGROUND` session does not probe at
281
+ * all — and every terminal that does answer replies in single-digit
282
+ * milliseconds (Alacritty 0.13 answers immediately), so the wait is not the
283
+ * common case. 120ms is one frame nobody notices, against a wrong palette the
284
+ * user cannot read.
285
+ */
286
+ const PROBE_TIMEOUT_MS = 120;
287
+
288
+ /** The query: `\x1b]11;?\x07` — "report your background", terminated by BEL. */
289
+ const OSC11_QUERY = '\x1b]11;?\x07';
290
+
291
+ /**
292
+ * The answer: `\x1b]11;rgb:1e1e/1e1e/2e2e\x07` (Alacritty, xterm, VTE, kitty),
293
+ * terminated by either BEL or ST. Matched loosely and out of a buffer, because
294
+ * a reply can arrive split across reads.
295
+ */
296
+ const OSC11_REPLY = /\x1b\]11;([^\x07\x1b]*)(?:\x07|\x1b\\)/;
297
+
298
+ /** A channel of an X11 colour spec: 1–4 hex digits, scaled to 0–255. */
299
+ function colorChannel(hex) {
300
+ const n = parseInt(hex, 16);
301
+ return Math.round((n / (Math.pow(16, hex.length) - 1)) * 255);
302
+ }
303
+
304
+ /**
305
+ * Parse an OSC 11 reply into an RGB triple, or `null` when the text is not one.
306
+ *
307
+ * Two bodies are accepted, both seen in the wild: X11's `rgb:RRRR/GGGG/BBBB`
308
+ * (1–4 hex digits per channel — Alacritty answers `rgb:1e1e/1e1e/2e2e`) and the
309
+ * `#rrggbb` shorthand some terminals use instead.
310
+ *
311
+ * @param {string} text
312
+ * @returns {{r: number, g: number, b: number}|null}
313
+ */
314
+ function parseBackgroundReply(text) {
315
+ const m = OSC11_REPLY.exec(String(text == null ? '' : text));
316
+ if (!m) return null;
317
+ const body = m[1].trim();
318
+ const rgb = /^rgba?:([0-9a-f]{1,4})\/([0-9a-f]{1,4})\/([0-9a-f]{1,4})/i.exec(body);
319
+ if (rgb) return { r: colorChannel(rgb[1]), g: colorChannel(rgb[2]), b: colorChannel(rgb[3]) };
320
+ const short = /^#?([0-9a-f]{6})$/i.exec(body);
321
+ if (short) {
322
+ const h = short[1];
323
+ return { r: parseInt(h.slice(0, 2), 16), g: parseInt(h.slice(2, 4), 16), b: parseInt(h.slice(4, 6), 16) };
324
+ }
325
+ return null;
326
+ }
327
+
328
+ /** WCAG relative luminance, 0 (black) … 1 (white). */
329
+ function relativeLuminance({ r, g, b }) {
330
+ const f = (v) => {
331
+ const s = v / 255;
332
+ return s <= 0.03928 ? s / 12.92 : Math.pow((s + 0.055) / 1.055, 2.4);
333
+ };
334
+ return 0.2126 * f(r) + 0.7152 * f(g) + 0.0722 * f(b);
335
+ }
336
+
337
+ /**
338
+ * The threshold between "a light background" and "a dark one", as relative
339
+ * luminance. 0.5 is the midpoint of the perceptual scale and the usual choice;
340
+ * a Catppuccin-Mocha `#1e1e2e` scores 0.014 and a #f5f5f5 scores 0.90, so no
341
+ * real terminal background sits anywhere near the line — the only colours that
342
+ * do are mid-greys, where either palette is legible anyway.
343
+ */
344
+ const LIGHT_LUMINANCE = 0.5;
345
+
346
+ /** `#1e1e2e` — for the `--terminal` report and the startup notice. */
347
+ function hexOf({ r, g, b }) {
348
+ return '#' + [r, g, b].map((v) => v.toString(16).padStart(2, '0')).join('');
349
+ }
350
+
351
+ /**
352
+ * Ask the terminal for its own background colour (OSC 11) and answer with RGB.
353
+ *
354
+ * Written directly, because there is nothing else to read: the environment
355
+ * variables in `resolveBackground` are absent on the terminals people run
356
+ * (Alacritty sets neither `COLORFGBG` nor `TERM_BACKGROUND`), and the terminal
357
+ * will not volunteer its colour — it only answers when asked. This is that ask.
358
+ *
359
+ * Only ever runs against a real TTY (`stdin` *and* `stdout`), so a pipe, a CI
360
+ * run, a test harness and a `--print` invocation never probe and never wait.
361
+ * The raw mode it needs is turned back off before returning, and any byte that
362
+ * is not the answer — a keystroke that raced the query — is pushed back onto
363
+ * `stdin`, so the probe is invisible to the session's own input handling.
364
+ *
365
+ * @returns {Promise<{background: 'dark'|'light', reason: string, rgb: object}|null>}
366
+ * `null` when the terminal did not answer within `timeoutMs`
367
+ */
368
+ function probeBackground({ stdin = process.stdin, stdout = process.stdout, timeoutMs = PROBE_TIMEOUT_MS, onLeftover = null } = {}) {
369
+ return new Promise((resolve) => {
370
+ if (!stdin || !stdout || !stdin.isTTY || !stdout.isTTY || typeof stdin.setRawMode !== 'function') {
371
+ resolve(null);
372
+ return;
373
+ }
374
+ const wasRaw = !!stdin.isRaw;
375
+ let buf = '';
376
+ let settled = false;
377
+ let timer = null;
378
+
379
+ const finish = (value, leftover) => {
380
+ if (settled) return;
381
+ settled = true;
382
+ if (timer) clearTimeout(timer);
383
+ stdin.removeListener('data', onData);
384
+ try {
385
+ if (!wasRaw) stdin.setRawMode(false);
386
+ } catch {
387
+ /* the terminal closed under us; the read end is already gone */
388
+ }
389
+ stdin.pause();
390
+ if (leftover) {
391
+ // Bytes that were not the answer belong to the session, not to us.
392
+ // `onLeftover` routes them back through the caller's key queue, which
393
+ // is lossless even when stdin has already ended (see `events.feedKeys`,
394
+ // and the 60-second hang its absence caused under `script`/`spawnSync`,
395
+ // where the write end closes the moment the command is sent).
396
+ if (typeof onLeftover === 'function') {
397
+ try {
398
+ onLeftover(leftover);
399
+ } catch {
400
+ /* a broken handback must not cost the probe its answer */
401
+ }
402
+ } else {
403
+ try {
404
+ stdin.unshift(Buffer.from(leftover, 'latin1'));
405
+ } catch {
406
+ /* nothing to push back onto; the deadline was still honoured */
407
+ }
408
+ }
409
+ }
410
+ resolve(value);
411
+ };
412
+
413
+ const onData = (chunk) => {
414
+ buf += chunk.toString('latin1');
415
+ const rgb = parseBackgroundReply(buf);
416
+ if (rgb) {
417
+ finish(
418
+ { background: relativeLuminance(rgb) > LIGHT_LUMINANCE ? 'light' : 'dark', rgb, reason: `osc11 ${hexOf(rgb)}` },
419
+ buf.replace(OSC11_REPLY, ''),
420
+ );
421
+ } else if (buf.length > 512) {
422
+ // Not an answer — most likely a paste or a keystroke arriving before
423
+ // the reply. Hand the bytes back rather than eating the user's input.
424
+ finish(null, buf);
425
+ }
426
+ };
427
+
428
+ timer = setTimeout(() => finish(null, buf), timeoutMs);
429
+ try {
430
+ stdin.setRawMode(true);
431
+ stdin.resume();
432
+ stdin.on('data', onData);
433
+ stdout.write(OSC11_QUERY);
434
+ } catch {
435
+ finish(null, '');
436
+ }
437
+ });
438
+ }
439
+
440
+ /**
441
+ * Ask the terminal for its background and fold the answer into the live
442
+ * capabilities, so every later `caps()`/`themeOf()` sees it.
443
+ *
444
+ * The single entry point the interactive host calls once at startup, before
445
+ * anything is drawn and before the persisted theme is restored: the stored row
446
+ * can only be checked against the terminal it is actually drawn on, and the
447
+ * restore is what turns that row into the palette of every frame after it.
448
+ *
449
+ * Deliberately *not* routed through `setCaps()`: that takes a patch over a
450
+ * fresh `detect()`, and a detect result carries `cols`/`rows`, which would pin
451
+ * the frame to the startup size and make every later resize be ignored. This
452
+ * mutates the background axis on the same cached object — so the holders that
453
+ * captured it (`theme.js` keeps one) see it, exactly like a `/terminal` change.
454
+ *
455
+ * @returns {Promise<{background: 'dark'|'light', known: boolean, reason: string}>}
456
+ */
457
+ async function probeTerminalBackground({ env = process.env, stdin = process.stdin, stdout = process.stdout, platform = process.platform, timeoutMs = PROBE_TIMEOUT_MS, onLeftover = null } = {}) {
458
+ const fromEnv = resolveBackground(env);
459
+ // An explicit signal is the user's word and outranks the terminal; asking
460
+ // anyway would spend the deadline to learn something we would not use.
461
+ const probe = fromEnv.known || String(env.AEGIS_BACKGROUND_PROBE || '').trim() === '0' ? null : await probeBackground({ stdin, stdout, timeoutMs, onLeftover });
462
+ const bg = resolveBackground(env, probe);
463
+ const live = axes();
464
+ live.background = bg.background;
465
+ live.backgroundKnown = bg.known;
466
+ if (live.reasons) live.reasons.background = bg.reason;
467
+ for (const fn of listeners) {
468
+ try {
469
+ fn(live);
470
+ } catch {
471
+ /* a listener must never break the session's capability resolution */
472
+ }
473
+ }
474
+ return bg;
475
+ }
476
+
179
477
  /**
180
478
  * Colour depth in bits per channel: 24 truecolor, 8 the 256-colour cube, 4 the
181
479
  * 16 ANSI slots, 0 no colour at all.
@@ -268,13 +566,17 @@ function resolveWideRunes(env) {
268
566
  * @param {object} [env] defaults to `process.env`
269
567
  * @param {object} [stdout] defaults to `process.stdout`
270
568
  * @param {string} [platform] defaults to `process.platform` (reported, not consulted)
569
+ * @param {object} [probed] the terminal's own OSC 11 answer, when the async
570
+ * entry point has one (`probeTerminalBackground()`); `null` here means "no
571
+ * one asked", which is every synchronous caller — a pipe, a test, `--print`
271
572
  */
272
- function detect(env = process.env, stdout = process.stdout, platform = process.platform) {
573
+ function detect(env = process.env, stdout = process.stdout, platform = process.platform, probed = null) {
273
574
  const isTTY = !!(stdout && stdout.isTTY);
274
575
  const glyph = resolveGlyphs(env, platform);
275
576
  const color = resolveDepth(env);
276
577
  const vt = resolveVt(env);
277
578
  const size = resolveSize(env, stdout);
579
+ const background = resolveBackground(env, probed);
278
580
  const host = platform === 'win32' ? modernWindows(env) : null;
279
581
  return {
280
582
  platform,
@@ -288,6 +590,12 @@ function detect(env = process.env, stdout = process.stdout, platform = process.p
288
590
  star: glyph.star,
289
591
  depth: color.depth,
290
592
  color: color.depth > 0,
593
+ background: background.background,
594
+ // Whether that background was *reported* or merely defaulted. A light/dark
595
+ // palette can only be checked against the terminal when this is true: it is
596
+ // what stops a stored preference from being overridden on the strength of a
597
+ // default that was never evidence.
598
+ backgroundKnown: background.known,
291
599
  vt: vt.vt,
292
600
  cols: size.cols,
293
601
  rows: size.rows,
@@ -298,6 +606,7 @@ function detect(env = process.env, stdout = process.stdout, platform = process.p
298
606
  depth: color.reason,
299
607
  vt: vt.reason,
300
608
  size: size.reason,
609
+ background: background.reason,
301
610
  },
302
611
  };
303
612
  }
@@ -512,6 +821,10 @@ function describe(c = caps()) {
512
821
  ['platform', c.windowsHost ? `${host} — ${c.windowsHost}` : host],
513
822
  ['terminal', c.termProgram || c.term || 'unknown'],
514
823
  ['locale', c.locale || 'unset'],
824
+ // Reported, not obeyed: the background picks the palette "Auto (match
825
+ // terminal)" resolves to, and it is the answer to "why is this white on
826
+ // white?" — so it belongs in the paste, next to the mark and the colour.
827
+ ['background', `${c.background} (${c.reasons.background})`],
515
828
  ['mark', c.glyphs === 'ascii' ? 'ascii' : c.face === 'edges' ? 'unicode (edges stencilled)' : 'unicode'],
516
829
  ['star', c.star],
517
830
  ['color', c.depth === 0 ? 'none' : c.depth >= 24 ? 'truecolor' : c.depth >= 8 ? '256' : '16'],
@@ -539,7 +852,18 @@ module.exports = {
539
852
  // internals the tests drive directly
540
853
  resolveGlyphs,
541
854
  resolveDepth,
855
+ resolveBackground,
542
856
  resolveVt,
543
857
  resolveSize,
544
858
  MODERN_WINDOWS,
859
+ // the terminal's own answer (OSC 11): the async startup probe and the pure
860
+ // pieces it is built from, so the parse, the threshold and the deadlined read
861
+ // are all testable without a real terminal
862
+ probeBackground,
863
+ probeTerminalBackground,
864
+ parseBackgroundReply,
865
+ relativeLuminance,
866
+ PROBE_TIMEOUT_MS,
867
+ LIGHT_LUMINANCE,
868
+ OSC11_QUERY,
545
869
  };
package/src/cloudsync.js CHANGED
@@ -101,10 +101,34 @@ function loadState() {
101
101
  };
102
102
  }
103
103
 
104
+ /**
105
+ * The quota numbers off a sync response, or null when it carried none.
106
+ *
107
+ * aegis1 `_token_quota_fields` emits **camelCase** — `tokensUsed`,
108
+ * `tokenLimit`, `tokensRemaining` — and its docstring is explicit that the
109
+ * session-named keys were *replaced* rather than aliased. The snake_case
110
+ * spellings are the pre-rename wire and are read only as a fallback.
111
+ *
112
+ * Reading snake_case alone here meant every successful push threw its quota
113
+ * reading away: `state.quota` stayed null, so `/sync status` printed "quota:
114
+ * not reported yet" forever no matter how many pushes succeeded, and the
115
+ * over-quota notice could only ever appear from a 402 body. The account was
116
+ * reporting 10 MB of 10.4 MB used the whole time.
117
+ */
118
+ function readQuota(payload) {
119
+ if (!payload || typeof payload !== 'object') return null;
120
+ const used = payload.tokensUsed != null ? payload.tokensUsed : payload.tokens_used;
121
+ const limit = payload.tokenLimit != null ? payload.tokenLimit : payload.token_limit;
122
+ if (used == null || limit == null) return null;
123
+ const u = Number(used);
124
+ const l = Number(limit);
125
+ if (!Number.isFinite(u) || !Number.isFinite(l)) return null;
126
+ return { used: u, limit: l };
127
+ }
128
+
104
129
  /**
105
130
  * Remember a quota reading from either half of a response — the numbers ride on
106
- * a successful push (`token_limit` / `tokens_used`) as well as on the 402 body,
107
- * and both are worth keeping.
131
+ * a successful push as well as on the 402 body, and both are worth keeping.
108
132
  *
109
133
  * `over` is derived here, once, so every surface (status panel, first-run
110
134
  * notice, auto-sync refusal) agrees about what "at the ceiling" means instead
@@ -185,12 +209,27 @@ function isPending(session, state) {
185
209
  return String(session.updatedAt || '') > String(rec.localUpdatedAt || '');
186
210
  }
187
211
 
188
- /** Sessions with local changes the cloud has not seen, oldest first. */
212
+ /**
213
+ * Sessions with local changes the cloud has not seen, oldest first.
214
+ *
215
+ * The candidate set is the whole store, never the recency slice
216
+ * `localSessions()` defaults to (the newest 50). `isPending` is a property of
217
+ * a session — "the cloud has not seen this version" — and not of how recently
218
+ * it was touched, so filtering a 50-session window silently drops every older
219
+ * unsynced session. On this machine that produced two contradictory answers
220
+ * from one state: `status()` scans in full and reported "pending: 8", while
221
+ * `push()` asked for the newest 50, found nothing pending in it, and `/sync
222
+ * now` said "nothing to push — every local session is already in the cloud".
223
+ * Whatever `limit` a caller passes now caps how many pending sessions are
224
+ * *returned* (oldest first, the documented drain order); it no longer changes
225
+ * which sessions count as pending.
226
+ */
189
227
  function listPending(o = {}) {
190
228
  const state = o.state || loadState();
191
- return localSessions(o)
229
+ const pending = localSessions({ ...o, limit: Number.MAX_SAFE_INTEGER })
192
230
  .filter((s) => isPending(s, state))
193
231
  .reverse();
232
+ return o.limit ? pending.slice(0, o.limit) : pending;
194
233
  }
195
234
 
196
235
  function markSynced(state, id, o = {}) {
@@ -314,17 +353,18 @@ async function push(client, o = {}) {
314
353
  localUpdatedAt: session.updatedAt,
315
354
  remoteUpdatedAt: (res && res.updated_at) || new Date().toISOString(),
316
355
  });
356
+ const quota = readQuota(res);
317
357
  pushed.push({
318
358
  id: session.id,
319
359
  remoteId,
320
360
  messages: transcript.messages.length,
321
361
  title: transcript.title,
322
- quota: res && res.token_limit ? { used: res.tokens_used, limit: res.token_limit } : null,
362
+ quota,
323
363
  });
324
364
  // A successful push is also a quota reading — the response reports the
325
365
  // running total, which is how the status panel can show "43k of 1M" on a
326
366
  // healthy account instead of only ever saying something when it breaks.
327
- if (res && res.token_limit != null) recordQuota(state, res.tokens_used, res.token_limit);
367
+ if (quota) recordQuota(state, quota.used, quota.limit);
328
368
  if (typeof o.onProgress === 'function') o.onProgress({ phase: 'push', id: session.id });
329
369
  } catch (err) {
330
370
  const info = describeError(err);
@@ -342,7 +382,10 @@ async function push(client, o = {}) {
342
382
  }
343
383
  if (pushed.length) state.lastPushAt = Date.now();
344
384
  saveState(state);
345
- return { pushed, failed, skipped, pending: listPending({ state, limit }).length };
385
+ // The remainder is counted over the WHOLE store, not the batch window — the
386
+ // caller prints this as "N still waiting", and counting only the drain cap
387
+ // would report a drained queue while sessions were still unsynced.
388
+ return { pushed, failed, skipped, pending: listPending({ state }).length };
346
389
  }
347
390
 
348
391
  /**
@@ -474,6 +517,7 @@ module.exports = {
474
517
  entriesFromRemote,
475
518
  describeError,
476
519
  recordQuota,
520
+ readQuota,
477
521
  push,
478
522
  pull,
479
523
  syncNow,