Files
2026-03-26 11:22:27 -07:00

197 lines
4.5 KiB
TypeScript

import { randomUUID } from 'node:crypto';
export interface Dict { [key: string]: any }
export function isRecord(value: unknown): value is Dict {
return value !== null && typeof value === 'object' && !Array.isArray(value);
}
export function pickString(...values: unknown[]): string | undefined {
for (const value of values) {
if (typeof value === 'string' && value.trim() !== '') {
return value;
}
}
return undefined;
}
export function pickNumber(...values: unknown[]): number | undefined {
for (const value of values) {
if (typeof value === 'number' && Number.isFinite(value)) {
return value;
}
}
return undefined;
}
export 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) + '...';
}
export function safeJSONStringify(value: unknown): string {
try {
return JSON.stringify(value);
} catch {
return String(value);
}
}
export function buildEnvelope(
framework: string,
host: string,
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,
client_id: host,
host,
},
},
};
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;
}
export function createTransport(
ingestUrl: string,
opts?: { batchSize?: number; flushMs?: number; fetchTimeoutMs?: number },
): { enqueue(event: Dict): void; flush(): Promise<void> } {
const batchSize = opts?.batchSize ?? 10;
const flushMs = opts?.flushMs ?? 2000;
const fetchTimeoutMs = opts?.fetchTimeoutMs ?? 500;
let buffer: Dict[] = [];
let flushTimer: ReturnType<typeof setTimeout> | null = null;
let isFlushing = false;
async function postBatch(batch: Dict[]) {
const controller = new AbortController();
const timeout = setTimeout(() => controller.abort(), fetchTimeoutMs);
try {
await fetch(`${ingestUrl}/v1/events`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(batch),
signal: controller.signal,
});
} finally {
clearTimeout(timeout);
}
}
function scheduleFlush() {
if (!flushTimer) {
flushTimer = setTimeout(() => {
void flush();
}, flushMs);
}
}
async function flush() {
if (flushTimer) {
clearTimeout(flushTimer);
flushTimer = null;
}
if (isFlushing || buffer.length === 0) {
return;
}
isFlushing = true;
const batch = buffer.splice(0, batchSize);
try {
await postBatch(batch);
} catch {
console.debug(`[agentmon] failed to flush ${batch.length} events`);
} finally {
isFlushing = false;
if (buffer.length > 0) {
if (buffer.length >= batchSize) {
void flush();
} else {
scheduleFlush();
}
}
}
}
function enqueue(event: Dict) {
buffer.push(event);
if (buffer.length >= batchSize) {
void flush();
} else {
scheduleFlush();
}
}
return { enqueue, flush };
}
export async function readStdin(): Promise<string> {
return new Promise((resolve) => {
let data = '';
let done = false;
const timer = setTimeout(() => finish(data), 100);
const finish = (value: string) => {
if (done) return;
done = true;
clearTimeout(timer);
resolve(value);
};
process.stdin.on('data', (chunk) => { data += chunk; });
process.stdin.on('end', () => finish(data));
process.stdin.on('error', () => finish(''));
});
}