noguard 1.1.1 → 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.
- package/bin/noguard.mjs +25 -13
- package/lib/agent.mjs +7 -0
- package/lib/chat.mjs +93 -58
- package/lib/persona-eval.mjs +305 -0
- package/lib/render.mjs +102 -34
- package/package.json +1 -1
package/bin/noguard.mjs
CHANGED
|
@@ -3,10 +3,11 @@
|
|
|
3
3
|
import {
|
|
4
4
|
BOLD, RST, UNDERLINE,
|
|
5
5
|
NEON_CYAN, HOT_PINK, LIME, ORANGE, GOLD, SKY, BRIGHT_WHITE, SOFT_GRAY, DARK_GRAY,
|
|
6
|
-
|
|
6
|
+
AMBER, MINT, ROSE, FG_STRONG, MUTED, FAINT,
|
|
7
|
+
gradient, NOGUARD_GRADIENT, sectionHeader, tierPill, creditMeter, sparkline,
|
|
7
8
|
} from '../lib/render.mjs'
|
|
8
9
|
|
|
9
|
-
const VERSION = '1.
|
|
10
|
+
const VERSION = '1.2.0'
|
|
10
11
|
|
|
11
12
|
function helpText() {
|
|
12
13
|
return `
|
|
@@ -27,6 +28,7 @@ ${GOLD}${BOLD}Usage:${RST}
|
|
|
27
28
|
${BRIGHT_WHITE}noguard usage${RST} ${NEON_CYAN}[--days N]${RST} ${SOFT_GRAY}Show credit usage history${RST}
|
|
28
29
|
${BRIGHT_WHITE}noguard config${RST} ${SOFT_GRAY}Show config file location${RST}
|
|
29
30
|
${BRIGHT_WHITE}noguard endpoint${RST} ${SKY}[URL]${RST} ${SOFT_GRAY}Show or set the API endpoint${RST}
|
|
31
|
+
${BRIGHT_WHITE}noguard eval-personas${RST} ${SOFT_GRAY}Run standardized persona evaluations (--help for options)${RST}
|
|
30
32
|
|
|
31
33
|
${GOLD}${BOLD}Options:${RST}
|
|
32
34
|
${NEON_CYAN}--model, -m${RST} ${SKY}<name>${RST} ${SOFT_GRAY}Choose a model (alias or name, e.g. noguard-ultra)${RST}
|
|
@@ -89,6 +91,11 @@ function fmtNumber(n) {
|
|
|
89
91
|
|
|
90
92
|
async function main() {
|
|
91
93
|
const args = process.argv.slice(2)
|
|
94
|
+
if (args[0] === 'eval-personas') {
|
|
95
|
+
const { main: evaluatePersonas } = await import('../lib/persona-eval.mjs')
|
|
96
|
+
await evaluatePersonas(args.slice(1))
|
|
97
|
+
return
|
|
98
|
+
}
|
|
92
99
|
const { flags, values, positional } = parseArgs(args)
|
|
93
100
|
const command = COMMANDS.has(positional[0]) ? positional[0] : positional.length ? 'prompt' : undefined
|
|
94
101
|
|
|
@@ -135,15 +142,16 @@ async function main() {
|
|
|
135
142
|
if (!getToken()) { console.log(`${HOT_PINK}✗${RST} Not signed in. Run ${BOLD}noguard login${RST} first.`); return }
|
|
136
143
|
try {
|
|
137
144
|
const me = await get('/api/v1/me')
|
|
138
|
-
const
|
|
145
|
+
const low = me.low_balance || me.available < 100
|
|
146
|
+
const row = (name, value) => console.log(` ${MUTED}${name.padEnd(9)}${RST} ${value}`)
|
|
139
147
|
console.log()
|
|
140
148
|
console.log(sectionHeader('Account'))
|
|
141
149
|
console.log()
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
150
|
+
if (me.display_name) row('Name', `${FG_STRONG}${BOLD}${me.display_name}${RST}`)
|
|
151
|
+
row('Email', `${FG_STRONG}${me.email}${RST} ${tierPill(me.tier)}`)
|
|
152
|
+
row('Verified', me.verified ? `${MINT}yes${RST}` : `${ROSE}no${RST}`)
|
|
153
|
+
row('Credits', `${low ? ROSE : AMBER}${BOLD}${fmtNumber(me.available)}${RST} ${MUTED}available${RST} ${FAINT}of ${fmtNumber(me.credits)}${RST} ${creditMeter(me.available, me.credits, { low })}`)
|
|
154
|
+
row('Token', `${SKY}${me.token.name}${RST} ${FAINT}(${me.token.uid})${RST}`)
|
|
147
155
|
console.log()
|
|
148
156
|
} catch (err) {
|
|
149
157
|
if (err.status === 401) console.log(`${HOT_PINK}✗${RST} Session expired. Run ${BOLD}noguard login${RST} again.`)
|
|
@@ -170,14 +178,18 @@ async function main() {
|
|
|
170
178
|
try {
|
|
171
179
|
const res = await get(`/api/v1/usage?days=${days}`)
|
|
172
180
|
console.log()
|
|
173
|
-
console.log(sectionHeader(`Usage
|
|
181
|
+
console.log(sectionHeader(`Usage · last ${res.days_covered} days`))
|
|
174
182
|
console.log()
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
183
|
+
const list = res.days ?? []
|
|
184
|
+
if (list.length) {
|
|
185
|
+
for (const day of list) {
|
|
186
|
+
console.log(` ${FG_STRONG}${day.day}${RST} ${AMBER}${BOLD}${fmtNumber(day.credits)}${RST} ${MUTED}cr${RST} ${FAINT}${day.requests} req${RST}`)
|
|
178
187
|
}
|
|
188
|
+
const total = res.total_credits ?? list.reduce((a, b) => a + b.credits, 0)
|
|
189
|
+
console.log()
|
|
190
|
+
console.log(` ${sparkline(list.map(d => d.credits))} ${FAINT}${fmtNumber(total)} credits · ${fmtNumber(res.total_requests ?? list.reduce((a, b) => a + b.requests, 0))} requests${RST}`)
|
|
179
191
|
} else {
|
|
180
|
-
console.log(` ${
|
|
192
|
+
console.log(` ${MUTED}No usage yet.${RST}`)
|
|
181
193
|
}
|
|
182
194
|
console.log()
|
|
183
195
|
} catch (err) {
|
package/lib/agent.mjs
CHANGED
|
@@ -143,6 +143,13 @@ export class Agent {
|
|
|
143
143
|
this.controller?.abort()
|
|
144
144
|
}
|
|
145
145
|
|
|
146
|
+
/** Rough context usage, for the prompt status line: { used, max, left } in characters. */
|
|
147
|
+
contextUse() {
|
|
148
|
+
const { chars } = this.#budget(this.getModel?.())
|
|
149
|
+
const used = this.#size()
|
|
150
|
+
return { used, max: chars, left: Math.max(0, chars - used) }
|
|
151
|
+
}
|
|
152
|
+
|
|
146
153
|
#pushUserText(text) {
|
|
147
154
|
const last = this.messages.at(-1)
|
|
148
155
|
if (last?.role === 'user') {
|
package/lib/chat.mjs
CHANGED
|
@@ -9,18 +9,20 @@ import { detectShell } from './shell.mjs'
|
|
|
9
9
|
import { TOOLS } from './tools.mjs'
|
|
10
10
|
import {
|
|
11
11
|
BOLD, DIM, RST, UNDERLINE,
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
12
|
+
IRIS, CYAN, MINT, AMBER, ROSE, SKY, MAGENTA, GOLD, LAVENDER,
|
|
13
|
+
FG, FG_STRONG, DIMFG, MUTED, FAINT, LINE,
|
|
14
|
+
NEON_CYAN, HOT_PINK, ELECTRIC_PURPLE, VIVID_MAGENTA, LIME, ORANGE, CORAL,
|
|
15
|
+
BRIGHT_WHITE, SOFT_GRAY, DARK_GRAY, BG_DARK,
|
|
15
16
|
sectionHeader, statusBar, gradient, NOGUARD_GRADIENT, stripAnsi, termWidth,
|
|
17
|
+
creditMeter, tierPill, tierColor, sparkline,
|
|
16
18
|
} from './render.mjs'
|
|
17
19
|
|
|
18
20
|
const RESET_COMMANDS = new Set(['/clear', '/reset', '/new'])
|
|
19
21
|
const EXIT_COMMANDS = new Set(['/exit', '/quit', '/bye'])
|
|
20
22
|
|
|
21
|
-
const TIER_COLORS = { ultra: GOLD,
|
|
22
|
-
const TIER_ICONS = {
|
|
23
|
-
const LIB_COLORS = { cyber:
|
|
23
|
+
const TIER_COLORS = { raw: MAGENTA, ultra: GOLD, pro: MINT, paid: MINT, standard: CYAN, free: MUTED }
|
|
24
|
+
const TIER_ICONS = { raw: '◆', ultra: '✦', pro: '▲', paid: '▲', standard: '⚡', free: '○' }
|
|
25
|
+
const LIB_COLORS = { cyber: ROSE, engineering: CYAN, bio: MINT, creative: IRIS }
|
|
24
26
|
|
|
25
27
|
const LIBRARIES = [
|
|
26
28
|
{ id: 'cyber', label: 'Cipher · Cyber', summary: 'Exploits, offensive security, reverse engineering' },
|
|
@@ -148,45 +150,39 @@ function shortPath(path) {
|
|
|
148
150
|
|
|
149
151
|
function printBanner({ model, agentMode, cwd, permissions, account }) {
|
|
150
152
|
const w = termWidth()
|
|
151
|
-
const inner = Math.max(
|
|
153
|
+
const inner = Math.max(28, Math.min(w - 4, 68))
|
|
154
|
+
const row = (name, value) => console.log(` ${MUTED}${name.padEnd(9)}${RST} ${value}`)
|
|
152
155
|
|
|
153
156
|
console.log()
|
|
154
|
-
console.log(` ${
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
const titleBare = stripAnsi(title).length
|
|
158
|
-
const titleLeft = Math.floor((inner - titleBare) / 2)
|
|
159
|
-
const titleRight = inner - titleBare - titleLeft
|
|
160
|
-
console.log(` ${NEON_CYAN}║${RST}${' '.repeat(titleLeft)}${title}${' '.repeat(titleRight)}${NEON_CYAN}║${RST}`)
|
|
161
|
-
|
|
162
|
-
const subText = 'The AI that doesn\'t say no.'
|
|
163
|
-
const subLeft = Math.floor((inner - subText.length) / 2)
|
|
164
|
-
const subRight = inner - subText.length - subLeft
|
|
165
|
-
console.log(` ${NEON_CYAN}║${RST}${' '.repeat(subLeft)}${SOFT_GRAY}${subText}${RST}${' '.repeat(subRight)}${NEON_CYAN}║${RST}`)
|
|
166
|
-
|
|
167
|
-
console.log(` ${NEON_CYAN}╚${'═'.repeat(inner)}╝${RST}`)
|
|
157
|
+
console.log(` ${gradient('◆ N O G U A R D', NOGUARD_GRADIENT)} ${FAINT}the AI that doesn't say no${RST}`)
|
|
158
|
+
const third = Math.max(4, Math.floor(inner / 3))
|
|
159
|
+
console.log(` ${CYAN}${'─'.repeat(third)}${IRIS}${'─'.repeat(third)}${MAGENTA}${'─'.repeat(inner - third * 2)}${RST}`)
|
|
168
160
|
console.log()
|
|
169
161
|
|
|
170
|
-
const modelName = model?.display_name ?? 'default'
|
|
171
|
-
const tierColor = TIER_COLORS[model?.tier] ?? NEON_CYAN
|
|
172
|
-
console.log(` ${SOFT_GRAY}Model:${RST} ${tierColor}${BOLD}${modelName}${RST} ${DARK_GRAY}(${model?.id ?? 'auto'})${RST}`)
|
|
173
|
-
|
|
174
162
|
if (account) {
|
|
175
|
-
const
|
|
176
|
-
|
|
163
|
+
const name = account.display_name || (account.email ? account.email.split('@')[0] : 'you')
|
|
164
|
+
row('Signed in', `${FG_STRONG}${BOLD}${name}${RST} ${MUTED}${account.email ?? ''}${RST} ${tierPill(account.tier)}`)
|
|
165
|
+
const bal = account.credits ?? 0
|
|
166
|
+
const avail = account.available ?? bal
|
|
167
|
+
const low = account.low_balance || avail < 100
|
|
168
|
+
row('Credits', `${low ? ROSE : AMBER}${BOLD}${fmtNumber(avail)}${RST} ${MUTED}available${RST} ${FAINT}of ${fmtNumber(bal)}${RST} ${creditMeter(avail, bal, { low })}`)
|
|
177
169
|
}
|
|
178
170
|
|
|
171
|
+
const modelName = model?.display_name ?? 'default'
|
|
172
|
+
row('Model', `${tierColor(model?.tier)}${BOLD}${modelName}${RST} ${FAINT}(${model?.id ?? 'auto'})${RST}`)
|
|
173
|
+
|
|
179
174
|
if (agentMode) {
|
|
180
|
-
const modeColor = permissions.mode === 'yolo' ?
|
|
181
|
-
|
|
182
|
-
|
|
175
|
+
const modeColor = permissions.mode === 'yolo' ? ROSE : permissions.mode === 'accept-edits' ? AMBER : CYAN
|
|
176
|
+
row('Mode', `${modeColor}${BOLD}${permissions.mode}${RST} ${FAINT}${MODES[permissions.mode]} · /mode to change${RST}`)
|
|
177
|
+
row('Folder', `${SKY}${shortPath(cwd)}${RST}`)
|
|
183
178
|
const files = instructionFiles(cwd)
|
|
184
|
-
if (files.length)
|
|
185
|
-
if (cwd === homedir()) console.log(` ${
|
|
179
|
+
if (files.length) row('Project', `${LAVENDER}${files.map(shortPath).join(', ')}${RST}`)
|
|
180
|
+
if (cwd === homedir()) console.log(` ${ROSE}▲${RST} ${MUTED}You're in your home folder. Start noguard inside a project folder to work on it.${RST}`)
|
|
186
181
|
} else {
|
|
187
|
-
|
|
182
|
+
row('Chat', `${MUTED}chat only — NoGuard can't see or change files in this session${RST}`)
|
|
188
183
|
}
|
|
189
|
-
console.log(
|
|
184
|
+
console.log()
|
|
185
|
+
console.log(` ${FAINT}/help for commands · Esc to interrupt · Ctrl+C twice to exit${RST}`)
|
|
190
186
|
console.log()
|
|
191
187
|
}
|
|
192
188
|
|
|
@@ -294,11 +290,25 @@ export async function chat(opts = {}) {
|
|
|
294
290
|
|
|
295
291
|
function buildPrompt() {
|
|
296
292
|
const modelName = currentModel?.display_name ?? 'default'
|
|
297
|
-
const
|
|
298
|
-
const modeColor = permissions.mode === 'yolo' ?
|
|
293
|
+
const mColor = tierColor(currentModel?.tier)
|
|
294
|
+
const modeColor = permissions.mode === 'yolo' ? ROSE : permissions.mode === 'accept-edits' ? AMBER : CYAN
|
|
295
|
+
const low = credits !== null && credits < 100
|
|
299
296
|
const credStr = credits !== null ? fmtNumber(credits) : '?'
|
|
300
|
-
const
|
|
301
|
-
|
|
297
|
+
const sep = ` ${FAINT}│${RST} `
|
|
298
|
+
const segs = [
|
|
299
|
+
`${mColor}${BOLD}${modelName}${RST}${currentModel?.tier ? ` ${FAINT}${currentModel.tier}${RST}` : ''}`,
|
|
300
|
+
`${modeColor}${permissions.mode}${RST}`,
|
|
301
|
+
`${low ? ROSE : AMBER}${BOLD}${credStr}${RST} ${FAINT}cr${RST}`,
|
|
302
|
+
]
|
|
303
|
+
const libs = [...activeLibraries]
|
|
304
|
+
if (libs.length) segs.push(`${CYAN}${libs.map(id => LIBRARIES.find(l => l.id === id)?.label.split(' · ')[0] ?? id).join(', ')} ●${RST}`)
|
|
305
|
+
if (agentMode) {
|
|
306
|
+
try {
|
|
307
|
+
const left = agent.contextUse().left
|
|
308
|
+
segs.push(`${DIMFG}${Math.round(left / 4000)}k${RST} ${FAINT}ctx${RST}`)
|
|
309
|
+
} catch { /* context estimate is best-effort */ }
|
|
310
|
+
}
|
|
311
|
+
return ` ${segs.join(sep)}\n ${CYAN}❯${RST} `
|
|
302
312
|
}
|
|
303
313
|
|
|
304
314
|
const more = `${DARK_GRAY} …${RST} `
|
|
@@ -332,10 +342,10 @@ export async function chat(opts = {}) {
|
|
|
332
342
|
console.log()
|
|
333
343
|
if (spent) {
|
|
334
344
|
console.log(statusBar([
|
|
335
|
-
['used', `${spent} cr`,
|
|
336
|
-
['
|
|
337
|
-
['model', currentModel?.display_name ?? 'default',
|
|
338
|
-
['mode', permissions.mode, permissions.mode === 'yolo' ?
|
|
345
|
+
['used', `${spent} cr`, AMBER],
|
|
346
|
+
['balance', `${fmtNumber(credits ?? '?')}`, credits !== null && credits < 100 ? ROSE : MINT],
|
|
347
|
+
['model', currentModel?.display_name ?? 'default', tierColor(currentModel?.tier)],
|
|
348
|
+
['mode', permissions.mode, permissions.mode === 'yolo' ? ROSE : permissions.mode === 'accept-edits' ? AMBER : CYAN],
|
|
339
349
|
]))
|
|
340
350
|
}
|
|
341
351
|
console.log()
|
|
@@ -366,19 +376,24 @@ export async function chat(opts = {}) {
|
|
|
366
376
|
if (lower === '/help' || lower === '/?') { printHelp(agentMode); continue }
|
|
367
377
|
if (lower === '/status') {
|
|
368
378
|
console.log()
|
|
369
|
-
console.log(sectionHeader('Session
|
|
379
|
+
console.log(sectionHeader('Session'))
|
|
370
380
|
console.log()
|
|
381
|
+
const row = (name, value) => console.log(` ${MUTED}${name.padEnd(10)}${RST} ${value}`)
|
|
371
382
|
const elapsed = Math.floor((Date.now() - sessionStart) / 60000)
|
|
372
|
-
const
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
if (credits !== null)
|
|
379
|
-
|
|
383
|
+
const modeColor = permissions.mode === 'yolo' ? ROSE : permissions.mode === 'accept-edits' ? AMBER : CYAN
|
|
384
|
+
if (accountInfo) row('Account', `${FG_STRONG}${BOLD}${accountInfo.display_name || accountInfo.email.split('@')[0]}${RST} ${tierPill(accountInfo.tier)} ${MUTED}${accountInfo.email}${RST}`)
|
|
385
|
+
row('Model', `${tierColor(currentModel?.tier)}${BOLD}${currentModel?.display_name ?? 'default'}${RST} ${FAINT}(${currentModel?.id ?? 'auto'})${RST}`)
|
|
386
|
+
row('Mode', `${modeColor}${BOLD}${permissions.mode}${RST}`)
|
|
387
|
+
row('Folder', `${SKY}${shortPath(cwd)}${RST}`)
|
|
388
|
+
row('Shell', `${DIMFG}${detectShell().label}${RST}`)
|
|
389
|
+
if (credits !== null) {
|
|
390
|
+
const low = credits < 100
|
|
391
|
+
row('Credits', `${low ? ROSE : AMBER}${BOLD}${fmtNumber(available ?? credits)}${RST} ${MUTED}available${RST} ${FAINT}of ${fmtNumber(credits)}${RST} ${creditMeter(available ?? credits, credits, { low })}`)
|
|
392
|
+
}
|
|
380
393
|
const libs = [...activeLibraries]
|
|
381
|
-
if (libs.length)
|
|
394
|
+
if (libs.length) row('Libraries', libs.map(id => `${LIB_COLORS[id] ?? CYAN}${id}${RST}`).join(', '))
|
|
395
|
+
console.log(` ${LINE}${'─'.repeat(Math.max(10, Math.min(termWidth() - 4, 58)))}${RST}`)
|
|
396
|
+
row('This run', `${IRIS}${BOLD}${sessionMessages}${RST} ${MUTED}msgs${RST} ${FAINT}·${RST} ${IRIS}${BOLD}${fmtNumber(sessionCredits)}${RST} ${MUTED}cr${RST} ${FAINT}·${RST} ${IRIS}${BOLD}${elapsed}${RST} ${MUTED}min${RST}`)
|
|
382
397
|
console.log()
|
|
383
398
|
continue
|
|
384
399
|
}
|
|
@@ -389,14 +404,34 @@ export async function chat(opts = {}) {
|
|
|
389
404
|
try {
|
|
390
405
|
const me = await get('/api/v1/me')
|
|
391
406
|
credits = me.credits; available = me.available
|
|
392
|
-
|
|
393
|
-
console.log(` ${
|
|
394
|
-
|
|
407
|
+
const low = me.low_balance || me.available < 100
|
|
408
|
+
const row = (name, value) => console.log(` ${MUTED}${name.padEnd(10)}${RST} ${value}`)
|
|
409
|
+
row('Balance', `${AMBER}${BOLD}${fmtNumber(me.credits)}${RST}`)
|
|
410
|
+
row('Available', `${low ? ROSE : AMBER}${BOLD}${fmtNumber(me.available)}${RST} ${creditMeter(me.available, me.credits, { low })}`)
|
|
411
|
+
const held = Math.max(0, me.credits - me.available)
|
|
412
|
+
if (held) row('On hold', `${MUTED}${fmtNumber(held)}${RST}`)
|
|
413
|
+
if (sessionCredits) row('This run', `${IRIS}${BOLD}${fmtNumber(sessionCredits)}${RST} ${MUTED}spent${RST}`)
|
|
414
|
+
try {
|
|
415
|
+
const usage = await get('/api/v1/usage?days=14')
|
|
416
|
+
const byDay = new Map((usage.days ?? []).map(d => [d.day, d.credits]))
|
|
417
|
+
if (byDay.size) {
|
|
418
|
+
const arr = []
|
|
419
|
+
const now = new Date()
|
|
420
|
+
for (let i = 13; i >= 0; i--) {
|
|
421
|
+
const dt = new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate() - i))
|
|
422
|
+
arr.push(byDay.get(dt.toISOString().slice(0, 10)) ?? 0)
|
|
423
|
+
}
|
|
424
|
+
const total = arr.reduce((a, b) => a + b, 0)
|
|
425
|
+
console.log()
|
|
426
|
+
console.log(` ${MUTED}credits / day${RST} ${FAINT}· last 14 days · ${fmtNumber(total)} total${RST}`)
|
|
427
|
+
console.log(` ${sparkline(arr)} ${FAINT}today${RST} ${AMBER}${BOLD}${fmtNumber(arr.at(-1))}${RST}`)
|
|
428
|
+
}
|
|
429
|
+
} catch { /* usage sparkline is best-effort */ }
|
|
395
430
|
console.log()
|
|
396
|
-
console.log(` ${
|
|
431
|
+
console.log(` ${FAINT}top up at${RST} ${SKY}${UNDERLINE}https://noguard.ai/credits${RST}`)
|
|
397
432
|
} catch {
|
|
398
|
-
if (credits !== null) console.log(` ${
|
|
399
|
-
else console.log(` ${
|
|
433
|
+
if (credits !== null) console.log(` ${AMBER}${fmtNumber(credits)}${RST} credits remaining.`)
|
|
434
|
+
else console.log(` ${MUTED}Could not load your balance.${RST}`)
|
|
400
435
|
}
|
|
401
436
|
console.log()
|
|
402
437
|
continue
|
|
@@ -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
|
-
// ───
|
|
16
|
-
export const
|
|
17
|
-
export const
|
|
18
|
-
export const
|
|
19
|
-
export const
|
|
20
|
-
export const
|
|
21
|
-
export const
|
|
22
|
-
export const
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
export const
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
export const
|
|
29
|
-
export const
|
|
30
|
-
export const
|
|
31
|
-
export const
|
|
32
|
-
export const
|
|
33
|
-
export const
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
export const
|
|
37
|
-
export const
|
|
38
|
-
export const
|
|
39
|
-
export const
|
|
40
|
-
export const
|
|
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 =
|
|
44
|
-
export const BG_SECTION =
|
|
45
|
-
export const BG_RED =
|
|
46
|
-
export const BG_GREEN =
|
|
47
|
-
export const BG_HIGHLIGHT =
|
|
48
|
-
export const BG_HEADER =
|
|
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 ` ${
|
|
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 = `${
|
|
169
|
+
constructor({ marker = `${IRIS}●${RST} `, indent = ' ' } = {}) {
|
|
102
170
|
this.marker = marker
|
|
103
171
|
this.indent = indent
|
|
104
172
|
this.started = false
|