mirror of
https://github.com/bitbaum/substrata.git
synced 2026-12-04 05:07:46 +01:00
* feat(market-data): share prices, SEC fundamentals and filing-based holders, with Ask tools and charts Prices: daily split-adjusted closes from Yahoo Finance's chart endpoint (query1, then query2), stored in research_price_points by /api/cron/prices, read by priceHistory(ticker, range) with a live fallback; returns, 52-week extremes, drawdown and moving averages computed in code. Stooq (browser challenge), Nasdaq (browser agent only) and Alpha Vantage (unadjusted free closes) were tested and rejected; the reasons and the licence position are in lib/market-data/prices/chain.ts. Fundamentals: SEC XBRL company facts per CIK — revenue, margins, R&D, capex, cash, assets, debt, shares — each point with form, accession and filing link; a typed "unavailable" with the reason for companies the SEC holds nothing for. Holders: the proxy's ownership table, structured Schedules 13G/13D filed since (issuer checked, 0% amendments honoured) and recent Forms 4, with the rest as a typed remainder that says what it is — never a bare "Other 87%". The company page's ownership view and share bar carry the same remainder. Ask: price_history, fundamentals and holders tools; a price question plans price_history and the answer draws a line chart built in code (answer charts routed like answer tables); four ask-evals rows. Keyed by ticker in lib/market-data/identity.ts with a committed seed (config/market-seed.ts) as the seam for the company universe. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_018WZnBnaLP6RhwFkLxRTKgE * fix(market-data): fundamentals lists newest first so a length cut keeps the latest years Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_018WZnBnaLP6RhwFkLxRTKgE --------- Co-authored-by: Claude <noreply@anthropic.com>
301 lines
11 KiB
TypeScript
301 lines
11 KiB
TypeScript
/**
|
|
* Ask, as an assistant rather than a retrieval probe: the model reads where the
|
|
* reader is, calls the functions in `lib/chat-tools/` for what it needs, and
|
|
* answers from what came back, streamed as it is written.
|
|
*
|
|
* The provider chain is ai-kit's; this file only adapts it. Why it is shaped so:
|
|
* 1. BOTH TOOL PROTOCOLS: half the free chain writes `TOOL:`/`ARGS:` lines
|
|
* instead of native calls (ai-kit tool-protocol.ts); they are parsed from
|
|
* the finished turn and `StreamGate` keeps them off the reader's screen.
|
|
* 2. RESULTS GO BACK AS TEXT, as a user message rather than `role: "tool"`:
|
|
* the chain can fall to another vendor between rounds, and a call id
|
|
* minted by one is not something the next must accept.
|
|
* 3. SPEED IS THE ROUND COUNT: a status line before anything is fetched,
|
|
* calls in a round in parallel, the page's own record skips tools, verify
|
|
* mode fetches its evidence first, rounds capped at three. The web is read
|
|
* beside the corpus (route.ts); an analysis question goes to research.ts.
|
|
*
|
|
* Out of free budget, the reader is told so, with the records read — never a fabricated answer.
|
|
*/
|
|
import { StreamInterrupted, type ChatMessage } from '@bitbaum/ai-kit';
|
|
import type { ByokConfig } from '../byok';
|
|
import { toolDefinitions } from '../chat-tools/registry';
|
|
import { emptyLedger, type ToolEnv } from '../chat-tools/ledger';
|
|
import { preloadPage, type ReaderContext } from '../chat-context';
|
|
import { followUpsFor } from '../chat-query';
|
|
import type { ChatTurn } from '../chat/types';
|
|
import {
|
|
answerableFromPage,
|
|
extrasOf,
|
|
failureEvent,
|
|
openingStatus,
|
|
sourcesOf,
|
|
unwrittenAnswer,
|
|
type AgentAnswer,
|
|
type AgentEvent,
|
|
} from './answer';
|
|
import { finalAnswer, renderCalls, toolRound } from './parse';
|
|
import { checkAnswer } from './check-answer';
|
|
import { runLookups, runPlan } from './lookups';
|
|
import type { GapFiler } from './gaps';
|
|
import { planLookups } from './plan';
|
|
import { routeQuestion } from './route';
|
|
import { runResearch } from './research';
|
|
import { LOOP_LIMITS, systemPrompt } from './prompt';
|
|
import type { ModelTurn, ModelTurnResult } from './turn';
|
|
import { gatherEvidence, verdictOf, verifyQuestion, type VerifyRequest } from './verify';
|
|
|
|
export {
|
|
answerableFromPage,
|
|
budgetMessage,
|
|
isPageRecord,
|
|
type AgentAnswer,
|
|
type AgentEvent,
|
|
} from './answer';
|
|
|
|
const { rounds: MAX_ROUNDS, callsPerRound: MAX_CALLS_PER_ROUND } = LOOP_LIMITS;
|
|
|
|
export async function runAgent(input: {
|
|
question: string;
|
|
history: ChatTurn[];
|
|
context: ReaderContext;
|
|
turn: ModelTurn;
|
|
env: Omit<ToolEnv, 'ledger'>;
|
|
emit: (event: AgentEvent) => void;
|
|
byok?: ByokConfig;
|
|
verify?: VerifyRequest;
|
|
today?: string;
|
|
replies?: boolean; // suggested replies: the Ask panel only, never a factcheck
|
|
fileGap?: GapFiler; // where a named missing link is filed (gaps.ts); the bound one by default
|
|
}): Promise<void> {
|
|
const started = Date.now();
|
|
let firstText: number | undefined;
|
|
const emit = (event: AgentEvent) => {
|
|
if (event.type === 'delta' && firstText === undefined) firstText = Date.now() - started;
|
|
input.emit(event);
|
|
};
|
|
emit({ type: 'status', text: openingStatus(input.context, input.verify) }); // before any fetch
|
|
const ledger = emptyLedger();
|
|
const env: ToolEnv = {
|
|
...input.env,
|
|
ledger,
|
|
step: (label) => {
|
|
ledger.trail.push(label); // "Reading reuters.com…": seen while it works, kept after
|
|
emit({ type: 'tool', label });
|
|
},
|
|
};
|
|
const question = input.verify ? verifyQuestion(input.verify) : input.question;
|
|
// The lookups the question obviously needs, made before any model round
|
|
// (plan.ts). A plan outranks "the page answers it": "what is new here" needs the leads.
|
|
const plan = input.verify
|
|
? { calls: [], confident: false, webQuery: '' }
|
|
: planLookups(question, input.context, env);
|
|
// Which sources the question needs (route.ts): the web is searched beside the corpus, up front.
|
|
const route = input.verify ? undefined : routeQuestion(question, input.today);
|
|
if (route?.analysis && input.env.web) return runResearch(input);
|
|
const pageOnly =
|
|
!input.verify &&
|
|
!plan.calls.length &&
|
|
answerableFromPage(question, Boolean(input.context.entity));
|
|
const [preload, evidence, looked] = await Promise.all([
|
|
preloadPage(input.context, env),
|
|
input.verify ? gatherEvidence(input.verify, env) : Promise.resolve(undefined),
|
|
runPlan(plan, question, input.context, env, emit, route),
|
|
]);
|
|
const lookedUp = looked.results; // an empty or partial lookup already opened the web (runPlan)
|
|
const allResults = [...lookedUp]; // every result the answer rests on: the wall check, the gap
|
|
const planEmpty = looked.empty;
|
|
const noTools = pageOnly || (plan.confident && !planEmpty);
|
|
// A tool the planner ran unfiltered is not offered again (models re-asked, 2026-10-02).
|
|
const tools = toolDefinitions(env).filter(
|
|
(t) => !plan.calls.some((c) => c.name === t.function.name && c.args === '{}'),
|
|
);
|
|
const system = systemPrompt({
|
|
context: input.context,
|
|
preloaded: preload?.text,
|
|
lookedUp: lookedUp.length ? lookedUp.join('\n\n') : undefined,
|
|
lookedUpEmpty: planEmpty,
|
|
web: looked.web,
|
|
openWorld: Boolean(route?.web),
|
|
gaps: looked.gaps,
|
|
tools: noTools ? [] : tools,
|
|
byok: input.byok,
|
|
today: input.today,
|
|
verify: evidence,
|
|
replies: input.replies,
|
|
});
|
|
const messages: ChatMessage[] = [
|
|
{ role: 'system', content: system },
|
|
// Recent turns only, long answers clipped: history is paid again every round.
|
|
...input.history.slice(-4).map((t) => ({
|
|
role: t.role,
|
|
content: t.content.length > 900 ? `${t.content.slice(0, 900)}…` : t.content,
|
|
})),
|
|
{ role: 'user', content: question },
|
|
];
|
|
if (input.verify || noTools) emit({ type: 'status', text: 'Writing…' });
|
|
const seen = new Set<string>(plan.calls.map((c) => `${c.name}:${c.args}`));
|
|
let modelCalls = 0;
|
|
const skipped: string[] = [];
|
|
let answer = '';
|
|
let replies: string[] = [];
|
|
let model: string | undefined;
|
|
let shown = '';
|
|
// Model calls are the latency: one, two with a record in hand, four from nowhere.
|
|
let lastRound = noTools
|
|
? 0
|
|
: planEmpty
|
|
? MAX_ROUNDS - 1
|
|
: plan.calls.length || preload
|
|
? 1
|
|
: MAX_ROUNDS;
|
|
// Once: a model asking for a tool when none are offered gets it run, then writes.
|
|
let bonusUsed = false;
|
|
let cutShort = '';
|
|
|
|
try {
|
|
for (let round = 0; round <= lastRound; round++) {
|
|
const offer = round < lastRound ? tools : undefined;
|
|
if (round > 0) emit({ type: 'status', text: 'Reading what came back…' });
|
|
shown = '';
|
|
let result: ModelTurnResult;
|
|
modelCalls++;
|
|
try {
|
|
result = await input.turn({
|
|
messages,
|
|
tools: offer,
|
|
onText: (text) => {
|
|
shown += text;
|
|
emit({ type: 'delta', text });
|
|
},
|
|
});
|
|
} catch (error) {
|
|
if (error instanceof StreamInterrupted && shown.trim().length > 40 && !offer) {
|
|
// Half an answer is on screen and the vendor went away. Say so rather
|
|
// than silently restart it from another vendor.
|
|
answer = `${finalAnswer(shown).answer}\n\n*(The model stopped mid-answer. Ask again to regenerate.)*`;
|
|
break;
|
|
}
|
|
throw error;
|
|
}
|
|
model = result.model;
|
|
skipped.push(...(result.skipped ?? []));
|
|
const fresh = result.calls
|
|
.filter((c) => {
|
|
const key = `${c.name}:${c.args}`;
|
|
if (seen.has(key)) return false;
|
|
seen.add(key);
|
|
return true;
|
|
})
|
|
.slice(0, MAX_CALLS_PER_ROUND);
|
|
if (offer && fresh.length) {
|
|
if (shown) emit({ type: 'reset' });
|
|
if (input.env.signal?.aborted) return;
|
|
const results = await runLookups(fresh, input.context, env, emit);
|
|
allResults.push(...results);
|
|
messages.push(...toolRound(result.text, fresh, results, 'more'));
|
|
continue;
|
|
}
|
|
if (offer && result.calls.length && !fresh.length) {
|
|
// Asked for exactly what it already has: push it to answer.
|
|
messages.push(
|
|
{ role: 'assistant', content: renderCalls(result.calls) },
|
|
{ role: 'user', content: 'You already have those results above. Answer now.' },
|
|
);
|
|
if (shown) emit({ type: 'reset' });
|
|
continue;
|
|
}
|
|
const stray = (result.stray ?? []).filter((c) => !seen.has(`${c.name}:${c.args}`));
|
|
if (!offer && stray.length && !bonusUsed && result.text.trim().length < 200) {
|
|
// Seen live 2026-10-02: the final round's whole answer was
|
|
// `TOOL: get_bottleneck / ARGS: {...}`, shown to the reader as the answer.
|
|
bonusUsed = true;
|
|
lastRound = round + 1;
|
|
if (shown) emit({ type: 'reset' });
|
|
if (input.env.signal?.aborted) return;
|
|
for (const c of stray) seen.add(`${c.name}:${c.args}`);
|
|
const results = await runLookups(
|
|
stray.slice(0, MAX_CALLS_PER_ROUND),
|
|
input.context,
|
|
env,
|
|
emit,
|
|
);
|
|
allResults.push(...results);
|
|
messages.push(...toolRound('', stray, results, 'last'));
|
|
continue;
|
|
}
|
|
if (result.truncated && !cutShort) {
|
|
// Out of output budget mid-answer: one call to finish it, not a blank.
|
|
cutShort = result.text;
|
|
lastRound = round + 1;
|
|
messages.push(
|
|
{ role: 'assistant', content: result.text },
|
|
{
|
|
role: 'user',
|
|
content:
|
|
'You stopped mid-answer. Continue exactly where you stopped; do not repeat anything.',
|
|
},
|
|
);
|
|
continue;
|
|
}
|
|
({ answer, replies } = finalAnswer(`${cutShort}${result.text}`));
|
|
break;
|
|
}
|
|
} catch (error) {
|
|
if (input.env.signal?.aborted) return;
|
|
const failure = failureEvent(error, ledger, {
|
|
total: Date.now() - started,
|
|
calls: modelCalls,
|
|
planned: plan.calls.length,
|
|
skipped,
|
|
});
|
|
if (failure.type === 'done' && shown) emit({ type: 'reset' });
|
|
emit(failure);
|
|
return;
|
|
}
|
|
|
|
const checked = await checkAnswer({
|
|
answer,
|
|
question,
|
|
results: allResults,
|
|
messages,
|
|
verify: Boolean(input.verify),
|
|
turn: input.turn,
|
|
emit,
|
|
fileGap: input.fileGap,
|
|
});
|
|
answer = checked.answer;
|
|
modelCalls += checked.calls;
|
|
answer = answer.trim() ? answer : (unwrittenAnswer(ledger) ?? '');
|
|
if (!answer) {
|
|
emit({
|
|
type: 'error',
|
|
kind: 'unavailable',
|
|
error: 'The model returned no answer. Please ask again.',
|
|
});
|
|
return;
|
|
}
|
|
const sources = sourcesOf(ledger);
|
|
const data: AgentAnswer = {
|
|
answer,
|
|
sources,
|
|
web: ledger.web,
|
|
leads: ledger.leads,
|
|
...extrasOf(ledger),
|
|
followUps: followUpsFor(sources.map((s) => ({ title: s.title, kind: s.kind }))),
|
|
trail: ledger.trail,
|
|
outside: ledger.web.length > 0,
|
|
...(replies.length ? { replies } : {}),
|
|
model,
|
|
timing: {
|
|
firstText,
|
|
total: Date.now() - started,
|
|
calls: modelCalls,
|
|
planned: plan.calls.length,
|
|
skipped,
|
|
},
|
|
};
|
|
if (input.verify) data.verdict = verdictOf(answer);
|
|
emit({ type: 'done', data });
|
|
}
|