noguard 1.2.0 → 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/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 = { ask: 'ask before edits and commands', 'accept-edits': 'edits allowed, ask before commands', yolo: 'everything allowed without asking' }
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) results.push({ type: 'text', text: 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) console.log(` ${SOFT_GRAY}⎿ Interrupted. Tell NoGuard what to do instead.${RST}`)
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) console.log(`${ORANGE}⚠${RST} Stopped after ${MAX_STEPS} steps. Send a message to continue.`)
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 new Promise(r => setTimeout(r, 15_000))
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
- console.log(` ${DIM}Context is full: removed older tool output and retrying.${RST}`)
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
- if (retries < 1) {
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
- console.log(`\n ${DIM}⎿ Interrupted.${RST}`)
288
- return { blocks: [], spent: 0, balance: null, stop: true, failed: false }
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') 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}`)
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
- ...(this.system ? { system: this.system } : {}),
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
- md ??= new MarkdownStream()
331
- md.write(data.delta.text)
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
- console.log(`\n ${DIM}⎿ Interrupted.${RST}`)
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
- console.log(`${HOT_PINK}✗${RST} ${streamError}`)
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
- console.log(` ${DIM}(The reply hit its length limit. Say "continue" to get the rest.)${RST}`)
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
- console.log(toolHeader(call.name))
392
- console.log(toolResultLine(`Unknown tool`, HOT_PINK))
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
- console.log(toolHeader(tool.name, label))
443
+ this.report(toolHeader(tool.name, label))
398
444
  if (call.parseError) {
399
- console.log(toolResultLine('Invalid arguments', HOT_PINK))
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
- console.log(toolResultLine(`Missing ${missing.join(', ')}`, HOT_PINK))
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) console.log(preview.split('\n').map(line => ` ${line}`).join('\n'))
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) console.log(command.split('\n').map(line => ` ${NEON_CYAN}${line}${RST}`).join('\n'))
416
- if (call.input.description) console.log(` ${DIM}${clean(String(call.input.description))}${RST}`)
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
- console.log(toolResultLine(this.ui.interactive ? 'Interrupted' : 'Needs approval (print mode)', ORANGE))
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
- if (always) this.permissions.alwaysAllow(tool, call.input)
431
- } else if (!(word === '' || word === 'y' || word === 'yes')) {
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
- console.log(toolResultLine('Denied', ORANGE))
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
- console.log(toolResultLine(clean(outcome.error), HOT_PINK))
500
+ this.report(toolResultLine(clean(outcome.error), HOT_PINK))
450
501
  return fail(outcome.error)
451
502
  }
452
- if (outcome.display) console.log(toolResultLine(outcome.display))
453
- if (outcome.diff) console.log(outcome.diff.split('\n').map(line => ` ${line}`).join('\n'))
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
- while (true) {
56
- const { done, value } = await reader.read()
57
- if (done) break
58
- buffer += decoder.decode(value, { stream: true })
59
- const lines = buffer.split('\n')
60
- buffer = lines.pop() ?? ''
61
- let eventName = ''
62
- for (const line of lines) {
63
- if (line.startsWith('event: ')) {
64
- eventName = line.slice(7).trim()
65
- } else if (line.startsWith('data: ')) {
66
- const data = line.slice(6)
67
- try {
68
- yield { event: eventName, data: JSON.parse(data) }
69
- } catch {
70
- yield { event: eventName, data }
71
- }
72
- eventName = ''
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
+ }