Skip to content

armgit / bento

Public Imported from GitHub
0

Bento, the office suite that fits in a file

27.1 KB
Raw Blame
// SPDX-License-Identifier: MIT
// Copyright (c) 2026 The Bento authors
//
// Provider shapers for the assistant. PURE: build a request description from
// chat messages, and parse one SSE stream into text deltas. No fetch, no
// `chrome`, no DOM — the service worker (assistant.js) makes the request, so
// the key never leaves extension storage, and this file runs unchanged in the
// node rig (scripts/test-webext-assistant.ts).
//
// Three HTTP families. Gemini is first-class rather than "OpenAI-compatible
// with another base URL": its compat endpoint drops system instructions and
// streaming details, so the native `streamGenerateContent?alt=sse` is used.
// The Chrome built-in model (Prompt API) is not HTTP and lives in assistant.js.
//
// Every provider takes a base URL (proxies, gateways, local servers); the
// defaults below are the vendors' own. `describeHost` is the ONLY thing the
// page may be told about the endpoint: a base URL can carry a tenant id in
// its path, a hostname cannot.

/** @typedef {'openai'|'anthropic'|'gemini'} Provider */
/** @typedef {{ provider: Provider, baseUrl?: string, model: string, key?: string }} ProviderConfig */
/** @typedef {{ role: 'system'|'user'|'assistant', content: string }} ChatMessage */

const trimSlash = (s) => String(s || '').replace(/\/+$/, '')

/**
 * The value BEFORE the first successful model listing, and nothing more: a
 * hard-coded model name goes stale in a season. Once a key is entered the
 * provider's own list is fetched and `pickDefault` chooses by RULE — the
 * newest general-purpose chat model at the vendor's mid tier — so these only
 * have to be right on the day the key is typed. Mid tier on purpose: cheap
 * and fast is the right default for editing slides; the big one is a pick.
 */
//
// The ids are as the maintainer named them (2026-09): OpenAI's 5.6 line ships
// two tiers, "luna" and "sol"; luna is taken as the mid tier here. Neither
// spelling has been checked against a live listing — that is exactly the
// case the rule exists for: once Check runs, the listing wins.
export const DEFAULTS = Object.freeze({
  openai: { baseUrl: 'https://api.openai.com/v1', model: 'gpt-5.6-luna' },
  anthropic: { baseUrl: 'https://api.anthropic.com', model: 'claude-sonnet-5' },
  gemini: { baseUrl: 'https://generativelanguage.googleapis.com', model: 'gemini-3.8-flash' },
})

/** The input window assumed when nothing — listing, family, the user — says otherwise. */
export const FALLBACK_CONTEXT = 128000

/** The model-list request, keyed like `shapeCheck`. All three vendors have one. */
export function shapeModels(cfg) {
  const base = baseOf(cfg)
  switch (cfg.provider) {
    case 'openai':
      return { method: 'GET', url: `${base}/models`, headers: cfg.key ? { authorization: `Bearer ${cfg.key}` } : {} }
    case 'anthropic':
      return { method: 'GET', url: `${base}/v1/models?limit=1000`, headers: { 'x-api-key': cfg.key || '', 'anthropic-version': '2023-06-01', 'anthropic-dangerous-direct-browser-access': 'true' } }
    case 'gemini':
      return { method: 'GET', url: `${base}/v1beta/models?pageSize=1000`, headers: { 'x-goog-api-key': cfg.key || '' } }
    default:
      throw new Error(`unknown provider: ${cfg.provider}`)
  }
}

/**
 * One shape out of three listings: `{ id, created?, contextTokens? }`.
 * OpenAI and Anthropic say when a model was made and nothing about its
 * window; Gemini says the window (`inputTokenLimit`) and nothing about when.
 * Gemini's ids arrive as `models/gemini-…`; the prefix is not part of the id
 * the request URL takes.
 */
export function parseModels(provider, json) {
  const rows = provider === 'gemini' ? json?.models : json?.data
  if (!Array.isArray(rows)) return []
  const out = []
  for (const r of rows) {
    if (!r || typeof r !== 'object') continue
    if (provider === 'gemini') {
      if (typeof r.name !== 'string') continue
      const methods = Array.isArray(r.supportedGenerationMethods) ? r.supportedGenerationMethods : []
      if (methods.length && !methods.includes('generateContent')) continue
      const m = { id: r.name.replace(/^models\//, '') }
      if (Number.isFinite(r.inputTokenLimit)) m.contextTokens = r.inputTokenLimit
      out.push(m)
    } else {
      if (typeof r.id !== 'string') continue
      const m = { id: r.id }
      const created = provider === 'anthropic' ? Date.parse(r.created_at) / 1000 : r.created
      if (Number.isFinite(created)) m.created = created
      out.push(m)
    }
  }
  return out
}

/**
 * The input window a model FAMILY is documented with, by id, for the two
 * vendors whose listings do not say. A gateway serving `gpt-4o` is still
 * serving a 128k model, so this is keyed on the id and not on the host.
 * Anything unrecognised gets FALLBACK_CONTEXT; the settings field overrides
 * all of it, which is the answer for a self-hosted server only its owner
 * knows the number for.
 */
export function familyContext(id) {
  const m = String(id || '').toLowerCase()
  if (/^claude-/.test(m)) return 200000            // every Claude line to date, the 5 family included
  if (/^gpt-4\.1/.test(m)) return 1047576
  if (/^gpt-5/.test(m)) return 400000              // gpt-5 as documented; gpt-5.6 luna/sol until the vendor says otherwise
  if (/^gpt-4o|^gpt-4-turbo|^chatgpt-4o/.test(m)) return 128000
  if (/^gpt-4/.test(m)) return 8192
  if (/^gpt-3\.5/.test(m)) return 16385
  if (/^o[134](-|$)/.test(m)) return 200000
  if (/^gemini-/.test(m)) return 1048576           // 2.x, 3.x and 3.8 alike
  return FALLBACK_CONTEXT
}

/**
 * The version number in a model id, wherever it sits: `gpt-5.6-luna` → 5.6,
 * `gemini-3.8-flash` → 3.8, `claude-sonnet-4-5` → 4.5 (Anthropic writes the
 * point as a dash), `gpt-4o-mini` → 4, `o3-mini` → 3. 0 when there is none.
 */
export function modelVersion(id) {
  const m = /(\d+)(?:[.-](\d+))?/.exec(String(id || '').replace(/^[a-z]+-/, ''))
  if (!m) return 0
  return parseFloat(m[2] ? `${m[1]}.${m[2]}` : m[1])
}

/** What is known about one model's window: the listing first, then the family. */
export function contextOf(id, models) {
  const hit = models?.find((m) => m.id === id)
  return Number.isFinite(hit?.contextTokens) ? hit.contextTokens : familyContext(id)
}

/** What a provider's listing is cut down to for a picker; the configured model is added on top. */
export const CURATED_MAX = 12

const CHAT = {
  openai: {
    keep: /^(gpt-|o\d|chatgpt-)/,
    drop: /embedding|whisper|tts|dall-e|realtime|audio|transcribe|moderation|babbage|davinci|instruct|search|image|codex|computer-use/,
  },
  anthropic: { keep: /^claude-/, drop: /$^/ },
  gemini: {
    keep: /^gemini-/,
    drop: /tts|image|embedding|audio|live|veo|imagen|aqa|learnlm|robotics|computer-use|native-audio|dialog/,
  },
}
const DATED = /-(\d{4}-\d{2}-\d{2}|\d{8}|\d{3,4})$/
const TRIAL = /-(preview|exp)(-|$)/

/**
 * The entries of a listing that can answer a chat turn with text — by name,
 * since none of the APIs classifies further than Gemini's generation
 * methods — with dated snapshots folded into their undated alias and
 * preview/experimental builds kept only when nothing else is left.
 */
export function chatModels(provider, models) {
  const rule = CHAT[provider]
  if (!rule) return []
  const all = (models || []).filter((m) => m && typeof m.id === 'string' && rule.keep.test(m.id) && !rule.drop.test(m.id))
  const ids = new Set(all.map((m) => m.id))
  const undated = all.filter((m) => !(DATED.test(m.id) && ids.has(m.id.replace(DATED, ''))))
  const stable = undated.filter((m) => !TRIAL.test(m.id))
  return stable.length ? stable : undated
}

/** The tier a picker sorts within a version: mid (flash/mini/sonnet/luna) first, then full (pro/opus/sol), then small (lite/nano). */
const tierOf = (id) => /flash-lite|-nano(-|$)|-lite(-|$)/.test(id) ? 0
  : /flash|-mini(-|$)|sonnet|-luna(-|$)/.test(id) ? 2
  : /haiku/.test(id) ? 0
  : 1

/**
 * A listing as a picker should show it: chat models only, newest version
 * first, mid tier before full before small within a version, and no more
 * than CURATED_MAX — unless `all`, which keeps everything the listing said
 * (still chat-sorted, uncapped) for the person who wants an exotic one.
 */
export function curateModels(provider, models, { all = false } = {}) {
  const pool = all ? (models || []).filter((m) => m && typeof m.id === 'string') : chatModels(provider, models)
  const sorted = [...pool].sort((a, b) => modelVersion(b.id) - modelVersion(a.id)
    || tierOf(b.id) - tierOf(a.id)
    || (b.created ?? 0) - (a.created ?? 0)
    || a.id.localeCompare(b.id))
  return all ? sorted : sorted.slice(0, CURATED_MAX)
}

/**
 * The recommended model out of a listing, by RULE: general-purpose chat
 * models only (no audio/image/embedding/realtime/dated snapshots), the
 * vendor's mid tier first — mini (and 5.6's "luna") over nano and the full
 * model ("sol"), sonnet over haiku over opus, flash over flash-lite and pro —
 * then the highest VERSION in the id (5.6 above 5, 3.8 above 3, 4-5 read as
 * 4.5), then `created` where the listing has it. Null when nothing qualifies.
 */
export function pickDefault(provider, models) {
  const rules = {
    openai: {
      family: /^gpt-\d/,
      exclude: /audio|realtime|search|transcribe|tts|image|embedding|instruct|codex|chat-latest|-\d{4}-\d{2}-\d{2}$|-\d{4}$/,
      // luna/sol are tiers of the 5.6 line, not versions: luna sits with mini.
      tier: (id) => /-(mini|luna)(-|$)/.test(id) ? 2 : /-nano(-|$)/.test(id) ? 1 : 0,
    },
    anthropic: {
      family: /^claude-/,
      exclude: /-\d{8}$/,
      tier: (id) => /sonnet/.test(id) ? 2 : /haiku/.test(id) ? 1 : 0,
    },
    gemini: {
      family: /^gemini-\d/,
      exclude: /preview|exp|image|tts|live|audio|embedding|thinking|-8b|learnlm|robotics|computer-use|-\d{3}$/,
      tier: (id) => /flash-lite/.test(id) ? 1 : /flash/.test(id) ? 2 : 0,
    },
  }[provider]
  if (!rules) return null
  const ok = (models || []).filter((m) => rules.family.test(m.id) && !rules.exclude.test(m.id))
  ok.sort((a, b) => rules.tier(b.id) - rules.tier(a.id)
    || modelVersion(b.id) - modelVersion(a.id)
    || (b.created ?? 0) - (a.created ?? 0)
    || a.id.localeCompare(b.id))
  return ok[0]?.id ?? null
}

export const PROVIDERS = Object.freeze(['openai', 'anthropic', 'gemini'])

const baseOf = (cfg) => trimSlash(cfg.baseUrl || DEFAULTS[cfg.provider].baseUrl)

/** Does a JSON Schema describe an object with at least one named property? */
export const hasProperties = (schema) => !!schema && typeof schema === 'object'
  && !!schema.properties && typeof schema.properties === 'object' && Object.keys(schema.properties).length > 0

/**
 * What the page may be told: the HOSTNAME the request goes to, never more.
 * Not host:port — the page bounds this to a hostname shape (transport.ts
 * HOST_RE) and blanks anything else, so `localhost:11434` would show as "—".
 * The port is shown where it is useful, in the settings page's own status.
 */
export function describeHost(cfg) {
  try { return new URL(shapeRequest(cfg, [{ role: 'user', content: '' }]).url).hostname } catch { return '' }
}

/** Host and port, for messages a person reads (the settings status line, an unreachable error). */
export function hostPortOf(cfg) {
  try { return new URL(shapeRequest(cfg, [{ role: 'user', content: '' }]).url).host } catch { return '' }
}

/** The origin a runtime host permission would be asked for, or null. */
export function originOf(cfg) {
  try { return new URL(baseOf(cfg)).origin } catch { return null }
}

/**
 * Build the streaming request for one chat turn. `opts.schema` is a JSON
 * Schema the reply must fit (the page sends one when it wants a structured
 * edit, nothing when it wants prose): OpenAI-shaped servers take it as
 * `response_format`, Gemini as `generationConfig.responseSchema`, Anthropic
 * has no constrained mode without tools and is left to the prompt. The
 * schema is DATA — passed through as JSON, never interpreted here.
 */
export function shapeRequest(cfg, messages, opts = {}) {
  const system = messages.filter((m) => m.role === 'system').map((m) => m.content).join('\n\n')
  const turns = messages.filter((m) => m.role !== 'system')
  const base = baseOf(cfg)
  const schema = opts.schema
  switch (cfg.provider) {
    case 'openai':
      return {
        url: `${base}/chat/completions`,
        headers: {
          'content-type': 'application/json',
          // A local server (Ollama, LM Studio) needs no key; sending an empty
          // bearer would be refused by some of them.
          ...(cfg.key ? { authorization: `Bearer ${cfg.key}` } : {}),
        },
        body: JSON.stringify({
          model: cfg.model, stream: true, messages,
          ...(schema ? { response_format: { type: 'json_schema', json_schema: { name: 'reply', schema } } } : {}),
        }),
      }
    case 'anthropic':
      return {
        url: `${base}/v1/messages`,
        headers: {
          'content-type': 'application/json',
          'x-api-key': cfg.key || '',
          'anthropic-version': '2023-06-01',
          // The request runs in an extension worker, which the API treats as a
          // browser origin: without this header it refuses CORS outright.
          'anthropic-dangerous-direct-browser-access': 'true',
        },
        body: JSON.stringify({
          model: cfg.model, max_tokens: 16384, stream: true,
          ...(system ? { system } : {}),
          messages: turns.map((m) => ({ role: m.role, content: m.content })),
        }),
      }
    case 'gemini':
      return {
        url: `${base}/v1beta/models/${encodeURIComponent(cfg.model)}:streamGenerateContent?alt=sse`,
        headers: { 'content-type': 'application/json', 'x-goog-api-key': cfg.key || '' },
        body: JSON.stringify({
          ...(system ? { systemInstruction: { parts: [{ text: system }] } } : {}),
          contents: turns.map((m) => ({ role: m.role === 'assistant' ? 'model' : 'user', parts: [{ text: m.content }] })),
          // Gemini's schema dialect wants an OBJECT to have properties; the
          // loose "any object" schema has none, and Gemini answers it with an
          // empty object rather than a 400 (measured, 3.5-flash-lite). So a
          // property-less schema asks for JSON by mime type only — the prompt
          // carries the shape — and a real schema goes through.
          ...(schema ? { generationConfig: { responseMimeType: 'application/json', ...(hasProperties(schema) ? { responseSchema: schema } : {}) } } : {}),
        }),
      }
    default:
      throw new Error(`unknown provider: ${cfg.provider}`)
  }
}

/** A cheap reachability probe (assistant.check): the request to make; 2xx counts as ok. */
export function shapeCheck(cfg) {
  const base = baseOf(cfg)
  switch (cfg.provider) {
    case 'openai':
      return { method: 'GET', url: `${base}/models`, headers: cfg.key ? { authorization: `Bearer ${cfg.key}` } : {} }
    case 'anthropic': {
      const r = shapeRequest(cfg, [{ role: 'user', content: 'ping' }])
      return { method: 'POST', url: r.url, headers: r.headers, body: JSON.stringify({ model: cfg.model, max_tokens: 1, messages: [{ role: 'user', content: 'ping' }] }) }
    }
    case 'gemini':
      return { method: 'GET', url: `${base}/v1beta/models/${encodeURIComponent(cfg.model)}`, headers: { 'x-goog-api-key': cfg.key || '' } }
    default:
      throw new Error(`unknown provider: ${cfg.provider}`)
  }
}

/**
 * Pull the text delta out of one SSE `data:` payload. Returns '' for frames
 * that carry no text (role deltas, usage, pings) and null when the stream is
 * finished ([DONE], message_stop, an error frame).
 */
export function deltaFrom(provider, data) {
  if (data === '[DONE]') return null
  let j
  try { j = JSON.parse(data) } catch { return '' }
  if (!j || typeof j !== 'object') return ''
  switch (provider) {
    case 'openai': {
      const c = j.choices?.[0]
      if (!c) return j.error ? null : ''
      const d = c.delta?.content ?? c.text ?? ''
      return typeof d === 'string' ? d : ''
    }
    case 'anthropic': {
      if (j.type === 'message_stop') return null
      if (j.type === 'error') return null
      if (j.type === 'content_block_delta' && j.delta?.type === 'text_delta') return String(j.delta.text ?? '')
      return ''
    }
    case 'gemini': {
      const parts = j.candidates?.[0]?.content?.parts
      return Array.isArray(parts) ? parts.map((p) => (typeof p?.text === 'string' ? p.text : '')).join('') : ''
    }
    default:
      return ''
  }
}

/**
 * The error text to surface for a non-2xx response body, provider-shaped.
 * Status and the provider's own message — never the URL, the headers or
 * what was sent (security review of #512, item 3).
 */
export function errorFrom(provider, status, body) {
  try {
    const j = JSON.parse(body)
    const m = j.error?.message ?? j.message ?? (typeof j.error === 'string' ? j.error : null)
    if (m) return `HTTP ${status}: ${String(m).slice(0, 200)}`
  } catch { /* not json */ }
  return `HTTP ${status}${body ? `: ${String(body).slice(0, 120)}` : ''}`
}

/**
 * Incremental SSE line parser: feed chunks of the response body, get the
 * `data:` payloads. Handles multi-line data fields, CRLF, and a payload
 * split across chunks (which every provider does).
 */
export class SseParser {
  #buf = ''
  #data = []
  feed(chunk) {
    this.#buf += chunk
    const out = []
    let i
    while ((i = this.#buf.search(/\r?\n/)) >= 0) {
      const line = this.#buf.slice(0, i)
      this.#buf = this.#buf.slice(i + (this.#buf[i] === '\r' ? 2 : 1))
      if (line === '') {
        if (this.#data.length) { out.push(this.#data.join('\n')); this.#data = [] }
      } else if (line.startsWith('data:')) {
        this.#data.push(line.slice(5).replace(/^ /, ''))
      }
      // event:/id:/retry:/comments ignored — none of the three providers needs them
    }
    return out
  }
  /** end of stream: flush a dangling event with no trailing blank line */
  end() {
    const out = this.feed('\n\n')
    if (this.#data.length) { out.push(this.#data.join('\n')); this.#data = [] }
    return out
  }
}

/**
 * Drive one streaming response. `read` yields body text chunks; `onChunk` is
 * called per text delta; resolves with the whole text. The model's text is
 * passed through VERBATIM and never interpreted — no tool calls honoured, no
 * URLs followed. The page treats the reply as data; so does this.
 */
export async function streamReply(provider, read, onChunk) {
  const sse = new SseParser()
  let text = ''
  let done = false
  const take = (payloads) => {
    for (const p of payloads) {
      if (done) return
      const d = deltaFrom(provider, p)
      if (d === null) { done = true; return }
      if (d) { text += d; onChunk(d) }
    }
  }
  for await (const chunk of read) { take(sse.feed(chunk)); if (done) break }
  if (!done) take(sse.end())
  return text
}

/** A fetch body as text chunks, for `streamReply`. */
export async function* iterateBody(body) {
  const reader = body.getReader()
  const dec = new TextDecoder()
  try {
    for (;;) {
      const { value, done } = await reader.read()
      if (done) break
      yield dec.decode(value, { stream: true })
    }
    const tail = dec.decode()
    if (tail) yield tail
  } finally {
    reader.releaseLock()
  }
}

// ---------------------------------------------------------------- tool calls
//
// The agent loop (assistant.js runAgent) speaks ONE neutral thread and the
// three vendors' function-calling dialects are shaped here, non-streaming:
//
//   { role:'system'|'user', content }
//   { role:'assistant', content?, calls?: [{ id, name, args }] }
//   { role:'tool', id, name, content }            the result of one call
//
// A tool is { name, description, parameters } with a JSON-Schema object of
// named string/integer properties — kept to what every dialect takes, and
// never an OBJECT with no properties (Gemini hollows those).

/**
 * Does this route have the provider's own web search, and how? Gemini and
 * Anthropic take a server-side tool beside our functions; OpenAI's chat
 * endpoint only searches on its `-search-preview` models (the Responses API
 * is another dialect, not spoken here) — Settings says which applies.
 */
export function nativeSearch(cfg) {
  switch (cfg.provider) {
    case 'gemini': return 'google'
    case 'anthropic': return 'anthropic'
    case 'openai': return /search-preview/.test(cfg.model || '') ? 'openai' : null
    default: return null
  }
}

/** The non-streaming request for one agent step with tools. `opts.search` adds the provider's own web search. */
export function shapeToolRequest(cfg, thread, tools, opts = {}) {
  const base = baseOf(cfg)
  const system = thread.filter((m) => m.role === 'system').map((m) => m.content).join('\n\n')
  const turns = thread.filter((m) => m.role !== 'system')
  switch (cfg.provider) {
    case 'openai': {
      const messages = []
      for (const m of turns) {
        if (m.role === 'tool') messages.push({ role: 'tool', tool_call_id: m.id, content: m.content })
        else if (m.role === 'assistant' && m.calls?.length) {
          messages.push({ role: 'assistant', content: m.content || null, tool_calls: m.calls.map((c) => ({ id: c.id, type: 'function', function: { name: c.name, arguments: JSON.stringify(c.args ?? {}) } })) })
        } else messages.push({ role: m.role, content: m.content })
      }
      if (system) messages.unshift({ role: 'system', content: system })
      return {
        url: `${base}/chat/completions`,
        headers: { 'content-type': 'application/json', ...(cfg.key ? { authorization: `Bearer ${cfg.key}` } : {}) },
        body: JSON.stringify({
          model: cfg.model, messages, tools: tools.map((t) => ({ type: 'function', function: { name: t.name, description: t.description, parameters: t.parameters } })), tool_choice: 'auto',
          ...(opts.search && nativeSearch(cfg) === 'openai' ? { web_search_options: {} } : {}),
        }),
      }
    }
    case 'anthropic': {
      const messages = []
      for (const m of turns) {
        if (m.role === 'tool') {
          const block = { type: 'tool_result', tool_use_id: m.id, content: m.content }
          const prev = messages[messages.length - 1]
          if (prev?.role === 'user' && Array.isArray(prev.content)) prev.content.push(block)
          else messages.push({ role: 'user', content: [block] })
        } else if (m.role === 'assistant' && m.raw) {
          // a reply that carried server-tool blocks (web search) goes back verbatim
          messages.push({ role: 'assistant', content: m.raw })
        } else if (m.role === 'assistant' && m.calls?.length) {
          messages.push({ role: 'assistant', content: [...(m.content ? [{ type: 'text', text: m.content }] : []), ...m.calls.map((c) => ({ type: 'tool_use', id: c.id, name: c.name, input: c.args ?? {} }))] })
        } else messages.push({ role: m.role, content: m.content })
      }
      return {
        url: `${base}/v1/messages`,
        headers: { 'content-type': 'application/json', 'x-api-key': cfg.key || '', 'anthropic-version': '2023-06-01', 'anthropic-dangerous-direct-browser-access': 'true' },
        body: JSON.stringify({
          model: cfg.model, max_tokens: 16384, ...(system ? { system } : {}), messages,
          tools: [
            ...tools.map((t) => ({ name: t.name, description: t.description, input_schema: t.parameters })),
            ...(opts.search ? [{ type: 'web_search_20250305', name: 'web_search', max_uses: 5 }] : []),
          ],
        }),
      }
    }
    case 'gemini': {
      const contents = []
      for (const m of turns) {
        if (m.role === 'tool') {
          const part = { functionResponse: { name: m.name, response: { result: m.content } } }
          const prev = contents[contents.length - 1]
          if (prev?.role === 'user' && prev.parts.some((p) => p.functionResponse)) prev.parts.push(part)
          else contents.push({ role: 'user', parts: [part] })
        } else if (m.role === 'assistant' && m.calls?.length) {
          contents.push({ role: 'model', parts: [...(m.content ? [{ text: m.content }] : []), ...m.calls.map((c) => ({ functionCall: { name: c.name, args: c.args ?? {} } }))] })
        } else contents.push({ role: m.role === 'assistant' ? 'model' : 'user', parts: [{ text: m.content }] })
      }
      return {
        url: `${base}/v1beta/models/${encodeURIComponent(cfg.model)}:generateContent`,
        headers: { 'content-type': 'application/json', 'x-goog-api-key': cfg.key || '' },
        body: JSON.stringify({
          ...(system ? { systemInstruction: { parts: [{ text: system }] } } : {}), contents,
          tools: [
            { functionDeclarations: tools.map((t) => ({ name: t.name, description: t.description, parameters: t.parameters })) },
            ...(opts.search ? [{ google_search: {} }] : []),
          ],
        }),
      }
    }
    default:
      throw new Error(`unknown provider: ${cfg.provider}`)
  }
}

/** One agent step's reply: the text, the calls it asked for, and any web sources it cited — in the neutral shape. */
export function parseToolReply(provider, json) {
  const out = { text: '', calls: [], sources: [] }
  if (!json || typeof json !== 'object') return out
  const cite = (title, url) => { if (typeof url === 'string' && /^https?:\/\//.test(url)) out.sources.push({ title: typeof title === 'string' ? title : '', url }) }
  let n = 0
  const mint = () => `call-${++n}`
  switch (provider) {
    case 'openai': {
      const msg = json.choices?.[0]?.message
      if (typeof msg?.content === 'string') out.text = msg.content
      for (const a of Array.isArray(msg?.annotations) ? msg.annotations : []) if (a?.type === 'url_citation') cite(a.url_citation?.title, a.url_citation?.url)
      for (const c of Array.isArray(msg?.tool_calls) ? msg.tool_calls : []) {
        let args = {}
        try { args = JSON.parse(c.function?.arguments || '{}') } catch { args = {} }
        out.calls.push({ id: typeof c.id === 'string' ? c.id : mint(), name: String(c.function?.name ?? ''), args: args && typeof args === 'object' ? args : {} })
      }
      return out
    }
    case 'anthropic': {
      const blocks = Array.isArray(json.content) ? json.content : []
      for (const b of blocks) {
        if (b?.type === 'text' && typeof b.text === 'string') {
          out.text += b.text
          for (const c of Array.isArray(b.citations) ? b.citations : []) cite(c?.title, c?.url)
        } else if (b?.type === 'tool_use') out.calls.push({ id: typeof b.id === 'string' ? b.id : mint(), name: String(b.name ?? ''), args: b.input && typeof b.input === 'object' ? b.input : {} })
        else if (b?.type === 'web_search_tool_result') for (const r of Array.isArray(b.content) ? b.content : []) if (r?.type === 'web_search_result') cite(r.title, r.url)
      }
      // server-tool blocks must go back to the model verbatim on the next step
      if (blocks.some((b) => b?.type === 'server_tool_use' || b?.type === 'web_search_tool_result')) out.raw = blocks
      return out
    }
    case 'gemini': {
      for (const p of json.candidates?.[0]?.content?.parts ?? []) {
        if (typeof p?.text === 'string') out.text += p.text
        else if (p?.functionCall) out.calls.push({ id: mint(), name: String(p.functionCall.name ?? ''), args: p.functionCall.args && typeof p.functionCall.args === 'object' ? p.functionCall.args : {} })
      }
      for (const ch of json.candidates?.[0]?.groundingMetadata?.groundingChunks ?? []) cite(ch?.web?.title, ch?.web?.uri)
      return out
    }
    default:
      return out
  }
}