feat(hooks): consolidate shared transport helpers
This commit is contained in:
@@ -205,6 +205,17 @@ Sample Codex hook configuration lives in [hooks/codex/hooks.json](/home/will/lab
|
|||||||
|
|
||||||
The current Codex integration does not assume tool or subagent span hooks exist. If a newer Codex CLI exposes official tool/span hooks, they can be added separately without changing the run/session flow above.
|
The current Codex integration does not assume tool or subagent span hooks exist. If a newer Codex CLI exposes official tool/span hooks, they can be added separately without changing the run/session flow above.
|
||||||
|
|
||||||
|
## Gemini Hook
|
||||||
|
|
||||||
|
The `hooks/gemini/` directory contains a TypeScript handler for Gemini CLI telemetry. The current integration maps Gemini hook events into agentmon's session/run/span model:
|
||||||
|
|
||||||
|
- `onStart` maps to `session.start` and an initial `run.start`
|
||||||
|
- `onStop` maps to `run.end` and `session.end`
|
||||||
|
- `onToolCall` maps to `span.start`
|
||||||
|
- `onToolResult` maps to `span.end`
|
||||||
|
|
||||||
|
Sample Gemini hook configuration lives in [hooks/gemini/hooks.json](/home/will/lab/agentmon/hooks/gemini/hooks.json). Install the handler from that directory so the `agentmon-gemini-handler` binary is available, then point Gemini CLI at the sample hook config and set `AGENTMON_INGEST_URL` to your ingest gateway.
|
||||||
|
|
||||||
## Go SDK
|
## Go SDK
|
||||||
|
|
||||||
Emit events from Go applications:
|
Emit events from Go applications:
|
||||||
|
|||||||
+19
-176
@@ -1,66 +1,22 @@
|
|||||||
import { randomUUID } from 'node:crypto';
|
import { randomUUID } from 'node:crypto';
|
||||||
import { hostname } from 'node:os';
|
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://localhost:8080';
|
||||||
|
|
||||||
const INGEST_URL = process.env.AGENTMON_INGEST_URL || 'http://192.168.122.1:8080';
|
|
||||||
const VM_NAME = process.env.AGENTMON_VM_NAME || hostname();
|
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[] = [];
|
const { enqueue, flush } = createTransport(INGEST_URL);
|
||||||
let flushTimer: ReturnType<typeof setTimeout> | null = null;
|
|
||||||
let isFlushing = false;
|
|
||||||
|
|
||||||
const activeRuns = new Map<string, string>();
|
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 {
|
function getEventName(input: Dict): string {
|
||||||
const direct = pickString(input.name, input.event);
|
const direct = pickString(input.name, input.event);
|
||||||
if (direct) {
|
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) {
|
function emitError(sessionKey: string | undefined, runId: string | undefined, spanId: string | undefined, errorValue: unknown) {
|
||||||
if (errorValue === undefined || errorValue === null || errorValue === false) {
|
if (errorValue === undefined || errorValue === null || errorValue === false) {
|
||||||
return;
|
return;
|
||||||
@@ -219,7 +62,7 @@ function emitError(sessionKey: string | undefined, runId: string | undefined, sp
|
|||||||
const message = pickString(errorRecord.message, errorRecord.error, errorValue) || 'unknown';
|
const message = pickString(errorRecord.message, errorRecord.error, errorValue) || 'unknown';
|
||||||
const errType = pickString(errorRecord.type, errorRecord.code) || 'openclaw';
|
const errType = pickString(errorRecord.type, errorRecord.code) || 'openclaw';
|
||||||
|
|
||||||
enqueue(buildEnvelope('error', sessionKey, {
|
enqueue(buildEnvelope('openclaw', VM_NAME, 'error', sessionKey, {
|
||||||
runId,
|
runId,
|
||||||
spanId,
|
spanId,
|
||||||
payload: {
|
payload: {
|
||||||
@@ -265,12 +108,12 @@ const handler = async (rawEvent: unknown) => {
|
|||||||
|
|
||||||
try {
|
try {
|
||||||
if (eventName === 'command:new') {
|
if (eventName === 'command:new') {
|
||||||
enqueue(buildEnvelope('session.start', sessionKey));
|
enqueue(buildEnvelope('openclaw', VM_NAME, 'session.start', sessionKey));
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (eventName === 'command:stop') {
|
if (eventName === 'command:stop') {
|
||||||
enqueue(buildEnvelope('session.end', sessionKey));
|
enqueue(buildEnvelope('openclaw', VM_NAME, 'session.end', sessionKey));
|
||||||
if (sessionKey) {
|
if (sessionKey) {
|
||||||
activeRuns.delete(sessionKey);
|
activeRuns.delete(sessionKey);
|
||||||
}
|
}
|
||||||
@@ -278,8 +121,8 @@ const handler = async (rawEvent: unknown) => {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (eventName === 'command:reset') {
|
if (eventName === 'command:reset') {
|
||||||
enqueue(buildEnvelope('session.end', sessionKey));
|
enqueue(buildEnvelope('openclaw', VM_NAME, 'session.end', sessionKey));
|
||||||
enqueue(buildEnvelope('session.start', sessionKey));
|
enqueue(buildEnvelope('openclaw', VM_NAME, 'session.start', sessionKey));
|
||||||
if (sessionKey) {
|
if (sessionKey) {
|
||||||
activeRuns.delete(sessionKey);
|
activeRuns.delete(sessionKey);
|
||||||
}
|
}
|
||||||
@@ -297,7 +140,7 @@ const handler = async (rawEvent: unknown) => {
|
|||||||
activeRuns.set(sessionKey, runId);
|
activeRuns.set(sessionKey, runId);
|
||||||
}
|
}
|
||||||
|
|
||||||
enqueue(buildEnvelope('run.start', sessionKey, {
|
enqueue(buildEnvelope('openclaw', VM_NAME, 'run.start', sessionKey, {
|
||||||
runId,
|
runId,
|
||||||
attributes: {
|
attributes: {
|
||||||
agent_id: pickString(context.agentId as string | undefined),
|
agent_id: pickString(context.agentId as string | undefined),
|
||||||
@@ -314,7 +157,7 @@ const handler = async (rawEvent: unknown) => {
|
|||||||
activeRuns.set(sessionKey, runId);
|
activeRuns.set(sessionKey, runId);
|
||||||
}
|
}
|
||||||
|
|
||||||
enqueue(buildEnvelope('run.start', sessionKey, {
|
enqueue(buildEnvelope('openclaw', VM_NAME, 'run.start', sessionKey, {
|
||||||
runId,
|
runId,
|
||||||
attributes: {
|
attributes: {
|
||||||
channel: pickString(context.channelId, context.channel_id),
|
channel: pickString(context.channelId, context.channel_id),
|
||||||
@@ -334,7 +177,7 @@ const handler = async (rawEvent: unknown) => {
|
|||||||
const runId = sessionKey ? activeRuns.get(sessionKey) : undefined;
|
const runId = sessionKey ? activeRuns.get(sessionKey) : undefined;
|
||||||
const success = context.success !== false && !context.error;
|
const success = context.success !== false && !context.error;
|
||||||
|
|
||||||
enqueue(buildEnvelope('run.end', sessionKey, {
|
enqueue(buildEnvelope('openclaw', VM_NAME, 'run.end', sessionKey, {
|
||||||
runId,
|
runId,
|
||||||
attributes: {
|
attributes: {
|
||||||
channel: pickString(context.channelId, context.channel_id),
|
channel: pickString(context.channelId, context.channel_id),
|
||||||
|
|||||||
+25
-191
@@ -3,15 +3,22 @@ import { randomUUID } from 'node:crypto';
|
|||||||
import { hostname, homedir } from 'node:os';
|
import { hostname, homedir } from 'node:os';
|
||||||
import { readFileSync, writeFileSync, mkdirSync, unlinkSync } from 'node:fs';
|
import { readFileSync, writeFileSync, mkdirSync, unlinkSync } from 'node:fs';
|
||||||
import { join } from 'node:path';
|
import { join } from 'node:path';
|
||||||
|
import {
|
||||||
|
type Dict,
|
||||||
|
isRecord,
|
||||||
|
pickString,
|
||||||
|
pickNumber,
|
||||||
|
truncate,
|
||||||
|
buildEnvelope,
|
||||||
|
createTransport,
|
||||||
|
readStdin,
|
||||||
|
} from '../shared/lib';
|
||||||
|
|
||||||
const INGEST_URL = process.env.AGENTMON_INGEST_URL || 'http://localhost:8080';
|
const INGEST_URL = process.env.AGENTMON_INGEST_URL || 'http://localhost:8080';
|
||||||
const FRAMEWORK = process.env.AGENTMON_FRAMEWORK || 'claude-code';
|
const FRAMEWORK = process.env.AGENTMON_FRAMEWORK || 'claude-code';
|
||||||
const HOST = process.env.AGENTMON_HOST || hostname();
|
const HOST = process.env.AGENTMON_HOST || hostname();
|
||||||
const BATCH_SIZE = 10;
|
|
||||||
const FLUSH_MS = 2000;
|
|
||||||
const FETCH_TIMEOUT_MS = 500;
|
|
||||||
|
|
||||||
interface Dict { [key: string]: any }
|
const { enqueue, flush } = createTransport(INGEST_URL);
|
||||||
|
|
||||||
// ── Persisted state (survives between hook subprocess invocations) ──────────
|
// ── Persisted state (survives between hook subprocess invocations) ──────────
|
||||||
interface SessionState {
|
interface SessionState {
|
||||||
@@ -49,60 +56,10 @@ function clearState(sessionKey: string) {
|
|||||||
}
|
}
|
||||||
// ─────────────────────────────────────────────────────────────────────────────
|
// ─────────────────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
let buffer: Dict[] = [];
|
|
||||||
let flushTimer: ReturnType<typeof setTimeout> | null = null;
|
|
||||||
let isFlushing = false;
|
|
||||||
|
|
||||||
const activeRuns = new Map<string, string>();
|
const activeRuns = new Map<string, string>();
|
||||||
const activeSpans = new Map<string, string>();
|
const activeSpans = new Map<string, string>();
|
||||||
const activeSubagents = new Map<string, { name: string; spanId: string }>();
|
const activeSubagents = new Map<string, { name: string; spanId: 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 getSessionKey(input: Dict): string | undefined {
|
function getSessionKey(input: Dict): string | undefined {
|
||||||
return pickString(
|
return pickString(
|
||||||
input.sessionId,
|
input.sessionId,
|
||||||
@@ -145,119 +102,6 @@ function getContextWindow(input: Dict): Dict | undefined {
|
|||||||
return Object.keys(result).length > 0 ? result : undefined;
|
return Object.keys(result).length > 0 ? result : 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: FRAMEWORK,
|
|
||||||
client_id: HOST,
|
|
||||||
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;
|
|
||||||
}
|
|
||||||
|
|
||||||
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) {
|
function emitError(sessionKey: string | undefined, runId: string | undefined, spanId: string | undefined, errorValue: unknown) {
|
||||||
if (errorValue === undefined || errorValue === null || errorValue === false) {
|
if (errorValue === undefined || errorValue === null || errorValue === false) {
|
||||||
return;
|
return;
|
||||||
@@ -267,7 +111,7 @@ function emitError(sessionKey: string | undefined, runId: string | undefined, sp
|
|||||||
const message = pickString(errorRecord.message, errorRecord.error, errorValue) || 'unknown';
|
const message = pickString(errorRecord.message, errorRecord.error, errorValue) || 'unknown';
|
||||||
const errType = pickString(errorRecord.type, errorRecord.code) || FRAMEWORK;
|
const errType = pickString(errorRecord.type, errorRecord.code) || FRAMEWORK;
|
||||||
|
|
||||||
enqueue(buildEnvelope('error', sessionKey, {
|
enqueue(buildEnvelope(FRAMEWORK, HOST, 'error', sessionKey, {
|
||||||
runId,
|
runId,
|
||||||
spanId,
|
spanId,
|
||||||
payload: {
|
payload: {
|
||||||
@@ -287,11 +131,11 @@ async function handleSessionStart(input: Dict) {
|
|||||||
|
|
||||||
const contextWindow = getContextWindow(input);
|
const contextWindow = getContextWindow(input);
|
||||||
|
|
||||||
enqueue(buildEnvelope('session.start', sessionKey, {
|
enqueue(buildEnvelope(FRAMEWORK, HOST, 'session.start', sessionKey, {
|
||||||
attributes: contextWindow ? { context_window: contextWindow } : undefined,
|
attributes: contextWindow ? { context_window: contextWindow } : undefined,
|
||||||
}));
|
}));
|
||||||
|
|
||||||
enqueue(buildEnvelope('run.start', sessionKey, {
|
enqueue(buildEnvelope(FRAMEWORK, HOST, 'run.start', sessionKey, {
|
||||||
runId,
|
runId,
|
||||||
attributes: {
|
attributes: {
|
||||||
trigger: pickString(input.trigger_type, input.trigger),
|
trigger: pickString(input.trigger_type, input.trigger),
|
||||||
@@ -313,7 +157,7 @@ async function handleSessionEnd(input: Dict) {
|
|||||||
const duration = pickNumber(input.duration_ms, input.elapsed_ms);
|
const duration = pickNumber(input.duration_ms, input.elapsed_ms);
|
||||||
|
|
||||||
if (runId) {
|
if (runId) {
|
||||||
enqueue(buildEnvelope('run.end', sessionKey, {
|
enqueue(buildEnvelope(FRAMEWORK, HOST, 'run.end', sessionKey, {
|
||||||
runId,
|
runId,
|
||||||
payload: {
|
payload: {
|
||||||
status: 'success',
|
status: 'success',
|
||||||
@@ -325,7 +169,7 @@ async function handleSessionEnd(input: Dict) {
|
|||||||
}));
|
}));
|
||||||
}
|
}
|
||||||
|
|
||||||
enqueue(buildEnvelope('session.end', sessionKey, {
|
enqueue(buildEnvelope(FRAMEWORK, HOST, 'session.end', sessionKey, {
|
||||||
payload: {
|
payload: {
|
||||||
...(usage && { usage }),
|
...(usage && { usage }),
|
||||||
...(contextWindow && { context_window: contextWindow }),
|
...(contextWindow && { context_window: contextWindow }),
|
||||||
@@ -346,7 +190,7 @@ async function handlePromptSubmit(input: Dict) {
|
|||||||
const prompt = pickString(input.prompt, input.text, input.message);
|
const prompt = pickString(input.prompt, input.text, input.message);
|
||||||
|
|
||||||
if (runId && prompt) {
|
if (runId && prompt) {
|
||||||
enqueue(buildEnvelope('run.end', sessionKey, {
|
enqueue(buildEnvelope(FRAMEWORK, HOST, 'run.end', sessionKey, {
|
||||||
runId,
|
runId,
|
||||||
payload: {
|
payload: {
|
||||||
status: 'success',
|
status: 'success',
|
||||||
@@ -361,7 +205,7 @@ async function handlePromptSubmit(input: Dict) {
|
|||||||
saveState(sessionKey, { runId: newRunId, spans: {} });
|
saveState(sessionKey, { runId: newRunId, spans: {} });
|
||||||
}
|
}
|
||||||
|
|
||||||
enqueue(buildEnvelope('run.start', sessionKey, {
|
enqueue(buildEnvelope(FRAMEWORK, HOST, 'run.start', sessionKey, {
|
||||||
runId: newRunId,
|
runId: newRunId,
|
||||||
attributes: {
|
attributes: {
|
||||||
type: 'user_prompt',
|
type: 'user_prompt',
|
||||||
@@ -392,7 +236,7 @@ async function handleToolStart(input: Dict) {
|
|||||||
if (sessionKey) saveState(sessionKey, state);
|
if (sessionKey) saveState(sessionKey, state);
|
||||||
}
|
}
|
||||||
|
|
||||||
enqueue(buildEnvelope('span.start', sessionKey, {
|
enqueue(buildEnvelope(FRAMEWORK, HOST, 'span.start', sessionKey, {
|
||||||
runId,
|
runId,
|
||||||
spanId,
|
spanId,
|
||||||
attributes: {
|
attributes: {
|
||||||
@@ -423,7 +267,7 @@ async function handleToolEnd(input: Dict) {
|
|||||||
if (sessionKey) saveState(sessionKey, state);
|
if (sessionKey) saveState(sessionKey, state);
|
||||||
}
|
}
|
||||||
|
|
||||||
enqueue(buildEnvelope('span.end', sessionKey, {
|
enqueue(buildEnvelope(FRAMEWORK, HOST, 'span.end', sessionKey, {
|
||||||
runId,
|
runId,
|
||||||
spanId,
|
spanId,
|
||||||
attributes: {
|
attributes: {
|
||||||
@@ -462,7 +306,7 @@ async function handleSubagentStart(input: Dict) {
|
|||||||
saveState(sessionKey, state);
|
saveState(sessionKey, state);
|
||||||
}
|
}
|
||||||
|
|
||||||
enqueue(buildEnvelope('span.start', sessionKey, {
|
enqueue(buildEnvelope(FRAMEWORK, HOST, 'span.start', sessionKey, {
|
||||||
runId,
|
runId,
|
||||||
spanId,
|
spanId,
|
||||||
attributes: {
|
attributes: {
|
||||||
@@ -493,7 +337,7 @@ async function handleSubagentStop(input: Dict) {
|
|||||||
if (sessionKey) saveState(sessionKey, state);
|
if (sessionKey) saveState(sessionKey, state);
|
||||||
}
|
}
|
||||||
|
|
||||||
enqueue(buildEnvelope('span.end', sessionKey, {
|
enqueue(buildEnvelope(FRAMEWORK, HOST, 'span.end', sessionKey, {
|
||||||
runId,
|
runId,
|
||||||
spanId,
|
spanId,
|
||||||
attributes: {
|
attributes: {
|
||||||
@@ -528,7 +372,7 @@ async function handleCompactStart(input: Dict) {
|
|||||||
saveState(sessionKey, state);
|
saveState(sessionKey, state);
|
||||||
}
|
}
|
||||||
|
|
||||||
enqueue(buildEnvelope('span.start', sessionKey, {
|
enqueue(buildEnvelope(FRAMEWORK, HOST, 'span.start', sessionKey, {
|
||||||
runId,
|
runId,
|
||||||
spanId,
|
spanId,
|
||||||
attributes: {
|
attributes: {
|
||||||
@@ -554,7 +398,7 @@ async function handleCompactEnd(input: Dict) {
|
|||||||
if (sessionKey) saveState(sessionKey, state);
|
if (sessionKey) saveState(sessionKey, state);
|
||||||
}
|
}
|
||||||
|
|
||||||
enqueue(buildEnvelope('span.end', sessionKey, {
|
enqueue(buildEnvelope(FRAMEWORK, HOST, 'span.end', sessionKey, {
|
||||||
runId,
|
runId,
|
||||||
spanId,
|
spanId,
|
||||||
attributes: {
|
attributes: {
|
||||||
@@ -585,7 +429,7 @@ async function handleNotification(input: Dict) {
|
|||||||
const runId = sessionKey ? (activeRuns.get(sessionKey) || state.runId) : undefined;
|
const runId = sessionKey ? (activeRuns.get(sessionKey) || state.runId) : undefined;
|
||||||
|
|
||||||
if (runId) {
|
if (runId) {
|
||||||
enqueue(buildEnvelope('run.end', sessionKey, {
|
enqueue(buildEnvelope(FRAMEWORK, HOST, 'run.end', sessionKey, {
|
||||||
runId,
|
runId,
|
||||||
payload: {
|
payload: {
|
||||||
status: 'success',
|
status: 'success',
|
||||||
@@ -660,14 +504,4 @@ const handler = async () => {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
async function readStdin(): Promise<string> {
|
|
||||||
return new Promise((resolve) => {
|
|
||||||
let data = '';
|
|
||||||
process.stdin.on('data', (chunk) => data += chunk);
|
|
||||||
process.stdin.on('end', () => resolve(data));
|
|
||||||
process.stdin.on('error', () => resolve(''));
|
|
||||||
setTimeout(() => resolve(data), 100);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
handler();
|
handler();
|
||||||
|
|||||||
+16
-182
@@ -1,68 +1,25 @@
|
|||||||
#!/usr/bin/env node
|
#!/usr/bin/env node
|
||||||
import { randomUUID } from 'node:crypto';
|
import { randomUUID } from 'node:crypto';
|
||||||
import { hostname } from 'node:os';
|
import { hostname } from 'node:os';
|
||||||
|
import {
|
||||||
|
type Dict,
|
||||||
|
isRecord,
|
||||||
|
pickString,
|
||||||
|
pickNumber,
|
||||||
|
truncate,
|
||||||
|
buildEnvelope,
|
||||||
|
createTransport,
|
||||||
|
readStdin,
|
||||||
|
} from '../shared/lib';
|
||||||
|
|
||||||
const INGEST_URL = process.env.AGENTMON_INGEST_URL || 'http://localhost:8080';
|
const INGEST_URL = process.env.AGENTMON_INGEST_URL || 'http://localhost:8080';
|
||||||
const FRAMEWORK = process.env.AGENTMON_FRAMEWORK || 'codex';
|
const FRAMEWORK = process.env.AGENTMON_FRAMEWORK || 'codex';
|
||||||
const HOST = process.env.AGENTMON_HOST || hostname();
|
const HOST = process.env.AGENTMON_HOST || hostname();
|
||||||
const BATCH_SIZE = 10;
|
|
||||||
const FLUSH_MS = 2000;
|
|
||||||
const FETCH_TIMEOUT_MS = 500;
|
|
||||||
|
|
||||||
interface Dict { [key: string]: any }
|
const { enqueue, flush } = createTransport(INGEST_URL);
|
||||||
|
|
||||||
let buffer: Dict[] = [];
|
|
||||||
let flushTimer: ReturnType<typeof setTimeout> | null = null;
|
|
||||||
let isFlushing = false;
|
|
||||||
|
|
||||||
const activeRuns = new Map<string, string>();
|
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 getSessionKey(input: Dict): string | undefined {
|
function getSessionKey(input: Dict): string | undefined {
|
||||||
return pickString(
|
return pickString(
|
||||||
input.id,
|
input.id,
|
||||||
@@ -108,75 +65,6 @@ function getModel(input: 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: FRAMEWORK,
|
|
||||||
client_id: HOST,
|
|
||||||
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;
|
|
||||||
}
|
|
||||||
|
|
||||||
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();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function enqueueMetricSnapshot(sessionKey: string | undefined, runId: string | undefined, usage: Dict | undefined, input: Dict) {
|
function enqueueMetricSnapshot(sessionKey: string | undefined, runId: string | undefined, usage: Dict | undefined, input: Dict) {
|
||||||
if (!usage) {
|
if (!usage) {
|
||||||
return;
|
return;
|
||||||
@@ -188,7 +76,7 @@ function enqueueMetricSnapshot(sessionKey: string | undefined, runId: string | u
|
|||||||
metrics.model = model;
|
metrics.model = model;
|
||||||
}
|
}
|
||||||
|
|
||||||
enqueue(buildEnvelope('metric.snapshot', sessionKey, {
|
enqueue(buildEnvelope(FRAMEWORK, HOST, 'metric.snapshot', sessionKey, {
|
||||||
runId,
|
runId,
|
||||||
payload: { metrics },
|
payload: { metrics },
|
||||||
}));
|
}));
|
||||||
@@ -200,7 +88,7 @@ function startRun(sessionKey: string | undefined, input: Dict): string {
|
|||||||
activeRuns.set(sessionKey, runId);
|
activeRuns.set(sessionKey, runId);
|
||||||
}
|
}
|
||||||
|
|
||||||
enqueue(buildEnvelope('run.start', sessionKey, {
|
enqueue(buildEnvelope(FRAMEWORK, HOST, 'run.start', sessionKey, {
|
||||||
runId,
|
runId,
|
||||||
attributes: {
|
attributes: {
|
||||||
trigger: pickString(input.trigger_type, input.trigger, input.event, input.event_type),
|
trigger: pickString(input.trigger_type, input.trigger, input.event, input.event_type),
|
||||||
@@ -219,7 +107,7 @@ function endRun(sessionKey: string | undefined, runId: string | undefined, input
|
|||||||
}
|
}
|
||||||
|
|
||||||
const usage = getUsage(input);
|
const usage = getUsage(input);
|
||||||
enqueue(buildEnvelope('run.end', sessionKey, {
|
enqueue(buildEnvelope(FRAMEWORK, HOST, 'run.end', sessionKey, {
|
||||||
runId,
|
runId,
|
||||||
payload: {
|
payload: {
|
||||||
status: 'success',
|
status: 'success',
|
||||||
@@ -231,54 +119,10 @@ function endRun(sessionKey: string | undefined, runId: string | undefined, input
|
|||||||
enqueueMetricSnapshot(sessionKey, runId, usage, input);
|
enqueueMetricSnapshot(sessionKey, runId, usage, input);
|
||||||
}
|
}
|
||||||
|
|
||||||
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();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async function handleSessionStart(input: Dict) {
|
async function handleSessionStart(input: Dict) {
|
||||||
const sessionKey = getSessionKey(input) || randomUUID();
|
const sessionKey = getSessionKey(input) || randomUUID();
|
||||||
|
|
||||||
enqueue(buildEnvelope('session.start', sessionKey));
|
enqueue(buildEnvelope(FRAMEWORK, HOST, 'session.start', sessionKey));
|
||||||
startRun(sessionKey, input);
|
startRun(sessionKey, input);
|
||||||
|
|
||||||
await flush();
|
await flush();
|
||||||
@@ -292,7 +136,7 @@ async function handleSessionEnd(input: Dict) {
|
|||||||
|
|
||||||
endRun(sessionKey, runId, input, duration);
|
endRun(sessionKey, runId, input, duration);
|
||||||
|
|
||||||
enqueue(buildEnvelope('session.end', sessionKey, {
|
enqueue(buildEnvelope(FRAMEWORK, HOST, 'session.end', sessionKey, {
|
||||||
payload: {
|
payload: {
|
||||||
model: getModel(input),
|
model: getModel(input),
|
||||||
...(usage && { usage }),
|
...(usage && { usage }),
|
||||||
@@ -376,14 +220,4 @@ const handler = async () => {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
async function readStdin(): Promise<string> {
|
|
||||||
return new Promise((resolve) => {
|
|
||||||
let data = '';
|
|
||||||
process.stdin.on('data', (chunk) => data += chunk);
|
|
||||||
process.stdin.on('end', () => resolve(data));
|
|
||||||
process.stdin.on('error', () => resolve(''));
|
|
||||||
setTimeout(() => resolve(data), 100);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
handler();
|
handler();
|
||||||
|
|||||||
+19
-185
@@ -1,69 +1,26 @@
|
|||||||
#!/usr/bin/env node
|
#!/usr/bin/env node
|
||||||
import { randomUUID } from 'node:crypto';
|
import { randomUUID } from 'node:crypto';
|
||||||
import { hostname } from 'node:os';
|
import { hostname } from 'node:os';
|
||||||
|
import {
|
||||||
|
type Dict,
|
||||||
|
isRecord,
|
||||||
|
pickString,
|
||||||
|
pickNumber,
|
||||||
|
truncate,
|
||||||
|
buildEnvelope,
|
||||||
|
createTransport,
|
||||||
|
readStdin,
|
||||||
|
} from '../shared/lib';
|
||||||
|
|
||||||
const INGEST_URL = process.env.AGENTMON_INGEST_URL || 'http://localhost:8080';
|
const INGEST_URL = process.env.AGENTMON_INGEST_URL || 'http://localhost:8080';
|
||||||
const FRAMEWORK = process.env.AGENTMON_FRAMEWORK || 'copilot';
|
const FRAMEWORK = process.env.AGENTMON_FRAMEWORK || 'copilot';
|
||||||
const HOST = process.env.AGENTMON_HOST || hostname();
|
const HOST = process.env.AGENTMON_HOST || hostname();
|
||||||
const BATCH_SIZE = 10;
|
|
||||||
const FLUSH_MS = 2000;
|
|
||||||
const FETCH_TIMEOUT_MS = 500;
|
|
||||||
|
|
||||||
interface Dict { [key: string]: any }
|
const { enqueue, flush } = createTransport(INGEST_URL);
|
||||||
|
|
||||||
let buffer: Dict[] = [];
|
|
||||||
let flushTimer: ReturnType<typeof setTimeout> | null = null;
|
|
||||||
let isFlushing = false;
|
|
||||||
|
|
||||||
const activeRuns = new Map<string, string>();
|
const activeRuns = new Map<string, string>();
|
||||||
const activeSpans = new Map<string, string>();
|
const activeSpans = 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 getSessionKey(input: Dict): string | undefined {
|
function getSessionKey(input: Dict): string | undefined {
|
||||||
return pickString(
|
return pickString(
|
||||||
input.sessionId,
|
input.sessionId,
|
||||||
@@ -90,127 +47,14 @@ function getUsage(input: Dict): Dict | undefined {
|
|||||||
return Object.keys(result).length > 0 ? result : undefined;
|
return Object.keys(result).length > 0 ? result : 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: FRAMEWORK,
|
|
||||||
client_id: HOST,
|
|
||||||
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;
|
|
||||||
}
|
|
||||||
|
|
||||||
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();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async function handleSessionStart(input: Dict) {
|
async function handleSessionStart(input: Dict) {
|
||||||
const sessionKey = getSessionKey(input) || randomUUID();
|
const sessionKey = getSessionKey(input) || randomUUID();
|
||||||
const runId = randomUUID();
|
const runId = randomUUID();
|
||||||
activeRuns.set(sessionKey, runId);
|
activeRuns.set(sessionKey, runId);
|
||||||
|
|
||||||
enqueue(buildEnvelope('session.start', sessionKey));
|
enqueue(buildEnvelope(FRAMEWORK, HOST, 'session.start', sessionKey));
|
||||||
|
|
||||||
enqueue(buildEnvelope('run.start', sessionKey, {
|
enqueue(buildEnvelope(FRAMEWORK, HOST, 'run.start', sessionKey, {
|
||||||
runId,
|
runId,
|
||||||
payload: {
|
payload: {
|
||||||
prompt_preview: truncate(input.prompt, 200),
|
prompt_preview: truncate(input.prompt, 200),
|
||||||
@@ -227,7 +71,7 @@ async function handleSessionEnd(input: Dict) {
|
|||||||
const duration = pickNumber(input.duration_ms, input.elapsed_ms);
|
const duration = pickNumber(input.duration_ms, input.elapsed_ms);
|
||||||
|
|
||||||
if (runId) {
|
if (runId) {
|
||||||
enqueue(buildEnvelope('run.end', sessionKey, {
|
enqueue(buildEnvelope(FRAMEWORK, HOST, 'run.end', sessionKey, {
|
||||||
runId,
|
runId,
|
||||||
payload: {
|
payload: {
|
||||||
status: 'success',
|
status: 'success',
|
||||||
@@ -237,7 +81,7 @@ async function handleSessionEnd(input: Dict) {
|
|||||||
}));
|
}));
|
||||||
}
|
}
|
||||||
|
|
||||||
enqueue(buildEnvelope('session.end', sessionKey, {
|
enqueue(buildEnvelope(FRAMEWORK, HOST, 'session.end', sessionKey, {
|
||||||
payload: usage ? { usage } : undefined,
|
payload: usage ? { usage } : undefined,
|
||||||
}));
|
}));
|
||||||
|
|
||||||
@@ -252,7 +96,7 @@ async function handlePromptSubmit(input: Dict) {
|
|||||||
const prompt = pickString(input.prompt, input.text, input.message);
|
const prompt = pickString(input.prompt, input.text, input.message);
|
||||||
|
|
||||||
if (runId && prompt) {
|
if (runId && prompt) {
|
||||||
enqueue(buildEnvelope('run.end', sessionKey, {
|
enqueue(buildEnvelope(FRAMEWORK, HOST, 'run.end', sessionKey, {
|
||||||
runId,
|
runId,
|
||||||
payload: {
|
payload: {
|
||||||
status: 'success',
|
status: 'success',
|
||||||
@@ -266,7 +110,7 @@ async function handlePromptSubmit(input: Dict) {
|
|||||||
activeRuns.set(sessionKey, newRunId);
|
activeRuns.set(sessionKey, newRunId);
|
||||||
}
|
}
|
||||||
|
|
||||||
enqueue(buildEnvelope('run.start', sessionKey, {
|
enqueue(buildEnvelope(FRAMEWORK, HOST, 'run.start', sessionKey, {
|
||||||
runId: newRunId,
|
runId: newRunId,
|
||||||
payload: {
|
payload: {
|
||||||
prompt_preview: truncate(prompt, 200),
|
prompt_preview: truncate(prompt, 200),
|
||||||
@@ -287,7 +131,7 @@ async function handleToolStart(input: Dict) {
|
|||||||
activeSpans.set(sessionKey + ':' + toolName, spanId);
|
activeSpans.set(sessionKey + ':' + toolName, spanId);
|
||||||
}
|
}
|
||||||
|
|
||||||
enqueue(buildEnvelope('span.start', sessionKey, {
|
enqueue(buildEnvelope(FRAMEWORK, HOST, 'span.start', sessionKey, {
|
||||||
runId,
|
runId,
|
||||||
spanId,
|
spanId,
|
||||||
attributes: {
|
attributes: {
|
||||||
@@ -313,7 +157,7 @@ async function handleToolEnd(input: Dict) {
|
|||||||
const duration = pickNumber(input.duration_ms, input.elapsed_ms);
|
const duration = pickNumber(input.duration_ms, input.elapsed_ms);
|
||||||
const usage = getUsage(input);
|
const usage = getUsage(input);
|
||||||
|
|
||||||
enqueue(buildEnvelope('span.end', sessionKey, {
|
enqueue(buildEnvelope(FRAMEWORK, HOST, 'span.end', sessionKey, {
|
||||||
runId,
|
runId,
|
||||||
spanId,
|
spanId,
|
||||||
attributes: {
|
attributes: {
|
||||||
@@ -371,14 +215,4 @@ const handler = async () => {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
async function readStdin(): Promise<string> {
|
|
||||||
return new Promise((resolve) => {
|
|
||||||
let data = '';
|
|
||||||
process.stdin.on('data', (chunk) => data += chunk);
|
|
||||||
process.stdin.on('end', () => resolve(data));
|
|
||||||
process.stdin.on('error', () => resolve(''));
|
|
||||||
setTimeout(() => resolve(data), 100);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
handler();
|
handler();
|
||||||
|
|||||||
+18
-183
@@ -2,68 +2,26 @@
|
|||||||
import { randomUUID } from 'node:crypto';
|
import { randomUUID } from 'node:crypto';
|
||||||
import { hostname } from 'node:os';
|
import { hostname } from 'node:os';
|
||||||
|
|
||||||
|
import {
|
||||||
|
Dict,
|
||||||
|
isRecord,
|
||||||
|
pickString,
|
||||||
|
pickNumber,
|
||||||
|
truncate,
|
||||||
|
buildEnvelope,
|
||||||
|
createTransport,
|
||||||
|
readStdin,
|
||||||
|
} from '../shared/lib';
|
||||||
|
|
||||||
const INGEST_URL = process.env.AGENTMON_INGEST_URL || 'http://localhost:8080';
|
const INGEST_URL = process.env.AGENTMON_INGEST_URL || 'http://localhost:8080';
|
||||||
const FRAMEWORK = process.env.AGENTMON_FRAMEWORK || 'gemini';
|
const FRAMEWORK = process.env.AGENTMON_FRAMEWORK || 'gemini';
|
||||||
const HOST = process.env.AGENTMON_HOST || hostname();
|
const HOST = process.env.AGENTMON_HOST || hostname();
|
||||||
const BATCH_SIZE = 10;
|
|
||||||
const FLUSH_MS = 2000;
|
|
||||||
const FETCH_TIMEOUT_MS = 500;
|
|
||||||
|
|
||||||
interface Dict { [key: string]: any }
|
const { enqueue, flush } = createTransport(INGEST_URL);
|
||||||
|
|
||||||
let buffer: Dict[] = [];
|
|
||||||
let flushTimer: ReturnType<typeof setTimeout> | null = null;
|
|
||||||
let isFlushing = false;
|
|
||||||
|
|
||||||
const activeRuns = new Map<string, string>();
|
const activeRuns = new Map<string, string>();
|
||||||
const activeSpans = new Map<string, string>();
|
const activeSpans = 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 getSessionKey(input: Dict): string | undefined {
|
function getSessionKey(input: Dict): string | undefined {
|
||||||
return pickString(
|
return pickString(
|
||||||
input.sessionId,
|
input.sessionId,
|
||||||
@@ -89,127 +47,14 @@ function getUsage(input: Dict): Dict | undefined {
|
|||||||
return Object.keys(result).length > 0 ? result : undefined;
|
return Object.keys(result).length > 0 ? result : 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: FRAMEWORK,
|
|
||||||
client_id: HOST,
|
|
||||||
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;
|
|
||||||
}
|
|
||||||
|
|
||||||
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();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async function handleSessionStart(input: Dict) {
|
async function handleSessionStart(input: Dict) {
|
||||||
const sessionKey = getSessionKey(input) || randomUUID();
|
const sessionKey = getSessionKey(input) || randomUUID();
|
||||||
const runId = randomUUID();
|
const runId = randomUUID();
|
||||||
activeRuns.set(sessionKey, runId);
|
activeRuns.set(sessionKey, runId);
|
||||||
|
|
||||||
enqueue(buildEnvelope('session.start', sessionKey));
|
enqueue(buildEnvelope(FRAMEWORK, HOST, 'session.start', sessionKey));
|
||||||
|
|
||||||
enqueue(buildEnvelope('run.start', sessionKey, {
|
enqueue(buildEnvelope(FRAMEWORK, HOST, 'run.start', sessionKey, {
|
||||||
runId,
|
runId,
|
||||||
payload: {
|
payload: {
|
||||||
prompt_preview: truncate(input.prompt, 200),
|
prompt_preview: truncate(input.prompt, 200),
|
||||||
@@ -226,7 +71,7 @@ async function handleSessionEnd(input: Dict) {
|
|||||||
const duration = pickNumber(input.duration_ms, input.elapsed_ms);
|
const duration = pickNumber(input.duration_ms, input.elapsed_ms);
|
||||||
|
|
||||||
if (runId) {
|
if (runId) {
|
||||||
enqueue(buildEnvelope('run.end', sessionKey, {
|
enqueue(buildEnvelope(FRAMEWORK, HOST, 'run.end', sessionKey, {
|
||||||
runId,
|
runId,
|
||||||
payload: {
|
payload: {
|
||||||
status: 'success',
|
status: 'success',
|
||||||
@@ -236,7 +81,7 @@ async function handleSessionEnd(input: Dict) {
|
|||||||
}));
|
}));
|
||||||
}
|
}
|
||||||
|
|
||||||
enqueue(buildEnvelope('session.end', sessionKey, {
|
enqueue(buildEnvelope(FRAMEWORK, HOST, 'session.end', sessionKey, {
|
||||||
payload: usage ? { usage } : undefined,
|
payload: usage ? { usage } : undefined,
|
||||||
}));
|
}));
|
||||||
|
|
||||||
@@ -256,7 +101,7 @@ async function handleToolCall(input: Dict) {
|
|||||||
activeSpans.set(sessionKey + ':' + toolName, spanId);
|
activeSpans.set(sessionKey + ':' + toolName, spanId);
|
||||||
}
|
}
|
||||||
|
|
||||||
enqueue(buildEnvelope('span.start', sessionKey, {
|
enqueue(buildEnvelope(FRAMEWORK, HOST, 'span.start', sessionKey, {
|
||||||
runId,
|
runId,
|
||||||
spanId,
|
spanId,
|
||||||
attributes: {
|
attributes: {
|
||||||
@@ -282,7 +127,7 @@ async function handleToolResult(input: Dict) {
|
|||||||
const duration = pickNumber(input.duration_ms, input.elapsed_ms);
|
const duration = pickNumber(input.duration_ms, input.elapsed_ms);
|
||||||
const usage = getUsage(input);
|
const usage = getUsage(input);
|
||||||
|
|
||||||
enqueue(buildEnvelope('span.end', sessionKey, {
|
enqueue(buildEnvelope(FRAMEWORK, HOST, 'span.end', sessionKey, {
|
||||||
runId,
|
runId,
|
||||||
spanId,
|
spanId,
|
||||||
attributes: {
|
attributes: {
|
||||||
@@ -337,14 +182,4 @@ const handler = async () => {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
async function readStdin(): Promise<string> {
|
|
||||||
return new Promise((resolve) => {
|
|
||||||
let data = '';
|
|
||||||
process.stdin.on('data', (chunk) => data += chunk);
|
|
||||||
process.stdin.on('end', () => resolve(data));
|
|
||||||
process.stdin.on('error', () => resolve(''));
|
|
||||||
setTimeout(() => resolve(data), 100);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
handler();
|
handler();
|
||||||
|
|||||||
Generated
+1
-1
@@ -8,7 +8,7 @@
|
|||||||
"name": "@anthropic-ai/agentmon-gemini",
|
"name": "@anthropic-ai/agentmon-gemini",
|
||||||
"version": "1.0.0",
|
"version": "1.0.0",
|
||||||
"bin": {
|
"bin": {
|
||||||
"agentmon-handler": "handler.js"
|
"agentmon-gemini-handler": "handler.js"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"esbuild": "^0.20.0",
|
"esbuild": "^0.20.0",
|
||||||
|
|||||||
@@ -5,7 +5,7 @@
|
|||||||
"main": "handler.js",
|
"main": "handler.js",
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"bin": {
|
"bin": {
|
||||||
"agentmon-handler": "./handler.js"
|
"agentmon-gemini-handler": "./handler.js"
|
||||||
},
|
},
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"build": "npx esbuild handler.ts --platform=node --format=esm --outfile=handler.js"
|
"build": "npx esbuild handler.ts --platform=node --format=esm --outfile=handler.js"
|
||||||
|
|||||||
+52
-13
@@ -1,21 +1,50 @@
|
|||||||
import { Plugin } from "@opencode-ai/plugin";
|
import { Plugin } from "@opencode-ai/plugin";
|
||||||
|
import { hostname } from "node:os";
|
||||||
|
|
||||||
const INGEST_URL = process.env.AGENTMON_INGEST_URL || "http://localhost:8080";
|
const INGEST_URL = process.env.AGENTMON_INGEST_URL || "http://localhost:8080";
|
||||||
|
const FETCH_TIMEOUT_MS = 500;
|
||||||
|
|
||||||
let buffer: any[] = [];
|
let buffer: any[] = [];
|
||||||
let flushTimer: NodeJS.Timeout | null = null;
|
let flushTimer: ReturnType<typeof setTimeout> | null = null;
|
||||||
|
let isFlushing = false;
|
||||||
const BATCH_SIZE = 10;
|
const BATCH_SIZE = 10;
|
||||||
const FLUSH_MS = 2000;
|
const FLUSH_MS = 2000;
|
||||||
|
|
||||||
let currentSessionId: string | undefined;
|
let currentSessionId: string | undefined;
|
||||||
let currentRunId: string | undefined;
|
let currentRunId: string | undefined;
|
||||||
|
|
||||||
|
const activeSpans = new Map<string, string>();
|
||||||
|
|
||||||
|
function scheduleFlush() {
|
||||||
|
if (!flushTimer) {
|
||||||
|
flushTimer = setTimeout(() => {
|
||||||
|
void flush();
|
||||||
|
}, FLUSH_MS);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
function enqueue(event: any) {
|
function enqueue(event: any) {
|
||||||
buffer.push(event);
|
buffer.push(event);
|
||||||
if (buffer.length >= BATCH_SIZE) {
|
if (buffer.length >= BATCH_SIZE) {
|
||||||
flush();
|
void flush();
|
||||||
} else if (!flushTimer) {
|
} else {
|
||||||
flushTimer = setTimeout(flush, FLUSH_MS);
|
scheduleFlush();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function postBatch(batch: any[]) {
|
||||||
|
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);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -24,17 +53,24 @@ async function flush() {
|
|||||||
clearTimeout(flushTimer);
|
clearTimeout(flushTimer);
|
||||||
flushTimer = null;
|
flushTimer = null;
|
||||||
}
|
}
|
||||||
if (buffer.length === 0) return;
|
if (isFlushing || buffer.length === 0) return;
|
||||||
|
|
||||||
|
isFlushing = true;
|
||||||
const batch = buffer.splice(0, BATCH_SIZE);
|
const batch = buffer.splice(0, BATCH_SIZE);
|
||||||
|
|
||||||
try {
|
try {
|
||||||
await fetch(`${INGEST_URL}/v1/events`, {
|
await postBatch(batch);
|
||||||
method: "POST",
|
} catch {
|
||||||
headers: { "Content-Type": "application/json" },
|
|
||||||
body: JSON.stringify(batch),
|
|
||||||
});
|
|
||||||
} catch (e) {
|
|
||||||
console.debug("[agentmon] failed to flush events");
|
console.debug("[agentmon] failed to flush events");
|
||||||
|
} finally {
|
||||||
|
isFlushing = false;
|
||||||
|
if (buffer.length > 0) {
|
||||||
|
if (buffer.length >= BATCH_SIZE) {
|
||||||
|
void flush();
|
||||||
|
} else {
|
||||||
|
scheduleFlush();
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -48,7 +84,7 @@ function buildEnvelope(type: string, data: any) {
|
|||||||
source: {
|
source: {
|
||||||
framework: "opencode",
|
framework: "opencode",
|
||||||
client_id: "opencode",
|
client_id: "opencode",
|
||||||
host: require("os").hostname(),
|
host: hostname(),
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
...(data.correlation && { correlation: data.correlation }),
|
...(data.correlation && { correlation: data.correlation }),
|
||||||
@@ -74,6 +110,7 @@ export const agentmon: Plugin = async (input) => {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const spanId = crypto.randomUUID();
|
const spanId = crypto.randomUUID();
|
||||||
|
activeSpans.set(data.tool, spanId);
|
||||||
enqueue(buildEnvelope("span.start", {
|
enqueue(buildEnvelope("span.start", {
|
||||||
correlation: { session_id: currentSessionId, run_id: currentRunId, span_id: spanId },
|
correlation: { session_id: currentSessionId, run_id: currentRunId, span_id: spanId },
|
||||||
attributes: { span_kind: "tool", name: data.tool },
|
attributes: { span_kind: "tool", name: data.tool },
|
||||||
@@ -84,8 +121,10 @@ export const agentmon: Plugin = async (input) => {
|
|||||||
"tool.execute.after": async (data: any) => {
|
"tool.execute.after": async (data: any) => {
|
||||||
if (!currentSessionId || !currentRunId) return;
|
if (!currentSessionId || !currentRunId) return;
|
||||||
|
|
||||||
|
const spanId = activeSpans.get(data.tool);
|
||||||
|
activeSpans.delete(data.tool);
|
||||||
enqueue(buildEnvelope("span.end", {
|
enqueue(buildEnvelope("span.end", {
|
||||||
correlation: { session_id: currentSessionId, run_id: currentRunId },
|
correlation: { session_id: currentSessionId, run_id: currentRunId, ...(spanId && { span_id: spanId }) },
|
||||||
attributes: { span_kind: "tool", name: data.tool },
|
attributes: { span_kind: "tool", name: data.tool },
|
||||||
payload: {
|
payload: {
|
||||||
status: data.error ? "error" : "success",
|
status: data.error ? "error" : "success",
|
||||||
|
|||||||
@@ -0,0 +1,196 @@
|
|||||||
|
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(''));
|
||||||
|
});
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user