peppa/packages/core/src/actor.ts
Асель 14916079bc PEP-5/43/47/48: usage and limits, story budgets, factory metrics, audit journal
- PEP-5: statusLine hook (cost, context, 5h/7d limit windows), transcript tokens,
  sessions.usage, usage strip over every page, runner usage, bot /status, MCP get_usage
- PEP-43: project/story budgets in settings, watchdog pause (Escape, question to the PM:
  extend x2 / remove limit / stop), start/resume guard, budget on the story card
- PEP-47: project metrics tab (cycle time, first pass, review returns, questions, runner
  hours, PM wait, limits, spend by week/agent/epic), MCP get_metrics
- PEP-48: event authors (actor columns, AsyncLocalStorage context), question_answered,
  /journal for superadmins, project journal tab, authors in the story feed
- Migration 0007_usage_audit; OpenSpec changes archived

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 06:52:13 +05:00

49 lines
1.8 KiB
TypeScript

// 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<Actor>();
let fallback: Actor | null = null;
/** Runs `fn` with this actor (bot handlers, tests). */
export function runAsActor<T>(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 };
}