aegiscode 6.6.0 → 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.
@@ -0,0 +1,286 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * The edit block's paint layer: a one-line summary row plus, when the block is
5
+ * open, the diff itself in Monokai Extended colors.
6
+ *
7
+ * Two shapes, driven by one boolean (`open`):
8
+ *
9
+ * collapsed ● editFile
10
+ * ⎿ Update(src/diff.js) +12 -3 · click to view diff
11
+ *
12
+ * open ● editFile
13
+ * ⎿ Update(src/diff.js) +12 -3 · click to collapse
14
+ * 12 const a = 1;
15
+ * 13 - const b = 2;
16
+ * 13 + const b = 3;
17
+ *
18
+ * Small diffs open themselves (AUTO_OPEN_ROWS) so the common one-line edit is
19
+ * readable with no gesture at all — and that is not a nicety on this host: the
20
+ * CLI writes finished turns once to scrollback (screen.js's design note), so
21
+ * an edit the user has to ask for twice is an edit they will not read. Anything
22
+ * bigger starts collapsed so a 300-line rewrite cannot bury the transcript.
23
+ *
24
+ * Width safety is a hard requirement here, not a preference: `cli-render.test.mjs`
25
+ * pins that no emitted row exceeds the terminal width, because one row that
26
+ * wraps corrupts the cursor arithmetic of every row after it. Every row this
27
+ * module returns is therefore built from `clip()`-measured plain text and
28
+ * closed with RESET, so an add/del background can never bleed into the next
29
+ * line of scrollback.
30
+ */
31
+
32
+ const { DIM, RESET, GLYPH, themeOf, diffOf } = require('./theme.js');
33
+ const { w, clip } = require('./screen.js');
34
+
35
+ /** Diff body rows at or below this size open without a gesture. */
36
+ const AUTO_OPEN_ROWS = 30;
37
+ /** Rows painted inside one open block before the "… more diff lines" footer. */
38
+ const MAX_BLOCK_ROWS = 200;
39
+
40
+ /** " ⎿ " is five cells, so block rows indent under the summary's text. */
41
+ const INDENT = ' ';
42
+
43
+ const KEYWORDS = new Set([
44
+ 'const', 'let', 'var', 'function', 'return', 'if', 'else', 'for', 'while', 'do', 'switch',
45
+ 'case', 'break', 'continue', 'import', 'export', 'from', 'default', 'class', 'extends',
46
+ 'new', 'try', 'catch', 'finally', 'throw', 'async', 'await', 'yield', 'static', 'typeof',
47
+ 'instanceof', 'in', 'of', 'delete', 'this', 'super', 'null', 'undefined', 'true', 'false',
48
+ 'def', 'elif', 'lambda', 'pass', 'raise', 'with', 'as', 'not', 'and', 'or', 'is', 'None',
49
+ 'True', 'False', 'self', 'fn', 'mut', 'pub', 'impl', 'struct', 'enum', 'trait', 'match',
50
+ 'package', 'func', 'defer', 'chan', 'nil', 'echo', 'local', 'then', 'fi', 'esac',
51
+ ]);
52
+
53
+ /**
54
+ * Split one line of code into colored tokens. Deliberately line-local and cheap
55
+ * — it runs on every changed row of every block — so it colors comments,
56
+ * strings, numbers, keywords and called functions and leaves the rest plain,
57
+ * which is all the tinted diff rows need to read as code.
58
+ *
59
+ * @param {string} text
60
+ * @param {object} [d] Diff palette (defaults to the dark one).
61
+ * @returns {Array<{t: string, c: string}>} tokens; `c` is a foreground color.
62
+ */
63
+ function highlightLine(text, d) {
64
+ const D = d || diffOf(null);
65
+ const out = [];
66
+ const src = String(text == null ? '' : text);
67
+ const re = /(\/\/[^\n]*|#[^\n]*|\/\*[\s\S]*?\*\/)|('(?:\\.|[^'\\])*'|"(?:\\.|[^"\\])*"|`(?:\\.|[^`\\])*`)|(0[xX][0-9a-fA-F]+|\d+(?:\.\d+)?)|([A-Za-z_$][A-Za-z0-9_$]*)/g;
68
+ const push = (t, c) => { if (t) out.push({ t, c }); };
69
+ let last = 0;
70
+ let m;
71
+ while ((m = re.exec(src))) {
72
+ if (m.index > last) push(src.slice(last, m.index), D.codeFg);
73
+ if (m[1]) push(m[1], D.comment);
74
+ else if (m[2]) push(m[2], D.str);
75
+ else if (m[3]) push(m[3], D.num);
76
+ else {
77
+ const word = m[4];
78
+ const isCall = /^\s*\(/.test(src.slice(m.index + word.length));
79
+ push(word, KEYWORDS.has(word) ? D.kw : isCall ? D.fn : D.codeFg);
80
+ }
81
+ last = m.index + m[0].length;
82
+ }
83
+ if (last < src.length) push(src.slice(last), D.codeFg);
84
+ return out;
85
+ }
86
+
87
+ /**
88
+ * Pair a run of removed rows with the added run that follows it and mark the
89
+ * slice that actually differs, so the changed word renders in the bright
90
+ * variant of the diff color. Equal run lengths only, and only when the shared
91
+ * prefix+suffix dominates the line — otherwise the mark would land on
92
+ * unrelated text. Mutates rows in place, adding `hi = {start, end}` in
93
+ * code-point offsets.
94
+ */
95
+ function markIntraLine(rows) {
96
+ for (let i = 0; i < rows.length; i++) {
97
+ if (rows[i].sign !== '-') continue;
98
+ let d = i;
99
+ while (d < rows.length && rows[d].sign === '-') d++;
100
+ let a = d;
101
+ while (a < rows.length && rows[a].sign === '+') a++;
102
+ const delCount = d - i;
103
+ const addCount = a - d;
104
+ if (delCount && delCount === addCount) {
105
+ for (let k = 0; k < delCount; k++) {
106
+ const pair = intraLine(rows[i + k].text, rows[d + k].text);
107
+ if (!pair) continue;
108
+ rows[i + k].hi = { start: pair.delStart, end: pair.delEnd, side: 'del' };
109
+ rows[d + k].hi = { start: pair.addStart, end: pair.addEnd, side: 'add' };
110
+ }
111
+ }
112
+ i = a - 1;
113
+ }
114
+ return rows;
115
+ }
116
+
117
+ function intraLine(delText, addText) {
118
+ const d = [...String(delText == null ? '' : delText)];
119
+ const a = [...String(addText == null ? '' : addText)];
120
+ let pre = 0;
121
+ while (pre < d.length && pre < a.length && d[pre] === a[pre]) pre++;
122
+ let post = 0;
123
+ while (post < d.length - pre && post < a.length - pre && d[d.length - 1 - post] === a[a.length - 1 - post]) post++;
124
+ const shared = pre + post;
125
+ const longest = Math.max(d.length, a.length) || 1;
126
+ if (shared < longest * 0.4) return null;
127
+ return {
128
+ delStart: pre,
129
+ delEnd: d.length - post,
130
+ addStart: pre,
131
+ addEnd: a.length - post,
132
+ };
133
+ }
134
+
135
+ /**
136
+ * Should this preview start open? Small diffs (the routine edit) do, so the
137
+ * change is readable immediately; a big one stays a one-line summary.
138
+ */
139
+ function defaultOpen(preview) {
140
+ if (!preview || !preview.rows) return false;
141
+ return preview.rows.length <= AUTO_OPEN_ROWS;
142
+ }
143
+
144
+ /**
145
+ * The summary row: ` ⎿ Update(src/diff.js) +12 -3 · click to view diff`.
146
+ *
147
+ * @param {object} preview From diff.js's editPreview().
148
+ * @param {object} ctx App context (selects the light/dark diff palette).
149
+ */
150
+ function diffSummaryRow(preview, ctx) {
151
+ const t = themeOf(ctx);
152
+ const D = diffOf(ctx);
153
+ const bits = [` ${t.gray}${GLYPH.hook} ${RESET}`];
154
+ bits.push(`${t.lavender}${preview.kind}(${preview.short})${RESET}`);
155
+ if (preview.adds) bits.push(`${D.addFg} +${preview.adds}${RESET}`);
156
+ if (preview.dels) bits.push(`${D.delFg} -${preview.dels}${RESET}`);
157
+ if (!preview.adds && !preview.dels) bits.push(`${t.gray} no line changes${RESET}`);
158
+ if (preview.misses) bits.push(`${t.gold} ${preview.misses} edit(s) not applied${RESET}`);
159
+ return bits.join('');
160
+ }
161
+
162
+ /**
163
+ * Everything the transcript paints for one edit block: the summary row, plus
164
+ * the colored diff body when open.
165
+ *
166
+ * @param {object} preview From diff.js's editPreview().
167
+ * @param {object} ctx App context (selects the light/dark diff palette).
168
+ * @param {number} cols Terminal width — the add/del backgrounds run the full
169
+ * width, which is what makes the rows read as one block rather than as loose
170
+ * colored text.
171
+ * @param {{open?: boolean}} [opts]
172
+ * @returns {string[]} ANSI rows, each at most `cols` cells wide and RESET-closed.
173
+ */
174
+ function renderDiffBlock(preview, ctx, cols, opts = {}) {
175
+ const width = Math.max(8, Number(cols) || 80);
176
+ const D = diffOf(ctx);
177
+ const t = themeOf(ctx);
178
+ const out = [clipRow(diffSummaryRow(preview, ctx), width)];
179
+ if (!opts.open || !preview || !preview.rows || !preview.rows.length) return out;
180
+
181
+ const rows = markIntraLine(preview.rows.slice(0, MAX_BLOCK_ROWS).map((r) => Object.assign({}, r)));
182
+ let maxNo = 1;
183
+ for (const r of rows) if (r.no && r.no > maxNo) maxNo = r.no;
184
+ const gutterW = Math.max(2, String(maxNo).length);
185
+ // INDENT + gutter + one separating space + the sign and its space.
186
+ const codeWidth = Math.max(4, width - (INDENT.length + gutterW + 3));
187
+
188
+ for (const r of rows) {
189
+ if (r.marker) {
190
+ out.push(clipRow(`${DIM}${INDENT}… ${r.note == null ? '' : r.note}${RESET}`, width));
191
+ continue;
192
+ }
193
+ const side = r.sign === '-' ? 'del' : r.sign === '+' ? 'add' : 'ctx';
194
+ const bg = side === 'del' ? D.delBg : side === 'add' ? D.addBg : '';
195
+ const hiBg = side === 'del' ? D.delHiBg : D.addHiBg;
196
+ const hiFg = side === 'del' ? D.delHiFg : D.addHiFg;
197
+ const fg = side === 'del' ? D.delFg : side === 'add' ? D.addFg : DIM;
198
+
199
+ const lead = `${bg}${D.gutter}${INDENT}${String(r.no == null ? '' : r.no).padStart(gutterW)} ${RESET}`;
200
+ const sign = `${bg}${fg}${r.sign === ' ' ? ' ' : r.sign} ${RESET}`;
201
+ // Clip the CODE, never the finished row: clipping the painted string would
202
+ // count escape bytes as cells and could also cut mid-sequence, leaving the
203
+ // terminal in the add/del background for the rest of the scrollback.
204
+ const body = codeRow(clip(String(r.text == null ? '' : r.text), codeWidth), bg, hiBg, hiFg, D, r.hi);
205
+ const used = w(`${INDENT}${String(r.no == null ? '' : r.no).padStart(gutterW)} `) + 2 + w(clip(String(r.text == null ? '' : r.text), codeWidth));
206
+ const fill = bg && used < width ? `${bg}${' '.repeat(width - used)}${RESET}` : '';
207
+ out.push(lead + sign + body + fill + RESET);
208
+ }
209
+
210
+ const hidden = preview.rows.length - MAX_BLOCK_ROWS;
211
+ if (hidden > 0) out.push(clipRow(`${DIM}${INDENT}… ${hidden} more diff lines${RESET}`, width));
212
+ if (preview.truncated) {
213
+ out.push(clipRow(`${DIM}${INDENT}… diff truncated (file too large to compare in full)${RESET}`, width));
214
+ }
215
+ return out;
216
+ }
217
+
218
+ /** Colored code tokens for one diff row, with the changed slice highlighted. */
219
+ function codeRow(text, bg, hiBg, hiFg, D, hi) {
220
+ const out = [];
221
+ let idx = 0;
222
+ for (const tk of highlightLine(text, D)) {
223
+ const chars = [...tk.t];
224
+ const start = idx;
225
+ const end = idx + chars.length;
226
+ idx = end;
227
+ if (!hi || end <= hi.start || start >= hi.end) {
228
+ out.push(`${bg}${tk.c}${tk.t}`);
229
+ continue;
230
+ }
231
+ const a = Math.max(hi.start, start) - start;
232
+ const b = Math.min(hi.end, end) - start;
233
+ if (a > 0) out.push(`${bg}${tk.c}${chars.slice(0, a).join('')}`);
234
+ if (b > a) out.push(`${hiBg}${hiFg}${chars.slice(a, b).join('')}`);
235
+ if (b < chars.length) out.push(`${bg}${tk.c}${chars.slice(b).join('')}`);
236
+ }
237
+ return out.join('');
238
+ }
239
+
240
+ /** Clip a painted row to `width` cells, measuring only its visible text. */
241
+ function clipRow(row, width) {
242
+ if (w(row) <= width) return row;
243
+ // Rebuild from the plain text so the escapes stay paired with the cells that
244
+ // survive the cut; the last segment ends with RESET below.
245
+ return clipVisible(row, width) + RESET;
246
+ }
247
+
248
+ /**
249
+ * Truncate a painted row to `width` visible cells, keeping the escape
250
+ * sequences it passes and never splitting one. Reuse the per-character width
251
+ * rule that `w()`/`clip()` use so a CJK or emoji cell can't be cut in half.
252
+ */
253
+ function clipVisible(row, width) {
254
+ let used = 0;
255
+ let out = '';
256
+ let i = 0;
257
+ const s = String(row);
258
+ while (i < s.length) {
259
+ if (s[i] === '\x1b' && s[i + 1] === '[') {
260
+ const close = s.indexOf('m', i);
261
+ if (close === -1) break;
262
+ out += s.slice(i, close + 1);
263
+ i = close + 1;
264
+ continue;
265
+ }
266
+ const cp = s.codePointAt(i);
267
+ const ch = String.fromCodePoint(cp);
268
+ i += ch.length;
269
+ const cw = w(ch);
270
+ if (used + cw > width) break;
271
+ out += ch;
272
+ used += cw;
273
+ }
274
+ return out;
275
+ }
276
+
277
+ module.exports = {
278
+ AUTO_OPEN_ROWS,
279
+ MAX_BLOCK_ROWS,
280
+ INDENT,
281
+ defaultOpen,
282
+ highlightLine,
283
+ markIntraLine,
284
+ diffSummaryRow,
285
+ renderDiffBlock,
286
+ };
package/src/events.js CHANGED
@@ -168,10 +168,13 @@ function feed(c) {
168
168
  seq += c;
169
169
  if (/[A-Za-z~]/.test(c)) {
170
170
  clearTimeout(escTimer);
171
- const mouseDir = parseSgrMouse(seq);
172
- if (mouseDir) {
171
+ const mouse = parseSgrMouse(seq);
172
+ if (mouse) {
173
173
  seq = '';
174
- dispatch({ name: 'wheel', dir: mouseDir });
174
+ // Wheel decodes to a direction string; a left press to a {name,col,row}
175
+ // event. Both are returned by parseSgrMouse so the caller stays a
176
+ // one-line dispatch.
177
+ dispatch(typeof mouse === 'string' ? { name: 'wheel', dir: mouse } : mouse);
175
178
  return;
176
179
  }
177
180
  const k = decodeEscSequence(seq);
@@ -185,19 +188,27 @@ function feed(c) {
185
188
  }
186
189
 
187
190
  /**
188
- * SGR mouse button code → wheel direction. 64 = up, 65 = down; modifier bits
189
- * are masked off so Shift+wheel still scrolls. Anything else (clicks, drags)
190
- * returns null, and the caller's CSI decoder ignores it — so stray mouse bytes
191
- * can neither type into the editor nor abort a turn.
191
+ * SGR mouse event → decoded value. Wheel codes 64/65 decode to 'up'/'down'
192
+ * (modifier bits masked off so Shift+wheel still scrolls). A left button PRESS
193
+ * decodes to `{name:'click', col, row}` with 1-based coordinates from the
194
+ * payload. Everything else — a release (`m`), a drag, another button, or a
195
+ * horizontal wheel — returns null, and the caller's CSI decoder ignores it, so
196
+ * stray mouse bytes can neither type into the editor nor abort a turn.
192
197
  */
193
198
  function parseSgrMouse(seq) {
194
- if (!seq.startsWith('\x1b[<')) return null;
195
- const body = seq.slice(3).replace(/[Mm]$/, '');
196
- const code = parseInt(body.split(';')[0], 10);
199
+ const m = /^\x1b\[<(\d+);(\d+);(\d+)([Mm])$/.exec(seq);
200
+ if (!m) return null;
201
+ const code = parseInt(m[1], 10);
197
202
  if (!Number.isFinite(code)) return null;
198
203
  const base = code & ~0b111100;
199
204
  if (base === 64) return 'up';
200
205
  if (base === 65) return 'down';
206
+ // Left press only: button bits 0-1 clear, wheel bits (0b1100000) clear, no
207
+ // motion bit, and the `M` (press) terminator — a release or drag toggles
208
+ // nothing.
209
+ if (m[4] === 'M' && (code & 3) === 0 && (code & 0b1100000) === 0 && (code & 0b100000) === 0) {
210
+ return { name: 'click', col: parseInt(m[2], 10), row: parseInt(m[3], 10) };
211
+ }
201
212
  return null;
202
213
  }
203
214
 
package/src/render.js CHANGED
@@ -34,6 +34,7 @@ const {
34
34
  const { WELCOME_TITLE, WELCOME_BACK, TAGLINE, STAR, stencilGlyph, welcomeArtParts } = require('./art.js');
35
35
  const { w, pad, padStart, wrapBlock, clip, span } = require('./screen.js');
36
36
  const { fmtTokens, fmtEur, fmtElapsed } = require('./format.js');
37
+ const { renderDiffBlock } = require('./diffview.js');
37
38
 
38
39
  // Guarded: a concurrent workstream owns ./markdown.js.
39
40
  let markdown = null;
@@ -264,7 +265,17 @@ function renderTurn(ctx, turn, width = 80) {
264
265
  : typeof turn.args === 'string'
265
266
  ? turn.args
266
267
  : JSON.stringify(turn.args);
267
- if (args) lines.push(` ${t.gray}${GLYPH.hook} $ ${clip(args, Math.max(0, width - 6))}${RESET}`);
268
+ // An editFile/writeFile turn carries a diff preview (app.js builds it from
269
+ // the tool call's `run` frame). Paint the colored block instead of the gray
270
+ // `$ {args}` row, so an edit shows *what* changed, not just that something
271
+ // did. The summary row is unconditional; the body follows when the block is
272
+ // open, which the click handler toggles. The `$ args` row stays the fallback
273
+ // for every non-edit tool and for a turn with no preview.
274
+ if (turn.diff) {
275
+ lines.push(...renderDiffBlock(turn.diff, ctx, width, { open: !!turn.diffOpen }));
276
+ } else if (args) {
277
+ lines.push(` ${t.gray}${GLYPH.hook} $ ${clip(args, Math.max(0, width - 6))}${RESET}`);
278
+ }
268
279
  } else if (role === 'error') {
269
280
  lines.push(`${t.red}${ERR} ${text}${RESET}`);
270
281
  } else {
package/src/theme.js CHANGED
@@ -138,6 +138,61 @@ const VERBS = [
138
138
  * after one that used tools. */
139
139
  const DONE_VERBS = ['Churned', 'Worked'];
140
140
 
141
+ /**
142
+ * Diff palette for edit blocks in the transcript — Monokai Extended, taken
143
+ * verbatim from the theme picker's preview (also `renderDiffPreview` in
144
+ * `aegiscodex-dev/src/markdown.js`) so the two can never drift apart: dim
145
+ * red/green backgrounds per row, the bright variant for the token that
146
+ * actually changed inside the row, and the monokai syntax colors for the code
147
+ * itself.
148
+ *
149
+ * A SEPARATE export, not keys added to `C`/`LIGHT`: `test/cli-conformance.test.mjs`
150
+ * pins `Object.keys(C)` to exactly the eleven DEV_DARK role names, so a diff
151
+ * entry folded into the palette would fail the conformance guard. This is the
152
+ * same reason `DIFF` is its own object in the engine.
153
+ */
154
+ const DIFF = {
155
+ delFg: RGB(220, 90, 90),
156
+ delBg: BG(61, 1, 0),
157
+ delHiFg: RGB(248, 248, 242),
158
+ delHiBg: BG(92, 2, 0),
159
+ addFg: RGB(80, 200, 80),
160
+ addBg: BG(2, 40, 0),
161
+ addHiFg: RGB(255, 255, 255),
162
+ addHiBg: BG(4, 71, 0),
163
+ codeFg: RGB(248, 248, 242),
164
+ gutter: RGB(120, 120, 120),
165
+ kw: RGB(102, 217, 239),
166
+ fn: RGB(166, 226, 46),
167
+ str: RGB(230, 219, 116),
168
+ num: RGB(174, 129, 255),
169
+ comment: RGB(117, 113, 94),
170
+ };
171
+
172
+ /**
173
+ * The light-theme diff palette. Monokai's dark backgrounds on a light terminal
174
+ * are unreadable, so the row backgrounds invert to a pale tint and the code
175
+ * keeps its hue mapping from the dark set — the same relationship `LIGHT`
176
+ * already has to `C`.
177
+ */
178
+ const DIFF_LIGHT = {
179
+ delFg: RGB(160, 40, 40),
180
+ delBg: BG(255, 235, 233),
181
+ delHiFg: RGB(90, 0, 0),
182
+ delHiBg: BG(255, 205, 200),
183
+ addFg: RGB(30, 130, 40),
184
+ addBg: BG(232, 250, 232),
185
+ addHiFg: RGB(0, 80, 0),
186
+ addHiBg: BG(195, 240, 195),
187
+ codeFg: RGB(40, 40, 40),
188
+ gutter: RGB(150, 150, 150),
189
+ kw: RGB(0, 120, 160),
190
+ fn: RGB(80, 140, 0),
191
+ str: RGB(150, 110, 0),
192
+ num: RGB(120, 60, 200),
193
+ comment: RGB(140, 140, 130),
194
+ };
195
+
141
196
  const THEMES = { dark: C, light: LIGHT };
142
197
 
143
198
  /**
@@ -206,6 +261,20 @@ function themeOf(ctx) {
206
261
  return ctx && ctx.light ? LIGHT : C;
207
262
  }
208
263
 
264
+ /**
265
+ * The diff palette for a context — the exact companion of `themeOf`, so a
266
+ * caller never has to ask "which palette did the rows use?" separately from
267
+ * "which diff colors go with it?". `themeIndex` 3–6 are the four picker rows
268
+ * whose brightness is named by their own `light` flag; anything else falls
269
+ * back to the ctx's `light` flag, exactly as `themeOf` does.
270
+ */
271
+ function diffOf(ctx) {
272
+ const light = ctx && typeof ctx.themeIndex === 'number' && ctx.themeIndex >= 3 && ctx.themeIndex <= 6
273
+ ? !!THEME_TABLE[ctx.themeIndex].light
274
+ : !!(ctx && ctx.light);
275
+ return light ? DIFF_LIGHT : DIFF;
276
+ }
277
+
209
278
  module.exports = {
210
279
  RGB,
211
280
  BG,
@@ -221,6 +290,9 @@ module.exports = {
221
290
  RESET_BG,
222
291
  C,
223
292
  LIGHT,
293
+ DIFF,
294
+ DIFF_LIGHT,
295
+ diffOf,
224
296
  CB_DARK,
225
297
  CB_LIGHT,
226
298
  ANSI_DARK,