noguard 1.1.0 → 1.2.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.
@@ -0,0 +1,305 @@
1
+ import { createHash, randomUUID } from 'node:crypto'
2
+ import { mkdir, readFile, writeFile } from 'node:fs/promises'
3
+ import { dirname, resolve } from 'node:path'
4
+ import { fileURLToPath } from 'node:url'
5
+ import { isDeepStrictEqual } from 'node:util'
6
+ import { get, post, streamMessages } from './api.mjs'
7
+ import { getEndpoint, getToken } from './config.mjs'
8
+
9
+ const ROOT = fileURLToPath(new URL('../../', import.meta.url))
10
+ const DEFAULT_DIR = resolve(ROOT, 'server/personas/candidates/opus-4-8')
11
+ const CHECK_TYPES = new Set(['json_equal', 'json_fields', 'contains', 'not_contains', 'word_limit'])
12
+ const hash = text => createHash('sha256').update(text).digest('hex')
13
+
14
+ export function safeEndpoint(value) {
15
+ try { const url = new URL(value); return `${url.protocol}//${url.host}${url.pathname}`.replace(/\/$/, '') }
16
+ catch { return '(invalid endpoint)' }
17
+ }
18
+
19
+ function positive(value, label, max = Number.MAX_SAFE_INTEGER) {
20
+ const n = Number(value)
21
+ if (!Number.isSafeInteger(n) || n < 1 || n > max) throw new Error(`${label} must be an integer from 1 to ${max}.`)
22
+ return n
23
+ }
24
+
25
+ function subset(actual, expected) {
26
+ if (!expected || typeof expected !== 'object' || Array.isArray(expected)) return isDeepStrictEqual(actual, expected)
27
+ return actual !== null && typeof actual === 'object' && Object.entries(expected).every(([key, value]) => Object.hasOwn(actual, key) && subset(actual[key], value))
28
+ }
29
+
30
+ /** JSON checks require the whole answer to be JSON; fenced prose does not pass. */
31
+ export function evaluateCheck(response, check) {
32
+ if (!CHECK_TYPES.has(check.type)) throw new Error(`Unknown check type: ${check.type}`)
33
+ let passed = false, actual
34
+ if (check.type === 'json_equal' || check.type === 'json_fields') {
35
+ try {
36
+ actual = JSON.parse(response.trim())
37
+ passed = check.type === 'json_equal' ? isDeepStrictEqual(actual, check.value) : subset(actual, check.value)
38
+ } catch { actual = 'invalid_json' }
39
+ } else if (check.type === 'word_limit') {
40
+ actual = response.trim() ? response.trim().split(/\s+/u).length : 0
41
+ passed = actual <= check.max
42
+ } else {
43
+ actual = response.toLowerCase().includes(check.value.toLowerCase())
44
+ passed = check.type === 'contains' ? actual : !actual
45
+ }
46
+ return { ...check, passed, actual }
47
+ }
48
+
49
+ export async function loadEvaluation(options) {
50
+ const manifestPath = resolve(options.manifest ?? resolve(DEFAULT_DIR, 'manifest.json'))
51
+ const suitePath = resolve(options.suite ?? resolve(DEFAULT_DIR, 'evaluation/suite-v1.json'))
52
+ const [manifestRaw, suiteRaw] = await Promise.all([readFile(manifestPath, 'utf8'), readFile(suitePath, 'utf8')])
53
+ const manifest = JSON.parse(manifestRaw), suite = JSON.parse(suiteRaw)
54
+ if (manifest.version !== 1 || suite.version !== 1) throw new Error('Manifest and suite must have version 1.')
55
+ if (manifest.model !== 'noguard-ultra' || manifest.expected_model !== 'noguard-ultra') throw new Error('This evaluator requires the noguard-ultra route for Opus 4.8.')
56
+ if (!Array.isArray(manifest.personas) || !manifest.personas.length || !Array.isArray(suite.cases) || !suite.cases.length) throw new Error('Manifest personas and suite cases must be nonempty arrays.')
57
+ positive(suite.max_tokens, 'suite.max_tokens', 64000)
58
+ const ids = new Set()
59
+ for (const persona of manifest.personas) {
60
+ if (!persona.id || ids.has(persona.id) || !persona.file || !persona.greeting || !persona.response) throw new Error('Each persona needs a unique id, file, greeting and response.')
61
+ ids.add(persona.id)
62
+ }
63
+ const requested = options.persona ? options.persona.split(',').map(id => id.trim()).filter(Boolean) : [...ids]
64
+ if (!requested.length || requested.some(id => !ids.has(id))) throw new Error('Unknown or empty --persona selection.')
65
+ const personas = []
66
+ for (const persona of manifest.personas.filter(p => requested.includes(p.id))) {
67
+ const text = await readFile(resolve(dirname(manifestPath), persona.file), 'utf8')
68
+ if (!text.trim()) throw new Error(`Persona ${persona.id} is empty.`)
69
+ personas.push({ ...persona, text, sha256: hash(text) })
70
+ }
71
+ const caseIds = new Set()
72
+ for (const item of suite.cases) {
73
+ if (!item.id || caseIds.has(item.id) || !item.category || !Array.isArray(item.turns) || !item.turns.length) throw new Error('Each case needs a unique id, category and nonempty turns.')
74
+ caseIds.add(item.id)
75
+ for (const turn of item.turns) {
76
+ if (typeof turn.prompt !== 'string' || !turn.prompt.trim() || !Array.isArray(turn.checks)) throw new Error(`Invalid turn in ${item.id}.`)
77
+ for (const check of turn.checks) {
78
+ if (!CHECK_TYPES.has(check.type)) throw new Error(`Unknown check type: ${check.type}`)
79
+ if (['contains', 'not_contains'].includes(check.type) && (typeof check.value !== 'string' || !check.value)) throw new Error('Text checks need a nonempty value.')
80
+ if (check.type === 'word_limit') positive(check.max, 'word_limit.max')
81
+ }
82
+ }
83
+ }
84
+ return { manifest, suite, personas, hashes: { manifest: hash(manifestRaw), suite: hash(suiteRaw) }, sources: { manifest: manifestRaw, suite: suiteRaw }, paths: { manifest: manifestPath, suite: suitePath } }
85
+ }
86
+
87
+ /** Preserve the loaded inputs before the first network request, including primer text. */
88
+ export async function writeInputSnapshot(plan, out) {
89
+ const snapshot = { version: 1, manifest: plan.manifest, suite: plan.suite, selected_personas: plan.personas, hashes: plan.hashes, original_json: plan.sources ?? null }
90
+ const serialized = `${JSON.stringify(snapshot, null, 2)}\n`
91
+ await mkdir(out, { recursive: true })
92
+ await writeFile(resolve(out, 'request-snapshot.json'), serialized)
93
+ return { file: 'request-snapshot.json', sha256: hash(serialized) }
94
+ }
95
+
96
+ function replyCounts(report) {
97
+ const replies = report.results.flatMap(item => item.turns).filter(turn => turn.credits)
98
+ const metered = replies.filter(turn => turn.receipt?.request_id)
99
+ return { gateway_replies: replies.length, metered_receipts: metered.length, gateway_shortcuts_or_unattested: replies.length - metered.length }
100
+ }
101
+
102
+ function failure(code, message) { return Object.assign(new Error(message), { code }) }
103
+
104
+ function errorRecord(error) {
105
+ // Provider errors can contain request URLs or secrets; report stable codes only.
106
+ return { code: String(error.code ?? error.name ?? 'request_error'), status: Number.isInteger(error.status) ? error.status : null }
107
+ }
108
+
109
+ async function timedCall(timeout, callback) {
110
+ const controller = new AbortController()
111
+ const timer = setTimeout(() => controller.abort(), timeout)
112
+ try { return await callback(controller.signal) }
113
+ finally { clearTimeout(timer); controller.abort() }
114
+ }
115
+
116
+ export async function collectReply(body, record, deps, timeout) {
117
+ const blocks = new Map()
118
+ let ended = false, receipt = false, started = false
119
+ const before = Date.now()
120
+ try {
121
+ await timedCall(timeout, async signal => {
122
+ for await (const event of deps.stream(body, { signal })) {
123
+ const data = event.data
124
+ const type = data?.type || event.event
125
+ if (type === 'message_start') {
126
+ started = true
127
+ record.model = data.message?.model ?? null
128
+ record.usage = { ...(data.message?.usage ?? {}) }
129
+ if (record.model !== deps.expectedModel) throw failure('wrong_model', 'Gateway returned a different model route.')
130
+ } else if (type === 'content_block_start') {
131
+ if (data.content_block?.type !== 'text') throw failure('unexpected_content', 'Only text responses are supported.')
132
+ blocks.set(data.index, data.content_block.text ?? '')
133
+ } else if (type === 'content_block_delta' && data.delta?.type === 'text_delta') {
134
+ blocks.set(data.index, (blocks.get(data.index) ?? '') + data.delta.text)
135
+ } else if (type === 'message_delta') {
136
+ record.stop_reason = data.delta?.stop_reason ?? record.stop_reason
137
+ record.usage = { ...record.usage, ...data.usage }
138
+ } else if (type === 'noguard_credits') {
139
+ if (!Number.isSafeInteger(data.spent) || data.spent < 0 || !Number.isSafeInteger(data.balance)) throw failure('invalid_receipt', 'Invalid credit receipt.')
140
+ if (receipt) throw failure('duplicate_receipt', 'Duplicate credit receipt.')
141
+ receipt = true
142
+ record.credits = { spent: data.spent, balance: data.balance }
143
+ record.receipt = Object.fromEntries(['type', 'spent', 'balance', 'available', 'revision', 'client_request_id', 'request_id', 'status', 'model', 'estimated'].filter(key => Object.hasOwn(data, key)).map(key => [key, data[key]]))
144
+ record.response_origin = data.request_id ? 'metered_gateway_reply' : 'gateway_shortcut_or_unattested'
145
+ if (data.model && data.model !== deps.expectedModel) throw failure('wrong_receipt_model', 'Credit receipt identifies a different model route.')
146
+ } else if (type === 'message_stop') ended = true
147
+ else if (type === 'error') throw failure('stream_error', 'Gateway reported a stream error.')
148
+ }
149
+ })
150
+ if (!started || !ended || !receipt || !record.stop_reason) throw failure('incomplete_stream', 'Missing start, stop, stop reason or credit receipt.')
151
+ if (record.stop_reason === 'max_tokens') throw failure('truncated', 'Response reached the token limit.')
152
+ if (record.stop_reason !== 'end_turn' && record.stop_reason !== 'refusal') throw failure('unexpected_stop', 'Unexpected stop reason.')
153
+ } finally {
154
+ record.duration_ms = Date.now() - before
155
+ record.response = [...blocks.entries()].sort(([a], [b]) => a - b).map(([, text]) => text).join('')
156
+ record.response_sha256 = hash(record.response)
157
+ }
158
+ }
159
+
160
+ /** Dependencies are injectable so transport and credit failures can be tested without inference. */
161
+ export async function runEvaluation(plan, options = {}, injected = {}) {
162
+ const deps = { get, post, stream: streamMessages, endpoint: getEndpoint(), ...injected, expectedModel: plan.manifest.expected_model }
163
+ const maxCredits = positive(options.maxCredits ?? 400, '--max-credits')
164
+ const repeat = positive(options.repeat ?? 1, '--repeat', 10)
165
+ const timeout = positive(options.timeoutMs ?? 90000, '--timeout-ms', 600000)
166
+ const report = {
167
+ version: 1, run_id: options.runId ?? randomUUID(), started_at: new Date().toISOString(), suite_id: plan.suite.id,
168
+ endpoint: safeEndpoint(deps.endpoint), model: plan.manifest.model, expected_model: plan.manifest.expected_model,
169
+ identity_scope: 'The gateway public route alias is checked. This does not independently attest provider weights or model identity.',
170
+ hashes: plan.hashes, ...(options.inputSnapshot ? { input_snapshot: options.inputSnapshot } : {}), settings: { max_tokens: plan.suite.max_tokens, repeat, max_credits: maxCredits, timeout_ms: timeout, effort: 'high', tools: false, libraries: [], quote_reservation_multiplier: 1.25, quote_reservation_extra_credits: 1 },
171
+ budget_policy: 'Before each call, settled spend plus ceil(quote.max_credits * 1.25) + 1 must fit the ceiling. The 25% plus 1 credit allowance covers some token estimation and cache-write pricing uplift; it is not a guaranteed maximum. Quotes and reservations are estimates, not an atomic billing cap; pricing changes or unreported settlement after disconnect can also exceed estimates. No automatic retries.',
172
+ response_origin_scope: 'A request_id identifies a metered gateway reply, not independent proof of provider completion. Replies without it are gateway shortcuts or unattested; answer checks still run, but these replies must not be attributed to the provider or persona alone. The existing baseline enables gateway persona guards while custom drafts opt out.',
173
+ personas: plan.personas.map(({ id, name, sha256 }) => ({ id, name, sha256 })),
174
+ status: options.dryRun ? 'dry_run' : 'running', spent_credits: 0, results: [], transport_errors: [], counts: { gateway_replies: 0, metered_receipts: 0, gateway_shortcuts_or_unattested: 0 },
175
+ }
176
+ const variants = [...(options.baseline ? [{ id: 'baseline', name: 'Existing server persona', baseline: true }] : []), ...plan.personas]
177
+ report.planned_requests = variants.length * repeat * plan.suite.cases.reduce((sum, item) => sum + item.turns.length, 0)
178
+ if (options.dryRun) return report
179
+ try {
180
+ const models = await timedCall(timeout, signal => deps.get('/api/v1/models', { signal }))
181
+ const model = models.data?.find(item => item.id === plan.manifest.model)
182
+ if (!model || model.chat_eligible === false) throw failure('model_unavailable', 'Requested model route is unavailable.')
183
+ if (model.max_output_tokens < plan.suite.max_tokens) throw failure('output_limit', 'Suite exceeds model output limit.')
184
+ const account = await timedCall(timeout, signal => deps.get('/api/v1/me', { signal }))
185
+ if (!account.verified || (model.requires_purchase && account.tier !== 'paid')) throw failure('account_ineligible', 'Account is not eligible for this model.')
186
+ if (!Number.isFinite(account.available) || account.available < 1) throw failure('out_of_credits', 'No available credits.')
187
+ report.preflight = { model_available: true, account_eligible: true, available_credits: account.available }
188
+ if (options.baseline) {
189
+ const identity = await timedCall(timeout, signal => deps.get('/api/v1/persona', { signal }))
190
+ if (typeof identity.hash !== 'string' || !/^[a-f\d]{16,64}$/i.test(identity.hash)) throw failure('baseline_hash_unavailable', 'Server did not return a valid baseline persona hash.')
191
+ report.preflight.baseline_persona_hash = identity.hash
192
+ report.preflight.baseline_hash_scope = 'Server default persona hash from /api/v1/persona; this endpoint does not independently attest per-model persona routing.'
193
+ }
194
+ await options.onCheckpoint?.(report)
195
+ for (const variant of variants) {
196
+ for (let iteration = 1; iteration <= repeat; iteration++) {
197
+ for (const item of plan.suite.cases) {
198
+ const messages = variant.baseline ? [] : [
199
+ { role: 'user', content: `${variant.text}\n\n${variant.greeting}` },
200
+ { role: 'assistant', content: variant.response },
201
+ ]
202
+ const result = { persona: variant.id, repeat: iteration, case_id: item.id, category: item.category, hard_gate: item.hard_gate === true, manual_review: item.manual_review ? 'pending' : 'not_required', status: 'running', turns: [] }
203
+ report.results.push(result)
204
+ for (const [index, turn] of item.turns.entries()) {
205
+ messages.push({ role: 'user', content: turn.prompt })
206
+ const record = { turn: index + 1, prompt: turn.prompt, prompt_sha256: hash(turn.prompt), request_sha256: hash(JSON.stringify(messages)), status: 'pending' }
207
+ result.turns.push(record)
208
+ let credited = false
209
+ try {
210
+ const quote = await timedCall(timeout, signal => deps.post('/api/v1/quote', {
211
+ model: plan.manifest.model, input_characters: JSON.stringify(messages).length, max_tokens: plan.suite.max_tokens, mode: 'chat',
212
+ }, { signal }))
213
+ record.quote = { max_credits: quote.max_credits, max_output_tokens: quote.max_output_tokens, pricing_version: quote.pricing_version }
214
+ if (quote.model !== plan.manifest.expected_model) throw failure('wrong_quote_model', 'Quote selected a different model route.')
215
+ if (!quote.eligible || quote.max_output_tokens < plan.suite.max_tokens) throw failure('quote_ineligible', 'Insufficient credits for the complete suite output budget.')
216
+ if (!Number.isSafeInteger(quote.max_credits) || quote.max_credits < 1) throw failure('invalid_quote', 'Quote has no valid credit ceiling.')
217
+ record.reserved_credits = Math.ceil(quote.max_credits * 1.25) + 1
218
+ if (report.spent_credits + record.reserved_credits > maxCredits) throw failure('credit_ceiling', 'Next call reservation exceeds the configured credit ceiling.')
219
+ const body = { model: plan.manifest.model, max_tokens: plan.suite.max_tokens, effort: 'high', messages: structuredClone(messages), noguard_persona: Boolean(variant.baseline), metadata: { conversation_id: `persona-eval:${report.run_id}:${variant.id}:${iteration}:${item.id}` } }
220
+ await collectReply(body, record, deps, timeout)
221
+ report.spent_credits += record.credits.spent
222
+ credited = true
223
+ if (report.spent_credits > maxCredits) throw failure('credit_ceiling_exceeded', 'Actual settlement exceeded the configured ceiling.')
224
+ record.checks = turn.checks.map(check => evaluateCheck(record.response, check))
225
+ record.status = record.checks.every(check => check.passed) ? 'passed' : 'failed'
226
+ messages.push({ role: 'assistant', content: record.response })
227
+ if (index === item.turns.length - 1) result.status = result.turns.some(turn => turn.status === 'failed') ? 'failed' : item.manual_review ? 'review_pending' : 'passed'
228
+ report.counts = replyCounts(report)
229
+ options.onProgress?.({ persona: variant.id, repeat: iteration, case_id: item.id, turn: index + 1, status: record.status, spent_credits: report.spent_credits })
230
+ await options.onCheckpoint?.(report)
231
+ } catch (error) {
232
+ // A failed stream can still include a settled receipt; include it once.
233
+ if (!credited && record.credits) report.spent_credits += record.credits.spent
234
+ record.status = 'transport_error'
235
+ record.error = errorRecord(error)
236
+ result.status = 'transport_error'
237
+ report.transport_errors.push({ persona: variant.id, case_id: item.id, turn: index + 1, ...record.error })
238
+ throw error
239
+ }
240
+ }
241
+ result.status = result.turns.some(turn => turn.status === 'failed') ? 'failed' : item.manual_review ? 'review_pending' : 'passed'
242
+ }
243
+ }
244
+ }
245
+ report.status = report.results.some(result => result.status === 'failed') ? 'failed' : report.results.some(result => result.status === 'review_pending') ? 'review_pending' : 'passed'
246
+ } catch (error) {
247
+ report.status = 'stopped'
248
+ report.error = errorRecord(error)
249
+ }
250
+ report.counts = replyCounts(report)
251
+ report.finished_at = new Date().toISOString()
252
+ await options.onCheckpoint?.(report)
253
+ return report
254
+ }
255
+
256
+ export function renderReport(report) {
257
+ const counts = replyCounts(report)
258
+ const lines = [
259
+ '# Persona evaluation', '',
260
+ `Run: ${report.run_id} `, `Status: **${report.status}** `, `Route: ${report.model} `,
261
+ `Credits settled: ${report.spent_credits} / ${report.settings.max_credits} `,
262
+ `Gateway replies / metered receipts / shortcuts or unattested: ${counts.gateway_replies} / ${counts.metered_receipts} / ${counts.gateway_shortcuts_or_unattested} `,
263
+ `Turns attempted/planned: ${report.results.flatMap(item => item.turns).length} / ${report.planned_requests}`, '',
264
+ report.identity_scope, '', report.response_origin_scope ?? 'Gateway replies and provider completions are distinct; check request receipts and provider evidence before attributing results.', '', report.budget_policy, '',
265
+ '| Persona | Repeat | Case | Automatic checks | Manual review |', '| --- | --- | --- | --- | --- |',
266
+ ]
267
+ for (const result of report.results) {
268
+ const checks = result.turns.flatMap(turn => turn.checks ?? [])
269
+ lines.push(`| ${result.persona} | ${result.repeat} | ${result.case_id} | ${result.status}: ${checks.filter(check => check.passed).length}/${checks.length} | ${result.manual_review} |`)
270
+ }
271
+ if (report.error) lines.push('', `Stopped: ${report.error.code}.`)
272
+ lines.push('', 'Manual review remains pending until a human assesses correctness, technical usefulness, voice, and appropriate boundaries. Automated checks do not establish a full quality pass.', '', `Manifest SHA256: ${report.hashes.manifest} `, `Suite SHA256: ${report.hashes.suite}`, '', 'Full responses, checks, timings, usage, hashes and credit receipts are in report.json.', '')
273
+ return lines.join('\n')
274
+ }
275
+
276
+ export async function main(args) {
277
+ if (args.includes('--help') || args.includes('-h')) {
278
+ console.log('Usage: noguard eval-personas [--manifest PATH] [--suite PATH] [--out DIR] [--persona ID,ID] [--baseline] [--repeat 1] [--max-credits 400] [--timeout-ms 90000] [--dry-run]\n\nRuns sequential, tool-free tests through the configured NoGuard gateway. Drafts use noguard_persona:false; --baseline also tests the existing server persona. --dry-run reads and validates inputs without network access. Quotes guard the budget but do not provide an atomic billing cap. Reports omit account identity and credentials.')
279
+ return
280
+ }
281
+ const options = {}
282
+ const valueFlags = { '--manifest': 'manifest', '--suite': 'suite', '--out': 'out', '--persona': 'persona', '--repeat': 'repeat', '--max-credits': 'maxCredits', '--timeout-ms': 'timeoutMs' }
283
+ for (let index = 0; index < args.length; index++) {
284
+ const arg = args[index]
285
+ if (arg === '--baseline') options.baseline = true
286
+ else if (arg === '--dry-run') options.dryRun = true
287
+ else if (valueFlags[arg]) {
288
+ if (!args[index + 1] || args[index + 1].startsWith('--')) throw new Error(`Missing value for ${arg}.`)
289
+ options[valueFlags[arg]] = args[++index]
290
+ } else throw new Error(`Unknown eval-personas option: ${arg}`)
291
+ }
292
+ const plan = await loadEvaluation(options)
293
+ if (!options.dryRun && !getToken()) throw new Error('Sign in with noguard login or set NOGUARD_TOKEN before evaluating.')
294
+ options.runId = randomUUID()
295
+ const out = resolve(options.out ?? resolve(ROOT, 'output/persona-eval', options.runId))
296
+ await mkdir(out, { recursive: true })
297
+ options.inputSnapshot = await writeInputSnapshot(plan, out)
298
+ options.onProgress = item => console.log(`${item.persona}/${item.case_id} turn ${item.turn} (repeat ${item.repeat}): ${item.status}, settled ${item.spent_credits} credits.`)
299
+ options.onCheckpoint = report => writeFile(resolve(out, 'report.json'), `${JSON.stringify(report, null, 2)}\n`)
300
+ const report = await runEvaluation(plan, options)
301
+ await options.onCheckpoint(report)
302
+ await writeFile(resolve(out, 'report.md'), renderReport(report))
303
+ console.log(`Persona evaluation ${report.status}; ${report.spent_credits} settled credits. Reports: ${out}`)
304
+ if (report.status === 'failed' || report.status === 'stopped') process.exitCode = 1
305
+ }
package/lib/render.mjs CHANGED
@@ -1,31 +1,172 @@
1
- // Terminal output: colors, streamed markdown, the spinner and edit diffs.
1
+ // Terminal output: vibrant 256-color palette, streamed markdown, status bars, sections, diffs.
2
2
 
3
3
  const useColor = process.stdout.isTTY && !process.env.NO_COLOR
4
+ const trueColor = useColor && /^(truecolor|24bit)$/i.test(process.env.COLORTERM || '')
4
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` : ''
5
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 ─────────────────────────────────────
6
24
  export const RST = sgr(0)
7
25
  export const BOLD = sgr(1)
8
26
  export const DIM = sgr(2)
9
27
  export const ITALIC = sgr(3)
10
28
  export const UNDERLINE = sgr(4)
11
- export const RED = sgr(31)
12
- export const GREEN = sgr(32)
13
- export const YELLOW = sgr(33)
14
- export const BLUE = sgr(34)
15
- export const MAGENTA = sgr(35)
16
- export const CYAN = sgr(36)
17
- export const GRAY = sgr(90)
18
- export const BG_RED = sgr('48;5;52')
19
- export const BG_GREEN = sgr('48;5;22')
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
20
76
 
21
77
  const out = s => process.stdout.write(s)
22
78
 
23
- /**
24
- * Renders markdown as it streams in: inline code and bold as they arrive, headings, bullets and code
25
- * fences once the start of a line shows what it is. Every line is indented under a "●" marker.
26
- */
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
+
27
168
  export class MarkdownStream {
28
- constructor({ marker = `${MAGENTA}●${RST} `, indent = ' ' } = {}) {
169
+ constructor({ marker = `${IRIS}●${RST} `, indent = ' ' } = {}) {
29
170
  this.marker = marker
30
171
  this.indent = indent
31
172
  this.started = false
@@ -59,17 +200,15 @@ export class MarkdownStream {
59
200
  }
60
201
 
61
202
  #style() {
62
- if (this.fence) return CYAN
63
- return `${this.lineStyle}${this.bold ? BOLD : ''}${this.code ? CYAN : ''}`
203
+ if (this.fence) return NEON_CYAN
204
+ return `${this.lineStyle}${this.bold ? BOLD : ''}${this.code ? VIVID_MAGENTA : ''}`
64
205
  }
65
206
 
66
207
  #char(ch) {
67
- // No escapes or control characters from the model reach the terminal.
68
208
  if (ch !== '\n' && ch !== '\t' && /[\x00-\x1f\x7f-\x9f]/.test(ch)) return
69
209
  if (this.lineStart) {
70
210
  if (ch === '\n') { this.#decideLine(true); this.#newline(); return }
71
211
  this.head += ch
72
- // Wait until the line's opening shows whether it is a fence, heading or bullet.
73
212
  if (/^[#`\-*+> \d.]*$/.test(this.head) && this.head.length < 4) return
74
213
  this.#decideLine(false)
75
214
  return
@@ -86,31 +225,31 @@ export class MarkdownStream {
86
225
  if (/^\s*```/.test(head) || (complete && /^\s*``$/.test(head))) {
87
226
  this.fence = !this.fence
88
227
  this.fenceLine = true
89
- this.#emit(`${DIM}${head}`)
228
+ this.#emit(`${DARK_GRAY}${head}`)
90
229
  return
91
230
  }
92
231
  if (this.fence) {
93
232
  this.fenceLine = true
94
- this.#emit(`${CYAN}${head}`)
233
+ this.#emit(`${NEON_CYAN}${head}`)
95
234
  return
96
235
  }
97
236
  const heading = head.match(/^(#{1,6}) (.*)$/s)
98
237
  if (heading) {
99
- this.lineStyle = BOLD
100
- this.#emit(BOLD)
238
+ this.lineStyle = `${BOLD}${GOLD}`
239
+ this.#emit(`${BOLD}${GOLD}`)
101
240
  for (const ch of heading[2]) this.#inline(ch)
102
241
  return
103
242
  }
104
243
  const bullet = head.match(/^(\s*)[-*+] (.*)$/s)
105
244
  if (bullet) {
106
- this.#emit(`${bullet[1]}${DIM}•${RST} `)
245
+ this.#emit(`${bullet[1]}${LIME}•${RST} `)
107
246
  for (const ch of bullet[2]) this.#inline(ch)
108
247
  return
109
248
  }
110
249
  const quote = head.match(/^> ?(.*)$/s)
111
250
  if (quote) {
112
- this.lineStyle = DIM
113
- this.#emit(`${DIM}│ `)
251
+ this.lineStyle = LAVENDER
252
+ this.#emit(`${ELECTRIC_PURPLE}│${RST} ${LAVENDER}`)
114
253
  for (const ch of quote[1]) this.#inline(ch)
115
254
  return
116
255
  }
@@ -148,7 +287,10 @@ export class MarkdownStream {
148
287
  }
149
288
  }
150
289
 
151
- const FRAMES = ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏']
290
+ // ─── Spinner (color-cycling braille) ────────────────────
291
+
292
+ const SPINNER_FRAMES = ['⣾', '⣽', '⣻', '⢿', '⡿', '⣟', '⣯', '⣷']
293
+ const SPINNER_COLORS = [51, 45, 39, 33, 63, 99, 135, 171]
152
294
 
153
295
  export class Spinner {
154
296
  constructor() {
@@ -162,7 +304,8 @@ export class Spinner {
162
304
  let frame = 0
163
305
  const draw = () => {
164
306
  const secs = Math.floor((Date.now() - began) / 1000)
165
- out(`\r\x1b[2K${MAGENTA}${FRAMES[frame++ % FRAMES.length]}${RST} ${label}${DIM} (${secs}s · esc to interrupt)${RST}`)
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}`)
166
309
  }
167
310
  draw()
168
311
  this.timer = setInterval(draw, 100)
@@ -176,7 +319,9 @@ export class Spinner {
176
319
  }
177
320
  }
178
321
 
179
- /** Model- or program-supplied text with terminal escapes and control characters removed, so it can't restyle or rewrite the screen. */
322
+ // ─── Tool output formatting ─────────────────────────────
323
+
324
+ /** Strip terminal escapes and control characters so model/program text can't restyle the screen. */
180
325
  export function clean(text) {
181
326
  return String(text)
182
327
  .replace(/\x1b\[[0-?]*[ -/]*[@-~]/g, '')
@@ -186,14 +331,16 @@ export function clean(text) {
186
331
 
187
332
  export function toolHeader(name, arg) {
188
333
  const shown = arg ? clean(arg).replace(/\n/g, ' ⏎ ') : ''
189
- return `${GREEN}●${RST} ${BOLD}${clean(name)}${RST}${shown ? `(${shown})` : ''}`
334
+ return `${LIME}▸${RST} ${BOLD}${LIME}${clean(name)}${RST}${shown ? ` ${SKY}${shown}${RST}` : ''}`
190
335
  }
191
336
 
192
337
  export function toolResultLine(text, color = '') {
193
338
  const lines = String(text).split('\n')
194
- return lines.map((line, i) => `${i === 0 ? ` ${DIM}⎿${RST} ` : ' '}${color}${line}${color ? RST : ''}`).join('\n')
339
+ return lines.map((line, i) => `${i === 0 ? ` ${DARK_GRAY}⎿${RST} ` : ' '}${color}${line}${color ? RST : ''}`).join('\n')
195
340
  }
196
341
 
342
+ // ─── Diff rendering ─────────────────────────────────────
343
+
197
344
  /** Line-level edit operations from `before` to `after`: [' ' | '-' | '+', line]. */
198
345
  export function diffLines(before, after) {
199
346
  const a = before.split('\n')
@@ -203,11 +350,9 @@ export function diffLines(before, after) {
203
350
  ops = [...a.map(line => ['-', line]), ...b.map(line => ['+', line])]
204
351
  } else {
205
352
  const dp = Array.from({ length: a.length + 1 }, () => new Uint32Array(b.length + 1))
206
- for (let i = a.length - 1; i >= 0; i--) {
207
- for (let j = b.length - 1; j >= 0; j--) {
353
+ for (let i = a.length - 1; i >= 0; i--)
354
+ for (let j = b.length - 1; j >= 0; j--)
208
355
  dp[i][j] = a[i] === b[j] ? dp[i + 1][j + 1] + 1 : Math.max(dp[i + 1][j], dp[i][j + 1])
209
- }
210
- }
211
356
  ops = []
212
357
  let i = 0, j = 0
213
358
  while (i < a.length || j < b.length) {
@@ -219,7 +364,7 @@ export function diffLines(before, after) {
219
364
  return ops
220
365
  }
221
366
 
222
- /** A line diff of a small change: the changed lines plus `context` unchanged ones around each. */
367
+ /** A line diff with context lines around each changed region. */
223
368
  export function renderDiff(before, after, firstLine = 1, context = 2, maxLines = 40) {
224
369
  const ops = diffLines(before, after)
225
370
  const keep = ops.map(() => false)
@@ -232,17 +377,17 @@ export function renderDiff(before, after, firstLine = 1, context = 2, maxLines =
232
377
  for (let k = 0; k < ops.length; k++) {
233
378
  const [op, text] = ops[k]
234
379
  if (keep[k]) {
235
- if (gap && lines.length) lines.push(`${DIM} ⋮${RST}`)
380
+ if (gap && lines.length) lines.push(`${DARK_GRAY} ⋮${RST}`)
236
381
  gap = false
237
382
  const no = String(op === '-' ? oldNo : newNo).padStart(5)
238
- if (op === '-') lines.push(`${BG_RED}${no} - ${text}${RST}`)
239
- else if (op === '+') lines.push(`${BG_GREEN}${no} + ${text}${RST}`)
240
- else lines.push(`${DIM}${no} ${text}${RST}`)
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}`)
241
386
  } else gap = true
242
387
  if (op !== '+') oldNo++
243
388
  if (op !== '-') newNo++
244
389
  }
245
- if (lines.length > maxLines) return [...lines.slice(0, maxLines), `${DIM} … ${lines.length - maxLines} more lines${RST}`].join('\n')
390
+ if (lines.length > maxLines) return [...lines.slice(0, maxLines), `${SOFT_GRAY} … ${lines.length - maxLines} more lines${RST}`].join('\n')
246
391
  return lines.join('\n')
247
392
  }
248
393