okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221Trial2 merge f-0291-pr-nv (97b3d614f)1306424be

main
2.1 KiB32 linesraw
1import type { SessionAgent } from './types';
2
3const statuses = new Set(['working', 'completed', 'failed', 'queued', 'cancelled']);
4const metric = (value: unknown, fallback = 0) => typeof value === 'number' && Number.isFinite(value) && value >= 0 ? value : fallback;
5
6/** Merge partial agent frames without replacing other agents or their readings. */
7export function updateAgent(agents: SessionAgent[], frame: unknown, now = Date.now()): SessionAgent[] {
8  if (!frame || typeof frame !== 'object') return agents;
9  const next = frame as Record<string, unknown>;
10  if (typeof next.id !== 'string' || !next.id.trim()) return agents;
11  const previous = agents.find(a => a.id === next.id);
12  const at = metric(next.updatedAt, now);
13  if (previous?.updatedAt && at < previous.updatedAt) return agents;
14  const previousDuration = (previous?.durationMs ?? 0) + (previous?.status === 'working' && previous.updatedAt ? Math.max(0, at - previous.updatedAt) : 0);
15  const agent: SessionAgent = {
16    id: next.id,
17    name: typeof next.name === 'string' ? next.name : previous?.name ?? 'Subagent',
18    description: typeof next.description === 'string' ? next.description : previous?.description ?? '',
19    status: statuses.has(String(next.status)) ? next.status as SessionAgent['status'] : previous?.status ?? 'queued',
20    durationMs: metric(next.durationMs, previousDuration),
21    tokens: metric(next.tokens, previous?.tokens),
22    updatedAt: at,
23  };
24  return previous ? agents.map(a => a.id === agent.id ? agent : a) : [...agents, agent];
25}
26
27export const runningAgents = (agents: SessionAgent[]) => agents.filter(a => a.status === 'working').length;
28
29/** A page that was closed or reloaded holds no live helper: a saved row still "working" is shown as stopped until a newer frame says otherwise
30 *  (updateAgent takes any frame newer than the row's own time, so a helper that really runs comes back by itself). #4218. */
31export const settleAgents = (agents: SessionAgent[] | undefined): SessionAgent[] | undefined =>
32  agents?.some(a => a.status === 'working') ? agents.map(a => a.status === 'working' ? { ...a, status: 'cancelled' as const } : a) : agents;