advisers 0.2.0-preview.71 → 0.2.1

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/remind.js CHANGED
@@ -150,6 +150,181 @@ export function escapeIcsText(value) {
150
150
  .replace(/,/g, '\\,')
151
151
  }
152
152
 
153
+ const OFFSET_PATTERN = /^([+-])(\d+)([dhm])(?:(\d{1,2}):(\d{2}))?$/
154
+ const MAX_OFFSET_DAYS = 3650
155
+ const MAX_OFFSET_HOURS = MAX_OFFSET_DAYS * 24
156
+ const MAX_OFFSET_MINUTES = MAX_OFFSET_HOURS * 60
157
+
158
+ /** Upper bound on per-commitment alarms so a ledger row cannot flood a calendar. */
159
+ export const MAX_REMINDER_OFFSETS = 24
160
+
161
+ const pad2 = (value) => String(value).padStart(2, '0')
162
+
163
+ /**
164
+ * Parse one custom reminder offset relative to the commitment due instant.
165
+ *
166
+ * Accepted grammar (Asia/Shanghai wall clock):
167
+ * - `-1d` / `+2d` — whole local days, same clock time as `dueAt`
168
+ * - `-2h` / `+90m` — hours or minutes relative to `dueAt`
169
+ * - `+0d09:00` — 09:00 on the due day (day shift + wall-clock time)
170
+ * - `-1d08:30` — 08:30 on the day before the due day
171
+ *
172
+ * The sign is mandatory. A time-of-day is only valid together with the `d`
173
+ * unit, and a zero-day time-of-day offset is canonicalised to `+`.
174
+ *
175
+ * @returns {{ offset: string, sign: 1|-1, days: number, hours: number,
176
+ * minutes: number, timeOfDay: { hour: number, minute: number }|null, source: string }}
177
+ */
178
+ export function parseReminderOffset(value) {
179
+ if (typeof value !== 'string') throw new TypeError('reminder offset must be a string')
180
+ const text = value.trim().toLowerCase()
181
+ if (!text) throw new TypeError('reminder offset must not be empty')
182
+ const match = OFFSET_PATTERN.exec(text)
183
+ if (!match) throw new TypeError(`invalid reminder offset: ${String(value)}`)
184
+ const [, rawSign, rawAmount, unit, rawHour, rawMinute] = match
185
+ const amount = Number(rawAmount)
186
+ if (!Number.isSafeInteger(amount)) throw new TypeError(`invalid reminder offset amount: ${String(value)}`)
187
+ let days = 0
188
+ let hours = 0
189
+ let minutes = 0
190
+ if (unit === 'd') {
191
+ days = amount
192
+ if (days > MAX_OFFSET_DAYS) throw new RangeError(`reminder offset too large: ${String(value)}`)
193
+ } else if (unit === 'h') {
194
+ hours = amount
195
+ if (hours > MAX_OFFSET_HOURS) throw new RangeError(`reminder offset too large: ${String(value)}`)
196
+ } else {
197
+ minutes = amount
198
+ if (minutes > MAX_OFFSET_MINUTES) throw new RangeError(`reminder offset too large: ${String(value)}`)
199
+ }
200
+ let timeOfDay = null
201
+ if (rawHour !== undefined) {
202
+ if (unit !== 'd') throw new TypeError(`time-of-day is only valid with a day offset: ${String(value)}`)
203
+ const hour = Number(rawHour)
204
+ const minute = Number(rawMinute)
205
+ if (hour > 23 || minute > 59) throw new RangeError(`invalid reminder offset time: ${String(value)}`)
206
+ timeOfDay = Object.freeze({ hour, minute })
207
+ }
208
+ const sign = rawSign === '-' ? -1 : 1
209
+ const canonicalSign = timeOfDay && days === 0 ? '+' : rawSign
210
+ const offset = timeOfDay
211
+ ? `${canonicalSign}${days}d${pad2(timeOfDay.hour)}:${pad2(timeOfDay.minute)}`
212
+ : unit === 'd'
213
+ ? `${canonicalSign}${days}d`
214
+ : unit === 'h'
215
+ ? `${canonicalSign}${hours}h`
216
+ : `${canonicalSign}${minutes}m`
217
+ return Object.freeze({ offset, sign, days, hours, minutes, timeOfDay, source: String(value) })
218
+ }
219
+
220
+ /**
221
+ * Strictly validate and canonicalise a list of offsets. Invalid input throws;
222
+ * use {@link reminderAlarms} for the lenient rendering path.
223
+ */
224
+ export function normalizeReminderOffsets(value) {
225
+ if (value == null) return []
226
+ if (!Array.isArray(value)) throw new TypeError('reminderOffsets must be an array of offset strings')
227
+ if (value.length > MAX_REMINDER_OFFSETS) {
228
+ throw new RangeError(`too many reminder offsets (max ${MAX_REMINDER_OFFSETS})`)
229
+ }
230
+ const seen = new Set()
231
+ const normalized = []
232
+ for (const entry of value) {
233
+ const parsed = parseReminderOffset(entry)
234
+ if (seen.has(parsed.offset)) continue
235
+ seen.add(parsed.offset)
236
+ normalized.push(parsed.offset)
237
+ }
238
+ return normalized
239
+ }
240
+
241
+ /** Lenient list reader used for rendering: skips invalid entries instead of throwing. */
242
+ function resolveReminderOffsets(value) {
243
+ if (value == null) return []
244
+ let items
245
+ if (Array.isArray(value)) items = value
246
+ else if (typeof value === 'string') items = value.split(',')
247
+ else return []
248
+ const seen = new Set()
249
+ const resolved = []
250
+ for (const item of items.slice(0, MAX_REMINDER_OFFSETS)) {
251
+ try {
252
+ const parsed = parseReminderOffset(item)
253
+ if (seen.has(parsed.offset)) continue
254
+ seen.add(parsed.offset)
255
+ resolved.push(parsed.offset)
256
+ } catch {
257
+ // A single malformed ledger value must not suppress every reminder.
258
+ }
259
+ }
260
+ return resolved
261
+ }
262
+
263
+ /** Human label used inside a VALARM DESCRIPTION. */
264
+ export function describeReminderOffset(value) {
265
+ const parsed = parseReminderOffset(value)
266
+ if (parsed.timeOfDay) {
267
+ const time = `${pad2(parsed.timeOfDay.hour)}:${pad2(parsed.timeOfDay.minute)}`
268
+ if (parsed.days === 0) return `当天 ${time}`
269
+ return `${parsed.sign < 0 ? '提前' : '延后'} ${parsed.days} 天 ${time}`
270
+ }
271
+ if (parsed.days === 0 && parsed.hours === 0 && parsed.minutes === 0) return '到期时'
272
+ const when = parsed.sign < 0 ? '提前' : '延后'
273
+ if (parsed.days) return `${when} ${parsed.days} 天`
274
+ if (parsed.hours) return `${when} ${parsed.hours} 小时`
275
+ return `${when} ${parsed.minutes} 分钟`
276
+ }
277
+
278
+ /**
279
+ * Absolute instant of one alarm: the due instant shifted by `offset`.
280
+ * All wall-clock arithmetic uses Asia/Shanghai (UTC+8, no DST since 1991).
281
+ */
282
+ export function reminderAlarmTime(dueAt, offset) {
283
+ const due = requireDate(dueAt, 'due date')
284
+ const parsed = parseReminderOffset(offset)
285
+ if (parsed.timeOfDay) {
286
+ const wall = new Date(due.getTime() + SHANGHAI_OFFSET_MS)
287
+ const shifted = new Date(
288
+ Date.UTC(
289
+ wall.getUTCFullYear(),
290
+ wall.getUTCMonth(),
291
+ wall.getUTCDate() + parsed.sign * parsed.days,
292
+ parsed.timeOfDay.hour,
293
+ parsed.timeOfDay.minute,
294
+ 0,
295
+ 0,
296
+ ),
297
+ )
298
+ const date = new Date(shifted.getTime() - SHANGHAI_OFFSET_MS)
299
+ if (Number.isNaN(date.getTime())) throw new RangeError(`invalid reminder offset: ${String(offset)}`)
300
+ return date
301
+ }
302
+ const deltaMs = parsed.sign * (parsed.days * 24 * 60 + parsed.hours * 60 + parsed.minutes) * 60_000
303
+ const date = new Date(due.getTime() + deltaMs)
304
+ if (Number.isNaN(date.getTime())) throw new RangeError(`invalid reminder offset: ${String(offset)}`)
305
+ return date
306
+ }
307
+
308
+ /**
309
+ * Build the VALARM instants for a due date. Duplicate instants collapse so the
310
+ * same calendar reminder is never emitted twice; output is chronological.
311
+ *
312
+ * @returns {Array<{ offset: string, at: Date, label: string }>}
313
+ */
314
+ export function reminderAlarms(dueAt, offsets) {
315
+ const normalized = resolveReminderOffsets(offsets)
316
+ const seen = new Set()
317
+ const alarms = []
318
+ for (const offset of normalized) {
319
+ const at = reminderAlarmTime(dueAt, offset)
320
+ const key = String(at.getTime())
321
+ if (seen.has(key)) continue
322
+ seen.add(key)
323
+ alarms.push({ offset, at, label: describeReminderOffset(offset) })
324
+ }
325
+ return alarms.sort((left, right) => left.at.getTime() - right.at.getTime() || left.offset.localeCompare(right.offset))
326
+ }
327
+
153
328
  function rule(id, description, test) {
154
329
  return Object.freeze({ id, description, test })
155
330
  }
@@ -266,6 +441,47 @@ function readSnoozeUntil(commitment, options, ledger) {
266
441
  return null
267
442
  }
268
443
 
444
+ /**
445
+ * Resolve reminder offsets for one commitment. Priority: injected per-id state
446
+ * (Map/object/function, mirroring snoozes), the commitment field itself, any
447
+ * commitment meta hook, a duck-typed ledger `getMeta`, then the caller's global
448
+ * default. Invalid entries are skipped so one bad ledger row cannot hide every
449
+ * reminder.
450
+ */
451
+ function readReminderOffsets(commitment, options, ledger) {
452
+ const meta = commitment.meta
453
+ const injected = options.reminderOffsets
454
+ const sources = []
455
+ if (injected instanceof Map) {
456
+ sources.push(injected.get(commitment.id))
457
+ sources.push(injected.get(`reminderOffsets:${commitment.id}`))
458
+ } else if (typeof injected === 'function') {
459
+ sources.push(injected(commitment))
460
+ } else if (injected && typeof injected === 'object') {
461
+ sources.push(injected[commitment.id])
462
+ sources.push(injected[`reminderOffsets:${commitment.id}`])
463
+ }
464
+ sources.push(commitment.reminderOffsets)
465
+ if (meta && typeof meta === 'object') {
466
+ sources.push(meta.reminderOffsets)
467
+ sources.push(meta[`reminderOffsets:${commitment.id}`])
468
+ if (typeof meta.get === 'function') sources.push(meta.get(`reminderOffsets:${commitment.id}`))
469
+ }
470
+ // Optional duck-typed store hook; never required, never SQLite-specific.
471
+ if (ledger && typeof ledger.getMeta === 'function') {
472
+ try {
473
+ sources.push(ledger.getMeta(`reminderOffsets:${commitment.id}`))
474
+ } catch {
475
+ // A read-only or closed store must not break planning.
476
+ }
477
+ }
478
+ for (const source of sources) {
479
+ const resolved = resolveReminderOffsets(source)
480
+ if (resolved.length) return resolved
481
+ }
482
+ return resolveReminderOffsets(options.defaultReminderOffsets)
483
+ }
484
+
269
485
  function outputDueAt(value) {
270
486
  if (typeof value === 'string') return value
271
487
  const date = toDate(value)
@@ -284,9 +500,14 @@ function outputDueAt(value) {
284
500
  * @param {Array<object|string>} [options.rules] Rule descriptors or ids.
285
501
  * @param {Map|object|Function} [options.snoozedUntil] Per-commitment snooze
286
502
  * deadlines, keyed by commitment id; future deadlines suppress reminders.
503
+ * @param {Map|object|Function} [options.reminderOffsets] Injected
504
+ * per-commitment offsets (same keying as `snoozedUntil`). Injected values
505
+ * are checked before the commitment's own `reminderOffsets` field.
506
+ * @param {string[]} [options.defaultReminderOffsets] Global offsets applied
507
+ * when a commitment has neither its own nor an injected list.
287
508
  * @returns {Array<{ commitmentId: string, action: string, dueAt: string,
288
509
  * bucket: 'overdue'|'due-today'|'due-1d'|'upcoming',
289
- * level: 'L1'|'L2'|'L3', ruleId: string }>}
510
+ * level: 'L1'|'L2'|'L3', ruleId: string, reminderOffsets?: string[] }>}
290
511
  */
291
512
  export function buildReminders(ledger, options = {}) {
292
513
  if (!ledger || typeof ledger.listCommitments !== 'function') {
@@ -319,6 +540,7 @@ export function buildReminders(ledger, options = {}) {
319
540
  // becomes visible again and the snooze-wake rule fires.
320
541
  if (snoozeUntil && snoozeUntil.getTime() > now.getTime()) continue
321
542
  const snoozeExpired = Boolean(snoozeUntil)
543
+ const reminderOffsets = readReminderOffsets(commitment, opts, ledger)
322
544
 
323
545
  const dueDay = localDay(due)
324
546
  const dayOffset = localDayIndex(dueDay) - todayIndex
@@ -353,6 +575,9 @@ export function buildReminders(ledger, options = {}) {
353
575
  bucket: result.bucket,
354
576
  level: result.level,
355
577
  ruleId: result.ruleId,
578
+ // Only present when customised: pre-0.2.0 reminder objects keep their
579
+ // exact shape and toIcs falls back to the legacy relative alarms.
580
+ ...(reminderOffsets.length ? { reminderOffsets } : {}),
356
581
  })
357
582
  }
358
583
  }
@@ -377,8 +602,42 @@ export function buildReminders(ledger, options = {}) {
377
602
  * @param {object} [options]
378
603
  * @param {Date|string|number} [options.now] DTSTAMP instant.
379
604
  * @param {string} [options.uidPrefix='advisers']
605
+ * @param {string[]} [options.reminderOffsets] Fallback custom offsets for
606
+ * reminders that do not carry their own `reminderOffsets`.
380
607
  * @returns {string} CRLF-terminated iCalendar text.
381
608
  */
609
+ const legacyAlarmLines = (title) => [
610
+ 'BEGIN:VALARM',
611
+ 'TRIGGER:-P1D',
612
+ 'ACTION:DISPLAY',
613
+ `DESCRIPTION:${escapeIcsText(`提醒:${title}(1 天前)`)}`,
614
+ 'END:VALARM',
615
+ 'BEGIN:VALARM',
616
+ 'TRIGGER:-PT1H',
617
+ 'ACTION:DISPLAY',
618
+ `DESCRIPTION:${escapeIcsText(`提醒:${title}(1 小时前)`)}`,
619
+ 'END:VALARM',
620
+ ]
621
+
622
+ /**
623
+ * VALARM lines for one event. Custom offsets become **absolute** DATE-TIME
624
+ * triggers computed in Asia/Shanghai (RFC5545 requires VALUE=DATE-TIME when
625
+ * TRIGGER is absolute) and one VALARM is emitted per rule. With no offsets the
626
+ * pre-0.2.0 relative defaults (-P1D, -PT1H) are preserved byte-for-byte.
627
+ */
628
+ function alarmLines(reminder, due, title, options) {
629
+ const configured = reminder.reminderOffsets ?? options.reminderOffsets
630
+ const alarms = reminderAlarms(due, configured)
631
+ if (!alarms.length) return legacyAlarmLines(title)
632
+ return alarms.flatMap((alarm) => [
633
+ 'BEGIN:VALARM',
634
+ `TRIGGER;VALUE=DATE-TIME:${formatIcsDate(alarm.at)}`,
635
+ 'ACTION:DISPLAY',
636
+ `DESCRIPTION:${escapeIcsText(`提醒:${title}(${alarm.label})`)}`,
637
+ 'END:VALARM',
638
+ ])
639
+ }
640
+
382
641
  export function toIcs(reminders, options = {}) {
383
642
  if (!Array.isArray(reminders)) throw new TypeError('toIcs requires an array of reminders')
384
643
  const opts = options ?? {}
@@ -419,16 +678,7 @@ export function toIcs(reminders, options = {}) {
419
678
  `DTSTART:${formatIcsDate(due)}`,
420
679
  `SUMMARY:${escapeIcsText(title)}`,
421
680
  `DESCRIPTION:${escapeIcsText(`到期:${localDue}(${TIME_ZONE})`)}`,
422
- 'BEGIN:VALARM',
423
- 'TRIGGER:-P1D',
424
- 'ACTION:DISPLAY',
425
- `DESCRIPTION:${escapeIcsText(`提醒:${title}(1 天前)`)}`,
426
- 'END:VALARM',
427
- 'BEGIN:VALARM',
428
- 'TRIGGER:-PT1H',
429
- 'ACTION:DISPLAY',
430
- `DESCRIPTION:${escapeIcsText(`提醒:${title}(1 小时前)`)}`,
431
- 'END:VALARM',
681
+ ...alarmLines(reminder, due, title, opts),
432
682
  'END:VEVENT',
433
683
  )
434
684
  }
package/lib/research.js CHANGED
@@ -2,8 +2,51 @@
2
2
  * DeepSeek server-side web tools (Messages API).
3
3
  * Search and URL reading run on the service; no local tool is executed.
4
4
  * Citations are provider output, not local evidence.
5
+ *
6
+ * Network hardening (2026-11-17 robustness audit P1-5): every request has an
7
+ * AbortController timeout, a hard wall-clock deadline that does not depend on
8
+ * the fetch implementation honoring the signal, and bounded retries for
9
+ * 429/5xx (same policy as lib/model.js).
10
+ *
11
+ * Content safety (0.2.0): the query/URL text is classified locally BEFORE any
12
+ * network request (surface research.query); a block throws ContentSafetyError
13
+ * and no fetch happens. A model answer that is flagged is returned as-is with
14
+ * an additive safetyWarnings field (the provider call already happened; the
15
+ * design keeps research output at warn, never a silent rewrite). The protected
16
+ * matter egress gate lives in the CLI (lib/egress.js) and is unchanged.
5
17
  */
18
+ import { classify, safetyErrorFrom, buildAuditReason } from './safety/index.js'
19
+
6
20
  const MAX_TOKENS = 4096
21
+ const RETRY_STATUS = new Set([429, 500, 502, 503, 504])
22
+
23
+ const RESEARCH_INPUT_SURFACE = 'research.query'
24
+ const RESEARCH_OUTPUT_SURFACE = 'research.output'
25
+
26
+ function safetyWarningOf(result, direction) {
27
+ if (!result || result.action === 'allow') return null
28
+ const surface = result.surface || RESEARCH_INPUT_SURFACE
29
+ const ruleIds = Array.isArray(result.ruleIds) ? [...result.ruleIds] : []
30
+ return {
31
+ direction,
32
+ action: result.action,
33
+ code: result.code,
34
+ categories: Array.isArray(result.categories) ? [...result.categories] : [],
35
+ ruleIds,
36
+ surface,
37
+ rulesetVersion: result.rulesetVersion,
38
+ evidenceHash: result.evidenceHash || null,
39
+ crisis: Boolean(result.crisis),
40
+ auditReason: buildAuditReason({
41
+ rulesetVersion: result.rulesetVersion,
42
+ surface,
43
+ action: result.action,
44
+ code: result.code,
45
+ ruleIds,
46
+ evidenceHash: result.evidenceHash,
47
+ }),
48
+ }
49
+ }
7
50
 
8
51
  function root(baseUrl) {
9
52
  const base = String(baseUrl || 'https://api.deepseek.com').replace(/\/+$/, '')
@@ -36,10 +79,36 @@ function normalizeCitations(blocks = []) {
36
79
  return citations
37
80
  }
38
81
 
39
- export async function research({ query, urls = [], apiKey, baseUrl, fetchImpl = fetch, deep = false, maxTokens = MAX_TOKENS }) {
40
- if (!apiKey) throw new Error('research requires ADVISERS_API_KEY')
82
+ async function sleep(ms) {
83
+ return new Promise((resolve) => setTimeout(resolve, ms))
84
+ }
85
+
86
+ export class ResearchError extends Error {
87
+ constructor(message, { status, code, retryable = false } = {}) {
88
+ super(message)
89
+ this.name = 'ResearchError'
90
+ this.status = status
91
+ this.code = code
92
+ this.retryable = retryable
93
+ }
94
+ }
95
+
96
+ export async function research({
97
+ query, urls = [], apiKey, baseUrl, fetchImpl = fetch, deep = false, maxTokens = MAX_TOKENS,
98
+ timeoutMs = Number(process.env.ADVISERS_RESEARCH_TIMEOUT_MS) || 60_000,
99
+ retries = 2,
100
+ signal,
101
+ safetyKey,
102
+ }) {
103
+ if (!apiKey) throw new ResearchError('research requires ADVISERS_API_KEY', { code: 'MISSING_API_KEY' })
41
104
  const text = [String(query || '').trim(), ...urls].filter(Boolean).join('\n')
42
- if (!text) throw new Error('research requires a query or URL')
105
+ if (!text) throw new ResearchError('research requires a query or URL', { code: 'INVALID_REQUEST' })
106
+ // Local pre-flight check: a blocked query/URL never opens a network request.
107
+ const requestSafety = classify(text, { surface: RESEARCH_INPUT_SURFACE, hmacKey: safetyKey })
108
+ if (requestSafety.action === 'block') throw safetyErrorFrom(requestSafety, { surface: RESEARCH_INPUT_SURFACE, provider: 'deepseek' })
109
+ const safetyWarnings = []
110
+ const requestWarning = safetyWarningOf(requestSafety, 'input')
111
+ if (requestWarning) safetyWarnings.push(requestWarning)
43
112
  const tools = urls.length
44
113
  ? [{ type: 'deepseek_read_url', name: 'deepseek_read_url' }]
45
114
  : [{ type: 'deepseek_web_search', name: 'deepseek_web_search' }]
@@ -50,20 +119,81 @@ export async function research({ query, urls = [], apiKey, baseUrl, fetchImpl =
50
119
  tools,
51
120
  messages: [{ role: 'user', content: text }],
52
121
  }
53
- const response = await fetchImpl(`${root(baseUrl)}/messages`, {
54
- method: 'POST',
55
- headers: { 'content-type': 'application/json', 'x-api-key': apiKey, 'anthropic-version': '2023-06-01' },
56
- body: JSON.stringify(body),
57
- })
58
- if (!response.ok) {
59
- const raw = await response.text().catch(() => '')
60
- throw new Error(`research HTTP ${response.status}: ${raw.slice(0, 300)}`)
122
+ let lastError
123
+ for (let attempt = 0; attempt <= retries; attempt++) {
124
+ const controller = new AbortController()
125
+ let timer
126
+ const onAbort = () => controller.abort()
127
+ signal?.addEventListener?.('abort', onAbort, { once: true })
128
+ // Race the fetch against a wall-clock deadline so a hung fetchImpl cannot
129
+ // keep the CLI (or a test) waiting forever even if it ignores the signal.
130
+ const deadline = new Promise((_, reject) => {
131
+ timer = setTimeout(() => {
132
+ controller.abort()
133
+ reject(new ResearchError(`research timeout after ${timeoutMs}ms`, { code: 'TIMEOUT' }))
134
+ }, timeoutMs)
135
+ // The deadline timer must stay referenced: a fetch implementation that
136
+ // ignores the abort signal may leave the event loop empty, and an unref'd
137
+ // timer would never fire (Node 22 treats that as a pending promise at exit).
138
+ })
139
+ try {
140
+ const request = fetchImpl(`${root(baseUrl)}/messages`, {
141
+ method: 'POST',
142
+ headers: { 'content-type': 'application/json', 'x-api-key': apiKey, 'anthropic-version': '2023-06-01' },
143
+ body: JSON.stringify(body),
144
+ signal: controller.signal,
145
+ })
146
+ // Avoid an unhandled rejection when the deadline wins the race.
147
+ request.catch?.(() => {})
148
+ const response = await Promise.race([request, deadline])
149
+ if (!response.ok) {
150
+ // Never copy the upstream body into the error message (privacy audit
151
+ // P1-2, 2026-11-17). A provider 401 can echo the submitted API key and
152
+ // the body may contain control characters; both used to reach stderr,
153
+ // CI logs and screenshots through the uncaught error. Only stable
154
+ // fields (status + code) are kept. The body is discarded.
155
+ try { await response.body?.cancel?.() } catch {}
156
+ const retryable = RETRY_STATUS.has(response.status)
157
+ const code = response.status === 401 || response.status === 403 ? 'AUTH' : response.status === 429 ? 'RATE_LIMITED' : response.status === 400 ? 'INVALID_REQUEST' : 'UPSTREAM'
158
+ const error = new ResearchError(`research HTTP ${response.status} (${code})`, {
159
+ status: response.status,
160
+ code,
161
+ retryable,
162
+ })
163
+ if (!retryable || attempt === retries) throw error
164
+ lastError = error
165
+ } else {
166
+ const data = await response.json()
167
+ const blocks = Array.isArray(data.content) ? data.content : []
168
+ const answer = blocks.filter((b) => b.type === 'text').map((b) => b.text || '').join('')
169
+ const sources = normalizeSources(blocks)
170
+ const citations = normalizeCitations(blocks)
171
+ if (data.stop_reason === 'refusal') throw new ResearchError('research refused by provider safety review', { code: 'REFUSAL' })
172
+ // Output stays at warn: the response already exists, so it is not
173
+ // rewritten; callers get an additive safetyWarnings field instead.
174
+ const answerWarning = safetyWarningOf(classify(answer, { surface: RESEARCH_OUTPUT_SURFACE, hmacKey: safetyKey }), 'output')
175
+ if (answerWarning) safetyWarnings.push(answerWarning)
176
+ return {
177
+ answer,
178
+ sources,
179
+ citations,
180
+ usage: data.usage,
181
+ stopReason: data.stop_reason,
182
+ blocks,
183
+ ...(safetyWarnings.length ? { safetyWarnings } : {}),
184
+ }
185
+ }
186
+ } catch (error) {
187
+ if (signal?.aborted) throw new ResearchError('research cancelled by user', { code: 'CANCELLED_BY_USER' })
188
+ if (error?.name === 'AbortError') throw new ResearchError(`research timeout after ${timeoutMs}ms`, { code: 'TIMEOUT' })
189
+ if (error instanceof ResearchError && !error.retryable) throw error
190
+ lastError = error
191
+ if (attempt === retries) throw error
192
+ } finally {
193
+ if (timer) clearTimeout(timer)
194
+ signal?.removeEventListener?.('abort', onAbort)
195
+ }
196
+ await sleep(400 * 2 ** attempt)
61
197
  }
62
- const data = await response.json()
63
- const blocks = Array.isArray(data.content) ? data.content : []
64
- const answer = blocks.filter((b) => b.type === 'text').map((b) => b.text || '').join('')
65
- const sources = normalizeSources(blocks)
66
- const citations = normalizeCitations(blocks)
67
- if (data.stop_reason === 'refusal') throw new Error('research refused by provider safety review')
68
- return { answer, sources, citations, usage: data.usage, stopReason: data.stop_reason, blocks }
198
+ throw lastError ?? new ResearchError('research request failed', { code: 'UPSTREAM' })
69
199
  }