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