feat(research): cut over canonical runtime and enforce agent budgets

This commit is contained in:
Boki 2026-10-24 16:47:19 -04:00
parent ab08db82fd
commit bbf0dd4453
103 changed files with 6138 additions and 3112 deletions

View file

@ -0,0 +1,354 @@
import { useEffect, useRef, useState } from 'react';
import { Link, useSearchParams } from 'react-router-dom';
import {
createResearchAgentSchema,
type ResearchAgentBudget,
type ResearchAgentLimits,
type ResearchAgentRecord,
} from '@stock-bot/stock-config/research-agents';
import { actionClass, fieldClass } from '../strategies/components/StrategyParameterForm';
import { useUnsavedWarning } from '../strategies/components/useUnsavedWarning';
import { ResearchAgentApiError, researchAgentsApi } from './services/researchAgentsApi';
const limitFields: Array<[keyof ResearchAgentLimits, string, string]> = [
['maxActiveTrials', 'Maximum active trials', '1'],
['maxTrialsPerExperiment', 'Maximum trials per experiment', '10'],
['maxBarEvaluationsPerExperiment', 'Maximum bar evaluations per experiment', '100000'],
['maxAttemptWallMs', 'Maximum attempt time (ms)', '60000'],
['maxAttempts', 'Maximum attempts per run', '3'],
];
const identifiers = (value: string) => value.split(/[\s,]+/).filter(Boolean);
const message = (cause: unknown) =>
cause instanceof Error ? cause.message : 'Research agent request failed';
export function ResearchAgentsPage() {
const [search] = useSearchParams();
const [agents, setAgents] = useState<ResearchAgentRecord[]>([]);
const [budgets, setBudgets] = useState<Record<string, ResearchAgentBudget>>({});
const [name, setName] = useState('');
const [projects, setProjects] = useState(search.get('projectId') ?? '');
const [backtests, setBacktests] = useState('');
const [limits, setLimits] = useState<Record<string, string>>(() =>
Object.fromEntries(limitFields.map(([key, , value]) => [key, value]))
);
const [loading, setLoading] = useState(true);
const [error, setError] = useState('');
const [writeError, setWriteError] = useState('');
const [uncertain, setUncertain] = useState(false);
const [uncertainListChecked, setUncertainListChecked] = useState(false);
const [pending, setPending] = useState(false);
const [refresh, setRefresh] = useState(0);
const [token, setToken] = useState<string | null>(null);
const alive = useRef(false);
const writing = useRef(false);
const generation = useRef(0);
const budgetRequests = useRef(new Map<string, number>());
useUnsavedWarning(Boolean(name || backtests || token || uncertain));
useEffect(() => {
alive.current = true;
return () => {
alive.current = false;
generation.current++;
};
}, []);
useEffect(() => {
const current = ++generation.current;
const controller = new AbortController();
setLoading(true);
setError('');
setBudgets({});
void researchAgentsApi
.list(controller.signal)
.then(({ agents: next }) => {
if (alive.current && current === generation.current) {
setAgents(next);
setUncertainListChecked(true);
}
})
.catch(cause => {
if (!controller.signal.aborted && current === generation.current) {
setError(message(cause));
}
})
.finally(() => {
if (alive.current && current === generation.current) {
setLoading(false);
}
});
return () => controller.abort();
}, [refresh]);
async function create(event: React.FormEvent) {
event.preventDefault();
if (writing.current || loading || uncertain || token) {
return;
}
const parsed = createResearchAgentSchema.safeParse({
name,
allowedProjectIds: identifiers(projects),
allowedBacktestIds: identifiers(backtests),
limits: Object.fromEntries(limitFields.map(([key]) => [key, Number(limits[key])])),
});
if (!parsed.success) {
setWriteError(
parsed.error.issues.map(issue => `${issue.path.join('.')}: ${issue.message}`).join('; ')
);
return;
}
writing.current = true;
setPending(true);
setWriteError('');
generation.current++;
try {
const result = await researchAgentsApi.create(parsed.data);
if (alive.current) {
setAgents(previous => [
result.agent,
...previous.filter(agent => agent.id !== result.agent.id),
]);
setToken(result.token);
setName('');
setBacktests('');
}
} catch (cause) {
if (alive.current) {
setWriteError(message(cause));
setUncertain(!(cause instanceof ResearchAgentApiError) || cause.uncertain);
setUncertainListChecked(false);
}
} finally {
writing.current = false;
if (alive.current) {
setPending(false);
setLoading(false);
}
}
}
async function toggle(agent: ResearchAgentRecord) {
if (writing.current) {
return;
}
writing.current = true;
setPending(true);
setWriteError('');
generation.current++;
try {
const { agent: updated } = await researchAgentsApi.update(agent.id, {
expectedRevision: agent.revision,
enabled: !agent.enabled,
});
if (alive.current) {
setAgents(previous => previous.map(value => (value.id === updated.id ? updated : value)));
}
} catch (cause) {
if (alive.current) {
setWriteError(`${message(cause)} Refresh to verify the saved policy before retrying.`);
setRefresh(value => value + 1);
}
} finally {
writing.current = false;
if (alive.current) {
setPending(false);
setLoading(false);
}
}
}
async function budget(agent: ResearchAgentRecord) {
const current = generation.current;
const request = (budgetRequests.current.get(agent.id) ?? 0) + 1;
budgetRequests.current.set(agent.id, request);
const isCurrent = () =>
alive.current &&
current === generation.current &&
budgetRequests.current.get(agent.id) === request;
try {
const value = await researchAgentsApi.budget(agent.id);
if (isCurrent() && value.agent.id === agent.id) {
setBudgets(previous => ({ ...previous, [agent.id]: value }));
}
} catch (cause) {
if (isCurrent()) {
setError(message(cause));
}
}
}
return (
<div className="space-y-5 text-text-primary">
<Link to="/research" className="text-primary-500">
Back to research
</Link>
<h1 className="text-xl font-semibold">Research agent access</h1>
<p>
Grant research writes to specific projects and experiments on saved canonical backtests.
Research catalog and historical results remain readable. The server freezes each backtest’s
financial policy. Research credentials cannot control paper or live trading.
</p>
{writeError && <p role="alert">{writeError}</p>}
{token && (
<section
aria-label="New research credential"
className="space-y-3 border border-border p-4"
>
<p>
This credential is shown once. Store it in the authorized research client before
dismissing.
</p>
<textarea aria-label="New research token" className={fieldClass} value={token} readOnly />
<button className={actionClass} onClick={() => setToken(null)}>
I have saved the credential
</button>
</section>
)}
{uncertain && (
<section aria-label="Uncertain research credential creation" className="space-y-2">
<p>
The response was incomplete. A credential may have been created, but its token cannot be
recovered. Refresh the saved list and disable any unwanted credential before creating
another.
</p>
<button
className={actionClass}
disabled={pending || loading}
onClick={() => setRefresh(value => value + 1)}
>
Check saved agents
</button>
<button
className={actionClass}
disabled={pending || loading || Boolean(error) || !uncertainListChecked}
onClick={() => {
setUncertain(false);
setWriteError('');
}}
>
I have checked the saved agents
</button>
</section>
)}
<form
onSubmit={event => void create(event)}
className="space-y-3 border border-border rounded p-4"
>
<h2 className="font-semibold">Create research credential</h2>
<fieldset
disabled={loading || pending || uncertain || Boolean(token)}
className="space-y-3"
>
<label className="block">
Agent name
<input
aria-label="Agent name"
className={fieldClass}
value={name}
onChange={event => setName(event.target.value)}
required
/>
</label>
<label className="block">
Allowed project IDs
<textarea
aria-label="Allowed project IDs"
className={fieldClass}
value={projects}
onChange={event => setProjects(event.target.value)}
/>
</label>
<label className="block">
Allowed backtest IDs
<textarea
aria-label="Allowed backtest IDs"
className={fieldClass}
value={backtests}
onChange={event => setBacktests(event.target.value)}
/>
</label>
<p className="text-sm text-text-secondary">
Separate IDs with commas or whitespace. Empty lists grant no access. Backtests must
already have an eligible immutable version, retained dataset and canonical policy.
</p>
{limitFields.map(([key, label]) => (
<label key={key} className="block">
{label}
<input
aria-label={label}
type="number"
min="1"
step="1"
required
className={fieldClass}
value={limits[key]}
onChange={event =>
setLimits(previous => ({ ...previous, [key]: event.target.value }))
}
/>
</label>
))}
<button
type="submit"
className={actionClass}
disabled={loading || pending || uncertain || Boolean(token)}
>
{pending ? 'Saving...' : 'Create credential'}
</button>
</fieldset>
</form>
<section aria-label="Saved research agents" className="space-y-3">
<h2 className="font-semibold">Saved research agents</h2>
<button
className={actionClass}
disabled={pending || loading}
onClick={() => setRefresh(value => value + 1)}
>
Refresh agents
</button>
{loading ? (
<p role="status">Loading research agents...</p>
) : error ? (
<p role="alert">{error}</p>
) : !agents.length ? (
<p>No research agents configured.</p>
) : (
agents.map(agent => (
<article key={agent.id} className="space-y-2 border border-border p-4">
<h3 className="font-semibold">{agent.name}</h3>
<p>
{agent.id} · {agent.enabled ? 'Enabled' : 'Disabled'} · Revision {agent.revision}
</p>
<p>Projects: {agent.allowedProjectIds.join(', ') || 'None'}</p>
<ul>
{agent.grants.map(grant => (
<li key={grant.backtestId}>
<Link to={`/backtests/${grant.backtestId}`} className="text-primary-500">
{grant.backtestId}
</Link>{' '}
· Policy {grant.policyHash}
</li>
))}
</ul>
<dl>
{limitFields.map(([key, label]) => (
<div key={key}>
<dt className="inline">{label}: </dt>
<dd className="inline">{agent.limits[key]}</dd>
</div>
))}
</dl>
{budgets[agent.id] && (
<p role="status">
Active trials: {budgets[agent.id]?.activeTrials}; available slots:{' '}
{budgets[agent.id]?.remainingActiveTrials}
</p>
)}
<button className={actionClass} disabled={pending} onClick={() => void budget(agent)}>
Check budget for {agent.name}
</button>{' '}
<button className={actionClass} disabled={pending} onClick={() => void toggle(agent)}>
{agent.enabled ? 'Disable' : 'Enable'} {agent.name}
</button>
</article>
))
)}
</section>
</div>
);
}

View file

@ -83,6 +83,9 @@ export function ResearchListPage() {
};
return (
<div className="space-y-5 text-text-primary">
<Link to="/research/agents" className="text-primary-500">
Research agent access
</Link>
<div className="flex items-center justify-between">
<h1 className="text-lg font-bold">Research</h1>
<button className={actionClass} onClick={() => setOpen(true)}>

View file

@ -1,2 +1,3 @@
export { ResearchListPage } from './ResearchListPage';
export { ResearchProjectPage } from './ResearchProjectPage';
export { ResearchAgentsPage } from './ResearchAgentsPage';

View file

@ -0,0 +1,79 @@
import { z } from 'zod';
import {
createResearchAgentSchema,
researchAgentBudgetSchema,
researchAgentRecordSchema,
updateResearchAgentSchema,
} from '@stock-bot/stock-config/research-agents';
import { API_BASE_URL, apiFetch } from '@/lib/api';
export class ResearchAgentApiError extends Error {
constructor(
message: string,
readonly status: number
) {
super(message);
}
get uncertain() {
return this.status >= 500 || this.status === 408;
}
}
async function request<T>(path: string, schema: z.ZodType<T>, init?: RequestInit) {
const response = await apiFetch(`${API_BASE_URL}/api/v2/research-agents${path}`, init);
const body: unknown = await response.json().catch(() => null);
if (!response.ok) {
throw new ResearchAgentApiError(
body && typeof body === 'object' && 'error' in body && typeof body.error === 'string'
? body.error
: `Research agent request failed (${response.status})`,
response.status
);
}
return schema.parse(body);
}
const json = (method: string, body: unknown): RequestInit => ({
method,
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body),
});
const record = z.object({ agent: researchAgentRecordSchema }).strict();
export const researchAgentsApi = {
list: (signal?: AbortSignal) =>
request('', z.object({ agents: z.array(researchAgentRecordSchema) }).strict(), { signal }),
create: (input: z.input<typeof createResearchAgentSchema>) =>
request(
'',
record.extend({ token: z.string().min(1) }),
json('POST', createResearchAgentSchema.parse(input))
),
update: async (id: string, input: z.input<typeof updateResearchAgentSchema>) => {
const result = await request(
`/${encodeURIComponent(id)}`,
record,
json('PATCH', updateResearchAgentSchema.parse(input))
);
if (
result.agent.id !== id ||
result.agent.revision !== input.expectedRevision + 1 ||
(input.enabled !== undefined && result.agent.enabled !== input.enabled)
) {
throw new Error('Research agent update identity or revision mismatch');
}
return result;
},
budget: async (id: string, signal?: AbortSignal) => {
const result = await request(`/${encodeURIComponent(id)}/budget`, researchAgentBudgetSchema, {
signal,
});
if (
result.agent.id !== id ||
result.remainingActiveTrials !==
Math.max(0, result.agent.limits.maxActiveTrials - result.activeTrials)
) {
throw new Error('Research agent budget identity or capacity mismatch');
}
return result;
},
};