@causyne/agent 1.20.35 → 1.20.38

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,360 @@
1
+ // ANSI-aware text primitives.
2
+ //
3
+ // Every one of these exists because the CLI got a terminal detail wrong:
4
+ //
5
+ // * `padEnd` on a coloured string pads by BYTE length, so escape sequences
6
+ // counted toward the column and every aligned table drifted.
7
+ // * `slice()` on a coloured string can cut through the middle of an escape,
8
+ // leaking `[38;2;96;205` as literal text and leaving the colour stuck on.
9
+ // * Tool output was printed raw — see sanitize() below, which is a security
10
+ // fix, not a cosmetic one.
11
+ //
12
+ // Pure TypeScript. No dependency, no shell.
13
+
14
+ import os from 'node:os';
15
+
16
+ // CSI sequences (colour, cursor movement, erase) and OSC sequences (window
17
+ // title, hyperlinks — terminated by BEL or ST).
18
+ const CSI_PATTERN = /\x1b\[[0-?]*[ -/]*[@-~]/g;
19
+ const OSC_PATTERN = /\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)/g;
20
+ const OTHER_ESCAPE_PATTERN = /\x1b[@-Z\\-_]/g;
21
+ const OSC8_SEQUENCE = /^\x1b\]8;[^;]*;([^\x07\x1b]*)(\x07|\x1b\\)/;
22
+
23
+ /** Everything that is an escape sequence rather than visible text. */
24
+ export function stripAnsi(text: unknown): string {
25
+ return String(text == null ? '' : text)
26
+ .replace(OSC_PATTERN, '')
27
+ .replace(CSI_PATTERN, '')
28
+ .replace(OTHER_ESCAPE_PATTERN, '');
29
+ }
30
+
31
+ /**
32
+ * Does this code point occupy two terminal columns?
33
+ *
34
+ * CJK, Hangul, Kana and most emoji are double-width. Getting this wrong is what
35
+ * makes a table of Indonesian and Chinese filenames drift apart.
36
+ */
37
+ function isWideCodePoint(code: number): boolean {
38
+ return (
39
+ (code >= 0x1100 && code <= 0x115f) || // Hangul Jamo
40
+ (code >= 0x2e80 && code <= 0xa4cf) || // CJK radicals … Yi
41
+ (code >= 0xac00 && code <= 0xd7a3) || // Hangul syllables
42
+ (code >= 0xf900 && code <= 0xfaff) || // CJK compatibility ideographs
43
+ (code >= 0xfe30 && code <= 0xfe6f) || // CJK compatibility forms
44
+ (code >= 0xff00 && code <= 0xff60) || // Fullwidth forms
45
+ (code >= 0xffe0 && code <= 0xffe6) ||
46
+ (code >= 0x1f300 && code <= 0x1f64f) || // emoji
47
+ (code >= 0x1f900 && code <= 0x1f9ff)
48
+ );
49
+ }
50
+
51
+ /**
52
+ * The East Asian AMBIGUOUS class (UAX #11).
53
+ *
54
+ * These render as ONE column beside Latin text and TWO beside CJK, depending on
55
+ * the terminal's font and locale — and every glyph in theme.js GLYPHS is in this
56
+ * class: `·` U+00B7, `▸` U+25B8, `✓` U+2713, `─` U+2500, `│` U+2502, `…` U+2026.
57
+ *
58
+ * Counting them narrow is right for a Western-configured terminal and is what
59
+ * every comparable library does, so that stays the default. But when the count
60
+ * is wrong the row is WIDER than measured, the terminal wraps it, and a wrapped
61
+ * row makes ChatPrompt.drawnRows (logical) disagree with the physical row count
62
+ * — which is what left a doubled hint row and glyph debris on screen. Callers
63
+ * that must not be wrong get the wide reading via the environment.
64
+ */
65
+ function isAmbiguousCodePoint(code: number): boolean {
66
+ return (
67
+ (code >= 0x00a1 && code <= 0x00ff && code !== 0x00ad) ||
68
+ (code >= 0x2010 && code <= 0x2027) ||
69
+ code === 0x2022 || code === 0x2026 ||
70
+ (code >= 0x2190 && code <= 0x21ff) || // arrows
71
+ (code >= 0x2200 && code <= 0x22ff) || // mathematical operators
72
+ (code >= 0x2460 && code <= 0x24ff) || // enclosed alphanumerics
73
+ (code >= 0x2500 && code <= 0x257f) || // box drawing
74
+ (code >= 0x2580 && code <= 0x259f) || // block elements
75
+ (code >= 0x25a0 && code <= 0x25ff) || // geometric shapes
76
+ (code >= 0x2600 && code <= 0x26ff) || // miscellaneous symbols
77
+ (code >= 0x2700 && code <= 0x27bf) // dingbats (✓ ✕)
78
+ );
79
+ }
80
+
81
+ /**
82
+ * Should ambiguous-width code points be measured as two columns?
83
+ *
84
+ * Read once at import: an explicit override wins, otherwise a CJK locale is the
85
+ * signal, because that is the configuration in which a terminal's font actually
86
+ * renders these glyphs wide.
87
+ */
88
+ function detectAmbiguousWide(): boolean {
89
+ const explicit = process.env.CAUSYNE_AMBIGUOUS_WIDE;
90
+ if (explicit === '1') return true;
91
+ if (explicit === '0') return false;
92
+ const locale = String(process.env.LC_ALL || process.env.LC_CTYPE || process.env.LANG || '');
93
+ return /^(ja|ko|zh)([_.-]|$)/i.test(locale);
94
+ }
95
+
96
+ export const AMBIGUOUS_IS_WIDE: boolean = detectAmbiguousWide();
97
+
98
+ /** Columns one code point occupies, under the active ambiguous-width policy. */
99
+ function columnsFor(code: number): number {
100
+ if (isWideCodePoint(code)) return 2;
101
+ if (AMBIGUOUS_IS_WIDE && isAmbiguousCodePoint(code)) return 2;
102
+ return 1;
103
+ }
104
+
105
+ /** Columns this string will occupy once printed. Escapes count for nothing. */
106
+ export function visibleWidth(text: unknown): number {
107
+ const plain = stripAnsi(text);
108
+ let width = 0;
109
+ for (const character of plain) {
110
+ const code = character.codePointAt(0);
111
+ if (code === undefined) continue;
112
+ if (code === 0x200d) continue; // zero-width joiner
113
+ if (code >= 0xfe00 && code <= 0xfe0f) continue; // variation selectors
114
+ width += columnsFor(code);
115
+ }
116
+ return width;
117
+ }
118
+
119
+ const RESET = '\x1b[0m';
120
+
121
+ /**
122
+ * Cut to `width` columns without ever splitting an escape sequence.
123
+ *
124
+ * Walks the string escape-aware rather than slicing by index, and closes any
125
+ * style or OSC 8 hyperlink that was still open at the cut so neither colour nor
126
+ * link underline bleeds into the rest of the row or subsequent rows.
127
+ */
128
+ export function truncate(text: unknown, width: number, ellipsis = '…'): string {
129
+ const source = String(text == null ? '' : text);
130
+ if (width <= 0) return '';
131
+ if (visibleWidth(source) <= width) return source;
132
+
133
+ const ellipsisWidth = visibleWidth(ellipsis);
134
+ const budget = Math.max(0, width - ellipsisWidth);
135
+
136
+ let out = '';
137
+ let used = 0;
138
+ let sawEscape = false;
139
+ let openOsc8Term = '';
140
+ let index = 0;
141
+
142
+ while (index < source.length) {
143
+ if (source[index] === '\x1b') {
144
+ // Copy the whole sequence verbatim; it costs no columns.
145
+ const rest = source.slice(index);
146
+ const match = rest.match(/^\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)/)
147
+ || rest.match(/^\x1b\[[0-?]*[ -/]*[@-~]/)
148
+ || rest.match(/^\x1b[@-Z\\-_]/);
149
+ if (match) {
150
+ const osc8 = OSC8_SEQUENCE.exec(match[0]);
151
+ if (osc8) {
152
+ const uri = osc8[1] ?? '';
153
+ const term = osc8[2] ?? '\x1b\\';
154
+ openOsc8Term = uri.length > 0 ? term : '';
155
+ }
156
+ out += match[0];
157
+ sawEscape = true;
158
+ index += match[0].length;
159
+ continue;
160
+ }
161
+ }
162
+
163
+ const code = source.codePointAt(index);
164
+ if (code === undefined) break;
165
+ const character = String.fromCodePoint(code);
166
+ const charWidth = columnsFor(code);
167
+ if (used + charWidth > budget) break;
168
+
169
+ out += character;
170
+ used += charWidth;
171
+ index += character.length;
172
+ }
173
+
174
+ const osc8Reset = openOsc8Term ? `\x1b]8;;${openOsc8Term}` : '';
175
+ return out + osc8Reset + (sawEscape ? RESET : '') + ellipsis;
176
+ }
177
+
178
+ /** Pad to an exact column count, measuring visible width rather than bytes. */
179
+ export function padEnd(text: unknown, width: number): string {
180
+ const gap = width - visibleWidth(text);
181
+ return gap > 0 ? String(text) + ' '.repeat(gap) : String(text);
182
+ }
183
+
184
+ export function wrap(text: unknown, width: number, _options?: { hang?: number }): string[] {
185
+ if (width <= 0) return [String(text)];
186
+ const lines: string[] = [];
187
+
188
+ for (const paragraph of String(text == null ? '' : text).split('\n')) {
189
+ if (visibleWidth(paragraph) <= width) {
190
+ lines.push(paragraph);
191
+ continue;
192
+ }
193
+
194
+ let current = '';
195
+ for (const word of paragraph.split(' ')) {
196
+ const candidate = current ? `${current} ${word}` : word;
197
+
198
+ if (visibleWidth(candidate) <= width) {
199
+ current = candidate;
200
+ continue;
201
+ }
202
+ if (current) {
203
+ lines.push(current);
204
+ current = '';
205
+ }
206
+
207
+ let remainder = word;
208
+ while (visibleWidth(remainder) > width) {
209
+ lines.push(truncate(remainder, width, ''));
210
+ // truncate() gives us the head; drop the same number of characters.
211
+ let consumed = 0;
212
+ let cut = 0;
213
+ while (cut < remainder.length && consumed < width) {
214
+ const code = remainder.codePointAt(cut);
215
+ if (code === undefined) break;
216
+ consumed += columnsFor(code);
217
+ cut += String.fromCodePoint(code).length;
218
+ }
219
+ remainder = remainder.slice(cut);
220
+ }
221
+ current = remainder;
222
+ }
223
+ if (current) lines.push(current);
224
+ }
225
+
226
+ return lines;
227
+ }
228
+
229
+ /**
230
+ * Word-wrap a block of text while preserving each line's own indentation.
231
+ *
232
+ * wrap() flattens indentation, which turns a nested list into a wall. This keeps
233
+ * the leading whitespace a line already has and indents its continuation rows by
234
+ * `hang` more, so a wrapped `/skills` entry still reads as one entry.
235
+ *
236
+ * Exists because command output was written to the terminal completely unwrapped
237
+ * — a `/skills` description reached 195 columns on a 102-column terminal and the
238
+ * terminal broke it at the right edge, mid-word, at column 0.
239
+ */
240
+ export function wrapBlock(text: unknown, width: number, { hang = 2 }: { hang?: number } = {}): string[] {
241
+ const rows: string[] = [];
242
+ for (const line of String(text == null ? '' : text).split('\n')) {
243
+ const indent = (line.match(/^[ \t]*/) || [''])[0];
244
+ const body = line.slice(indent.length);
245
+ if (!body) { rows.push(''); continue; }
246
+
247
+ const continuation = indent + ' '.repeat(hang);
248
+ // Wrap at the NARROWER of the two budgets so neither the first row nor a
249
+ // continuation row can exceed `width`.
250
+ const budget = Math.max(8, width - visibleWidth(continuation));
251
+ const parts = wrap(body, budget);
252
+ rows.push(indent + (parts[0] ?? ''));
253
+ for (const part of parts.slice(1)) rows.push(continuation + part);
254
+ }
255
+ return rows;
256
+ }
257
+
258
+ /**
259
+ * Make untrusted text safe to print.
260
+ *
261
+ * SECURITY, not cosmetics. Tool output reaches the terminal directly: a file
262
+ * read by fs_read, or the stdout of sysRun, is attacker-influenced content. If
263
+ * it carries escape sequences it can move the cursor, erase the screen, or
264
+ * overwrite lines that are already printed — including repainting an approval
265
+ * prompt the user just answered. Stripping escapes is what makes "the user saw
266
+ * what happened" true.
267
+ *
268
+ * Newlines and tabs survive; every other control character does not.
269
+ */
270
+ /** Columns between terminal tab stops. Eight is the POSIX default everywhere. */
271
+ const TAB_WIDTH = 8;
272
+
273
+ /**
274
+ * Replace tabs with the spaces the terminal would have moved over.
275
+ *
276
+ * A TAB MOVES THE CURSOR WITHOUT WRITING ANYTHING. In a live region that
277
+ * redraws in place, that is not a formatting detail — it is corruption. The
278
+ * cursor jumps over cells the previous frame wrote and leaves them on screen,
279
+ * so `sw_vers` output rendered as:
280
+ *
281
+ * ProductName:P_FIX_PLAN.mdmacOS
282
+ * ProductVersion:EGOTIATION26.5.2
283
+ *
284
+ * where `P_FIX_PLAN.md` and `EGOTIATION` are the tails of filenames printed by
285
+ * the PREVIOUS command. Spaces overwrite; tabs do not.
286
+ *
287
+ * It also breaks measurement, which is worse. visibleWidth() counted a tab as
288
+ * one column while the terminal advanced up to eight — on that line the error
289
+ * was ten columns. A row the renderer believes fits therefore wraps, erase()
290
+ * miscounts how many rows to walk back, and it eats real conversation above the
291
+ * prompt. That is the live-region width invariant, broken by one byte.
292
+ *
293
+ * Tab stops are per LINE and reset after every newline, so this tracks the
294
+ * column rather than substituting a fixed run of spaces — which is what keeps
295
+ * columnar output actually lining up.
296
+ */
297
+ export function expandTabs(text: unknown, tabWidth = TAB_WIDTH): string {
298
+ const source = String(text == null ? '' : text);
299
+ if (!source.includes('\t')) return source;
300
+
301
+ let out = '';
302
+ let column = 0;
303
+ for (const char of source) {
304
+ if (char === '\t') {
305
+ const advance = tabWidth - (column % tabWidth);
306
+ out += ' '.repeat(advance);
307
+ column += advance;
308
+ } else if (char === '\n') {
309
+ out += char;
310
+ column = 0;
311
+ } else {
312
+ out += char;
313
+ column += 1;
314
+ }
315
+ }
316
+ return out;
317
+ }
318
+
319
+ export function sanitize(text: unknown): string {
320
+ // Tabs are expanded rather than stripped: removing them would collapse
321
+ // columnar output into an unreadable run, and leaving them corrupts the
322
+ // frame. Expansion is the only option that preserves what the user meant to
323
+ // see. Everything else in this class is genuinely unwanted and is removed.
324
+ const normalized = String(text == null ? '' : text)
325
+ .replace(/\r\n/g, '\n')
326
+ .replace(/\r/g, '\n');
327
+ return expandTabs(stripAnsi(normalized))
328
+ // eslint-disable-next-line no-control-regex
329
+ .replace(/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]/g, '');
330
+ }
331
+
332
+ /** `/Users/example/Projects/x` → `~/Projects/x`. Long paths dominate a tool row. */
333
+ export function shortenHome(value: unknown): string {
334
+ const home = os.homedir();
335
+ const text = String(value == null ? '' : value);
336
+ if (home && text.startsWith(home)) return '~' + text.slice(home.length);
337
+ return text;
338
+ }
339
+
340
+ const SECRET_PATTERNS: Array<[RegExp, (match: string) => string]> = [
341
+ [/\b(sk|pk|rk)-[A-Za-z0-9_-]{12,}/g, (m) => `${m.slice(0, 5)}…${m.slice(-4)}`],
342
+ [/\b(gh[pousr]|xox[baprs])_[A-Za-z0-9]{12,}/g, (m) => `${m.slice(0, 7)}…`],
343
+ [/\b(Bearer|Basic)\s+[A-Za-z0-9._~+/=-]{12,}/gi, (m) => `${m.split(/\s+/)[0]} …`],
344
+ [/\b(api[_-]?key|token|secret|password|passwd)\s*[=:]\s*["']?[^\s"']{6,}/gi,
345
+ (m) => `${m.split(/[=:]/)[0]}=…`]
346
+ ];
347
+
348
+ export function redactSecrets(text: unknown): string {
349
+ let out = String(text == null ? '' : text);
350
+ for (const [pattern, replace] of SECRET_PATTERNS) {
351
+ out = out.replace(pattern, replace);
352
+ }
353
+ return out;
354
+ }
355
+
356
+ /** sanitize + redact — the pipeline every untrusted string goes through. */
357
+ export function safeDisplay(text: unknown): string {
358
+ return redactSecrets(sanitize(text));
359
+ }
360
+
@@ -0,0 +1,210 @@
1
+ import fs from 'node:fs';
2
+ const DECAY_MARKER = '[decayed]';
3
+ const SPILL_HEADER_PREFIX = '=== CAUSYNE TOOL OUTPUT';
4
+ /**
5
+ * Strip internal context-compaction markers, ToolOutputStore spill headers,
6
+ * and middle-omission notices so the TUI only displays real tool output.
7
+ */
8
+ export function cleanToolOutputPreview(payload, toolName = '') {
9
+ if (!payload || typeof payload !== 'string')
10
+ return '';
11
+ if (toolName === 'update_plan')
12
+ return '';
13
+ const trimmed = payload.trim();
14
+ if (!trimmed || trimmed.startsWith(DECAY_MARKER))
15
+ return '';
16
+ let text = payload
17
+ .replace(/\x1b\[(?:[12]K|\d*G)/g, '\n')
18
+ .replace(/(https?:\/\/[^\s"'<>]+?\.[a-z]{2,10})([A-Z][a-z]{2,15}:\s)/g, '$1\n$2');
19
+ // Strip renderSpillDocument metadata header up to the first `--- field: ... ---` marker
20
+ if (text.startsWith(SPILL_HEADER_PREFIX)) {
21
+ const fieldHeaderMatch = /\n--- field: [^\n]+ ---\n/.exec(text);
22
+ if (fieldHeaderMatch && fieldHeaderMatch.index !== undefined) {
23
+ text = text.slice(fieldHeaderMatch.index + fieldHeaderMatch[0].length);
24
+ }
25
+ else {
26
+ const blankLineIndex = text.indexOf('\n\n');
27
+ if (blankLineIndex !== -1) {
28
+ text = text.slice(blankLineIndex + 2);
29
+ }
30
+ }
31
+ }
32
+ // Strip internal ToolOutputStore and historyPruner middle-omission lines
33
+ const filteredLines = text
34
+ .split('\n')
35
+ .filter(line => {
36
+ const t = line.trim();
37
+ if (t.startsWith('[... Causyne ToolOutputStore:'))
38
+ return false;
39
+ if (t.startsWith('[... Full log persisted to:'))
40
+ return false;
41
+ if (t.startsWith('[... Read or search a relevant range'))
42
+ return false;
43
+ if (/^\[\d+\s+middle characters omitted from active context/i.test(t))
44
+ return false;
45
+ return true;
46
+ });
47
+ return filteredLines.join('\n').trim();
48
+ }
49
+ function readSpillPreview(spillPath, maxBytes = 4096) {
50
+ if (!spillPath || typeof spillPath !== 'string')
51
+ return '';
52
+ try {
53
+ if (!fs.existsSync(spillPath))
54
+ return '';
55
+ const stat = fs.statSync(spillPath);
56
+ if (!stat.isFile() || stat.size <= 0)
57
+ return '';
58
+ const bytesToRead = Math.min(stat.size, maxBytes);
59
+ const fd = fs.openSync(spillPath, 'r');
60
+ try {
61
+ const buf = Buffer.alloc(bytesToRead);
62
+ const read = fs.readSync(fd, buf, 0, bytesToRead, 0);
63
+ return buf.subarray(0, read).toString('utf8');
64
+ }
65
+ finally {
66
+ fs.closeSync(fd);
67
+ }
68
+ }
69
+ catch {
70
+ return '';
71
+ }
72
+ }
73
+ function extractSpillPathFromDecay(content) {
74
+ const match = /\bat (\/[^\s]+)\s+—\s+read or search\b/.exec(content);
75
+ return match?.[1];
76
+ }
77
+ function recoverBrokenJsonOutput(raw, spillPath) {
78
+ const prefixMatch = /^\s*\{\s*"success"\s*:\s*(true|false)\b/.exec(raw);
79
+ if (!prefixMatch)
80
+ return null;
81
+ const success = prefixMatch[1] === 'true';
82
+ if (spillPath) {
83
+ const fromSpill = readSpillPreview(spillPath);
84
+ if (fromSpill) {
85
+ return { success, output: fromSpill, spillPath };
86
+ }
87
+ }
88
+ const outputMatch = /"output"\s*:\s*"([\s\S]*)/.exec(raw);
89
+ if (outputMatch?.[1]) {
90
+ const body = outputMatch[1]
91
+ .replace(/"\s*\}\s*$/, '')
92
+ .replace(/\\n/g, '\n')
93
+ .replace(/\\"/g, '"')
94
+ .replace(/\\\\/g, '\\');
95
+ return {
96
+ success,
97
+ output: body,
98
+ ...(spillPath ? { spillPath } : {})
99
+ };
100
+ }
101
+ return {
102
+ success,
103
+ output: '',
104
+ ...(spillPath ? { spillPath } : {})
105
+ };
106
+ }
107
+ /**
108
+ * Normalize a historical `role: 'tool'` message for TUI session replay.
109
+ * Suppresses internal `checkpoint: 'synthesis'` governor intercepts (which are
110
+ * never emitted during live execution) and recovers clean output previews for
111
+ * `[decayed]` or shortened tool observations.
112
+ */
113
+ export function normalizeHistoricalToolResult(toolName, toolMsg, options = {}) {
114
+ const explicitSpill = typeof toolMsg.spillPath === 'string' && toolMsg.spillPath.trim()
115
+ ? toolMsg.spillPath.trim()
116
+ : undefined;
117
+ if (typeof toolMsg.content === 'string') {
118
+ const raw = toolMsg.content;
119
+ if (raw.startsWith(DECAY_MARKER)) {
120
+ const spillPath = explicitSpill ?? extractSpillPathFromDecay(raw);
121
+ const isFailure = /^\[decayed\] [^:]+: reported failure\b/i.test(raw);
122
+ const success = !isFailure;
123
+ if (toolName === 'update_plan') {
124
+ return {
125
+ skipStep: Boolean(options.unpaired),
126
+ result: { success: true, output: '' }
127
+ };
128
+ }
129
+ const recoveredRaw = spillPath ? readSpillPreview(spillPath) : '';
130
+ const cleaned = cleanToolOutputPreview(recoveredRaw, toolName);
131
+ return {
132
+ skipStep: false,
133
+ result: {
134
+ success,
135
+ output: cleaned,
136
+ ...(spillPath ? { spillPath } : {})
137
+ }
138
+ };
139
+ }
140
+ let parsed = null;
141
+ try {
142
+ const candidate = JSON.parse(raw);
143
+ if (candidate && typeof candidate === 'object' && !Array.isArray(candidate)) {
144
+ parsed = { ...candidate };
145
+ }
146
+ }
147
+ catch {
148
+ parsed = recoverBrokenJsonOutput(raw, explicitSpill);
149
+ }
150
+ if (parsed) {
151
+ if (parsed.checkpoint === 'synthesis') {
152
+ return { skipStep: true, result: parsed };
153
+ }
154
+ if (parsed.success === undefined) {
155
+ parsed.success = !parsed.error;
156
+ }
157
+ if (explicitSpill && typeof parsed.spillPath !== 'string') {
158
+ parsed.spillPath = explicitSpill;
159
+ }
160
+ if (typeof parsed.output === 'string') {
161
+ parsed.output = cleanToolOutputPreview(parsed.output, toolName);
162
+ }
163
+ if (typeof parsed.log === 'string') {
164
+ parsed.log = cleanToolOutputPreview(parsed.log, toolName);
165
+ }
166
+ const plan = Array.isArray(parsed.plan)
167
+ ? parsed.plan
168
+ : undefined;
169
+ return { skipStep: false, result: parsed, plan };
170
+ }
171
+ const lowered = raw.toLowerCase();
172
+ return {
173
+ skipStep: false,
174
+ result: {
175
+ success: !lowered.startsWith('error') && !lowered.includes('failed'),
176
+ output: cleanToolOutputPreview(raw, toolName),
177
+ ...(explicitSpill ? { spillPath: explicitSpill } : {})
178
+ }
179
+ };
180
+ }
181
+ if (toolMsg.content && typeof toolMsg.content === 'object' && !Array.isArray(toolMsg.content)) {
182
+ const copy = { ...toolMsg.content };
183
+ if (copy.checkpoint === 'synthesis') {
184
+ return { skipStep: true, result: copy };
185
+ }
186
+ if (copy.success === undefined)
187
+ copy.success = !copy.error;
188
+ if (explicitSpill && typeof copy.spillPath !== 'string') {
189
+ copy.spillPath = explicitSpill;
190
+ }
191
+ if (typeof copy.output === 'string') {
192
+ copy.output = cleanToolOutputPreview(copy.output, toolName);
193
+ }
194
+ if (typeof copy.log === 'string') {
195
+ copy.log = cleanToolOutputPreview(copy.log, toolName);
196
+ }
197
+ const plan = Array.isArray(copy.plan)
198
+ ? copy.plan
199
+ : undefined;
200
+ return { skipStep: false, result: copy, plan };
201
+ }
202
+ return {
203
+ skipStep: false,
204
+ result: {
205
+ success: true,
206
+ output: '',
207
+ ...(explicitSpill ? { spillPath: explicitSpill } : {})
208
+ }
209
+ };
210
+ }