UNPKG

@phren/cli

Version:

Knowledge layer for AI agents - CLI, MCP server, and data layer

80 lines (79 loc) • 4.92 kB
import { provider, bridgeRoot } from "./protocol.js"; import { childAgentTree, runningChildAgents } from "./transcripts.js"; import { readFinalTurn } from "./schedule-watch.js"; import { paneRecord } from "./session-activity.js"; import { turnPhase } from "./turn-records.js"; const CHILD_ACTIVITY_CACHE_MS = 5_000; const CHILD_ACTIVITY_PENDING_MS = 30_000; const childActivityCache = new Map(); export async function childActivity(source, session, record) { const key = `${bridgeRoot()}\0${source}\0${session}`, now = Date.now(), cached = childActivityCache.get(key); const stop = record?.stop; const stopKey = stop ? JSON.stringify([record?.terminal, stop.seq, stop.at, !!stop.tasks]) : ""; // Share pending or settled evidence only for the same Stop. A newer Stop // can arrive in the same millisecond or while a prior lookup is in flight. if (cached && cached.stopKey === stopKey && (cached.pending ? now - cached.startedAt < CHILD_ACTIVITY_PENDING_MS : now - cached.at < CHILD_ACTIVITY_CACHE_MS)) return cached.result; const result = childAgentTree(source, session, 0, new Set(), "local", stop).then(tree => { const running = runningChildAgents(tree); return { runningChildren: running.length, childProviders: [...new Set(running.map(child => child.provider))].sort() }; }); const entry = { at: now, startedAt: now, stopKey, pending: true, result }; // A failure is held for 5 s like an answer, as a backoff, so a missing transcript is not rescanned every tick. const settle = () => { entry.at = Date.now(); entry.pending = false; }; void result.then(settle, settle); childActivityCache.set(key, entry); while (childActivityCache.size > 128) childActivityCache.delete(childActivityCache.keys().next().value); return result; } /** Wait for optional enrichment without holding transcript delivery indefinitely. */ async function bounded(work, ms = 100) { let timer; try { return await Promise.race([work.catch(() => undefined), new Promise(resolve => { timer = setTimeout(() => resolve(undefined), ms); })]); } finally { clearTimeout(timer); } } /** Evidence already in memory must not wait on children, transcripts or dialogs. */ export function availablePaneEvidence(server, pane, session, record, hooks) { const target = { server, pane: String(pane.pane_id), workspace: String(pane.workspace_id), tab: String(pane.tab_id), source: pane.agent, session }; const held = !!(hooks?.approval?.(target) || hooks?.servedQuestion?.(target)); return { paneStatus: pane.agent_status, record, held, dialog: !!hooks?.confirmedTerminalDialog?.(target) }; } const finalReads = new Map(); function finalEvidence(record) { if (record.source === "phren") return Promise.resolve(undefined); const key = `${bridgeRoot()}:${record.source}:${record.session}:${record.stop?.seq}`, cached = finalReads.get(key); if (cached) return cached; const result = readFinalTurn(record.source, record.session).catch(() => undefined); finalReads.set(key, result); void result.then(() => { if (finalReads.get(key) === result) finalReads.delete(key); }); while (finalReads.size > 128) finalReads.delete(finalReads.keys().next().value); return result; } /** Every caller gets the same guarded foreground evidence, with whatever * enrichment is ready inside one bounded window. Late work never mutates it. */ export async function effectivePaneEvidence(server, pane, session, hooks, questions, knownRecord) { const record = knownRecord === undefined ? await bounded(paneRecord(server, pane, session)) : knownRecord ?? undefined; const phase = record ? turnPhase(record) : undefined; const target = { server, pane: String(pane.pane_id), workspace: String(pane.workspace_id), tab: String(pane.tab_id), source: pane.agent, session }; let children, final; const source = provider.safeParse(pane.agent); let question = false; await bounded(Promise.all([ record && phase?.phase === "ended" ? finalEvidence(record).then(value => { final = value; }) : undefined, // A failed lookup leaves children pending without cutting the other reads short. source.success ? childActivity(source.data, session, record).then(value => { children = value; }, () => undefined) : undefined, hooks?.syncTerminalDialog?.(target, ["blocked", "waiting"].includes(String(pane.agent_status)) || phase?.phase === "working"), pane.agent === "codex" ? questions?.pending(target).then(value => { question = !!value?.length; }) : undefined, ])); const available = availablePaneEvidence(server, pane, session, record, hooks); return { ...available, final, children, childrenPending: source.success && children === undefined, runningChildren: children?.runningChildren, held: available.held || question }; }