aegiscode 6.6.1 → 6.7.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.
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "aegiscode",
3
3
  "productName": "AEGIS Code",
4
- "version": "6.6.1",
4
+ "version": "6.7.0",
5
5
  "description": "aegiscode — the command-line version of AEGIS Desktop. The shared tool surface in your shell, over the same thin transport and tool registry as the MCP plugin and the desktop app. Ships transport + UI only; no brain.",
6
6
  "author": {
7
7
  "name": "AEGIS Code",
package/src/app.js CHANGED
@@ -25,8 +25,18 @@ const { createTools, createClient, usageTokens, buildSystemPrompt } = require('.
25
25
  const { createEngine } = require('./engine.js');
26
26
  const { GLYPH, VERBS, themeOf, RESET, THEME_TABLE } = require('./theme.js');
27
27
  const { LiveRegion, termWidth, w } = require('./screen.js');
28
+ const { editPreview } = require('./diff.js');
29
+ const { defaultOpen } = require('./diffview.js');
28
30
  const { parseLine, COMMANDS, visibleCommands } = require('./commands.js');
29
- const { updateConfig, loadPermissions, loadConfig, configExists } = require('./config.js');
31
+ const {
32
+ updateConfig,
33
+ loadPermissions,
34
+ loadConfig,
35
+ configExists,
36
+ memoryPersistState,
37
+ memoryPersistEnabled,
38
+ setMemoryPersist,
39
+ } = require('./config.js');
30
40
  const credentials = require('./credentials.js');
31
41
  const cloudsync = require('./cloudsync.js');
32
42
  const { readSecret } = require('./secret.js');
@@ -377,16 +387,32 @@ function createApp(options = {}) {
377
387
  return res;
378
388
  }
379
389
 
390
+ /**
391
+ * The persisting-memory gate — the WRITE half of aegis_memory, and now ON by
392
+ * default for every account (see config.js `memoryPersistState` for the
393
+ * migration and the reasoning). The name is historical: `/sync`, `/cloud sync`
394
+ * and `cloudSyncEnabled()` predate the flip, and they all mean this one gate,
395
+ * so there is exactly one boolean behind every switch and status line.
396
+ */
380
397
  function cloudSyncEnabled() {
381
398
  try {
382
- return loadConfig().cloudSync === true;
399
+ return memoryPersistEnabled();
383
400
  } catch {
384
- return false;
401
+ return true; // default on: a corrupt config must not silently stop storage
402
+ }
403
+ }
404
+
405
+ /** Where that answer came from — 'config' | 'legacy' | 'default'. */
406
+ function cloudSyncState() {
407
+ try {
408
+ return memoryPersistState();
409
+ } catch {
410
+ return { enabled: true, source: 'default', explicit: false };
385
411
  }
386
412
  }
387
413
 
388
414
  function setCloudSync(on) {
389
- return updateConfig({ cloudSync: on === true });
415
+ return setMemoryPersist(on);
390
416
  }
391
417
 
392
418
  /**
@@ -534,6 +560,22 @@ function createApp(options = {}) {
534
560
  // Presentation hooks. With no presenter these reproduce the linear
535
561
  // behaviour exactly (live-region spinner, tool rows written to scrollback).
536
562
  const p = presenter || {};
563
+ // The engine opens a tool with a `phase: 'run'` frame BEFORE the executor
564
+ // runs, so a writeFile preview built here still reads the pre-edit file.
565
+ // Cached per tool id so the later `done` frame reuses the same preview
566
+ // instead of re-reading a file the tool has already overwritten (which
567
+ // would diff clean and show nothing).
568
+ const diffCache = new Map();
569
+ const previewFor = (tool) => {
570
+ const key =
571
+ tool && tool.id !== undefined
572
+ ? `id:${tool.id}`
573
+ : `${tool && tool.name}:${JSON.stringify(tool && tool.args)}`;
574
+ if (!diffCache.has(key)) {
575
+ diffCache.set(key, editPreview(tool && tool.name, tool && tool.args, { cwd: process.cwd() }));
576
+ }
577
+ return diffCache.get(key);
578
+ };
537
579
  const present = {
538
580
  text: (d) => {
539
581
  if (p.text) return p.text(d);
@@ -547,10 +589,11 @@ function createApp(options = {}) {
547
589
  tool: (tool) => {
548
590
  if (p.tool) return p.tool(tool);
549
591
  if (live) live.clear();
592
+ const diff = previewFor(tool);
550
593
  emit(
551
594
  render.renderTurn(
552
595
  ctx(),
553
- { role: 'tool', label: tool.name, args: tool.args, ok: tool.ok },
596
+ { role: 'tool', label: tool.name, args: tool.args, ok: tool.ok, diff, diffOpen: defaultOpen(diff) },
554
597
  width()
555
598
  )
556
599
  );
@@ -911,9 +954,17 @@ function createApp(options = {}) {
911
954
  case 'error': emit(render.renderNotice(ctx(), 'error', row.text)); return;
912
955
  case 'user': emit(render.renderTurn(ctx(), { role: 'user', text: row.text, label: row.label }, W)); return;
913
956
  case 'assistant': emit(render.renderTurn(ctx(), { role: 'assistant', text: row.text }, W)); return;
914
- case 'tool':
915
- emit(render.renderTurn(ctx(), { role: 'tool', label: row.label || row.name, args: row.args, ok: row.ok }, W));
957
+ case 'tool': {
958
+ // A chatflow row carries the preview it built from the run frame
959
+ // (chatflow.js); a row pushed straight from a command handler has none,
960
+ // so build one here rather than re-showing the gray `$ {args}` row.
961
+ if (row.diff === undefined) {
962
+ row.diff = editPreview(row.name || row.label, row.args, { cwd: process.cwd() });
963
+ row.diffOpen = defaultOpen(row.diff);
964
+ }
965
+ emit(render.renderTurn(ctx(), { role: 'tool', label: row.label || row.name, args: row.args, ok: row.ok, diff: row.diff, diffOpen: !!row.diffOpen }, W));
916
966
  return;
967
+ }
917
968
  default: emit(render.renderNotice(ctx(), 'info', row.text == null ? '' : String(row.text))); return;
918
969
  }
919
970
  }
@@ -1012,6 +1063,7 @@ function createApp(options = {}) {
1012
1063
  readSecret: (text) => readSecret(text, { stdin: process.stdin, stdout: out }),
1013
1064
  cloudsync,
1014
1065
  cloudSyncEnabled: () => cloudSyncEnabled(),
1066
+ cloudSyncState: () => cloudSyncState(),
1015
1067
  setCloudSync: (on) => setCloudSync(on),
1016
1068
  adoptLegacyKey: () => adoptLegacyKeyOnce(),
1017
1069
  };
@@ -1111,12 +1163,47 @@ function createApp(options = {}) {
1111
1163
  }
1112
1164
  if (cmd.tool === 'aegis_ask') return await runPrompt(args.prompt);
1113
1165
  await runTool(cmd.tool, args);
1166
+ // `/memory` is where a user actually looks at what is stored, so the
1167
+ // quota state belongs here as well as in /cloud: the ceiling is the one
1168
+ // fact about this feature that changes what the account can do, and it is
1169
+ // invisible from the entries themselves.
1170
+ if (cmd.tool === 'aegis_memory_list' || cmd.tool === 'aegis_memory_search') memoryQuotaNote();
1114
1171
  } catch (e) {
1115
1172
  emit(render.renderNotice(ctx(), 'error', e.message));
1116
1173
  }
1117
1174
  return true;
1118
1175
  }
1119
1176
 
1177
+ /**
1178
+ * One line of quota state for the memory read commands. Quiet when the server
1179
+ * has not reported a ceiling yet (nothing useful to say), a statement when it
1180
+ * has, and — when the account is at it — the two halves spelled out: reads
1181
+ * keep working, new writes do not.
1182
+ */
1183
+ function memoryQuotaNote() {
1184
+ let st;
1185
+ try {
1186
+ st = cloudsync.status();
1187
+ } catch {
1188
+ return;
1189
+ }
1190
+ const q = st.quota;
1191
+ if (!q) return;
1192
+ const used = fmtTokens(q.used || 0);
1193
+ const limit = fmtTokens(q.limit || 0);
1194
+ if (st.overQuota) {
1195
+ emit(
1196
+ render.renderNotice(
1197
+ ctx(),
1198
+ 'warn',
1199
+ `cloud memory: ${used} of ${limit} synced tokens — at the plan's ceiling. Everything stored stays readable; new writes are paused until there is room. /cloud memory for the full state.`
1200
+ )
1201
+ );
1202
+ return;
1203
+ }
1204
+ emit(render.renderNotice(ctx(), 'info', `cloud memory: ${used} of ${limit} synced tokens — /cloud memory for the full state`));
1205
+ }
1206
+
1120
1207
  /**
1121
1208
  * Ask for a secret on this session's streams.
1122
1209
  *
@@ -1236,9 +1323,12 @@ function createApp(options = {}) {
1236
1323
  /* persistence is best-effort */
1237
1324
  }
1238
1325
  // Auto-sync hook: one place, reached by both the linear REPL and the
1239
- // chatflow's session loop, and only when the user turned it on. Off by
1240
- // default because a push is billed against the plan's synced-token ceiling
1241
- // (aegis1 charges the *growth* of a session), so uploading is a choice.
1326
+ // chatflow's session loop. On by default — a push is billed against the
1327
+ // plan's synced-token ceiling (aegis1 charges the *growth* of a session),
1328
+ // so it is a real gate rather than an unconditional write, but the default
1329
+ // is on because a session that dies at its tool-round horizon is only
1330
+ // recoverable if the transcript exists somewhere the next session can read
1331
+ // it. `/cloud memory off` is the opt-out.
1242
1332
  if (cloudSyncEnabled()) autoSync();
1243
1333
  }
1244
1334
 
@@ -1250,6 +1340,13 @@ function createApp(options = {}) {
1250
1340
  * per session per session-cycle — a quota refusal that repeats forever is a
1251
1341
  * wall of text, not information — and never thrown, because the user's turn
1252
1342
  * already succeeded by the time this runs.
1343
+ *
1344
+ * The quota refusal gets its own sentence, and it is the whole point of the
1345
+ * default flip being safe: past the plan's ceiling the account does NOT lose
1346
+ * anything it already stored (reads keep working — aegis1 meters writes
1347
+ * only), and the failure is not "sync failed", it is "there is no room left
1348
+ * for new writes". Saying which half stopped is what keeps a silent stop from
1349
+ * looking like a broken feature.
1253
1350
  */
1254
1351
  let autoSyncNotes = new Set();
1255
1352
  function autoSync() {
@@ -1261,8 +1358,18 @@ function createApp(options = {}) {
1261
1358
  const f = res.failed[0];
1262
1359
  if (autoSyncNotes.has(f.kind)) return;
1263
1360
  autoSyncNotes.add(f.kind);
1361
+ if (f.kind === 'quota') {
1362
+ emit(
1363
+ render.renderNotice(
1364
+ ctx(),
1365
+ 'warn',
1366
+ `cloud memory: the plan's synced-token ceiling is reached — earlier sessions stay readable, only NEW writes pause. /cloud memory shows the quota; /cloud memory off stops trying.`
1367
+ )
1368
+ );
1369
+ return;
1370
+ }
1264
1371
  const hint = f.hint ? ` — ${f.hint}` : '';
1265
- emit(render.renderNotice(ctx(), f.kind === 'quota' ? 'warn' : 'error', `cloud sync: ${f.message}${hint}`));
1372
+ emit(render.renderNotice(ctx(), 'error', `cloud sync: ${f.message}${hint}`));
1266
1373
  }
1267
1374
  })
1268
1375
  .catch(() => {
@@ -1270,6 +1377,38 @@ function createApp(options = {}) {
1270
1377
  });
1271
1378
  }
1272
1379
 
1380
+ /**
1381
+ * First-run notice for the write half, printed once, right after onboarding.
1382
+ *
1383
+ * The default flip is invisible otherwise: the read half was already on for
1384
+ * everyone, so nothing about the first session looks different — the thing
1385
+ * that changed is that the transcript is now being *stored*, and that costs
1386
+ * quota on a free plan. One line at the moment the account is set up is the
1387
+ * difference between a default and a surprise.
1388
+ */
1389
+ function memoryFirstRunNotice() {
1390
+ const st = cloudSyncState();
1391
+ if (!st.enabled) {
1392
+ emit(
1393
+ render.renderNotice(
1394
+ ctx(),
1395
+ 'info',
1396
+ 'cross-session memory: off (you turned it off) — /cloud memory on stores sessions so an interrupted turn can be picked up later'
1397
+ )
1398
+ );
1399
+ return;
1400
+ }
1401
+ const quota = cloudsync.status().quota;
1402
+ const usage = quota && quota.limit ? ` (used ${fmtTokens(quota.used || 0)} of ${fmtTokens(quota.limit)} tokens)` : '';
1403
+ emit(
1404
+ render.renderNotice(
1405
+ ctx(),
1406
+ 'info',
1407
+ `cross-session memory: on${usage} — sessions are stored to your account so a turn that is interrupted can be resumed. /cloud memory shows the quota; /cloud memory off stops it. Past the ceiling, saved memory stays readable and only new writes pause.`
1408
+ )
1409
+ );
1410
+ }
1411
+
1273
1412
  /** One line of session accounting, for ctrl+t and the meta row. */ function tokenSummary() {
1274
1413
  return (
1275
1414
  `${fmtTokens(session.tokens)} tok ` +
@@ -1466,6 +1605,11 @@ function createApp(options = {}) {
1466
1605
  )
1467
1606
  );
1468
1607
  }
1608
+ // The write half of cross-session memory is on by default (see
1609
+ // config.js). Say so once, on the run that sets the account up, together
1610
+ // with the ceiling and the opt-out — a default nobody is told about is a
1611
+ // setting they cannot make a decision about.
1612
+ if (onboard.firstRun) memoryFirstRunNotice();
1469
1613
  // A stored pin the platform does not advertise routes elsewhere in
1470
1614
  // silence (see validatePinnedModel) — checked once, here, where the user
1471
1615
  // can act on it. Not on `-p`: a network round-trip ahead of the first
@@ -1519,6 +1663,7 @@ function createApp(options = {}) {
1519
1663
  forgetApiKey,
1520
1664
  adoptLegacyKeyOnce,
1521
1665
  cloudSyncEnabled,
1666
+ cloudSyncState,
1522
1667
  setCloudSync,
1523
1668
  cloudsync,
1524
1669
  keyStatus: () => credentials.keyStatus(),
package/src/autonomous.js CHANGED
@@ -100,8 +100,14 @@ function describeCounts(items) {
100
100
  */
101
101
  function printRunReport(ran, io) {
102
102
  for (const r of ran) {
103
- const mark = r.ok ? '✓' : '✗';
104
- io.stdout.write(`aegiscode: ${mark} #${r.id} ${r.ok ? 'done' : 'failed'} (${fmtElapsed(r.ms)})`);
103
+ // stoppedOnRounds + ok means the task hit its tool-round horizon, not
104
+ // that it finished — the queue item is left 'pending' (autonomous.js's
105
+ // runOne) so a later proceed() resumes it. Calling that "done" would
106
+ // hide the exact case this whole mechanism exists to make visible.
107
+ const paused = Boolean(r.ok && r.stoppedOnRounds);
108
+ const mark = paused ? '⏸' : r.ok ? '✓' : '✗';
109
+ const label = paused ? 'paused — will resume' : r.ok ? 'done' : 'failed';
110
+ io.stdout.write(`aegiscode: ${mark} #${r.id} ${label} (${fmtElapsed(r.ms)})`);
105
111
  if (r.commit && r.commit.ok && r.commit.staged) {
106
112
  io.stdout.write(` — committed ${r.commit.staged} path(s)`);
107
113
  } else if (r.commit && r.commit.skipped && r.commit.reason) {
package/src/chatflow.js CHANGED
@@ -49,6 +49,8 @@ const { renderMarkdown } = require('./markdown.js');
49
49
  const overlays = require('./overlays.js');
50
50
  const fuzzy = require('./fuzzy.js');
51
51
  const { fmtTokens, fmtEur, fmtElapsed } = require('./format.js');
52
+ const { editPreview } = require('./diff.js');
53
+ const { renderDiffBlock, defaultOpen } = require('./diffview.js');
52
54
 
53
55
  /** The rotating placeholder shown on an empty input line. */
54
56
  const SUGGESTIONS = [
@@ -438,6 +440,18 @@ function rowLines(msg, cols, ctx, now = Date.now()) {
438
440
  } else {
439
441
  out.push([span(t.gray, `${label}${where}`)]);
440
442
  }
443
+ // An editFile/writeFile row carries a diff preview (built from the tool's
444
+ // `run` frame, before the executor reads/writes). Paint the colored block —
445
+ // summary always, body when open — instead of the gray `$ {args}` row, so
446
+ // the transcript shows *what* changed. renderDiffBlock emits ANSI strings,
447
+ // so each becomes one pre-styled span whose visible width padLine still
448
+ // measures and pads correctly.
449
+ if (msg.diff) {
450
+ for (const l of renderDiffBlock(msg.diff, ctx, cols, { open: !!msg.diffOpen })) {
451
+ out.push([span('', l)]);
452
+ }
453
+ return out;
454
+ }
441
455
  const argsStr =
442
456
  typeof msg.args === 'string'
443
457
  ? msg.args
@@ -560,21 +574,34 @@ function transcriptLines(rows, view, ctx, now = Date.now(), cache = null) {
560
574
  const { cols, rows: termRows } = view;
561
575
  const avail = Math.max(1, termRows - 6);
562
576
  const out = [];
577
+ // Which transcript row produced each line, in lockstep with `out`. The frame
578
+ // builder needs it to map a clicked screen row back to the row it toggles.
579
+ const owners = [];
563
580
  for (const msg of rows) {
564
581
  const key = cache || null;
565
582
  const isGrower = msg.role === 'assistant' && msg.streaming;
566
583
  if (key && !isGrower) {
567
584
  const hit = key.get(msg);
568
- if (hit && hit.text === msg.text && hit.cols === cols) {
569
- for (const l of hit.segment) out.push(l);
585
+ // diffOpen is part of the cache key: a toggled edit block must re-render.
586
+ if (hit && hit.text === msg.text && hit.cols === cols && hit.diffOpen === msg.diffOpen) {
587
+ for (const l of hit.segment) {
588
+ out.push(l);
589
+ owners.push(msg);
590
+ }
570
591
  continue;
571
592
  }
572
593
  const segment = rowLines(msg, cols, ctx, now);
573
- key.set(msg, { text: msg.text, cols, segment });
574
- for (const l of segment) out.push(l);
594
+ key.set(msg, { text: msg.text, cols, diffOpen: msg.diffOpen, segment });
595
+ for (const l of segment) {
596
+ out.push(l);
597
+ owners.push(msg);
598
+ }
575
599
  continue;
576
600
  }
577
- for (const l of rowLines(msg, cols, ctx, now)) out.push(l);
601
+ for (const l of rowLines(msg, cols, ctx, now)) {
602
+ out.push(l);
603
+ owners.push(msg);
604
+ }
578
605
  }
579
606
 
580
607
  let scroll = view.scroll || 0;
@@ -596,7 +623,7 @@ function transcriptLines(rows, view, ctx, now = Date.now(), cache = null) {
596
623
  end = total;
597
624
  }
598
625
  const start = Math.max(0, end - avail);
599
- return { lines: out.slice(start, end), scroll, anchorEnd };
626
+ return { lines: out.slice(start, end), owners: owners.slice(start, end), scroll, anchorEnd };
600
627
  }
601
628
 
602
629
  // ── the input line ──────────────────────────────────────────────────────────
@@ -738,6 +765,10 @@ async function runSession(host) {
738
765
  let suggestionIdx = 0;
739
766
  let scroll = 0;
740
767
  let anchorEnd = null;
768
+ // Screen row (1-based, as the mouse reports it) → the transcript row painted
769
+ // there. Rebuilt on every frame so it follows scrolling; a click reads it to
770
+ // find which edit block to toggle.
771
+ const clickHits = new Map();
741
772
  let insertMode = false;
742
773
  let hintUntil = 0;
743
774
  let hintText = '';
@@ -767,6 +798,10 @@ async function runSession(host) {
767
798
  const view = transcriptLines(transcript, { cols, rows, scroll, anchorEnd }, ctx, Date.now(), lineCache);
768
799
  scroll = view.scroll;
769
800
  anchorEnd = view.anchorEnd;
801
+ // The header is frame line 0 (screen row 1), so the transcript window starts
802
+ // at screen row 2; each painted line carries its source row in view.owners.
803
+ clickHits.clear();
804
+ for (let i = 0; i < view.lines.length; i++) clickHits.set(2 + i, view.owners[i]);
770
805
  for (const l of view.lines) lines.push(l);
771
806
  // Exactly `avail` transcript rows, so the frame is exactly `rows` lines:
772
807
  // header(1) + transcript(avail) + spinner/effort + rule + input + rule +
@@ -1223,6 +1258,18 @@ async function runSession(host) {
1223
1258
  if (key.name === KEY.PAGE_UP) d = +5;
1224
1259
  else if (key.name === KEY.PAGE_DOWN) d = -5;
1225
1260
  else if (key.name === 'wheel') d = key.dir === 'up' ? +3 : -3;
1261
+ else if (key.name === 'click') {
1262
+ // A click on an edit row toggles its diff block. Not a scroll, but the
1263
+ // same "act on the live frame, then repaint" shape — and routing it
1264
+ // through here means it works both at the idle prompt and mid-turn,
1265
+ // since drainWhileWorking feeds this same function.
1266
+ const msg = clickHits.get(key.row);
1267
+ if (msg && msg.diff) {
1268
+ msg.diffOpen = !msg.diffOpen;
1269
+ scheduleRender();
1270
+ }
1271
+ return true; // consumed: a click is never replayed as typed-ahead input
1272
+ }
1226
1273
  else if (key.name === 'char' && ctx.vim && !insertMode && !editor.buf) {
1227
1274
  if (key.ch === 'j') d = +1;
1228
1275
  else if (key.ch === 'k') d = -1;
@@ -1654,6 +1701,12 @@ async function runSession(host) {
1654
1701
  await dispatch('/permissions');
1655
1702
  return;
1656
1703
  }
1704
+ if (key.name === 'click') {
1705
+ // Consumed here: it either toggles an edit row's diff block or does
1706
+ // nothing, but must never fall through to the input editor.
1707
+ applyLiveScroll(key);
1708
+ return;
1709
+ }
1657
1710
  if (key.name === KEY.PAGE_UP || key.name === KEY.PAGE_DOWN || key.name === 'wheel') {
1658
1711
  applyLiveScroll(key);
1659
1712
  return;
package/src/cloudsync.js CHANGED
@@ -29,10 +29,22 @@
29
29
  * Quota note, because it is the difference between a working sync and a
30
30
  * surprise: the server charges a push for the *growth* of a session
31
31
  * (`_session_token_delta` in aegis1's conversation_sync), refuses with 402 once
32
- * the plan's synced-token ceiling would be exceeded, and always serves pulls.
33
- * So sync is opt-in (config `cloudSync`, default off) rather than automatic on
34
- * every turn, and a 402 is reported as the quota error it is instead of being
35
- * swallowed into "sync failed".
32
+ * the plan's synced-token ceiling would be exceeded (FREE_SYNC_TOKENS = 1 MB,
33
+ * PRO_SYNC_TOKENS = 10 MB), and always serves pulls. So a 402 is reported as the
34
+ * quota error it is instead of being swallowed into "sync failed".
35
+ *
36
+ * This used to be the reason sync was opt-IN (config `cloudSync`, default off):
37
+ * automatic writes against a metered ceiling felt like spending someone else's
38
+ * money. It is now default ON (config `memoryPersist` — see config.js for the
39
+ * migration), because the ceiling is not a hard stop: aegis1's
40
+ * `_memory_sync_access()` enforces the limit on WRITES only, so an over-quota
41
+ * account still reads back everything it stored. What was missing was not
42
+ * caution, it was honesty: a free account passes ~1 MB of transcript in weeks,
43
+ * and the old failure mode was a silent stop with no visible state. So this
44
+ * module now records the quota it is told about (`status().quota`) and
45
+ * classifies the refusal as "writes paused, reads fine" rather than as a
46
+ * generic failure — `/cloud memory` (and the first-run notice) say exactly
47
+ * that, and `/cloud memory off` is the explicit opt-out.
36
48
  */
37
49
 
38
50
  const fs = require('node:fs');
@@ -70,10 +82,40 @@ function loadState() {
70
82
  // whole transcript, so every pull duplicated every earlier exchange and
71
83
  // /cost doubled with each sync.
72
84
  importedRemoteCount: parsed.importedRemoteCount || {},
85
+ // The last quota the server told us about — `{ used, limit, at, over }`.
86
+ // Persisted because it is the only way the NEXT run can say "you are at
87
+ // the ceiling, only new writes are paused" before it has re-attempted a
88
+ // push: without it, a restarted session looks identical to a fresh one
89
+ // and the over-quota state is invisible until the next refused write.
90
+ quota: parsed.quota && typeof parsed.quota === 'object' ? parsed.quota : null,
73
91
  };
74
92
  }
75
93
  } catch {}
76
- return { sessions: {}, lastPushAt: null, lastPullAt: null, importedRemoteAt: {}, importedRemoteCount: {} };
94
+ return {
95
+ sessions: {},
96
+ lastPushAt: null,
97
+ lastPullAt: null,
98
+ importedRemoteAt: {},
99
+ importedRemoteCount: {},
100
+ quota: null,
101
+ };
102
+ }
103
+
104
+ /**
105
+ * 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.
108
+ *
109
+ * `over` is derived here, once, so every surface (status panel, first-run
110
+ * notice, auto-sync refusal) agrees about what "at the ceiling" means instead
111
+ * of each comparing used >= limit on its own.
112
+ */
113
+ function recordQuota(state, used, limit) {
114
+ const u = Number(used);
115
+ const l = Number(limit);
116
+ if (!state || !Number.isFinite(u) || !Number.isFinite(l) || l <= 0) return null;
117
+ state.quota = { used: u, limit: l, over: u >= l, at: Date.now() };
118
+ return state.quota;
77
119
  }
78
120
 
79
121
  function saveState(state) {
@@ -217,7 +259,23 @@ function describeError(err) {
217
259
  const status = err && (err.status || (err.response && err.response.status));
218
260
  const message = (err && err.message) || String(err);
219
261
  if (status === 402) {
220
- return { kind: 'quota', status, message, hint: 'the plan’s synced-token ceiling is reached — /cloud sync off, or free space in the account dashboard' };
262
+ // The 402 body carries the quota (`tokensUsed` / `tokenLimit`, from aegis1
263
+ // `_token_quota_fields`); the legacy session-named keys are read only as a
264
+ // fallback for a server that predates the rename.
265
+ const data = (err && err.data) || {};
266
+ const used = data.tokensUsed != null ? data.tokensUsed : data.sessionsUsed;
267
+ const limit = data.tokenLimit != null ? data.tokenLimit : data.freeSessionLimit;
268
+ return {
269
+ kind: 'quota',
270
+ status,
271
+ message,
272
+ used: used != null ? Number(used) : null,
273
+ limit: limit != null ? Number(limit) : null,
274
+ // The refusal is about WRITES only — say what still works and how to stop
275
+ // trying, instead of implying the account lost its memory.
276
+ hint:
277
+ 'the plan’s synced-token ceiling is reached — everything already stored stays readable, only NEW writes pause: /cloud memory shows the quota, /cloud memory off stops syncing',
278
+ };
221
279
  }
222
280
  if (status === 401) {
223
281
  return { kind: 'auth', status, message, hint: 'the memory token was refused — run /key <api_key> to re-exchange it' };
@@ -263,11 +321,22 @@ async function push(client, o = {}) {
263
321
  title: transcript.title,
264
322
  quota: res && res.token_limit ? { used: res.tokens_used, limit: res.token_limit } : null,
265
323
  });
324
+ // A successful push is also a quota reading — the response reports the
325
+ // running total, which is how the status panel can show "43k of 1M" on a
326
+ // 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);
266
328
  if (typeof o.onProgress === 'function') o.onProgress({ phase: 'push', id: session.id });
267
329
  } catch (err) {
268
330
  const info = describeError(err);
269
331
  markFailed(state, session.id, info.message);
270
332
  failed.push({ id: session.id, ...info });
333
+ // Record the ceiling state even when the body carried no numbers: the
334
+ // point of the honesty fix is that the stopped state is visible, and a
335
+ // server that refuses without reporting a limit must not produce a status
336
+ // panel that looks healthy.
337
+ if (info.kind === 'quota' && !recordQuota(state, info.used, info.limit)) {
338
+ state.quota = { used: null, limit: null, over: true, at: Date.now() };
339
+ }
271
340
  if (info.kind === 'quota' || info.kind === 'auth') break; // every later one fails the same way
272
341
  }
273
342
  }
@@ -367,6 +436,8 @@ function status() {
367
436
  const errors = sessions
368
437
  .filter((s) => state.sessions[s.id] && state.sessions[s.id].lastError)
369
438
  .map((s) => ({ id: s.id, error: state.sessions[s.id].lastError }));
439
+ const quota = state.quota || null;
440
+ const overQuota = Boolean(quota && quota.over);
370
441
  return {
371
442
  local: sessions.length,
372
443
  pending: pending.length,
@@ -375,6 +446,14 @@ function status() {
375
446
  lastPullAt: state.lastPullAt,
376
447
  importedRemote: Object.keys(state.importedRemoteAt || {}).length,
377
448
  errors,
449
+ // The ceiling, as last reported by the server, plus whether new writes are
450
+ // currently stopped by it. `paused` is the combination the panels print:
451
+ // there is local work waiting AND the last thing the server said was "no
452
+ // room". Both halves matter — a full account with nothing pending is not
453
+ // stuck, it is caught up.
454
+ quota,
455
+ overQuota,
456
+ paused: overQuota && pending.length > 0,
378
457
  path: syncStatePath(),
379
458
  historyPath: historyPath(),
380
459
  };
@@ -394,6 +473,7 @@ module.exports = {
394
473
  markFailed,
395
474
  entriesFromRemote,
396
475
  describeError,
476
+ recordQuota,
397
477
  push,
398
478
  pull,
399
479
  syncNow,