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 +1 -1
- package/src/app.js +156 -11
- package/src/autonomous.js +8 -2
- package/src/chatflow.js +59 -6
- package/src/cloudsync.js +86 -6
- package/src/commands.js +158 -22
- package/src/config.js +87 -0
- package/src/diff.js +330 -0
- package/src/diffview.js +286 -0
- package/src/events.js +21 -10
- package/src/render.js +12 -1
- package/src/theme.js +72 -0
- package/vendor/desktop/lib/local/autonomous.js +45 -4
- package/vendor/desktop/lib/local/engine.js +38 -0
- package/vendor/desktop/lib/local/queue.js +4 -0
- package/vendor/desktop/lib/local/session-rounds.js +19 -2
package/src/commands.js
CHANGED
|
@@ -50,6 +50,7 @@ const overlays = require('./overlays.js');
|
|
|
50
50
|
const {
|
|
51
51
|
updateConfig, loadConfig, loadPermissions, savePermissions, addPermissionRule,
|
|
52
52
|
DEFAULT_PERMISSIONS, permissionsPath, configPath,
|
|
53
|
+
memoryPersistState, setMemoryPersist,
|
|
53
54
|
} = require('./config.js');
|
|
54
55
|
const { copyToClipboard } = require('./clipboard.js');
|
|
55
56
|
const { snapshotCheckpoint, listCheckpoints, loadCheckpoint } = require('./checkpoint.js');
|
|
@@ -60,7 +61,7 @@ const { transcriptToMarkdown, transcriptToJSON, writeExportFile, lastAssistantTe
|
|
|
60
61
|
const { detectDevCommand, runDevServer } = require('./devrun.js');
|
|
61
62
|
const credentials = require('./credentials.js');
|
|
62
63
|
const cloudsync = require('./cloudsync.js');
|
|
63
|
-
const { maskKey } = require('./format.js');
|
|
64
|
+
const { maskKey, fmtTokens } = require('./format.js');
|
|
64
65
|
const { openUrl, URLS } = require('./system.js');
|
|
65
66
|
const { sniffProject, buildAegisMd } = require('./init.js');
|
|
66
67
|
const {
|
|
@@ -216,6 +217,113 @@ async function applyAccountKey(c, raw, { label = 'AEGIS API key' } = {}) {
|
|
|
216
217
|
return res;
|
|
217
218
|
}
|
|
218
219
|
|
|
220
|
+
/** Human token count for the sync quota: 1000000 -> "1M", 42800 -> "43k".
|
|
221
|
+
* The ceiling is denominated in tokens (aegis1 FREE_SYNC_TOKENS = 1 MB,
|
|
222
|
+
* PRO_SYNC_TOKENS = 10 MB), which for stored prose is about one per
|
|
223
|
+
* character — "1000000" at a glance tells a user nothing about how close they
|
|
224
|
+
* are to it. */
|
|
225
|
+
function fmtQuotaTokens(n) {
|
|
226
|
+
const v = Number(n);
|
|
227
|
+
if (!Number.isFinite(v)) return '?';
|
|
228
|
+
if (v >= 1e6) return `${(v / 1e6).toFixed(v % 1e6 === 0 ? 0 : 1)}M`;
|
|
229
|
+
if (v >= 1e4) return `${Math.round(v / 1e3)}k`;
|
|
230
|
+
return fmtTokens(v);
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
/**
|
|
234
|
+
* The persisting-memory gate, read off the command context (the live app
|
|
235
|
+
* exposes `cloudSyncState()`) with a fallback for callers that only pass the
|
|
236
|
+
* older boolean probe — `/cloud` and `/sync` predate the rename, and a stub
|
|
237
|
+
* context in a test must not have to grow a method to render a panel.
|
|
238
|
+
*/
|
|
239
|
+
function memoryGate(c) {
|
|
240
|
+
if (c && typeof c.cloudSyncState === 'function') {
|
|
241
|
+
try {
|
|
242
|
+
return c.cloudSyncState();
|
|
243
|
+
} catch {
|
|
244
|
+
/* fall through to the boolean */
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
const enabled =
|
|
248
|
+
c && typeof c.cloudSyncEnabled === 'function' ? c.cloudSyncEnabled() === true : true;
|
|
249
|
+
return { enabled, source: 'default' };
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
/**
|
|
253
|
+
* Flip the gate through the command context (app.js's `setCloudSync` is
|
|
254
|
+
* `config.setMemoryPersist`), which is what keeps the setting and the running
|
|
255
|
+
* session agreeing. Guarded because a context stub that never flips anything
|
|
256
|
+
* still has to be able to *run* the handler — the command smoke test drives
|
|
257
|
+
* every handler with no arguments.
|
|
258
|
+
*/
|
|
259
|
+
function setMemoryGate(c, on) {
|
|
260
|
+
if (c && typeof c.setCloudSync === 'function') return c.setCloudSync(on);
|
|
261
|
+
try {
|
|
262
|
+
return setMemoryPersist(on);
|
|
263
|
+
} catch {
|
|
264
|
+
return null;
|
|
265
|
+
}
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
/**
|
|
269
|
+
* The persisting-memory block every cloud surface shows: the switch, the
|
|
270
|
+
* ceiling, and — the part that was missing — what a stopped write does and
|
|
271
|
+
* does not cost.
|
|
272
|
+
*
|
|
273
|
+
* The honesty requirement is not cosmetic. aegis1 meters WRITES only
|
|
274
|
+
* (`_memory_sync_access`), so a free account that passes ~1 MB of transcript
|
|
275
|
+
* keeps every entry it stored and simply stops accumulating new ones. The old
|
|
276
|
+
* rollout printed nothing at all, so "memory is free with any account" and
|
|
277
|
+
* "nothing is being stored any more" were both true and indistinguishable.
|
|
278
|
+
* These lines make the ceiling a state the user can see: the number, whose
|
|
279
|
+
* limit it is, and the one sentence that separates the working half (reads)
|
|
280
|
+
* from the stopped half (new writes).
|
|
281
|
+
*/
|
|
282
|
+
function memoryStatusLines(c) {
|
|
283
|
+
const gate = memoryGate(c);
|
|
284
|
+
const st = cloudsync.status();
|
|
285
|
+
const q = st.quota;
|
|
286
|
+
const used = q && q.used != null ? fmtQuotaTokens(q.used) : null;
|
|
287
|
+
const limit = q && q.limit != null ? fmtQuotaTokens(q.limit) : null;
|
|
288
|
+
const how =
|
|
289
|
+
gate.source === 'legacy'
|
|
290
|
+
? ' (kept from your old cloudSync setting)'
|
|
291
|
+
: gate.source === 'default'
|
|
292
|
+
? ' (default)'
|
|
293
|
+
: '';
|
|
294
|
+
const rows = [
|
|
295
|
+
// Both names, one gate. The commit that flipped the default renamed the
|
|
296
|
+
// panel to say what is being stored, but `/sync`, `/cloud sync` and the
|
|
297
|
+
// docs all still call it cloud sync — a panel that only answers to its new
|
|
298
|
+
// name makes the setting unfindable to anyone who learned the old one.
|
|
299
|
+
[span(C.white + BOLD, 'Persisting memory'), span(C.gray, ' · Cloud sync'), span(BOLD_OFF, '')],
|
|
300
|
+
[span(C.gray, '─'.repeat(34))],
|
|
301
|
+
[
|
|
302
|
+
span(C.white, ` ${gate.enabled ? 'on' : 'off'}`),
|
|
303
|
+
span(C.gray, `${how} · ${gate.enabled ? 'each session is stored so an interrupted turn can be resumed' : 'nothing new is stored'}`),
|
|
304
|
+
],
|
|
305
|
+
];
|
|
306
|
+
if (limit) {
|
|
307
|
+
rows.push([
|
|
308
|
+
span(C.gray, ' quota: '),
|
|
309
|
+
span(C.white, `${used} of ${limit} tokens synced`),
|
|
310
|
+
span(C.gray, ' (aegis1 charges writes; reads are always served)'),
|
|
311
|
+
]);
|
|
312
|
+
} else {
|
|
313
|
+
rows.push([span(C.gray, ' quota: not reported yet — /sync now asks the server for the current numbers')]);
|
|
314
|
+
}
|
|
315
|
+
if (st.overQuota) {
|
|
316
|
+
rows.push([span(C.coral, ' writes: paused — the plan’s ceiling is reached, so new memory is not being stored')]);
|
|
317
|
+
rows.push([span(C.green, ' reads: still work — everything already stored stays readable (/aegis-recall <topic>)')]);
|
|
318
|
+
rows.push([span(C.gray, ' free room at https://aegiscloud.org/subscribe, or /cloud memory off to stop trying')]);
|
|
319
|
+
}
|
|
320
|
+
if (gate.enabled && st.pending > 0) {
|
|
321
|
+
rows.push([span(C.gray, ` pending: ${st.pending} session(s) waiting to sync`)]);
|
|
322
|
+
}
|
|
323
|
+
rows.push([span(C.gray, ` /cloud memory on | off · /sync now pushes once by hand`)]);
|
|
324
|
+
return rows;
|
|
325
|
+
}
|
|
326
|
+
|
|
219
327
|
/** Push + pull once, and report the counts (or the quota refusal). */
|
|
220
328
|
async function runCloudSync(c, o = {}) {
|
|
221
329
|
if (!c.client.apiKey) {
|
|
@@ -1364,7 +1472,7 @@ const COMMANDS = [
|
|
|
1364
1472
|
},
|
|
1365
1473
|
},
|
|
1366
1474
|
{
|
|
1367
|
-
name: 'cloud', args: ['sub', 'value'], hint: '[status|key <api_key>|activate|deactivate|sync [on|off|now]]', category: 'support',
|
|
1475
|
+
name: 'cloud', args: ['sub', 'value'], hint: '[status|key <api_key>|activate|deactivate|memory [on|off]|sync [on|off|now]]', category: 'support',
|
|
1368
1476
|
desc: 'Show and control ÆGIS cloud sync',
|
|
1369
1477
|
handler: async (c, args) => {
|
|
1370
1478
|
const sub = (args.sub || '').toLowerCase();
|
|
@@ -1408,12 +1516,35 @@ const COMMANDS = [
|
|
|
1408
1516
|
return true;
|
|
1409
1517
|
}
|
|
1410
1518
|
|
|
1519
|
+
if (sub === 'memory' || sub === 'persist' || sub === 'memory-persist') {
|
|
1520
|
+
// The write half's one switch. `/cloud sync on|off` and `/sync on|off`
|
|
1521
|
+
// still work (they always meant "should this host store my sessions"),
|
|
1522
|
+
// but this is the name that says what is actually being flipped.
|
|
1523
|
+
const mode = (rest || 'status').toLowerCase();
|
|
1524
|
+
if (mode === 'on' || mode === 'off') {
|
|
1525
|
+
const on = mode === 'on';
|
|
1526
|
+
setMemoryGate(c, on);
|
|
1527
|
+
if (on) {
|
|
1528
|
+
done(c, 'persisting memory on — sessions are stored to your account so an interrupted turn can be resumed');
|
|
1529
|
+
note(c, '/cloud memory shows the quota; past the plan’s ceiling reads keep working and only new writes pause');
|
|
1530
|
+
} else {
|
|
1531
|
+
note(c, 'persisting memory off — nothing new is stored');
|
|
1532
|
+
note(c, 'everything already in the cloud stays readable (/aegis-recall <topic>), and /sync now still pushes once by hand');
|
|
1533
|
+
}
|
|
1534
|
+
c.render();
|
|
1535
|
+
return true;
|
|
1536
|
+
}
|
|
1537
|
+
panel(c, memoryStatusLines(c));
|
|
1538
|
+
c.render();
|
|
1539
|
+
return true;
|
|
1540
|
+
}
|
|
1541
|
+
|
|
1411
1542
|
if (sub === 'sync' || sub === 'push' || sub === 'pull') {
|
|
1412
1543
|
const mode = sub === 'sync' ? (rest || 'status').toLowerCase() : sub;
|
|
1413
1544
|
if (mode === 'on' || mode === 'off') {
|
|
1414
1545
|
const on = mode === 'on';
|
|
1415
|
-
c
|
|
1416
|
-
note(c, on ? '
|
|
1546
|
+
setMemoryGate(c, on);
|
|
1547
|
+
note(c, on ? 'persisting memory on — sessions are stored after each turn (this is the old "cloud sync")' : 'persisting memory off — nothing new is stored; /sync now still runs a manual pass');
|
|
1417
1548
|
c.render();
|
|
1418
1549
|
return true;
|
|
1419
1550
|
}
|
|
@@ -1423,18 +1554,17 @@ const COMMANDS = [
|
|
|
1423
1554
|
return true;
|
|
1424
1555
|
}
|
|
1425
1556
|
const st = cloudsync.status();
|
|
1426
|
-
|
|
1427
|
-
|
|
1428
|
-
[span(C.gray, '
|
|
1429
|
-
[span(C.white
|
|
1557
|
+
panel(c, [
|
|
1558
|
+
...memoryStatusLines(c),
|
|
1559
|
+
[span(C.gray, '')],
|
|
1560
|
+
[span(C.white + BOLD, 'Sync ledger'), span(BOLD_OFF, '')],
|
|
1430
1561
|
[span(C.gray, ` local sessions: ${st.local} · pending push: ${st.pending} · in sync: ${st.synced}`)],
|
|
1431
1562
|
[span(C.gray, ` last push: ${st.lastPushAt ? new Date(st.lastPushAt).toLocaleString() : 'never'} · last pull: ${st.lastPullAt ? new Date(st.lastPullAt).toLocaleString() : 'never'}`)],
|
|
1432
1563
|
[span(C.gray, ` state: ${st.path}`)],
|
|
1433
|
-
];
|
|
1564
|
+
]);
|
|
1434
1565
|
for (const e of st.errors.slice(0, 3)) {
|
|
1435
|
-
|
|
1566
|
+
panel(c, [[span(C.coral, ` ⚠ ${e.error}`)]]);
|
|
1436
1567
|
}
|
|
1437
|
-
panel(c, rows);
|
|
1438
1568
|
c.render();
|
|
1439
1569
|
return true;
|
|
1440
1570
|
}
|
|
@@ -1444,9 +1574,17 @@ const COMMANDS = [
|
|
|
1444
1574
|
panel(c, [
|
|
1445
1575
|
...keyPanelLines(c, 'AEGIS cloud'),
|
|
1446
1576
|
[span(C.gray, '')],
|
|
1577
|
+
...memoryStatusLines(c),
|
|
1578
|
+
[span(C.gray, '')],
|
|
1447
1579
|
[span(C.white + BOLD, ' Sync'), span(BOLD_OFF, '')],
|
|
1448
|
-
[span(C.gray, ` ${
|
|
1449
|
-
|
|
1580
|
+
[span(C.gray, ` ${st.pending} pending · ${st.synced} in sync · ${st.importedRemote} pulled from cloud`)],
|
|
1581
|
+
// Both names, because both work: `/cloud memory` is the new one that
|
|
1582
|
+
// says what is being flipped, and `/cloud sync` is what every user who
|
|
1583
|
+
// has ever turned this off typed (it dispatched here before the flip
|
|
1584
|
+
// renamed the panel, and still does — see the `sub === 'sync'` branch).
|
|
1585
|
+
// Advertising only the new name hides a working control behind a
|
|
1586
|
+
// rename, which is how a setting becomes a rumour.
|
|
1587
|
+
[span(C.gray, ' /cloud memory on | off · /cloud sync on | off · /sync now')],
|
|
1450
1588
|
]);
|
|
1451
1589
|
c.render();
|
|
1452
1590
|
return true;
|
|
@@ -1479,24 +1617,22 @@ const COMMANDS = [
|
|
|
1479
1617
|
},
|
|
1480
1618
|
{
|
|
1481
1619
|
name: 'sync', aliases: ['cloudsync', 'cloud-sync'], args: ['mode'], hint: '[now|on|off|status]', category: 'data',
|
|
1482
|
-
desc: '
|
|
1620
|
+
desc: 'Store sessions in AEGIS Cloud (cross-session memory)',
|
|
1483
1621
|
hidden: (c) => !cloudReady(),
|
|
1484
1622
|
handler: async (c, args) => {
|
|
1485
1623
|
const mode = (args.mode || '').toLowerCase();
|
|
1486
1624
|
if (mode === 'on' || mode === 'off') {
|
|
1487
|
-
c
|
|
1488
|
-
note(c, mode === 'on' ? '
|
|
1625
|
+
setMemoryGate(c, mode === 'on');
|
|
1626
|
+
note(c, mode === 'on' ? 'persisting memory on — sessions are stored so an interrupted turn can be resumed' : 'persisting memory off — nothing new is stored; /sync now still runs a manual pass');
|
|
1489
1627
|
c.render();
|
|
1490
1628
|
return true;
|
|
1491
1629
|
}
|
|
1492
1630
|
if (mode === 'status') {
|
|
1493
1631
|
const st = cloudsync.status();
|
|
1494
|
-
|
|
1495
|
-
|
|
1496
|
-
|
|
1497
|
-
|
|
1498
|
-
[span(C.gray, ` local ${st.local} · pending ${st.pending} · in sync ${st.synced}`)],
|
|
1499
|
-
]);
|
|
1632
|
+
const rows = memoryStatusLines(c);
|
|
1633
|
+
rows.push([span(C.gray, '')]);
|
|
1634
|
+
rows.push([span(C.gray, ` local ${st.local} · pending ${st.pending} · in sync ${st.synced}`)]);
|
|
1635
|
+
panel(c, rows);
|
|
1500
1636
|
c.render();
|
|
1501
1637
|
return true;
|
|
1502
1638
|
}
|
package/src/config.js
CHANGED
|
@@ -75,6 +75,87 @@ const DEFAULT_CONFIG = {
|
|
|
75
75
|
lastCwd: '',
|
|
76
76
|
};
|
|
77
77
|
|
|
78
|
+
// ── persisting memory (the WRITE half of aegis_memory) ──────────────────────
|
|
79
|
+
|
|
80
|
+
/**
|
|
81
|
+
* Cross-session memory has two halves. The READ half (`aegis_recall`) is sent
|
|
82
|
+
* unconditionally by both hosts — it is cheap, it is what lets an interrupted
|
|
83
|
+
* turn be picked up in a later session, and it is free on every plan. The
|
|
84
|
+
* WRITE half is what actually stored anything, and it used to sit behind
|
|
85
|
+
* `cloudSync`, which is absent (i.e. off) on every fresh install. That is the
|
|
86
|
+
* defect this key replaces: the copy promises "cross-session memory free with
|
|
87
|
+
* any account", the read half shipped to everybody, and the write half — the
|
|
88
|
+
* half that makes the promise true — was opt-in and undiscoverable.
|
|
89
|
+
*
|
|
90
|
+
* So the gate is now `memoryPersist` and it defaults ON. It stays a real gate:
|
|
91
|
+
* `/cloud memory off` (or `/sync off`) writes it false, and this resolver
|
|
92
|
+
* honours it. The write half also has a price, so the ceiling is surfaced
|
|
93
|
+
* rather than guessed at — aegis1 meters WRITES only (FREE_SYNC_TOKENS = 1 MB,
|
|
94
|
+
* PRO_SYNC_TOKENS = 10 MB); reads keep working past it. `/cloud memory` and the
|
|
95
|
+
* first-run notice state that in those words.
|
|
96
|
+
*
|
|
97
|
+
* Migration, not a reset. `loadConfig()` merges DEFAULT_CONFIG under the parsed
|
|
98
|
+
* file, so the *absence* of a key cannot be told from a default once merged —
|
|
99
|
+
* that is why this resolver reads the raw values in the order below instead of
|
|
100
|
+
* checking a merged boolean:
|
|
101
|
+
*
|
|
102
|
+
* memoryPersist (explicit) → cloudSync (an explicit pre-flip choice)
|
|
103
|
+
* → MEMORY_PERSIST_DEFAULT (on)
|
|
104
|
+
*
|
|
105
|
+
* An explicit `cloudSync: false` on disk therefore stays off (nobody who turned
|
|
106
|
+
* sync off gets quietly opted back in), an explicit `cloudSync: true` stays on,
|
|
107
|
+
* and a config with neither key becomes on. `setMemoryPersist()` then removes
|
|
108
|
+
* the legacy key, so the choice exists in exactly one place from then on.
|
|
109
|
+
*/
|
|
110
|
+
const MEMORY_PERSIST_KEY = 'memoryPersist';
|
|
111
|
+
const LEGACY_MEMORY_PERSIST_KEY = 'cloudSync';
|
|
112
|
+
const MEMORY_PERSIST_DEFAULT = true;
|
|
113
|
+
|
|
114
|
+
/**
|
|
115
|
+
* Resolve the write half, with where the answer came from.
|
|
116
|
+
*
|
|
117
|
+
* @param {object} [cfg] a loaded config (defaults to `loadConfig()`).
|
|
118
|
+
* @returns {{enabled:boolean, source:'config'|'legacy'|'default'}}
|
|
119
|
+
* `explicit` is true for the first two — that is the distinction the
|
|
120
|
+
* status panels need to say "you turned this off" vs "this is the
|
|
121
|
+
* default", which is the difference between a setting and a rumour.
|
|
122
|
+
*/
|
|
123
|
+
function memoryPersistState(cfg) {
|
|
124
|
+
let c = cfg;
|
|
125
|
+
if (!c) {
|
|
126
|
+
try {
|
|
127
|
+
c = loadConfig();
|
|
128
|
+
} catch {
|
|
129
|
+
return { enabled: MEMORY_PERSIST_DEFAULT, source: 'default', explicit: false };
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
if (c && typeof c[MEMORY_PERSIST_KEY] === 'boolean') {
|
|
133
|
+
return { enabled: c[MEMORY_PERSIST_KEY], source: 'config', explicit: true };
|
|
134
|
+
}
|
|
135
|
+
if (c && typeof c[LEGACY_MEMORY_PERSIST_KEY] === 'boolean') {
|
|
136
|
+
return { enabled: c[LEGACY_MEMORY_PERSIST_KEY], source: 'legacy', explicit: true };
|
|
137
|
+
}
|
|
138
|
+
return { enabled: MEMORY_PERSIST_DEFAULT, source: 'default', explicit: false };
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
/** True when this host should persist memory (default on — see above). */
|
|
142
|
+
function memoryPersistEnabled(cfg) {
|
|
143
|
+
return memoryPersistState(cfg).enabled;
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
/**
|
|
147
|
+
* Persist the flip, and retire the legacy key in the same write so the two can
|
|
148
|
+
* never disagree. `undefined` (not `false`) is what removes a key through
|
|
149
|
+
* JSON.stringify — writing `false` would look like an explicit opt-out under
|
|
150
|
+
* the legacy name.
|
|
151
|
+
*/
|
|
152
|
+
function setMemoryPersist(on) {
|
|
153
|
+
return updateConfig({
|
|
154
|
+
[MEMORY_PERSIST_KEY]: on === true,
|
|
155
|
+
[LEGACY_MEMORY_PERSIST_KEY]: undefined,
|
|
156
|
+
});
|
|
157
|
+
}
|
|
158
|
+
|
|
78
159
|
/** Read the config, falling back to defaults (never throws). */
|
|
79
160
|
function loadConfig() {
|
|
80
161
|
try {
|
|
@@ -176,6 +257,12 @@ module.exports = {
|
|
|
176
257
|
DEFAULT_CONFIG,
|
|
177
258
|
loadConfig,
|
|
178
259
|
updateConfig,
|
|
260
|
+
MEMORY_PERSIST_KEY,
|
|
261
|
+
LEGACY_MEMORY_PERSIST_KEY,
|
|
262
|
+
MEMORY_PERSIST_DEFAULT,
|
|
263
|
+
memoryPersistState,
|
|
264
|
+
memoryPersistEnabled,
|
|
265
|
+
setMemoryPersist,
|
|
179
266
|
DEFAULT_PERMISSIONS,
|
|
180
267
|
loadPermissions,
|
|
181
268
|
savePermissions,
|
package/src/diff.js
ADDED
|
@@ -0,0 +1,330 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Line-level diff for the transcript's edit blocks.
|
|
5
|
+
*
|
|
6
|
+
* An `editFile`/`writeFile` call used to render as a single gray row
|
|
7
|
+
* (" ⎿ $ {\"file_path\":\"src/hello.js\",...}"): you could see that a file
|
|
8
|
+
* changed and never *what* changed — the one thing a coding session is
|
|
9
|
+
* actually about. This module turns the tool call's arguments into a real
|
|
10
|
+
* unified-style diff, which diffview.js paints as a colored block.
|
|
11
|
+
*
|
|
12
|
+
* Where the two sides come from:
|
|
13
|
+
* editFile — args.old_string → args.new_string. No I/O at all.
|
|
14
|
+
* writeFile — the file as it was on disk *before* the call ran, against
|
|
15
|
+
* args.content. app.js builds the preview when the tool's
|
|
16
|
+
* `phase: 'run'` event arrives, which is strictly before the
|
|
17
|
+
* executor writes, so the read is the pre-edit state.
|
|
18
|
+
*
|
|
19
|
+
* Pure: strings in, plain row objects out — no spans, no colors, no globals,
|
|
20
|
+
* no `process.stdout` — so the whole thing is unit-testable with no TTY. The
|
|
21
|
+
* ANSI painting lives in diffview.js, exactly the split render.js already
|
|
22
|
+
* keeps between structure and paint.
|
|
23
|
+
*
|
|
24
|
+
* Ported from `aegiscodex-dev/src/diff.js`; the engine's tool names are
|
|
25
|
+
* `Edit`/`Write`/`MultiEdit`, this host's are `editFile`/`writeFile`, so
|
|
26
|
+
* `editPreview` accepts both spellings. `MultiEdit` has no counterpart here
|
|
27
|
+
* and is kept only so a newer engine frame cannot silently render nothing.
|
|
28
|
+
*/
|
|
29
|
+
|
|
30
|
+
const fs = require('node:fs');
|
|
31
|
+
const path = require('node:path');
|
|
32
|
+
|
|
33
|
+
// Budgets. The preview is built synchronously inside the tool event, on the
|
|
34
|
+
// render path, so a 200 MB writeFile must not stall the CLI — the read is
|
|
35
|
+
// capped and the LCS table is bounded so a pathological pair of long files
|
|
36
|
+
// cannot allocate hundreds of megabytes. Past a budget the middle collapses to
|
|
37
|
+
// "remove everything, add everything", which is honest about being incomplete
|
|
38
|
+
// (`truncated: true` on the preview, `… N unchanged lines` in the block).
|
|
39
|
+
const DIFF_LIMITS = {
|
|
40
|
+
fileBytes: 256 * 1024, // bytes read from disk for writeFile
|
|
41
|
+
lcsCells: 250000, // n*m cap for the LCS table (~1 MB of Int32)
|
|
42
|
+
rows: 400, // diff rows kept per preview
|
|
43
|
+
context: 3, // unchanged lines kept around each change
|
|
44
|
+
};
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* Split text into display lines. A trailing newline is a terminator, not an
|
|
48
|
+
* empty last line — otherwise every normal file diff ends in a phantom
|
|
49
|
+
* "- " / "+ " pair. CRLF is normalized so a Windows checkout doesn't render as
|
|
50
|
+
* "every line changed".
|
|
51
|
+
*/
|
|
52
|
+
function splitLines(text) {
|
|
53
|
+
const s = String(text == null ? '' : text).replace(/\r\n?/g, '\n');
|
|
54
|
+
if (s === '') return [];
|
|
55
|
+
const lines = s.split('\n');
|
|
56
|
+
if (lines.length && lines[lines.length - 1] === '') lines.pop();
|
|
57
|
+
return lines;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* Unified-style diff of two strings.
|
|
62
|
+
*
|
|
63
|
+
* @returns {{rows: Array<{sign: string, text: string, no: number|null,
|
|
64
|
+
* marker?: boolean, note?: string}>, adds: number, dels: number,
|
|
65
|
+
* truncated: boolean}} `rows` carries context rows around each change run
|
|
66
|
+
* (DIFF_LIMITS.context lines), collapsed runs of unchanged lines as `marker`
|
|
67
|
+
* rows, and every changed line with a `no` for the gutter (old number on
|
|
68
|
+
* '-', new number otherwise).
|
|
69
|
+
*/
|
|
70
|
+
function lineDiff(oldText, newText) {
|
|
71
|
+
const a = splitLines(oldText);
|
|
72
|
+
const b = splitLines(newText);
|
|
73
|
+
let pre = 0;
|
|
74
|
+
while (pre < a.length && pre < b.length && a[pre] === b[pre]) pre++;
|
|
75
|
+
let post = 0;
|
|
76
|
+
while (post < a.length - pre && post < b.length - pre && a[a.length - 1 - post] === b[b.length - 1 - post]) post++;
|
|
77
|
+
|
|
78
|
+
const midA = a.slice(pre, a.length - post);
|
|
79
|
+
const midB = b.slice(pre, b.length - post);
|
|
80
|
+
const ops = lcsOps(midA, midB);
|
|
81
|
+
const truncated = ops === null;
|
|
82
|
+
const body = ops || [
|
|
83
|
+
...midA.map((text) => ({ sign: '-', text })),
|
|
84
|
+
...midB.map((text) => ({ sign: '+', text })),
|
|
85
|
+
];
|
|
86
|
+
|
|
87
|
+
// Nothing changed: say so with no rows at all. The prefix/suffix trim ate the
|
|
88
|
+
// whole file (pre === a.length, post === 0), so the context arithmetic below
|
|
89
|
+
// would otherwise paint "… 46 unchanged lines" plus three orphans over an
|
|
90
|
+
// identical pair — a marker claiming an omission that never happened.
|
|
91
|
+
if (!body.some((op) => op.sign !== ' ')) return { rows: [], adds: 0, dels: 0, truncated };
|
|
92
|
+
|
|
93
|
+
const ctx = DIFF_LIMITS.context;
|
|
94
|
+
|
|
95
|
+
const rows = [];
|
|
96
|
+
let oldNo = 1;
|
|
97
|
+
let newNo = 1;
|
|
98
|
+
// Leading context: keep *all* of it when it fits, otherwise the last `ctx`
|
|
99
|
+
// lines plus a marker for the ones actually dropped. The engine's original
|
|
100
|
+
// condition (`ctxBeforeStart < pre`) fires whenever the change is preceded by
|
|
101
|
+
// any line at all, so an ordinary three-line edit grew a bogus
|
|
102
|
+
// "… 1 unchanged line" marker and a change deep in a file reported `ctx` as
|
|
103
|
+
// the number hidden rather than the real count. A marker means "something was
|
|
104
|
+
// omitted", so it may only appear when something was.
|
|
105
|
+
const leadStart = pre > ctx ? pre - ctx : 0;
|
|
106
|
+
const hiddenLead = leadStart;
|
|
107
|
+
if (hiddenLead > 0) {
|
|
108
|
+
rows.push({ sign: ' ', text: '', marker: true, note: `… ${hiddenLead} unchanged line${hiddenLead === 1 ? '' : 's'}` });
|
|
109
|
+
}
|
|
110
|
+
for (let i = leadStart; i < pre; i++) {
|
|
111
|
+
rows.push({ sign: ' ', text: a[i], no: newNo });
|
|
112
|
+
newNo++;
|
|
113
|
+
oldNo++;
|
|
114
|
+
}
|
|
115
|
+
for (const op of body) {
|
|
116
|
+
if (op.sign === ' ') {
|
|
117
|
+
rows.push({ sign: ' ', text: op.text, no: newNo });
|
|
118
|
+
newNo++;
|
|
119
|
+
oldNo++;
|
|
120
|
+
} else if (op.sign === '-') {
|
|
121
|
+
rows.push({ sign: '-', text: op.text, no: oldNo });
|
|
122
|
+
oldNo++;
|
|
123
|
+
} else {
|
|
124
|
+
rows.push({ sign: '+', text: op.text, no: newNo });
|
|
125
|
+
newNo++;
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
// Suffix context: the first `ctx` lines of the untouched tail, then a marker
|
|
129
|
+
// for whatever unchanged tail is left over. Both the index into `b` and the
|
|
130
|
+
// gutter number come from `b`'s tail, not `a`'s: the engine read
|
|
131
|
+
// `b[a.length - post + i]`, which is the wrong line — and the wrong numbering
|
|
132
|
+
// — for every edit that changes the line count.
|
|
133
|
+
const tailStart = b.length - post;
|
|
134
|
+
const tailCount = Math.min(post, ctx);
|
|
135
|
+
newNo = tailStart + 1;
|
|
136
|
+
for (let i = 0; i < tailCount; i++) {
|
|
137
|
+
rows.push({ sign: ' ', text: b[tailStart + i], no: newNo });
|
|
138
|
+
newNo++;
|
|
139
|
+
oldNo++;
|
|
140
|
+
}
|
|
141
|
+
if (post > ctx) {
|
|
142
|
+
const n = post - ctx;
|
|
143
|
+
rows.push({ sign: ' ', text: '', marker: true, note: `… ${n} unchanged line${n === 1 ? '' : 's'}` });
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
const adds = rows.filter((r) => r.sign === '+').length;
|
|
147
|
+
const dels = rows.filter((r) => r.sign === '-').length;
|
|
148
|
+
let out = rows;
|
|
149
|
+
let cut = false;
|
|
150
|
+
if (out.length > DIFF_LIMITS.rows) {
|
|
151
|
+
out = out.slice(0, DIFF_LIMITS.rows);
|
|
152
|
+
out.push({ sign: ' ', text: '', marker: true, note: `… ${rows.length - DIFF_LIMITS.rows} more diff lines` });
|
|
153
|
+
cut = true;
|
|
154
|
+
}
|
|
155
|
+
return { rows: out, adds, dels, truncated: truncated || cut };
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
/**
|
|
159
|
+
* Longest-common-subsequence walk over two line arrays.
|
|
160
|
+
* @returns {Array<{sign: string, text: string}>|null} ops, or null when the
|
|
161
|
+
* table would exceed DIFF_LIMITS.lcsCells (the caller then treats the middle
|
|
162
|
+
* as a full replacement).
|
|
163
|
+
*/
|
|
164
|
+
function lcsOps(a, b) {
|
|
165
|
+
const n = a.length;
|
|
166
|
+
const m = b.length;
|
|
167
|
+
if (!n || !m) {
|
|
168
|
+
return [
|
|
169
|
+
...a.map((text) => ({ sign: '-', text })),
|
|
170
|
+
...b.map((text) => ({ sign: '+', text })),
|
|
171
|
+
];
|
|
172
|
+
}
|
|
173
|
+
if (n * m > DIFF_LIMITS.lcsCells) return null;
|
|
174
|
+
const w = m + 1;
|
|
175
|
+
const dp = new Int32Array((n + 1) * w); // dp[i*w+j] = |LCS(a[i:], b[j:])|
|
|
176
|
+
for (let i = n - 1; i >= 0; i--) {
|
|
177
|
+
for (let j = m - 1; j >= 0; j--) {
|
|
178
|
+
dp[i * w + j] = a[i] === b[j]
|
|
179
|
+
? dp[(i + 1) * w + (j + 1)] + 1
|
|
180
|
+
: Math.max(dp[(i + 1) * w + j], dp[i * w + (j + 1)]);
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
const ops = [];
|
|
184
|
+
let i = 0;
|
|
185
|
+
let j = 0;
|
|
186
|
+
while (i < n && j < m) {
|
|
187
|
+
if (a[i] === b[j]) { ops.push({ sign: ' ', text: a[i] }); i++; j++; }
|
|
188
|
+
else if (dp[(i + 1) * w + j] >= dp[i * w + (j + 1)]) { ops.push({ sign: '-', text: a[i] }); i++; }
|
|
189
|
+
else { ops.push({ sign: '+', text: b[j] }); j++; }
|
|
190
|
+
}
|
|
191
|
+
while (i < n) ops.push({ sign: '-', text: a[i++] });
|
|
192
|
+
while (j < m) ops.push({ sign: '+', text: b[j++] });
|
|
193
|
+
return ops;
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
/** Capped read for the pre-edit state. Never throws; missing/unreadable → null. */
|
|
197
|
+
function readCapped(file, opts = {}) {
|
|
198
|
+
const bytes = opts.bytes == null ? DIFF_LIMITS.fileBytes : opts.bytes;
|
|
199
|
+
try {
|
|
200
|
+
const st = fs.statSync(file);
|
|
201
|
+
if (!st.isFile()) return { text: null, missing: true };
|
|
202
|
+
const text = fs.readFileSync(file, 'utf8');
|
|
203
|
+
if (st.size > bytes) return { text: text.slice(0, bytes), missing: false, truncated: true };
|
|
204
|
+
return { text, missing: false };
|
|
205
|
+
} catch {
|
|
206
|
+
return { text: null, missing: true };
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
/** Path as the user thinks of it: relative to the session cwd when it is inside it. */
|
|
211
|
+
function shortPath(file, cwd) {
|
|
212
|
+
const f = String(file || '');
|
|
213
|
+
if (!cwd) return f;
|
|
214
|
+
const rel = path.relative(cwd, f);
|
|
215
|
+
if (rel && !rel.startsWith('..') && !path.isAbsolute(rel)) return rel;
|
|
216
|
+
const parts = f.split(path.sep).filter(Boolean);
|
|
217
|
+
const base = f.startsWith(path.sep) ? path.sep : '';
|
|
218
|
+
return parts.length > 2 ? base + '…' + path.sep + parts.slice(-2).join(path.sep) : f;
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
/**
|
|
222
|
+
* Build the diff preview for a tool call, or null when the call isn't an edit
|
|
223
|
+
* or its arguments don't carry enough to diff (a partial stream, a malformed
|
|
224
|
+
* call). Never throws — a preview is decoration, not the tool result, so a bad
|
|
225
|
+
* argument object must not be able to break a turn.
|
|
226
|
+
*
|
|
227
|
+
* @param {string} name Tool name — this host's `editFile`/`writeFile`, or the
|
|
228
|
+
* engine's `Edit`/`Write`/`MultiEdit` (a vendored frame can carry either).
|
|
229
|
+
* @param {object|string} args Tool arguments as parsed from the stream.
|
|
230
|
+
* @param {{cwd?: string, readFile?: Function}} [opts] `readFile` is injectable
|
|
231
|
+
* so tests never touch disk.
|
|
232
|
+
*/
|
|
233
|
+
function editPreview(name, args, opts = {}) {
|
|
234
|
+
try {
|
|
235
|
+
const cwd = opts.cwd == null ? process.cwd() : opts.cwd;
|
|
236
|
+
const readFile = opts.readFile || readCapped;
|
|
237
|
+
if (!args || typeof args !== 'object') return null;
|
|
238
|
+
const file = typeof args.file_path === 'string' ? args.file_path
|
|
239
|
+
: typeof args.path === 'string' ? args.path : null;
|
|
240
|
+
if (!file) return null;
|
|
241
|
+
const base = { file, short: shortPath(file, cwd) };
|
|
242
|
+
|
|
243
|
+
if (name === 'Edit' || name === 'editFile') {
|
|
244
|
+
if (typeof args.old_string !== 'string' || typeof args.new_string !== 'string') return null;
|
|
245
|
+
return Object.assign(
|
|
246
|
+
{ kind: 'Update' },
|
|
247
|
+
base,
|
|
248
|
+
lineDiff(args.old_string, args.new_string),
|
|
249
|
+
{ replaceAll: !!args.replace_all },
|
|
250
|
+
);
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
if (name === 'Write' || name === 'writeFile') {
|
|
254
|
+
if (typeof args.content !== 'string') return null;
|
|
255
|
+
const prev = readFile(file) || { text: null, missing: true };
|
|
256
|
+
const d = lineDiff(prev.text == null ? '' : prev.text, args.content);
|
|
257
|
+
return Object.assign(
|
|
258
|
+
{ kind: prev.missing ? 'Create' : 'Write' },
|
|
259
|
+
base,
|
|
260
|
+
d,
|
|
261
|
+
{ truncated: d.truncated || !!prev.truncated },
|
|
262
|
+
);
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
if (name === 'MultiEdit') {
|
|
266
|
+
const edits = (Array.isArray(args.edits) ? args.edits : []).filter(
|
|
267
|
+
(e) => e && typeof e.old_string === 'string' && typeof e.new_string === 'string',
|
|
268
|
+
);
|
|
269
|
+
if (!edits.length) return null;
|
|
270
|
+
const prev = readFile(file) || { text: null, missing: true };
|
|
271
|
+
if (typeof prev.text === 'string') {
|
|
272
|
+
let cur = prev.text;
|
|
273
|
+
let misses = 0;
|
|
274
|
+
for (const e of edits) {
|
|
275
|
+
if (cur.indexOf(e.old_string) === -1) { misses++; continue; }
|
|
276
|
+
cur = e.replace_all
|
|
277
|
+
? cur.split(e.old_string).join(e.new_string)
|
|
278
|
+
: cur.replace(e.old_string, e.new_string);
|
|
279
|
+
}
|
|
280
|
+
const d = lineDiff(prev.text, cur);
|
|
281
|
+
return Object.assign(
|
|
282
|
+
{ kind: 'Update' },
|
|
283
|
+
base,
|
|
284
|
+
d,
|
|
285
|
+
{ misses, replaceAll: edits.some((e) => e.replace_all) },
|
|
286
|
+
);
|
|
287
|
+
}
|
|
288
|
+
// No base on disk: stack each edit's own diff rather than inventing one.
|
|
289
|
+
let rows = [];
|
|
290
|
+
let adds = 0;
|
|
291
|
+
let dels = 0;
|
|
292
|
+
let truncated = false;
|
|
293
|
+
edits.forEach((e, i) => {
|
|
294
|
+
const d = lineDiff(e.old_string, e.new_string);
|
|
295
|
+
if (i) rows.push({ sign: ' ', text: '', marker: true, note: `… edit ${i + 1} of ${edits.length}` });
|
|
296
|
+
rows = rows.concat(d.rows);
|
|
297
|
+
adds += d.adds;
|
|
298
|
+
dels += d.dels;
|
|
299
|
+
truncated = truncated || d.truncated;
|
|
300
|
+
});
|
|
301
|
+
return Object.assign(
|
|
302
|
+
{ kind: 'Update' },
|
|
303
|
+
base,
|
|
304
|
+
{ rows, adds, dels, truncated, stacked: edits.length },
|
|
305
|
+
);
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
return null;
|
|
309
|
+
} catch {
|
|
310
|
+
return null; // decoration must never break a turn
|
|
311
|
+
}
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
/** Human count line in the reference's wording: "Added 3 lines, removed 1 line". */
|
|
315
|
+
function changeSummary(preview) {
|
|
316
|
+
const parts = [];
|
|
317
|
+
if (preview.adds) parts.push(`Added ${preview.adds} line${preview.adds === 1 ? '' : 's'}`);
|
|
318
|
+
if (preview.dels) parts.push(`removed ${preview.dels} line${preview.dels === 1 ? '' : 's'}`);
|
|
319
|
+
return parts.length ? parts.join(', ') : 'no line changes';
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
module.exports = {
|
|
323
|
+
DIFF_LIMITS,
|
|
324
|
+
splitLines,
|
|
325
|
+
lineDiff,
|
|
326
|
+
readCapped,
|
|
327
|
+
shortPath,
|
|
328
|
+
changeSummary,
|
|
329
|
+
editPreview,
|
|
330
|
+
};
|