noguard 1.2.1 → 1.3.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 +29 -10
- package/lib/agent.mjs +102 -51
- package/lib/api.mjs +81 -76
- package/lib/auth.mjs +77 -77
- package/lib/chat.mjs +79 -90
- package/lib/config.mjs +57 -57
- package/lib/context.mjs +115 -115
- package/lib/files.mjs +168 -168
- package/lib/persona-eval.mjs +305 -305
- package/lib/render.mjs +400 -398
- package/lib/shell.mjs +84 -84
- package/package.json +1 -1
package/bin/noguard.mjs
CHANGED
|
@@ -1,5 +1,7 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
|
|
3
|
+
import { readFileSync } from 'node:fs'
|
|
4
|
+
import { permissionMode } from '../lib/agent.mjs'
|
|
3
5
|
import {
|
|
4
6
|
BOLD, RST, UNDERLINE,
|
|
5
7
|
NEON_CYAN, HOT_PINK, LIME, ORANGE, GOLD, SKY, BRIGHT_WHITE, SOFT_GRAY, DARK_GRAY,
|
|
@@ -7,13 +9,11 @@ import {
|
|
|
7
9
|
gradient, NOGUARD_GRADIENT, sectionHeader, tierPill, creditMeter, sparkline,
|
|
8
10
|
} from '../lib/render.mjs'
|
|
9
11
|
|
|
10
|
-
const VERSION = '
|
|
12
|
+
const { version: VERSION } = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8'))
|
|
11
13
|
|
|
12
14
|
function helpText() {
|
|
13
15
|
return `
|
|
14
16
|
${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
17
|
Run ${BRIGHT_WHITE}${BOLD}noguard${RST} inside a project folder. NoGuard can read, search and edit its files
|
|
18
18
|
and run commands there, asking you before it changes anything.
|
|
19
19
|
|
|
@@ -33,6 +33,7 @@ ${GOLD}${BOLD}Usage:${RST}
|
|
|
33
33
|
${GOLD}${BOLD}Options:${RST}
|
|
34
34
|
${NEON_CYAN}--model, -m${RST} ${SKY}<name>${RST} ${SOFT_GRAY}Choose a model (alias or name, e.g. noguard-ultra)${RST}
|
|
35
35
|
${NEON_CYAN}--print, -p${RST} ${SOFT_GRAY}Print mode: run one task and exit${RST}
|
|
36
|
+
${NEON_CYAN}--permission-mode${RST} ${SKY}<mode>${RST} ${SOFT_GRAY}Choose ask, accept-edits or plan${RST}
|
|
36
37
|
${NEON_CYAN}--accept-edits${RST} ${SOFT_GRAY}Let NoGuard edit files without asking (still asks before commands)${RST}
|
|
37
38
|
${NEON_CYAN}--yolo${RST} ${SOFT_GRAY}Let NoGuard edit files and run commands without asking${RST}
|
|
38
39
|
${NEON_CYAN}--no-tools${RST} ${SOFT_GRAY}Chat only: NoGuard can't see or change files${RST}
|
|
@@ -41,7 +42,8 @@ ${GOLD}${BOLD}Options:${RST}
|
|
|
41
42
|
|
|
42
43
|
${GOLD}${BOLD}In-session commands:${RST}
|
|
43
44
|
${BRIGHT_WHITE}/models, /model <name>${RST} ${SOFT_GRAY}List models, switch model${RST}
|
|
44
|
-
${BRIGHT_WHITE}/
|
|
45
|
+
${BRIGHT_WHITE}/permissions${RST} ${SKY}[mode]${RST} ${SOFT_GRAY}Show or change what needs your approval${RST}
|
|
46
|
+
${BRIGHT_WHITE}/plan${RST} ${SKY}[task]${RST} ${SOFT_GRAY}Inspect project files and plan changes${RST}
|
|
45
47
|
${BRIGHT_WHITE}/status${RST} ${SOFT_GRAY}Show session info, credits, model, and stats${RST}
|
|
46
48
|
${BRIGHT_WHITE}/init${RST} ${SOFT_GRAY}Write a NOGUARD.md describing this project${RST}
|
|
47
49
|
${BRIGHT_WHITE}/compact${RST} ${SOFT_GRAY}Free context by dropping old tool output${RST}
|
|
@@ -57,7 +59,8 @@ ${GOLD}${BOLD}Project instructions:${RST}
|
|
|
57
59
|
}
|
|
58
60
|
|
|
59
61
|
const COMMANDS = new Set(['login', 'logout', 'me', 'models', 'usage', 'config', 'endpoint', 'chat'])
|
|
60
|
-
const VALUE_FLAGS = new Set(['--model', '-m', '--days'])
|
|
62
|
+
const VALUE_FLAGS = new Set(['--model', '-m', '--days', '--permission-mode'])
|
|
63
|
+
const BOOLEAN_FLAGS = new Set(['--print', '-p', '--accept-edits', '--yolo', '--dangerously-skip-permissions', '--no-tools', '--help', '-h', '--version', '-v'])
|
|
61
64
|
|
|
62
65
|
function parseArgs(argv) {
|
|
63
66
|
const flags = new Set()
|
|
@@ -65,9 +68,22 @@ function parseArgs(argv) {
|
|
|
65
68
|
const positional = []
|
|
66
69
|
for (let i = 0; i < argv.length; i++) {
|
|
67
70
|
const arg = argv[i]
|
|
68
|
-
if (
|
|
69
|
-
|
|
70
|
-
|
|
71
|
+
if (arg === '--') {
|
|
72
|
+
positional.push(...argv.slice(i + 1))
|
|
73
|
+
break
|
|
74
|
+
}
|
|
75
|
+
if (VALUE_FLAGS.has(arg)) {
|
|
76
|
+
const value = argv[i + 1]
|
|
77
|
+
if (!value || value.startsWith('-')) throw new Error(`Missing value for ${arg}.`)
|
|
78
|
+
values[arg] = value
|
|
79
|
+
i++
|
|
80
|
+
} else if (BOOLEAN_FLAGS.has(arg)) {
|
|
81
|
+
flags.add(arg)
|
|
82
|
+
} else if (arg.startsWith('-') && arg.length > 1) {
|
|
83
|
+
throw new Error(`Unknown option ${arg}. Run noguard --help.`)
|
|
84
|
+
} else {
|
|
85
|
+
positional.push(arg)
|
|
86
|
+
}
|
|
71
87
|
}
|
|
72
88
|
return { flags, values, positional }
|
|
73
89
|
}
|
|
@@ -107,10 +123,13 @@ async function main() {
|
|
|
107
123
|
console.log(`${gradient('NoGuard', NOGUARD_GRADIENT)} ${SOFT_GRAY}v${VERSION}${RST}`)
|
|
108
124
|
return
|
|
109
125
|
}
|
|
126
|
+
const explicitMode = values['--permission-mode']
|
|
127
|
+
const mode = explicitMode ? permissionMode(explicitMode) : null
|
|
128
|
+
if (explicitMode && (!mode || mode === 'yolo')) throw new Error('Unknown permission mode. Choose ask, accept-edits or plan.')
|
|
110
129
|
const session = {
|
|
111
130
|
model: values['--model'] ?? values['-m'],
|
|
112
131
|
tools: !flags.has('--no-tools'),
|
|
113
|
-
mode: flags.has('--yolo') || flags.has('--dangerously-skip-permissions') ? 'yolo' : flags.has('--accept-edits') ? 'accept-edits' : 'ask',
|
|
132
|
+
mode: mode ?? (flags.has('--yolo') || flags.has('--dangerously-skip-permissions') ? 'yolo' : flags.has('--accept-edits') ? 'accept-edits' : 'ask'),
|
|
114
133
|
}
|
|
115
134
|
if (flags.has('-p') || flags.has('--print')) {
|
|
116
135
|
const typed = (command === 'chat' ? positional.slice(1) : positional).join(' ')
|
|
@@ -241,5 +260,5 @@ async function main() {
|
|
|
241
260
|
|
|
242
261
|
main().catch(err => {
|
|
243
262
|
console.error(`${HOT_PINK}✗${RST} ${err.message}`)
|
|
244
|
-
process.
|
|
263
|
+
process.exitCode = 1
|
|
245
264
|
})
|
package/lib/agent.mjs
CHANGED
|
@@ -2,6 +2,7 @@
|
|
|
2
2
|
// results back, and repeat until the model answers without a tool call.
|
|
3
3
|
|
|
4
4
|
import { randomBytes, randomUUID } from 'node:crypto'
|
|
5
|
+
import { setTimeout as delay } from 'node:timers/promises'
|
|
5
6
|
import { ApiError, streamMessages } from './api.mjs'
|
|
6
7
|
import { isInsideReal, resolvePath } from './files.mjs'
|
|
7
8
|
import { clean, MarkdownStream, Spinner, toolHeader, toolResultLine, BOLD, DIM, RST, UNDERLINE, NEON_CYAN, HOT_PINK, LIME, ORANGE, BRIGHT_WHITE, SOFT_GRAY } from './render.mjs'
|
|
@@ -26,7 +27,19 @@ const PREFIX_COMMANDS = new Set([
|
|
|
26
27
|
const PLAIN_ARG = /^[A-Za-z0-9_./:@+-]+$/
|
|
27
28
|
const ELIDED = '[Earlier tool output removed to save context. Run the tool again if you need it.]'
|
|
28
29
|
|
|
29
|
-
export const MODES = {
|
|
30
|
+
export const MODES = {
|
|
31
|
+
ask: 'ask before edits and commands',
|
|
32
|
+
'accept-edits': 'edits allowed, ask before commands',
|
|
33
|
+
plan: 'inspect workspace files and propose a plan',
|
|
34
|
+
yolo: 'everything allowed without asking',
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export function permissionMode(value) {
|
|
38
|
+
const aliases = { default: 'ask', manual: 'ask', acceptedits: 'accept-edits', edits: 'accept-edits' }
|
|
39
|
+
const name = String(value).toLowerCase()
|
|
40
|
+
if (Object.hasOwn(aliases, name)) return aliases[name]
|
|
41
|
+
return Object.hasOwn(MODES, name) ? name : null
|
|
42
|
+
}
|
|
30
43
|
|
|
31
44
|
/**
|
|
32
45
|
* What "always" remembers for a command: { prefix } (program plus subcommand, e.g. "npm test", extended by
|
|
@@ -63,9 +76,12 @@ export class Permissions {
|
|
|
63
76
|
|
|
64
77
|
/** null when the call may run now, else what to ask the user about. */
|
|
65
78
|
check(tool, input, cwd) {
|
|
66
|
-
if (tool.kind === 'meta') return null
|
|
67
79
|
// Symlinks are resolved first, so a link inside the folder can't reach outside it unasked.
|
|
68
80
|
const outside = tool.paths(input).some(p => p != null && !isInsideReal(cwd, resolvePath(cwd, p)))
|
|
81
|
+
if (this.mode === 'plan') {
|
|
82
|
+
return tool.kind === 'read' && !outside ? null : 'Plan mode allows only reads inside the working directory.'
|
|
83
|
+
}
|
|
84
|
+
if (tool.kind === 'meta') return null
|
|
69
85
|
if (tool.kind === 'read') return outside && !this.outside && this.mode !== 'yolo' ? 'read outside the working directory' : null
|
|
70
86
|
if (this.mode === 'yolo') return null
|
|
71
87
|
if (tool.kind === 'edit') {
|
|
@@ -120,9 +136,10 @@ export class Agent {
|
|
|
120
136
|
this.getModel = getModel
|
|
121
137
|
this.permissions = permissions
|
|
122
138
|
this.useTools = tools
|
|
139
|
+
this.report = ui.interactive ? console.log : console.error
|
|
123
140
|
this.getLibraries = getLibraries
|
|
124
141
|
this.ctx = { cwd, readFiles: new Map(), todos: [], signal: null }
|
|
125
|
-
this.spinner = new Spinner()
|
|
142
|
+
this.spinner = new Spinner(ui.interactive ? process.stdout : process.stderr)
|
|
126
143
|
this.reset()
|
|
127
144
|
}
|
|
128
145
|
|
|
@@ -166,7 +183,7 @@ export class Agent {
|
|
|
166
183
|
this.#pushUserText(text)
|
|
167
184
|
this.controller = new AbortController()
|
|
168
185
|
this.ctx.signal = this.controller.signal
|
|
169
|
-
let spent = 0, balance = null, ok = true
|
|
186
|
+
let spent = 0, balance = null, ok = true, interrupted = false
|
|
170
187
|
try {
|
|
171
188
|
for (let step = 0; step < MAX_STEPS; step++) {
|
|
172
189
|
const reply = await this.#request()
|
|
@@ -178,6 +195,7 @@ export class Agent {
|
|
|
178
195
|
if (!calls.length) break
|
|
179
196
|
const results = []
|
|
180
197
|
let halt = false
|
|
198
|
+
const feedback = []
|
|
181
199
|
for (const call of calls) {
|
|
182
200
|
if (halt || this.controller.signal.aborted) {
|
|
183
201
|
results.push({ type: 'tool_result', tool_use_id: call.id, content: 'Not run: the user stopped this turn.', is_error: true })
|
|
@@ -185,22 +203,31 @@ export class Agent {
|
|
|
185
203
|
}
|
|
186
204
|
const outcome = await this.#runTool(call)
|
|
187
205
|
results.push(outcome.result)
|
|
188
|
-
if (outcome.feedback)
|
|
206
|
+
if (outcome.feedback) feedback.push({ type: 'text', text: outcome.feedback })
|
|
189
207
|
if (outcome.halt) halt = true
|
|
208
|
+
if (outcome.blocked) ok = false
|
|
190
209
|
}
|
|
191
|
-
this.messages.push({ role: 'user', content: results })
|
|
210
|
+
this.messages.push({ role: 'user', content: [...results, ...feedback] })
|
|
192
211
|
if (halt || this.controller.signal.aborted) {
|
|
193
|
-
if (this.controller.signal.aborted)
|
|
212
|
+
if (this.controller.signal.aborted) this.report(` ${SOFT_GRAY}⎿ Interrupted. Tell NoGuard what to do instead.${RST}`)
|
|
194
213
|
break
|
|
195
214
|
}
|
|
196
|
-
if (step === MAX_STEPS - 1)
|
|
215
|
+
if (step === MAX_STEPS - 1) {
|
|
216
|
+
ok = false
|
|
217
|
+
this.report(`${ORANGE}⚠${RST} Stopped after ${MAX_STEPS} steps. Send a message to continue.`)
|
|
218
|
+
}
|
|
197
219
|
}
|
|
220
|
+
} catch (err) {
|
|
221
|
+
if (!this.controller.signal.aborted) throw err
|
|
222
|
+
this.#interrupted()
|
|
198
223
|
} finally {
|
|
199
224
|
this.spinner.stop()
|
|
225
|
+
if (this.controller.signal.aborted) ok = false
|
|
226
|
+
interrupted = this.controller.signal.aborted
|
|
200
227
|
this.controller = null
|
|
201
228
|
this.ctx.signal = null
|
|
202
229
|
}
|
|
203
|
-
return { spent, balance, ok }
|
|
230
|
+
return { spent, balance, ok, interrupted }
|
|
204
231
|
}
|
|
205
232
|
|
|
206
233
|
#budget(model) {
|
|
@@ -258,86 +285,93 @@ export class Agent {
|
|
|
258
285
|
if (err.status === 429 && retries < 3) {
|
|
259
286
|
retries++
|
|
260
287
|
this.spinner.start(`Rate limited, retrying in 15s (${retries}/3)…`)
|
|
261
|
-
await
|
|
288
|
+
await delay(15_000, undefined, { signal: this.controller.signal })
|
|
262
289
|
this.spinner.stop()
|
|
263
290
|
continue
|
|
264
291
|
}
|
|
265
292
|
if (err.code === 'request_too_large' && retries < 2) {
|
|
266
293
|
retries++
|
|
267
294
|
if (this.compact(Math.floor(this.#size() * 0.6))) {
|
|
268
|
-
|
|
295
|
+
this.report(` ${DIM}Context is full: removed older tool output and retrying.${RST}`)
|
|
269
296
|
continue
|
|
270
297
|
}
|
|
271
298
|
}
|
|
272
299
|
return { blocks: [], spent: 0, balance: null, stop: true, failed: true, error: this.#explain(err) }
|
|
273
300
|
}
|
|
274
|
-
|
|
275
|
-
retries++
|
|
276
|
-
console.log(` ${DIM}Connection problem (${err.message}); retrying…${RST}`)
|
|
277
|
-
await new Promise(r => setTimeout(r, 2000))
|
|
278
|
-
continue
|
|
279
|
-
}
|
|
280
|
-
console.log(`${HOT_PINK}✗${RST} Connection error: ${err.message}`)
|
|
301
|
+
this.report(`${HOT_PINK}✗${RST} Connection error: ${err.message}`)
|
|
281
302
|
return { blocks: [], spent: 0, balance: null, stop: true, failed: true }
|
|
282
303
|
}
|
|
283
304
|
}
|
|
284
305
|
}
|
|
285
306
|
|
|
286
307
|
#interrupted() {
|
|
287
|
-
|
|
288
|
-
return { blocks: [], spent: 0, balance: null, stop: true, failed:
|
|
308
|
+
this.report(`\n ${DIM}⎿ Interrupted.${RST}`)
|
|
309
|
+
return { blocks: [], spent: 0, balance: null, stop: true, failed: true }
|
|
289
310
|
}
|
|
290
311
|
|
|
291
312
|
#explain(err) {
|
|
292
|
-
if (err.status === 401 || err.code === 'invalid_token')
|
|
293
|
-
else if (err.code === 'out_of_credits' || err.status === 402)
|
|
294
|
-
else if (err.code === 'model_unavailable')
|
|
295
|
-
else
|
|
313
|
+
if (err.status === 401 || err.code === 'invalid_token') this.report(`${HOT_PINK}✗${RST} Session expired. Run ${BOLD}noguard login${RST} again.`)
|
|
314
|
+
else if (err.code === 'out_of_credits' || err.status === 402) this.report(`${ORANGE}⚠${RST} ${err.message}\n Top up at ${NEON_CYAN}${UNDERLINE}https://noguard.ai/credits${RST}`)
|
|
315
|
+
else if (err.code === 'model_unavailable') this.report(`${ORANGE}⚠${RST} ${err.message} Run /models to pick another.`)
|
|
316
|
+
else this.report(`${HOT_PINK}✗${RST} ${err.message}`)
|
|
296
317
|
return err.message
|
|
297
318
|
}
|
|
298
319
|
|
|
299
320
|
async #stream(model, maxOut) {
|
|
300
321
|
const libraries = this.getLibraries()
|
|
322
|
+
const planning = this.useTools && this.permissions.mode === 'plan'
|
|
323
|
+
const system = planning ? `${this.system}\n\nThe user selected Plan mode. Inspect files inside the working directory and propose a plan. Do not edit files, run commands or retrieve network resources.` : this.system
|
|
301
324
|
const body = {
|
|
302
325
|
...(model ? { model: model.id } : {}),
|
|
303
326
|
max_tokens: maxOut,
|
|
304
327
|
messages: this.messages,
|
|
305
328
|
noguard_persona: true,
|
|
306
329
|
metadata: { conversation_id: this.conversationId },
|
|
307
|
-
...(
|
|
330
|
+
...(system ? { system } : {}),
|
|
308
331
|
...(this.useTools ? { tools: toolDefinitions() } : {}),
|
|
309
332
|
...(libraries.length ? { libraries } : {}),
|
|
310
333
|
}
|
|
311
334
|
const blocks = new Map()
|
|
312
335
|
let md = null, spent = 0, balance = null, stopReason = null, streamError = null
|
|
336
|
+
let started = false, completed = false
|
|
313
337
|
const signal = this.controller.signal
|
|
314
338
|
this.spinner.start('Thinking…')
|
|
315
339
|
try {
|
|
316
340
|
for await (const { event, data } of streamMessages(body, { signal })) {
|
|
341
|
+
started = true
|
|
317
342
|
if (event === 'content_block_start') {
|
|
318
343
|
const block = data.content_block
|
|
319
344
|
if (block.type === 'text') blocks.set(data.index, { type: 'text', text: '' })
|
|
320
345
|
else if (block.type === 'tool_use') {
|
|
321
346
|
md?.end(); md = null
|
|
322
|
-
blocks.set(data.index, { type: 'tool_use', id: block.id, name: block.name, json: '' })
|
|
323
|
-
this.spinner.start(`${block.name}…`)
|
|
347
|
+
blocks.set(data.index, { type: 'tool_use', id: block.id, name: block.name, json: '', closed: false })
|
|
348
|
+
this.spinner.start(`${clean(block.name)}…`)
|
|
324
349
|
}
|
|
325
350
|
} else if (event === 'content_block_delta') {
|
|
326
351
|
const block = blocks.get(data.index)
|
|
327
352
|
if (!block) continue
|
|
328
353
|
if (data.delta?.type === 'text_delta' && block.type === 'text') {
|
|
329
354
|
this.spinner.stop()
|
|
330
|
-
|
|
331
|
-
|
|
355
|
+
if (this.ui.interactive) {
|
|
356
|
+
md ??= new MarkdownStream()
|
|
357
|
+
md.write(data.delta.text)
|
|
358
|
+
} else {
|
|
359
|
+
process.stdout.write(clean(data.delta.text))
|
|
360
|
+
}
|
|
332
361
|
block.text += data.delta.text
|
|
333
362
|
} else if (data.delta?.type === 'input_json_delta' && block.type === 'tool_use') {
|
|
334
363
|
block.json += data.delta.partial_json
|
|
335
364
|
}
|
|
365
|
+
} else if (event === 'content_block_stop') {
|
|
366
|
+
const block = blocks.get(data.index)
|
|
367
|
+
if (block) block.closed = true
|
|
336
368
|
} else if (event === 'message_delta') {
|
|
337
369
|
stopReason = data.delta?.stop_reason ?? stopReason
|
|
338
370
|
} else if (event === 'noguard_credits') {
|
|
339
371
|
spent = data.spent ?? spent
|
|
340
372
|
balance = data.balance ?? balance
|
|
373
|
+
} else if (event === 'message_stop') {
|
|
374
|
+
completed = true
|
|
341
375
|
} else if (event === 'error') {
|
|
342
376
|
streamError = data?.error?.message ?? 'Something went wrong.'
|
|
343
377
|
}
|
|
@@ -348,10 +382,11 @@ export class Agent {
|
|
|
348
382
|
if (err.name === 'AbortError' || signal.aborted) {
|
|
349
383
|
// Keep what was said; drop tool calls that never ran.
|
|
350
384
|
const text = [...blocks.values()].filter(b => b.type === 'text' && b.text.trim()).map(b => ({ type: 'text', text: b.text }))
|
|
351
|
-
|
|
385
|
+
this.report(`\n ${DIM}⎿ Interrupted.${RST}`)
|
|
352
386
|
return { blocks: text, spent, balance, stop: true }
|
|
353
387
|
}
|
|
354
|
-
throw err
|
|
388
|
+
if (!started) throw err
|
|
389
|
+
streamError = 'Connection lost during the reply.'
|
|
355
390
|
}
|
|
356
391
|
md?.end()
|
|
357
392
|
this.spinner.stop()
|
|
@@ -373,14 +408,25 @@ export class Agent {
|
|
|
373
408
|
if (parseError) Object.defineProperty(call, 'parseError', { value: parseError, enumerable: false })
|
|
374
409
|
finished.push(call)
|
|
375
410
|
}
|
|
411
|
+
const calls = finished.filter(block => block.type === 'tool_use')
|
|
412
|
+
if (!streamError && !completed) streamError = 'The reply ended before it was complete.'
|
|
413
|
+
if (!streamError && calls.length && (!this.useTools || stopReason !== 'tool_use'
|
|
414
|
+
|| [...blocks.values()].some(block => block.type === 'tool_use' && (!block.closed || !TOOLS_BY_NAME.has(block.name))))) {
|
|
415
|
+
streamError = 'The model returned an incomplete or unavailable tool call.'
|
|
416
|
+
}
|
|
417
|
+
if (!streamError && stopReason === 'tool_use' && !calls.length) streamError = 'The model returned no tool call.'
|
|
376
418
|
if (streamError) {
|
|
377
|
-
|
|
419
|
+
this.report(`${HOT_PINK}✗${RST} ${streamError}`)
|
|
378
420
|
return { blocks: finished.filter(b => b.type === 'text'), spent, balance, stop: true, failed: true }
|
|
379
421
|
}
|
|
380
422
|
if (stopReason === 'max_tokens' && !finished.some(b => b.type === 'tool_use')) {
|
|
381
|
-
|
|
423
|
+
this.report(` ${DIM}(The reply hit its length limit. Say "continue" to get the rest.)${RST}`)
|
|
424
|
+
return { blocks: finished, spent, balance, stop: true, failed: true }
|
|
425
|
+
}
|
|
426
|
+
if (stopReason === 'refusal') {
|
|
427
|
+
this.report(` ${DIM}(The model declined this one.)${RST}`)
|
|
428
|
+
return { blocks: finished, spent, balance, stop: true, failed: true }
|
|
382
429
|
}
|
|
383
|
-
if (stopReason === 'refusal') console.log(` ${DIM}(The model declined this one.)${RST}`)
|
|
384
430
|
return { blocks: finished, spent, balance, stop: false }
|
|
385
431
|
}
|
|
386
432
|
|
|
@@ -388,32 +434,36 @@ export class Agent {
|
|
|
388
434
|
const tool = TOOLS_BY_NAME.get(call.name)
|
|
389
435
|
const fail = (message, extra = {}) => ({ result: { type: 'tool_result', tool_use_id: call.id, content: message, is_error: true }, ...extra })
|
|
390
436
|
if (!tool) {
|
|
391
|
-
|
|
392
|
-
|
|
437
|
+
this.report(toolHeader(call.name))
|
|
438
|
+
this.report(toolResultLine(`Unknown tool`, HOT_PINK))
|
|
393
439
|
return fail(`There is no tool named ${call.name}.`)
|
|
394
440
|
}
|
|
395
441
|
let label = ''
|
|
396
442
|
try { label = tool.label(call.input, this.ctx) } catch { /* bad input shows no label */ }
|
|
397
|
-
|
|
443
|
+
this.report(toolHeader(tool.name, label))
|
|
398
444
|
if (call.parseError) {
|
|
399
|
-
|
|
445
|
+
this.report(toolResultLine('Invalid arguments', HOT_PINK))
|
|
400
446
|
return fail(`The tool arguments were not valid JSON (${call.parseError}). The reply may have been cut off; try again with smaller input.`)
|
|
401
447
|
}
|
|
402
448
|
const missing = (tool.input_schema.required ?? []).filter(key => call.input[key] === undefined)
|
|
403
449
|
if (missing.length) {
|
|
404
|
-
|
|
450
|
+
this.report(toolResultLine(`Missing ${missing.join(', ')}`, HOT_PINK))
|
|
405
451
|
return fail(`Missing required argument${missing.length > 1 ? 's' : ''}: ${missing.join(', ')}.`)
|
|
406
452
|
}
|
|
407
453
|
const reason = this.permissions.check(tool, call.input, this.cwd)
|
|
408
454
|
if (reason) {
|
|
455
|
+
if (this.permissions.mode === 'plan') {
|
|
456
|
+
this.report(toolResultLine(reason, ORANGE))
|
|
457
|
+
return fail(reason)
|
|
458
|
+
}
|
|
409
459
|
let preview = null
|
|
410
460
|
try { preview = tool.preview?.(call.input, this.ctx) } catch { /* the run reports the problem */ }
|
|
411
|
-
if (preview)
|
|
461
|
+
if (preview) this.report(preview.split('\n').map(line => ` ${line}`).join('\n'))
|
|
412
462
|
if (tool.kind === 'exec') {
|
|
413
463
|
// The header may be shortened: show exactly what will run before asking.
|
|
414
464
|
const command = clean(String(call.input.command ?? ''))
|
|
415
|
-
if (command !== label)
|
|
416
|
-
if (call.input.description)
|
|
465
|
+
if (command !== label) this.report(command.split('\n').map(line => ` ${NEON_CYAN}${line}${RST}`).join('\n'))
|
|
466
|
+
if (call.input.description) this.report(` ${DIM}${clean(String(call.input.description))}${RST}`)
|
|
417
467
|
}
|
|
418
468
|
const always = this.permissions.alwaysLabel(tool, call.input)
|
|
419
469
|
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} `)
|
|
@@ -421,22 +471,23 @@ export class Agent {
|
|
|
421
471
|
const why = this.ui.interactive
|
|
422
472
|
? 'Not run: the user interrupted.'
|
|
423
473
|
: `Not run: this needs approval, and nobody can approve it in print mode. Rerun with --accept-edits or --yolo to allow it.`
|
|
424
|
-
|
|
425
|
-
return fail(why, { halt: true })
|
|
474
|
+
this.report(toolResultLine(this.ui.interactive ? 'Interrupted' : 'Needs approval (print mode)', ORANGE))
|
|
475
|
+
return fail(why, { halt: true, blocked: !this.ui.interactive })
|
|
426
476
|
}
|
|
427
477
|
const reply = answer.trim()
|
|
428
478
|
const word = reply.toLowerCase()
|
|
429
|
-
if (word === 'a' || word === 'always') {
|
|
430
|
-
|
|
431
|
-
} else if (
|
|
479
|
+
if (always && (word === 'a' || word === 'always')) {
|
|
480
|
+
this.permissions.alwaysAllow(tool, call.input)
|
|
481
|
+
} else if (word !== 'y' && word !== 'yes') {
|
|
432
482
|
const feedback = ['n', 'no'].includes(word) ? '' : reply
|
|
433
|
-
|
|
483
|
+
this.report(toolResultLine('Denied', ORANGE))
|
|
434
484
|
if (feedback) {
|
|
435
485
|
return fail('The user denied this action.', { feedback: `The user denied that and said: ${feedback}` })
|
|
436
486
|
}
|
|
437
487
|
return fail('The user denied this action. Stop and wait for them to say what to do instead.', { halt: true })
|
|
438
488
|
}
|
|
439
489
|
}
|
|
490
|
+
if (this.ctx.signal.aborted) return fail('Not run: the user stopped this turn.', { halt: true })
|
|
440
491
|
if (tool.kind === 'exec' || tool.kind === 'network') this.spinner.start(tool.kind === 'exec' ? 'Running…' : 'Fetching…')
|
|
441
492
|
let outcome
|
|
442
493
|
try {
|
|
@@ -446,11 +497,11 @@ export class Agent {
|
|
|
446
497
|
}
|
|
447
498
|
this.spinner.stop()
|
|
448
499
|
if (outcome.error) {
|
|
449
|
-
|
|
500
|
+
this.report(toolResultLine(clean(outcome.error), HOT_PINK))
|
|
450
501
|
return fail(outcome.error)
|
|
451
502
|
}
|
|
452
|
-
if (outcome.display)
|
|
453
|
-
if (outcome.diff)
|
|
503
|
+
if (outcome.display) this.report(toolResultLine(outcome.display))
|
|
504
|
+
if (outcome.diff) this.report(outcome.diff.split('\n').map(line => ` ${line}`).join('\n'))
|
|
454
505
|
return { result: { type: 'tool_result', tool_use_id: call.id, content: outcome.content || '(no output)', ...(outcome.isError ? { is_error: true } : {}) } }
|
|
455
506
|
}
|
|
456
507
|
}
|
package/lib/api.mjs
CHANGED
|
@@ -1,76 +1,81 @@
|
|
|
1
|
-
import { getToken, getEndpoint } from './config.mjs'
|
|
2
|
-
|
|
3
|
-
export class ApiError extends Error {
|
|
4
|
-
constructor(status, body) {
|
|
5
|
-
const msg = body?.error?.message ?? body?.error_description ?? body?.message ?? `HTTP ${status}`
|
|
6
|
-
super(msg)
|
|
7
|
-
this.status = status
|
|
8
|
-
this.code = body?.error?.type ?? body?.error ?? body?.code ?? 'unknown'
|
|
9
|
-
this.body = body
|
|
10
|
-
}
|
|
11
|
-
}
|
|
12
|
-
|
|
13
|
-
function headers(token) {
|
|
14
|
-
const h = { 'Content-Type': 'application/json', 'Accept': 'application/json' }
|
|
15
|
-
if (token) h['Authorization'] = `Bearer ${token}`
|
|
16
|
-
return h
|
|
17
|
-
}
|
|
18
|
-
|
|
19
|
-
export async function request(method, path, body, opts = {}) {
|
|
20
|
-
const base = getEndpoint()
|
|
21
|
-
const token = opts.token ?? getToken()
|
|
22
|
-
const url = `${base}${path}`
|
|
23
|
-
const res = await fetch(url, {
|
|
24
|
-
method,
|
|
25
|
-
headers: headers(token),
|
|
26
|
-
body: body ? JSON.stringify(body) : undefined,
|
|
27
|
-
signal: opts.signal,
|
|
28
|
-
})
|
|
29
|
-
if (path === '/api/v1/messages' && opts.stream) return res
|
|
30
|
-
const json = await res.json().catch(() => null)
|
|
31
|
-
if (!res.ok) throw new ApiError(res.status, json)
|
|
32
|
-
return json
|
|
33
|
-
}
|
|
34
|
-
|
|
35
|
-
export async function get(path, opts) { return request('GET', path, null, opts) }
|
|
36
|
-
export async function post(path, body, opts) { return request('POST', path, body, opts) }
|
|
37
|
-
export async function del(path, opts) { return request('DELETE', path, null, opts) }
|
|
38
|
-
|
|
39
|
-
export async function* streamMessages(body, opts = {}) {
|
|
40
|
-
const base = getEndpoint()
|
|
41
|
-
const token = getToken()
|
|
42
|
-
const res = await fetch(`${base}/api/v1/messages`, {
|
|
43
|
-
method: 'POST',
|
|
44
|
-
headers: { ...headers(token), 'Accept': 'text/event-stream' },
|
|
45
|
-
body: JSON.stringify({ ...body, stream: true }),
|
|
46
|
-
signal: opts.signal,
|
|
47
|
-
})
|
|
48
|
-
if (!res.ok) {
|
|
49
|
-
const json = await res.json().catch(() => null)
|
|
50
|
-
throw new ApiError(res.status, json)
|
|
51
|
-
}
|
|
52
|
-
const reader = res.body.getReader()
|
|
53
|
-
const decoder = new TextDecoder()
|
|
54
|
-
let buffer = ''
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
}
|
|
1
|
+
import { getToken, getEndpoint } from './config.mjs'
|
|
2
|
+
|
|
3
|
+
export class ApiError extends Error {
|
|
4
|
+
constructor(status, body) {
|
|
5
|
+
const msg = body?.error?.message ?? body?.error_description ?? body?.message ?? `HTTP ${status}`
|
|
6
|
+
super(msg)
|
|
7
|
+
this.status = status
|
|
8
|
+
this.code = body?.error?.type ?? body?.error ?? body?.code ?? 'unknown'
|
|
9
|
+
this.body = body
|
|
10
|
+
}
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
function headers(token) {
|
|
14
|
+
const h = { 'Content-Type': 'application/json', 'Accept': 'application/json' }
|
|
15
|
+
if (token) h['Authorization'] = `Bearer ${token}`
|
|
16
|
+
return h
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export async function request(method, path, body, opts = {}) {
|
|
20
|
+
const base = getEndpoint()
|
|
21
|
+
const token = opts.token ?? getToken()
|
|
22
|
+
const url = `${base}${path}`
|
|
23
|
+
const res = await fetch(url, {
|
|
24
|
+
method,
|
|
25
|
+
headers: headers(token),
|
|
26
|
+
body: body ? JSON.stringify(body) : undefined,
|
|
27
|
+
signal: opts.signal,
|
|
28
|
+
})
|
|
29
|
+
if (path === '/api/v1/messages' && opts.stream) return res
|
|
30
|
+
const json = await res.json().catch(() => null)
|
|
31
|
+
if (!res.ok) throw new ApiError(res.status, json)
|
|
32
|
+
return json
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export async function get(path, opts) { return request('GET', path, null, opts) }
|
|
36
|
+
export async function post(path, body, opts) { return request('POST', path, body, opts) }
|
|
37
|
+
export async function del(path, opts) { return request('DELETE', path, null, opts) }
|
|
38
|
+
|
|
39
|
+
export async function* streamMessages(body, opts = {}) {
|
|
40
|
+
const base = getEndpoint()
|
|
41
|
+
const token = getToken()
|
|
42
|
+
const res = await fetch(`${base}/api/v1/messages`, {
|
|
43
|
+
method: 'POST',
|
|
44
|
+
headers: { ...headers(token), 'Accept': 'text/event-stream' },
|
|
45
|
+
body: JSON.stringify({ ...body, stream: true }),
|
|
46
|
+
signal: opts.signal,
|
|
47
|
+
})
|
|
48
|
+
if (!res.ok) {
|
|
49
|
+
const json = await res.json().catch(() => null)
|
|
50
|
+
throw new ApiError(res.status, json)
|
|
51
|
+
}
|
|
52
|
+
const reader = res.body.getReader()
|
|
53
|
+
const decoder = new TextDecoder()
|
|
54
|
+
let buffer = ''
|
|
55
|
+
let event = ''
|
|
56
|
+
let data = []
|
|
57
|
+
try {
|
|
58
|
+
while (true) {
|
|
59
|
+
const { done, value } = await reader.read()
|
|
60
|
+
if (done) break
|
|
61
|
+
buffer += decoder.decode(value, { stream: true })
|
|
62
|
+
const lines = buffer.split('\n')
|
|
63
|
+
buffer = lines.pop()
|
|
64
|
+
for (const raw of lines) {
|
|
65
|
+
const line = raw.endsWith('\r') ? raw.slice(0, -1) : raw
|
|
66
|
+
if (!line) {
|
|
67
|
+
if (data.length) yield { event, data: JSON.parse(data.join('\n')) }
|
|
68
|
+
event = ''
|
|
69
|
+
data = []
|
|
70
|
+
} else if (line.startsWith('event:')) {
|
|
71
|
+
event = line.slice(6).trim()
|
|
72
|
+
} else if (line.startsWith('data:')) {
|
|
73
|
+
data.push(line.slice(5).replace(/^ /, ''))
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
} finally {
|
|
78
|
+
await reader.cancel().catch(() => {})
|
|
79
|
+
reader.releaseLock()
|
|
80
|
+
}
|
|
81
|
+
}
|