src/sessions/events.ts
3 KB - 查看原始文件
// Session events: the typed records written to a session log, one JSON object per line.
//
// The log stores more than messages. Turn boundaries, stop reasons, and usage are events too,
// so the log can answer questions later ("which turn crashed?", "what did this session cost?")
// and a restart can tell a finished turn from an interrupted one.
import { z } from 'zod';
import type { BetaMessageParam } from '../core/model.ts';
export const LOG_FORMAT_VERSION = 1;
const Base = z.object({
v: z.literal(LOG_FORMAT_VERSION),
/** ISO timestamp when the event was written. */
ts: z.string(),
});
const Usage = z.object({
modelCalls: z.number(),
inputTokens: z.number(),
outputTokens: z.number(),
cacheReadTokens: z.number(),
cacheWriteTokens: z.number(),
contextTokens: z.number().optional(),
requests: z
.array(
z.object({
model: z.string(),
inputTokens: z.number(),
outputTokens: z.number(),
cacheReadTokens: z.number(),
cacheWriteTokens: z.number(),
}),
)
.optional(),
});
export const SessionEventSchema = z.discriminatedUnion('type', [
Base.extend({
type: z.literal('session_started'),
sessionId: z.string(),
key: z.string(),
}),
Base.extend({
type: z.literal('turn_started'),
turnId: z.string(),
/** Where the user message came from, for example "terminal" (lab 08 adds more). */
channel: z.string(),
}),
Base.extend({
type: z.literal('message'),
turnId: z.string(),
// Messages are stored exactly as sent to or received from the API. We validate only the
// shape we rely on; the SDK types describe the rest.
message: z.custom<BetaMessageParam>(
(value) =>
typeof value === 'object' &&
value !== null &&
['user', 'assistant', 'system'].includes(String((value as { role?: unknown }).role)),
),
}),
Base.extend({
type: z.literal('turn_completed'),
turnId: z.string(),
stop: z.string(),
model: z.string(),
usage: Usage,
}),
Base.extend({
type: z.literal('turn_interrupted'),
turnId: z.string(),
reason: z.string(),
/** Model calls made before the turn stopped: they are billed, so /usage counts them. */
model: z.string().optional(),
usage: Usage.optional(),
}),
// Lab 05: a tool call waits for the owner. The turn that asked ends with stop
// "awaiting_approval"; the tool_use stays unanswered until every request is resolved.
Base.extend({
type: z.literal('approval_requested'),
turnId: z.string(),
approvalId: z.string(),
toolUseId: z.string(),
tool: z.string(),
summary: z.string(),
reason: z.string(),
}),
Base.extend({
type: z.literal('approval_resolved'),
approvalId: z.string(),
decision: z.enum(['approved', 'denied']),
/** Who answered: a channel name, or "system" when a new message replaced the request. */
by: z.string(),
note: z.string().optional(),
}),
]);
export type SessionEvent = z.infer<typeof SessionEventSchema>;
/** Event without the fields the log fills in itself. */
export type NewSessionEvent = SessionEvent extends infer E
? E extends SessionEvent
? Omit<E, 'v' | 'ts'>
: never
: never;