src/sessions/session.ts
10 KB - Открыть исходный файл
// A session: one conversation, backed by one append-only event log.
//
// The log is the source of truth. The message list sent to the model is rebuilt from it on
// every load, so a restart picks up exactly where the conversation stopped.
import type {
BetaMessageParam,
BetaToolResultBlockParam,
} from '@anthropic-ai/sdk/resources/beta/messages/messages';
import { mergeConsecutiveUserMessages } from '../core/messages.ts';
import { randomBytes } from 'node:crypto';
import type { PendingApproval, TurnStop, TurnUsage } from '../core/turn-loop.ts';
import { EventLog } from './event-log.ts';
import type { SessionEvent } from './events.ts';
export interface ApprovalRequest extends PendingApproval {
approvalId: string;
turnId: string;
}
export interface RecoveryReport {
/** A torn last line was closed off so new events start on a fresh line. */
sealedTornLine: boolean;
/** Lines that could not be read. */
skippedLines: number;
/** Turn that was running when the process stopped, if any. */
interruptedTurn?: string;
/** Tool calls from that turn that never got a result; they now have error results. */
closedToolCalls: number;
}
export class Session {
readonly key: string;
readonly id: string;
private readonly log: EventLog;
private events: SessionEvent[];
private constructor(key: string, id: string, log: EventLog, events: SessionEvent[]) {
this.key = key;
this.id = id;
this.log = log;
this.events = events;
}
/** Opens (or creates) a session log and repairs anything a crash left behind. */
static async open(
key: string,
id: string,
file: string,
clock?: () => Date,
): Promise<{ session: Session; recovery: RecoveryReport }> {
const log = new EventLog(file, clock);
const sealedTornLine = await log.sealTornTail();
const { events, skipped } = await log.read();
const session = new Session(key, id, log, events);
if (events.length === 0) {
await session.write({ type: 'session_started', sessionId: id, key });
}
const recovery = await session.recover();
return {
session,
recovery: { ...recovery, sealedTornLine, skippedLines: skipped.length },
};
}
/**
* Reads a session without changing it: no torn-tail sealing, no session_started event, no
* recovery. For readers (`steward show`, `steward usage`, the pending-approvals list) that must
* not touch a log another task may be writing right now. Do not write through it.
*/
static async peek(key: string, id: string, file: string, clock?: () => Date): Promise<Session> {
const log = new EventLog(file, clock);
const { events } = await log.read();
return new Session(key, id, log, events);
}
/** All events, oldest first (a copy). */
history(): SessionEvent[] {
return [...this.events];
}
/**
* The conversation as the API expects it, rebuilt from the log.
*
* Back-to-back user messages (left by an interrupted turn) are merged into one; see
* core/messages.ts.
*/
messages(): BetaMessageParam[] {
const stored = this.events.flatMap((event) =>
event.type === 'message' ? [event.message] : [],
);
return mergeConsecutiveUserMessages(stored);
}
async startTurn(channel: string): Promise<string> {
const turns = this.events.filter((e) => e.type === 'turn_started').length;
const turnId = `turn-${String(turns + 1).padStart(4, '0')}`;
await this.write({ type: 'turn_started', turnId, channel });
return turnId;
}
async addMessage(turnId: string, message: BetaMessageParam): Promise<void> {
await this.write({ type: 'message', turnId, message });
}
async completeTurn(
turnId: string,
result: { stop: TurnStop; model: string; usage: TurnUsage },
): Promise<void> {
await this.write({ type: 'turn_completed', turnId, ...result });
}
/**
* Ends a turn that did not finish (an error, Ctrl+C, or a crash found at startup). Nothing is
* deleted: tool calls that never got a result get an error result, then a turn_interrupted
* event closes the turn. `spent` is what the model calls made before the stop used: they are
* billed, so the event keeps them for /usage. Returns how many tool calls were closed.
*/
async interruptTurn(
turnId: string,
reason: string,
spent?: { model: string; usage: TurnUsage },
): Promise<number> {
const unanswered = unansweredToolCalls(this.messages());
if (unanswered.length > 0) {
const results: BetaToolResultBlockParam[] = unanswered.map((id) => ({
type: 'tool_result',
tool_use_id: id,
is_error: true,
content: 'Interrupted: the assistant stopped before this tool finished. It did not run.',
}));
await this.write({ type: 'message', turnId, message: { role: 'user', content: results } });
// Any approval still waiting for one of these calls is now moot: the call has a result.
for (const request of this.pendingApprovals()) {
if (unanswered.includes(request.toolUseId)) {
await this.resolveApproval(request.approvalId, 'denied', 'system', 'turn interrupted');
}
}
}
await this.write({ type: 'turn_interrupted', turnId, reason, ...spent });
return unanswered.length;
}
/**
* Total usage of all turns that used the model: completed turns, and interrupted turns that
* made model calls before they stopped. contextTokens is the size of the latest request.
*/
usage(): TurnUsage {
const total = {
modelCalls: 0,
inputTokens: 0,
outputTokens: 0,
cacheReadTokens: 0,
cacheWriteTokens: 0,
contextTokens: 0,
};
for (const { usage } of this.billedTurns()) {
total.modelCalls += usage.modelCalls;
total.inputTokens += usage.inputTokens;
total.outputTokens += usage.outputTokens;
total.cacheReadTokens += usage.cacheReadTokens;
total.cacheWriteTokens += usage.cacheWriteTokens;
if (usage.contextTokens) total.contextTokens = usage.contextTokens;
}
return total;
}
/**
* Turns that used the model, with the model that ran them, for cost reports (lab 03): every
* completed turn, plus interrupted turns that recorded the calls they made.
*/
billedTurns(): { model: string; usage: TurnUsage }[] {
return this.events.flatMap((e) => {
if (e.type === 'turn_completed') return [{ model: e.model, usage: e.usage }];
if (e.type === 'turn_interrupted' && e.model && e.usage) {
return [{ model: e.model, usage: e.usage }];
}
return [];
});
}
// ----- Approvals (lab 05) -----
/** Records tool calls that wait for the owner. Returns them with their approval ids. */
async requestApprovals(
turnId: string,
pending: readonly PendingApproval[],
): Promise<ApprovalRequest[]> {
const requests: ApprovalRequest[] = [];
for (const p of pending) {
const approvalId = this.newApprovalId();
await this.write({ type: 'approval_requested', turnId, approvalId, ...p });
requests.push({ approvalId, turnId, ...p });
}
return requests;
}
/** Approval requests that have no answer yet, oldest first. */
pendingApprovals(): ApprovalRequest[] {
const resolved = new Set(
this.events.flatMap((e) => (e.type === 'approval_resolved' ? [e.approvalId] : [])),
);
return this.events.flatMap((e) =>
e.type === 'approval_requested' && !resolved.has(e.approvalId)
? [
{
approvalId: e.approvalId,
turnId: e.turnId,
toolUseId: e.toolUseId,
tool: e.tool,
summary: e.summary,
reason: e.reason,
},
]
: [],
);
}
/** All requests made by one turn, with the answer each one got (if any). */
approvalsForTurn(turnId: string): (ApprovalRequest & { decision?: 'approved' | 'denied' })[] {
const answers = new Map<string, 'approved' | 'denied'>();
for (const e of this.events) {
if (e.type === 'approval_resolved') answers.set(e.approvalId, e.decision);
}
return this.events.flatMap((e) =>
e.type === 'approval_requested' && e.turnId === turnId
? [
{
approvalId: e.approvalId,
turnId: e.turnId,
toolUseId: e.toolUseId,
tool: e.tool,
summary: e.summary,
reason: e.reason,
decision: answers.get(e.approvalId),
},
]
: [],
);
}
async resolveApproval(
approvalId: string,
decision: 'approved' | 'denied',
by: string,
note?: string,
): Promise<void> {
await this.write({
type: 'approval_resolved',
approvalId,
decision,
by,
...(note ? { note } : {}),
});
}
private newApprovalId(): string {
const used = new Set(
this.events.flatMap((e) => (e.type === 'approval_requested' ? [e.approvalId] : [])),
);
for (;;) {
const id = randomBytes(2).toString('hex');
if (!used.has(id)) return id;
}
}
private async write(event: Parameters<EventLog['append']>[0]): Promise<void> {
const written = await this.log.append(event);
this.events.push(written);
}
/** Closes a turn that was still running when the process stopped. */
private async recover(): Promise<Omit<RecoveryReport, 'sealedTornLine' | 'skippedLines'>> {
const open = findOpenTurn(this.events);
if (!open) return { closedToolCalls: 0 };
const closedToolCalls = await this.interruptTurn(
open,
'the process stopped before the turn finished',
);
return { interruptedTurn: open, closedToolCalls };
}
}
function findOpenTurn(events: SessionEvent[]): string | undefined {
const open = new Set<string>();
for (const event of events) {
if (event.type === 'turn_started') open.add(event.turnId);
if (event.type === 'turn_completed' || event.type === 'turn_interrupted') {
open.delete(event.turnId);
}
}
return [...open].at(-1);
}
/** tool_use ids in the last assistant message that have no tool_result after them. */
function unansweredToolCalls(messages: BetaMessageParam[]): string[] {
const last = messages.at(-1);
if (!last || last.role !== 'assistant' || typeof last.content === 'string') return [];
return last.content.flatMap((block) => (block.type === 'tool_use' ? [block.id] : []));
}