/** * Turn reporter: one activity record per finished conversation round. * * Contract with the cloud service (`POST /activity/turn`): * - exactly six fields; any extra key is rejected with 400, * - `started_at` / `completed_at` are epoch-millisecond integers, * `completed_at >= started_at` and not more than 5 minutes in the future, * - `turn_id` is idempotent, so retries never double-count a round. * * Only metadata leaves the process. Prompt text and tool output are never part * of a report — the payload builder cannot see them. */ import type { CloudClient, SummaryMessage, SummaryPayload, TurnPayload } from './api.ts' import { describeError } from './api.ts' import type { SessionEventLike, SessionLike } from './context-types.ts' /** The three statuses the service accepts; only `completed` feeds the heatmap. */ export type TurnStatus = 'completed' | 'failed' | 'cancelled' /** One finished report, kept for the status card. */ export interface ReportRecord { turnId: string conversationId: string status: TurnStatus startedAt: number completedAt: number at: number /** `recorded` (201), `duplicate` (200), `failed`, or `queued` (waiting for retry). */ outcome: 'recorded' | 'duplicate' | 'failed' | 'queued' | 'skipped' httpStatus?: number error?: string } /** Counters + recent history exposed by `GET /dsh-brain/status`. */ export interface ReporterSnapshot { attempted: number recorded: number duplicate: number failed: number skipped: number queued: number summaryAttempted?: number summaryStaged?: number summaryFailed?: number lastSummaryError?: string lastSentAt?: number lastError?: string recent: ReportRecord[] } /** * Everything one outbound request needs, frozen at request start. Requests and * queued retries carry the context they began with: a settings change * mid-flight cannot redirect or re-attribute an in-progress record. */ export interface ReporterConnection { baseUrl: string activityToken: string summaryToken: string timeoutMs: number } /** Collaborators the reporter needs. */ export interface ReporterOptions { /** Client bound to one pinned connection context. */ clientFor?: (context: ReporterConnection) => CloudClient /** Legacy single client; only safe for tests and single-connection use. */ client?: CloudClient /** Effective settings (never a token). */ settings: () => { enabled: boolean; clientId: string } /** Activity token, or empty when unconfigured. */ activityToken: () => string /** Effective summary settings (never a token). */ summary: () => { enabled: boolean; maxChars: number } /** summary:write token, or empty when summaries are not configured. */ summaryToken: () => string /** Current service endpoint, used to bind queues and buffers to one account. */ baseUrl?: () => string /** Per-request timeout, mirrored into pinned contexts. */ timeoutMs?: () => number /** Log sink for operator-visible diagnostics. */ log: (message: string) => void } /** Normalize an event timestamp (ms epoch or ISO string) into epoch ms. */ export function toEpochMs(value: unknown): number | undefined { if (typeof value === 'number' && Number.isFinite(value)) { // Accept seconds as well: anything below ~2001 in ms is almost certainly seconds. return value < 1e11 ? Math.round(value * 1000) : Math.round(value) } if (typeof value === 'string' && value.trim() !== '') { const parsed = Date.parse(value) return Number.isNaN(parsed) ? undefined : parsed } return undefined } /** * Map a DSH `TurnEndReason` onto a reportable status. * * `forked` is not a real completion: the child session starts a fresh turn, and * counting the fork would inflate the heatmap with rounds the user never ran. */ export function statusForReason(reason: unknown): TurnStatus | null { const kind = typeof reason === 'string' ? reason : reason !== null && typeof reason === 'object' ? (reason as { kind?: unknown }).kind : undefined if (typeof kind !== 'string') return 'completed' switch (kind) { case 'completed': return 'completed' case 'aborted': case 'interrupted': case 'blocked': return 'cancelled' case 'error': case 'max-tokens': return 'failed' case 'forked': return null default: return 'completed' } } /** Extract the numeric turn id from a `turn/start` or `turn/end` payload. */ export function turnOf(data: Record | undefined): number | undefined { if (data === undefined) return undefined const value = data.turn if (typeof value === 'number' && Number.isFinite(value)) return value if (typeof value === 'string' && value.trim() !== '' && Number.isFinite(Number(value))) return Number(value) return undefined } /** Conversation (session) id, tolerating both `id` and `sessionId` shapes. */ export function conversationIdOf(session: SessionLike | undefined): string | undefined { if (session === undefined) return undefined const value = session.id ?? session.sessionId return typeof value === 'string' && value !== '' ? value : undefined } /** Text pulled out of one `user/message` or `assistant/message` payload. */ export function textOf(value: unknown, depth = 0): string | undefined { if (depth > 5) return undefined if (typeof value === 'string') return value.trim() === '' ? undefined : value if (Array.isArray(value)) { const parts: string[] = [] for (const item of value) { if (item !== null && typeof item === 'object') { const part = item as Record // Tool calls/results are never summarized: they can carry files and secrets. if (part.type === 'tool_use' || part.type === 'tool_result' || part.type === 'image') continue if (part.type === 'text' && typeof part.text === 'string') { parts.push(part.text) continue } } const nested = textOf(item, depth + 1) if (nested !== undefined) parts.push(nested) } return parts.length === 0 ? undefined : parts.join('\n') } if (value === null || typeof value !== 'object') return undefined const record = value as Record for (const key of ['text', 'message', 'content', 'body']) { const nested = textOf(record[key], depth + 1) if (nested !== undefined) return nested } return undefined } /** Local redaction: a summary must not carry credentials to the cloud. */ const REDACTIONS: [RegExp, string][] = [ [/-----BEGIN [A-Z ]+-----[\s\S]*?-----END [A-Z ]+-----/g, '[已脱敏:私钥]'], [/\b(sk|ghp|gho|ghs|xox[abprs]|cmt|cmr)_[A-Za-z0-9_-]{12,}/g, '[已脱敏:令牌]'], [/\bBearer\s+[A-Za-z0-9._-]{16,}/gi, 'Bearer [已脱敏]'], [/\beyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}/g, '[已脱敏:JWT]'], [/((?:password|passwd|pwd|secret|api[_-]?key|access[_-]?token)\s*[:=]\s*)[^\s,;]{6,}/gi, '$1[已脱敏]'], ] export function redactSecrets(text: string): string { let out = text for (const [pattern, replacement] of REDACTIONS) out = out.replace(pattern, replacement) return out } /** One buffered message, tagged with the turn it belongs to when known. */ interface BufferedMessage extends SummaryMessage { turn?: number } /** * One conversation's summary buffer, owned by the connection scope that * collected it. A scope change mid-conversation drops the old text: it must * never be handed to the new account. */ interface TranscriptBuffer { /** `baseUrl|summaryToken` the text was collected under. */ scope: string messages: BufferedMessage[] } /** A queued retry, bound to the account+endpoint that produced it. */ interface QueuedReport { payload: TurnPayload /** `baseUrl|token` of the account that enqueued it; a mismatch drops it. */ scope: string } /** * Tracks open turns and reports each finished one. * * Reporting never blocks the agent loop: a failed POST is queued and retried by * {@link flush}, and a service outage only shows up in the status card. */ /** A queued report is retried at most this many times before being dropped. */ const MAX_RETRY_ATTEMPTS = 5 /** Conversations kept in the summary buffer; the oldest is evicted beyond this. */ const MAX_CONVERSATIONS = 50 export class Reporter { private readonly startedAt = new Map() private readonly queue: QueuedReport[] = [] private readonly retries = new Map() private readonly recent: ReportRecord[] = [] private attempted = 0 private recorded = 0 private duplicate = 0 private failed = 0 private skipped = 0 private lastSentAt: number | undefined private lastError: string | undefined private draining = false /** Redacted message text per conversation, consumed at turn/end. */ private readonly transcripts = new Map() private summaryAttempted = 0 private summaryStaged = 0 private summaryFailed = 0 private lastSummaryError: string | undefined constructor(private readonly options: ReporterOptions) {} /** Record a turn start so its duration can be reported later. */ handleStart(session: SessionLike | undefined, event: SessionEventLike): void { const conversationId = conversationIdOf(session) const turn = turnOf(event.data) if (conversationId === undefined || turn === undefined) return const at = toEpochMs(event.time) ?? Date.now() this.startedAt.set(`${conversationId}:${turn}`, at) // Bound the map: a session that never ends must not leak forever. if (this.startedAt.size > 500) { const oldest = this.startedAt.keys().next() if (oldest.done !== true) this.startedAt.delete(oldest.value) } } /** Handle any `session/event`; message, turn and session lifecycle events matter. */ handleEvent(session: SessionLike | undefined, event: SessionEventLike): void { if (event === null || typeof event !== 'object') return if (event.type === 'user/message' || event.type === 'assistant/message') { this.collect(session, event) return } if (event.type === 'turn/start') { this.handleStart(session, event) return } if (event.type === 'session/end' || event.type === 'session/close' || event.type === 'session/closed' || event.type === 'session/terminated') { // A session that ends without a turn/end must not leave transcript text // (or start timestamps) behind for a later session with the same id. this.releaseConversation(conversationIdOf(session)) return } if (event.type !== 'turn/end') return this.handleEnd(session, event) } /** Drop every buffered turn and open-turn timestamp for one conversation. */ private releaseConversation(conversationId: string | undefined): void { if (conversationId === undefined) return this.transcripts.delete(conversationId) for (const key of this.startedAt.keys()) { if (key.startsWith(`${conversationId}:`)) this.startedAt.delete(key) } } private handleEnd(session: SessionLike | undefined, event: SessionEventLike): void { const settings = this.options.settings() const conversationId = conversationIdOf(session) if (conversationId === undefined) return const turn = turnOf(event.data) if (turn === undefined) { // Without a turn id there is nothing reportable or summarizable; still // release any buffered text so it cannot outlive the conversation. this.releaseConversation(conversationId) return } const key = `${conversationId}:${turn}` const completedAt = toEpochMs(event.time) ?? Date.now() const startedAt = this.startedAt.get(key) ?? completedAt this.startedAt.delete(key) const reason = event.data?.reason const status = statusForReason(reason) if (status === null) { // A forked turn restarts in the child session; its partial text would // double-count there, so release it here instead of letting it leak // into the child's summary. this.releaseTranscript(conversationId, turn) this.push({ turnId: key, conversationId, status: 'cancelled', startedAt, completedAt, at: Date.now(), outcome: 'skipped', error: 'forked turn is not reported' }) this.skipped += 1 return } // Summary staging and activity reporting are independent features with // independent credentials: every turn releases its buffered text, even // when the activity side is disabled or unconfigured. void this.sendSummary(conversationId, turn, status) if (!settings.enabled) { this.push({ turnId: key, conversationId, status, startedAt, completedAt, at: Date.now(), outcome: 'skipped', error: 'reporting disabled' }) this.skipped += 1 return } const token = this.options.activityToken() if (token === '') { this.push({ turnId: key, conversationId, status, startedAt, completedAt, at: Date.now(), outcome: 'skipped', error: 'activity token not configured' }) this.skipped += 1 return } const payload: TurnPayload = { client_id: settings.clientId, conversation_id: conversationId, turn_id: key, status, started_at: Math.min(startedAt, completedAt), completed_at: completedAt, } void this.send(payload) } /** * Buffer one redacted message for the turn that is still open. * * Nothing is buffered unless summaries are fully configured: a disabled or * token-less summary must not keep accumulating transcript text, and a * message with no turn of its own is dropped rather than attached to an * unrelated future turn. */ private collect(session: SessionLike | undefined, event: SessionEventLike): void { // Summary is part of the activity pipeline: when activity reporting is // switched off, no new transcript text is collected. Buffered text from // before the switch is released in sendSummary instead of being sent. if (!this.options.settings().enabled || !this.options.summary().enabled || this.options.summaryToken() === '') return const conversationId = conversationIdOf(session) if (conversationId === undefined) return const turn = turnOf(event.data) if (turn === undefined) return const raw = textOf(event.data) if (raw === undefined) return const value = redactSecrets(raw).slice(0, 4000) const scope = this.summaryScope(this.connection()) let buffer = this.transcripts.get(conversationId) if (buffer === undefined) { buffer = { scope, messages: [] } this.transcripts.set(conversationId, buffer) if (this.transcripts.size > MAX_CONVERSATIONS) { const oldest = this.transcripts.keys().next() if (oldest.done !== true) this.transcripts.delete(oldest.value) } } else if (buffer.scope !== scope) { // Connection switched mid-conversation: the earlier text belongs to the // old account and must never reach the new one. this.options.log(`dsh-brain: dropping turn-summary buffer after a connection switch: ${conversationId}`) buffer.scope = scope buffer.messages = [] } buffer.messages.push({ role: event.type === 'user/message' ? 'user' : 'assistant', text: value, turn }) if (buffer.messages.length > 120) buffer.messages.splice(0, buffer.messages.length - 120) } /** * Split the conversation buffer into this turn's messages and the rest. * * Only messages tagged with exactly this turn belong to it; anything else * (a stray turn-less message) is dropped, not reattached to a future turn. */ private partitionTranscript(conversationId: string, turn: number): { picked: SummaryMessage[]; rest: BufferedMessage[] } { const buffer = this.transcripts.get(conversationId) if (buffer === undefined) return { picked: [], rest: [] } const picked: SummaryMessage[] = [] const rest: BufferedMessage[] = [] for (const item of buffer.messages) { const matches = item.turn !== undefined && item.turn === turn if (matches) picked.push({ role: item.role, text: item.text }) else if (item.turn !== undefined && item.turn !== turn) rest.push(item) } buffer.messages = rest return { picked, rest } } /** Take this turn's messages out of the buffer, capped by the char budget. */ private takeTranscript(conversationId: string, turn: number): SummaryMessage[] { const { picked } = this.partitionTranscript(conversationId, turn) const maxChars = Math.max(1000, this.options.summary().maxChars) let total = 0 const kept: SummaryMessage[] = [] for (const message of picked) { if (total + message.text.length > maxChars) break kept.push(message) total += message.text.length } return kept } /** Drop this turn's messages without sending them (fork, cancel, disable). */ private releaseTranscript(conversationId: string, turn: number): void { this.partitionTranscript(conversationId, turn) } /** * Stage one summary; failures only surface in the status card. * * Every end path consumes the turn's buffered text: sent, failed, cancelled * and disabled all release the buffer, so a turn never leaves text behind * for an unrelated later turn. Text collected under a different connection * scope is dropped here instead of being handed to the current account. */ private async sendSummary(conversationId: string, turn: number, status: TurnStatus): Promise { const context = this.connection() const scope = this.summaryScope(context) const buffer = this.transcripts.get(conversationId) let messages: SummaryMessage[] = [] if (buffer === undefined) { // Nothing was buffered (summaries may have been off during the turn). } else if (buffer.scope === scope) { messages = this.takeTranscript(conversationId, turn) } else { // The buffered text belongs to a different account or service: never // hand it to the current one — release everything. this.options.log(`dsh-brain: dropping turn-summary buffer for a switched account: ${conversationId}`) this.transcripts.delete(conversationId) } const activity = this.options.settings() if (!activity.enabled) { // The activity switch also gates summaries: a turn ending while // reporting is off must release its text, not stage it. this.releaseTranscript(conversationId, turn) return } const summary = this.options.summary() const token = context.summaryToken if (!summary.enabled || token === '' || status !== 'completed' || messages.length === 0) return const payload: SummaryPayload = { conversation_id: conversationId, turn_id: `${conversationId}:${turn}`, messages } this.summaryAttempted += 1 const client = this.clientFor(context) const result = await client.submitSummary(payload, token) if (result.ok) { this.summaryStaged += typeof result.data.staged === 'number' ? result.data.staged : 0 return } if (result.error.status === 0 || result.error.status >= 500) { const retry = await client.submitSummary(payload, token) if (retry.ok) { this.summaryStaged += typeof retry.data.staged === 'number' ? retry.data.staged : 0 return } } this.summaryFailed += 1 this.lastSummaryError = describeError(result.error) this.options.log(`dsh-brain: turn summary failed: ${this.lastSummaryError}`) } private push(record: ReportRecord): void { this.recent.unshift(record) if (this.recent.length > 50) this.recent.length = 50 } /** Send one payload, queueing it when the failure looks transient. */ private async send(payload: TurnPayload): Promise { this.attempted += 1 // Pin the connection BEFORE the first await: the record leaves under the // account it was collected for, even when settings change mid-send. const context = this.connection() const result = await this.clientFor(context).reportTurn(payload, context.activityToken) const now = Date.now() if (result.ok) { const duplicate = result.data.duplicate === true || result.status === 200 if (duplicate) this.duplicate += 1 else this.recorded += 1 this.retries.delete(payload.turn_id) this.lastSentAt = now this.push({ turnId: payload.turn_id, conversationId: payload.conversation_id, status: payload.status, startedAt: payload.started_at, completedAt: payload.completed_at, at: now, outcome: duplicate ? 'duplicate' : 'recorded', httpStatus: result.status, }) return } this.lastError = describeError(result.error) this.failed += 1 this.push({ turnId: payload.turn_id, conversationId: payload.conversation_id, status: payload.status, startedAt: payload.started_at, completedAt: payload.completed_at, at: now, outcome: 'queued', httpStatus: result.error.status, error: this.lastError, }) // 4xx (other than 429) means the payload or token is wrong: retrying cannot help. if (result.error.status === 0 || result.error.status >= 500) { this.queue.push({ payload, scope: this.activityScope(context) }) if (this.queue.length > 200) this.queue.shift() } this.options.log(`dsh-brain: turn report failed: ${this.lastError}`) } /** Resolve the client bound to the context pinned for this request. */ private clientFor(context: ReporterConnection): CloudClient { if (this.options.clientFor !== undefined) return this.options.clientFor(context) if (this.options.client !== undefined) return this.options.client throw new Error('Reporter requires clientFor(context)') } /** Snapshot the whole connection at one instant. */ private connection(): ReporterConnection { return { baseUrl: this.options.baseUrl === undefined ? '' : this.options.baseUrl(), activityToken: this.options.activityToken(), summaryToken: this.options.summaryToken(), timeoutMs: this.options.timeoutMs === undefined ? 30_000 : this.options.timeoutMs(), } } /** Scope key binding an activity record to one endpoint+account. */ private activityScope(context: ReporterConnection): string { return `${context.baseUrl}|${context.activityToken}` } /** Scope key binding summary text to one endpoint+account. */ private summaryScope(context: ReporterConnection): string { return `${context.baseUrl}|${context.summaryToken}` } /** Retry queued reports; safe to call at any time. */ async flush(): Promise<{ sent: number; remaining: number }> { if (this.draining) return { sent: 0, remaining: this.queue.length } // Retrying is a reporting action: when reporting is switched off, the // queue waits instead of pushing data the user turned off. if (!this.options.settings().enabled) return { sent: 0, remaining: this.queue.length } this.draining = true let sent = 0 try { while (this.queue.length > 0) { // Re-check the gates on EVERY entry: a mid-flush disable stops new // requests (records already sent are not recalled), and a mid-flush // account switch drops the remaining old-account entries. if (!this.options.settings().enabled) break const context = this.connection() const scope = this.activityScope(context) // A queued entry belongs to the account that failed to send it. After a // token or endpoint switch the current credential must not replay old // records to (or as) a different account, so stale entries are dropped. const head = this.queue[0] if (head === undefined) break if (head.scope !== scope) { this.queue.shift() this.options.log(`dsh-brain: dropping queued turn report for a switched account: ${head.payload.turn_id}`) continue } const payload = head.payload this.attempted += 1 const result = await this.clientFor(context).reportTurn(payload, context.activityToken) if (!result.ok) { this.lastError = describeError(result.error) this.failed += 1 const attempt = (this.retries.get(payload.turn_id) ?? 0) + 1 if (attempt >= MAX_RETRY_ATTEMPTS) { // Give up on this turn: a permanently failing endpoint must not keep // an unbounded queue of metadata forever. this.queue.shift() this.retries.delete(payload.turn_id) this.options.log(`dsh-brain: dropping turn report after ${attempt} attempts: ${this.lastError}`) continue } this.retries.set(payload.turn_id, attempt) break } this.queue.shift() this.retries.delete(payload.turn_id) sent += 1 if (result.data.duplicate === true || result.status === 200) this.duplicate += 1 else this.recorded += 1 this.lastSentAt = Date.now() } } finally { this.draining = false } return { sent, remaining: this.queue.length } } /** Counters + recent history. */ snapshot(): ReporterSnapshot { return { attempted: this.attempted, recorded: this.recorded, duplicate: this.duplicate, failed: this.failed, skipped: this.skipped, queued: this.queue.length, summaryAttempted: this.summaryAttempted, summaryStaged: this.summaryStaged, summaryFailed: this.summaryFailed, ...(this.lastSummaryError === undefined ? {} : { lastSummaryError: this.lastSummaryError }), ...(this.lastSentAt === undefined ? {} : { lastSentAt: this.lastSentAt }), ...(this.lastError === undefined ? {} : { lastError: this.lastError }), recent: [...this.recent], } } }