noguard 1.0.0 → 1.1.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/agent.mjs ADDED
@@ -0,0 +1,449 @@
1
+ // The agent loop: stream a reply, run the tools it asks for (with the user's approval), send the
2
+ // results back, and repeat until the model answers without a tool call.
3
+
4
+ import { randomBytes, randomUUID } from 'node:crypto'
5
+ import { ApiError, streamMessages } from './api.mjs'
6
+ import { isInsideReal, resolvePath } from './files.mjs'
7
+ import { clean, MarkdownStream, Spinner, toolHeader, toolResultLine, BOLD, CYAN, DIM, RED, RST, YELLOW } from './render.mjs'
8
+ import { systemPrompt } from './context.mjs'
9
+ import { TOOLS_BY_NAME, toolDefinitions } from './tools.mjs'
10
+
11
+ const MAX_STEPS = 200
12
+ const TOOL_ID = /^[A-Za-z_][A-Za-z0-9_.-]{0,127}$/
13
+ // Anything that could make an approved command run or reach something else: separators, redirection,
14
+ // substitution, expansion, globs, home and history expansion, quotes, escapes and control characters.
15
+ const UNSAFE_COMMAND = /[;&|<>`$(){}\\~*?%^!'"\x00-\x1f\x7f]/
16
+ // The only commands "always" widens to later variants: reading the repo, and the project's own build and tests.
17
+ // Anything that can name arbitrary code or change state (npm run, git config, git branch <name>, make targets,
18
+ // mvn/gradle goals, …) is remembered exactly instead.
19
+ const PREFIX_COMMANDS = new Set([
20
+ 'git status', 'git diff', 'git log', 'git show',
21
+ 'npm test', 'pnpm test', 'yarn test', 'bun test', 'cargo test', 'cargo build', 'cargo check', 'cargo clippy',
22
+ 'go test', 'go build', 'go vet', 'dotnet test', 'dotnet build',
23
+ ])
24
+ // What may follow an approved prefix: plain words and relative paths inside the folder, never options (which can
25
+ // write files or run programs), absolute or drive paths, or "..".
26
+ const PLAIN_ARG = /^[A-Za-z0-9_./:@+-]+$/
27
+ const ELIDED = '[Earlier tool output removed to save context. Run the tool again if you need it.]'
28
+
29
+ export const MODES = { ask: 'ask before edits and commands', 'accept-edits': 'edits allowed, ask before commands', yolo: 'everything allowed without asking' }
30
+
31
+ /**
32
+ * What "always" remembers for a command: { prefix } (program plus subcommand, e.g. "npm test", extended by
33
+ * further arguments), { exact } (only this command again), or null when nothing about it is safe to remember.
34
+ * Only the read, build and test commands in PREFIX_COMMANDS become a prefix; anything else ("python -c …",
35
+ * "cat file", "npm run x") could reach other files or code through further arguments, so only the exact
36
+ * command is remembered.
37
+ */
38
+ function commandRule(command) {
39
+ const text = command.trim()
40
+ if (!text || UNSAFE_COMMAND.test(text)) return null
41
+ const words = text.split(/\s+/)
42
+ const pair = words.slice(0, 2).join(' ')
43
+ return PREFIX_COMMANDS.has(pair) ? { prefix: pair, exact: text } : { exact: text }
44
+ }
45
+
46
+ /** A later command an approved prefix covers: the prefix plus plain arguments that stay inside the folder. */
47
+ function extendsPrefix(command, prefix, cwd) {
48
+ if (command === prefix) return true
49
+ if (!command.startsWith(`${prefix} `)) return false
50
+ return command.slice(prefix.length).trim().split(/\s+/).every(arg =>
51
+ PLAIN_ARG.test(arg) && !arg.startsWith('-') && !arg.startsWith('/') && !/^[A-Za-z]:/.test(arg)
52
+ && !arg.split('/').includes('..') && isInsideReal(cwd, resolvePath(cwd, arg.split(':').pop())))
53
+ }
54
+
55
+ export class Permissions {
56
+ constructor(mode = 'ask') {
57
+ this.mode = mode
58
+ this.prefixes = new Set()
59
+ this.exact = new Set()
60
+ this.hosts = new Set()
61
+ this.outside = false
62
+ }
63
+
64
+ /** null when the call may run now, else what to ask the user about. */
65
+ check(tool, input, cwd) {
66
+ if (tool.kind === 'meta') return null
67
+ // Symlinks are resolved first, so a link inside the folder can't reach outside it unasked.
68
+ const outside = tool.paths(input).some(p => p != null && !isInsideReal(cwd, resolvePath(cwd, p)))
69
+ if (tool.kind === 'read') return outside && !this.outside && this.mode !== 'yolo' ? 'read outside the working directory' : null
70
+ if (this.mode === 'yolo') return null
71
+ if (tool.kind === 'edit') {
72
+ if (outside) return 'change a file outside the working directory'
73
+ return this.mode === 'accept-edits' ? null : 'make this edit'
74
+ }
75
+ if (tool.kind === 'exec') {
76
+ const command = String(input.command ?? '').trim()
77
+ const allowed = !UNSAFE_COMMAND.test(command)
78
+ && (this.exact.has(command) || [...this.prefixes].some(p => extendsPrefix(command, p, cwd)))
79
+ return allowed ? null : 'run this command'
80
+ }
81
+ if (tool.kind === 'network') {
82
+ let host = ''
83
+ try { host = new URL(String(input.url)).host } catch { /* invalid URLs fail in the tool */ }
84
+ return this.hosts.has(host) ? null : `fetch from ${host || 'this URL'}`
85
+ }
86
+ return 'use this tool'
87
+ }
88
+
89
+ alwaysAllow(tool, input) {
90
+ if (tool.kind === 'read') this.outside = true
91
+ else if (tool.kind === 'edit') { if (this.mode === 'ask') this.mode = 'accept-edits' }
92
+ else if (tool.kind === 'exec') {
93
+ const rule = commandRule(String(input.command ?? ''))
94
+ if (rule?.prefix) this.prefixes.add(rule.prefix)
95
+ if (rule?.exact) this.exact.add(rule.exact)
96
+ }
97
+ else if (tool.kind === 'network') { try { this.hosts.add(new URL(String(input.url)).host) } catch { /* nothing to remember */ } }
98
+ }
99
+
100
+ alwaysLabel(tool, input) {
101
+ if (tool.kind === 'read') return 'reads outside this folder'
102
+ if (tool.kind === 'edit') return 'all edits this session'
103
+ if (tool.kind === 'exec') {
104
+ const rule = commandRule(String(input.command ?? ''))
105
+ return rule?.prefix ? `"${rule.prefix}" commands` : rule?.exact ? 'this exact command' : null
106
+ }
107
+ if (tool.kind === 'network') { try { return new URL(String(input.url)).host } catch { return null } }
108
+ return null
109
+ }
110
+ }
111
+
112
+ export class Agent {
113
+ /**
114
+ * ui.ask(question) resolves to the user's answer, or null when nobody can answer (print mode, interrupted).
115
+ * getModel() returns the model entry from /api/v1/models (or null to let the server choose).
116
+ */
117
+ constructor({ cwd, ui, getModel, permissions, tools = true, getLibraries = () => [] }) {
118
+ this.cwd = cwd
119
+ this.ui = ui
120
+ this.getModel = getModel
121
+ this.permissions = permissions
122
+ this.useTools = tools
123
+ this.getLibraries = getLibraries
124
+ this.ctx = { cwd, readFiles: new Map(), todos: [], signal: null }
125
+ this.spinner = new Spinner()
126
+ this.reset()
127
+ }
128
+
129
+ reset() {
130
+ this.messages = []
131
+ this.conversationId = randomUUID()
132
+ this.ctx.readFiles.clear()
133
+ this.ctx.todos = []
134
+ this.seenIds = new Set()
135
+ this.system = this.useTools ? systemPrompt(this.cwd) : ''
136
+ }
137
+
138
+ get busy() {
139
+ return Boolean(this.controller)
140
+ }
141
+
142
+ abort() {
143
+ this.controller?.abort()
144
+ }
145
+
146
+ #pushUserText(text) {
147
+ const last = this.messages.at(-1)
148
+ if (last?.role === 'user') {
149
+ // After an interruption or a denied tool the history already ends with the user: add to that turn.
150
+ if (typeof last.content === 'string') last.content = [{ type: 'text', text: last.content }]
151
+ last.content.push({ type: 'text', text })
152
+ } else {
153
+ this.messages.push({ role: 'user', content: text })
154
+ }
155
+ }
156
+
157
+ /** Runs one user message to completion. Returns { spent, balance, ok }. */
158
+ async send(text) {
159
+ this.#pushUserText(text)
160
+ this.controller = new AbortController()
161
+ this.ctx.signal = this.controller.signal
162
+ let spent = 0, balance = null, ok = true
163
+ try {
164
+ for (let step = 0; step < MAX_STEPS; step++) {
165
+ const reply = await this.#request()
166
+ spent += reply.spent
167
+ if (reply.balance != null) balance = reply.balance
168
+ if (reply.blocks.length) this.messages.push({ role: 'assistant', content: reply.blocks })
169
+ if (reply.stop) { ok = !reply.failed; break }
170
+ const calls = reply.blocks.filter(b => b.type === 'tool_use')
171
+ if (!calls.length) break
172
+ const results = []
173
+ let halt = false
174
+ for (const call of calls) {
175
+ if (halt || this.controller.signal.aborted) {
176
+ results.push({ type: 'tool_result', tool_use_id: call.id, content: 'Not run: the user stopped this turn.', is_error: true })
177
+ continue
178
+ }
179
+ const outcome = await this.#runTool(call)
180
+ results.push(outcome.result)
181
+ if (outcome.feedback) results.push({ type: 'text', text: outcome.feedback })
182
+ if (outcome.halt) halt = true
183
+ }
184
+ this.messages.push({ role: 'user', content: results })
185
+ if (halt || this.controller.signal.aborted) {
186
+ if (this.controller.signal.aborted) console.log(` ${DIM}⎿ Interrupted. Tell NoGuard what to do instead.${RST}`)
187
+ break
188
+ }
189
+ if (step === MAX_STEPS - 1) console.log(`${YELLOW}⚠${RST} Stopped after ${MAX_STEPS} steps. Send a message to continue.`)
190
+ }
191
+ } finally {
192
+ this.spinner.stop()
193
+ this.controller = null
194
+ this.ctx.signal = null
195
+ }
196
+ return { spent, balance, ok }
197
+ }
198
+
199
+ #budget(model) {
200
+ const maxOut = Math.min(model?.max_output_tokens ?? 32_000, 32_000)
201
+ const window = model?.context_window ?? 200_000
202
+ return { maxOut, chars: Math.min(900_000, Math.max(50_000, (window - maxOut) * 3 - 20_000)) }
203
+ }
204
+
205
+ #size() {
206
+ return JSON.stringify(this.messages).length + this.system.length + (this.useTools ? 20_000 : 0)
207
+ }
208
+
209
+ /** Frees room: old tool output first, then the oldest exchanges. Returns whether anything changed. */
210
+ compact(limit = 0) {
211
+ let changed = false
212
+ const keepFrom = Math.max(0, this.messages.length - 6)
213
+ for (let i = 0; i < keepFrom; i++) {
214
+ const content = this.messages[i].content
215
+ if (!Array.isArray(content)) continue
216
+ for (const block of content) {
217
+ if (block.type === 'tool_result' && block.content.length > 400) { block.content = ELIDED; changed = true }
218
+ if (block.type === 'tool_use' && JSON.stringify(block.input).length > 2000 && (block.name === 'Write' || block.name === 'Edit')) {
219
+ block.input = { ...block.input, ...(block.input.content ? { content: '[elided]' } : {}), ...(block.input.new_string ? { new_string: '[elided]' } : {}), ...(block.input.old_string ? { old_string: '[elided]' } : {}) }
220
+ changed = true
221
+ }
222
+ }
223
+ }
224
+ while (limit && this.#size() > limit && this.messages.length > 2) {
225
+ // Drop the oldest exchange: everything up to the next user message that is typed text, not tool results.
226
+ let cut = 1
227
+ while (cut < this.messages.length - 1) {
228
+ const m = this.messages[cut]
229
+ if (m.role === 'user' && (typeof m.content === 'string' || m.content.every(b => b.type === 'text'))) break
230
+ cut++
231
+ }
232
+ if (cut >= this.messages.length - 1) break
233
+ this.messages.splice(0, cut)
234
+ changed = true
235
+ }
236
+ return changed
237
+ }
238
+
239
+ async #request() {
240
+ const model = this.getModel()
241
+ const { maxOut, chars } = this.#budget(model)
242
+ if (this.#size() > chars) this.compact(chars)
243
+ let retries = 0
244
+ for (;;) {
245
+ try {
246
+ return await this.#stream(model, maxOut)
247
+ } catch (err) {
248
+ this.spinner.stop()
249
+ if (err.name === 'AbortError' || this.controller.signal.aborted) return this.#interrupted()
250
+ if (err instanceof ApiError) {
251
+ if (err.status === 429 && retries < 3) {
252
+ retries++
253
+ this.spinner.start(`Rate limited, retrying in 15s (${retries}/3)…`)
254
+ await new Promise(r => setTimeout(r, 15_000))
255
+ this.spinner.stop()
256
+ continue
257
+ }
258
+ if (err.code === 'request_too_large' && retries < 2) {
259
+ retries++
260
+ if (this.compact(Math.floor(this.#size() * 0.6))) {
261
+ console.log(` ${DIM}Context is full: removed older tool output and retrying.${RST}`)
262
+ continue
263
+ }
264
+ }
265
+ return { blocks: [], spent: 0, balance: null, stop: true, failed: true, error: this.#explain(err) }
266
+ }
267
+ if (retries < 1) {
268
+ retries++
269
+ console.log(` ${DIM}Connection problem (${err.message}); retrying…${RST}`)
270
+ await new Promise(r => setTimeout(r, 2000))
271
+ continue
272
+ }
273
+ console.log(`${RED}✗${RST} Connection error: ${err.message}`)
274
+ return { blocks: [], spent: 0, balance: null, stop: true, failed: true }
275
+ }
276
+ }
277
+ }
278
+
279
+ #interrupted() {
280
+ console.log(`\n ${DIM}⎿ Interrupted.${RST}`)
281
+ return { blocks: [], spent: 0, balance: null, stop: true, failed: false }
282
+ }
283
+
284
+ #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}`)
289
+ return err.message
290
+ }
291
+
292
+ async #stream(model, maxOut) {
293
+ const libraries = this.getLibraries()
294
+ const body = {
295
+ ...(model ? { model: model.id } : {}),
296
+ max_tokens: maxOut,
297
+ messages: this.messages,
298
+ noguard_persona: true,
299
+ metadata: { conversation_id: this.conversationId },
300
+ ...(this.system ? { system: this.system } : {}),
301
+ ...(this.useTools ? { tools: toolDefinitions() } : {}),
302
+ ...(libraries.length ? { libraries } : {}),
303
+ }
304
+ const blocks = new Map()
305
+ let md = null, spent = 0, balance = null, stopReason = null, streamError = null
306
+ const signal = this.controller.signal
307
+ this.spinner.start('Thinking…')
308
+ try {
309
+ for await (const { event, data } of streamMessages(body, { signal })) {
310
+ if (event === 'content_block_start') {
311
+ const block = data.content_block
312
+ if (block.type === 'text') blocks.set(data.index, { type: 'text', text: '' })
313
+ else if (block.type === 'tool_use') {
314
+ md?.end(); md = null
315
+ blocks.set(data.index, { type: 'tool_use', id: block.id, name: block.name, json: '' })
316
+ this.spinner.start(`${block.name}…`)
317
+ }
318
+ } else if (event === 'content_block_delta') {
319
+ const block = blocks.get(data.index)
320
+ if (!block) continue
321
+ if (data.delta?.type === 'text_delta' && block.type === 'text') {
322
+ this.spinner.stop()
323
+ md ??= new MarkdownStream()
324
+ md.write(data.delta.text)
325
+ block.text += data.delta.text
326
+ } else if (data.delta?.type === 'input_json_delta' && block.type === 'tool_use') {
327
+ block.json += data.delta.partial_json
328
+ }
329
+ } else if (event === 'message_delta') {
330
+ stopReason = data.delta?.stop_reason ?? stopReason
331
+ } else if (event === 'noguard_credits') {
332
+ spent = data.spent ?? spent
333
+ balance = data.balance ?? balance
334
+ } else if (event === 'error') {
335
+ streamError = data?.error?.message ?? 'Something went wrong.'
336
+ }
337
+ }
338
+ } catch (err) {
339
+ md?.end()
340
+ this.spinner.stop()
341
+ if (err.name === 'AbortError' || signal.aborted) {
342
+ // Keep what was said; drop tool calls that never ran.
343
+ const text = [...blocks.values()].filter(b => b.type === 'text' && b.text.trim()).map(b => ({ type: 'text', text: b.text }))
344
+ console.log(`\n ${DIM}⎿ Interrupted.${RST}`)
345
+ return { blocks: text, spent, balance, stop: true }
346
+ }
347
+ throw err
348
+ }
349
+ md?.end()
350
+ this.spinner.stop()
351
+
352
+ const finished = []
353
+ for (const [, block] of [...blocks.entries()].sort((a, b) => a[0] - b[0])) {
354
+ if (block.type === 'text') {
355
+ if (block.text.trim()) finished.push({ type: 'text', text: block.text })
356
+ continue
357
+ }
358
+ let input = {}, parseError = null
359
+ try { input = block.json.trim() ? JSON.parse(block.json) : {} } catch (err) { parseError = err.message }
360
+ if (!input || typeof input !== 'object' || Array.isArray(input)) { input = {}; parseError ??= 'arguments were not an object' }
361
+ let id = block.id
362
+ if (!TOOL_ID.test(id ?? '') || this.seenIds.has(id)) id = `toolu_${randomBytes(12).toString('hex')}`
363
+ this.seenIds.add(id)
364
+ const call = { type: 'tool_use', id, name: block.name, input }
365
+ // parseError is local bookkeeping: not enumerable, so it is never sent back to the server.
366
+ if (parseError) Object.defineProperty(call, 'parseError', { value: parseError, enumerable: false })
367
+ finished.push(call)
368
+ }
369
+ if (streamError) {
370
+ console.log(`${RED}✗${RST} ${streamError}`)
371
+ return { blocks: finished.filter(b => b.type === 'text'), spent, balance, stop: true, failed: true }
372
+ }
373
+ if (stopReason === 'max_tokens' && !finished.some(b => b.type === 'tool_use')) {
374
+ console.log(` ${DIM}(The reply hit its length limit. Say "continue" to get the rest.)${RST}`)
375
+ }
376
+ if (stopReason === 'refusal') console.log(` ${DIM}(The model declined this one.)${RST}`)
377
+ return { blocks: finished, spent, balance, stop: false }
378
+ }
379
+
380
+ async #runTool(call) {
381
+ const tool = TOOLS_BY_NAME.get(call.name)
382
+ const fail = (message, extra = {}) => ({ result: { type: 'tool_result', tool_use_id: call.id, content: message, is_error: true }, ...extra })
383
+ if (!tool) {
384
+ console.log(toolHeader(call.name))
385
+ console.log(toolResultLine(`Unknown tool`, RED))
386
+ return fail(`There is no tool named ${call.name}.`)
387
+ }
388
+ let label = ''
389
+ try { label = tool.label(call.input, this.ctx) } catch { /* bad input shows no label */ }
390
+ console.log(toolHeader(tool.name, label))
391
+ if (call.parseError) {
392
+ console.log(toolResultLine('Invalid arguments', RED))
393
+ return fail(`The tool arguments were not valid JSON (${call.parseError}). The reply may have been cut off; try again with smaller input.`)
394
+ }
395
+ const missing = (tool.input_schema.required ?? []).filter(key => call.input[key] === undefined)
396
+ if (missing.length) {
397
+ console.log(toolResultLine(`Missing ${missing.join(', ')}`, RED))
398
+ return fail(`Missing required argument${missing.length > 1 ? 's' : ''}: ${missing.join(', ')}.`)
399
+ }
400
+ const reason = this.permissions.check(tool, call.input, this.cwd)
401
+ if (reason) {
402
+ let preview = null
403
+ try { preview = tool.preview?.(call.input, this.ctx) } catch { /* the run reports the problem */ }
404
+ if (preview) console.log(preview.split('\n').map(line => ` ${line}`).join('\n'))
405
+ if (tool.kind === 'exec') {
406
+ // The header may be shortened: show exactly what will run before asking.
407
+ const command = clean(String(call.input.command ?? ''))
408
+ if (command !== label) console.log(command.split('\n').map(line => ` ${CYAN}${line}${RST}`).join('\n'))
409
+ if (call.input.description) console.log(` ${DIM}${clean(String(call.input.description))}${RST}`)
410
+ }
411
+ 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} `)
413
+ if (answer === null) {
414
+ const why = this.ui.interactive
415
+ ? 'Not run: the user interrupted.'
416
+ : `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))
418
+ return fail(why, { halt: true })
419
+ }
420
+ const reply = answer.trim()
421
+ const word = reply.toLowerCase()
422
+ if (word === 'a' || word === 'always') {
423
+ if (always) this.permissions.alwaysAllow(tool, call.input)
424
+ } else if (!(word === '' || word === 'y' || word === 'yes')) {
425
+ const feedback = ['n', 'no'].includes(word) ? '' : reply
426
+ console.log(toolResultLine('Denied', YELLOW))
427
+ if (feedback) {
428
+ return fail('The user denied this action.', { feedback: `The user denied that and said: ${feedback}` })
429
+ }
430
+ return fail('The user denied this action. Stop and wait for them to say what to do instead.', { halt: true })
431
+ }
432
+ }
433
+ if (tool.kind === 'exec' || tool.kind === 'network') this.spinner.start(tool.kind === 'exec' ? 'Running…' : 'Fetching…')
434
+ let outcome
435
+ try {
436
+ outcome = await tool.run(call.input, this.ctx)
437
+ } catch (err) {
438
+ outcome = { error: err.message }
439
+ }
440
+ this.spinner.stop()
441
+ if (outcome.error) {
442
+ console.log(toolResultLine(clean(outcome.error), RED))
443
+ return fail(outcome.error)
444
+ }
445
+ if (outcome.display) console.log(toolResultLine(outcome.display))
446
+ if (outcome.diff) console.log(outcome.diff.split('\n').map(line => ` ${line}`).join('\n'))
447
+ return { result: { type: 'tool_result', tool_use_id: call.id, content: outcome.content || '(no output)', ...(outcome.isError ? { is_error: true } : {}) } }
448
+ }
449
+ }