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

@ -12,7 +12,7 @@ import {
} from '@/features/experiments';
import { MonitoringPage } from '@/features/monitoring';
import { PipelinePage } from '@/features/pipeline';
import { ResearchListPage, ResearchProjectPage } from '@/features/research';
import { ResearchAgentsPage, ResearchListPage, ResearchProjectPage } from '@/features/research';
import { StrategyDetailPage, StrategyListPage, StrategyVersionPage } from '@/features/strategies';
import { SymbolDetailPage, SymbolsPage } from '@/features/symbols';
import { AuthGate } from './AuthGate';
@ -53,6 +53,7 @@ export function App() {
</Route>
<Route path="research">
<Route index element={<ResearchListPage />} />
<Route path="agents" element={<ResearchAgentsPage />} />
<Route path=":projectId" element={<ResearchProjectPage />} />
</Route>
<Route path="experiments">

View file

@ -3,10 +3,7 @@ import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { Link, useNavigate, useParams } from 'react-router-dom';
import { isCanonicalRunResult } from '@stock-bot/stock-config/canonical-research';
import { SaveFindingDialog } from '@/features/research/components/SaveFindingDialog';
import {
catalogExecutionReason,
supportedLegacyStrategy,
} from '@/features/strategies/components/StrategySelection';
import { catalogExecutionReason } from '@/features/strategies/components/StrategySelection';
import { useWebSocket } from '@/hooks/useWebSocket';
import { ArchiveBacktestDialog } from './components/ArchiveBacktestDialog';
import { BacktestConfiguration } from './components/BacktestConfiguration';
@ -77,9 +74,7 @@ export function BacktestDetailPageV2() {
? runResults
: null;
const catalog = Boolean(backtest?.strategyVersionId) || backtest?.strategy === 'catalog';
const unsupportedLegacy = Boolean(
backtest && !catalog && !supportedLegacyStrategy(backtest.strategy)
);
const unsupportedLegacy = Boolean(backtest && !catalog);
const executionUnavailable = catalog ? !canonicalCapability?.available : unsupportedLegacy;
const canSubmit = (!archived && !executionUnavailable) || hasPendingSubmission;
@ -572,8 +567,8 @@ export function BacktestDetailPageV2() {
)}
{unsupportedLegacy && (
<p role="status" className="mb-4 text-sm text-text-secondary">
This legacy strategy is not supported for new submissions by this form. Its existing
history remains readable.
Legacy execution is retired. Create a catalog backtest to run with retained canonical
inputs. Its existing history remains readable.
</p>
)}
{archived && (

View file

@ -199,9 +199,9 @@ export function BacktestListPageV2() {
}
void loadBacktests();
}}
onCreated={(created, run) => {
onCreated={created => {
setShowCreateDialog(false);
navigate(`/backtests/${created.id}${run ? `/run/${run.id}` : ''}`);
navigate(`/backtests/${created.id}`);
}}
/>
)}

View file

@ -1,7 +1,6 @@
import { XMarkIcon } from '@heroicons/react/24/solid';
import { useEffect, useRef, useState } from 'react';
import {
LegacyStrategySelect,
StrategySelection,
type CatalogSelection,
} from '@/features/strategies/components/StrategySelection';
@ -9,14 +8,14 @@ import {
confirmDiscard,
useUnsavedWarning,
} from '@/features/strategies/components/useUnsavedWarning';
import { backtestApiV2, type Backtest, type Run } from '../services/backtestApiV2';
import { backtestApiV2, type Backtest } from '../services/backtestApiV2';
import type { HistoricalSelection } from '../services/historical-selection';
import { HistoricalDataSelection } from './HistoricalDataSelection';
interface CreateBacktestDialogProps {
initialSelection?: CatalogSelection;
onClose: () => void;
onCreated: (backtest: Backtest, run?: Run) => void;
onCreated: (backtest: Backtest) => void;
}
export function CreateBacktestDialog({
@ -27,14 +26,12 @@ export function CreateBacktestDialog({
const [formData, setFormData] = useState<
HistoricalSelection & {
name: string;
strategy: string;
initialCapital: number;
commission: number;
slippage: number;
}
>({
name: '',
strategy: 'moving-average',
symbols: ['AAPL.US'],
startDate: new Date(Date.now() - 365 * 24 * 60 * 60 * 1000).toISOString().slice(0, 10),
endDate: new Date().toISOString().slice(0, 10),
@ -46,17 +43,14 @@ export function CreateBacktestDialog({
dataSource: 'auto',
});
const [catalogMode, setCatalogMode] = useState(Boolean(initialSelection?.strategyVersionId));
const [selection, setSelection] = useState<CatalogSelection>(initialSelection ?? {});
const [strategyValid, setStrategyValid] = useState(false);
const [edited, setEdited] = useState(false);
useUnsavedWarning(edited);
const [historicalValid, setHistoricalValid] = useState(true);
const [phase, setPhase] = useState<'idle' | 'saving' | 'submitting'>('idle');
const [phase, setPhase] = useState<'idle' | 'saving'>('idle');
const isSubmitting = phase !== 'idle';
const [error, setError] = useState<string | null>(null);
const saved = useRef<Backtest | null>(null);
const submission = useRef<{ key: string; body: { speedMultiplier: null } } | null>(null);
const pending = useRef(false);
const active = useRef(true);
@ -69,23 +63,18 @@ export function CreateBacktestDialog({
const close = () => {
// A list refresh before this write settles could miss the newly saved row.
if (pending.current && !saved.current) {
if (pending.current) {
return;
}
if (!saved.current && !confirmDiscard(edited)) {
if (!confirmDiscard(edited)) {
return;
}
active.current = false;
onClose();
};
const handleSubmit = async (runAfterSave: boolean) => {
if (
pending.current ||
!active.current ||
(!saved.current && (!historicalValid || (catalogMode && !strategyValid))) ||
(runAfterSave && catalogMode)
) {
const handleSubmit = async () => {
if (pending.current || !active.current || !historicalValid || !strategyValid) {
return;
}
@ -95,56 +84,36 @@ export function CreateBacktestDialog({
}
pending.current = true;
setPhase(saved.current ? 'submitting' : 'saving');
setPhase('saving');
setError(null);
try {
if (!saved.current) {
const created = await backtestApiV2.createBacktest({
name: formData.name,
strategy: catalogMode ? 'catalog' : formData.strategy,
...(catalogMode ? selection : {}),
symbols: formData.symbols,
startDate: formData.startDate,
endDate: formData.endDate,
initialCapital: formData.initialCapital,
config: {
commission: formData.commission,
slippage: formData.slippage,
dataFrequency: formData.dataFrequency,
dataSource: formData.dataSource,
datasetHash: formData.datasetHash,
dataPolicy: {
adjustment: formData.priceAdjustment ?? 'raw',
timestamp: formData.dataFrequency === '1d' ? 'utc-session-date' : 'utc-instant',
},
const created = await backtestApiV2.createBacktest({
name: formData.name,
strategy: 'catalog',
...selection,
symbols: formData.symbols,
startDate: formData.startDate,
endDate: formData.endDate,
initialCapital: formData.initialCapital,
config: {
commission: formData.commission,
slippage: formData.slippage,
dataFrequency: formData.dataFrequency,
dataSource: formData.dataSource,
datasetHash: formData.datasetHash,
dataPolicy: {
adjustment: formData.priceAdjustment ?? 'raw',
timestamp: formData.dataFrequency === '1d' ? 'utc-session-date' : 'utc-instant',
},
});
if (!active.current) {
return;
}
saved.current = created;
}
let run: Run | undefined;
if (runAfterSave) {
setPhase('submitting');
submission.current ??= { key: crypto.randomUUID(), body: { speedMultiplier: null } };
run = await backtestApiV2.createRun(
saved.current.id,
submission.current.body,
submission.current.key
);
}
},
});
if (active.current) {
onCreated(saved.current, run);
onCreated(created);
}
} catch (err) {
if (active.current) {
const detail = err instanceof Error ? err.message : 'Please try again.';
setError(
saved.current
? `Backtest saved, but run submission failed. Retry submission to recover the same run. ${detail}`
: `Failed to save backtest. ${detail}`
);
setError(`Failed to save backtest. ${detail}`);
}
} finally {
pending.current = false;
@ -177,12 +146,12 @@ export function CreateBacktestDialog({
<form
onSubmit={e => {
e.preventDefault();
void handleSubmit(saved.current !== null);
void handleSubmit();
}}
className="space-y-6"
onChange={() => setEdited(true)}
>
<fieldset disabled={isSubmitting || saved.current !== null} className="space-y-6">
<fieldset disabled={isSubmitting} className="space-y-6">
<div>
<label className="block text-sm font-medium text-text-secondary mb-2">
Backtest Name
@ -197,41 +166,22 @@ export function CreateBacktestDialog({
/>
</div>
<label className="block text-sm text-text-secondary">
Strategy mode
<select
aria-label="Strategy mode"
value={catalogMode ? 'catalog' : 'legacy'}
onChange={event => {
if (confirmDiscard(Boolean(selection.strategyVersionId))) {
setCatalogMode(event.target.value === 'catalog');
}
}}
className="w-full px-3 py-2 bg-background border border-border rounded-md"
>
<option value="legacy">Legacy strategy</option>
<option value="catalog">Catalog version (save only)</option>
</select>
</label>
{catalogMode ? (
<StrategySelection
value={selection}
onChange={setSelection}
onValidityChange={setStrategyValid}
disabled={isSubmitting || saved.current !== null}
/>
) : (
<LegacyStrategySelect
value={formData.strategy}
onChange={strategy => setFormData(previous => ({ ...previous, strategy }))}
/>
)}
<p className="text-sm text-text-secondary">
Select an immutable strategy version. After saving, configure a retained dataset and
financial policies before running a canonical backtest.
</p>
<StrategySelection
value={selection}
onChange={setSelection}
onValidityChange={setStrategyValid}
disabled={isSubmitting}
/>
<HistoricalDataSelection
value={formData}
onChange={selection => setFormData(previous => ({ ...previous, ...selection }))}
onValidityChange={setHistoricalValid}
disabled={isSubmitting || saved.current !== null}
disabled={isSubmitting}
/>
<div>
@ -295,32 +245,19 @@ export function CreateBacktestDialog({
</button>
<button
type="submit"
disabled={
isSubmitting ||
(!saved.current && (!historicalValid || (catalogMode && !strategyValid)))
}
disabled={isSubmitting || !historicalValid || !strategyValid}
className="px-4 py-2 bg-primary-500 text-white rounded-md text-sm font-medium hover:bg-primary-600 transition-colors"
>
{isSubmitting
? 'Saving / submitting...'
: saved.current
? 'Retry submission'
: 'Save'}
{isSubmitting ? 'Saving...' : 'Save'}
</button>
<button
type="button"
disabled
title="Save first, then configure the retained dataset and financial policies."
className="px-4 py-2 bg-primary-500 text-white rounded-md text-sm font-medium opacity-50"
>
Save and run
</button>
{!saved.current && (
<button
type="button"
disabled={isSubmitting || catalogMode || (!saved.current && !historicalValid)}
onClick={e => {
if (e.currentTarget.form?.reportValidity()) {
void handleSubmit(true);
}
}}
className="px-4 py-2 bg-primary-500 text-white rounded-md text-sm font-medium hover:bg-primary-600 transition-colors disabled:opacity-50"
>
Save and run
</button>
)}
</div>
</form>
</div>

View file

@ -1,9 +1,6 @@
import { useCallback, useEffect, useRef, useState } from 'react';
import type { CanonicalRunCapability } from '@stock-bot/stock-config/canonical-research';
import {
catalogExecutionReason,
supportedLegacyStrategy,
} from '@/features/strategies/components/StrategySelection';
import { catalogExecutionReason } from '@/features/strategies/components/StrategySelection';
import { backtestApiV2, RunResultsUnavailableError } from '../services/backtestApiV2';
import type {
Backtest,
@ -423,30 +420,30 @@ export function useBacktestV2() {
}, []);
const createRun = useCallback(
async (speedMultiplier: number | null = null) => {
async (_speedMultiplier: number | null = null) => {
if (!backtest || backtest.id !== loadedBacktestId.current || submission.current?.pending) {
return undefined;
}
if (backtest.archivedAt && !submission.current) {
setSubmissionError('Restore this archived backtest before starting a new run.');
return undefined;
}
if (catalog && !canonicalCapability?.available && !submission.current) {
setSubmissionError(
capabilityError ?? canonicalCapability?.reason ?? catalogExecutionReason
);
return undefined;
}
if (!catalog && !supportedLegacyStrategy(backtest.strategy) && !submission.current) {
if (!catalog && !submission.current) {
setSubmissionError(
'This legacy strategy is not supported for new submissions by this form.'
'Legacy execution is retired. Create a catalog backtest to run with retained canonical inputs.'
);
return undefined;
}
if (backtest.archivedAt && !submission.current) {
setSubmissionError('Restore this archived backtest before starting a new run.');
return undefined;
}
const intent = (submission.current ??= {
backtestId: backtest.id,
key: crypto.randomUUID(),
body: { speedMultiplier: catalog ? null : speedMultiplier },
body: { speedMultiplier: null },
pending: false,
});
intent.pending = true;

View file

@ -9,6 +9,7 @@ import {
type ChronologicalValidationSummary,
type ValidationResultEvidence,
} from '@stock-bot/stock-config/chronological-validation';
import { researchActorSchema } from '@stock-bot/stock-config/research';
import { canonicalStrategyJson } from '@stock-bot/stock-config/strategy';
import { API_BASE_URL, apiFetch } from '@/lib/api';
import {
@ -49,7 +50,7 @@ const candidate = z.object({
trialKey: hash,
parameters: z.record(z.union([z.string(), z.number().finite(), z.boolean()])),
});
const actor = z.enum(['operator', 'service']);
const actor = researchActorSchema;
const summary = z.object({
id: uuid,
name: z.string().min(1),

View file

@ -20,6 +20,7 @@ import {
type ExperimentSummary,
type ExperimentTrialRetry,
} from '@stock-bot/stock-config/experiments';
import { researchActorSchema } from '@stock-bot/stock-config/research';
import { canonicalStrategyJson } from '@stock-bot/stock-config/strategy';
import { API_BASE_URL, apiFetch } from '@/lib/api';
@ -165,7 +166,7 @@ const retryReceipt = z.object({
pausedAt: z.string().nullable(),
failureUpdatedAt: z.string().min(1),
recordedAt: z.string().min(1),
principal: z.enum(['operator', 'service']),
principal: researchActorSchema,
reviewId: z.string().uuid(),
});
/** Immutable source identity captured when the operator reviews a failed trial. */

View file

@ -1,4 +1,5 @@
import { z } from 'zod';
import { researchActorSchema } from '@stock-bot/stock-config/research';
import { canonicalStrategyJson } from '@stock-bot/stock-config/strategy';
import {
MAX_WALK_FORWARD_RUNS,
@ -173,7 +174,7 @@ const report = z.object({
previewHash: hash,
reportHash: hash,
createdAt: z.string().min(1),
principal: z.enum(['operator', 'service']),
principal: researchActorSchema,
reset: z.literal('initial-capital-empty-positions'),
segments: z
.array(
@ -395,7 +396,7 @@ export const walkForwardApi = {
previewHash: hash,
reportHash: hash,
createdAt: z.string().min(1),
principal: z.enum(['operator', 'service']),
principal: researchActorSchema,
})
.parse(envelope(body, 'receipt'));
const value = parseWalkForwardDetail(envelope(body, 'walkForward')),

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;
},
};