@hncode/hncode 0.8.1 → 0.8.3

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.
Files changed (52) hide show
  1. package/README.md +18 -0
  2. package/README_CN.md +14 -0
  3. package/bin/hncode +54 -8
  4. package/package.json +1 -1
  5. package/src/agent-task.js +356 -337
  6. package/src/agent.js +1465 -1405
  7. package/src/animate.js +56 -0
  8. package/src/colors.js +615 -593
  9. package/src/config.js +50 -7
  10. package/src/context-bar.js +280 -278
  11. package/src/doctor.js +4 -3
  12. package/src/file-tree.js +4 -3
  13. package/src/highlight.js +20 -6
  14. package/src/i18n.js +1432 -389
  15. package/src/image-row.js +11 -2
  16. package/src/index.js +218 -6
  17. package/src/keybindings.js +2 -1
  18. package/src/llm.js +146 -21
  19. package/src/log-file.js +112 -0
  20. package/src/markdown.js +646 -567
  21. package/src/mcp-server.js +409 -0
  22. package/src/mcp.js +279 -29
  23. package/src/memory-profile.js +19 -16
  24. package/src/migrate-index.js +175 -0
  25. package/src/migrate.js +392 -0
  26. package/src/panels.js +9 -7
  27. package/src/plan.js +7 -5
  28. package/src/plugin.js +37 -21
  29. package/src/registry-browser.js +17 -15
  30. package/src/rows-plan-bg.js +3 -2
  31. package/src/rows-status.js +20 -6
  32. package/src/rows-tool-result.js +242 -208
  33. package/src/screen-paint.js +153 -128
  34. package/src/session-recover.js +317 -0
  35. package/src/session.js +203 -13
  36. package/src/settings-schema.js +9 -0
  37. package/src/swarm-progress.js +6 -2
  38. package/src/tasks-browser.js +37 -36
  39. package/src/team-panel.js +12 -11
  40. package/src/term.js +57 -21
  41. package/src/text.js +254 -149
  42. package/src/tool-line.js +7 -2
  43. package/src/tool-result.js +400 -327
  44. package/src/tools/agent.js +7 -2
  45. package/src/tools/ask-user-question.js +1 -2
  46. package/src/tools/bash.js +446 -434
  47. package/src/tools/edit.js +653 -665
  48. package/src/tools/goal.js +130 -93
  49. package/src/tools/read.js +141 -133
  50. package/src/tools/tasks.js +214 -214
  51. package/src/tools/utils.js +143 -104
  52. package/src/tui.js +20887 -19942
@@ -1,128 +1,153 @@
1
- /**
2
- * Text and styled strings → a Screen.
3
- *
4
- * The frame composer produces rows of ANSI-decorated strings, because that is how every surface in this app was
5
- * written. Rather than rewrite all of them at once, this module paints those rows into a cell grid: it parses
6
- * the SGR runs, interns each style once, and writes the characters with their widths.
7
- *
8
- * The result is what the painter wants — a grid it can diff cell by cell, and in which a bitmap is a region
9
- * with no characters in it rather than a row with bytes in it.
10
- */
11
- import { charWidth, CELL_WIDTH } from './screen.js';
12
-
13
- /** Matches an SGR sequence: `ESC [ params m`. */
14
- const SGR = /\x1b\[([0-9;]*)m/g;
15
-
16
- /** Matches any other escape sequence, which the painter does not place as text. */
17
- const OTHER_ESCAPE = /\x1b(\[[0-9;?]*[ -/]*[@-~]|\][^\x07\x1b]*(?:\x07|\x1b\\)|[@-_])/g;
18
-
19
- /**
20
- * Split a line into runs of `{ text, styleId }`, interning each style.
21
- *
22
- * Styles are tracked as the CURRENT sgr string in effect, accumulated until a reset. Two runs that end up with
23
- * the same accumulated string share an id, so a row of plain text costs one lookup.
24
- *
25
- * @param {string} line
26
- * @param {import('./screen.js').StylePool} stylePool
27
- * @returns {Array<{text: string, styleId: number}>}
28
- */
29
- export function styledRuns(line, stylePool) {
30
- const runs = [];
31
- let current = '';
32
- let pos = 0;
33
- SGR.lastIndex = 0;
34
-
35
- const push = (text) => {
36
- if (!text) return;
37
- runs.push({ text, styleId: stylePool.intern(current) });
38
- };
39
-
40
- let m;
41
- while ((m = SGR.exec(line))) {
42
- push(line.slice(pos, m.index));
43
- const params = m[1];
44
- // `0` and an empty parameter both mean "reset everything".
45
- if (params === '' || params === '0') current = '';
46
- else current += `\x1b[${params}m`;
47
- pos = m.index + m[0].length;
48
- }
49
- push(line.slice(pos));
50
- return runs;
51
- }
52
-
53
- /** Strip every escape sequence from a string, leaving what the terminal would draw as text. */
54
- export function stripEscapes(line) {
55
- return String(line)
56
- .replace(SGR, '')
57
- .replace(OTHER_ESCAPE, '')
58
- .replace(/\x1b/g, '');
59
- }
60
-
61
- /** Terminal width of a string once its escapes are ignored. */
62
- export function displayWidth(line) {
63
- let w = 0;
64
- for (const ch of stripEscapes(line)) {
65
- const cw = charWidth(ch);
66
- if (cw > 0) w += cw;
67
- }
68
- return w;
69
- }
70
-
71
- /**
72
- * Paint rows of styled text into a screen.
73
- *
74
- * @param {import('./screen.js').Screen} screen Destination, already the right size.
75
- * @param {string[]} rows One string per row; extra rows are ignored, missing ones stay blank.
76
- * @param {import('./screen.js').StylePool} stylePool
77
- */
78
- export function paintRows(screen, rows, stylePool) {
79
- screen._rowCount = rows.length;
80
- const n = Math.min(rows.length, screen.height);
81
- for (let y = 0; y < n; y++) {
82
- const line = rows[y];
83
- if (!line) continue;
84
- let x = 0;
85
- for (const run of styledRuns(line, stylePool)) {
86
- for (const ch of run.text) {
87
- const w = charWidth(ch);
88
- if (w === 0) continue; // a combining mark has no column of its own
89
- if (x + w > screen.width) break;
90
- screen.set(x, y, ch, run.styleId, w);
91
- x += w;
92
- }
93
- if (x >= screen.width) break;
94
- }
95
- screen._mark(0, y, screen.width);
96
- }
97
- }
98
-
99
- /**
100
- * Turn a screen back into rows of ANSI strings, for the paths that still expect text.
101
- *
102
- * This is the inverse of `paintRows` and is meant for the web mirror and for plugins that read the frame's
103
- * lines; the terminal itself is written from the cell diff, not from these strings.
104
- *
105
- * @param {import('./screen.js').Screen} screen
106
- * @returns {string[]}
107
- */
108
- export function screenToRows(screen) {
109
- const rows = [];
110
- for (let y = 0; y < screen.height; y++) {
111
- let out = '';
112
- let styleId = -1;
113
- for (let x = 0; x < screen.width; x++) {
114
- if (screen.isSpacer(x, y)) continue;
115
- const cell = screen.at(x, y);
116
- if (cell.styleId !== styleId) {
117
- out += '\x1b[0m' + screen.stylePool.get(cell.styleId);
118
- styleId = cell.styleId;
119
- }
120
- out += cell.ch;
121
- }
122
- if (styleId !== -1) out += '\x1b[0m';
123
- rows.push(out);
124
- }
125
- return rows;
126
- }
127
-
128
- export { CELL_WIDTH };
1
+ /**
2
+ * Text and styled strings → a Screen.
3
+ *
4
+ * The frame composer produces rows of ANSI-decorated strings, because that is how every surface in this app was
5
+ * written. Rather than rewrite all of them at once, this module paints those rows into a cell grid: it parses
6
+ * the SGR runs, interns each style once, and writes the characters with their widths.
7
+ *
8
+ * The result is what the painter wants — a grid it can diff cell by cell, and in which a bitmap is a region
9
+ * with no characters in it rather than a row with bytes in it.
10
+ */
11
+ import { charWidth, CELL_WIDTH } from './screen.js';
12
+
13
+ /** Matches an SGR sequence: `ESC [ params m`. */
14
+ const SGR = /\x1b\[([0-9;]*)m/g;
15
+
16
+ /** Matches any other escape sequence, which the painter does not place as text. */
17
+ const OTHER_ESCAPE = /\x1b(\[[0-9;?]*[ -/]*[@-~]|\][^\x07\x1b]*(?:\x07|\x1b\\)|[@-_])/g;
18
+
19
+ /**
20
+ * Split a line into runs of `{ text, styleId }`, interning each style.
21
+ *
22
+ * Styles are tracked as the CURRENT sgr string in effect, accumulated until a reset. Two runs that end up with
23
+ * the same accumulated string share an id, so a row of plain text costs one lookup.
24
+ *
25
+ * @param {string} line
26
+ * @param {import('./screen.js').StylePool} stylePool
27
+ * @returns {Array<{text: string, styleId: number}>}
28
+ */
29
+ export function styledRuns(line, stylePool) {
30
+ const runs = [];
31
+ let current = '';
32
+ let pos = 0;
33
+ SGR.lastIndex = 0;
34
+
35
+ const push = (text) => {
36
+ if (!text) return;
37
+ runs.push({ text, styleId: stylePool.intern(current) });
38
+ };
39
+
40
+ let m;
41
+ while ((m = SGR.exec(line))) {
42
+ push(line.slice(pos, m.index));
43
+ const params = m[1];
44
+ // `0` and an empty parameter both mean "reset everything".
45
+ if (params === '' || params === '0') current = '';
46
+ else current += `\x1b[${params}m`;
47
+ pos = m.index + m[0].length;
48
+ }
49
+ push(line.slice(pos));
50
+ return runs;
51
+ }
52
+
53
+ /** Strip every escape sequence from a string, leaving what the terminal would draw as text. */
54
+ export function stripEscapes(line) {
55
+ return String(line)
56
+ .replace(SGR, '')
57
+ .replace(OTHER_ESCAPE, '')
58
+ .replace(/\x1b/g, '');
59
+ }
60
+
61
+ /** Terminal width of a string once its escapes are ignored. */
62
+ export function displayWidth(line) {
63
+ let w = 0;
64
+ for (const ch of stripEscapes(line)) {
65
+ const cw = charWidth(ch);
66
+ if (cw > 0) w += cw;
67
+ }
68
+ return w;
69
+ }
70
+
71
+ /**
72
+ * Paint rows of styled text into a screen.
73
+ *
74
+ * NO INTERMEDIATE RUNS. This used to call `styledRuns`, which built a `{ text, styleId }` object per SGR run and
75
+ * sliced a fresh string for each one — a hundred-odd throwaway objects per frame for a 40-row screen, on top of the
76
+ * per-character `for…of` that allocates a one-character string per glyph.
77
+ *
78
+ * The loop below walks the escapes in place and copies each run straight into the cell grid, so the only allocation
79
+ * left is whatever `screen.set` interns. The painted cells are identical.
80
+ *
81
+ * @param {import('./screen.js').Screen} screen Destination, already the right size.
82
+ * @param {string[]} rows One string per row; extra rows are ignored, missing ones stay blank.
83
+ * @param {import('./screen.js').StylePool} stylePool
84
+ */
85
+ export function paintRows(screen, rows, stylePool) {
86
+ screen._rowCount = rows.length;
87
+ const n = Math.min(rows.length, screen.height);
88
+ const width = screen.width;
89
+ // A style is interned only when it CHANGES, so a run of plain text costs one lookup for the whole row.
90
+ let curStyle = '';
91
+ let curStyleId = -1;
92
+ for (let y = 0; y < n; y++) {
93
+ const line = rows[y];
94
+ if (!line) continue;
95
+ let x = 0;
96
+ let pos = 0;
97
+ let internedForRun = false;
98
+ SGR.lastIndex = 0;
99
+ for (;;) {
100
+ const m = SGR.exec(line);
101
+ const end = m ? m.index : line.length;
102
+ if (end > pos && x < width) {
103
+ if (!internedForRun) { curStyleId = stylePool.intern(curStyle); internedForRun = true; }
104
+ for (let i = pos; i < end; i++) {
105
+ const ch = line[i];
106
+ const w = charWidth(ch);
107
+ if (w === 0) continue; // a combining mark has no column of its own
108
+ if (x + w > width) break;
109
+ screen.set(x, y, ch, curStyleId, w);
110
+ x += w;
111
+ }
112
+ }
113
+ if (!m) break;
114
+ const params = m[1];
115
+ if (params === '' || params === '0') curStyle = '';
116
+ else curStyle += `\x1b[${params}m`;
117
+ pos = m.index + m[0].length;
118
+ internedForRun = false;
119
+ }
120
+ screen._mark(0, y, width);
121
+ }
122
+ }
123
+
124
+ /**
125
+ * Turn a screen back into rows of ANSI strings, for the paths that still expect text.
126
+ *
127
+ * This is the inverse of `paintRows` and is meant for the web mirror and for plugins that read the frame's
128
+ * lines; the terminal itself is written from the cell diff, not from these strings.
129
+ *
130
+ * @param {import('./screen.js').Screen} screen
131
+ * @returns {string[]}
132
+ */
133
+ export function screenToRows(screen) {
134
+ const rows = [];
135
+ for (let y = 0; y < screen.height; y++) {
136
+ let out = '';
137
+ let styleId = -1;
138
+ for (let x = 0; x < screen.width; x++) {
139
+ if (screen.isSpacer(x, y)) continue;
140
+ const cell = screen.at(x, y);
141
+ if (cell.styleId !== styleId) {
142
+ out += '\x1b[0m' + screen.stylePool.get(cell.styleId);
143
+ styleId = cell.styleId;
144
+ }
145
+ out += cell.ch;
146
+ }
147
+ if (styleId !== -1) out += '\x1b[0m';
148
+ rows.push(out);
149
+ }
150
+ return rows;
151
+ }
152
+
153
+ export { CELL_WIDTH };
@@ -0,0 +1,317 @@
1
+ // Recovering a session file that a broken save left unparseable.
2
+ //
3
+ // WHAT BROKE
4
+ // ----------
5
+ // `stringifySession` spliced the message array into a placeholder with
6
+ // `String.replace(pattern, messagesJson)`. A replacement STRING is not literal text:
7
+ // `$&`, `` $` ``, `$'` and `$$` are expansions. A conversation that merely mentioned
8
+ // `sed s/x/$&/g` therefore corrupted its own file on save, and because the write is
9
+ // tmp-then-rename with no verification, the damaged bytes replaced the good ones. The
10
+ // next load failed, `latestSession` fell back to the metadata head, and the next save
11
+ // wrote `messages: []` over the history.
12
+ //
13
+ // Only two of those expansions break the STRUCTURE, and both insert whole copies of text
14
+ // that is already present:
15
+ //
16
+ // `$&` -> the matched placeholder, quotes and all
17
+ // `` $` `` -> a copy of everything before the match, which is the metadata head
18
+ //
19
+ // `$'` inserts the `}` that follows the match and `$$` inserts a `$`: both damage the
20
+ // conversation TEXT, not the JSON around it, so the file still loads.
21
+ //
22
+ // A file saved once can be undone exactly. A file saved repeatedly has the copies
23
+ // interleaved with conversation text that was streaming at the time, so the boundaries
24
+ // are gone and the offset is unrecoverable — the salvager then reads each surviving
25
+ // message OBJECT out of the array and keeps every one that still parses.
26
+ //
27
+ // Nothing here guesses at text. A message whose bytes no longer form a valid object is
28
+ // dropped and counted, never repaired by inference.
29
+
30
+ import fs from 'node:fs';
31
+
32
+ // The literal placeholder as it appears inside a JSON string, quotes included. It can
33
+ // only ever have come from a `$&` expansion: no message the user writes contains a NUL,
34
+ // and JSON.stringify escapes it, so this exact sequence is the marker itself.
35
+ const PLACE_QUOTED = '"\\u0000HNCODE_PLACEHOLDER\\u0000"';
36
+
37
+ const isObj = (v) => v && typeof v === 'object' && !Array.isArray(v);
38
+
39
+ /** Index of the `[` that opens the array value of `"messages"`, or -1. */
40
+ function messagesArrayStart(text) {
41
+ const key = text.indexOf('"messages"');
42
+ if (key < 0) return -1;
43
+ return text.indexOf('[', key);
44
+ }
45
+
46
+ /**
47
+ * The metadata block, parsed on its own.
48
+ *
49
+ * Everything before the messages array is written by `JSON.stringify` alone — it is the
50
+ * SEARCH side of the broken replace, never the replacement — so it is intact even in a
51
+ * file whose array is shredded. Closing it with an empty array yields the whole session
52
+ * minus its messages: title, workspace, todos, usage, shell history, all of it.
53
+ */
54
+ function parseHead(text) {
55
+ const open = messagesArrayStart(text);
56
+ if (open < 0) return null;
57
+ const head = text.slice(0, open);
58
+ for (const tail of ['[]}', '[]'] ) {
59
+ try {
60
+ const obj = JSON.parse(head + tail);
61
+ if (isObj(obj)) return obj;
62
+ } catch { /* try the next closing form */ }
63
+ }
64
+ return null;
65
+ }
66
+
67
+ // End index (exclusive) of the JSON value starting at `at`, or -1 when it is incomplete.
68
+ // Strings are skipped whole, so braces inside a message body cannot be miscounted.
69
+ function valueEnd(text, at) {
70
+ const c = text[at];
71
+ if (c !== '{' && c !== '[') return -1;
72
+ let depth = 0;
73
+ for (let i = at; i < text.length; i++) {
74
+ const ch = text[i];
75
+ if (ch === '"') {
76
+ let j = i + 1;
77
+ while (j < text.length) {
78
+ if (text[j] === '\\') { j += 2; continue; }
79
+ if (text[j] === '"') break;
80
+ j++;
81
+ }
82
+ if (j >= text.length) return -1;
83
+ i = j;
84
+ continue;
85
+ }
86
+ if (ch === '{' || ch === '[') depth++;
87
+ else if (ch === '}' || ch === ']') {
88
+ depth--;
89
+ if (depth === 0) return i + 1;
90
+ }
91
+ }
92
+ return -1;
93
+ }
94
+
95
+ /**
96
+ * Read every message object that still parses, out of a damaged `messages` array.
97
+ *
98
+ * A damaged array is a series of JSON objects with rubbish BETWEEN them, so the scan looks
99
+ * for the next `{"role":` and tries to parse an object there. When that object runs into an
100
+ * inserted copy of the head its own strings still close correctly, so a failed parse means
101
+ * the walk steps INSIDE it instead of skipping past the whole thing — which is what keeps
102
+ * the messages that follow a damaged one.
103
+ */
104
+ export function salvageMessages(text) {
105
+ const open = messagesArrayStart(text);
106
+ if (open < 0) return { messages: [], dropped: 0 };
107
+ const end = text.indexOf('"transcript"', open);
108
+ const limit = end > 0 ? end : text.length;
109
+ const messages = [];
110
+ let dropped = 0;
111
+ let i = open + 1;
112
+ while (i < limit) {
113
+ const at = text.indexOf('{"role":', i);
114
+ if (at < 0 || at >= limit) break;
115
+ const stop = valueEnd(text, at);
116
+ let ok = null;
117
+ if (stop > 0) {
118
+ try { ok = JSON.parse(text.slice(at, stop)); } catch { ok = null; }
119
+ }
120
+ if (isObj(ok) && typeof ok.role === 'string') {
121
+ messages.push(ok);
122
+ i = stop;
123
+ continue;
124
+ }
125
+ dropped++;
126
+ // The object at `at` is damaged. Its damage may span several messages, so resume the
127
+ // search just after its opening key rather than after its (misleading) end.
128
+ i = at + '{"role":'.length;
129
+ }
130
+ return { messages, dropped };
131
+ }
132
+
133
+ /**
134
+ * Make a recovered list safe to SEND, not merely parsed.
135
+ *
136
+ * A salvage can drop the assistant message that ISSUED a tool call while keeping its
137
+ * result, or the other way round. Every provider rejects both: a `tool` row with no call,
138
+ * and a call with no result. The pair rule is the protocol's own — results follow their
139
+ * call immediately — so an assistant keeps only the calls that a following `tool` run
140
+ * answers, and a `tool` row is kept only when the call it answers was kept.
141
+ *
142
+ * Nothing else is touched. Returns `{ messages, orphaned }`.
143
+ */
144
+ export function sanitizeToolPairs(messages) {
145
+ const out = [];
146
+ let orphaned = 0;
147
+ let i = 0;
148
+ while (i < messages.length) {
149
+ const m = messages[i];
150
+ if (!isObj(m)) { i++; continue; }
151
+ if (m.role === 'assistant') {
152
+ const calls = Array.isArray(m.toolCalls) ? m.toolCalls.filter((tc) => tc && tc.id) : [];
153
+ let j = i + 1;
154
+ const results = [];
155
+ while (j < messages.length && isObj(messages[j]) && messages[j].role === 'tool') {
156
+ results.push(messages[j]);
157
+ j++;
158
+ }
159
+ const answered = new Set(results.map((r) => r.toolCallId));
160
+ const keptCalls = calls.filter((tc) => answered.has(tc.id));
161
+ const hasText = typeof m.content === 'string' && m.content.trim();
162
+ if (hasText || keptCalls.length) {
163
+ const copy = { ...m };
164
+ if (calls.length) {
165
+ if (keptCalls.length) copy.toolCalls = keptCalls;
166
+ else delete copy.toolCalls;
167
+ orphaned += calls.length - keptCalls.length;
168
+ }
169
+ out.push(copy);
170
+ const keepIds = new Set(keptCalls.map((tc) => tc.id));
171
+ for (const r of results) {
172
+ if (keepIds.has(r.toolCallId)) out.push(r);
173
+ else orphaned++;
174
+ }
175
+ } else {
176
+ orphaned += 1 + calls.length + results.length;
177
+ }
178
+ i = j;
179
+ continue;
180
+ }
181
+ if (m.role === 'tool') { orphaned++; i++; continue; }
182
+ out.push(m);
183
+ i++;
184
+ }
185
+ return { messages: out, orphaned };
186
+ }
187
+
188
+ /**
189
+ * Delete the copies `` $` `` injected, keeping the first occurrence because the first one
190
+ * IS the file's real head.
191
+ *
192
+ * A saved-once file becomes valid JSON again. A file saved repeatedly usually will not —
193
+ * the copies were spliced around text that was streaming at the time — so the caller
194
+ * falls back to `salvageMessages`.
195
+ */
196
+ function stripInjectedHeadCopies(text) {
197
+ const open = messagesArrayStart(text);
198
+ if (open < 0) return text;
199
+ const head = text.slice(0, open);
200
+ if (head.length < 64) return text;
201
+ let out = text;
202
+ let at = out.indexOf(head, head.length);
203
+ if (at < 0) return out;
204
+ while (at >= 0) {
205
+ out = out.slice(0, at) + out.slice(at + head.length);
206
+ at = out.indexOf(head, head.length);
207
+ }
208
+ return out;
209
+ }
210
+
211
+ /**
212
+ * Salvage the display-only `transcript` array, which follows `messages` in the file.
213
+ *
214
+ * The real key is the LAST unescaped `"transcript":` in the file — an inserted head copy
215
+ * can carry its own, earlier one. The array is written after the messages, so on a file
216
+ * damaged mid-history it is normally intact, but it can be cut too, so every candidate is
217
+ * walked with the same object salvage and the first one that yields rows wins.
218
+ */
219
+ function salvageTranscript(text) {
220
+ const key = '"transcript":';
221
+ let at = text.lastIndexOf(key);
222
+ while (at >= 0) {
223
+ const open = text.indexOf('[', at);
224
+ if (open < 0) return [];
225
+ const got = salvageArrayAt(text, open);
226
+ if (got.length) return got;
227
+ at = text.lastIndexOf(key, at - 1);
228
+ }
229
+ return [];
230
+ }
231
+
232
+ /** Every object in the array starting at `open` that still parses. */
233
+ function salvageArrayAt(text, open) {
234
+ const out = [];
235
+ let i = open + 1;
236
+ while (i < text.length) {
237
+ const start = text.indexOf('{', i);
238
+ if (start < 0) break;
239
+ const stop = valueEnd(text, start);
240
+ if (stop < 0) break;
241
+ try { out.push(JSON.parse(text.slice(start, stop))); } catch { /* skip the damaged one */ }
242
+ i = stop;
243
+ }
244
+ return out;
245
+ }
246
+
247
+ /**
248
+ * Recover a session from a file that does not parse.
249
+ *
250
+ * Returns `{ session, report }`, or null when nothing of value could be read back. The
251
+ * report says which route worked and how many messages were lost, so the caller can tell
252
+ * the user the truth instead of presenting a silently shortened history.
253
+ */
254
+ export function recoverSessionText(text) {
255
+ if (typeof text !== 'string' || !text) return null;
256
+ const head = parseHead(text);
257
+ if (!head) return null;
258
+
259
+ // Route 1, exact: remove what the expansions inserted and reparse.
260
+ let exact = null;
261
+ try {
262
+ const cleaned = stripInjectedHeadCopies(text.split(PLACE_QUOTED).join(''));
263
+ exact = JSON.parse(cleaned);
264
+ } catch { exact = null; }
265
+ if (isObj(exact) && Array.isArray(exact.messages)) {
266
+ const clean = sanitizeToolPairs(exact.messages);
267
+ return {
268
+ session: { ...exact, messages: clean.messages },
269
+ report: { route: 'exact', kept: clean.messages.length, dropped: 0, orphaned: clean.orphaned },
270
+ };
271
+ }
272
+
273
+ // Route 2, salvage: keep every message object that still parses, then make the result
274
+ // safe to send — a salvaged list can hold half of a tool exchange, which every provider
275
+ // rejects with a 400 the moment the session is resumed.
276
+ const salvaged = salvageMessages(text.split(PLACE_QUOTED).join(''));
277
+ const clean = sanitizeToolPairs(salvaged.messages);
278
+ if (!clean.messages.length) return null;
279
+ const session = { ...head, messages: clean.messages };
280
+ // The on-screen rows live after `messages`, so the parsed head does not carry them.
281
+ // Losing them would make a resumed session show less than it had.
282
+ const transcript = salvageTranscript(text);
283
+ if (transcript.length) session.transcript = transcript;
284
+ return {
285
+ session,
286
+ report: {
287
+ route: 'salvage',
288
+ kept: clean.messages.length,
289
+ dropped: salvaged.dropped,
290
+ orphaned: clean.orphaned,
291
+ },
292
+ };
293
+ }
294
+
295
+ /**
296
+ * Recover a session file in place, keeping the damaged original as `<file>.bak`.
297
+ *
298
+ * The backup is written BEFORE the repair, so a wrong recovery is never the only copy
299
+ * left on disk.
300
+ */
301
+ export function recoverSessionFile(file, knownText) {
302
+ let text = typeof knownText === 'string' ? knownText : null;
303
+ if (text === null) {
304
+ try { text = fs.readFileSync(file, 'utf8'); } catch { return null; }
305
+ }
306
+ const got = recoverSessionText(text);
307
+ if (!got) return null;
308
+ try {
309
+ fs.writeFileSync(`${file}.bak`, text, 'utf8');
310
+ const tmp = `${file}.${process.pid}.recover.tmp`;
311
+ fs.writeFileSync(tmp, JSON.stringify(got.session), 'utf8');
312
+ fs.renameSync(tmp, file);
313
+ } catch (e) {
314
+ return { ...got, wrote: false, error: e && e.message ? e.message : String(e) };
315
+ }
316
+ return { ...got, wrote: true, backup: `${file}.bak` };
317
+ }