noguard 1.1.1 → 1.2.1

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,10 +1,25 @@
1
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` : ''
5
6
  const c256 = fg => useColor ? `\x1b[38;5;${fg}m` : ''
6
7
  const c256bg = bg => useColor ? `\x1b[48;5;${bg}m` : ''
7
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
+
8
23
  // ─── Core formatting ─────────────────────────────────────
9
24
  export const RST = sgr(0)
10
25
  export const BOLD = sgr(1)
@@ -12,40 +27,52 @@ export const DIM = sgr(2)
12
27
  export const ITALIC = sgr(3)
13
28
  export const UNDERLINE = sgr(4)
14
29
 
15
- // ─── Standard 16-color (backward compat) ────────────────
16
- export const RED = sgr(31)
17
- export const GREEN = sgr(32)
18
- export const YELLOW = sgr(33)
19
- export const BLUE = sgr(34)
20
- export const MAGENTA = sgr(35)
21
- export const CYAN = sgr(36)
22
- export const GRAY = sgr(90)
23
-
24
- // ─── Vibrant 256-color palette ──────────────────────────
25
- export const NEON_CYAN = c256(51) // Primary accent — prompts, borders, active states
26
- export const HOT_PINK = c256(198) // Errors, critical alerts, denials
27
- export const ELECTRIC_PURPLE = c256(135) // Model names, section headers
28
- export const VIVID_MAGENTA = c256(201) // Inline code highlights
29
- export const LIME = c256(118) // Success marks, tool names, confirmations
30
- export const ORANGE = c256(208) // Credits, cost, warnings
31
- export const GOLD = c256(220) // Premium tier, markdown headings, emphasis
32
- export const CORAL = c256(209) // Secondary accent, session stats
33
- export const SKY = c256(117) // File paths, info text
34
- export const MINT = c256(121) // Diff additions, completions
35
- export const LAVENDER = c256(183) // Blockquotes, metadata
36
- export const PEACH = c256(216) // Warm accents
37
- export const BRIGHT_WHITE = c256(231) // Primary text emphasis
38
- export const SOFT_GRAY = c256(245) // Secondary text, labels
39
- export const DARK_GRAY = c256(238) // Borders, separators, subtle elements
40
- export const DEEP_BLUE = c256(27) // Links, special actions
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
41
68
 
42
69
  // ─── Background colors ──────────────────────────────────
43
- export const BG_DARK = c256bg(233) // Status bar background
44
- export const BG_SECTION = c256bg(235) // Section background
45
- export const BG_RED = c256bg(52) // Diff removed
46
- export const BG_GREEN = c256bg(22) // Diff added
47
- export const BG_HIGHLIGHT = c256bg(236) // Highlighted lines
48
- export const BG_HEADER = c256bg(234) // Header background
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
49
76
 
50
77
  const out = s => process.stdout.write(s)
51
78
 
@@ -63,7 +90,48 @@ export function stripAnsi(text) {
63
90
  export function sectionHeader(title) {
64
91
  const w = termWidth() - 4
65
92
  const rightPad = Math.max(1, w - title.length - 4)
66
- return ` ${NEON_CYAN}──${RST} ${BOLD}${BRIGHT_WHITE}${title}${RST} ${NEON_CYAN}${'─'.repeat(rightPad)}${RST}`
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('')
67
135
  }
68
136
 
69
137
  /** Compact status bar: colored segments on a dark background filling the terminal width. */
@@ -98,7 +166,7 @@ export const NOGUARD_GRADIENT = [51, 45, 39, 33, 69, 105, 141, 135, 171, 207, 20
98
166
  // ─── Markdown stream ────────────────────────────────────
99
167
 
100
168
  export class MarkdownStream {
101
- constructor({ marker = `${NEON_CYAN}●${RST} `, indent = ' ' } = {}) {
169
+ constructor({ marker = `${IRIS}●${RST} `, indent = ' ' } = {}) {
102
170
  this.marker = marker
103
171
  this.indent = indent
104
172
  this.started = false
package/package.json CHANGED
@@ -1,23 +1,23 @@
1
- {
2
- "name": "noguard",
3
- "version": "1.1.1",
4
- "description": "NoGuard AI — the AI that doesn't say no. An agent in your terminal that reads, edits and runs your project.",
5
- "type": "module",
6
- "bin": {
7
- "noguard": "bin/noguard.mjs"
8
- },
9
- "files": [
10
- "bin/",
11
- "lib/"
12
- ],
13
- "keywords": [
14
- "noguard",
15
- "ai",
16
- "cli",
17
- "chat"
18
- ],
19
- "license": "UNLICENSED",
20
- "engines": {
21
- "node": ">=18"
22
- }
23
- }
1
+ {
2
+ "name": "noguard",
3
+ "version": "1.2.1",
4
+ "description": "NoGuard AI — the AI that doesn't say no. An agent in your terminal that reads, edits and runs your project.",
5
+ "type": "module",
6
+ "bin": {
7
+ "noguard": "bin/noguard.mjs"
8
+ },
9
+ "files": [
10
+ "bin/",
11
+ "lib/"
12
+ ],
13
+ "keywords": [
14
+ "noguard",
15
+ "ai",
16
+ "cli",
17
+ "chat"
18
+ ],
19
+ "license": "UNLICENSED",
20
+ "engines": {
21
+ "node": ">=18"
22
+ }
23
+ }