noguard 1.1.0 โ†’ 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/chat.mjs CHANGED
@@ -1,377 +1,515 @@
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 { BOLD, CYAN, DIM, GREEN, RED, RST, YELLOW } from './render.mjs'
11
-
12
- const RESET_COMMANDS = new Set(['/clear', '/reset', '/new'])
13
- const EXIT_COMMANDS = new Set(['/exit', '/quit', '/bye'])
14
-
15
- const TIER_COLORS = { ultra: '\x1b[33m', standard: '\x1b[36m', pro: '\x1b[32m', raw: '\x1b[35m' }
16
- const TIER_ICONS = { ultra: '๐Ÿ’Ž', standard: 'โšก', pro: '๐Ÿ”ฅ', raw: '๐Ÿ—ก๏ธ' }
17
-
18
- const LIBRARIES = [
19
- { id: 'cyber', label: 'Cipher ยท Cyber', summary: 'Exploits, offensive security, reverse engineering' },
20
- { id: 'engineering', label: 'Forge ยท Engineering', summary: 'Software, systems and hardware engineering' },
21
- { id: 'bio', label: 'Helix ยท Bio', summary: 'Pharmacology, substance data, harm reduction' },
22
- { id: 'creative', label: 'Muse ยท Creative', summary: 'Uncensored creative writing and full artistic freedom' },
23
- ]
24
-
25
- 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:
26
- - what the project is and how it is laid out (the main folders and entry points),
27
- - the commands to install, build, run, lint and test it (check package.json, Makefiles, pyproject, Cargo.toml, CI config and so on),
28
- - conventions a contributor must follow that are not obvious from a single file.
29
- 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.`
30
-
31
- function requireAuth() {
32
- if (!getToken()) {
33
- console.log(`${RED}โœ—${RST} Not signed in. Run ${BOLD}noguard login${RST} first.`)
34
- process.exit(1)
35
- }
36
- }
37
-
38
- export function printModels(models, current = null) {
39
- console.log()
40
- console.log(` ${BOLD}Available models${RST}`)
41
- console.log()
42
- for (const model of models) {
43
- const tierColor = TIER_COLORS[model.tier] ?? CYAN
44
- const icon = TIER_ICONS[model.tier] ?? '๐Ÿค–'
45
- const tags = []
46
- if (model.default_chat) tags.push(`${GREEN}chat default${RST}`)
47
- if (model.default_build) tags.push(`${GREEN}agent default${RST}`)
48
- if (model.default && !model.default_chat && !model.default_build) tags.push(`${GREEN}default${RST}`)
49
- const active = current && model.id === current ? ` ${YELLOW}โ† active${RST}` : ''
50
- const tagStr = tags.length ? ` ${tags.join(' ยท ')}` : ''
51
- const cost = model.cost_indicator ?? '$'
52
- console.log(` ${icon} ${tierColor}${BOLD}${model.display_name}${RST} ${DIM}${model.id}${RST} ${GREEN}${cost}${RST}${tagStr}${active}`)
53
- if (model.description) console.log(` ${DIM}${model.description}${RST}`)
54
- const caps = []
55
- if (model.chat_eligible) caps.push('chat')
56
- if (model.build_eligible && model.supports_tools !== false) caps.push('agent (files and commands)')
57
- if (caps.length) console.log(` ${DIM}Supports: ${caps.join(', ')} ยท Context: ${(model.context_window / 1000).toFixed(0)}k ยท Max output: ${(model.max_output_tokens / 1000).toFixed(0)}k${RST}`)
58
- console.log()
59
- }
60
- }
61
-
62
- function printLibraries(activeLibs) {
63
- console.log()
64
- console.log(` ${BOLD}Research libraries${RST}`)
65
- console.log(` ${DIM}Toggle with /library <id> โ€” active libraries inject curated sources into your questions.${RST}`)
66
- console.log()
67
- for (const lib of LIBRARIES) {
68
- const active = activeLibs.has(lib.id)
69
- const mark = active ? `${GREEN}โ—${RST}` : `${DIM}โ—‹${RST}`
70
- const label = active ? `${BOLD}${lib.label}${RST}` : `${DIM}${lib.label}${RST}`
71
- console.log(` ${mark} ${label} ${DIM}(${lib.id})${RST}`)
72
- console.log(` ${DIM}${lib.summary}${RST}`)
73
- }
74
- console.log()
75
- }
76
-
77
- function printHelp(agentMode) {
78
- console.log()
79
- console.log(` ${BOLD}Commands${RST}`)
80
- console.log(` /models โ€” List all models with tier info`)
81
- console.log(` /model <name> โ€” Switch to a model (alias or display name)`)
82
- if (agentMode) {
83
- console.log(` /mode [mode] โ€” Show or set permissions: ask, accept-edits, yolo`)
84
- console.log(` /init โ€” Write a NOGUARD.md describing this project`)
85
- console.log(` /compact โ€” Free context by dropping old tool output`)
86
- console.log(` /tools โ€” List the tools NoGuard can use`)
87
- }
88
- console.log(` /libraries, /libs โ€” Show research libraries and their status`)
89
- console.log(` /library <id>, /lib โ€” Toggle a library on/off`)
90
- console.log(` /clear, /reset, /new โ€” Start a new conversation`)
91
- console.log(` /credits โ€” Show remaining credits`)
92
- console.log(` /exit, /quit โ€” Leave`)
93
- console.log()
94
- console.log(` ${BOLD}Keys${RST}`)
95
- console.log(` Esc or Ctrl+C โ€” Stop NoGuard mid-reply or mid-command`)
96
- console.log(` Ctrl+C twice โ€” Exit at the prompt`)
97
- console.log(` End a line with \\ โ€” Continue on the next line (pasting multiple lines also works)`)
98
- console.log(` Type """ โ€” Start/end a multi-line block`)
99
- console.log()
100
- }
101
-
102
- /** The model a session runs on: the one asked for if it can do the job, else the right default. */
103
- export function pickModel(models, requested, agentMode) {
104
- const usable = m => agentMode ? Boolean(m.build_eligible) && m.supports_tools !== false : m.chat_eligible !== false
105
- if (requested) {
106
- const name = requested.toLowerCase()
107
- const match = models.find(m => m.id === requested || m.id === name || m.display_name.toLowerCase() === name)
108
- if (!match) return { model: null, warning: `Model "${requested}" not found. Run /models to see options.` }
109
- 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.' : ''}` }
110
- return { model: match }
111
- }
112
- const model = agentMode
113
- ? models.find(m => m.default_build && usable(m)) ?? models.find(usable)
114
- : models.find(m => (m.default_chat || m.default) && usable(m)) ?? models.find(usable)
115
- return { model: model ?? null }
116
- }
117
-
118
- async function loadModels() {
119
- try {
120
- const res = await get('/api/v1/models')
121
- return res.data ?? []
122
- } catch {
123
- return []
124
- }
125
- }
126
-
127
- function shortPath(path) {
128
- const home = homedir()
129
- return path.toLowerCase().startsWith(home.toLowerCase()) ? `~${path.slice(home.length)}` : path
130
- }
131
-
132
- function printBanner({ model, agentMode, cwd, permissions }) {
133
- console.log()
134
- console.log(`${BOLD} โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”“${RST}`)
135
- console.log(`${BOLD} โ”ƒ NoGuard AI โ€” CLI โ”ƒ${RST}`)
136
- console.log(`${BOLD} โ”ƒ The AI that doesn't say no. โ”ƒ${RST}`)
137
- console.log(`${BOLD} โ”—โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”›${RST}`)
138
- console.log()
139
- console.log(` ${DIM}Model:${RST} ${BOLD}${model?.display_name ?? 'default'}${RST}`)
140
- if (agentMode) {
141
- console.log(` ${DIM}Folder:${RST} ${shortPath(cwd)}`)
142
- console.log(` ${DIM}Mode:${RST} ${permissions.mode} ${DIM}(${MODES[permissions.mode]} ยท /mode to change)${RST}`)
143
- const files = instructionFiles(cwd)
144
- if (files.length) console.log(` ${DIM}Project: ${files.map(shortPath).join(', ')}${RST}`)
145
- if (cwd === homedir()) console.log(` ${YELLOW}โš ${RST} ${DIM}You're in your home folder. Start noguard inside a project folder to work on it.${RST}`)
146
- } else {
147
- console.log(` ${DIM}Chat only: NoGuard can't see or change files in this session.${RST}`)
148
- }
149
- console.log(` ${DIM}/help for commands ยท Esc to interrupt${RST}`)
150
- console.log()
151
- }
152
-
153
- function creditsLine(spent, credits) {
154
- if (spent > 0) console.log(`${DIM} ${spent} credits ยท ${credits ?? '?'} remaining${RST}`)
155
- }
156
-
157
- /** `noguard -p "โ€ฆ"`: one task, no prompts, then exit. Edits and commands need --accept-edits or --yolo. */
158
- export async function runOnce(opts) {
159
- requireAuth()
160
- const agentMode = opts.tools !== false
161
- const models = await loadModels()
162
- const { model, warning } = pickModel(models, opts.model, agentMode)
163
- if (warning) { console.error(`${YELLOW}โš ${RST} ${warning}`); process.exit(1) }
164
- const agent = new Agent({
165
- cwd: process.cwd(),
166
- ui: { interactive: false, ask: async () => null },
167
- getModel: () => model,
168
- permissions: new Permissions(opts.mode ?? 'ask'),
169
- tools: agentMode,
170
- })
171
- const onInt = () => agent.busy ? agent.abort() : process.exit(130)
172
- process.on('SIGINT', onInt)
173
- const { ok, spent, balance } = await agent.send(opts.prompt)
174
- if (process.stderr.isTTY && spent) process.stderr.write(`${DIM} ${spent} credits ยท ${balance ?? '?'} remaining${RST}\n`)
175
- // Let the process end on its own: process.exit() while sockets close can trip a libuv assertion on Windows.
176
- process.off('SIGINT', onInt)
177
- process.exitCode = ok ? 0 : 1
178
- }
179
-
180
- export async function chat(opts = {}) {
181
- requireAuth()
182
- const cwd = process.cwd()
183
- let agentMode = opts.tools !== false
184
- let availableModels = await loadModels()
185
-
186
- let { model: currentModel, warning } = pickModel(availableModels, opts.model, agentMode)
187
- if (warning) {
188
- console.log(`${YELLOW}โš ${RST} ${warning}`)
189
- currentModel = pickModel(availableModels, null, agentMode).model
190
- }
191
- if (agentMode && availableModels.length && !currentModel) {
192
- console.log(`${YELLOW}โš ${RST} No model that can work on files is available to you, so this is a chat-only session.`)
193
- agentMode = false
194
- currentModel = pickModel(availableModels, null, false).model
195
- }
196
-
197
- const permissions = new Permissions(opts.mode ?? 'ask')
198
- const activeLibraries = new Set()
199
- let credits = null
200
-
201
- const interactive = process.stdin.isTTY !== false
202
- const rl = createInterface({ input: process.stdin, output: process.stdout, terminal: interactive, historySize: 500 })
203
- const pasted = []
204
- rl.on('line', line => pasted.push(line))
205
- let asking = null
206
- let lastInterrupt = 0
207
-
208
- const ui = {
209
- interactive: true,
210
- async ask(question) {
211
- asking = new AbortController()
212
- try {
213
- return await rl.question(question, { signal: asking.signal })
214
- } catch {
215
- return null
216
- } finally {
217
- asking = null
218
- }
219
- },
220
- }
221
-
222
- const agent = new Agent({
223
- cwd,
224
- ui,
225
- getModel: () => currentModel,
226
- permissions,
227
- tools: agentMode,
228
- getLibraries: () => [...activeLibraries],
229
- })
230
-
231
- rl.on('SIGINT', () => {
232
- if (asking) { asking.abort(); agent.abort(); return }
233
- if (agent.busy) { agent.abort(); return }
234
- if (rl.line) { rl.write(null, { ctrl: true, name: 'u' }); return }
235
- if (Date.now() - lastInterrupt < 2000) { console.log(`\n${DIM} Bye.${RST}`); process.exit(0) }
236
- lastInterrupt = Date.now()
237
- process.stdout.write(`\n${DIM} Press Ctrl+C again to exit.${RST}\n`)
238
- rl.prompt()
239
- })
240
- rl.on('close', () => { console.log(`${DIM} Bye.${RST}`); process.exit(0) })
241
- if (interactive) {
242
- emitKeypressEvents(process.stdin, rl)
243
- process.stdin.on('keypress', (_, key) => {
244
- if (key?.name === 'escape' && agent.busy && !asking) agent.abort()
245
- })
246
- }
247
-
248
- printBanner({ model: currentModel, agentMode, cwd, permissions })
249
-
250
- const prompt = `${CYAN}โฏ${RST} `
251
- const more = `${DIM}โ€ฆ${RST} `
252
-
253
- async function readInput() {
254
- pasted.length = 0
255
- const first = await rl.question(prompt)
256
- // A multi-line paste arrives as several lines at once: gather the rest of the burst.
257
- if (interactive) await new Promise(r => setTimeout(r, 30))
258
- const lines = [first, ...(interactive ? pasted.splice(0) : [])]
259
- if (lines.length === 1 && lines[0].trim() === '"""') {
260
- const block = []
261
- for (;;) {
262
- const line = await rl.question(more)
263
- if (line.trim() === '"""') break
264
- block.push(line)
265
- }
266
- return block.join('\n')
267
- }
268
- while (lines.at(-1).endsWith('\\')) {
269
- lines[lines.length - 1] = lines.at(-1).slice(0, -1)
270
- lines.push(await rl.question(more))
271
- }
272
- return lines.join('\n')
273
- }
274
-
275
- async function send(text) {
276
- console.log()
277
- const { spent, balance } = await agent.send(text)
278
- if (balance != null) credits = balance
279
- console.log()
280
- creditsLine(spent, credits)
281
- if (spent) console.log()
282
- }
283
-
284
- if (opts.prompt) await send(opts.prompt)
285
-
286
- for (;;) {
287
- let input
288
- try {
289
- input = await readInput()
290
- } catch {
291
- break
292
- }
293
- const trimmed = input.trim()
294
- if (!trimmed) continue
295
- const lower = trimmed.toLowerCase()
296
- const [command, ...rest] = lower.split(/\s+/)
297
- const arg = trimmed.split(/\s+/).slice(1).join(' ')
298
-
299
- if (EXIT_COMMANDS.has(lower)) break
300
- if (RESET_COMMANDS.has(lower)) {
301
- agent.reset()
302
- console.log(`${GREEN}โœ“${RST} New conversation.\n`)
303
- continue
304
- }
305
- if (lower === '/help' || lower === '/?') { printHelp(agentMode); continue }
306
- if (lower === '/credits') {
307
- try {
308
- const me = await get('/api/v1/me')
309
- credits = me.credits
310
- console.log(` ${YELLOW}${me.credits}${RST} credits (${me.available} available).\n`)
311
- } catch {
312
- console.log(credits !== null ? ` ${YELLOW}${credits}${RST} credits remaining.\n` : ` ${DIM}Could not load your balance.${RST}\n`)
313
- }
314
- continue
315
- }
316
- if (lower === '/models') {
317
- if (!availableModels.length) availableModels = await loadModels()
318
- if (availableModels.length) printModels(availableModels, currentModel?.id)
319
- else console.log(` ${DIM}Could not load the model list.${RST}\n`)
320
- continue
321
- }
322
- if (command === '/model') {
323
- if (!arg) { console.log(` ${DIM}Usage: /model <alias or name>${RST}\n`); continue }
324
- const picked = pickModel(availableModels, arg, agentMode)
325
- if (picked.model) {
326
- currentModel = picked.model
327
- console.log(`${GREEN}โœ“${RST} Switched to ${BOLD}${currentModel.display_name}${RST} (${currentModel.id})\n`)
328
- } else console.log(`${RED}โœ—${RST} ${picked.warning}\n`)
329
- continue
330
- }
331
- if (command === '/mode' || command === '/permissions') {
332
- const wanted = rest[0] === 'edits' ? 'accept-edits' : rest[0]
333
- if (!agentMode) console.log(` ${DIM}This is a chat-only session.${RST}\n`)
334
- else if (!wanted) {
335
- for (const [mode, about] of Object.entries(MODES)) console.log(` ${mode === permissions.mode ? `${GREEN}โ—${RST}` : `${DIM}โ—‹${RST}`} ${BOLD}${mode}${RST} ${DIM}${about}${RST}`)
336
- console.log(`\n ${DIM}Change with /mode <mode>${RST}\n`)
337
- } else if (MODES[wanted]) {
338
- permissions.mode = wanted
339
- console.log(`${GREEN}โœ“${RST} Mode: ${BOLD}${wanted}${RST} ${DIM}(${MODES[wanted]})${RST}\n`)
340
- } else console.log(`${RED}โœ—${RST} Unknown mode. Options: ${Object.keys(MODES).join(', ')}\n`)
341
- continue
342
- }
343
- if (lower === '/tools') {
344
- if (!agentMode) { console.log(` ${DIM}This is a chat-only session.${RST}\n`); continue }
345
- console.log()
346
- for (const tool of TOOLS) console.log(` ${BOLD}${tool.name.padEnd(10)}${RST} ${DIM}${tool.description.split('\n')[0]}${RST}`)
347
- console.log(`\n ${DIM}Commands run in ${detectShell().label}.${RST}\n`)
348
- continue
349
- }
350
- if (lower === '/compact') {
351
- console.log(agent.compact() ? `${GREEN}โœ“${RST} Dropped older tool output.\n` : ` ${DIM}Nothing to compact yet.${RST}\n`)
352
- continue
353
- }
354
- if (lower === '/init') {
355
- if (!agentMode) { console.log(` ${DIM}This is a chat-only session.${RST}\n`); continue }
356
- await send(INIT_PROMPT)
357
- continue
358
- }
359
- if (lower === '/libraries' || lower === '/libs') { printLibraries(activeLibraries); continue }
360
- if (command === '/library' || command === '/lib') {
361
- const id = rest[0]
362
- const lib = LIBRARIES.find(l => l.id === id)
363
- if (!lib) console.log(`${RED}โœ—${RST} Unknown library "${id ?? ''}". Options: ${LIBRARIES.map(l => l.id).join(', ')}\n`)
364
- else if (activeLibraries.has(id)) { activeLibraries.delete(id); console.log(`${GREEN}โœ“${RST} Disabled ${BOLD}${lib.label}${RST}\n`) }
365
- else { activeLibraries.add(id); console.log(`${GREEN}โœ“${RST} Enabled ${BOLD}${lib.label}${RST}\n`) }
366
- continue
367
- }
368
- if (trimmed.startsWith('/') && !trimmed.includes(' ') && trimmed.length < 20) {
369
- console.log(`${RED}โœ—${RST} Unknown command ${trimmed}. Type /help for the list.\n`)
370
- continue
371
- }
372
- await send(input)
373
- }
374
- console.log(`${DIM} Bye.${RST}`)
375
- process.exit(0)
376
- }
377
-
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
+ export async function runOnce(opts) {
191
+ requireAuth()
192
+ const agentMode = opts.tools !== false
193
+ const models = await loadModels()
194
+ const { model, warning } = pickModel(models, opts.model, agentMode)
195
+ if (warning) { console.error(`${ORANGE}โš ${RST} ${warning}`); process.exit(1) }
196
+ const agent = new Agent({
197
+ cwd: process.cwd(),
198
+ ui: { interactive: false, ask: async () => null },
199
+ getModel: () => model,
200
+ permissions: new Permissions(opts.mode ?? 'ask'),
201
+ tools: agentMode,
202
+ })
203
+ const onInt = () => agent.busy ? agent.abort() : process.exit(130)
204
+ process.on('SIGINT', onInt)
205
+ const { ok, spent, balance } = await agent.send(opts.prompt)
206
+ if (process.stderr.isTTY && spent) process.stderr.write(`${SOFT_GRAY} ${spent} credits ยท ${balance ?? '?'} remaining${RST}\n`)
207
+ process.off('SIGINT', onInt)
208
+ process.exitCode = ok ? 0 : 1
209
+ }
210
+
211
+ export async function chat(opts = {}) {
212
+ requireAuth()
213
+ const cwd = process.cwd()
214
+ let agentMode = opts.tools !== false
215
+
216
+ const [availableModelsRaw, accountInfo] = await Promise.all([
217
+ loadModels(),
218
+ get('/api/v1/me').catch(() => null),
219
+ ])
220
+ let availableModels = availableModelsRaw
221
+
222
+ let { model: currentModel, warning } = pickModel(availableModels, opts.model, agentMode)
223
+ if (warning) {
224
+ console.log(`${ORANGE}โš ${RST} ${warning}`)
225
+ currentModel = pickModel(availableModels, null, agentMode).model
226
+ }
227
+ if (agentMode && availableModels.length && !currentModel) {
228
+ console.log(`${ORANGE}โš ${RST} No model that can work on files is available to you, so this is a chat-only session.`)
229
+ agentMode = false
230
+ currentModel = pickModel(availableModels, null, false).model
231
+ }
232
+
233
+ const permissions = new Permissions(opts.mode ?? 'ask')
234
+ const activeLibraries = new Set()
235
+ let credits = accountInfo?.credits ?? null
236
+ let available = accountInfo?.available ?? null
237
+
238
+ const sessionStart = Date.now()
239
+ let sessionMessages = 0
240
+ let sessionCredits = 0
241
+
242
+ const interactive = process.stdin.isTTY !== false
243
+ const rl = createInterface({ input: process.stdin, output: process.stdout, terminal: interactive, historySize: 500 })
244
+ const pasted = []
245
+ rl.on('line', line => pasted.push(line))
246
+ let asking = null
247
+ let lastInterrupt = 0
248
+
249
+ const ui = {
250
+ interactive: true,
251
+ async ask(question) {
252
+ asking = new AbortController()
253
+ try {
254
+ return await rl.question(question, { signal: asking.signal })
255
+ } catch {
256
+ return null
257
+ } finally {
258
+ asking = null
259
+ }
260
+ },
261
+ }
262
+
263
+ const agent = new Agent({
264
+ cwd,
265
+ ui,
266
+ getModel: () => currentModel,
267
+ permissions,
268
+ tools: agentMode,
269
+ getLibraries: () => [...activeLibraries],
270
+ })
271
+
272
+ rl.on('SIGINT', () => {
273
+ if (asking) { asking.abort(); agent.abort(); return }
274
+ if (agent.busy) { agent.abort(); return }
275
+ if (rl.line) { rl.write(null, { ctrl: true, name: 'u' }); return }
276
+ if (Date.now() - lastInterrupt < 2000) { console.log(`\n${SOFT_GRAY} Bye.${RST}`); process.exit(0) }
277
+ lastInterrupt = Date.now()
278
+ process.stdout.write(`\n${SOFT_GRAY} Press Ctrl+C again to exit.${RST}\n`)
279
+ rl.prompt()
280
+ })
281
+ rl.on('close', () => { console.log(`${SOFT_GRAY} Bye.${RST}`); process.exit(0) })
282
+ if (interactive) {
283
+ emitKeypressEvents(process.stdin, rl)
284
+ process.stdin.on('keypress', (_, key) => {
285
+ if (key?.name === 'escape' && agent.busy && !asking) agent.abort()
286
+ })
287
+ }
288
+
289
+ printBanner({ model: currentModel, agentMode, cwd, permissions, account: accountInfo })
290
+
291
+ function buildPrompt() {
292
+ const modelName = currentModel?.display_name ?? 'default'
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
296
+ const credStr = credits !== null ? fmtNumber(credits) : '?'
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} `
312
+ }
313
+
314
+ const more = `${DARK_GRAY} โ€ฆ${RST} `
315
+
316
+ async function readInput() {
317
+ pasted.length = 0
318
+ const first = await rl.question(buildPrompt())
319
+ if (interactive) await new Promise(r => setTimeout(r, 30))
320
+ const lines = [first, ...(interactive ? pasted.splice(0) : [])]
321
+ if (lines.length === 1 && lines[0].trim() === '"""') {
322
+ const block = []
323
+ for (;;) {
324
+ const line = await rl.question(more)
325
+ if (line.trim() === '"""') break
326
+ block.push(line)
327
+ }
328
+ return block.join('\n')
329
+ }
330
+ while (lines.at(-1).endsWith('\\')) {
331
+ lines[lines.length - 1] = lines.at(-1).slice(0, -1)
332
+ lines.push(await rl.question(more))
333
+ }
334
+ return lines.join('\n')
335
+ }
336
+
337
+ async function send(text) {
338
+ console.log()
339
+ const { spent, balance } = await agent.send(text)
340
+ if (balance != null) { credits = balance; available = balance }
341
+ if (spent) { sessionCredits += spent; sessionMessages++ }
342
+ console.log()
343
+ if (spent) {
344
+ console.log(statusBar([
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],
349
+ ]))
350
+ }
351
+ console.log()
352
+ }
353
+
354
+ if (opts.prompt) await send(opts.prompt)
355
+
356
+ for (;;) {
357
+ let input
358
+ try {
359
+ input = await readInput()
360
+ } catch {
361
+ break
362
+ }
363
+ const trimmed = input.trim()
364
+ if (!trimmed) continue
365
+ const lower = trimmed.toLowerCase()
366
+ const [command, ...rest] = lower.split(/\s+/)
367
+ const arg = trimmed.split(/\s+/).slice(1).join(' ')
368
+
369
+ if (EXIT_COMMANDS.has(lower)) break
370
+ if (RESET_COMMANDS.has(lower)) {
371
+ agent.reset()
372
+ sessionMessages = 0; sessionCredits = 0
373
+ console.log(`${LIME}โœ“${RST} New conversation.\n`)
374
+ continue
375
+ }
376
+ if (lower === '/help' || lower === '/?') { printHelp(agentMode); continue }
377
+ if (lower === '/status') {
378
+ console.log()
379
+ console.log(sectionHeader('Session'))
380
+ console.log()
381
+ const row = (name, value) => console.log(` ${MUTED}${name.padEnd(10)}${RST} ${value}`)
382
+ const elapsed = Math.floor((Date.now() - sessionStart) / 60000)
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
+ }
393
+ const libs = [...activeLibraries]
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}`)
397
+ console.log()
398
+ continue
399
+ }
400
+ if (lower === '/credits') {
401
+ console.log()
402
+ console.log(sectionHeader('Credits'))
403
+ console.log()
404
+ try {
405
+ const me = await get('/api/v1/me')
406
+ credits = me.credits; available = me.available
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 */ }
430
+ console.log()
431
+ console.log(` ${FAINT}top up at${RST} ${SKY}${UNDERLINE}https://noguard.ai/credits${RST}`)
432
+ } catch {
433
+ if (credits !== null) console.log(` ${AMBER}${fmtNumber(credits)}${RST} credits remaining.`)
434
+ else console.log(` ${MUTED}Could not load your balance.${RST}`)
435
+ }
436
+ console.log()
437
+ continue
438
+ }
439
+ if (lower === '/models') {
440
+ if (!availableModels.length) availableModels = await loadModels()
441
+ if (availableModels.length) printModels(availableModels, currentModel?.id)
442
+ else console.log(` ${SOFT_GRAY}Could not load the model list.${RST}\n`)
443
+ continue
444
+ }
445
+ if (command === '/model') {
446
+ if (!arg) { console.log(` ${SOFT_GRAY}Usage: /model <alias or name>${RST}\n`); continue }
447
+ const picked = pickModel(availableModels, arg, agentMode)
448
+ if (picked.model) {
449
+ currentModel = picked.model
450
+ const tierColor = TIER_COLORS[currentModel.tier] ?? NEON_CYAN
451
+ console.log(`${LIME}โœ“${RST} Switched to ${tierColor}${BOLD}${currentModel.display_name}${RST} ${DARK_GRAY}(${currentModel.id})${RST}\n`)
452
+ } else console.log(`${HOT_PINK}โœ—${RST} ${picked.warning}\n`)
453
+ continue
454
+ }
455
+ if (command === '/mode' || command === '/permissions') {
456
+ const wanted = rest[0] === 'edits' ? 'accept-edits' : rest[0]
457
+ if (!agentMode) console.log(` ${SOFT_GRAY}This is a chat-only session.${RST}\n`)
458
+ else if (!wanted) {
459
+ console.log()
460
+ console.log(sectionHeader('Permission Mode'))
461
+ console.log()
462
+ for (const [mode, about] of Object.entries(MODES)) {
463
+ const modeColor = mode === 'yolo' ? HOT_PINK : mode === 'accept-edits' ? ORANGE : NEON_CYAN
464
+ const active = mode === permissions.mode
465
+ console.log(` ${active ? `${modeColor}โ—${RST}` : `${DARK_GRAY}โ—‹${RST}`} ${active ? `${modeColor}${BOLD}` : SOFT_GRAY}${mode}${RST} ${DARK_GRAY}${about}${RST}`)
466
+ }
467
+ console.log(`\n ${SOFT_GRAY}Change with /mode <mode>${RST}\n`)
468
+ } else if (MODES[wanted]) {
469
+ permissions.mode = wanted
470
+ const modeColor = wanted === 'yolo' ? HOT_PINK : wanted === 'accept-edits' ? ORANGE : NEON_CYAN
471
+ console.log(`${LIME}โœ“${RST} Mode: ${modeColor}${BOLD}${wanted}${RST} ${DARK_GRAY}(${MODES[wanted]})${RST}\n`)
472
+ } else console.log(`${HOT_PINK}โœ—${RST} Unknown mode. Options: ${Object.keys(MODES).join(', ')}\n`)
473
+ continue
474
+ }
475
+ if (lower === '/tools') {
476
+ if (!agentMode) { console.log(` ${SOFT_GRAY}This is a chat-only session.${RST}\n`); continue }
477
+ console.log()
478
+ console.log(sectionHeader('Available Tools'))
479
+ console.log()
480
+ for (const tool of TOOLS) console.log(` ${LIME}${BOLD}${tool.name.padEnd(12)}${RST} ${SOFT_GRAY}${tool.description.split('\n')[0]}${RST}`)
481
+ console.log(`\n ${DARK_GRAY}Commands run in ${BRIGHT_WHITE}${detectShell().label}${DARK_GRAY}.${RST}\n`)
482
+ continue
483
+ }
484
+ if (lower === '/compact') {
485
+ console.log(agent.compact() ? `${LIME}โœ“${RST} Dropped older tool output.\n` : ` ${SOFT_GRAY}Nothing to compact yet.${RST}\n`)
486
+ continue
487
+ }
488
+ if (lower === '/init') {
489
+ if (!agentMode) { console.log(` ${SOFT_GRAY}This is a chat-only session.${RST}\n`); continue }
490
+ await send(INIT_PROMPT)
491
+ continue
492
+ }
493
+ if (lower === '/libraries' || lower === '/libs') { printLibraries(activeLibraries); continue }
494
+ if (command === '/library' || command === '/lib') {
495
+ const id = rest[0]
496
+ const lib = LIBRARIES.find(l => l.id === id)
497
+ if (!lib) console.log(`${HOT_PINK}โœ—${RST} Unknown library "${id ?? ''}". Options: ${LIBRARIES.map(l => l.id).join(', ')}\n`)
498
+ else if (activeLibraries.has(id)) {
499
+ activeLibraries.delete(id)
500
+ console.log(`${LIME}โœ“${RST} Disabled ${LIB_COLORS[id] ?? NEON_CYAN}${BOLD}${lib.label}${RST}\n`)
501
+ } else {
502
+ activeLibraries.add(id)
503
+ console.log(`${LIME}โœ“${RST} Enabled ${LIB_COLORS[id] ?? NEON_CYAN}${BOLD}${lib.label}${RST}\n`)
504
+ }
505
+ continue
506
+ }
507
+ if (trimmed.startsWith('/') && !trimmed.includes(' ') && trimmed.length < 20) {
508
+ console.log(`${HOT_PINK}โœ—${RST} Unknown command ${BRIGHT_WHITE}${trimmed}${RST}. Type /help for the list.\n`)
509
+ continue
510
+ }
511
+ await send(input)
512
+ }
513
+ console.log(`${SOFT_GRAY} Bye.${RST}`)
514
+ process.exit(0)
515
+ }