@causyne/agent 1.20.36 → 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
+
@@ -13,7 +13,9 @@ export function cleanToolOutputPreview(payload, toolName = '') {
13
13
  const trimmed = payload.trim();
14
14
  if (!trimmed || trimmed.startsWith(DECAY_MARKER))
15
15
  return '';
16
- let text = payload;
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');
17
19
  // Strip renderSpillDocument metadata header up to the first `--- field: ... ---` marker
18
20
  if (text.startsWith(SPILL_HEADER_PREFIX)) {
19
21
  const fieldHeaderMatch = /\n--- field: [^\n]+ ---\n/.exec(text);
@@ -28,7 +28,9 @@ export function cleanToolOutputPreview(payload: string, toolName = ''): string {
28
28
  const trimmed = payload.trim();
29
29
  if (!trimmed || trimmed.startsWith(DECAY_MARKER)) return '';
30
30
 
31
- let text = payload;
31
+ let text = payload
32
+ .replace(/\x1b\[(?:[12]K|\d*G)/g, '\n')
33
+ .replace(/(https?:\/\/[^\s"'<>]+?\.[a-z]{2,10})([A-Z][a-z]{2,15}:\s)/g, '$1\n$2');
32
34
 
33
35
  // Strip renderSpillDocument metadata header up to the first `--- field: ... ---` marker
34
36
  if (text.startsWith(SPILL_HEADER_PREFIX)) {
@@ -124,7 +124,17 @@ export function sliceFromColumn(source, startCol) {
124
124
  }
125
125
  }
126
126
  if (col >= startCol) {
127
- return activeStyles + source.slice(index);
127
+ const tail = source.slice(index);
128
+ // Ensure any OSC 8 hyperlink opened inside `tail` is closed at the end of the slice
129
+ let openOsc8Term = '';
130
+ const osc8Re = /\x1b\]8;[^;]*;([^\x07\x1b]*)(\x07|\x1b\\)/g;
131
+ let oscMatch;
132
+ while ((oscMatch = osc8Re.exec(tail)) !== null) {
133
+ const uri = oscMatch[1] ?? '';
134
+ const term = oscMatch[2] ?? '\x1b\\';
135
+ openOsc8Term = uri.length > 0 ? term : '';
136
+ }
137
+ return activeStyles + tail + (openOsc8Term ? `\x1b]8;;${openOsc8Term}` : '');
128
138
  }
129
139
  const code = source.codePointAt(index);
130
140
  if (code === undefined)
@@ -158,7 +158,17 @@ export function sliceFromColumn(source: string, startCol: number): string {
158
158
  }
159
159
 
160
160
  if (col >= startCol) {
161
- return activeStyles + source.slice(index);
161
+ const tail = source.slice(index);
162
+ // Ensure any OSC 8 hyperlink opened inside `tail` is closed at the end of the slice
163
+ let openOsc8Term = '';
164
+ const osc8Re = /\x1b\]8;[^;]*;([^\x07\x1b]*)(\x07|\x1b\\)/g;
165
+ let oscMatch: RegExpExecArray | null;
166
+ while ((oscMatch = osc8Re.exec(tail)) !== null) {
167
+ const uri = oscMatch[1] ?? '';
168
+ const term = oscMatch[2] ?? '\x1b\\';
169
+ openOsc8Term = uri.length > 0 ? term : '';
170
+ }
171
+ return activeStyles + tail + (openOsc8Term ? `\x1b]8;;${openOsc8Term}` : '');
162
172
  }
163
173
 
164
174
  const code = source.codePointAt(index);
package/src/tui/text.d.ts DELETED
@@ -1,7 +0,0 @@
1
- export function safeDisplay(value: string): string;
2
- export function stripAnsi(text: string): string;
3
- export function truncate(value: string, width: number, ellipsis?: string): string;
4
- export function padEnd(value: string, width: number): string;
5
- export function visibleWidth(value: string): number;
6
- export function wrap(value: string, width: number, options?: { hang?: number }): string[];
7
- export function wrapBlock(value: string, width: number, options?: { hang?: number }): string[];