@prismshadow/penguin-library-trace · library/trace/src/trace-service.ts:352

TraceService

component

No JSDoc comment in source yet.

API

@Component()
export class TraceService implements Traces {
  @Use() private readonly paths!: TracePaths;
  @Use() private readonly index!: TraceIndex;
  @Use() private readonly store!: TraceIndexStore;
  @Use() private readonly sessions?: SessionIndex;
  @Use() private readonly sources?: SessionOrigins;
  @Use() private readonly projectConfig?: TracePricing;
  async subagentChildren(projectId: string, agentId: string, sessionId: string): Promise<Array<{ sessionId: string; agentId: string | null; spawnedAt: string }>>;
  async ownedSubagents(parent: {
    projectId: string;
    agentId: string;
    sessionId: string;
    createdAt: string;
  }): Promise<OwnedSubagent[]>;
  async deleteSessionTraces(projectId: string, agentId: string, sessionId: string): Promise<void>;
  async readMessages(projectId: string, agentId: string, sessionId: string): Promise<HistoryMessage[]>;
  async readMessagesPage(projectId: string, agentId: string, sessionId: string, req: MessagesPageRequest): Promise<MessagesPageResult>;
  async readHistoryWindow(projectId: string, agentId: string, sessionId: string, req: MessagesPageRequest | { kind: "full" }): Promise<HistoryWindowRead>;
  async historyTraceFiles(projectId: string, agentId: string, sessionId: string): Promise<HistoryTraceFile[]>;
  async forkSessionTrace(projectId: string, agentId: string, sourceSessionId: string, position: TracePosition): Promise<ForkTraceResult>;
  async contextBreakdown(projectId: string, agentId: string, sessionId: string): Promise<SessionContextParts>;
  async listTraceFiles(projectId: string, agentId: string, sessionId: string): Promise<TraceFileInfo[]>;
  async readEvents(projectId: string, agentId: string, sessionId: string, index: number, offset: number, limit: number): Promise<TraceEventsResponse>;
  async readTraceImage(projectId: string, agentId: string, sessionId: string, fileIndex: number, ordinal: number, slot: number | undefined): Promise<{ mime: string; bytes: Buffer }>;
  async analyze(projectId: string, agentId: string, sessionId: string, index: number): Promise<TraceAnalysisResponse>;
  async analyzeRecords(projectId: string, messages: readonly AmspRecord[]): Promise<TraceAnalysisResponse>;
  async agentTraces(projectId: string, agentId: string, paging?: { offset: number; limit: number } | null, opts: { category?: SessionCategory } = {}): Promise<AgentTracesResponse>;
  async readFileRaw(projectId: string, agentId: string, sessionId: string, index: number): Promise<Buffer>;
  async importTraceFile(projectId: string, agentId: string, content: string): Promise<TraceImportResponse>;
  async importSessions(projectId: string, agentId: string, sessions: readonly ImportedSession[]): Promise<{ imported: number; skipped: string[] }>;
}

Dependencies & Wiring

Extracted from class decorators
implementsinterfaces
@Userequires (6)
paths: TracePaths · index: TraceIndex · store: TraceIndexStore · sessions: SessionIndex · sources: SessionOrigins · projectConfig: TracePricing

Methods (18)

subagentChildren

async subagentChildren(projectId: string, agentId: string, sessionId: string): Promise<Array<{ sessionId: string; agentId: string | null; spawnedAt: string }>>

The direct subagent children of a Session: the ids its Trace's subagent pointer records name, in Trace order, each with the Agent whose Trace directory holds the child (a child may run under another Agent of the Project; null when no Trace of it is indexed) and the time the pointer was recorded. A fork copies its source's records, pointers included, under their own times, so a pointer older than the Session names a child of the Session it was forked from (see session-deletion.ts). Only the pointer records matter, so each shard is scanned as text and only the lines that can hold one are parsed.

@paramprojectIdstring
@paramagentIdstring
@paramsessionIdstring
@returnsPromise<Array<{ sessionId: string; agentId: string | null; spawnedAt: string }>>

ownedSubagents

async ownedSubagents(parent: { projectId: string; agentId: string; sessionId: string; createdAt: string; }): Promise<OwnedSubagent[]>

Direct children across all parent Tasks. The sparse index includes no child conversation bodies.

@paramparent{ projectId: string; agentId: string; sessionId: string; createdAt: string; }
@returnsPromise<OwnedSubagent[]>

deleteSessionTraces

async deleteSessionTraces(projectId: string, agentId: string, sessionId: string): Promise<void>

Deletes all of this Session's Trace files (called when the Session is deleted); the index rows go with them.

@paramprojectIdstring
@paramagentIdstring
@paramsessionIdstring
@returnsPromise<void>

readMessages

async readMessages(projectId: string, agentId: string, sessionId: string): Promise<HistoryMessage[]>

History messages: all index files concatenated in order, with sub-sessions expanded in place.

The parent Trace only records a subagent pointer event at the spawn point (recording just the child Session id; the content lives in the child Session's own Trace). Here the pointer is used to locate the child Trace within the Project, read it recursively, and splice the child messages — tagged with an origin chain — back in at the pointer's position, so that when the session is reopened, the frontend can re-attach the sub-session to the run_subagent tool card via origin (the child Trace's first session_meta, once given an origin, takes the same shape as what's forwarded over the live stream). When expansion succeeds, the pointer event itself is no longer emitted; when the child Trace is missing (deleted), the pointer event is kept so API consumers can still know it existed.

@paramprojectIdstring
@paramagentIdstring
@paramsessionIdstring
@returnsPromise<HistoryMessage[]>

readMessagesPage

async readMessagesPage(projectId: string, agentId: string, sessionId: string, req: MessagesPageRequest): Promise<MessagesPageResult>

Windowed history read (the tailLimit / before forms of GET /messages). The window is a run of whole units — cut points and unit semantics live in message-window.ts — assembled by reading ONLY the shards the window overlaps (plus, once ever per old shard, the prefix-cache backfill above). Subagent pointers are expanded exactly as the full path expands them, but only within the window: children referenced by older windows load when those windows do.

Two limits bound a window: at most limit units, and at most MESSAGES_PAGE_MAX_BYTES of serialized messages, measured with images by reference (the route applies that rewrite after merging the held inputs). The newest unit always joins, however large; a window the budget cut short carries the cursor of its first unit like any other. A child's expanded size is not counted.

@paramprojectIdstring
@paramagentIdstring
@paramsessionIdstring
@paramreqMessagesPageRequest
@returnsPromise<MessagesPageResult>

readHistoryWindow

async readHistoryWindow(projectId: string, agentId: string, sessionId: string, req: MessagesPageRequest | { kind: "full" }): Promise<HistoryWindowRead>

A history window as readMessagesPage reads it (full: the whole transcript, as readMessages does), with the Trace file and ordinal of every record beside it.

@paramprojectIdstring
@paramagentIdstring
@paramsessionIdstring
@paramreqMessagesPageRequest | { kind: "full" }
@returnsPromise<HistoryWindowRead>

historyTraceFiles

async historyTraceFiles(projectId: string, agentId: string, sessionId: string): Promise<HistoryTraceFile[]>

Every Trace file of the Session and of its descendants (subagent children, recursively, by the same depth and cycle rules the history expansion follows), with their line offsets.

@paramprojectIdstring
@paramagentIdstring
@paramsessionIdstring
@returnsPromise<HistoryTraceFile[]>

forkSessionTrace

async forkSessionTrace(projectId: string, agentId: string, sourceSessionId: string, position: TracePosition): Promise<ForkTraceResult>

Clone a source Session through one completed root-assistant reply. The supplied position names the reply record itself; this method validates it against raw Trace structure and chooses the exclusive cut after the request's closing records but before a later Task or compaction. Earlier shards stay intact so the fork renders the same history, while core resumes from the selected shard exactly as it would after a restart.

@paramprojectIdstring
@paramagentIdstring
@paramsourceSessionIdstring
@parampositionTracePosition
@returnsPromise<ForkTraceResult>

contextBreakdown

async contextBreakdown(projectId: string, agentId: string, sessionId: string): Promise<SessionContextParts>

Composition of the Session's current model context, read from its newest Trace shard — one shard is one complete context (see context-breakdown.ts). A Session with no Trace yet answers with zeros rather than a 404: "nothing in the context" is a true statement about it, and the caller is a display that would have to invent the same answer.

@paramprojectIdstring
@paramagentIdstring
@paramsessionIdstring
@returnsPromise<SessionContextParts>

listTraceFiles

async listTraceFiles(projectId: string, agentId: string, sessionId: string): Promise<TraceFileInfo[]>

List of Trace files (index / date / size / mtime).

@paramprojectIdstring
@paramagentIdstring
@paramsessionIdstring
@returnsPromise<TraceFileInfo[]>

readEvents

async readEvents(projectId: string, agentId: string, sessionId: string, index: number, offset: number, limit: number): Promise<TraceEventsResponse>

Reads records [offset, offset + limit) of the Trace file at the given index, in the tolerant reader's ordinals. Served from the file's line index: one ranged read per page, not a parse of the whole file.

@paramprojectIdstring
@paramagentIdstring
@paramsessionIdstring
@paramindexnumber
@paramoffsetnumber
@paramlimitnumber
@returnsPromise<TraceEventsResponse>

readTraceImage

async readTraceImage(projectId: string, agentId: string, sessionId: string, fileIndex: number, ordinal: number, slot: number | undefined): Promise<{ mime: string; bytes: Buffer }>

One image of one Trace record, decoded: the image_url of the record at (fileIndex, ordinal), or its tool output's images[slot]. This is what a windowed history page's image URL names (trace-images.ts). 404 trace_image_not_found when the file, the record or the slot holds no image the route serves.

@paramprojectIdstring
@paramagentIdstring
@paramsessionIdstring
@paramfileIndexnumber
@paramordinalnumber
@paramslotnumber | undefined
@returnsPromise<{ mime: string; bytes: Buffer }>

analyze

async analyze(projectId: string, agentId: string, sessionId: string, index: number): Promise<TraceAnalysisResponse>

Performance analysis: derived from a single Trace file.

@paramprojectIdstring
@paramagentIdstring
@paramsessionIdstring
@paramindexnumber
@returnsPromise<TraceAnalysisResponse>

analyzeRecords

async analyzeRecords(projectId: string, messages: readonly AmspRecord[]): Promise<TraceAnalysisResponse>

The analysis of one Trace file's records, however they were read (Traces.analyzeRecords).

@paramprojectIdstring
@parammessagesreadonly AmspRecord[]
@returnsPromise<TraceAnalysisResponse>

agentTraces

async agentTraces(projectId: string, agentId: string, paging?: { offset: number; limit: number } | null, opts: { category?: SessionCategory } = {}): Promise<AgentTracesResponse>

Agent-level browsing, served from the trace-file index (one mtime-gated reconcile, then pure DB — no directory walks, no head-reads). Without paging: the legacy full drill-down (newest first: Agent -> date -> Session -> Trace files; sizes are the index's last observed values). With paging: session-group-centric — Sessions ordered by id descending (ids embed a timestamp, so that is reverse chronological), optionally filtered to one sidebar category — every Session is listed whichever client created it — and only the returned slice gets per-file fs.stat for fresh sizes (written back to the index).

@paramprojectIdstring
@paramagentIdstring
@parampaging?{ offset: number; limit: number } | null
@paramopts?{ category?: SessionCategory }
@returnsPromise<AgentTracesResponse>

readFileRaw

async readFileRaw(projectId: string, agentId: string, sessionId: string, index: number): Promise<Buffer>

Raw bytes of the Trace file at the given index (export/download: the file is served verbatim).

@paramprojectIdstring
@paramagentIdstring
@paramsessionIdstring
@paramindexnumber
@returnsPromise<Buffer>

importTraceFile

async importTraceFile(projectId: string, agentId: string, content: string): Promise<TraceImportResponse>

Imports an uploaded Trace file (raw JSONL content). Validates the content itself — parseable JSONL whose first record is a session_meta carrying a filename-safe session_id (400 invalid_trace otherwise) — then writes it under the Agent's traces directory as a new Session: a session id the Agent already has is rejected with 409 trace_session_exists (splicing a further index into an existing Session would corrupt its concatenated transcript, silently become its resume point, and could collide with a live Writer's rotation), so the imported file is always index 1. The date dir comes from the first record's timestamp (falling back to now), formatted as a local date — the same convention as core's Trace Writer — so an export → import round-trip lands in the same date dir on non-UTC servers.

@paramprojectIdstring
@paramagentIdstring
@paramcontentstring
@returnsPromise<TraceImportResponse>

importSessions

async importSessions(projectId: string, agentId: string, sessions: readonly ImportedSession[]): Promise<{ imported: number; skipped: string[] }>

Lands Sessions' Trace files in the Agent's traces// under their own indexes and registers each once as a Session of this Agent. A Session id is the identity everywhere — the sessions table keys on it, the frontend dedupes rows by it, /chat/:sessionId routes by it — so one whose id is anywhere in the install is skipped: a second copy would be a Session nothing could own.

@paramprojectIdstring
@paramagentIdstring
@paramsessionsreadonly ImportedSession[]
@returnsPromise<{ imported: number; skipped: string[] }>