545 lines
23 KiB
JavaScript
545 lines
23 KiB
JavaScript
import { describeError } from "./api.js";
|
||
/** Normalize an event timestamp (ms epoch or ISO string) into epoch ms. */
|
||
export function toEpochMs(value) {
|
||
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) {
|
||
const kind = typeof reason === 'string'
|
||
? reason
|
||
: reason !== null && typeof reason === 'object'
|
||
? reason.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) {
|
||
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) {
|
||
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, depth = 0) {
|
||
if (depth > 5)
|
||
return undefined;
|
||
if (typeof value === 'string')
|
||
return value.trim() === '' ? undefined : value;
|
||
if (Array.isArray(value)) {
|
||
const parts = [];
|
||
for (const item of value) {
|
||
if (item !== null && typeof item === 'object') {
|
||
const part = item;
|
||
// 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;
|
||
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 = [
|
||
[/-----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) {
|
||
let out = text;
|
||
for (const [pattern, replacement] of REDACTIONS)
|
||
out = out.replace(pattern, replacement);
|
||
return out;
|
||
}
|
||
/**
|
||
* 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 {
|
||
options;
|
||
startedAt = new Map();
|
||
queue = [];
|
||
retries = new Map();
|
||
recent = [];
|
||
attempted = 0;
|
||
recorded = 0;
|
||
duplicate = 0;
|
||
failed = 0;
|
||
skipped = 0;
|
||
lastSentAt;
|
||
lastError;
|
||
draining = false;
|
||
/** Redacted message text per conversation, consumed at turn/end. */
|
||
transcripts = new Map();
|
||
summaryAttempted = 0;
|
||
summaryStaged = 0;
|
||
summaryFailed = 0;
|
||
lastSummaryError;
|
||
constructor(options) {
|
||
this.options = options;
|
||
}
|
||
/** Record a turn start so its duration can be reported later. */
|
||
handleStart(session, event) {
|
||
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, event) {
|
||
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. */
|
||
releaseConversation(conversationId) {
|
||
if (conversationId === undefined)
|
||
return;
|
||
this.transcripts.delete(conversationId);
|
||
for (const key of this.startedAt.keys()) {
|
||
if (key.startsWith(`${conversationId}:`))
|
||
this.startedAt.delete(key);
|
||
}
|
||
}
|
||
handleEnd(session, event) {
|
||
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 = {
|
||
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.
|
||
*/
|
||
collect(session, event) {
|
||
// 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.
|
||
*/
|
||
partitionTranscript(conversationId, turn) {
|
||
const buffer = this.transcripts.get(conversationId);
|
||
if (buffer === undefined)
|
||
return { picked: [], rest: [] };
|
||
const picked = [];
|
||
const rest = [];
|
||
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. */
|
||
takeTranscript(conversationId, turn) {
|
||
const { picked } = this.partitionTranscript(conversationId, turn);
|
||
const maxChars = Math.max(1000, this.options.summary().maxChars);
|
||
let total = 0;
|
||
const kept = [];
|
||
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). */
|
||
releaseTranscript(conversationId, turn) {
|
||
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.
|
||
*/
|
||
async sendSummary(conversationId, turn, status) {
|
||
const context = this.connection();
|
||
const scope = this.summaryScope(context);
|
||
const buffer = this.transcripts.get(conversationId);
|
||
let messages = [];
|
||
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 = { 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}`);
|
||
}
|
||
push(record) {
|
||
this.recent.unshift(record);
|
||
if (this.recent.length > 50)
|
||
this.recent.length = 50;
|
||
}
|
||
/** Send one payload, queueing it when the failure looks transient. */
|
||
async send(payload) {
|
||
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. */
|
||
clientFor(context) {
|
||
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. */
|
||
connection() {
|
||
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. */
|
||
activityScope(context) {
|
||
return `${context.baseUrl}|${context.activityToken}`;
|
||
}
|
||
/** Scope key binding summary text to one endpoint+account. */
|
||
summaryScope(context) {
|
||
return `${context.baseUrl}|${context.summaryToken}`;
|
||
}
|
||
/** Retry queued reports; safe to call at any time. */
|
||
async flush() {
|
||
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() {
|
||
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],
|
||
};
|
||
}
|
||
}
|