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.
package/lib/chat.mjs CHANGED
@@ -1,480 +1,525 @@
1
- import { emitKeypressEvents } from 'node:readline'
2
- import { createInterface } from 'node:readline/promises'
3
- import { homedir } from 'node:os'
4
- import { get } from './api.mjs'
5
- import { getToken } from './config.mjs'
6
- import { Agent, MODES, Permissions } from './agent.mjs'
7
- import { instructionFiles } from './context.mjs'
8
- import { detectShell } from './shell.mjs'
9
- import { TOOLS } from './tools.mjs'
10
- import {
11
- BOLD, DIM, RST, UNDERLINE,
12
- NEON_CYAN, HOT_PINK, ELECTRIC_PURPLE, VIVID_MAGENTA, LIME, ORANGE, GOLD, CORAL,
13
- SKY, MINT, LAVENDER, PEACH, BRIGHT_WHITE, SOFT_GRAY, DARK_GRAY, DEEP_BLUE,
14
- BG_DARK,
15
- sectionHeader, statusBar, gradient, NOGUARD_GRADIENT, stripAnsi, termWidth,
16
- } from './render.mjs'
17
-
18
- const RESET_COMMANDS = new Set(['/clear', '/reset', '/new'])
19
- const EXIT_COMMANDS = new Set(['/exit', '/quit', '/bye'])
20
-
21
- const TIER_COLORS = { ultra: GOLD, standard: NEON_CYAN, pro: LIME, raw: VIVID_MAGENTA }
22
- const TIER_ICONS = { ultra: '◆', standard: '⚡', pro: '▲', raw: '✦' }
23
- const LIB_COLORS = { cyber: HOT_PINK, engineering: NEON_CYAN, bio: LIME, creative: ELECTRIC_PURPLE }
24
-
25
- const LIBRARIES = [
26
- { id: 'cyber', label: 'Cipher · Cyber', summary: 'Exploits, offensive security, reverse engineering' },
27
- { id: 'engineering', label: 'Forge · Engineering', summary: 'Software, systems and hardware engineering' },
28
- { id: 'bio', label: 'Helix · Bio', summary: 'Pharmacology, substance data, harm reduction' },
29
- { id: 'creative', label: 'Muse · Creative', summary: 'Uncensored creative writing and full artistic freedom' },
30
- ]
31
-
32
- const INIT_PROMPT = `Look through this project and write a NOGUARD.md file at the root of the working directory for future sessions to read. Cover, briefly:
33
- - what the project is and how it is laid out (the main folders and entry points),
34
- - the commands to install, build, run, lint and test it (check package.json, Makefiles, pyproject, Cargo.toml, CI config and so on),
35
- - conventions a contributor must follow that are not obvious from a single file.
36
- Keep it short and specific to this project. If a NOGUARD.md, CLAUDE.md or AGENTS.md already exists, improve on it rather than repeating it.`
37
-
38
- function fmtNumber(n) {
39
- return Number(n).toLocaleString('en-US')
40
- }
41
-
42
- function requireAuth() {
43
- if (!getToken()) {
44
- console.log(`${HOT_PINK}✗${RST} Not signed in. Run ${BOLD}noguard login${RST} first.`)
45
- process.exit(1)
46
- }
47
- }
48
-
49
- export function printModels(models, current = null) {
50
- console.log()
51
- console.log(sectionHeader('Available Models'))
52
- console.log()
53
- for (const model of models) {
54
- const tierColor = TIER_COLORS[model.tier] ?? NEON_CYAN
55
- const icon = TIER_ICONS[model.tier] ?? '●'
56
- const tags = []
57
- if (model.default_chat) tags.push(`${LIME}chat default${RST}`)
58
- if (model.default_build) tags.push(`${LIME}agent default${RST}`)
59
- if (model.default && !model.default_chat && !model.default_build) tags.push(`${LIME}default${RST}`)
60
- const active = current && model.id === current ? ` ${ORANGE}← active${RST}` : ''
61
- const tagStr = tags.length ? ` ${tags.join(` ${DARK_GRAY}·${RST} `)}` : ''
62
- const cost = model.cost_indicator ?? '$'
63
- console.log(` ${tierColor}${icon}${RST} ${tierColor}${BOLD}${model.display_name}${RST} ${SOFT_GRAY}${model.id}${RST} ${GOLD}${cost}${RST}${tagStr}${active}`)
64
- if (model.description) console.log(` ${SOFT_GRAY}${model.description}${RST}`)
65
- const caps = []
66
- if (model.chat_eligible) caps.push('chat')
67
- if (model.build_eligible && model.supports_tools !== false) caps.push('agent (files and commands)')
68
- if (caps.length) console.log(` ${DARK_GRAY}Supports: ${caps.join(', ')} · Context: ${(model.context_window / 1000).toFixed(0)}k · Max output: ${(model.max_output_tokens / 1000).toFixed(0)}k${RST}`)
69
- console.log()
70
- }
71
- }
72
-
73
- function printLibraries(activeLibs) {
74
- console.log()
75
- console.log(sectionHeader('Research Libraries'))
76
- console.log(` ${SOFT_GRAY}Toggle with /library <id> — active libraries inject curated sources into your questions.${RST}`)
77
- console.log()
78
- for (const lib of LIBRARIES) {
79
- const active = activeLibs.has(lib.id)
80
- const color = LIB_COLORS[lib.id] ?? NEON_CYAN
81
- const mark = active ? `${color}●${RST}` : `${DARK_GRAY}○${RST}`
82
- const label = active ? `${BOLD}${color}${lib.label}${RST}` : `${SOFT_GRAY}${lib.label}${RST}`
83
- console.log(` ${mark} ${label} ${DARK_GRAY}(${lib.id})${RST}`)
84
- console.log(` ${SOFT_GRAY}${lib.summary}${RST}`)
85
- }
86
- console.log()
87
- }
88
-
89
- function printHelp(agentMode) {
90
- console.log()
91
- console.log(sectionHeader('Commands'))
92
- console.log()
93
- const cmd = (name, desc) => console.log(` ${NEON_CYAN}${name.padEnd(22)}${RST} ${SOFT_GRAY}${desc}${RST}`)
94
- cmd('/models', 'List all models with tier info')
95
- cmd('/model <name>', 'Switch to a model (alias or display name)')
96
- if (agentMode) {
97
- cmd('/mode [mode]', 'Show or set permissions: ask, accept-edits, yolo')
98
- cmd('/init', 'Write a NOGUARD.md describing this project')
99
- cmd('/compact', 'Free context by dropping old tool output')
100
- cmd('/tools', 'List the tools NoGuard can use')
101
- cmd('/status', 'Show session info, credits, model, and stats')
102
- }
103
- cmd('/libraries, /libs', 'Show research libraries and their status')
104
- cmd('/library <id>, /lib', 'Toggle a library on/off')
105
- cmd('/clear, /reset, /new', 'Start a new conversation')
106
- cmd('/credits', 'Show remaining credits')
107
- cmd('/exit, /quit', 'Leave')
108
- console.log()
109
- console.log(sectionHeader('Keys'))
110
- console.log()
111
- const key = (name, desc) => console.log(` ${GOLD}${name.padEnd(22)}${RST} ${SOFT_GRAY}${desc}${RST}`)
112
- key('Esc or Ctrl+C', 'Stop NoGuard mid-reply or mid-command')
113
- key('Ctrl+C twice', 'Exit at the prompt')
114
- key('End line with \\', 'Continue on the next line (pasting works too)')
115
- key('Type """', 'Start/end a multi-line block')
116
- console.log()
117
- }
118
-
119
- /** The model a session runs on: the one asked for if it can do the job, else the right default. */
120
- export function pickModel(models, requested, agentMode) {
121
- const usable = m => agentMode ? Boolean(m.build_eligible) && m.supports_tools !== false : m.chat_eligible !== false
122
- if (requested) {
123
- const name = requested.toLowerCase()
124
- const match = models.find(m => m.id === requested || m.id === name || m.display_name.toLowerCase() === name)
125
- if (!match) return { model: null, warning: `Model "${requested}" not found. Run /models to see options.` }
126
- if (!usable(match)) return { model: null, warning: `${match.display_name} can't use tools, so it can't work on files. ${agentMode ? 'Pick a model marked "agent" in /models, or run noguard --no-tools to chat with it.' : ''}` }
127
- return { model: match }
128
- }
129
- const model = agentMode
130
- ? models.find(m => m.default_build && usable(m)) ?? models.find(usable)
131
- : models.find(m => (m.default_chat || m.default) && usable(m)) ?? models.find(usable)
132
- return { model: model ?? null }
133
- }
134
-
135
- async function loadModels() {
136
- try {
137
- const res = await get('/api/v1/models')
138
- return res.data ?? []
139
- } catch {
140
- return []
141
- }
142
- }
143
-
144
- function shortPath(path) {
145
- const home = homedir()
146
- return path.toLowerCase().startsWith(home.toLowerCase()) ? `~${path.slice(home.length)}` : path
147
- }
148
-
149
- function printBanner({ model, agentMode, cwd, permissions, account }) {
150
- const w = termWidth()
151
- const inner = Math.max(30, w - 4)
152
-
153
- console.log()
154
- console.log(` ${NEON_CYAN}╔${'═'.repeat(inner)}╗${RST}`)
155
-
156
- const title = gradient('◆ N O G U A R D A I ◆', NOGUARD_GRADIENT)
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}`)
168
- console.log()
169
-
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
- if (account) {
175
- const credColor = (account.credits ?? 0) < 100 ? HOT_PINK : ORANGE
176
- console.log(` ${SOFT_GRAY}Credits:${RST} ${credColor}${BOLD}${fmtNumber(account.credits ?? 0)}${RST} ${DARK_GRAY}(${fmtNumber(account.available ?? 0)} available)${RST}`)
177
- }
178
-
179
- if (agentMode) {
180
- const modeColor = permissions.mode === 'yolo' ? HOT_PINK : permissions.mode === 'accept-edits' ? ORANGE : NEON_CYAN
181
- console.log(` ${SOFT_GRAY}Mode:${RST} ${modeColor}${BOLD}${permissions.mode}${RST} ${DARK_GRAY}(${MODES[permissions.mode]} · /mode to change)${RST}`)
182
- console.log(` ${SOFT_GRAY}Folder:${RST} ${SKY}${shortPath(cwd)}${RST}`)
183
- const files = instructionFiles(cwd)
184
- if (files.length) console.log(` ${SOFT_GRAY}Project:${RST} ${LAVENDER}${files.map(shortPath).join(', ')}${RST}`)
185
- if (cwd === homedir()) console.log(` ${ORANGE}⚠${RST} ${SOFT_GRAY}You're in your home folder. Start noguard inside a project folder to work on it.${RST}`)
186
- } else {
187
- console.log(` ${SOFT_GRAY}Chat only: NoGuard can't see or change files in this session.${RST}`)
188
- }
189
- console.log(` ${DARK_GRAY}/help for commands · Esc to interrupt${RST}`)
190
- console.log()
191
- }
192
-
193
- /** `noguard -p "…"`: one task, no prompts, then exit. Edits and commands need --accept-edits or --yolo. */
194
- export async function runOnce(opts) {
195
- requireAuth()
196
- const agentMode = opts.tools !== false
197
- const models = await loadModels()
198
- const { model, warning } = pickModel(models, opts.model, agentMode)
199
- if (warning) { console.error(`${ORANGE}⚠${RST} ${warning}`); process.exit(1) }
200
- const agent = new Agent({
201
- cwd: process.cwd(),
202
- ui: { interactive: false, ask: async () => null },
203
- getModel: () => model,
204
- permissions: new Permissions(opts.mode ?? 'ask'),
205
- tools: agentMode,
206
- })
207
- const onInt = () => agent.busy ? agent.abort() : process.exit(130)
208
- process.on('SIGINT', onInt)
209
- const { ok, spent, balance } = await agent.send(opts.prompt)
210
- if (process.stderr.isTTY && spent) process.stderr.write(`${SOFT_GRAY} ${spent} credits · ${balance ?? '?'} remaining${RST}\n`)
211
- process.off('SIGINT', onInt)
212
- process.exitCode = ok ? 0 : 1
213
- }
214
-
215
- export async function chat(opts = {}) {
216
- requireAuth()
217
- const cwd = process.cwd()
218
- let agentMode = opts.tools !== false
219
-
220
- const [availableModelsRaw, accountInfo] = await Promise.all([
221
- loadModels(),
222
- get('/api/v1/me').catch(() => null),
223
- ])
224
- let availableModels = availableModelsRaw
225
-
226
- let { model: currentModel, warning } = pickModel(availableModels, opts.model, agentMode)
227
- if (warning) {
228
- console.log(`${ORANGE}⚠${RST} ${warning}`)
229
- currentModel = pickModel(availableModels, null, agentMode).model
230
- }
231
- if (agentMode && availableModels.length && !currentModel) {
232
- console.log(`${ORANGE}⚠${RST} No model that can work on files is available to you, so this is a chat-only session.`)
233
- agentMode = false
234
- currentModel = pickModel(availableModels, null, false).model
235
- }
236
-
237
- const permissions = new Permissions(opts.mode ?? 'ask')
238
- const activeLibraries = new Set()
239
- let credits = accountInfo?.credits ?? null
240
- let available = accountInfo?.available ?? null
241
-
242
- const sessionStart = Date.now()
243
- let sessionMessages = 0
244
- let sessionCredits = 0
245
-
246
- const interactive = process.stdin.isTTY !== false
247
- const rl = createInterface({ input: process.stdin, output: process.stdout, terminal: interactive, historySize: 500 })
248
- const pasted = []
249
- rl.on('line', line => pasted.push(line))
250
- let asking = null
251
- let lastInterrupt = 0
252
-
253
- const ui = {
254
- interactive: true,
255
- async ask(question) {
256
- asking = new AbortController()
257
- try {
258
- return await rl.question(question, { signal: asking.signal })
259
- } catch {
260
- return null
261
- } finally {
262
- asking = null
263
- }
264
- },
265
- }
266
-
267
- const agent = new Agent({
268
- cwd,
269
- ui,
270
- getModel: () => currentModel,
271
- permissions,
272
- tools: agentMode,
273
- getLibraries: () => [...activeLibraries],
274
- })
275
-
276
- rl.on('SIGINT', () => {
277
- if (asking) { asking.abort(); agent.abort(); return }
278
- if (agent.busy) { agent.abort(); return }
279
- if (rl.line) { rl.write(null, { ctrl: true, name: 'u' }); return }
280
- if (Date.now() - lastInterrupt < 2000) { console.log(`\n${SOFT_GRAY} Bye.${RST}`); process.exit(0) }
281
- lastInterrupt = Date.now()
282
- process.stdout.write(`\n${SOFT_GRAY} Press Ctrl+C again to exit.${RST}\n`)
283
- rl.prompt()
284
- })
285
- rl.on('close', () => { console.log(`${SOFT_GRAY} Bye.${RST}`); process.exit(0) })
286
- if (interactive) {
287
- emitKeypressEvents(process.stdin, rl)
288
- process.stdin.on('keypress', (_, key) => {
289
- if (key?.name === 'escape' && agent.busy && !asking) agent.abort()
290
- })
291
- }
292
-
293
- printBanner({ model: currentModel, agentMode, cwd, permissions, account: accountInfo })
294
-
295
- function buildPrompt() {
296
- const modelName = currentModel?.display_name ?? 'default'
297
- const tierColor = TIER_COLORS[currentModel?.tier] ?? NEON_CYAN
298
- const modeColor = permissions.mode === 'yolo' ? HOT_PINK : permissions.mode === 'accept-edits' ? ORANGE : NEON_CYAN
299
- const credStr = credits !== null ? fmtNumber(credits) : '?'
300
- const credColor = credits !== null && credits < 100 ? HOT_PINK : ORANGE
301
- return `${DARK_GRAY}╭─${RST}${tierColor}[${modelName}]${RST}${DARK_GRAY}─${RST}${credColor}[${credStr} cr]${RST}${DARK_GRAY}─${RST}${modeColor}[${permissions.mode}]${RST}\n${DARK_GRAY}╰${RST} ${NEON_CYAN}❯${RST} `
302
- }
303
-
304
- const more = `${DARK_GRAY} …${RST} `
305
-
306
- async function readInput() {
307
- pasted.length = 0
308
- const first = await rl.question(buildPrompt())
309
- if (interactive) await new Promise(r => setTimeout(r, 30))
310
- const lines = [first, ...(interactive ? pasted.splice(0) : [])]
311
- if (lines.length === 1 && lines[0].trim() === '"""') {
312
- const block = []
313
- for (;;) {
314
- const line = await rl.question(more)
315
- if (line.trim() === '"""') break
316
- block.push(line)
317
- }
318
- return block.join('\n')
319
- }
320
- while (lines.at(-1).endsWith('\\')) {
321
- lines[lines.length - 1] = lines.at(-1).slice(0, -1)
322
- lines.push(await rl.question(more))
323
- }
324
- return lines.join('\n')
325
- }
326
-
327
- async function send(text) {
328
- console.log()
329
- const { spent, balance } = await agent.send(text)
330
- if (balance != null) { credits = balance; available = balance }
331
- if (spent) { sessionCredits += spent; sessionMessages++ }
332
- console.log()
333
- if (spent) {
334
- console.log(statusBar([
335
- ['used', `${spent} cr`, ORANGE],
336
- ['remaining', `${fmtNumber(credits ?? '?')}`, credits !== null && credits < 100 ? HOT_PINK : LIME],
337
- ['model', currentModel?.display_name ?? 'default', TIER_COLORS[currentModel?.tier] ?? NEON_CYAN],
338
- ['mode', permissions.mode, permissions.mode === 'yolo' ? HOT_PINK : permissions.mode === 'accept-edits' ? ORANGE : NEON_CYAN],
339
- ]))
340
- }
341
- console.log()
342
- }
343
-
344
- if (opts.prompt) await send(opts.prompt)
345
-
346
- for (;;) {
347
- let input
348
- try {
349
- input = await readInput()
350
- } catch {
351
- break
352
- }
353
- const trimmed = input.trim()
354
- if (!trimmed) continue
355
- const lower = trimmed.toLowerCase()
356
- const [command, ...rest] = lower.split(/\s+/)
357
- const arg = trimmed.split(/\s+/).slice(1).join(' ')
358
-
359
- if (EXIT_COMMANDS.has(lower)) break
360
- if (RESET_COMMANDS.has(lower)) {
361
- agent.reset()
362
- sessionMessages = 0; sessionCredits = 0
363
- console.log(`${LIME}✓${RST} New conversation.\n`)
364
- continue
365
- }
366
- if (lower === '/help' || lower === '/?') { printHelp(agentMode); continue }
367
- if (lower === '/status') {
368
- console.log()
369
- console.log(sectionHeader('Session Status'))
370
- console.log()
371
- const elapsed = Math.floor((Date.now() - sessionStart) / 60000)
372
- const tierColor = TIER_COLORS[currentModel?.tier] ?? NEON_CYAN
373
- const modeColor = permissions.mode === 'yolo' ? HOT_PINK : permissions.mode === 'accept-edits' ? ORANGE : NEON_CYAN
374
- console.log(` ${SOFT_GRAY}Model:${RST} ${tierColor}${BOLD}${currentModel?.display_name ?? 'default'}${RST} ${DARK_GRAY}(${currentModel?.id ?? 'auto'})${RST}`)
375
- console.log(` ${SOFT_GRAY}Mode:${RST} ${modeColor}${BOLD}${permissions.mode}${RST}`)
376
- console.log(` ${SOFT_GRAY}Folder:${RST} ${SKY}${shortPath(cwd)}${RST}`)
377
- console.log(` ${SOFT_GRAY}Shell:${RST} ${BRIGHT_WHITE}${detectShell().label}${RST}`)
378
- if (credits !== null) console.log(` ${SOFT_GRAY}Credits:${RST} ${ORANGE}${BOLD}${fmtNumber(credits)}${RST} ${DARK_GRAY}(${fmtNumber(available ?? credits)} available)${RST}`)
379
- console.log(` ${SOFT_GRAY}Session:${RST} ${CORAL}${sessionMessages}${RST} messages ${DARK_GRAY}·${RST} ${CORAL}${sessionCredits}${RST} credits ${DARK_GRAY}·${RST} ${CORAL}${elapsed}${RST} min`)
380
- const libs = [...activeLibraries]
381
- if (libs.length) console.log(` ${SOFT_GRAY}Libraries:${RST} ${libs.map(id => `${LIB_COLORS[id] ?? NEON_CYAN}${id}${RST}`).join(', ')}`)
382
- console.log()
383
- continue
384
- }
385
- if (lower === '/credits') {
386
- console.log()
387
- console.log(sectionHeader('Credits'))
388
- console.log()
389
- try {
390
- const me = await get('/api/v1/me')
391
- credits = me.credits; available = me.available
392
- console.log(` ${SOFT_GRAY}Balance:${RST} ${ORANGE}${BOLD}${fmtNumber(me.credits)}${RST}`)
393
- console.log(` ${SOFT_GRAY}Available:${RST} ${ORANGE}${fmtNumber(me.available)}${RST}`)
394
- console.log(` ${SOFT_GRAY}Session:${RST} ${CORAL}${sessionCredits}${RST} credits used`)
395
- console.log()
396
- console.log(` ${SOFT_GRAY}Top up at ${NEON_CYAN}${UNDERLINE}https://noguard.ai/credits${RST}`)
397
- } catch {
398
- if (credits !== null) console.log(` ${ORANGE}${fmtNumber(credits)}${RST} credits remaining.`)
399
- else console.log(` ${SOFT_GRAY}Could not load your balance.${RST}`)
400
- }
401
- console.log()
402
- continue
403
- }
404
- if (lower === '/models') {
405
- if (!availableModels.length) availableModels = await loadModels()
406
- if (availableModels.length) printModels(availableModels, currentModel?.id)
407
- else console.log(` ${SOFT_GRAY}Could not load the model list.${RST}\n`)
408
- continue
409
- }
410
- if (command === '/model') {
411
- if (!arg) { console.log(` ${SOFT_GRAY}Usage: /model <alias or name>${RST}\n`); continue }
412
- const picked = pickModel(availableModels, arg, agentMode)
413
- if (picked.model) {
414
- currentModel = picked.model
415
- const tierColor = TIER_COLORS[currentModel.tier] ?? NEON_CYAN
416
- console.log(`${LIME}✓${RST} Switched to ${tierColor}${BOLD}${currentModel.display_name}${RST} ${DARK_GRAY}(${currentModel.id})${RST}\n`)
417
- } else console.log(`${HOT_PINK}✗${RST} ${picked.warning}\n`)
418
- continue
419
- }
420
- if (command === '/mode' || command === '/permissions') {
421
- const wanted = rest[0] === 'edits' ? 'accept-edits' : rest[0]
422
- if (!agentMode) console.log(` ${SOFT_GRAY}This is a chat-only session.${RST}\n`)
423
- else if (!wanted) {
424
- console.log()
425
- console.log(sectionHeader('Permission Mode'))
426
- console.log()
427
- for (const [mode, about] of Object.entries(MODES)) {
428
- const modeColor = mode === 'yolo' ? HOT_PINK : mode === 'accept-edits' ? ORANGE : NEON_CYAN
429
- const active = mode === permissions.mode
430
- console.log(` ${active ? `${modeColor}●${RST}` : `${DARK_GRAY}○${RST}`} ${active ? `${modeColor}${BOLD}` : SOFT_GRAY}${mode}${RST} ${DARK_GRAY}${about}${RST}`)
431
- }
432
- console.log(`\n ${SOFT_GRAY}Change with /mode <mode>${RST}\n`)
433
- } else if (MODES[wanted]) {
434
- permissions.mode = wanted
435
- const modeColor = wanted === 'yolo' ? HOT_PINK : wanted === 'accept-edits' ? ORANGE : NEON_CYAN
436
- console.log(`${LIME}✓${RST} Mode: ${modeColor}${BOLD}${wanted}${RST} ${DARK_GRAY}(${MODES[wanted]})${RST}\n`)
437
- } else console.log(`${HOT_PINK}✗${RST} Unknown mode. Options: ${Object.keys(MODES).join(', ')}\n`)
438
- continue
439
- }
440
- if (lower === '/tools') {
441
- if (!agentMode) { console.log(` ${SOFT_GRAY}This is a chat-only session.${RST}\n`); continue }
442
- console.log()
443
- console.log(sectionHeader('Available Tools'))
444
- console.log()
445
- for (const tool of TOOLS) console.log(` ${LIME}${BOLD}${tool.name.padEnd(12)}${RST} ${SOFT_GRAY}${tool.description.split('\n')[0]}${RST}`)
446
- console.log(`\n ${DARK_GRAY}Commands run in ${BRIGHT_WHITE}${detectShell().label}${DARK_GRAY}.${RST}\n`)
447
- continue
448
- }
449
- if (lower === '/compact') {
450
- console.log(agent.compact() ? `${LIME}✓${RST} Dropped older tool output.\n` : ` ${SOFT_GRAY}Nothing to compact yet.${RST}\n`)
451
- continue
452
- }
453
- if (lower === '/init') {
454
- if (!agentMode) { console.log(` ${SOFT_GRAY}This is a chat-only session.${RST}\n`); continue }
455
- await send(INIT_PROMPT)
456
- continue
457
- }
458
- if (lower === '/libraries' || lower === '/libs') { printLibraries(activeLibraries); continue }
459
- if (command === '/library' || command === '/lib') {
460
- const id = rest[0]
461
- const lib = LIBRARIES.find(l => l.id === id)
462
- if (!lib) console.log(`${HOT_PINK}✗${RST} Unknown library "${id ?? ''}". Options: ${LIBRARIES.map(l => l.id).join(', ')}\n`)
463
- else if (activeLibraries.has(id)) {
464
- activeLibraries.delete(id)
465
- console.log(`${LIME}✓${RST} Disabled ${LIB_COLORS[id] ?? NEON_CYAN}${BOLD}${lib.label}${RST}\n`)
466
- } else {
467
- activeLibraries.add(id)
468
- console.log(`${LIME}✓${RST} Enabled ${LIB_COLORS[id] ?? NEON_CYAN}${BOLD}${lib.label}${RST}\n`)
469
- }
470
- continue
471
- }
472
- if (trimmed.startsWith('/') && !trimmed.includes(' ') && trimmed.length < 20) {
473
- console.log(`${HOT_PINK}✗${RST} Unknown command ${BRIGHT_WHITE}${trimmed}${RST}. Type /help for the list.\n`)
474
- continue
475
- }
476
- await send(input)
477
- }
478
- console.log(`${SOFT_GRAY} Bye.${RST}`)
479
- process.exit(0)
480
- }
1
+ import { emitKeypressEvents } from 'node:readline'
2
+ import { createInterface } from 'node:readline/promises'
3
+ import { homedir } from 'node:os'
4
+ import { get } from './api.mjs'
5
+ import { getToken } from './config.mjs'
6
+ import { Agent, MODES, Permissions } from './agent.mjs'
7
+ import { instructionFiles } from './context.mjs'
8
+ import { detectShell } from './shell.mjs'
9
+ import { TOOLS } from './tools.mjs'
10
+ import {
11
+ BOLD, DIM, RST, UNDERLINE,
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,
16
+ sectionHeader, statusBar, gradient, NOGUARD_GRADIENT, stripAnsi, termWidth,
17
+ creditMeter, tierPill, tierColor, sparkline,
18
+ } from './render.mjs'
19
+
20
+ const RESET_COMMANDS = new Set(['/clear', '/reset', '/new'])
21
+ const EXIT_COMMANDS = new Set(['/exit', '/quit', '/bye'])
22
+
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 }
26
+
27
+ const LIBRARIES = [
28
+ { id: 'cyber', label: 'Cipher · Cyber', summary: 'Exploits, offensive security, reverse engineering' },
29
+ { id: 'engineering', label: 'Forge · Engineering', summary: 'Software, systems and hardware engineering' },
30
+ { id: 'bio', label: 'Helix · Bio', summary: 'Pharmacology, substance data, harm reduction' },
31
+ { id: 'creative', label: 'Muse · Creative', summary: 'Uncensored creative writing and full artistic freedom' },
32
+ ]
33
+
34
+ const INIT_PROMPT = `Look through this project and write a NOGUARD.md file at the root of the working directory for future sessions to read. Cover, briefly:
35
+ - what the project is and how it is laid out (the main folders and entry points),
36
+ - the commands to install, build, run, lint and test it (check package.json, Makefiles, pyproject, Cargo.toml, CI config and so on),
37
+ - conventions a contributor must follow that are not obvious from a single file.
38
+ Keep it short and specific to this project. If a NOGUARD.md, CLAUDE.md or AGENTS.md already exists, improve on it rather than repeating it.`
39
+
40
+ function fmtNumber(n) {
41
+ return Number(n).toLocaleString('en-US')
42
+ }
43
+
44
+ function requireAuth() {
45
+ if (!getToken()) {
46
+ console.log(`${HOT_PINK}✗${RST} Not signed in. Run ${BOLD}noguard login${RST} first.`)
47
+ process.exit(1)
48
+ }
49
+ }
50
+
51
+ export function printModels(models, current = null) {
52
+ console.log()
53
+ console.log(sectionHeader('Available Models'))
54
+ console.log()
55
+ for (const model of models) {
56
+ const tierColor = TIER_COLORS[model.tier] ?? NEON_CYAN
57
+ const icon = TIER_ICONS[model.tier] ?? '●'
58
+ const tags = []
59
+ if (model.default_chat) tags.push(`${LIME}chat default${RST}`)
60
+ if (model.default_build) tags.push(`${LIME}agent default${RST}`)
61
+ if (model.default && !model.default_chat && !model.default_build) tags.push(`${LIME}default${RST}`)
62
+ const active = current && model.id === current ? ` ${ORANGE}← active${RST}` : ''
63
+ const tagStr = tags.length ? ` ${tags.join(` ${DARK_GRAY}·${RST} `)}` : ''
64
+ const cost = model.cost_indicator ?? '$'
65
+ console.log(` ${tierColor}${icon}${RST} ${tierColor}${BOLD}${model.display_name}${RST} ${SOFT_GRAY}${model.id}${RST} ${GOLD}${cost}${RST}${tagStr}${active}`)
66
+ if (model.description) console.log(` ${SOFT_GRAY}${model.description}${RST}`)
67
+ const caps = []
68
+ if (model.chat_eligible) caps.push('chat')
69
+ if (model.build_eligible && model.supports_tools !== false) caps.push('agent (files and commands)')
70
+ if (caps.length) console.log(` ${DARK_GRAY}Supports: ${caps.join(', ')} · Context: ${(model.context_window / 1000).toFixed(0)}k · Max output: ${(model.max_output_tokens / 1000).toFixed(0)}k${RST}`)
71
+ console.log()
72
+ }
73
+ }
74
+
75
+ function printLibraries(activeLibs) {
76
+ console.log()
77
+ console.log(sectionHeader('Research Libraries'))
78
+ console.log(` ${SOFT_GRAY}Toggle with /library <id> — active libraries inject curated sources into your questions.${RST}`)
79
+ console.log()
80
+ for (const lib of LIBRARIES) {
81
+ const active = activeLibs.has(lib.id)
82
+ const color = LIB_COLORS[lib.id] ?? NEON_CYAN
83
+ const mark = active ? `${color}●${RST}` : `${DARK_GRAY}○${RST}`
84
+ const label = active ? `${BOLD}${color}${lib.label}${RST}` : `${SOFT_GRAY}${lib.label}${RST}`
85
+ console.log(` ${mark} ${label} ${DARK_GRAY}(${lib.id})${RST}`)
86
+ console.log(` ${SOFT_GRAY}${lib.summary}${RST}`)
87
+ }
88
+ console.log()
89
+ }
90
+
91
+ function printHelp(agentMode) {
92
+ console.log()
93
+ console.log(sectionHeader('Commands'))
94
+ console.log()
95
+ const cmd = (name, desc) => console.log(` ${NEON_CYAN}${name.padEnd(22)}${RST} ${SOFT_GRAY}${desc}${RST}`)
96
+ cmd('/models', 'List all models with tier info')
97
+ cmd('/model <name>', 'Switch to a model (alias or display name)')
98
+ if (agentMode) {
99
+ cmd('/mode [mode]', 'Show or set permissions: ask, accept-edits, yolo')
100
+ cmd('/init', 'Write a NOGUARD.md describing this project')
101
+ cmd('/compact', 'Free context by dropping old tool output')
102
+ cmd('/tools', 'List the tools NoGuard can use')
103
+ cmd('/status', 'Show session info, credits, model, and stats')
104
+ }
105
+ cmd('/libraries, /libs', 'Show research libraries and their status')
106
+ cmd('/library <id>, /lib', 'Toggle a library on/off')
107
+ cmd('/clear, /reset, /new', 'Start a new conversation')
108
+ cmd('/credits', 'Show remaining credits')
109
+ cmd('/exit, /quit', 'Leave')
110
+ console.log()
111
+ console.log(sectionHeader('Keys'))
112
+ console.log()
113
+ const key = (name, desc) => console.log(` ${GOLD}${name.padEnd(22)}${RST} ${SOFT_GRAY}${desc}${RST}`)
114
+ key('Esc or Ctrl+C', 'Stop NoGuard mid-reply or mid-command')
115
+ key('Ctrl+C twice', 'Exit at the prompt')
116
+ key('End line with \\', 'Continue on the next line (pasting works too)')
117
+ key('Type """', 'Start/end a multi-line block')
118
+ console.log()
119
+ }
120
+
121
+ /** The model a session runs on: the one asked for if it can do the job, else the right default. */
122
+ export function pickModel(models, requested, agentMode) {
123
+ const usable = m => agentMode ? Boolean(m.build_eligible) && m.supports_tools !== false : m.chat_eligible !== false
124
+ if (requested) {
125
+ const name = requested.toLowerCase()
126
+ const match = models.find(m => m.id === requested || m.id === name || m.display_name.toLowerCase() === name)
127
+ if (!match) return { model: null, warning: `Model "${requested}" not found. Run /models to see options.` }
128
+ if (!usable(match)) return { model: null, warning: `${match.display_name} can't use tools, so it can't work on files. ${agentMode ? 'Pick a model marked "agent" in /models, or run noguard --no-tools to chat with it.' : ''}` }
129
+ return { model: match }
130
+ }
131
+ const model = agentMode
132
+ ? models.find(m => m.default_build && usable(m)) ?? models.find(usable)
133
+ : models.find(m => (m.default_chat || m.default) && usable(m)) ?? models.find(usable)
134
+ return { model: model ?? null }
135
+ }
136
+
137
+ async function loadModels() {
138
+ try {
139
+ const res = await get('/api/v1/models')
140
+ return res.data ?? []
141
+ } catch {
142
+ return []
143
+ }
144
+ }
145
+
146
+ function shortPath(path) {
147
+ const home = homedir()
148
+ return path.toLowerCase().startsWith(home.toLowerCase()) ? `~${path.slice(home.length)}` : path
149
+ }
150
+
151
+ function printBanner({ model, agentMode, cwd, permissions, account }) {
152
+ const w = termWidth()
153
+ const inner = Math.max(28, Math.min(w - 4, 68))
154
+ const row = (name, value) => console.log(` ${MUTED}${name.padEnd(9)}${RST} ${value}`)
155
+
156
+ console.log()
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}`)
160
+ console.log()
161
+
162
+ if (account) {
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 })}`)
169
+ }
170
+
171
+ const modelName = model?.display_name ?? 'default'
172
+ row('Model', `${tierColor(model?.tier)}${BOLD}${modelName}${RST} ${FAINT}(${model?.id ?? 'auto'})${RST}`)
173
+
174
+ if (agentMode) {
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}`)
178
+ const files = instructionFiles(cwd)
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}`)
181
+ } else {
182
+ row('Chat', `${MUTED}chat only — NoGuard can't see or change files in this session${RST}`)
183
+ }
184
+ console.log()
185
+ console.log(` ${FAINT}/help for commands · Esc to interrupt · Ctrl+C twice to exit${RST}`)
186
+ console.log()
187
+ }
188
+
189
+ /** `noguard -p "…"`: one task, no prompts, then exit. Edits and commands need --accept-edits or --yolo. */
190
+ /** Build (tools) comes with any credit pack; a free account chats. Says so once and returns whether tools stay on. */
191
+ function buildAllowed(account, wanted, log = console.log) {
192
+ if (!wanted || !account || account.tier === 'paid') return wanted
193
+ log(`${ORANGE}⚠${RST} Build mode (working on files and running commands) comes with any credit pack. This is a chat-only session.`)
194
+ log(` ${FAINT}Unlock Build, NoGuard Ultra and the desktop app: https://noguard.ai/credits${RST}`)
195
+ return false
196
+ }
197
+
198
+ export async function runOnce(opts) {
199
+ requireAuth()
200
+ const account = opts.tools !== false ? await get('/api/v1/me').catch(() => null) : null
201
+ const agentMode = buildAllowed(account, opts.tools !== false, line => console.error(line))
202
+ const models = await loadModels()
203
+ const { model, warning } = pickModel(models, opts.model, agentMode)
204
+ if (warning) { console.error(`${ORANGE}⚠${RST} ${warning}`); process.exit(1) }
205
+ const agent = new Agent({
206
+ cwd: process.cwd(),
207
+ ui: { interactive: false, ask: async () => null },
208
+ getModel: () => model,
209
+ permissions: new Permissions(opts.mode ?? 'ask'),
210
+ tools: agentMode,
211
+ })
212
+ const onInt = () => agent.busy ? agent.abort() : process.exit(130)
213
+ process.on('SIGINT', onInt)
214
+ const { ok, spent, balance } = await agent.send(opts.prompt)
215
+ if (process.stderr.isTTY && spent) process.stderr.write(`${SOFT_GRAY} ${spent} credits · ${balance ?? '?'} remaining${RST}\n`)
216
+ process.off('SIGINT', onInt)
217
+ process.exitCode = ok ? 0 : 1
218
+ }
219
+
220
+ export async function chat(opts = {}) {
221
+ requireAuth()
222
+ const cwd = process.cwd()
223
+ let agentMode = opts.tools !== false
224
+
225
+ const [availableModelsRaw, accountInfo] = await Promise.all([
226
+ loadModels(),
227
+ get('/api/v1/me').catch(() => null),
228
+ ])
229
+ let availableModels = availableModelsRaw
230
+ agentMode = buildAllowed(accountInfo, agentMode)
231
+
232
+ let { model: currentModel, warning } = pickModel(availableModels, opts.model, agentMode)
233
+ if (warning) {
234
+ console.log(`${ORANGE}⚠${RST} ${warning}`)
235
+ currentModel = pickModel(availableModels, null, agentMode).model
236
+ }
237
+ if (agentMode && availableModels.length && !currentModel) {
238
+ console.log(`${ORANGE}⚠${RST} No model that can work on files is available to you, so this is a chat-only session.`)
239
+ agentMode = false
240
+ currentModel = pickModel(availableModels, null, false).model
241
+ }
242
+
243
+ const permissions = new Permissions(opts.mode ?? 'ask')
244
+ const activeLibraries = new Set()
245
+ let credits = accountInfo?.credits ?? null
246
+ let available = accountInfo?.available ?? null
247
+
248
+ const sessionStart = Date.now()
249
+ let sessionMessages = 0
250
+ let sessionCredits = 0
251
+
252
+ const interactive = process.stdin.isTTY !== false
253
+ const rl = createInterface({ input: process.stdin, output: process.stdout, terminal: interactive, historySize: 500 })
254
+ const pasted = []
255
+ rl.on('line', line => pasted.push(line))
256
+ let asking = null
257
+ let lastInterrupt = 0
258
+
259
+ const ui = {
260
+ interactive: true,
261
+ async ask(question) {
262
+ asking = new AbortController()
263
+ try {
264
+ return await rl.question(question, { signal: asking.signal })
265
+ } catch {
266
+ return null
267
+ } finally {
268
+ asking = null
269
+ }
270
+ },
271
+ }
272
+
273
+ const agent = new Agent({
274
+ cwd,
275
+ ui,
276
+ getModel: () => currentModel,
277
+ permissions,
278
+ tools: agentMode,
279
+ getLibraries: () => [...activeLibraries],
280
+ })
281
+
282
+ rl.on('SIGINT', () => {
283
+ if (asking) { asking.abort(); agent.abort(); return }
284
+ if (agent.busy) { agent.abort(); return }
285
+ if (rl.line) { rl.write(null, { ctrl: true, name: 'u' }); return }
286
+ if (Date.now() - lastInterrupt < 2000) { console.log(`\n${SOFT_GRAY} Bye.${RST}`); process.exit(0) }
287
+ lastInterrupt = Date.now()
288
+ process.stdout.write(`\n${SOFT_GRAY} Press Ctrl+C again to exit.${RST}\n`)
289
+ rl.prompt()
290
+ })
291
+ rl.on('close', () => { console.log(`${SOFT_GRAY} Bye.${RST}`); process.exit(0) })
292
+ if (interactive) {
293
+ emitKeypressEvents(process.stdin, rl)
294
+ process.stdin.on('keypress', (_, key) => {
295
+ if (key?.name === 'escape' && agent.busy && !asking) agent.abort()
296
+ })
297
+ }
298
+
299
+ printBanner({ model: currentModel, agentMode, cwd, permissions, account: accountInfo })
300
+
301
+ function buildPrompt() {
302
+ const modelName = currentModel?.display_name ?? 'default'
303
+ const mColor = tierColor(currentModel?.tier)
304
+ const modeColor = permissions.mode === 'yolo' ? ROSE : permissions.mode === 'accept-edits' ? AMBER : CYAN
305
+ const low = credits !== null && credits < 100
306
+ const credStr = credits !== null ? fmtNumber(credits) : '?'
307
+ const sep = ` ${FAINT}│${RST} `
308
+ const segs = [
309
+ `${mColor}${BOLD}${modelName}${RST}${currentModel?.tier ? ` ${FAINT}${currentModel.tier}${RST}` : ''}`,
310
+ `${modeColor}${permissions.mode}${RST}`,
311
+ `${low ? ROSE : AMBER}${BOLD}${credStr}${RST} ${FAINT}cr${RST}`,
312
+ ]
313
+ const libs = [...activeLibraries]
314
+ if (libs.length) segs.push(`${CYAN}${libs.map(id => LIBRARIES.find(l => l.id === id)?.label.split(' · ')[0] ?? id).join(', ')} ●${RST}`)
315
+ if (agentMode) {
316
+ try {
317
+ const left = agent.contextUse().left
318
+ segs.push(`${DIMFG}${Math.round(left / 4000)}k${RST} ${FAINT}ctx${RST}`)
319
+ } catch { /* context estimate is best-effort */ }
320
+ }
321
+ return ` ${segs.join(sep)}\n ${CYAN}❯${RST} `
322
+ }
323
+
324
+ const more = `${DARK_GRAY} …${RST} `
325
+
326
+ async function readInput() {
327
+ pasted.length = 0
328
+ const first = await rl.question(buildPrompt())
329
+ if (interactive) await new Promise(r => setTimeout(r, 30))
330
+ const lines = [first, ...(interactive ? pasted.splice(0) : [])]
331
+ if (lines.length === 1 && lines[0].trim() === '"""') {
332
+ const block = []
333
+ for (;;) {
334
+ const line = await rl.question(more)
335
+ if (line.trim() === '"""') break
336
+ block.push(line)
337
+ }
338
+ return block.join('\n')
339
+ }
340
+ while (lines.at(-1).endsWith('\\')) {
341
+ lines[lines.length - 1] = lines.at(-1).slice(0, -1)
342
+ lines.push(await rl.question(more))
343
+ }
344
+ return lines.join('\n')
345
+ }
346
+
347
+ async function send(text) {
348
+ console.log()
349
+ const { spent, balance } = await agent.send(text)
350
+ if (balance != null) { credits = balance; available = balance }
351
+ if (spent) { sessionCredits += spent; sessionMessages++ }
352
+ console.log()
353
+ if (spent) {
354
+ console.log(statusBar([
355
+ ['used', `${spent} cr`, AMBER],
356
+ ['balance', `${fmtNumber(credits ?? '?')}`, credits !== null && credits < 100 ? ROSE : MINT],
357
+ ['model', currentModel?.display_name ?? 'default', tierColor(currentModel?.tier)],
358
+ ['mode', permissions.mode, permissions.mode === 'yolo' ? ROSE : permissions.mode === 'accept-edits' ? AMBER : CYAN],
359
+ ]))
360
+ }
361
+ console.log()
362
+ }
363
+
364
+ if (opts.prompt) await send(opts.prompt)
365
+
366
+ for (;;) {
367
+ let input
368
+ try {
369
+ input = await readInput()
370
+ } catch {
371
+ break
372
+ }
373
+ const trimmed = input.trim()
374
+ if (!trimmed) continue
375
+ const lower = trimmed.toLowerCase()
376
+ const [command, ...rest] = lower.split(/\s+/)
377
+ const arg = trimmed.split(/\s+/).slice(1).join(' ')
378
+
379
+ if (EXIT_COMMANDS.has(lower)) break
380
+ if (RESET_COMMANDS.has(lower)) {
381
+ agent.reset()
382
+ sessionMessages = 0; sessionCredits = 0
383
+ console.log(`${LIME}✓${RST} New conversation.\n`)
384
+ continue
385
+ }
386
+ if (lower === '/help' || lower === '/?') { printHelp(agentMode); continue }
387
+ if (lower === '/status') {
388
+ console.log()
389
+ console.log(sectionHeader('Session'))
390
+ console.log()
391
+ const row = (name, value) => console.log(` ${MUTED}${name.padEnd(10)}${RST} ${value}`)
392
+ const elapsed = Math.floor((Date.now() - sessionStart) / 60000)
393
+ const modeColor = permissions.mode === 'yolo' ? ROSE : permissions.mode === 'accept-edits' ? AMBER : CYAN
394
+ if (accountInfo) row('Account', `${FG_STRONG}${BOLD}${accountInfo.display_name || accountInfo.email.split('@')[0]}${RST} ${tierPill(accountInfo.tier)} ${MUTED}${accountInfo.email}${RST}`)
395
+ row('Model', `${tierColor(currentModel?.tier)}${BOLD}${currentModel?.display_name ?? 'default'}${RST} ${FAINT}(${currentModel?.id ?? 'auto'})${RST}`)
396
+ row('Mode', `${modeColor}${BOLD}${permissions.mode}${RST}`)
397
+ row('Folder', `${SKY}${shortPath(cwd)}${RST}`)
398
+ row('Shell', `${DIMFG}${detectShell().label}${RST}`)
399
+ if (credits !== null) {
400
+ const low = credits < 100
401
+ row('Credits', `${low ? ROSE : AMBER}${BOLD}${fmtNumber(available ?? credits)}${RST} ${MUTED}available${RST} ${FAINT}of ${fmtNumber(credits)}${RST} ${creditMeter(available ?? credits, credits, { low })}`)
402
+ }
403
+ const libs = [...activeLibraries]
404
+ if (libs.length) row('Libraries', libs.map(id => `${LIB_COLORS[id] ?? CYAN}${id}${RST}`).join(', '))
405
+ console.log(` ${LINE}${'─'.repeat(Math.max(10, Math.min(termWidth() - 4, 58)))}${RST}`)
406
+ 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}`)
407
+ console.log()
408
+ continue
409
+ }
410
+ if (lower === '/credits') {
411
+ console.log()
412
+ console.log(sectionHeader('Credits'))
413
+ console.log()
414
+ try {
415
+ const me = await get('/api/v1/me')
416
+ credits = me.credits; available = me.available
417
+ const low = me.low_balance || me.available < 100
418
+ const row = (name, value) => console.log(` ${MUTED}${name.padEnd(10)}${RST} ${value}`)
419
+ row('Balance', `${AMBER}${BOLD}${fmtNumber(me.credits)}${RST}`)
420
+ row('Available', `${low ? ROSE : AMBER}${BOLD}${fmtNumber(me.available)}${RST} ${creditMeter(me.available, me.credits, { low })}`)
421
+ const held = Math.max(0, me.credits - me.available)
422
+ if (held) row('On hold', `${MUTED}${fmtNumber(held)}${RST}`)
423
+ if (sessionCredits) row('This run', `${IRIS}${BOLD}${fmtNumber(sessionCredits)}${RST} ${MUTED}spent${RST}`)
424
+ try {
425
+ const usage = await get('/api/v1/usage?days=14')
426
+ const byDay = new Map((usage.days ?? []).map(d => [d.day, d.credits]))
427
+ if (byDay.size) {
428
+ const arr = []
429
+ const now = new Date()
430
+ for (let i = 13; i >= 0; i--) {
431
+ const dt = new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate() - i))
432
+ arr.push(byDay.get(dt.toISOString().slice(0, 10)) ?? 0)
433
+ }
434
+ const total = arr.reduce((a, b) => a + b, 0)
435
+ console.log()
436
+ console.log(` ${MUTED}credits / day${RST} ${FAINT}· last 14 days · ${fmtNumber(total)} total${RST}`)
437
+ console.log(` ${sparkline(arr)} ${FAINT}today${RST} ${AMBER}${BOLD}${fmtNumber(arr.at(-1))}${RST}`)
438
+ }
439
+ } catch { /* usage sparkline is best-effort */ }
440
+ console.log()
441
+ console.log(` ${FAINT}top up at${RST} ${SKY}${UNDERLINE}https://noguard.ai/credits${RST}`)
442
+ } catch {
443
+ if (credits !== null) console.log(` ${AMBER}${fmtNumber(credits)}${RST} credits remaining.`)
444
+ else console.log(` ${MUTED}Could not load your balance.${RST}`)
445
+ }
446
+ console.log()
447
+ continue
448
+ }
449
+ if (lower === '/models') {
450
+ if (!availableModels.length) availableModels = await loadModels()
451
+ if (availableModels.length) printModels(availableModels, currentModel?.id)
452
+ else console.log(` ${SOFT_GRAY}Could not load the model list.${RST}\n`)
453
+ continue
454
+ }
455
+ if (command === '/model') {
456
+ if (!arg) { console.log(` ${SOFT_GRAY}Usage: /model <alias or name>${RST}\n`); continue }
457
+ const picked = pickModel(availableModels, arg, agentMode)
458
+ if (picked.model) {
459
+ currentModel = picked.model
460
+ const tierColor = TIER_COLORS[currentModel.tier] ?? NEON_CYAN
461
+ console.log(`${LIME}✓${RST} Switched to ${tierColor}${BOLD}${currentModel.display_name}${RST} ${DARK_GRAY}(${currentModel.id})${RST}\n`)
462
+ } else console.log(`${HOT_PINK}✗${RST} ${picked.warning}\n`)
463
+ continue
464
+ }
465
+ if (command === '/mode' || command === '/permissions') {
466
+ const wanted = rest[0] === 'edits' ? 'accept-edits' : rest[0]
467
+ if (!agentMode) console.log(` ${SOFT_GRAY}This is a chat-only session.${RST}\n`)
468
+ else if (!wanted) {
469
+ console.log()
470
+ console.log(sectionHeader('Permission Mode'))
471
+ console.log()
472
+ for (const [mode, about] of Object.entries(MODES)) {
473
+ const modeColor = mode === 'yolo' ? HOT_PINK : mode === 'accept-edits' ? ORANGE : NEON_CYAN
474
+ const active = mode === permissions.mode
475
+ console.log(` ${active ? `${modeColor}●${RST}` : `${DARK_GRAY}○${RST}`} ${active ? `${modeColor}${BOLD}` : SOFT_GRAY}${mode}${RST} ${DARK_GRAY}${about}${RST}`)
476
+ }
477
+ console.log(`\n ${SOFT_GRAY}Change with /mode <mode>${RST}\n`)
478
+ } else if (MODES[wanted]) {
479
+ permissions.mode = wanted
480
+ const modeColor = wanted === 'yolo' ? HOT_PINK : wanted === 'accept-edits' ? ORANGE : NEON_CYAN
481
+ console.log(`${LIME}✓${RST} Mode: ${modeColor}${BOLD}${wanted}${RST} ${DARK_GRAY}(${MODES[wanted]})${RST}\n`)
482
+ } else console.log(`${HOT_PINK}✗${RST} Unknown mode. Options: ${Object.keys(MODES).join(', ')}\n`)
483
+ continue
484
+ }
485
+ if (lower === '/tools') {
486
+ if (!agentMode) { console.log(` ${SOFT_GRAY}This is a chat-only session.${RST}\n`); continue }
487
+ console.log()
488
+ console.log(sectionHeader('Available Tools'))
489
+ console.log()
490
+ for (const tool of TOOLS) console.log(` ${LIME}${BOLD}${tool.name.padEnd(12)}${RST} ${SOFT_GRAY}${tool.description.split('\n')[0]}${RST}`)
491
+ console.log(`\n ${DARK_GRAY}Commands run in ${BRIGHT_WHITE}${detectShell().label}${DARK_GRAY}.${RST}\n`)
492
+ continue
493
+ }
494
+ if (lower === '/compact') {
495
+ console.log(agent.compact() ? `${LIME}✓${RST} Dropped older tool output.\n` : ` ${SOFT_GRAY}Nothing to compact yet.${RST}\n`)
496
+ continue
497
+ }
498
+ if (lower === '/init') {
499
+ if (!agentMode) { console.log(` ${SOFT_GRAY}This is a chat-only session.${RST}\n`); continue }
500
+ await send(INIT_PROMPT)
501
+ continue
502
+ }
503
+ if (lower === '/libraries' || lower === '/libs') { printLibraries(activeLibraries); continue }
504
+ if (command === '/library' || command === '/lib') {
505
+ const id = rest[0]
506
+ const lib = LIBRARIES.find(l => l.id === id)
507
+ if (!lib) console.log(`${HOT_PINK}✗${RST} Unknown library "${id ?? ''}". Options: ${LIBRARIES.map(l => l.id).join(', ')}\n`)
508
+ else if (activeLibraries.has(id)) {
509
+ activeLibraries.delete(id)
510
+ console.log(`${LIME}✓${RST} Disabled ${LIB_COLORS[id] ?? NEON_CYAN}${BOLD}${lib.label}${RST}\n`)
511
+ } else {
512
+ activeLibraries.add(id)
513
+ console.log(`${LIME}✓${RST} Enabled ${LIB_COLORS[id] ?? NEON_CYAN}${BOLD}${lib.label}${RST}\n`)
514
+ }
515
+ continue
516
+ }
517
+ if (trimmed.startsWith('/') && !trimmed.includes(' ') && trimmed.length < 20) {
518
+ console.log(`${HOT_PINK}✗${RST} Unknown command ${BRIGHT_WHITE}${trimmed}${RST}. Type /help for the list.\n`)
519
+ continue
520
+ }
521
+ await send(input)
522
+ }
523
+ console.log(`${SOFT_GRAY} Bye.${RST}`)
524
+ process.exit(0)
525
+ }