Files
CatoandClaude fa73bb626b fix(chat): the reader is told when the web search brought nothing back (#372)
Seen on production: every question showed "Searching the web for …" in
its steps and then an answer with no web page and no word about it. The
search outcome was known to the prompt only, so saying it was left to
the model, which did not.

The outcome of the answer's web searches (found, nothing, or could not
be reached) is now recorded by the search itself and carried on the
answer. When no page came back, a line under the answer says which of
the two it was. An outage is never told as "found nothing".

Claude-Session: https://claude.ai/code/session_019MDtmuvTGrpo3VChP3skH8

Co-authored-by: Claude <noreply@anthropic.com>
2026-11-12 06:15:56 +01:00

181 lines
7.1 KiB
TypeScript

/** What the loop streams, what a finished answer carries, and the honest fallbacks. */
import { ChainExhaustedError } from '@bitbaum/ai-kit';
import { ByokError } from '../byok';
import type { Ledger } from '../chat-tools/ledger';
import { findBottleneck, findCompany } from '../chat-tools/resolve';
import type { ReaderContext } from '../chat-context';
import type { ChatSource } from '../chat/types';
import type { AnswerTable } from '../chat/answer-table';
import { extrasOf, type AnswerChart } from '../chat/answer-chart';
export { extrasOf };
import type { EntityKind } from '../entities/types';
import { safeArgs, type ToolRequest } from './parse';
import type { Verdict } from './verify';
export type AgentEvent =
| { type: 'status'; text: string }
| { type: 'tool'; label: string }
| { type: 'delta'; text: string }
| { type: 'reset' }
| { type: 'done'; data: AgentAnswer }
| { type: 'error'; error: string; kind?: 'budget' | 'byok' | 'unavailable' | 'blind' };
export interface AgentAnswer {
answer: string;
sources: ChatSource[];
web: Ledger['web'];
leads: Ledger['leads'];
/** Tables built in code from the tool rows, drawn under the prose (lib/chat/answer-table.ts). */
tables?: AnswerTable[];
/** Charts built in code from tool rows (lib/chat/answer-chart.ts). */
charts?: AnswerChart[];
/** How the web search went, when the web was searched (lib/chat-tools/ledger.ts). */
webSearch?: Ledger['webSearch'];
followUps: string[];
/** The tool calls made, in order, as the reader-facing labels. */
trail: string[];
outside: boolean;
model?: string;
/** True when no model could answer and this is the honest fallback. */
degraded?: boolean;
/** Verify mode: the verdict the answer opened with. */
verdict?: Verdict;
/** What the reader is likely to say next, written by the model (chatkit). */
replies?: string[];
/** Claim check: the reader's screenshot or post as read, kept for the next turn's history. */
material?: string;
/**
* Milliseconds from the request to the first visible text and to the end;
* how many model calls it took and how many lookups were planned before them.
*/
timing?: {
firstText?: number;
total: number;
calls?: number;
planned?: number;
/** Links that refused on the way, `provider/model: kind`. */
skipped?: string[];
};
}
/** Why the chain came back empty, in words a reader can act on. */
export function budgetMessage(error: unknown): string | undefined {
if (!(error instanceof ChainExhaustedError)) return undefined;
const messages = error.failures.map((f) => f.message);
if (!messages.length) return 'No AI provider is configured on this deployment.';
const limited = messages.filter((m) => /: 429 /.test(m));
if (limited.length === 0 || limited.length < messages.length) return undefined;
if (limited.some((m) => /: 429 daily/.test(m)))
return "Today's free AI budget is used up — every free model this site uses has refused for the day. It resets at midnight UTC. Nothing below is an AI answer; the records I had already read are listed, and search still works. With your own AI key (the Key button under the question box) Ask keeps working now.";
return 'Every free AI model is at its per-minute limit right now. Try again in a minute; the records I had already read are listed below.';
}
export function sourcesOf(ledger: Ledger): ChatSource[] {
return [...ledger.records.values()].map((r, i) => ({
number: i + 1,
id: `R${i + 1}`,
title: r.title,
href: r.href,
evidence: r.evidence,
primary: r.primary,
kind: r.kind as EntityKind,
}));
}
/** A lookup of the record the page is about, which the prompt already carries. */
export function isPageRecord(call: ToolRequest, context: ReaderContext): boolean {
const entity = context.entity;
if (!entity) return false;
const name = String(safeArgs(call.args).name ?? '');
if (!name) return false;
if (
call.name === 'get_bottleneck' ||
(call.name === 'get_record' && entity.kind === 'bottleneck')
)
return entity.kind === 'bottleneck' && findBottleneck(name)?.slug === entity.key;
if (call.name === 'get_company' || (call.name === 'get_record' && entity.kind === 'company'))
return entity.kind === 'company' && findCompany(name)?.slug === entity.key;
return call.name === 'get_record' && name.toLowerCase() === entity.name.toLowerCase();
}
/**
* A question about the page the reader is on, which the pre-loaded record
* answers — so no tool round is paid for. Deliberately narrow: it must name
* the page ("this", "here", "it") and not reach for anything the record cannot
* hold (news, other companies, comparisons, the web).
*/
export function answerableFromPage(question: string, hasRecord: boolean): boolean {
if (!hasRecord || question.length > 160) return false;
const q = question.toLowerCase();
if (!/\b(this|here|it|its|page|summar|explain|what is|what does|why is|how is)\b/.test(q))
return false;
return !/\b(news|latest|today|this week|recent|lead|web|compare|versus|vs\.?|other|else|alternative|who else|competitor|price|stock|share)\b/.test(
q,
);
}
/**
* What the reader sees when the turn failed: the budget note (with what was
* read), a reader's-own-key error, or a plain "could not reach a model".
*/
export function failureEvent(
error: unknown,
ledger: Ledger,
timing: NonNullable<AgentAnswer['timing']>,
): AgentEvent {
const budget = budgetMessage(error);
if (budget)
return {
type: 'done',
data: {
answer: budget,
sources: sourcesOf(ledger),
web: ledger.web,
leads: ledger.leads,
// No AI answer, but the rows were read: the table still shows them.
...extrasOf(ledger),
followUps: [],
trail: ledger.trail,
outside: ledger.web.length > 0,
degraded: true,
timing,
},
};
if (error instanceof ByokError) return { type: 'error', error: error.message, kind: 'byok' };
console.error(
'Substrata ask failed',
error instanceof ChainExhaustedError
? error.failures.map((f) => f.message.slice(0, 120)).join(' | ')
: error instanceof Error
? error.name
: 'unknown',
);
return {
type: 'error',
kind: 'unavailable',
error:
'The assistant could not reach a model just now. You can still search the research or send a contribution.',
};
}
/** No prose came back: never a blank — the records it read are still worth opening. */
export function unwrittenAnswer(ledger: Ledger): string | undefined {
const read = sourcesOf(ledger);
if (!read.length) return undefined;
return `The model looked these up but did not write an answer. Ask again, or open them:\n\n${read
.slice(0, 8)
.map((s) => `- [${s.title}](${s.href})`)
.join('\n')}`;
}
/** The status line shown before anything is fetched: what the loop is about to read. */
export function openingStatus(context: ReaderContext, verify?: { source?: unknown }): string {
if (verify) {
return verify.source
? 'Reading the cited source and searching the web…'
: 'Searching the web for the claim…';
}
return context.entity ? `Reading ${context.entity.name}…` : 'Thinking…';
}