noguard 1.2.0 → 1.3.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/lib/render.mjs CHANGED
@@ -1,398 +1,400 @@
1
- // Terminal output: vibrant 256-color palette, streamed markdown, status bars, sections, diffs.
2
-
3
- const useColor = process.stdout.isTTY && !process.env.NO_COLOR
4
- const trueColor = useColor && /^(truecolor|24bit)$/i.test(process.env.COLORTERM || '')
5
- const sgr = code => useColor ? `\x1b[${code}m` : ''
6
- const c256 = fg => useColor ? `\x1b[38;5;${fg}m` : ''
7
- const c256bg = bg => useColor ? `\x1b[48;5;${bg}m` : ''
8
-
9
- /** A role colour: 24-bit where the terminal supports it, nearest 256-colour otherwise, nothing when colour is off. */
10
- function paint(hex, fallback) {
11
- if (!useColor) return ''
12
- if (!trueColor) return `\x1b[38;5;${fallback}m`
13
- const n = parseInt(hex.slice(1), 16)
14
- return `\x1b[38;2;${(n >> 16) & 255};${(n >> 8) & 255};${n & 255}m`
15
- }
16
- function paintBg(hex, fallback) {
17
- if (!useColor) return ''
18
- if (!trueColor) return `\x1b[48;5;${fallback}m`
19
- const n = parseInt(hex.slice(1), 16)
20
- return `\x1b[48;2;${(n >> 16) & 255};${(n >> 8) & 255};${n & 255}m`
21
- }
22
-
23
- // ─── Core formatting ─────────────────────────────────────
24
- export const RST = sgr(0)
25
- export const BOLD = sgr(1)
26
- export const DIM = sgr(2)
27
- export const ITALIC = sgr(3)
28
- export const UNDERLINE = sgr(4)
29
-
30
- // ─── Aurora palette — seven roles, each with one job ────
31
- export const IRIS = paint('#9A92FF', 141) // primary — models, headings, the caret
32
- export const CYAN = paint('#39E0E6', 51) // live edges — prompt, active state
33
- export const MINT = paint('#45E0A4', 49) // success — tools, confirmations, +diff
34
- export const AMBER = paint('#FFB65C', 215) // credits — cost, spend, warnings
35
- export const ROSE = paint('#FF6183', 204) // alert — errors, −diff, low balance, yolo
36
- export const SKY = paint('#5FC9FF', 81) // paths — files, links, info
37
- export const MAGENTA = paint('#E36BFF', 177) // raw tier, inline code, the gradient's end
38
- export const GOLD = paint('#FFC861', 221) // ultra tier, emphasis
39
- export const COBALT = paint('#6E8BFF', 69) // links, special actions
40
- export const LAVENDER = paint('#B9B2FF', 183) // blockquotes, metadata
41
-
42
- // ─── Neutrals (the onyx world) ──────────────────────────
43
- export const FG_STRONG = paint('#F7F9FD', 231) // primary emphasis
44
- export const FG = paint('#E8EBF4', 255) // body text
45
- export const DIMFG = paint('#9BA2B8', 247) // secondary text
46
- export const MUTED = paint('#6C7389', 244) // labels
47
- export const FAINT = paint('#495069', 240) // subtle marks
48
- export const LINE = paint('#39405A', 238) // borders, separators
49
-
50
- // ─── Backward-compatible aliases (old names → Aurora roles) ──
51
- export const NEON_CYAN = CYAN
52
- export const HOT_PINK = ROSE
53
- export const ELECTRIC_PURPLE = IRIS
54
- export const VIVID_MAGENTA = MAGENTA
55
- export const LIME = MINT
56
- export const ORANGE = AMBER
57
- export const CORAL = IRIS
58
- export const PEACH = AMBER
59
- export const BRIGHT_WHITE = FG_STRONG
60
- export const SOFT_GRAY = MUTED
61
- export const DARK_GRAY = LINE
62
- export const DEEP_BLUE = COBALT
63
- export const RED = ROSE
64
- export const GREEN = MINT
65
- export const YELLOW = AMBER
66
- export const BLUE = COBALT
67
- export const GRAY = MUTED
68
-
69
- // ─── Background colors ──────────────────────────────────
70
- export const BG_DARK = paintBg('#10121C', 234) // Status bar background
71
- export const BG_SECTION = paintBg('#141726', 235) // Section background
72
- export const BG_RED = paintBg('#3A1A24', 52) // Diff removed
73
- export const BG_GREEN = paintBg('#123026', 22) // Diff added
74
- export const BG_HIGHLIGHT = paintBg('#161A28', 236) // Highlighted lines
75
- export const BG_HEADER = paintBg('#0E1017', 234) // Header background
76
-
77
- const out = s => process.stdout.write(s)
78
-
79
- // ─── Terminal utilities ─────────────────────────────────
80
-
81
- export function termWidth() {
82
- return process.stdout.columns || 80
83
- }
84
-
85
- export function stripAnsi(text) {
86
- return String(text).replace(/\x1b\[[0-?]*[ -/]*[@-~]/g, '')
87
- }
88
-
89
- /** Section header: a left-aligned label on a colored rule. */
90
- export function sectionHeader(title) {
91
- const w = termWidth() - 4
92
- const rightPad = Math.max(1, w - title.length - 4)
93
- return ` ${CYAN}──${RST} ${BOLD}${FG_STRONG}${title}${RST} ${LINE}${'─'.repeat(rightPad)}${RST}`
94
- }
95
-
96
- /** A credit meter: filled vs empty blocks, amber when healthy, rose when low. */
97
- export function creditMeter(available, balance, { width = 24, low = false } = {}) {
98
- const ratio = balance > 0 ? Math.max(0, Math.min(1, available / balance)) : 0
99
- const filled = available > 0 ? Math.max(1, Math.round(ratio * width)) : 0
100
- const color = low ? ROSE : AMBER
101
- return `${color}${'▰'.repeat(filled)}${LINE}${'▱'.repeat(Math.max(0, width - filled))}${RST}`
102
- }
103
-
104
- const TIER_META = {
105
- raw: { color: MAGENTA, icon: '◆', label: 'RAW' },
106
- ultra: { color: GOLD, icon: '✦', label: 'ULTRA' },
107
- pro: { color: MINT, icon: '▲', label: 'PRO' },
108
- paid: { color: MINT, icon: '▲', label: 'PAID' },
109
- standard: { color: CYAN, icon: '⚡', label: 'STD' },
110
- free: { color: MUTED, icon: '○', label: 'FREE' },
111
- }
112
-
113
- /** The colour that stands for an account or model tier. */
114
- export function tierColor(tier) {
115
- return (TIER_META[tier] ?? {}).color ?? CYAN
116
- }
117
-
118
- /** A tier badge, e.g. ◆ RAW, coloured by tier. */
119
- export function tierPill(tier) {
120
- const m = TIER_META[tier] ?? { color: CYAN, icon: '●', label: String(tier || '').toUpperCase() || 'TIER' }
121
- return `${m.color}${BOLD}${m.icon} ${m.label}${RST}`
122
- }
123
-
124
- /** A unicode sparkline from a list of values; highlights the final bar. */
125
- export function sparkline(values, { highlightLast = true } = {}) {
126
- const bars = '▁▂▃▄▅▆▇█'
127
- if (!values.length) return ''
128
- const max = Math.max(...values, 1)
129
- return values.map((v, i) => {
130
- const idx = v <= 0 ? 0 : Math.max(1, Math.min(bars.length - 1, Math.round((v / max) * (bars.length - 1))))
131
- const ch = bars[idx]
132
- if (highlightLast && i === values.length - 1) return `${AMBER}${BOLD}${ch}${RST}`
133
- return `${CYAN}${ch}${RST}`
134
- }).join('')
135
- }
136
-
137
- /** Compact status bar: colored segments on a dark background filling the terminal width. */
138
- export function statusBar(segments) {
139
- const w = termWidth()
140
- const parts = segments.map(([label, value, color]) =>
141
- `${SOFT_GRAY}${label}${label ? ' ' : ''}${color ?? BRIGHT_WHITE}${BOLD}${value}${RST}`
142
- )
143
- const joined = parts.join(` ${DARK_GRAY}│${RST} `)
144
- const bare = stripAnsi(joined).length
145
- const rightPad = Math.max(0, w - bare - 2)
146
- return `${BG_DARK} ${joined}${' '.repeat(rightPad)} ${RST}`
147
- }
148
-
149
- /** Apply a gradient across a string using 256-color codes. Spaces are transparent. */
150
- export function gradient(text, colors) {
151
- if (!useColor || !colors.length || !text.length) return text
152
- const chars = [...text].filter(ch => ch !== ' ').length
153
- if (!chars) return text
154
- let ci = 0
155
- return [...text].map(ch => {
156
- if (ch === ' ') return ch
157
- const idx = Math.min(Math.floor((ci / chars) * colors.length), colors.length - 1)
158
- ci++
159
- return `${c256(colors[idx])}${ch}`
160
- }).join('') + RST
161
- }
162
-
163
- /** NoGuard brand gradient: cyan → blue → purple → magenta. */
164
- export const NOGUARD_GRADIENT = [51, 45, 39, 33, 69, 105, 141, 135, 171, 207, 201, 200, 199, 198]
165
-
166
- // ─── Markdown stream ────────────────────────────────────
167
-
168
- export class MarkdownStream {
169
- constructor({ marker = `${IRIS}●${RST} `, indent = ' ' } = {}) {
170
- this.marker = marker
171
- this.indent = indent
172
- this.started = false
173
- this.lineStart = true
174
- this.head = ''
175
- this.fence = false
176
- this.fenceLine = false
177
- this.code = false
178
- this.bold = false
179
- this.star = false
180
- this.lineStyle = ''
181
- }
182
-
183
- write(text) {
184
- for (const ch of text) this.#char(ch)
185
- }
186
-
187
- end() {
188
- if (this.lineStart && this.head) this.#decideLine(true)
189
- if (this.star) { this.#emit('*'); this.star = false }
190
- if (this.started) out(`${RST}\n`)
191
- this.started = false
192
- }
193
-
194
- #emit(s) {
195
- if (!this.started) {
196
- this.started = true
197
- out(this.marker)
198
- }
199
- out(s)
200
- }
201
-
202
- #style() {
203
- if (this.fence) return NEON_CYAN
204
- return `${this.lineStyle}${this.bold ? BOLD : ''}${this.code ? VIVID_MAGENTA : ''}`
205
- }
206
-
207
- #char(ch) {
208
- if (ch !== '\n' && ch !== '\t' && /[\x00-\x1f\x7f-\x9f]/.test(ch)) return
209
- if (this.lineStart) {
210
- if (ch === '\n') { this.#decideLine(true); this.#newline(); return }
211
- this.head += ch
212
- if (/^[#`\-*+> \d.]*$/.test(this.head) && this.head.length < 4) return
213
- this.#decideLine(false)
214
- return
215
- }
216
- if (ch === '\n') { this.#newline(); return }
217
- if (this.fenceLine) { this.#emit(ch); return }
218
- this.#inline(ch)
219
- }
220
-
221
- #decideLine(complete) {
222
- const head = this.head
223
- this.head = ''
224
- this.lineStart = false
225
- if (/^\s*```/.test(head) || (complete && /^\s*``$/.test(head))) {
226
- this.fence = !this.fence
227
- this.fenceLine = true
228
- this.#emit(`${DARK_GRAY}${head}`)
229
- return
230
- }
231
- if (this.fence) {
232
- this.fenceLine = true
233
- this.#emit(`${NEON_CYAN}${head}`)
234
- return
235
- }
236
- const heading = head.match(/^(#{1,6}) (.*)$/s)
237
- if (heading) {
238
- this.lineStyle = `${BOLD}${GOLD}`
239
- this.#emit(`${BOLD}${GOLD}`)
240
- for (const ch of heading[2]) this.#inline(ch)
241
- return
242
- }
243
- const bullet = head.match(/^(\s*)[-*+] (.*)$/s)
244
- if (bullet) {
245
- this.#emit(`${bullet[1]}${LIME}•${RST} `)
246
- for (const ch of bullet[2]) this.#inline(ch)
247
- return
248
- }
249
- const quote = head.match(/^> ?(.*)$/s)
250
- if (quote) {
251
- this.lineStyle = LAVENDER
252
- this.#emit(`${ELECTRIC_PURPLE}│${RST} ${LAVENDER}`)
253
- for (const ch of quote[1]) this.#inline(ch)
254
- return
255
- }
256
- for (const ch of head) this.#inline(ch)
257
- }
258
-
259
- #inline(ch) {
260
- if (this.star) {
261
- this.star = false
262
- if (ch === '*' && !this.code) {
263
- this.bold = !this.bold
264
- this.#emit(`${RST}${this.#style()}`)
265
- return
266
- }
267
- this.#emit('*')
268
- }
269
- if (ch === '*' && !this.code) { this.star = true; return }
270
- if (ch === '`') {
271
- this.code = !this.code
272
- this.#emit(`${RST}${this.#style()}`)
273
- return
274
- }
275
- this.#emit(ch)
276
- }
277
-
278
- #newline() {
279
- if (this.star) { this.#emit('*'); this.star = false }
280
- this.code = false
281
- this.bold = false
282
- this.lineStyle = ''
283
- this.fenceLine = false
284
- if (!this.started) { this.lineStart = true; return }
285
- out(`${RST}\n${this.indent}`)
286
- this.lineStart = true
287
- }
288
- }
289
-
290
- // ─── Spinner (color-cycling braille) ────────────────────
291
-
292
- const SPINNER_FRAMES = ['⣾', '⣽', '⣻', '⢿', '⡿', '⣟', '⣯', '⣷']
293
- const SPINNER_COLORS = [51, 45, 39, 33, 63, 99, 135, 171]
294
-
295
- export class Spinner {
296
- constructor() {
297
- this.timer = null
298
- }
299
-
300
- start(label) {
301
- if (!process.stdout.isTTY) return
302
- this.stop()
303
- const began = Date.now()
304
- let frame = 0
305
- const draw = () => {
306
- const secs = Math.floor((Date.now() - began) / 1000)
307
- const color = c256(SPINNER_COLORS[frame % SPINNER_COLORS.length])
308
- out(`\r\x1b[2K${color}${SPINNER_FRAMES[frame++ % SPINNER_FRAMES.length]}${RST} ${BRIGHT_WHITE}${label}${RST} ${SOFT_GRAY}(${secs}s · esc to interrupt)${RST}`)
309
- }
310
- draw()
311
- this.timer = setInterval(draw, 100)
312
- }
313
-
314
- stop() {
315
- if (!this.timer) return
316
- clearInterval(this.timer)
317
- this.timer = null
318
- out('\r\x1b[2K')
319
- }
320
- }
321
-
322
- // ─── Tool output formatting ─────────────────────────────
323
-
324
- /** Strip terminal escapes and control characters so model/program text can't restyle the screen. */
325
- export function clean(text) {
326
- return String(text)
327
- .replace(/\x1b\[[0-?]*[ -/]*[@-~]/g, '')
328
- .replace(/\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)/g, '')
329
- .replace(/[\x00-\x08\x0b-\x1f\x7f-\x9f]/g, '')
330
- }
331
-
332
- export function toolHeader(name, arg) {
333
- const shown = arg ? clean(arg).replace(/\n/g, ' ⏎ ') : ''
334
- return `${LIME}▸${RST} ${BOLD}${LIME}${clean(name)}${RST}${shown ? ` ${SKY}${shown}${RST}` : ''}`
335
- }
336
-
337
- export function toolResultLine(text, color = '') {
338
- const lines = String(text).split('\n')
339
- return lines.map((line, i) => `${i === 0 ? ` ${DARK_GRAY}⎿${RST} ` : ' '}${color}${line}${color ? RST : ''}`).join('\n')
340
- }
341
-
342
- // ─── Diff rendering ─────────────────────────────────────
343
-
344
- /** Line-level edit operations from `before` to `after`: [' ' | '-' | '+', line]. */
345
- export function diffLines(before, after) {
346
- const a = before.split('\n')
347
- const b = after.split('\n')
348
- let ops
349
- if (a.length * b.length > 250_000) {
350
- ops = [...a.map(line => ['-', line]), ...b.map(line => ['+', line])]
351
- } else {
352
- const dp = Array.from({ length: a.length + 1 }, () => new Uint32Array(b.length + 1))
353
- for (let i = a.length - 1; i >= 0; i--)
354
- for (let j = b.length - 1; j >= 0; j--)
355
- dp[i][j] = a[i] === b[j] ? dp[i + 1][j + 1] + 1 : Math.max(dp[i + 1][j], dp[i][j + 1])
356
- ops = []
357
- let i = 0, j = 0
358
- while (i < a.length || j < b.length) {
359
- if (i < a.length && j < b.length && a[i] === b[j]) { ops.push([' ', a[i]]); i++; j++ }
360
- else if (i < a.length && (j >= b.length || dp[i + 1][j] >= dp[i][j + 1])) { ops.push(['-', a[i]]); i++ }
361
- else { ops.push(['+', b[j]]); j++ }
362
- }
363
- }
364
- return ops
365
- }
366
-
367
- /** A line diff with context lines around each changed region. */
368
- export function renderDiff(before, after, firstLine = 1, context = 2, maxLines = 40) {
369
- const ops = diffLines(before, after)
370
- const keep = ops.map(() => false)
371
- ops.forEach(([op], k) => {
372
- if (op === ' ') return
373
- for (let n = Math.max(0, k - context); n <= Math.min(ops.length - 1, k + context); n++) keep[n] = true
374
- })
375
- const lines = []
376
- let oldNo = firstLine, newNo = firstLine, gap = false
377
- for (let k = 0; k < ops.length; k++) {
378
- const [op, text] = ops[k]
379
- if (keep[k]) {
380
- if (gap && lines.length) lines.push(`${DARK_GRAY} ⋮${RST}`)
381
- gap = false
382
- const no = String(op === '-' ? oldNo : newNo).padStart(5)
383
- if (op === '-') lines.push(`${BG_RED}${HOT_PINK}${no} - ${text}${RST}`)
384
- else if (op === '+') lines.push(`${BG_GREEN}${MINT}${no} + ${text}${RST}`)
385
- else lines.push(`${DARK_GRAY}${no} ${text}${RST}`)
386
- } else gap = true
387
- if (op !== '+') oldNo++
388
- if (op !== '-') newNo++
389
- }
390
- if (lines.length > maxLines) return [...lines.slice(0, maxLines), `${SOFT_GRAY} … ${lines.length - maxLines} more lines${RST}`].join('\n')
391
- return lines.join('\n')
392
- }
393
-
394
- export function truncateMiddle(text, max) {
395
- if (text.length <= max) return text
396
- const half = Math.floor(max / 2)
397
- return `${text.slice(0, half)}\n\n… [${text.length - max} characters cut] …\n\n${text.slice(-half)}`
398
- }
1
+ // Terminal output: vibrant 256-color palette, streamed markdown, status bars, sections, diffs.
2
+
3
+ const useColor = process.stdout.isTTY && !process.env.NO_COLOR
4
+ const trueColor = useColor && /^(truecolor|24bit)$/i.test(process.env.COLORTERM || '')
5
+ const sgr = code => useColor ? `\x1b[${code}m` : ''
6
+ const c256 = fg => useColor ? `\x1b[38;5;${fg}m` : ''
7
+ const c256bg = bg => useColor ? `\x1b[48;5;${bg}m` : ''
8
+
9
+ /** A role colour: 24-bit where the terminal supports it, nearest 256-colour otherwise, nothing when colour is off. */
10
+ function paint(hex, fallback) {
11
+ if (!useColor) return ''
12
+ if (!trueColor) return `\x1b[38;5;${fallback}m`
13
+ const n = parseInt(hex.slice(1), 16)
14
+ return `\x1b[38;2;${(n >> 16) & 255};${(n >> 8) & 255};${n & 255}m`
15
+ }
16
+ function paintBg(hex, fallback) {
17
+ if (!useColor) return ''
18
+ if (!trueColor) return `\x1b[48;5;${fallback}m`
19
+ const n = parseInt(hex.slice(1), 16)
20
+ return `\x1b[48;2;${(n >> 16) & 255};${(n >> 8) & 255};${n & 255}m`
21
+ }
22
+
23
+ // ─── Core formatting ─────────────────────────────────────
24
+ export const RST = sgr(0)
25
+ export const BOLD = sgr(1)
26
+ export const DIM = sgr(2)
27
+ export const ITALIC = sgr(3)
28
+ export const UNDERLINE = sgr(4)
29
+
30
+ // ─── Aurora palette — seven roles, each with one job ────
31
+ export const IRIS = paint('#9A92FF', 141) // primary — models, headings, the caret
32
+ export const CYAN = paint('#39E0E6', 51) // live edges — prompt, active state
33
+ export const MINT = paint('#45E0A4', 49) // success — tools, confirmations, +diff
34
+ export const AMBER = paint('#FFB65C', 215) // credits — cost, spend, warnings
35
+ export const ROSE = paint('#FF6183', 204) // alert — errors, −diff, low balance, yolo
36
+ export const SKY = paint('#5FC9FF', 81) // paths — files, links, info
37
+ export const MAGENTA = paint('#E36BFF', 177) // raw tier, inline code, the gradient's end
38
+ export const GOLD = paint('#FFC861', 221) // ultra tier, emphasis
39
+ export const COBALT = paint('#6E8BFF', 69) // links, special actions
40
+ export const LAVENDER = paint('#B9B2FF', 183) // blockquotes, metadata
41
+
42
+ // ─── Neutrals (the onyx world) ──────────────────────────
43
+ export const FG_STRONG = paint('#F7F9FD', 231) // primary emphasis
44
+ export const FG = paint('#E8EBF4', 255) // body text
45
+ export const DIMFG = paint('#9BA2B8', 247) // secondary text
46
+ export const MUTED = paint('#6C7389', 244) // labels
47
+ export const FAINT = paint('#495069', 240) // subtle marks
48
+ export const LINE = paint('#39405A', 238) // borders, separators
49
+
50
+ // ─── Backward-compatible aliases (old names → Aurora roles) ──
51
+ export const NEON_CYAN = CYAN
52
+ export const HOT_PINK = ROSE
53
+ export const ELECTRIC_PURPLE = IRIS
54
+ export const VIVID_MAGENTA = MAGENTA
55
+ export const LIME = MINT
56
+ export const ORANGE = AMBER
57
+ export const CORAL = IRIS
58
+ export const PEACH = AMBER
59
+ export const BRIGHT_WHITE = FG_STRONG
60
+ export const SOFT_GRAY = MUTED
61
+ export const DARK_GRAY = LINE
62
+ export const DEEP_BLUE = COBALT
63
+ export const RED = ROSE
64
+ export const GREEN = MINT
65
+ export const YELLOW = AMBER
66
+ export const BLUE = COBALT
67
+ export const GRAY = MUTED
68
+
69
+ // ─── Background colors ──────────────────────────────────
70
+ export const BG_DARK = paintBg('#10121C', 234) // Status bar background
71
+ export const BG_SECTION = paintBg('#141726', 235) // Section background
72
+ export const BG_RED = paintBg('#3A1A24', 52) // Diff removed
73
+ export const BG_GREEN = paintBg('#123026', 22) // Diff added
74
+ export const BG_HIGHLIGHT = paintBg('#161A28', 236) // Highlighted lines
75
+ export const BG_HEADER = paintBg('#0E1017', 234) // Header background
76
+
77
+ const out = s => process.stdout.write(s)
78
+
79
+ // ─── Terminal utilities ─────────────────────────────────
80
+
81
+ export function termWidth() {
82
+ return process.stdout.columns || 80
83
+ }
84
+
85
+ export function stripAnsi(text) {
86
+ return String(text).replace(/\x1b\[[0-?]*[ -/]*[@-~]/g, '')
87
+ }
88
+
89
+ /** Section header: a left-aligned label on a colored rule. */
90
+ export function sectionHeader(title) {
91
+ const w = termWidth() - 4
92
+ const rightPad = Math.max(1, w - title.length - 4)
93
+ return ` ${CYAN}──${RST} ${BOLD}${FG_STRONG}${title}${RST} ${LINE}${'─'.repeat(rightPad)}${RST}`
94
+ }
95
+
96
+ /** A credit meter: filled vs empty blocks, amber when healthy, rose when low. */
97
+ export function creditMeter(available, balance, { width = 24, low = false } = {}) {
98
+ const ratio = balance > 0 ? Math.max(0, Math.min(1, available / balance)) : 0
99
+ const filled = available > 0 ? Math.max(1, Math.round(ratio * width)) : 0
100
+ const color = low ? ROSE : AMBER
101
+ return `${color}${'▰'.repeat(filled)}${LINE}${'▱'.repeat(Math.max(0, width - filled))}${RST}`
102
+ }
103
+
104
+ const TIER_META = {
105
+ raw: { color: MAGENTA, icon: '◆', label: 'RAW' },
106
+ ultra: { color: GOLD, icon: '✦', label: 'ULTRA' },
107
+ pro: { color: MINT, icon: '▲', label: 'PRO' },
108
+ paid: { color: MINT, icon: '▲', label: 'PAID' },
109
+ standard: { color: CYAN, icon: '⚡', label: 'STD' },
110
+ free: { color: MUTED, icon: '○', label: 'FREE' },
111
+ }
112
+
113
+ /** The colour that stands for an account or model tier. */
114
+ export function tierColor(tier) {
115
+ return (TIER_META[tier] ?? {}).color ?? CYAN
116
+ }
117
+
118
+ /** A tier badge, e.g. ◆ RAW, coloured by tier. */
119
+ export function tierPill(tier) {
120
+ const m = TIER_META[tier] ?? { color: CYAN, icon: '●', label: String(tier || '').toUpperCase() || 'TIER' }
121
+ return `${m.color}${BOLD}${m.icon} ${m.label}${RST}`
122
+ }
123
+
124
+ /** A unicode sparkline from a list of values; highlights the final bar. */
125
+ export function sparkline(values, { highlightLast = true } = {}) {
126
+ const bars = '▁▂▃▄▅▆▇█'
127
+ if (!values.length) return ''
128
+ const max = Math.max(...values, 1)
129
+ return values.map((v, i) => {
130
+ const idx = v <= 0 ? 0 : Math.max(1, Math.min(bars.length - 1, Math.round((v / max) * (bars.length - 1))))
131
+ const ch = bars[idx]
132
+ if (highlightLast && i === values.length - 1) return `${AMBER}${BOLD}${ch}${RST}`
133
+ return `${CYAN}${ch}${RST}`
134
+ }).join('')
135
+ }
136
+
137
+ /** Compact status bar: colored segments on a dark background filling the terminal width. */
138
+ export function statusBar(segments) {
139
+ const w = termWidth()
140
+ const parts = segments.map(([label, value, color]) =>
141
+ `${SOFT_GRAY}${label}${label ? ' ' : ''}${color ?? BRIGHT_WHITE}${BOLD}${value}${RST}`
142
+ )
143
+ const joined = parts.join(` ${DARK_GRAY}│${RST} `)
144
+ const bare = stripAnsi(joined).length
145
+ const rightPad = Math.max(0, w - bare - 2)
146
+ return `${BG_DARK} ${joined}${' '.repeat(rightPad)} ${RST}`
147
+ }
148
+
149
+ /** Apply a gradient across a string using 256-color codes. Spaces are transparent. */
150
+ export function gradient(text, colors) {
151
+ if (!useColor || !colors.length || !text.length) return text
152
+ const chars = [...text].filter(ch => ch !== ' ').length
153
+ if (!chars) return text
154
+ let ci = 0
155
+ return [...text].map(ch => {
156
+ if (ch === ' ') return ch
157
+ const idx = Math.min(Math.floor((ci / chars) * colors.length), colors.length - 1)
158
+ ci++
159
+ return `${c256(colors[idx])}${ch}`
160
+ }).join('') + RST
161
+ }
162
+
163
+ /** NoGuard brand gradient: cyan → blue → purple → magenta. */
164
+ export const NOGUARD_GRADIENT = [51, 45, 39, 33, 69, 105, 141, 135, 171, 207, 201, 200, 199, 198]
165
+
166
+ // ─── Markdown stream ────────────────────────────────────
167
+
168
+ export class MarkdownStream {
169
+ constructor({ marker = `${IRIS}●${RST} `, indent = ' ' } = {}) {
170
+ this.marker = marker
171
+ this.indent = indent
172
+ this.started = false
173
+ this.lineStart = true
174
+ this.head = ''
175
+ this.fence = false
176
+ this.fenceLine = false
177
+ this.code = false
178
+ this.bold = false
179
+ this.star = false
180
+ this.lineStyle = ''
181
+ }
182
+
183
+ write(text) {
184
+ for (const ch of text) this.#char(ch)
185
+ }
186
+
187
+ end() {
188
+ if (this.lineStart && this.head) this.#decideLine(true)
189
+ if (this.star) { this.#emit('*'); this.star = false }
190
+ if (this.started) out(`${RST}\n`)
191
+ this.started = false
192
+ }
193
+
194
+ #emit(s) {
195
+ if (!this.started) {
196
+ this.started = true
197
+ out(this.marker)
198
+ }
199
+ out(s)
200
+ }
201
+
202
+ #style() {
203
+ if (this.fence) return NEON_CYAN
204
+ return `${this.lineStyle}${this.bold ? BOLD : ''}${this.code ? VIVID_MAGENTA : ''}`
205
+ }
206
+
207
+ #char(ch) {
208
+ if (ch !== '\n' && ch !== '\t' && /[\x00-\x1f\x7f-\x9f]/.test(ch)) return
209
+ if (this.lineStart) {
210
+ if (ch === '\n') { this.#decideLine(true); this.#newline(); return }
211
+ this.head += ch
212
+ if (/^[#`\-*+> \d.]*$/.test(this.head) && this.head.length < 4) return
213
+ this.#decideLine(false)
214
+ return
215
+ }
216
+ if (ch === '\n') { this.#newline(); return }
217
+ if (this.fenceLine) { this.#emit(ch); return }
218
+ this.#inline(ch)
219
+ }
220
+
221
+ #decideLine(complete) {
222
+ const head = this.head
223
+ this.head = ''
224
+ this.lineStart = false
225
+ if (/^\s*```/.test(head) || (complete && /^\s*``$/.test(head))) {
226
+ this.fence = !this.fence
227
+ this.fenceLine = true
228
+ this.#emit(`${DARK_GRAY}${head}`)
229
+ return
230
+ }
231
+ if (this.fence) {
232
+ this.fenceLine = true
233
+ this.#emit(`${NEON_CYAN}${head}`)
234
+ return
235
+ }
236
+ const heading = head.match(/^(#{1,6}) (.*)$/s)
237
+ if (heading) {
238
+ this.lineStyle = `${BOLD}${GOLD}`
239
+ this.#emit(`${BOLD}${GOLD}`)
240
+ for (const ch of heading[2]) this.#inline(ch)
241
+ return
242
+ }
243
+ const bullet = head.match(/^(\s*)[-*+] (.*)$/s)
244
+ if (bullet) {
245
+ this.#emit(`${bullet[1]}${LIME}•${RST} `)
246
+ for (const ch of bullet[2]) this.#inline(ch)
247
+ return
248
+ }
249
+ const quote = head.match(/^> ?(.*)$/s)
250
+ if (quote) {
251
+ this.lineStyle = LAVENDER
252
+ this.#emit(`${ELECTRIC_PURPLE}│${RST} ${LAVENDER}`)
253
+ for (const ch of quote[1]) this.#inline(ch)
254
+ return
255
+ }
256
+ for (const ch of head) this.#inline(ch)
257
+ }
258
+
259
+ #inline(ch) {
260
+ if (this.star) {
261
+ this.star = false
262
+ if (ch === '*' && !this.code) {
263
+ this.bold = !this.bold
264
+ this.#emit(`${RST}${this.#style()}`)
265
+ return
266
+ }
267
+ this.#emit('*')
268
+ }
269
+ if (ch === '*' && !this.code) { this.star = true; return }
270
+ if (ch === '`') {
271
+ this.code = !this.code
272
+ this.#emit(`${RST}${this.#style()}`)
273
+ return
274
+ }
275
+ this.#emit(ch)
276
+ }
277
+
278
+ #newline() {
279
+ if (this.star) { this.#emit('*'); this.star = false }
280
+ this.code = false
281
+ this.bold = false
282
+ this.lineStyle = ''
283
+ this.fenceLine = false
284
+ if (!this.started) { this.lineStart = true; return }
285
+ out(`${RST}\n${this.indent}`)
286
+ this.lineStart = true
287
+ }
288
+ }
289
+
290
+ // ─── Spinner (color-cycling braille) ────────────────────
291
+
292
+ const SPINNER_FRAMES = ['⣾', '⣽', '⣻', '⢿', '⡿', '⣟', '⣯', '⣷']
293
+ const SPINNER_COLORS = [51, 45, 39, 33, 63, 99, 135, 171]
294
+
295
+ export class Spinner {
296
+ constructor(output = process.stdout) {
297
+ this.output = output
298
+ this.timer = null
299
+ }
300
+
301
+ start(label) {
302
+ if (!this.output.isTTY) return
303
+ this.stop()
304
+ const began = Date.now()
305
+ let frame = 0
306
+ const draw = () => {
307
+ const secs = Math.floor((Date.now() - began) / 1000)
308
+ const color = c256(SPINNER_COLORS[frame % SPINNER_COLORS.length])
309
+ const interrupt = this.output === process.stderr ? 'Ctrl+C' : 'Esc'
310
+ this.output.write(`\r\x1b[2K${color}${SPINNER_FRAMES[frame++ % SPINNER_FRAMES.length]}${RST} ${BRIGHT_WHITE}${label}${RST} ${SOFT_GRAY}(${secs}s · ${interrupt} to interrupt)${RST}`)
311
+ }
312
+ draw()
313
+ this.timer = setInterval(draw, 100)
314
+ }
315
+
316
+ stop() {
317
+ if (!this.timer) return
318
+ clearInterval(this.timer)
319
+ this.timer = null
320
+ this.output.write('\r\x1b[2K')
321
+ }
322
+ }
323
+
324
+ // ─── Tool output formatting ─────────────────────────────
325
+
326
+ /** Strip terminal escapes and control characters so model/program text can't restyle the screen. */
327
+ export function clean(text) {
328
+ return String(text)
329
+ .replace(/\x1b\[[0-?]*[ -/]*[@-~]/g, '')
330
+ .replace(/\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)/g, '')
331
+ .replace(/[\x00-\x08\x0b-\x1f\x7f-\x9f]/g, '')
332
+ }
333
+
334
+ export function toolHeader(name, arg) {
335
+ const shown = arg ? clean(arg).replace(/\n/g, ' ⏎ ') : ''
336
+ return `${LIME}▸${RST} ${BOLD}${LIME}${clean(name)}${RST}${shown ? ` ${SKY}${shown}${RST}` : ''}`
337
+ }
338
+
339
+ export function toolResultLine(text, color = '') {
340
+ const lines = String(text).split('\n')
341
+ return lines.map((line, i) => `${i === 0 ? ` ${DARK_GRAY}⎿${RST} ` : ' '}${color}${line}${color ? RST : ''}`).join('\n')
342
+ }
343
+
344
+ // ─── Diff rendering ─────────────────────────────────────
345
+
346
+ /** Line-level edit operations from `before` to `after`: [' ' | '-' | '+', line]. */
347
+ export function diffLines(before, after) {
348
+ const a = before.split('\n')
349
+ const b = after.split('\n')
350
+ let ops
351
+ if (a.length * b.length > 250_000) {
352
+ ops = [...a.map(line => ['-', line]), ...b.map(line => ['+', line])]
353
+ } else {
354
+ const dp = Array.from({ length: a.length + 1 }, () => new Uint32Array(b.length + 1))
355
+ for (let i = a.length - 1; i >= 0; i--)
356
+ for (let j = b.length - 1; j >= 0; j--)
357
+ dp[i][j] = a[i] === b[j] ? dp[i + 1][j + 1] + 1 : Math.max(dp[i + 1][j], dp[i][j + 1])
358
+ ops = []
359
+ let i = 0, j = 0
360
+ while (i < a.length || j < b.length) {
361
+ if (i < a.length && j < b.length && a[i] === b[j]) { ops.push([' ', a[i]]); i++; j++ }
362
+ else if (i < a.length && (j >= b.length || dp[i + 1][j] >= dp[i][j + 1])) { ops.push(['-', a[i]]); i++ }
363
+ else { ops.push(['+', b[j]]); j++ }
364
+ }
365
+ }
366
+ return ops
367
+ }
368
+
369
+ /** A line diff with context lines around each changed region. */
370
+ export function renderDiff(before, after, firstLine = 1, context = 2, maxLines = 40) {
371
+ const ops = diffLines(before, after)
372
+ const keep = ops.map(() => false)
373
+ ops.forEach(([op], k) => {
374
+ if (op === ' ') return
375
+ for (let n = Math.max(0, k - context); n <= Math.min(ops.length - 1, k + context); n++) keep[n] = true
376
+ })
377
+ const lines = []
378
+ let oldNo = firstLine, newNo = firstLine, gap = false
379
+ for (let k = 0; k < ops.length; k++) {
380
+ const [op, text] = ops[k]
381
+ if (keep[k]) {
382
+ if (gap && lines.length) lines.push(`${DARK_GRAY} ⋮${RST}`)
383
+ gap = false
384
+ const no = String(op === '-' ? oldNo : newNo).padStart(5)
385
+ if (op === '-') lines.push(`${BG_RED}${HOT_PINK}${no} - ${text}${RST}`)
386
+ else if (op === '+') lines.push(`${BG_GREEN}${MINT}${no} + ${text}${RST}`)
387
+ else lines.push(`${DARK_GRAY}${no} ${text}${RST}`)
388
+ } else gap = true
389
+ if (op !== '+') oldNo++
390
+ if (op !== '-') newNo++
391
+ }
392
+ if (lines.length > maxLines) return [...lines.slice(0, maxLines), `${SOFT_GRAY} … ${lines.length - maxLines} more lines${RST}`].join('\n')
393
+ return lines.join('\n')
394
+ }
395
+
396
+ export function truncateMiddle(text, max) {
397
+ if (text.length <= max) return text
398
+ const half = Math.floor(max / 2)
399
+ return `${text.slice(0, half)}\n\n… [${text.length - max} characters cut] …\n\n${text.slice(-half)}`
400
+ }