// PEP-48: who is acting — a person (and through which channel), an agent, or Peppa itself. // Carried in AsyncLocalStorage, so the few functions that write events stamp the author // without threading it through every call (moveTask → startSession → launch → event). import { AsyncLocalStorage } from "node:async_hooks"; import type { actorChannels, actorKinds } from "@peppa/db"; export type ActorKind = (typeof actorKinds)[number]; export type ActorChannel = (typeof actorChannels)[number]; export interface Actor { kind: ActorKind; userId?: number | null; channel?: ActorChannel | null; /** OAuth client of the remote MCP (PEP-8). */ clientId?: string | null; } const store = new AsyncLocalStorage(); let fallback: Actor | null = null; /** Runs `fn` with this actor (bot handlers, tests). */ export function runAsActor(actor: Actor, fn: () => T): T { return store.run(actor, fn); } /** * Sets the actor for the rest of the current async context. Call it synchronously in the * body of a request handler / server action (not inside an awaited helper), e.g. * `const user = asWebActor(await requireUser())`. */ export function enterActor(actor: Actor): void { store.enterWith(actor); } /** Process-wide default (agent MCP server, hook, watchdog, CLI). */ export function setDefaultActor(actor: Actor | null): void { fallback = actor; } export function currentActor(): Actor | null { return store.getStore() ?? fallback; } /** Event columns for the current actor; without one: the session's agent, else Peppa itself. */ export function actorColumns(sessionId?: number | null) { const a = currentActor() ?? (sessionId ? { kind: "agent" as const } : { kind: "system" as const }); return { actorKind: a.kind, actorUserId: a.userId ?? null, actorChannel: a.channel ?? null, actorClientId: a.clientId ?? null }; }