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/bin/noguard.mjs CHANGED
@@ -1,216 +1,245 @@
1
- #!/usr/bin/env node
2
-
3
- const VERSION = '1.1.0'
4
- const HELP = `
5
- \x1b[1mNoGuard AI CLI v${VERSION}\x1b[0m
6
- The AI that doesn't say no — in your terminal, working on your project.
7
-
8
- Run \x1b[1mnoguard\x1b[0m inside a project folder. NoGuard can read, search and edit its files
9
- and run commands there, asking you before it changes anything.
10
-
11
- \x1b[1mUsage:\x1b[0m
12
- noguard Start a session in the current folder
13
- noguard "task" Start a session with a first message
14
- noguard -p "task" Do one task and print the result (no prompts; pipe input works too)
15
- noguard login Sign in with your NoGuard account
16
- noguard logout Sign out and revoke the token
17
- noguard me Show your account and credits
18
- noguard models List available models with tiers and pricing
19
- noguard usage [--days N] Show credit usage history
20
- noguard config Show config file location
21
- noguard endpoint [URL] Show or set the API endpoint
22
-
23
- \x1b[1mOptions:\x1b[0m
24
- --model, -m <name> Choose a model (alias or name, e.g. noguard-ultra)
25
- --print, -p Print mode: run one task and exit
26
- --accept-edits Let NoGuard edit files without asking (still asks before commands)
27
- --yolo Let NoGuard edit files and run commands without asking
28
- --no-tools Chat only: NoGuard can't see or change files
29
- --help, -h Show this help
30
- --version, -v Show version
31
-
32
- \x1b[1mIn-session commands:\x1b[0m
33
- /models, /model <name> List models, switch model
34
- /mode [ask|accept-edits|yolo] Show or change what needs your approval
35
- /init Write a NOGUARD.md describing this project
36
- /compact Free context by dropping old tool output
37
- /libraries, /library <id> Research libraries
38
- /clear Start a new conversation
39
- /credits Show remaining credits
40
- /help, /exit
41
-
42
- \x1b[1mProject instructions:\x1b[0m
43
- NoGuard reads NOGUARD.md (and CLAUDE.md or AGENTS.md) from the project folder and
44
- its parents, and ~/.noguard/NOGUARD.md, at the start of each session.
45
- `
46
-
47
- const COMMANDS = new Set(['login', 'logout', 'me', 'models', 'usage', 'config', 'endpoint', 'chat'])
48
- const VALUE_FLAGS = new Set(['--model', '-m', '--days'])
49
-
50
- function parseArgs(argv) {
51
- const flags = new Set()
52
- const values = {}
53
- const positional = []
54
- for (let i = 0; i < argv.length; i++) {
55
- const arg = argv[i]
56
- if (VALUE_FLAGS.has(arg)) values[arg] = argv[++i]
57
- else if (arg.startsWith('-') && arg.length > 1) flags.add(arg)
58
- else positional.push(arg)
59
- }
60
- return { flags, values, positional }
61
- }
62
-
63
- /** Piped input. With a typed task too, an open stdin that sends nothing (scripts, CI) is not waited on. */
64
- function readStdin(optional) {
65
- if (process.stdin.isTTY) return Promise.resolve('')
66
- return new Promise(resolve => {
67
- const chunks = []
68
- const done = () => { clearTimeout(idle); process.stdin.destroy(); resolve(Buffer.concat(chunks).toString('utf8')) }
69
- const idle = optional ? setTimeout(done, 500) : null
70
- process.stdin.on('data', chunk => { clearTimeout(idle); chunks.push(chunk) })
71
- process.stdin.on('end', done)
72
- process.stdin.on('error', done)
73
- })
74
- }
75
-
76
- async function main() {
77
- const args = process.argv.slice(2)
78
- const { flags, values, positional } = parseArgs(args)
79
- const command = COMMANDS.has(positional[0]) ? positional[0] : positional.length ? 'prompt' : undefined
80
-
81
- if (flags.has('--help') || flags.has('-h')) {
82
- console.log(HELP)
83
- return
84
- }
85
- if (flags.has('--version') || flags.has('-v')) {
86
- console.log(VERSION)
87
- return
88
- }
89
- const session = {
90
- model: values['--model'] ?? values['-m'],
91
- tools: !flags.has('--no-tools'),
92
- mode: flags.has('--yolo') || flags.has('--dangerously-skip-permissions') ? 'yolo' : flags.has('--accept-edits') ? 'accept-edits' : 'ask',
93
- }
94
- if (flags.has('-p') || flags.has('--print')) {
95
- const typed = (command === 'chat' ? positional.slice(1) : positional).join(' ')
96
- const piped = await readStdin(Boolean(typed))
97
- const prompt = [typed, piped.trim()].filter(Boolean).join('\n\n')
98
- if (!prompt) {
99
- console.error('\x1b[31m✗\x1b[0m Give a task: noguard -p "what to do" (or pipe text in).')
100
- process.exit(1)
101
- }
102
- const { runOnce } = await import('../lib/chat.mjs')
103
- await runOnce({ ...session, prompt })
104
- return
105
- }
106
-
107
- switch (command) {
108
- case 'login': {
109
- const { login } = await import('../lib/auth.mjs')
110
- await login()
111
- break
112
- }
113
- case 'logout': {
114
- const { logout } = await import('../lib/auth.mjs')
115
- await logout()
116
- break
117
- }
118
- case 'me': {
119
- const { getToken } = await import('../lib/config.mjs')
120
- const { get } = await import('../lib/api.mjs')
121
- if (!getToken()) { console.log('\x1b[31m✗\x1b[0m Not signed in. Run \x1b[1mnoguard login\x1b[0m first.'); return }
122
- try {
123
- const me = await get('/api/v1/me')
124
- console.log()
125
- console.log(` \x1b[1mAccount\x1b[0m`)
126
- console.log(` Email: ${me.email}`)
127
- console.log(` Tier: ${me.tier}`)
128
- console.log(` Verified: ${me.verified ? '\x1b[32myes\x1b[0m' : '\x1b[31mno\x1b[0m'}`)
129
- console.log(` Credits: \x1b[33m${me.credits}\x1b[0m (${me.available} available)`)
130
- console.log(` Token: ${me.token.name} (${me.token.uid})`)
131
- console.log()
132
- } catch (err) {
133
- if (err.status === 401) console.log('\x1b[31m✗\x1b[0m Session expired. Run \x1b[1mnoguard login\x1b[0m again.')
134
- else console.error(`\x1b[31m✗\x1b[0m ${err.message}`)
135
- }
136
- break
137
- }
138
- case 'models': {
139
- const { get } = await import('../lib/api.mjs')
140
- const { printModels } = await import('../lib/chat.mjs')
141
- try {
142
- const res = await get('/api/v1/models')
143
- printModels(res.data)
144
- } catch (err) {
145
- console.error(`\x1b[31m✗\x1b[0m ${err.message}`)
146
- }
147
- break
148
- }
149
- case 'usage': {
150
- const { getToken } = await import('../lib/config.mjs')
151
- const { get } = await import('../lib/api.mjs')
152
- if (!getToken()) { console.log('\x1b[31m✗\x1b[0m Not signed in. Run \x1b[1mnoguard login\x1b[0m first.'); return }
153
- const days = parseInt(values['--days'], 10) || 30
154
- try {
155
- const res = await get(`/api/v1/usage?days=${days}`)
156
- console.log()
157
- console.log(` \x1b[1mUsage (last ${res.days_covered} days)\x1b[0m`)
158
- if (res.by_day?.length) {
159
- for (const day of res.by_day) {
160
- console.log(` ${day.date} \x1b[33m${day.credits_spent}\x1b[0m credits ${day.requests} requests`)
161
- }
162
- } else {
163
- console.log(' \x1b[2mNo usage yet.\x1b[0m')
164
- }
165
- console.log()
166
- } catch (err) {
167
- if (err.status === 401) console.log('\x1b[31m✗\x1b[0m Session expired. Run \x1b[1mnoguard login\x1b[0m again.')
168
- else console.error(`\x1b[31m✗\x1b[0m ${err.message}`)
169
- }
170
- break
171
- }
172
- case 'config': {
173
- const { configPath, load } = await import('../lib/config.mjs')
174
- const cfg = load()
175
- console.log()
176
- console.log(` \x1b[1mConfig\x1b[0m`)
177
- console.log(` File: ${configPath()}`)
178
- console.log(` Endpoint: ${cfg.endpoint ?? 'https://noguard.ai'}`)
179
- console.log(` Signed: ${cfg.token ? '\x1b[32myes\x1b[0m' : '\x1b[31mno\x1b[0m'}`)
180
- if (cfg.account) console.log(` Account: ${cfg.account.email}`)
181
- console.log()
182
- break
183
- }
184
- case 'endpoint': {
185
- const sub = positional[1]
186
- if (sub) {
187
- const { setEndpoint } = await import('../lib/config.mjs')
188
- setEndpoint(sub)
189
- console.log(`\x1b[32m✓\x1b[0m Endpoint set to \x1b[1m${sub}\x1b[0m`)
190
- } else {
191
- const { getEndpoint } = await import('../lib/config.mjs')
192
- console.log(getEndpoint())
193
- }
194
- break
195
- }
196
- case 'prompt':
197
- case 'chat':
198
- case undefined: {
199
- const words = command === 'chat' ? positional.slice(1) : positional
200
- // A lone word is more likely a mistyped command than a task.
201
- if (command === 'prompt' && words.length === 1 && !/\s/.test(words[0])) {
202
- console.log(`\x1b[31m✗\x1b[0m Unknown command: ${words[0]}`)
203
- console.log(' Run \x1b[1mnoguard --help\x1b[0m for usage, or quote a task: noguard "fix the failing test"')
204
- process.exit(1)
205
- }
206
- const { chat } = await import('../lib/chat.mjs')
207
- await chat({ ...session, prompt: words.join(' ') || undefined })
208
- break
209
- }
210
- }
211
- }
212
-
213
- main().catch(err => {
214
- console.error(`\x1b[31m✗\x1b[0m ${err.message}`)
215
- process.exit(1)
216
- })
1
+ #!/usr/bin/env node
2
+
3
+ import {
4
+ BOLD, RST, UNDERLINE,
5
+ NEON_CYAN, HOT_PINK, LIME, ORANGE, GOLD, SKY, BRIGHT_WHITE, SOFT_GRAY, DARK_GRAY,
6
+ AMBER, MINT, ROSE, FG_STRONG, MUTED, FAINT,
7
+ gradient, NOGUARD_GRADIENT, sectionHeader, tierPill, creditMeter, sparkline,
8
+ } from '../lib/render.mjs'
9
+
10
+ const VERSION = '1.2.0'
11
+
12
+ function helpText() {
13
+ return `
14
+ ${gradient('NoGuard AI CLI', NOGUARD_GRADIENT)} ${SOFT_GRAY}v${VERSION}${RST}
15
+ ${SOFT_GRAY}The AI that doesn't say no — in your terminal, working on your project.${RST}
16
+
17
+ Run ${BRIGHT_WHITE}${BOLD}noguard${RST} inside a project folder. NoGuard can read, search and edit its files
18
+ and run commands there, asking you before it changes anything.
19
+
20
+ ${GOLD}${BOLD}Usage:${RST}
21
+ ${BRIGHT_WHITE}noguard${RST} ${SOFT_GRAY}Start a session in the current folder${RST}
22
+ ${BRIGHT_WHITE}noguard${RST} ${SKY}"task"${RST} ${SOFT_GRAY}Start a session with a first message${RST}
23
+ ${BRIGHT_WHITE}noguard${RST} ${NEON_CYAN}-p${RST} ${SKY}"task"${RST} ${SOFT_GRAY}Do one task and print the result (pipe input works too)${RST}
24
+ ${BRIGHT_WHITE}noguard login${RST} ${SOFT_GRAY}Sign in with your NoGuard account${RST}
25
+ ${BRIGHT_WHITE}noguard logout${RST} ${SOFT_GRAY}Sign out and revoke the token${RST}
26
+ ${BRIGHT_WHITE}noguard me${RST} ${SOFT_GRAY}Show your account and credits${RST}
27
+ ${BRIGHT_WHITE}noguard models${RST} ${SOFT_GRAY}List available models with tiers and pricing${RST}
28
+ ${BRIGHT_WHITE}noguard usage${RST} ${NEON_CYAN}[--days N]${RST} ${SOFT_GRAY}Show credit usage history${RST}
29
+ ${BRIGHT_WHITE}noguard config${RST} ${SOFT_GRAY}Show config file location${RST}
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}
32
+
33
+ ${GOLD}${BOLD}Options:${RST}
34
+ ${NEON_CYAN}--model, -m${RST} ${SKY}<name>${RST} ${SOFT_GRAY}Choose a model (alias or name, e.g. noguard-ultra)${RST}
35
+ ${NEON_CYAN}--print, -p${RST} ${SOFT_GRAY}Print mode: run one task and exit${RST}
36
+ ${NEON_CYAN}--accept-edits${RST} ${SOFT_GRAY}Let NoGuard edit files without asking (still asks before commands)${RST}
37
+ ${NEON_CYAN}--yolo${RST} ${SOFT_GRAY}Let NoGuard edit files and run commands without asking${RST}
38
+ ${NEON_CYAN}--no-tools${RST} ${SOFT_GRAY}Chat only: NoGuard can't see or change files${RST}
39
+ ${NEON_CYAN}--help, -h${RST} ${SOFT_GRAY}Show this help${RST}
40
+ ${NEON_CYAN}--version, -v${RST} ${SOFT_GRAY}Show version${RST}
41
+
42
+ ${GOLD}${BOLD}In-session commands:${RST}
43
+ ${BRIGHT_WHITE}/models, /model <name>${RST} ${SOFT_GRAY}List models, switch model${RST}
44
+ ${BRIGHT_WHITE}/mode${RST} ${SKY}[ask|accept-edits|yolo]${RST} ${SOFT_GRAY}Show or change what needs your approval${RST}
45
+ ${BRIGHT_WHITE}/status${RST} ${SOFT_GRAY}Show session info, credits, model, and stats${RST}
46
+ ${BRIGHT_WHITE}/init${RST} ${SOFT_GRAY}Write a NOGUARD.md describing this project${RST}
47
+ ${BRIGHT_WHITE}/compact${RST} ${SOFT_GRAY}Free context by dropping old tool output${RST}
48
+ ${BRIGHT_WHITE}/libraries, /library <id>${RST} ${SOFT_GRAY}Research libraries${RST}
49
+ ${BRIGHT_WHITE}/clear${RST} ${SOFT_GRAY}Start a new conversation${RST}
50
+ ${BRIGHT_WHITE}/credits${RST} ${SOFT_GRAY}Show remaining credits${RST}
51
+ ${BRIGHT_WHITE}/help, /exit${RST}
52
+
53
+ ${GOLD}${BOLD}Project instructions:${RST}
54
+ NoGuard reads ${SKY}NOGUARD.md${RST} (and ${SKY}CLAUDE.md${RST} or ${SKY}AGENTS.md${RST}) from the project folder and
55
+ its parents, and ${SKY}~/.noguard/NOGUARD.md${RST}, at the start of each session.
56
+ `
57
+ }
58
+
59
+ const COMMANDS = new Set(['login', 'logout', 'me', 'models', 'usage', 'config', 'endpoint', 'chat'])
60
+ const VALUE_FLAGS = new Set(['--model', '-m', '--days'])
61
+
62
+ function parseArgs(argv) {
63
+ const flags = new Set()
64
+ const values = {}
65
+ const positional = []
66
+ for (let i = 0; i < argv.length; i++) {
67
+ const arg = argv[i]
68
+ if (VALUE_FLAGS.has(arg)) values[arg] = argv[++i]
69
+ else if (arg.startsWith('-') && arg.length > 1) flags.add(arg)
70
+ else positional.push(arg)
71
+ }
72
+ return { flags, values, positional }
73
+ }
74
+
75
+ /** Piped input. With a typed task too, an open stdin that sends nothing (scripts, CI) is not waited on. */
76
+ function readStdin(optional) {
77
+ if (process.stdin.isTTY) return Promise.resolve('')
78
+ return new Promise(resolve => {
79
+ const chunks = []
80
+ const done = () => { clearTimeout(idle); process.stdin.destroy(); resolve(Buffer.concat(chunks).toString('utf8')) }
81
+ const idle = optional ? setTimeout(done, 500) : null
82
+ process.stdin.on('data', chunk => { clearTimeout(idle); chunks.push(chunk) })
83
+ process.stdin.on('end', done)
84
+ process.stdin.on('error', done)
85
+ })
86
+ }
87
+
88
+ function fmtNumber(n) {
89
+ return Number(n).toLocaleString('en-US')
90
+ }
91
+
92
+ async function main() {
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
+ }
99
+ const { flags, values, positional } = parseArgs(args)
100
+ const command = COMMANDS.has(positional[0]) ? positional[0] : positional.length ? 'prompt' : undefined
101
+
102
+ if (flags.has('--help') || flags.has('-h')) {
103
+ console.log(helpText())
104
+ return
105
+ }
106
+ if (flags.has('--version') || flags.has('-v')) {
107
+ console.log(`${gradient('NoGuard', NOGUARD_GRADIENT)} ${SOFT_GRAY}v${VERSION}${RST}`)
108
+ return
109
+ }
110
+ const session = {
111
+ model: values['--model'] ?? values['-m'],
112
+ tools: !flags.has('--no-tools'),
113
+ mode: flags.has('--yolo') || flags.has('--dangerously-skip-permissions') ? 'yolo' : flags.has('--accept-edits') ? 'accept-edits' : 'ask',
114
+ }
115
+ if (flags.has('-p') || flags.has('--print')) {
116
+ const typed = (command === 'chat' ? positional.slice(1) : positional).join(' ')
117
+ const piped = await readStdin(Boolean(typed))
118
+ const prompt = [typed, piped.trim()].filter(Boolean).join('\n\n')
119
+ if (!prompt) {
120
+ console.error(`${HOT_PINK}✗${RST} Give a task: ${BRIGHT_WHITE}noguard -p "what to do"${RST} (or pipe text in).`)
121
+ process.exit(1)
122
+ }
123
+ const { runOnce } = await import('../lib/chat.mjs')
124
+ await runOnce({ ...session, prompt })
125
+ return
126
+ }
127
+
128
+ switch (command) {
129
+ case 'login': {
130
+ const { login } = await import('../lib/auth.mjs')
131
+ await login()
132
+ break
133
+ }
134
+ case 'logout': {
135
+ const { logout } = await import('../lib/auth.mjs')
136
+ await logout()
137
+ break
138
+ }
139
+ case 'me': {
140
+ const { getToken } = await import('../lib/config.mjs')
141
+ const { get } = await import('../lib/api.mjs')
142
+ if (!getToken()) { console.log(`${HOT_PINK}✗${RST} Not signed in. Run ${BOLD}noguard login${RST} first.`); return }
143
+ try {
144
+ const me = await get('/api/v1/me')
145
+ const low = me.low_balance || me.available < 100
146
+ const row = (name, value) => console.log(` ${MUTED}${name.padEnd(9)}${RST} ${value}`)
147
+ console.log()
148
+ console.log(sectionHeader('Account'))
149
+ console.log()
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}`)
155
+ console.log()
156
+ } catch (err) {
157
+ if (err.status === 401) console.log(`${HOT_PINK}✗${RST} Session expired. Run ${BOLD}noguard login${RST} again.`)
158
+ else console.error(`${HOT_PINK}✗${RST} ${err.message}`)
159
+ }
160
+ break
161
+ }
162
+ case 'models': {
163
+ const { get } = await import('../lib/api.mjs')
164
+ const { printModels } = await import('../lib/chat.mjs')
165
+ try {
166
+ const res = await get('/api/v1/models')
167
+ printModels(res.data)
168
+ } catch (err) {
169
+ console.error(`${HOT_PINK}✗${RST} ${err.message}`)
170
+ }
171
+ break
172
+ }
173
+ case 'usage': {
174
+ const { getToken } = await import('../lib/config.mjs')
175
+ const { get } = await import('../lib/api.mjs')
176
+ if (!getToken()) { console.log(`${HOT_PINK}✗${RST} Not signed in. Run ${BOLD}noguard login${RST} first.`); return }
177
+ const days = parseInt(values['--days'], 10) || 30
178
+ try {
179
+ const res = await get(`/api/v1/usage?days=${days}`)
180
+ console.log()
181
+ console.log(sectionHeader(`Usage · last ${res.days_covered} days`))
182
+ console.log()
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}`)
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}`)
191
+ } else {
192
+ console.log(` ${MUTED}No usage yet.${RST}`)
193
+ }
194
+ console.log()
195
+ } catch (err) {
196
+ if (err.status === 401) console.log(`${HOT_PINK}✗${RST} Session expired. Run ${BOLD}noguard login${RST} again.`)
197
+ else console.error(`${HOT_PINK}✗${RST} ${err.message}`)
198
+ }
199
+ break
200
+ }
201
+ case 'config': {
202
+ const { configPath, load } = await import('../lib/config.mjs')
203
+ const cfg = load()
204
+ console.log()
205
+ console.log(sectionHeader('Config'))
206
+ console.log()
207
+ console.log(` ${SOFT_GRAY}File:${RST} ${SKY}${configPath()}${RST}`)
208
+ console.log(` ${SOFT_GRAY}Endpoint:${RST} ${BRIGHT_WHITE}${cfg.endpoint ?? 'https://noguard.ai'}${RST}`)
209
+ console.log(` ${SOFT_GRAY}Signed:${RST} ${cfg.token ? `${LIME}yes${RST}` : `${HOT_PINK}no${RST}`}`)
210
+ if (cfg.account) console.log(` ${SOFT_GRAY}Account:${RST} ${BRIGHT_WHITE}${cfg.account.email}${RST}`)
211
+ console.log()
212
+ break
213
+ }
214
+ case 'endpoint': {
215
+ const sub = positional[1]
216
+ if (sub) {
217
+ const { setEndpoint } = await import('../lib/config.mjs')
218
+ setEndpoint(sub)
219
+ console.log(`${LIME}✓${RST} Endpoint set to ${BRIGHT_WHITE}${BOLD}${sub}${RST}`)
220
+ } else {
221
+ const { getEndpoint } = await import('../lib/config.mjs')
222
+ console.log(getEndpoint())
223
+ }
224
+ break
225
+ }
226
+ case 'prompt':
227
+ case 'chat':
228
+ case undefined: {
229
+ const words = command === 'chat' ? positional.slice(1) : positional
230
+ if (command === 'prompt' && words.length === 1 && !/\s/.test(words[0])) {
231
+ console.log(`${HOT_PINK}✗${RST} Unknown command: ${BRIGHT_WHITE}${words[0]}${RST}`)
232
+ console.log(` Run ${BRIGHT_WHITE}${BOLD}noguard --help${RST} for usage, or quote a task: ${BRIGHT_WHITE}noguard "fix the failing test"${RST}`)
233
+ process.exit(1)
234
+ }
235
+ const { chat } = await import('../lib/chat.mjs')
236
+ await chat({ ...session, prompt: words.join(' ') || undefined })
237
+ break
238
+ }
239
+ }
240
+ }
241
+
242
+ main().catch(err => {
243
+ console.error(`${HOT_PINK}✗${RST} ${err.message}`)
244
+ process.exit(1)
245
+ })
package/lib/agent.mjs CHANGED
@@ -4,7 +4,7 @@
4
4
  import { randomBytes, randomUUID } from 'node:crypto'
5
5
  import { ApiError, streamMessages } from './api.mjs'
6
6
  import { isInsideReal, resolvePath } from './files.mjs'
7
- import { clean, MarkdownStream, Spinner, toolHeader, toolResultLine, BOLD, CYAN, DIM, RED, RST, YELLOW } from './render.mjs'
7
+ import { clean, MarkdownStream, Spinner, toolHeader, toolResultLine, BOLD, DIM, RST, UNDERLINE, NEON_CYAN, HOT_PINK, LIME, ORANGE, BRIGHT_WHITE, SOFT_GRAY } from './render.mjs'
8
8
  import { systemPrompt } from './context.mjs'
9
9
  import { TOOLS_BY_NAME, toolDefinitions } from './tools.mjs'
10
10
 
@@ -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') {
@@ -183,10 +190,10 @@ export class Agent {
183
190
  }
184
191
  this.messages.push({ role: 'user', content: results })
185
192
  if (halt || this.controller.signal.aborted) {
186
- if (this.controller.signal.aborted) console.log(` ${DIM}⎿ Interrupted. Tell NoGuard what to do instead.${RST}`)
193
+ if (this.controller.signal.aborted) console.log(` ${SOFT_GRAY}⎿ Interrupted. Tell NoGuard what to do instead.${RST}`)
187
194
  break
188
195
  }
189
- if (step === MAX_STEPS - 1) console.log(`${YELLOW}⚠${RST} Stopped after ${MAX_STEPS} steps. Send a message to continue.`)
196
+ if (step === MAX_STEPS - 1) console.log(`${ORANGE}⚠${RST} Stopped after ${MAX_STEPS} steps. Send a message to continue.`)
190
197
  }
191
198
  } finally {
192
199
  this.spinner.stop()
@@ -270,7 +277,7 @@ export class Agent {
270
277
  await new Promise(r => setTimeout(r, 2000))
271
278
  continue
272
279
  }
273
- console.log(`${RED}✗${RST} Connection error: ${err.message}`)
280
+ console.log(`${HOT_PINK}✗${RST} Connection error: ${err.message}`)
274
281
  return { blocks: [], spent: 0, balance: null, stop: true, failed: true }
275
282
  }
276
283
  }
@@ -282,10 +289,10 @@ export class Agent {
282
289
  }
283
290
 
284
291
  #explain(err) {
285
- if (err.status === 401 || err.code === 'invalid_token') console.log(`${RED}✗${RST} Session expired. Run ${BOLD}noguard login${RST} again.`)
286
- else if (err.code === 'out_of_credits' || err.status === 402) console.log(`${YELLOW}⚠${RST} ${err.message}\n Top up at \x1b[4mhttps://noguard.ai/credits${RST}`)
287
- else if (err.code === 'model_unavailable') console.log(`${YELLOW}⚠${RST} ${err.message} Run /models to pick another.`)
288
- else console.log(`${RED}✗${RST} ${err.message}`)
292
+ if (err.status === 401 || err.code === 'invalid_token') console.log(`${HOT_PINK}✗${RST} Session expired. Run ${BOLD}noguard login${RST} again.`)
293
+ else if (err.code === 'out_of_credits' || err.status === 402) console.log(`${ORANGE}⚠${RST} ${err.message}\n Top up at ${NEON_CYAN}${UNDERLINE}https://noguard.ai/credits${RST}`)
294
+ else if (err.code === 'model_unavailable') console.log(`${ORANGE}⚠${RST} ${err.message} Run /models to pick another.`)
295
+ else console.log(`${HOT_PINK}✗${RST} ${err.message}`)
289
296
  return err.message
290
297
  }
291
298
 
@@ -367,7 +374,7 @@ export class Agent {
367
374
  finished.push(call)
368
375
  }
369
376
  if (streamError) {
370
- console.log(`${RED}✗${RST} ${streamError}`)
377
+ console.log(`${HOT_PINK}✗${RST} ${streamError}`)
371
378
  return { blocks: finished.filter(b => b.type === 'text'), spent, balance, stop: true, failed: true }
372
379
  }
373
380
  if (stopReason === 'max_tokens' && !finished.some(b => b.type === 'tool_use')) {
@@ -382,19 +389,19 @@ export class Agent {
382
389
  const fail = (message, extra = {}) => ({ result: { type: 'tool_result', tool_use_id: call.id, content: message, is_error: true }, ...extra })
383
390
  if (!tool) {
384
391
  console.log(toolHeader(call.name))
385
- console.log(toolResultLine(`Unknown tool`, RED))
392
+ console.log(toolResultLine(`Unknown tool`, HOT_PINK))
386
393
  return fail(`There is no tool named ${call.name}.`)
387
394
  }
388
395
  let label = ''
389
396
  try { label = tool.label(call.input, this.ctx) } catch { /* bad input shows no label */ }
390
397
  console.log(toolHeader(tool.name, label))
391
398
  if (call.parseError) {
392
- console.log(toolResultLine('Invalid arguments', RED))
399
+ console.log(toolResultLine('Invalid arguments', HOT_PINK))
393
400
  return fail(`The tool arguments were not valid JSON (${call.parseError}). The reply may have been cut off; try again with smaller input.`)
394
401
  }
395
402
  const missing = (tool.input_schema.required ?? []).filter(key => call.input[key] === undefined)
396
403
  if (missing.length) {
397
- console.log(toolResultLine(`Missing ${missing.join(', ')}`, RED))
404
+ console.log(toolResultLine(`Missing ${missing.join(', ')}`, HOT_PINK))
398
405
  return fail(`Missing required argument${missing.length > 1 ? 's' : ''}: ${missing.join(', ')}.`)
399
406
  }
400
407
  const reason = this.permissions.check(tool, call.input, this.cwd)
@@ -405,16 +412,16 @@ export class Agent {
405
412
  if (tool.kind === 'exec') {
406
413
  // The header may be shortened: show exactly what will run before asking.
407
414
  const command = clean(String(call.input.command ?? ''))
408
- if (command !== label) console.log(command.split('\n').map(line => ` ${CYAN}${line}${RST}`).join('\n'))
415
+ if (command !== label) console.log(command.split('\n').map(line => ` ${NEON_CYAN}${line}${RST}`).join('\n'))
409
416
  if (call.input.description) console.log(` ${DIM}${clean(String(call.input.description))}${RST}`)
410
417
  }
411
418
  const always = this.permissions.alwaysLabel(tool, call.input)
412
- const answer = await this.ui.ask(` ${YELLOW}?${RST} Allow NoGuard to ${reason}? ${BOLD}y${RST}es${always ? ` · ${BOLD}a${RST}lways (${always})` : ''} · ${BOLD}n${RST}o, or type what to do instead ${CYAN}›${RST} `)
419
+ const answer = await this.ui.ask(` ${ORANGE}?${RST} Allow NoGuard to ${reason}? ${LIME}y${RST}es${always ? ` · ${NEON_CYAN}a${RST}lways (${always})` : ''} · ${HOT_PINK}n${RST}o, or type what to do instead ${NEON_CYAN}›${RST} `)
413
420
  if (answer === null) {
414
421
  const why = this.ui.interactive
415
422
  ? 'Not run: the user interrupted.'
416
423
  : `Not run: this needs approval, and nobody can approve it in print mode. Rerun with --accept-edits or --yolo to allow it.`
417
- console.log(toolResultLine(this.ui.interactive ? 'Interrupted' : 'Needs approval (print mode)', YELLOW))
424
+ console.log(toolResultLine(this.ui.interactive ? 'Interrupted' : 'Needs approval (print mode)', ORANGE))
418
425
  return fail(why, { halt: true })
419
426
  }
420
427
  const reply = answer.trim()
@@ -423,7 +430,7 @@ export class Agent {
423
430
  if (always) this.permissions.alwaysAllow(tool, call.input)
424
431
  } else if (!(word === '' || word === 'y' || word === 'yes')) {
425
432
  const feedback = ['n', 'no'].includes(word) ? '' : reply
426
- console.log(toolResultLine('Denied', YELLOW))
433
+ console.log(toolResultLine('Denied', ORANGE))
427
434
  if (feedback) {
428
435
  return fail('The user denied this action.', { feedback: `The user denied that and said: ${feedback}` })
429
436
  }
@@ -439,7 +446,7 @@ export class Agent {
439
446
  }
440
447
  this.spinner.stop()
441
448
  if (outcome.error) {
442
- console.log(toolResultLine(clean(outcome.error), RED))
449
+ console.log(toolResultLine(clean(outcome.error), HOT_PINK))
443
450
  return fail(outcome.error)
444
451
  }
445
452
  if (outcome.display) console.log(toolResultLine(outcome.display))