@hncode/hncode 0.7.7 → 0.8.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/agent.js +1405 -1400
- package/src/animate.js +371 -0
- package/src/colors.js +593 -556
- package/src/composer.js +182 -0
- package/src/diff.js +186 -0
- package/src/format.js +275 -0
- package/src/highlight.js +670 -4
- package/src/markdown.js +567 -0
- package/src/panels.js +256 -0
- package/src/rows-plan-bg.js +83 -0
- package/src/rows-status.js +104 -0
- package/src/rows-tool-result.js +208 -0
- package/src/text.js +149 -0
- package/src/tool-line.js +193 -0
- package/src/tools/bash.js +11 -10
- package/src/tools/ptc.js +2 -2
- package/src/tools/read.js +3 -0
- package/src/tui.js +381 -2766
- package/src/web-public/app.css +7 -5
- package/src/web-public/app.js +7 -4
- package/src/web.js +2 -0
package/src/composer.js
ADDED
|
@@ -0,0 +1,182 @@
|
|
|
1
|
+
// The input line: its prompt, its collapsed pastes, and its selection.
|
|
2
|
+
//
|
|
3
|
+
// Nothing here paints a screen or reads a session. A caller hands in the state object and gets back the prefix, the
|
|
4
|
+
// marker text, or a row with a span recoloured — which is what lets the same rules serve the TUI's composer and any
|
|
5
|
+
// other front end that wants them.
|
|
6
|
+
|
|
7
|
+
import { C } from './colors.js';
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* What the composer shows for this state: the buffer, the caret, and the prompt prefix.
|
|
11
|
+
*
|
|
12
|
+
* SHELL MODE (`!`) is modelled on kimi-code's editor. Typing `!` on an EMPTY composer flips a mode flag instead of
|
|
13
|
+
* inserting the character; the `!` is rendered as the PREFIX. That is what keeps it from appearing twice: the buffer
|
|
14
|
+
* holds only the command, the caret never has to step over a marker it is not editing, and submit never has to strip
|
|
15
|
+
* anything.
|
|
16
|
+
*
|
|
17
|
+
* STDIN MODE takes `▸`, the same glyph the hint row under a running command uses, so one idea has one symbol.
|
|
18
|
+
*/
|
|
19
|
+
export function composerInput(state) {
|
|
20
|
+
const shell = state.inputMode === 'bash';
|
|
21
|
+
const prefix = state.stdinMode ? '▸ ' : (shell ? '! ' : '> ');
|
|
22
|
+
return { text: state.input || '', caret: state.caret || 0, prefix };
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* Marker text for a collapsed paste.
|
|
27
|
+
*
|
|
28
|
+
* Only a multi-line TEXT paste collapses; an IMAGE always collapses, because its payload is a temp file path that
|
|
29
|
+
* should never be shown as if the user typed it.
|
|
30
|
+
*
|
|
31
|
+
* text, multi-line : [paste #1 +12 lines]
|
|
32
|
+
* text, one line : [paste #1 1 lines]
|
|
33
|
+
* image : [paste #1 image]
|
|
34
|
+
*
|
|
35
|
+
* The `image` form keeps the same `paste #N` prefix on purpose: expansion, chipping and caret movement all key off
|
|
36
|
+
* it, so images get the styling and atomic behaviour for free.
|
|
37
|
+
*/
|
|
38
|
+
export function pasteMarker(id, lineCount, kind = 'paste') {
|
|
39
|
+
if (kind === 'image') return `[paste #${id} image]`;
|
|
40
|
+
return lineCount > 1 ? `[paste #${id} +${lineCount} lines]` : `[paste #${id} ${lineCount} lines]`;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/** The tail of any collapsed-paste marker: `+L lines`, `L lines`, or `image`. */
|
|
44
|
+
export const PASTE_MARKER_RE = /\[paste #(\d+) (?:\+\d+ lines|\d+ lines|image)\]/g;
|
|
45
|
+
|
|
46
|
+
const MARKER_LEFT_RE = /\[paste #(\d+) (?:\+\d+ lines|\d+ lines|image)\]$/;
|
|
47
|
+
const MARKER_RIGHT_RE = /^\[paste #(\d+) (?:\+\d+ lines|\d+ lines|image)\]/;
|
|
48
|
+
|
|
49
|
+
/** Expand every `[paste #N …]` marker in `text` back to its real content. */
|
|
50
|
+
export function expandPastes(text, pastes) {
|
|
51
|
+
if (!pastes || !text || !text.includes('[paste #')) return text;
|
|
52
|
+
return text.replace(PASTE_MARKER_RE, (whole, id) => {
|
|
53
|
+
const entry = pastes.get(Number(id));
|
|
54
|
+
return entry ? entry.text : whole;
|
|
55
|
+
});
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* Chip each collapsed-paste marker with a selection background, leaving non-marker text untouched.
|
|
60
|
+
*
|
|
61
|
+
* The chip ends with `C.bgReset` and then the caller's SURFACE, not with a bare reset: `ESC[0m` clears EVERY style, so
|
|
62
|
+
* it also wiped the foreground the caller had applied to the text after the chip — the rest of the line came out in
|
|
63
|
+
* the terminal's default grey instead of the prompt's colour. `ESC[49m` gives the background back to the terminal
|
|
64
|
+
* rather than to the theme, so the caller's own surface has to follow it immediately or the rest of the row shows
|
|
65
|
+
* whatever background the user's terminal happens to have.
|
|
66
|
+
*
|
|
67
|
+
* `hoverId` is the paste number the pointer is over, when it is over one; that chip keeps the hover accent.
|
|
68
|
+
* `surface` is the background the caller is about to paint under this row, or '' when the row has none.
|
|
69
|
+
*/
|
|
70
|
+
export function highlightPasteMarkers(row, hoverId = null, surface = C.bg) {
|
|
71
|
+
const s = String(row);
|
|
72
|
+
if (!s.includes('[paste #')) return s;
|
|
73
|
+
return s.replace(PASTE_MARKER_RE, (m, id) => {
|
|
74
|
+
const after = C.bgReset + surface;
|
|
75
|
+
if (Number(id) === hoverId) return C.hover + C.selBg + m + after;
|
|
76
|
+
return C.selBg + m + after;
|
|
77
|
+
});
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/**
|
|
81
|
+
* Which paste number, if any, occupies this input index. Returns null when none does.
|
|
82
|
+
*
|
|
83
|
+
* The companion to `expandPasteMarkerAt`: that one acts on the chip under the pointer, this one merely names it so the
|
|
84
|
+
* row can be drawn differently. Both need the same bounds, and a chip is inclusive of its end because the caret index
|
|
85
|
+
* rounds to the position after the last character.
|
|
86
|
+
*/
|
|
87
|
+
export function pasteMarkerIdAt(input, idx) {
|
|
88
|
+
const cur = String(input == null ? '' : input);
|
|
89
|
+
if (!cur.includes('[paste #')) return null;
|
|
90
|
+
for (const m of cur.matchAll(PASTE_MARKER_RE)) {
|
|
91
|
+
const at = m.index;
|
|
92
|
+
if (idx >= at && idx <= at + m[0].length) return Number(m[1]);
|
|
93
|
+
}
|
|
94
|
+
return null;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/**
|
|
98
|
+
* Expand the collapsed paste the caret index lands on, in place. Returns true when one was expanded.
|
|
99
|
+
*
|
|
100
|
+
* `onChanged` is called after a successful expansion so the host can re-run whatever menu or completion refresh it
|
|
101
|
+
* owns — this module does not know about menus.
|
|
102
|
+
*
|
|
103
|
+
* Takes the ALREADY-CONVERTED index. An earlier version took the row and column and converted itself, which
|
|
104
|
+
* double-subtracted the row's prefix width — every click landed two columns left of the pointer and a click on the
|
|
105
|
+
* chip's first character expanded nothing.
|
|
106
|
+
*
|
|
107
|
+
* `state.pastes` keeps its entry: expansion is a no-op for text with no marker, so leaving it costs nothing, and
|
|
108
|
+
* dropping it would break a later marker that still refers to the same paste.
|
|
109
|
+
*/
|
|
110
|
+
export function expandPasteMarkerAt(state, idx, onChanged) {
|
|
111
|
+
const cur = state.input || '';
|
|
112
|
+
if (!cur.includes('[paste #')) return false;
|
|
113
|
+
|
|
114
|
+
for (const m of cur.matchAll(PASTE_MARKER_RE)) {
|
|
115
|
+
const at = m.index;
|
|
116
|
+
const end = at + m[0].length;
|
|
117
|
+
// Clicking any character of the chip targets it — including the character after the last one, which is where a
|
|
118
|
+
// click on the closing bracket rounds to.
|
|
119
|
+
if (idx < at || idx > end) continue;
|
|
120
|
+
const entry = state.pastes && state.pastes.get(Number(m[1]));
|
|
121
|
+
if (!entry) return false;
|
|
122
|
+
state.input = cur.slice(0, at) + entry.text + cur.slice(end);
|
|
123
|
+
// The caret goes AFTER the expanded text, so the next keystroke continues where it ends rather than landing in the
|
|
124
|
+
// middle of the paste the user just revealed.
|
|
125
|
+
state.caret = at + entry.text.length;
|
|
126
|
+
state.composerSel = null;
|
|
127
|
+
if (typeof onChanged === 'function') onChanged();
|
|
128
|
+
return true;
|
|
129
|
+
}
|
|
130
|
+
return false;
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
/**
|
|
134
|
+
* Apply a selection background to the text portion of a composer row.
|
|
135
|
+
*
|
|
136
|
+
* `text` is the visible text on this row (after the prefix), `textStart` is the character offset of `text[0]` in the
|
|
137
|
+
* full input string, and `[selAnchor, selHead]` is the selection range in the full input.
|
|
138
|
+
*
|
|
139
|
+
* Selection changes only the BACKGROUND; the foreground keeps its own colour. Leaving the selection restores the
|
|
140
|
+
* PAGE instead of emitting a full reset, for two reasons: a bare reset also kills the foreground, and `ESC[49m` hands
|
|
141
|
+
* the background back to the TERMINAL — which showed its own colour for the rest of the line.
|
|
142
|
+
*/
|
|
143
|
+
export function highlightSelection(text, textStart, selAnchor, selHead) {
|
|
144
|
+
if (!text) return text;
|
|
145
|
+
const a = Math.min(selAnchor, selHead);
|
|
146
|
+
const h = Math.max(selAnchor, selHead);
|
|
147
|
+
let out = '';
|
|
148
|
+
let inSel = false;
|
|
149
|
+
for (let i = 0; i < text.length; i++) {
|
|
150
|
+
const globalIdx = textStart + i;
|
|
151
|
+
const want = globalIdx >= a && globalIdx < h;
|
|
152
|
+
if (want && !inSel) { out += C.selBg; inSel = true; }
|
|
153
|
+
else if (!want && inSel) { out += C.bg; inSel = false; }
|
|
154
|
+
out += text[i];
|
|
155
|
+
}
|
|
156
|
+
if (inSel) out += C.reset;
|
|
157
|
+
return out;
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
/**
|
|
161
|
+
* The collapsed-paste marker adjacent to the caret, in the given direction.
|
|
162
|
+
*
|
|
163
|
+
* The composer treats a marker as ONE atomic unit: moving the caret across it jumps over the whole thing, and
|
|
164
|
+
* deleting it removes the entire marker.
|
|
165
|
+
*
|
|
166
|
+
* @param {string} text the buffer
|
|
167
|
+
* @param {number} caret character index
|
|
168
|
+
* @param {number} dir -1 looks left of the caret, +1 looks right
|
|
169
|
+
* @returns {{start:number, end:number, id:number}|null}
|
|
170
|
+
*/
|
|
171
|
+
export function adjacentPasteMarker(text, caret, dir) {
|
|
172
|
+
const s = String(text || '');
|
|
173
|
+
const c = Math.max(0, Math.min(s.length, caret));
|
|
174
|
+
if (dir < 0) {
|
|
175
|
+
const m = MARKER_LEFT_RE.exec(s.slice(0, c));
|
|
176
|
+
if (m) return { start: c - m[0].length, end: c, id: Number(m[1]) };
|
|
177
|
+
} else {
|
|
178
|
+
const m = MARKER_RIGHT_RE.exec(s.slice(c));
|
|
179
|
+
if (m) return { start: c, end: c + m[0].length, id: Number(m[1]) };
|
|
180
|
+
}
|
|
181
|
+
return null;
|
|
182
|
+
}
|
package/src/diff.js
ADDED
|
@@ -0,0 +1,186 @@
|
|
|
1
|
+
// Diff construction and syntax colouring for a diff body.
|
|
2
|
+
//
|
|
3
|
+
// Both halves of one job: an Edit reports what it replaced, and this module turns that into numbered rows and paints
|
|
4
|
+
// them. Nothing here knows about the transcript, so a caller can diff without a screen.
|
|
5
|
+
|
|
6
|
+
import { highlightLine, langForPath } from './highlight.js';
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* How many unchanged lines to keep either side of a change, when a diff is elided.
|
|
10
|
+
*
|
|
11
|
+
* FIVE, not three: three was too few to place a change among near-identical neighbours — several small functions, or
|
|
12
|
+
* two `}` a couple of rows apart, look the same inside a three-row window — and the rows just past the window are
|
|
13
|
+
* exactly what a reader uses to tell one site from another.
|
|
14
|
+
*
|
|
15
|
+
* Shared by both builders so a change can never be shown with one amount of surrounding context in the model's tool
|
|
16
|
+
* result and another on screen.
|
|
17
|
+
*/
|
|
18
|
+
export const DIFF_CONTEXT_LINES = 5;
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* Colour one line of code, carrying block-comment state across rows.
|
|
22
|
+
*
|
|
23
|
+
* The state matters: a block comment that opens on one row and closes on the next left the second row looking like
|
|
24
|
+
* ordinary code, so `extends` and `const` inside a comment were coloured as keywords.
|
|
25
|
+
*
|
|
26
|
+
* @param {string} text The row.
|
|
27
|
+
* @param {object} lang The language entry, or null.
|
|
28
|
+
* @param {string} bg The background colour, or '' for none.
|
|
29
|
+
* @param {boolean} [inComment] Whether the previous row ended inside a block comment.
|
|
30
|
+
* @returns {{text: string, inComment: boolean}}
|
|
31
|
+
*/
|
|
32
|
+
export function paintCode(text, lang, bg, inComment = false) {
|
|
33
|
+
const result = lang ? highlightLine(text, lang, inComment) : { text: String(text), inComment: false };
|
|
34
|
+
const raw = result.text;
|
|
35
|
+
if (!bg) return result;
|
|
36
|
+
// THE BACKGROUND GOES ON BEFORE ANY TOKEN COLOUR AND COMES BACK AFTER EVERY RESET.
|
|
37
|
+
//
|
|
38
|
+
// Prefixing only after `\x1b[0m` left the run of text BEFORE the first token uncoloured — a comment line has its
|
|
39
|
+
// whole body inside one token, so it drew with no wash at all while the code below it was washed, and the block
|
|
40
|
+
// looked striped. Seeding the background at the front covers that first run; the replacement covers every run after
|
|
41
|
+
// it, because each token closes with a reset that would otherwise drop back to the page background.
|
|
42
|
+
//
|
|
43
|
+
// ESC[39m, NOT ESC[0m: a bare reset clears the background too, and the row's wash must survive past the last token.
|
|
44
|
+
// The final glyph is still inside the coloured run, so nothing is left over to clear.
|
|
45
|
+
return { text: bg + raw.replace(/\x1b\[0m/g, `\x1b[0m${bg}`) + '\x1b[39m', inComment: result.inComment };
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* Align two line arrays into `same` / `del` / `add` steps (longest common subsequence).
|
|
50
|
+
*
|
|
51
|
+
* The table is O(n*m), which is right for the block an edit replaces — a handful of lines — and wrong for a whole
|
|
52
|
+
* file. Past the cap on either side it falls back to "everything replaced", which is exactly what the old code always
|
|
53
|
+
* did, so a pathological case is no worse than before and the common one is much better.
|
|
54
|
+
*/
|
|
55
|
+
export function alignLines(a, b) {
|
|
56
|
+
const n = a.length;
|
|
57
|
+
const m = b.length;
|
|
58
|
+
const MAX = 400;
|
|
59
|
+
const all = () => [
|
|
60
|
+
...a.map((_, i) => ({ op: 'del', a: i, b: 0 })),
|
|
61
|
+
...b.map((_, j) => ({ op: 'add', a: 0, b: j })),
|
|
62
|
+
];
|
|
63
|
+
if (n * m > MAX * MAX) return all();
|
|
64
|
+
|
|
65
|
+
// `dp[i][j]` is the LCS length of a[i..] against b[j..], filled from the bottom right.
|
|
66
|
+
const dp = Array.from({ length: n + 1 }, () => new Uint32Array(m + 1));
|
|
67
|
+
for (let i = n - 1; i >= 0; i--) {
|
|
68
|
+
for (let j = m - 1; j >= 0; j--) {
|
|
69
|
+
dp[i][j] = a[i] === b[j] ? dp[i + 1][j + 1] + 1 : Math.max(dp[i + 1][j], dp[i][j + 1]);
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
const steps = [];
|
|
73
|
+
let i = 0;
|
|
74
|
+
let j = 0;
|
|
75
|
+
while (i < n && j < m) {
|
|
76
|
+
if (a[i] === b[j]) { steps.push({ op: 'same', a: i, b: j }); i++; j++; }
|
|
77
|
+
else if (dp[i + 1][j] >= dp[i][j + 1]) { steps.push({ op: 'del', a: i, b: j }); i++; }
|
|
78
|
+
else { steps.push({ op: 'add', a: i, b: j }); j++; }
|
|
79
|
+
}
|
|
80
|
+
while (i < n) { steps.push({ op: 'del', a: i, b: j }); i++; }
|
|
81
|
+
while (j < m) { steps.push({ op: 'add', a: i, b: j }); j++; }
|
|
82
|
+
return steps;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* Drop context rows further than DIFF_CONTEXT_LINES from any change, one `gap` per run.
|
|
87
|
+
*
|
|
88
|
+
* Shared by both diff builders so a change can never be shown with one amount of surrounding context in the model's
|
|
89
|
+
* tool result and another on screen.
|
|
90
|
+
*/
|
|
91
|
+
export function elideContext(raw) {
|
|
92
|
+
const isChange = (k) => raw[k] && raw[k].type !== 'ctx';
|
|
93
|
+
const out = [];
|
|
94
|
+
for (let k = 0; k < raw.length; k++) {
|
|
95
|
+
if (raw[k].type !== 'ctx') { out.push(raw[k]); continue; }
|
|
96
|
+
// Distance to the NEAREST change on either side; keep when within the window.
|
|
97
|
+
let dist = Infinity;
|
|
98
|
+
for (let t = k - 1; t >= 0 && t >= k - DIFF_CONTEXT_LINES; t--) { if (isChange(t)) { dist = Math.min(dist, k - t); break; } }
|
|
99
|
+
for (let t = k + 1; t < raw.length && t <= k + DIFF_CONTEXT_LINES; t++) { if (isChange(t)) { dist = Math.min(dist, t - k); break; } }
|
|
100
|
+
if (dist <= DIFF_CONTEXT_LINES) { out.push(raw[k]); continue; }
|
|
101
|
+
// Elide this context row, marking the gap once.
|
|
102
|
+
if (out.length && out[out.length - 1].type !== 'gap') out.push({ type: 'gap' });
|
|
103
|
+
}
|
|
104
|
+
return out;
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/**
|
|
108
|
+
* Rows for an Edit, from the tool's own diff payload.
|
|
109
|
+
*
|
|
110
|
+
* The tool KNOWS what it replaced, so there is nothing to infer: the surrounding lines it reports are context, its
|
|
111
|
+
* `old` is what went, its `new` is what arrived. Running the spliced text through `lineDiff`'s LCS instead made it
|
|
112
|
+
* MIS-READ them — a context block prepended to the old text and appended to the new has a different shape on each
|
|
113
|
+
* side, so the LCS paired the wrong lines and rendered five unchanged context rows as `-`/`+` pairs.
|
|
114
|
+
*
|
|
115
|
+
* Rows are numbered from the real file: `before` carries its own line numbers, and the change starts at `startLine`.
|
|
116
|
+
*/
|
|
117
|
+
export function editDiffRows(diff) {
|
|
118
|
+
if (!diff || typeof diff.old !== 'string' || typeof diff.new !== 'string') return [];
|
|
119
|
+
// An empty side is ZERO lines and a trailing newline is not a line: `''.split('\n')` is `['']`, which drew a
|
|
120
|
+
// phantom blank row, and `'a\n'` split to `['a', '']`, which drew one past the end.
|
|
121
|
+
const split = (s) => {
|
|
122
|
+
const t = String(s).replace(/\r\n/g, '\n').replace(/\n$/, '');
|
|
123
|
+
return t === '' ? [] : t.split('\n');
|
|
124
|
+
};
|
|
125
|
+
const ctx = diff.context || {};
|
|
126
|
+
const before = Array.isArray(ctx.before) ? ctx.before : [];
|
|
127
|
+
const after = Array.isArray(ctx.after) ? ctx.after : [];
|
|
128
|
+
const startLine = Number(diff.startLine) > 0 ? Number(diff.startLine) : 1;
|
|
129
|
+
|
|
130
|
+
// AN EDIT THAT CHANGED ONE LINE SHOWS ONE LINE CHANGED.
|
|
131
|
+
//
|
|
132
|
+
// Emitting every old line as `del` and every new line as `add` meant replacing three lines whose last one changed
|
|
133
|
+
// produced three deletions and three additions — the two identical lines scrolled past as noise and the one real
|
|
134
|
+
// change was buried. Aligning the two sides and emitting the unchanged pairs as CONTEXT is what a diff is.
|
|
135
|
+
const oldLines = split(diff.old);
|
|
136
|
+
const newLines = split(diff.new);
|
|
137
|
+
|
|
138
|
+
const out = [];
|
|
139
|
+
for (const c of before) out.push({ type: 'ctx', text: String(c.text), no: c.n });
|
|
140
|
+
let oldNo = startLine;
|
|
141
|
+
let newNo = startLine;
|
|
142
|
+
const steps = alignLines(oldLines, newLines);
|
|
143
|
+
for (let k = 0; k < steps.length; k++) {
|
|
144
|
+
const step = steps[k];
|
|
145
|
+
if (step.op === 'same') { out.push({ type: 'ctx', text: oldLines[step.a], no: newNo }); oldNo++; newNo++; continue; }
|
|
146
|
+
if (step.op === 'del') { out.push({ type: 'del', text: oldLines[step.a], no: oldNo++ }); continue; }
|
|
147
|
+
out.push({ type: 'add', text: newLines[step.b], no: newNo++ });
|
|
148
|
+
}
|
|
149
|
+
for (const c of after) out.push({ type: 'ctx', text: String(c.text), no: c.n });
|
|
150
|
+
// THE LANGUAGE TRAVELS WITH THE ROWS. The renderer draws a diff several layers away from the tool call, with no
|
|
151
|
+
// path of its own, so resolving the highlighter here — from the diff's own `path` — is the only place that still
|
|
152
|
+
// knows what file this is.
|
|
153
|
+
const lang = diff.path ? langForPath(diff.path) : null;
|
|
154
|
+
if (lang) for (const r of out) r.lang = lang;
|
|
155
|
+
return elideContext(out);
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
/**
|
|
159
|
+
* A diff between two whole strings, for callers that have the text rather than a tool payload.
|
|
160
|
+
*
|
|
161
|
+
* Same window rule as `editDiffRows`, from the one helper: a change must never be shown with a different amount of
|
|
162
|
+
* surrounding context on screen and in the model's tool result.
|
|
163
|
+
*/
|
|
164
|
+
export function lineDiff(oldStr, newStr, startLine = 1) {
|
|
165
|
+
const a = String(oldStr == null ? '' : oldStr).replace(/\r\n/g, '\n').split('\n');
|
|
166
|
+
const b = String(newStr == null ? '' : newStr).replace(/\r\n/g, '\n').split('\n');
|
|
167
|
+
const n = a.length, m = b.length;
|
|
168
|
+
const dp = Array.from({ length: n + 1 }, () => new Uint16Array(m + 1));
|
|
169
|
+
for (let i = n - 1; i >= 0; i--) {
|
|
170
|
+
for (let j = m - 1; j >= 0; j--) {
|
|
171
|
+
dp[i][j] = a[i] === b[j] ? dp[i + 1][j + 1] + 1 : Math.max(dp[i + 1][j], dp[i][j + 1]);
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
const raw = [];
|
|
175
|
+
let i = 0, j = 0;
|
|
176
|
+
// Line numbers as they appear in the real file (startLine = first old line).
|
|
177
|
+
let oldNo = startLine, newNo = startLine;
|
|
178
|
+
while (i < n && j < m) {
|
|
179
|
+
if (a[i] === b[j]) { raw.push({ type: 'ctx', text: a[i], no: oldNo }); i++; j++; oldNo++; newNo++; }
|
|
180
|
+
else if (dp[i + 1][j] >= dp[i][j + 1]) { raw.push({ type: 'del', text: a[i], no: oldNo }); i++; oldNo++; }
|
|
181
|
+
else { raw.push({ type: 'add', text: b[j], no: newNo }); j++; newNo++; }
|
|
182
|
+
}
|
|
183
|
+
while (i < n) { raw.push({ type: 'del', text: a[i], no: oldNo }); i++; oldNo++; }
|
|
184
|
+
while (j < m) { raw.push({ type: 'add', text: b[j], no: newNo }); j++; newNo++; }
|
|
185
|
+
return elideContext(raw);
|
|
186
|
+
}
|
package/src/format.js
ADDED
|
@@ -0,0 +1,275 @@
|
|
|
1
|
+
// Number, money and time formatting for the readouts.
|
|
2
|
+
//
|
|
3
|
+
// One rule per quantity, stated once: a token count must read the same in the context gauge and in the working row, and
|
|
4
|
+
// a cost must never round a real amount down to `0.00`.
|
|
5
|
+
|
|
6
|
+
import { fitAnsi, visualCol } from './text.js';
|
|
7
|
+
|
|
8
|
+
export function trimDecimal(v) {
|
|
9
|
+
const s = v.toFixed(1);
|
|
10
|
+
return s.endsWith('.0') ? s.slice(0, -2) : s;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* One unit's worth of a count: `1.2`, `97`, `262`.
|
|
15
|
+
*
|
|
16
|
+
* One decimal below 100, whole numbers at and above it. Used by every token formatter so the same quantity cannot read
|
|
17
|
+
* two ways on one screen.
|
|
18
|
+
*/
|
|
19
|
+
export function scaleUnit(v) {
|
|
20
|
+
if (v < 100) return v.toFixed(1).replace(/\.0$/, '');
|
|
21
|
+
const r = Math.round(v);
|
|
22
|
+
// A value that ROUNDS to the whole number keeps its decimal: 1048576/1e6 is 1.048576, and printing `1` put it in the
|
|
23
|
+
// same bucket as a plain million.
|
|
24
|
+
if (r >= 100 && Math.abs(v - r) <= 0.5) return String(r);
|
|
25
|
+
return v.toFixed(1).replace(/\.0$/, '');
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* Token counts use DECIMAL units, the same ones `fmtTokensShort` uses for the working row.
|
|
30
|
+
*
|
|
31
|
+
* This was 1024-based, on the reasoning that a context size is a power of two. Two things outweighed that:
|
|
32
|
+
*
|
|
33
|
+
* * TOKENS ARE NOT BYTES. Dividing by 1024 turns 97000 tokens into "94.7k", which is simply wrong — and the context
|
|
34
|
+
* window is not the only figure here, since /ctx and /usage also report live counts that are not powers of two.
|
|
35
|
+
* * IT DISAGREED WITH ITSELF ON SCREEN. The working row divided by 1000 and this divided by 1024, so one frame showed
|
|
36
|
+
* "97k" for the turn and "94.7k" for the context it was using.
|
|
37
|
+
*
|
|
38
|
+
* A model's window is advertised in decimal terms anyway (200k, 128k), so nothing is lost at the size that matters.
|
|
39
|
+
*/
|
|
40
|
+
export function fmtTokens(n) {
|
|
41
|
+
const v = Math.max(0, Math.floor(Number(n) || 0));
|
|
42
|
+
if (!Number.isFinite(v)) return '0';
|
|
43
|
+
const units = [
|
|
44
|
+
{ at: 1e12, suffix: 'T' },
|
|
45
|
+
{ at: 1e9, suffix: 'B' },
|
|
46
|
+
{ at: 1e6, suffix: 'M' },
|
|
47
|
+
{ at: 1e3, suffix: 'k' },
|
|
48
|
+
];
|
|
49
|
+
for (let i = 0; i < units.length; i++) {
|
|
50
|
+
const u = units[i];
|
|
51
|
+
if (v < u.at) continue;
|
|
52
|
+
// The SAME scaling rule as `fmtTokensShort`: a tenth is information at `1.2k` and noise at `262.1k`. Sharing the
|
|
53
|
+
// rule is what keeps one frame from showing `262.1k` for the context and `262k` for the turn that filled it.
|
|
54
|
+
const shown = scaleUnit(v / u.at);
|
|
55
|
+
// Rounding can reach the next unit (`999999` is `1000k`, which is `1m`).
|
|
56
|
+
if (Number(shown) >= 1000 && i > 0) return scaleUnit(v / units[i - 1].at) + units[i - 1].suffix;
|
|
57
|
+
return shown + u.suffix;
|
|
58
|
+
}
|
|
59
|
+
return String(v);
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/**
|
|
63
|
+
* Thousands separators for a plain count.
|
|
64
|
+
*
|
|
65
|
+
* `fmtTokens` rounds to k/M, which is right for a context gauge but wrong for a token BILL: "1.5M input tokens" hides
|
|
66
|
+
* whether that is 1.45M or 1.54M, and the cost readout next to it is precise.
|
|
67
|
+
*/
|
|
68
|
+
export function fmtCount(n) {
|
|
69
|
+
const v = Number(n);
|
|
70
|
+
if (!Number.isFinite(v)) return '0';
|
|
71
|
+
return Math.round(v).toLocaleString('en-US');
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/**
|
|
75
|
+
* A money amount, at a precision that stays readable across five orders of magnitude: a single cheap request is
|
|
76
|
+
* fractions of a cent, a long session is dollars. A bare `0.00` for a real cost is the failure to avoid, so anything
|
|
77
|
+
* non-zero under a cent keeps its decimals rather than rounding away. The symbol is the caller's business — the status
|
|
78
|
+
* row puts it AFTER the number.
|
|
79
|
+
*/
|
|
80
|
+
export function moneyAmount(v, currency = 'USD') {
|
|
81
|
+
const n = Number(v);
|
|
82
|
+
if (!Number.isFinite(n)) return 'n/a';
|
|
83
|
+
// CNY is about 7x USD, so the same amount crosses these thresholds one step sooner; scaling the comparison keeps both
|
|
84
|
+
// currencies at the same precision.
|
|
85
|
+
const scale = currency === 'CNY' ? 7 : 1;
|
|
86
|
+
if (n === 0) return '0.00';
|
|
87
|
+
if (n * scale < 0.01) return n.toFixed(5);
|
|
88
|
+
if (n * scale < 1) return n.toFixed(4);
|
|
89
|
+
return n.toFixed(2);
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/** `$12.34` / `¥86.51` — the amount with its symbol in front. */
|
|
93
|
+
export function formatCost(amount, currency = 'USD') {
|
|
94
|
+
const n = Number(amount);
|
|
95
|
+
if (!Number.isFinite(n)) return 'unknown';
|
|
96
|
+
return `${currency === 'CNY' ? '¥' : '$'}${moneyAmount(n, currency)}`;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/**
|
|
100
|
+
* A tiny ASCII line chart for a numeric series (context growth over steps).
|
|
101
|
+
*
|
|
102
|
+
* Renders `height` rows; each column is one sample, scaled to the series max. No dependency.
|
|
103
|
+
*/
|
|
104
|
+
export function sparkChart(values, width, height) {
|
|
105
|
+
const series = (values || []).filter((v) => Number.isFinite(v));
|
|
106
|
+
if (series.length < 2) return [];
|
|
107
|
+
// Downsample to `width` columns by taking evenly spaced samples.
|
|
108
|
+
const cols = Math.min(width, series.length);
|
|
109
|
+
const sampled = [];
|
|
110
|
+
for (let i = 0; i < cols; i++) {
|
|
111
|
+
sampled.push(series[Math.round(i / (cols - 1) * (series.length - 1))]);
|
|
112
|
+
}
|
|
113
|
+
const max = Math.max(...sampled, 1);
|
|
114
|
+
const min = Math.min(...sampled, 0);
|
|
115
|
+
const span = Math.max(1, max - min);
|
|
116
|
+
const rows = [];
|
|
117
|
+
const BLOCK = [' ', '▁', '▂', '▃', '▄', '▅', '▆', '▇', '█'];
|
|
118
|
+
// Single-row sparkline.
|
|
119
|
+
if (height <= 1) {
|
|
120
|
+
rows.push(sampled.map((v) => BLOCK[Math.min(8, Math.round((v - min) / span * 8))]).join(''));
|
|
121
|
+
return rows;
|
|
122
|
+
}
|
|
123
|
+
for (let r = height - 1; r >= 0; r--) {
|
|
124
|
+
let line = '';
|
|
125
|
+
for (const v of sampled) {
|
|
126
|
+
const level = (v - min) / span * (height - 1);
|
|
127
|
+
line += level >= r ? '█' : ' ';
|
|
128
|
+
}
|
|
129
|
+
rows.push(line);
|
|
130
|
+
}
|
|
131
|
+
return rows;
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/**
|
|
135
|
+
* Usage as a whole-number percentage of `max`, ceiled so any non-zero usage shows at least 1%, clamped to [0, 100].
|
|
136
|
+
*
|
|
137
|
+
* `used` can be undefined on a session resumed before any usage was recorded; without the guard the division produced
|
|
138
|
+
* NaN and the row printed `NaN%` where it should have printed `0%`.
|
|
139
|
+
*/
|
|
140
|
+
export function usagePercent(used, max) {
|
|
141
|
+
if (!Number.isFinite(used)) return 0;
|
|
142
|
+
if (!Number.isFinite(max) || max <= 0) return 0;
|
|
143
|
+
return Math.min(100, Math.max(0, Math.ceil((used / max) * 100)));
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
/** `1h 2m 3s` — every non-zero unit, seconds always shown. */
|
|
147
|
+
export function fmtDuration(ms) {
|
|
148
|
+
ms = Math.max(0, Math.floor(ms));
|
|
149
|
+
const sec = Math.floor(ms / 1000) % 60;
|
|
150
|
+
const min = Math.floor(ms / 60000) % 60;
|
|
151
|
+
const hour = Math.floor(ms / 3600000) % 24;
|
|
152
|
+
const day = Math.floor(ms / 86400000) % 30;
|
|
153
|
+
const mon = Math.floor(ms / 2592000000) % 12;
|
|
154
|
+
const year = Math.floor(ms / 31536000000);
|
|
155
|
+
const parts = [];
|
|
156
|
+
if (year) parts.push(year + 'y');
|
|
157
|
+
if (mon) parts.push(mon + 'mon');
|
|
158
|
+
if (day) parts.push(day + 'd');
|
|
159
|
+
if (hour) parts.push(hour + 'h');
|
|
160
|
+
if (min) parts.push(min + 'm');
|
|
161
|
+
// Seconds are always shown (at least "0s").
|
|
162
|
+
parts.push(sec + 's');
|
|
163
|
+
return parts.join(' ');
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
/**
|
|
167
|
+
* The turn's output tokens as `50k`, `1.2k`, `999`, or `0 tokens`.
|
|
168
|
+
*
|
|
169
|
+
* The rule is the one `Intl` compact notation applies, so a figure read in one tool is not read differently in the
|
|
170
|
+
* other:
|
|
171
|
+
*
|
|
172
|
+
* 1200 -> 1.2k one decimal while it carries information
|
|
173
|
+
* 9999 -> 10k compact rounds here, so the decimal falls away on its own
|
|
174
|
+
* 12400 -> 12.4k STILL one decimal — whole thousands would lose the 400
|
|
175
|
+
* 1234567 -> 1.2M and each thousand-group gets its own unit
|
|
176
|
+
*/
|
|
177
|
+
export function fmtTokensShort(n) {
|
|
178
|
+
const v = Math.max(0, Math.floor(Number(n) || 0));
|
|
179
|
+
if (v < 1000) return `${v} token${v === 1 ? '' : 's'}`;
|
|
180
|
+
const units = [
|
|
181
|
+
{ at: 1e12, suffix: 'T' },
|
|
182
|
+
{ at: 1e9, suffix: 'B' },
|
|
183
|
+
{ at: 1e6, suffix: 'M' },
|
|
184
|
+
{ at: 1e3, suffix: 'k' },
|
|
185
|
+
];
|
|
186
|
+
for (let i = 0; i < units.length; i++) {
|
|
187
|
+
const u = units[i];
|
|
188
|
+
if (v < u.at) continue;
|
|
189
|
+
const scaled = v / u.at;
|
|
190
|
+
// One decimal, dropped when it is a zero — the shape compact notation gives (`1k`, not `1.0k`).
|
|
191
|
+
const shown = scaled < 100 ? scaled.toFixed(1).replace(/\.0$/, '') : String(Math.round(scaled));
|
|
192
|
+
// ROUNDING CAN REACH THE NEXT UNIT. 999999 is 999.999k, which rounds to `1000k`, and `1000k` is `1m` — showing the
|
|
193
|
+
// first makes the reader convert a unit themselves. `units` is ordered largest-first, so `i - 1` is it.
|
|
194
|
+
if (Number(shown) >= 1000 && i > 0) {
|
|
195
|
+
const up = units[i - 1];
|
|
196
|
+
const upScaled = v / up.at;
|
|
197
|
+
const upShown = upScaled < 100 ? upScaled.toFixed(1).replace(/\.0$/, '') : String(Math.round(upScaled));
|
|
198
|
+
return `${upShown}${up.suffix} tokens`;
|
|
199
|
+
}
|
|
200
|
+
return `${shown}${u.suffix} tokens`;
|
|
201
|
+
}
|
|
202
|
+
return `${v} tokens`;
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
/**
|
|
206
|
+
* A prose setting as one short cell, for a list that has room for about forty characters.
|
|
207
|
+
*
|
|
208
|
+
* A truncated paragraph fills that space with text nobody can read and pushes the label out of line with every other
|
|
209
|
+
* row; the size is the fact worth showing at a glance.
|
|
210
|
+
*/
|
|
211
|
+
export function proseSummary(value) {
|
|
212
|
+
const text = String(value == null ? '' : value);
|
|
213
|
+
if (!text.trim()) return '(unset)';
|
|
214
|
+
if (text === '(unset)') return text; // already a placeholder, not prose
|
|
215
|
+
const lines = text.split(/\r?\n/);
|
|
216
|
+
const first = lines[0].trim();
|
|
217
|
+
// One short line with no newline fits as-is — that IS the whole value.
|
|
218
|
+
if (lines.length === 1 && first.length <= 32) return first;
|
|
219
|
+
return `${lines.length} line${lines.length === 1 ? '' : 's'}, ${text.length} chars`;
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
/**
|
|
223
|
+
* The `[2s | ↓40]` tail shown at the end of the Working row, WITHOUT brackets.
|
|
224
|
+
*
|
|
225
|
+
* The brackets belong to the caller, because the two rows want them in different places: the live row wraps the TAIL,
|
|
226
|
+
* the settled row wraps word AND tail. Putting them here produced `[turn took [6m 44s | …]`.
|
|
227
|
+
*
|
|
228
|
+
* The token count is shown FROM THE FIRST FRAME: it used to be hidden for thirty seconds on the theory that a small
|
|
229
|
+
* number is noise, but the row is the only place that number exists, and a count that appears partway through reads as
|
|
230
|
+
* something that just started rather than as a running total.
|
|
231
|
+
*/
|
|
232
|
+
export function elapsedTail(ms, tokens) {
|
|
233
|
+
return `${fmtDuration(ms)} | ↓ ${fmtTokensShort(tokens)}`;
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
/**
|
|
237
|
+
* Has the turn gone quiet, and how much should that show?
|
|
238
|
+
*
|
|
239
|
+
* A turn that produces no tokens for a few seconds is either thinking, waiting on a tool, or stuck — and from outside
|
|
240
|
+
* those look identical. The one case that matters is the last: a request that hangs leaves the row spinning forever
|
|
241
|
+
* with no way to tell it apart from a long answer.
|
|
242
|
+
*
|
|
243
|
+
* Returns 0 while healthy and 1 at full stall, so the caller can interpolate rather than switch abruptly. NEVER
|
|
244
|
+
* reports a stall while a tool is running — a long install is working, not stalled, and flashing at it would train the
|
|
245
|
+
* user to ignore the signal.
|
|
246
|
+
*/
|
|
247
|
+
export const STALL_AFTER_MS = 3000;
|
|
248
|
+
export const STALL_FADE_MS = 2000;
|
|
249
|
+
|
|
250
|
+
export function stallIntensity({ sinceLastTokenMs, hasActiveTools }) {
|
|
251
|
+
if (hasActiveTools) return 0;
|
|
252
|
+
const quiet = Number(sinceLastTokenMs) || 0;
|
|
253
|
+
if (quiet <= STALL_AFTER_MS) return 0;
|
|
254
|
+
return Math.min((quiet - STALL_AFTER_MS) / STALL_FADE_MS, 1);
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
/**
|
|
258
|
+
* Left/right justify: left text, then padding, then right text flush to `w`.
|
|
259
|
+
*
|
|
260
|
+
* ANSI codes are ignored for width so coloured segments still align exactly. When both do not fit, the LEFT is preserved
|
|
261
|
+
* and the RIGHT is truncated — the left is what the user is reading.
|
|
262
|
+
*/
|
|
263
|
+
export function justify(left, right, w) {
|
|
264
|
+
const lw = visualCol(left);
|
|
265
|
+
const rw = visualCol(right);
|
|
266
|
+
if (left && right) {
|
|
267
|
+
if (lw + rw + 1 <= w) return left + ' '.repeat(w - lw - rw) + right;
|
|
268
|
+
const room = w - lw - 1;
|
|
269
|
+
if (room > 0) return left + ' ' + fitAnsi(right, room);
|
|
270
|
+
return fitAnsi(left, w);
|
|
271
|
+
}
|
|
272
|
+
if (!left) return ' '.repeat(Math.max(0, w - rw)) + right;
|
|
273
|
+
if (!right) return left + ' '.repeat(Math.max(0, w - lw));
|
|
274
|
+
return fitAnsi(left, w);
|
|
275
|
+
}
|