feat(hooks): consolidate shared transport helpers

This commit is contained in:
William Valentin
2026-03-26 11:22:27 -07:00
parent d49785cb25
commit fdfcb50e80
10 changed files with 374 additions and 948 deletions
+19 -176
View File
@@ -1,66 +1,22 @@
import { randomUUID } from 'node:crypto';
import { hostname } from 'node:os';
import {
Dict,
isRecord,
pickString,
pickNumber,
truncate,
buildEnvelope,
createTransport,
} from '../shared/lib';
type Dict = Record<string, any>;
const INGEST_URL = process.env.AGENTMON_INGEST_URL || 'http://192.168.122.1:8080';
const INGEST_URL = process.env.AGENTMON_INGEST_URL || 'http://localhost:8080';
const VM_NAME = process.env.AGENTMON_VM_NAME || hostname();
const BATCH_SIZE = 10;
const FLUSH_MS = 2000;
const FETCH_TIMEOUT_MS = 500;
let buffer: Dict[] = [];
let flushTimer: ReturnType<typeof setTimeout> | null = null;
let isFlushing = false;
const { enqueue, flush } = createTransport(INGEST_URL);
const activeRuns = new Map<string, string>();
function isRecord(value: unknown): value is Dict {
return value !== null && typeof value === 'object' && !Array.isArray(value);
}
function pickString(...values: unknown[]): string | undefined {
for (const value of values) {
if (typeof value === 'string' && value.trim() !== '') {
return value;
}
}
return undefined;
}
function pickNumber(...values: unknown[]): number | undefined {
for (const value of values) {
if (typeof value === 'number' && Number.isFinite(value)) {
return value;
}
}
return undefined;
}
function truncate(value: unknown, limit: number): string | undefined {
if (value === undefined || value === null) {
return undefined;
}
const text = typeof value === 'string' ? value : safeJSONStringify(value);
if (!text) {
return undefined;
}
if (text.length <= limit) {
return text;
}
return text.slice(0, limit) + '...';
}
function safeJSONStringify(value: unknown): string {
try {
return JSON.stringify(value);
} catch {
return String(value);
}
}
function getEventName(input: Dict): string {
const direct = pickString(input.name, input.event);
if (direct) {
@@ -97,119 +53,6 @@ function getSessionKey(input: Dict, context: Dict): string | undefined {
);
}
function buildEnvelope(
type: string,
sessionKey?: string,
opts: {
runId?: string;
spanId?: string;
parentSpanId?: string;
attributes?: Dict;
payload?: Dict;
} = {},
): Dict {
const correlation: Dict = {};
if (sessionKey) {
correlation.session_id = sessionKey;
}
if (opts.runId) {
correlation.run_id = opts.runId;
}
if (opts.spanId) {
correlation.span_id = opts.spanId;
}
if (opts.parentSpanId) {
correlation.parent_span_id = opts.parentSpanId;
}
const envelope: Dict = {
schema: { name: 'agentmon.event', version: 1 },
event: {
id: randomUUID(),
type,
ts: new Date().toISOString(),
source: {
framework: 'openclaw',
client_id: VM_NAME,
host: VM_NAME,
},
},
};
if (Object.keys(correlation).length > 0) {
envelope.correlation = correlation;
}
if (opts.attributes && Object.keys(opts.attributes).length > 0) {
envelope.attributes = opts.attributes;
}
if (opts.payload && Object.keys(opts.payload).length > 0) {
envelope.payload = opts.payload;
}
return envelope;
}
function scheduleFlush() {
if (!flushTimer) {
flushTimer = setTimeout(() => {
void flush();
}, FLUSH_MS);
}
}
function enqueue(event: Dict) {
buffer.push(event);
if (buffer.length >= BATCH_SIZE) {
void flush();
} else {
scheduleFlush();
}
}
async function postBatch(batch: Dict[]) {
const controller = new AbortController();
const timeout = setTimeout(() => controller.abort(), FETCH_TIMEOUT_MS);
try {
await fetch(`${INGEST_URL}/v1/events`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(batch),
signal: controller.signal,
});
} finally {
clearTimeout(timeout);
}
}
async function flush() {
if (flushTimer) {
clearTimeout(flushTimer);
flushTimer = null;
}
if (isFlushing || buffer.length === 0) {
return;
}
isFlushing = true;
const batch = buffer.splice(0, BATCH_SIZE);
try {
await postBatch(batch);
} catch {
console.debug(`[agentmon] failed to flush ${batch.length} events`);
} finally {
isFlushing = false;
if (buffer.length > 0) {
if (buffer.length >= BATCH_SIZE) {
void flush();
} else {
scheduleFlush();
}
}
}
}
function emitError(sessionKey: string | undefined, runId: string | undefined, spanId: string | undefined, errorValue: unknown) {
if (errorValue === undefined || errorValue === null || errorValue === false) {
return;
@@ -219,7 +62,7 @@ function emitError(sessionKey: string | undefined, runId: string | undefined, sp
const message = pickString(errorRecord.message, errorRecord.error, errorValue) || 'unknown';
const errType = pickString(errorRecord.type, errorRecord.code) || 'openclaw';
enqueue(buildEnvelope('error', sessionKey, {
enqueue(buildEnvelope('openclaw', VM_NAME, 'error', sessionKey, {
runId,
spanId,
payload: {
@@ -265,12 +108,12 @@ const handler = async (rawEvent: unknown) => {
try {
if (eventName === 'command:new') {
enqueue(buildEnvelope('session.start', sessionKey));
enqueue(buildEnvelope('openclaw', VM_NAME, 'session.start', sessionKey));
return;
}
if (eventName === 'command:stop') {
enqueue(buildEnvelope('session.end', sessionKey));
enqueue(buildEnvelope('openclaw', VM_NAME, 'session.end', sessionKey));
if (sessionKey) {
activeRuns.delete(sessionKey);
}
@@ -278,8 +121,8 @@ const handler = async (rawEvent: unknown) => {
}
if (eventName === 'command:reset') {
enqueue(buildEnvelope('session.end', sessionKey));
enqueue(buildEnvelope('session.start', sessionKey));
enqueue(buildEnvelope('openclaw', VM_NAME, 'session.end', sessionKey));
enqueue(buildEnvelope('openclaw', VM_NAME, 'session.start', sessionKey));
if (sessionKey) {
activeRuns.delete(sessionKey);
}
@@ -297,7 +140,7 @@ const handler = async (rawEvent: unknown) => {
activeRuns.set(sessionKey, runId);
}
enqueue(buildEnvelope('run.start', sessionKey, {
enqueue(buildEnvelope('openclaw', VM_NAME, 'run.start', sessionKey, {
runId,
attributes: {
agent_id: pickString(context.agentId as string | undefined),
@@ -314,7 +157,7 @@ const handler = async (rawEvent: unknown) => {
activeRuns.set(sessionKey, runId);
}
enqueue(buildEnvelope('run.start', sessionKey, {
enqueue(buildEnvelope('openclaw', VM_NAME, 'run.start', sessionKey, {
runId,
attributes: {
channel: pickString(context.channelId, context.channel_id),
@@ -334,7 +177,7 @@ const handler = async (rawEvent: unknown) => {
const runId = sessionKey ? activeRuns.get(sessionKey) : undefined;
const success = context.success !== false && !context.error;
enqueue(buildEnvelope('run.end', sessionKey, {
enqueue(buildEnvelope('openclaw', VM_NAME, 'run.end', sessionKey, {
runId,
attributes: {
channel: pickString(context.channelId, context.channel_id),