Back to Body Journal
SOURCE / PINNED RELEASE

Made of little things.

Body Journal

Release
e8049f8da4e2…
Author-recorded commit
61c04bf0e8aa…
License
LICENSE
Author’s source reference
nostr://npub182jczunncwe0jn6frpqwq3e0qjws7yqqnc3auccqv9nte2dnd63scjm4rf/wss%3A%2F%2Fgit.napplet.soy%2F/n-6c4554844c7

Archive hash verified: 4369d778da046a8b…. The source-to-build association is the author’s claim; it has not been independently rebuilt.

bridge/provider-response.mjs
import { OUTPUT_LIMIT, REASONING_LIMIT, redact } from '../src/ai-diagnostics.ts';

export function diagnostics(key, onProgress = () => {}) {
  const start = Date.now();
  const d = { stage: 'requesting', elapsedMs: 0, output: '', reasoning: '', events: [] };
  let raw = '', reasoning = '';
  function publish(stage = d.stage, final = false) {
    d.elapsedMs = Date.now() - start;
    if (d.events.at(-1)?.stage !== stage) d.events.push({ stage, elapsedMs: d.elapsedMs });
    d.events = d.events.slice(-24); d.stage = stage;
    // Hold a tail while streaming: an API key split across chunks must never leak.
    const safe = value => { const clean=redact(value,key);return clean.slice(0,final && !d.truncated?undefined:Math.max(0,clean.length-key.length*3)); };
    d.output = safe(raw); d.reasoning = safe(reasoning);
    onProgress(structuredClone(d));
  }
  return { d, publish, content: () => raw,
    append(content, thinking) {
      if (typeof content === 'string') { raw += content; if (raw.length > OUTPUT_LIMIT) { raw = raw.slice(0, OUTPUT_LIMIT); d.truncated = true; throw new Error('output-limit'); } }
      if (typeof thinking === 'string') { if (reasoning.length + thinking.length > REASONING_LIMIT) d.truncated = true; reasoning = (reasoning + thinking).slice(0, REASONING_LIMIT); }
      publish('receiving');
    },
    metadata(data, choice) {
      for (const [name, value] of [['model', data.model], ['responseId', data.id], ['finishReason', choice?.finish_reason]]) if (typeof value === 'string') d[name] = redact(value, key).slice(0, 160);
      if (data.usage && typeof data.usage === 'object') {
        d.usage ||= {};
        for (const [name, value] of [['input', data.usage.prompt_tokens], ['output', data.usage.completion_tokens], ['total', data.usage.total_tokens], ['reasoning', data.usage.completion_tokens_details?.reasoning_tokens]]) if (Number.isInteger(value) && value >= 0 && value <= 1e9) d.usage[name] = value;
      }
    },
  };
}
export async function readText(response, limit = 160_000) {
  const reader = response.body?.getReader(); if (!reader) throw new Error('empty-body');
  const chunks = []; let size = 0;
  try {
    for (;;) { const { done, value } = await reader.read(); if (done) break; size += value.byteLength; if (size > limit) throw new Error('response-limit'); chunks.push(value); }
    return Buffer.concat(chunks).toString('utf8');
  } finally { await reader.cancel().catch(() => {}); reader.releaseLock(); }
}
export async function readCompletion(response, capture) {
  if (!response.headers.get('content-type')?.includes('text/event-stream')) {
    const text = await readText(response);
    let data; try { data = JSON.parse(text); } catch { capture.append(text.slice(0, OUTPUT_LIMIT)); throw new Error('envelope-json'); }
    const choice = data?.choices?.[0]; capture.metadata(data, choice);
    capture.append(choice?.message?.content, choice?.message?.reasoning_content);
    return { choice, data };
  }
  const reader = response.body?.getReader(); if (!reader) throw new Error('empty-body');
  const decoder = new TextDecoder(); let buffer = '', bytes = 0, ended = false, finish, refusal = false, model = '';
  const event = block => {
    const payload = block.split('\n').filter(l => l.startsWith('data:')).map(l => l.slice(5).trimStart()).join('\n');
    if (!payload) return;
    if (payload.trim() === '[DONE]') { ended = true; return; }
    let data; try { data = JSON.parse(payload); } catch { throw new Error('stream-json'); }
    if (data.error) { capture.d.issue = {path:'provider',message:'The provider sent an error during streaming.'}; throw new Error('stream-error'); }
    const choice = data.choices?.find(c => c.index === 0) || data.choices?.[0];
    capture.metadata(data, choice); if (typeof data.model === 'string') model = data.model;
    capture.append(choice?.delta?.content, choice?.delta?.reasoning_content);
    if (choice?.delta?.refusal) refusal = true;
    if (choice?.finish_reason) finish = choice.finish_reason;
  };
  try {
    while (!ended) {
      const {done,value} = await reader.read();
      if (done) { buffer += decoder.decode(); if (buffer.trim()) event(buffer.replace(/\r/g,'')); break; }
      bytes += value.byteLength; if (bytes > 2_000_000) throw new Error('response-limit');
      buffer += decoder.decode(value,{stream:true});
      // CRLF can be split between reads. Normalize only complete frames.
      for (;;) { const match = /\r?\n\r?\n/.exec(buffer); if (!match) break; const block=buffer.slice(0,match.index).replace(/\r/g,''); buffer=buffer.slice(match.index+match[0].length); event(block); if(ended)break; }
      if (buffer.length > 160_000) throw new Error('response-limit');
    }
    if (!ended || !finish) throw new Error('stream-incomplete');
    return {data:{model},choice:{finish_reason:finish,message:{content:capture.content(),refusal}}};
  } finally { await reader.cancel().catch(()=>{}); reader.releaseLock(); }
}