UNPKG

@code-yeongyu/senpi

Version:

Coding agent CLI with read, bash, edit, write tools and session management

169 lines • 7.42 kB
import { AsyncLocalStorage } from "node:async_hooks"; const attributionStore = new AsyncLocalStorage(); /** * Monotonic activity counter. Ordering is all the watchdog needs - it samples the mark * on every tick and asks what ran since - so the registry never reads a clock and stays * deterministic under fake timers. */ let sequence = 0; /** Attributed work that is still running, keyed by its sequence number (ascending). */ const openActivities = new Map(); /** Called synchronously when attributed work starts, before it can block the loop. */ const activityStartListeners = new Set(); /** * Subscribe to the start of attributed work (senpi#3738): the loop-lag watchdog slows its tick while the * host is idle and uses this to return to its fast tick before the work that could stall the loop runs. */ export function onSessionActivityStart(listener) { activityStartListeners.add(listener); return () => activityStartListeners.delete(listener); } function notifyActivityStarted() { for (const listener of activityStartListeners) listener(); } /** The most recent synchronous activity that has finished. */ let lastFinished; /** * Run `task` attributed to `attribution`: its async chain reads the attribution from * `AsyncLocalStorage`, and the work stays blamable for as long as it is IN FLIGHT. * * The whole lifetime matters, not just the first synchronous segment: a routed command * almost never blocks the loop before its first await - an extension request, a tool, a * turn all block in a later continuation, by which time a synchronous-only registration * has already been retired (observed on a live host: `no attributed session` for a * 1.7 s stall caused by one session's extension request). */ export function runWithSessionAttribution(attribution, task) { const mark = ++sequence; openActivities.set(mark, attribution); notifyActivityStarted(); const finish = () => { if (!openActivities.delete(mark)) return; lastFinished = { sequence: ++sequence, attribution }; }; let awaited = false; try { const result = attributionStore.run(attribution, task); if (isPromiseLike(result)) { awaited = true; // Settlement of a COPY: the caller still receives (and must handle) the // original rejection - this branch only ends the attribution window. void Promise.resolve(result).then(finish, finish); } return result; } finally { if (!awaited) finish(); } } function isPromiseLike(value) { return typeof value === "object" && value !== null && "then" in value && typeof value.then === "function"; } /** * Open-ended attribution for work that outlives its dispatch, i.e. a tool executing * inside a turn. The span inherits the ambient session id when the caller does not * name one, and stays blamable until the returned disposer runs. */ export function openSessionAttributionSpan(attribution) { const ambient = attributionStore.getStore(); const sessionId = attribution.sessionId ?? ambient?.sessionId; const merged = { ...(sessionId !== undefined ? { sessionId } : {}), ...(attribution.tool !== undefined ? { tool: attribution.tool } : {}), ...(attribution.job !== undefined ? { job: attribution.job } : {}), }; const mark = ++sequence; openActivities.set(mark, merged); notifyActivityStarted(); return () => { if (!openActivities.delete(mark)) return; lastFinished = { sequence: ++sequence, attribution: merged }; }; } /** A job-kind span that inherits the ambient session; it stays blamable until the disposer runs. */ export function openJobSpan(job) { const ambient = attributionStore.getStore(); return openSessionAttributionSpan({ sessionId: ambient?.sessionId, job }); } /** Run `task` as a job of `job`'s kind, attributed for its whole lifetime like a routed command. */ export function runWithJob(job, task) { const ambient = attributionStore.getStore(); return runWithSessionAttribution({ ...(ambient?.sessionId ? { sessionId: ambient.sessionId } : {}), job }, task); } /** One stall line's attribution clause: `sessionId=<id>[ tool=<name>][ job=<kind>]`. */ export function describeAttribution(attribution) { if (attribution?.sessionId === undefined && attribution?.tool === undefined && attribution?.job === undefined) { return "no attributed session"; } const tool = attribution.tool ? ` tool=${attribution.tool}` : ""; const job = attribution.job ? ` job=${attribution.job}` : ""; return `sessionId=${attribution.sessionId ?? "unknown"}${tool}${job}`; } /** Current activity counter; the watchdog samples it once per tick. */ export function sessionActivityMark() { return sequence; } /** * The activity to blame for work that ran after `mark`. A synchronous body that * finished inside the window wins (it is the code that just held the loop); otherwise * the newest open span - a tool mid-execution - takes the blame. Neither means the * stall belongs to the host itself, and the record is emitted without a session. */ export function sessionActivitySince(mark) { if (lastFinished !== undefined && lastFinished.sequence > mark) return lastFinished.attribution; let newest; for (const attribution of openActivities.values()) newest = attribution; return newest; } function toolRecord(record) { if (!("type" in record) || typeof record.type !== "string") return undefined; return { type: record.type, toolCallId: "toolCallId" in record && typeof record.toolCallId === "string" ? record.toolCallId : undefined, toolName: "toolName" in record && typeof record.toolName === "string" ? record.toolName : undefined, }; } /** * Track which tool a session is executing, from the record stream its runtime already * produces. In-process sessions run their tools ON the host loop, so this is where a * blocking tool becomes attributable; worker sessions block their own isolate and * deliberately have no spans here. */ export function createToolAttributionSpans(sessionId) { const spans = new Map(); const closeAll = () => { for (const close of spans.values()) close(); spans.clear(); }; return { closeAll, observe: (record) => { const parsed = toolRecord(record); if (parsed === undefined) return; if (parsed.type === "tool_execution_start" && parsed.toolCallId !== undefined) { spans.get(parsed.toolCallId)?.(); spans.set(parsed.toolCallId, openSessionAttributionSpan({ sessionId, tool: parsed.toolName })); return; } if (parsed.type === "tool_execution_end" && parsed.toolCallId !== undefined) { spans.get(parsed.toolCallId)?.(); spans.delete(parsed.toolCallId); return; } // A settled turn cannot still be inside a tool: release whatever is left, so a // tool whose end record never arrived cannot keep taking the blame forever. if (parsed.type === "agent_settled" || parsed.type === "agent_idle") closeAll(); }, }; } //# sourceMappingURL=session-attribution.js.map