stock-bot/apps/stock/web-api/src/services/research-agents.service.ts

519 lines
19 KiB
TypeScript

import { createHash, randomBytes, randomUUID } from 'node:crypto';
import type { PoolClient, QueryResultRow } from 'pg';
import { z } from 'zod';
import { requireServices, type IServiceContainer } from '@stock-bot/services';
import {
createResearchAgentSchema,
researchAgentIdSchema,
updateResearchAgentSchema,
type ResearchAgentBudget,
type ResearchAgentRecord,
} from '@stock-bot/stock-config/research-agents';
import { HistoricalDataRequestError, isResearchAgent } from '@stock-bot/types';
import { admitCanonicalRequest } from './canonical-research.service';
import { PREVIEW_RUN_ID } from './experiment-input';
import {
ResearchAgentError,
researchGrantHash,
researchGrantPolicy,
} from './research-agent-budget';
import { StrategyCatalogError } from './strategy-catalog.service';
const tokenHash = (token: string) => createHash('sha256').update(token).digest('hex');
function record(row: QueryResultRow): ResearchAgentRecord {
return {
id: row.id,
name: row.name,
enabled: row.enabled,
revision: row.revision,
allowedProjectIds: row.policy.allowedProjectIds,
grants: row.policy.grants.map(
(grant: { backtestId: string; policyHash: string; allowOwnCandidates?: boolean }) => ({
backtestId: grant.backtestId,
policyHash: grant.policyHash,
...(grant.allowOwnCandidates ? { allowOwnCandidates: true } : {}),
})
),
limits: row.policy.limits,
createdAt: new Date(row.created_at).toISOString(),
updatedAt: new Date(row.updated_at).toISOString(),
};
}
const uuid = '[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}';
const strictUuid = new RegExp(`^${uuid}$`);
function permitted(request: Request): boolean {
const path = new URL(request.url).pathname,
method = request.method;
if (method === 'GET' || method === 'HEAD') {
return (
/^\/api\/v2\/(research-projects|hypotheses|analysis-artifacts|strategies|strategy-versions|experiments|backtests|runs)(\/|$)/.test(
path
) || path === '/api/v2/research-agent/budget'
);
}
if (method === 'PUT') {
return new RegExp(`^/api/v2/research-projects/${uuid}/strategies/${uuid}$`).test(path);
}
if (method !== 'POST') {
return false;
}
return (
path === '/api/v2/strategies' ||
new RegExp(`^/api/v2/strategies/${uuid}/versions$`).test(path) ||
new RegExp(`^/api/v2/strategy-versions/${uuid}/(clone|validate)$`).test(path) ||
new RegExp(`^/api/v2/research-projects/${uuid}/(hypotheses|analysis-artifacts)$`).test(path) ||
new RegExp(`^/api/v2/(hypotheses|analysis-artifacts)/${uuid}/revisions$`).test(path) ||
/^\/api\/v2\/experiments(?:\/(?:preview|cost-sensitivity(?:\/preview)?|validation(?:\/preview)?|walk-forward(?:\/preview)?))?$/.test(
path
) ||
new RegExp(
`^/api/v2/experiments/(?:validation/|walk-forward/)?${uuid}/(?:cancel|select|finalize)$`
).test(path) ||
new RegExp(`^/api/v2/experiments/${uuid}/trials/${uuid}/retry$`).test(path)
);
}
export class ResearchAgentsService {
private readonly database;
constructor(private readonly container: IServiceContainer) {
this.database = requireServices(container, 'postgres').postgres;
}
private async policy(
client: PoolClient,
input: {
allowedProjectIds: string[];
allowedBacktestIds: string[];
allowOwnCandidateBacktestIds?: string[];
limits: ResearchAgentRecord['limits'];
}
) {
if (input.allowOwnCandidateBacktestIds?.some(id => !input.allowedBacktestIds.includes(id))) {
throw new ResearchAgentError(400, 'Candidate opt-ins must be a subset of granted backtests');
}
for (const id of input.allowedProjectIds) {
if (
!(
await client.query(
'SELECT id FROM research_projects WHERE id=$1 AND archived_at IS NULL',
[id]
)
).rows.length
) {
throw new ResearchAgentError(400, 'Choose existing active research projects');
}
}
// Lock every parent before acquiring any family lock; interleaving these can deadlock
// a concurrent admission on another granted template sharing the same family.
const parents = (
await client.query(
'SELECT * FROM backtests WHERE id=ANY($1::uuid[]) ORDER BY id FOR UPDATE',
[input.allowedBacktestIds]
)
).rows;
if (
parents.length !== input.allowedBacktestIds.length ||
parents.some(row => row.archived_at)
) {
throw new ResearchAgentError(400, 'Choose existing active canonical templates');
}
await client.query(
'SELECT id FROM strategies WHERE id IN (SELECT strategy_id FROM strategy_versions WHERE id=ANY($1::uuid[])) ORDER BY id FOR UPDATE',
[parents.map(row => row.strategy_version_id).filter(Boolean)]
);
const grants = [];
for (const row of parents) {
const id = row.id as string;
let request;
try {
request = await admitCanonicalRequest(
client,
this.container,
{
name: row.name,
strategyVersionId: row.strategy_version_id,
strategyParameters: row.strategy_parameters,
symbols: row.symbols,
startDate: row.start_date,
endDate: row.end_date,
initialCapital: Number(row.initial_capital),
config: row.config,
},
id,
PREVIEW_RUN_ID
);
} catch (error) {
if (
!(
error instanceof HistoricalDataRequestError ||
error instanceof StrategyCatalogError ||
error instanceof z.ZodError
)
) {
throw error;
}
throw new ResearchAgentError(
400,
'Agent grants require currently approved canonical templates'
);
}
const policy = researchGrantPolicy(request);
grants.push({
backtestId: id,
policyHash: researchGrantHash(policy),
policy,
...(input.allowOwnCandidateBacktestIds?.includes(id) ? { allowOwnCandidates: true } : {}),
});
}
return { version: 1, allowedProjectIds: input.allowedProjectIds, grants, limits: input.limits };
}
async create(raw: unknown) {
const input = createResearchAgentSchema.parse(raw),
token = `sb-research.${randomBytes(32).toString('base64url')}`;
const agent = await this.database.transaction(async client => {
const policy = await this.policy(client, input);
const row = (
await client.query(
'INSERT INTO research_agents(id,name,token_hash,policy) VALUES($1,$2,$3,$4::jsonb) RETURNING *',
[`agent:${randomUUID()}`, input.name, tokenHash(token), JSON.stringify(policy)]
)
).rows[0];
if (!row) {
throw new Error('Research agent was not created');
}
return record(row);
});
return { agent, token };
}
async list(): Promise<ResearchAgentRecord[]> {
return (
await this.database.query('SELECT * FROM research_agents ORDER BY created_at,id')
).rows.map(record);
}
async update(id: string, raw: unknown): Promise<ResearchAgentRecord> {
researchAgentIdSchema.parse(id);
const input = updateResearchAgentSchema.parse(raw);
return this.database.transaction(async client => {
const old = (await client.query('SELECT * FROM research_agents WHERE id=$1 FOR UPDATE', [id]))
.rows[0];
if (!old) {
throw new ResearchAgentError(404, 'Research principal not found');
}
if (old.revision !== input.expectedRevision) {
throw new ResearchAgentError(
409,
'Research principal policy changed; reload before editing'
);
}
const policy =
input.allowedBacktestIds === undefined
? {
...old.policy,
allowedProjectIds: input.allowedProjectIds ?? old.policy.allowedProjectIds,
limits: input.limits ?? old.policy.limits,
}
: await this.policy(client, {
allowedProjectIds: input.allowedProjectIds ?? old.policy.allowedProjectIds,
allowedBacktestIds: input.allowedBacktestIds,
allowOwnCandidateBacktestIds: input.allowOwnCandidateBacktestIds ?? [],
limits: input.limits ?? old.policy.limits,
});
if (
input.allowedBacktestIds === undefined &&
input.allowOwnCandidateBacktestIds !== undefined
) {
const allowed = new Set(
policy.grants.map((grant: { backtestId: string }) => grant.backtestId)
);
if (input.allowOwnCandidateBacktestIds.some(id => !allowed.has(id))) {
throw new ResearchAgentError(
400,
'Candidate opt-ins must be a subset of granted backtests'
);
}
const candidateOptIns = input.allowOwnCandidateBacktestIds;
policy.grants = policy.grants.map(
(grant: { backtestId: string; allowOwnCandidates?: boolean }) => {
const { allowOwnCandidates: _old, ...frozen } = grant;
return {
...frozen,
...(candidateOptIns.includes(grant.backtestId) ? { allowOwnCandidates: true } : {}),
};
}
);
}
if (input.allowedProjectIds) {
for (const projectId of input.allowedProjectIds) {
if (
!(
await client.query(
'SELECT id FROM research_projects WHERE id=$1 AND archived_at IS NULL',
[projectId]
)
).rows.length
) {
throw new ResearchAgentError(400, 'Choose existing active research projects');
}
}
}
const row = (
await client.query(
'UPDATE research_agents SET name=$2,enabled=$3,policy=$4::jsonb,revision=revision+1,updated_at=NOW() WHERE id=$1 RETURNING *',
[id, input.name ?? old.name, input.enabled ?? old.enabled, JSON.stringify(policy)]
)
).rows[0];
if (!row) {
throw new Error('Research principal update disappeared');
}
return record(row);
});
}
async budget(id: string, allowDisabled = false): Promise<ResearchAgentBudget> {
const row = (
await this.database.query(
`SELECT a.*,(SELECT count(*)::integer FROM runs r WHERE r.research_agent_id=a.id AND r.status IN ('pending','running','paused')) AS active_trials FROM research_agents a WHERE a.id=$1`,
[researchAgentIdSchema.parse(id)]
)
).rows[0];
if (!row || (!allowDisabled && !row.enabled)) {
throw new ResearchAgentError(403, 'Research principal is disabled or unavailable');
}
const agent = record(row),
activeTrials = Number(row.active_trials);
return {
agent,
activeTrials,
remainingActiveTrials: Math.max(0, agent.limits.maxActiveTrials - activeTrials),
};
}
async authenticate(
request: Request
): Promise<{ principal: `agent:${string}` } | Response | undefined> {
const match = /^Bearer (sb-research\.[A-Za-z0-9_-]+)$/i.exec(
request.headers.get('authorization') ?? ''
);
if (!match?.[1]) {
return undefined;
}
const row = (
await this.database.query(
'SELECT id,enabled,policy FROM research_agents WHERE token_hash=$1',
[tokenHash(match[1])]
)
).rows[0];
if (!row?.enabled || !isResearchAgent(row.id)) {
return undefined;
}
const deny = () =>
Response.json(
{ error: 'Research credential does not permit this operation' },
{ status: 403, headers: { 'Cache-Control': 'no-store' } }
);
if (!permitted(request)) {
return deny();
}
const allowedProjectIds = Array.isArray(row.policy?.allowedProjectIds)
? row.policy.allowedProjectIds
.filter((id: unknown): id is string => typeof id === 'string')
.map((id: string) => id.toLowerCase())
: [];
const grantedBacktestIds = Array.isArray(row.policy?.grants)
? row.policy.grants
.map((grant: unknown) =>
grant && typeof grant === 'object' && 'backtestId' in grant
? (grant as { backtestId?: unknown }).backtestId
: undefined
)
.filter((id: unknown): id is string => typeof id === 'string')
.map((id: string) => id.toLowerCase())
: [];
const url = new URL(request.url);
const path = url.pathname;
const project = /^\/api\/v2\/research-projects\/([^/]+)(?:\/|$)/.exec(path);
if (project) {
const projectId = project[1];
if (!projectId || !allowedProjectIds.includes(projectId.toLowerCase())) {
return deny();
}
}
if (request.method === 'GET' || request.method === 'HEAD') {
const narrative = /^\/api\/v2\/(hypotheses|analysis-artifacts)\/([^/]+)(?:\/|$)/.exec(path);
if (narrative) {
const narrativeId = narrative[2];
if (!narrativeId || !strictUuid.test(narrativeId)) {
return deny();
}
const table = narrative[1] === 'hypotheses' ? 'research_hypotheses' : 'analysis_artifacts';
const owned = (
await this.database.query(`SELECT project_id FROM ${table} WHERE id=$1`, [narrativeId])
).rows[0];
if (!owned || !allowedProjectIds.includes(String(owned.project_id).toLowerCase())) {
return deny();
}
}
const backtest = /^\/api\/v2\/backtests\/([^/]+)(?:\/|$)/.exec(path);
if (backtest) {
const backtestId = backtest[1];
if (!backtestId || !grantedBacktestIds.includes(backtestId.toLowerCase())) {
return deny();
}
}
if (path === '/api/v2/experiments/compare') {
const leftIds = url.searchParams.getAll('leftId');
const rightIds = url.searchParams.getAll('rightId');
const leftId = leftIds[0];
const rightId = rightIds[0];
if (
leftIds.length !== 1 ||
rightIds.length !== 1 ||
!leftId ||
!rightId ||
!strictUuid.test(leftId) ||
!strictUuid.test(rightId)
) {
return deny();
}
const uniqueIds = [...new Set([leftId.toLowerCase(), rightId.toLowerCase()])];
const rows = (
await this.database.query(
'SELECT id,submission_principal FROM research_experiments WHERE id=ANY($1::uuid[])',
[uniqueIds]
)
).rows;
if (
rows.length !== uniqueIds.length ||
rows.some(item => item.submission_principal !== row.id)
) {
return deny();
}
} else if (
path === '/api/v2/experiments' ||
path === '/api/v2/experiments/validation' ||
path === '/api/v2/experiments/walk-forward'
) {
const backtestIds = url.searchParams.getAll('backtestId');
if (backtestIds.some(id => !grantedBacktestIds.includes(id.toLowerCase()))) {
return deny();
}
} else {
const experiment =
/^\/api\/v2\/experiments\/(walk-forward\/|validation\/)?([^/]+)(?:\/|$)/.exec(path);
if (experiment) {
const experimentId = experiment[2];
if (!experimentId || !strictUuid.test(experimentId)) {
return deny();
}
const table =
experiment[1] === 'walk-forward/' ? 'research_walk_forwards' : 'research_experiments';
const owned = (
await this.database.query(`SELECT submission_principal FROM ${table} WHERE id=$1`, [
experimentId,
])
).rows[0];
if (owned?.submission_principal !== row.id) {
return deny();
}
}
}
const run = /^\/api\/v2\/runs\/([^/]+)(?:\/|$)/.exec(path);
if (run) {
const runId = run[1];
if (!runId || !strictUuid.test(runId)) {
return deny();
}
const owned = (
await this.database.query('SELECT research_agent_id FROM runs WHERE id=$1', [runId])
).rows[0];
if (owned?.research_agent_id !== row.id) {
return deny();
}
}
const strategy = /^\/api\/v2\/strategies\/([^/]+)(?:\/|$)/.exec(path);
if (strategy) {
const strategyId = strategy[1];
if (!strategyId || !strictUuid.test(strategyId)) {
return deny();
}
const permittedStrategy = (
await this.database.query(
`SELECT 1 FROM strategies s
WHERE s.id=$1 AND (
s.owner_principal=$2
OR EXISTS(SELECT 1 FROM research_project_strategies rps WHERE rps.strategy_id=s.id AND rps.project_id=ANY($3::uuid[]))
OR EXISTS(SELECT 1 FROM strategy_versions sv JOIN backtests b ON b.strategy_version_id=sv.id WHERE sv.strategy_id=s.id AND b.id=ANY($4::uuid[]))
)`,
[strategyId, row.id, allowedProjectIds, grantedBacktestIds]
)
).rows[0];
if (!permittedStrategy) {
return deny();
}
}
const strategyVersion = /^\/api\/v2\/strategy-versions\/([^/]+)(?:\/|$)/.exec(path);
if (strategyVersion) {
const versionId = strategyVersion[1];
if (!versionId || !strictUuid.test(versionId)) {
return deny();
}
const permittedVersion = (
await this.database.query(
`SELECT 1 FROM strategy_versions sv
JOIN strategies s ON s.id=sv.strategy_id
WHERE sv.id=$1 AND (
s.owner_principal=$2
OR EXISTS(SELECT 1 FROM research_project_strategies rps WHERE rps.strategy_id=s.id AND rps.project_id=ANY($3::uuid[]))
OR EXISTS(SELECT 1 FROM strategy_versions sv2 JOIN backtests b ON b.strategy_version_id=sv2.id WHERE sv2.strategy_id=s.id AND b.id=ANY($4::uuid[]))
)`,
[versionId, row.id, allowedProjectIds, grantedBacktestIds]
)
).rows[0];
if (!permittedVersion) {
return deny();
}
}
} else {
const experiment = new RegExp(
`^/api/v2/experiments/(walk-forward/|validation/)?(${uuid})/`
).exec(path);
if (experiment) {
const table =
experiment[1] === 'walk-forward/' ? 'research_walk_forwards' : 'research_experiments';
const owned = (
await this.database.query(`SELECT submission_principal FROM ${table} WHERE id=$1`, [
experiment[2],
])
).rows[0];
if (owned?.submission_principal !== row.id) {
return deny();
}
}
const family = new RegExp(`^/api/v2/strategies/(${uuid})/versions$`).exec(path);
if (
family &&
(
await this.database.query('SELECT owner_principal FROM strategies WHERE id=$1', [
family[1],
])
).rows[0]?.owner_principal !== row.id
) {
return deny();
}
const narrative = new RegExp(
`^/api/v2/(hypotheses|analysis-artifacts)/(${uuid})/revisions$`
).exec(path);
if (narrative) {
const table = narrative[1] === 'hypotheses' ? 'research_hypotheses' : 'analysis_artifacts';
const owned = (
await this.database.query(`SELECT owner_principal,project_id FROM ${table} WHERE id=$1`, [
narrative[2],
])
).rows[0];
if (
owned?.owner_principal !== row.id ||
!allowedProjectIds.includes(String(owned.project_id).toLowerCase())
) {
return deny();
}
}
}
return { principal: row.id };
}
}