503 lines
13 KiB
JavaScript
Executable File
503 lines
13 KiB
JavaScript
Executable File
#!/usr/bin/env node
|
|
|
|
// handler.ts
|
|
import { randomUUID as randomUUID2 } from "node:crypto";
|
|
import { mkdirSync, readFileSync, unlinkSync, writeFileSync } from "node:fs";
|
|
import { homedir, hostname } from "node:os";
|
|
import { join } from "node:path";
|
|
|
|
// ../shared/lib.ts
|
|
import { randomUUID } from "node:crypto";
|
|
function isRecord(value) {
|
|
return value !== null && typeof value === "object" && !Array.isArray(value);
|
|
}
|
|
function pickString(...values) {
|
|
for (const value of values) {
|
|
if (typeof value === "string" && value.trim() !== "") {
|
|
return value;
|
|
}
|
|
}
|
|
return void 0;
|
|
}
|
|
function pickNumber(...values) {
|
|
for (const value of values) {
|
|
if (typeof value === "number" && Number.isFinite(value)) {
|
|
return value;
|
|
}
|
|
}
|
|
return void 0;
|
|
}
|
|
function truncate(value, limit) {
|
|
if (value === void 0 || value === null) {
|
|
return void 0;
|
|
}
|
|
const text = typeof value === "string" ? value : safeJSONStringify(value);
|
|
if (!text) {
|
|
return void 0;
|
|
}
|
|
if (text.length <= limit) {
|
|
return text;
|
|
}
|
|
return text.slice(0, limit) + "...";
|
|
}
|
|
function safeJSONStringify(value) {
|
|
try {
|
|
return JSON.stringify(value);
|
|
} catch {
|
|
return String(value);
|
|
}
|
|
}
|
|
function buildEnvelope(framework, host, type, sessionKey, opts = {}) {
|
|
const correlation = {};
|
|
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 = {
|
|
schema: { name: "agentmon.event", version: 1 },
|
|
event: {
|
|
id: randomUUID(),
|
|
type,
|
|
ts: (/* @__PURE__ */ 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;
|
|
}
|
|
function createTransport(ingestUrl, opts) {
|
|
const batchSize = opts?.batchSize ?? 10;
|
|
const flushMs = opts?.flushMs ?? 2e3;
|
|
const fetchTimeoutMs = opts?.fetchTimeoutMs ?? 500;
|
|
let buffer = [];
|
|
let flushTimer = null;
|
|
let isFlushing = false;
|
|
async function postBatch(batch) {
|
|
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 flush2();
|
|
}, flushMs);
|
|
}
|
|
}
|
|
async function flush2() {
|
|
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 flush2();
|
|
} else {
|
|
scheduleFlush();
|
|
}
|
|
}
|
|
}
|
|
}
|
|
function enqueue2(event) {
|
|
buffer.push(event);
|
|
if (buffer.length >= batchSize) {
|
|
void flush2();
|
|
} else {
|
|
scheduleFlush();
|
|
}
|
|
}
|
|
return { enqueue: enqueue2, flush: flush2 };
|
|
}
|
|
async function readStdin() {
|
|
return new Promise((resolve) => {
|
|
let data = "";
|
|
let done = false;
|
|
const timer = setTimeout(() => finish(data), 100);
|
|
const finish = (value) => {
|
|
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(""));
|
|
});
|
|
}
|
|
|
|
// handler.ts
|
|
var INGEST_URL = process.env.AGENTMON_INGEST_URL || "http://localhost:8080";
|
|
var FRAMEWORK = process.env.AGENTMON_FRAMEWORK || "codex";
|
|
var HOST = process.env.AGENTMON_HOST || hostname();
|
|
var { enqueue, flush } = createTransport(INGEST_URL);
|
|
var STATE_DIR = join(homedir(), ".agentmon-state", "codex");
|
|
function ensureStateDir() {
|
|
try {
|
|
mkdirSync(STATE_DIR, { recursive: true });
|
|
} catch {
|
|
}
|
|
}
|
|
function loadState(sessionKey) {
|
|
try {
|
|
const raw = readFileSync(join(STATE_DIR, sessionKey + ".json"), "utf8");
|
|
return JSON.parse(raw);
|
|
} catch {
|
|
return {};
|
|
}
|
|
}
|
|
function saveState(sessionKey, state) {
|
|
ensureStateDir();
|
|
try {
|
|
writeFileSync(join(STATE_DIR, sessionKey + ".json"), JSON.stringify(state), "utf8");
|
|
} catch {
|
|
}
|
|
}
|
|
function clearState(sessionKey) {
|
|
try {
|
|
unlinkSync(join(STATE_DIR, sessionKey + ".json"));
|
|
} catch {
|
|
}
|
|
}
|
|
function getContext(input) {
|
|
return isRecord(input.context) ? input.context : {};
|
|
}
|
|
function getSessionRecord(input) {
|
|
return isRecord(input.session) ? input.session : {};
|
|
}
|
|
function getConversationRecord(input) {
|
|
return isRecord(input.conversation) ? input.conversation : {};
|
|
}
|
|
function getSessionKey(input) {
|
|
const context = getContext(input);
|
|
const session = getSessionRecord(input);
|
|
const conversation = getConversationRecord(input);
|
|
return pickString(
|
|
input.id,
|
|
input.session,
|
|
input.sessionId,
|
|
input.session_id,
|
|
input.sessionID,
|
|
input.threadId,
|
|
input.thread_id,
|
|
input.threadID,
|
|
input.chatId,
|
|
input.chat_id,
|
|
input.conversationId,
|
|
input.conversation_id,
|
|
context.id,
|
|
context.session,
|
|
context.sessionKey,
|
|
context.sessionId,
|
|
context.session_id,
|
|
context.threadId,
|
|
context.thread_id,
|
|
context.conversationId,
|
|
context.conversation_id,
|
|
session.id,
|
|
session.key,
|
|
session.sessionId,
|
|
session.session_id,
|
|
conversation.id,
|
|
conversation.sessionId,
|
|
conversation.session_id,
|
|
conversation.conversationId,
|
|
conversation.conversation_id
|
|
);
|
|
}
|
|
function getUsage(input) {
|
|
const context = getContext(input);
|
|
const usage = isRecord(input.usage) ? input.usage : isRecord(input.llm) ? input.llm : isRecord(input.tokens) ? input.tokens : isRecord(input.llm_usage) ? input.llm_usage : isRecord(context.usage) ? context.usage : isRecord(context.llm) ? context.llm : isRecord(context.tokens) ? context.tokens : isRecord(context.llm_usage) ? context.llm_usage : void 0;
|
|
if (!usage)
|
|
return void 0;
|
|
const result = {};
|
|
if (usage.input_tokens !== void 0)
|
|
result.input_tokens = usage.input_tokens;
|
|
if (usage.prompt_tokens !== void 0)
|
|
result.input_tokens = usage.prompt_tokens;
|
|
if (usage.input !== void 0)
|
|
result.input_tokens = usage.input;
|
|
if (usage.output_tokens !== void 0)
|
|
result.output_tokens = usage.output_tokens;
|
|
if (usage.completion_tokens !== void 0)
|
|
result.output_tokens = usage.completion_tokens;
|
|
if (usage.output !== void 0)
|
|
result.output_tokens = usage.output;
|
|
if (usage.total_tokens !== void 0)
|
|
result.total_tokens = usage.total_tokens;
|
|
if (usage.total !== void 0)
|
|
result.total_tokens = usage.total;
|
|
if (usage.cost !== void 0)
|
|
result.total_cost = usage.cost;
|
|
if (usage.total_cost !== void 0)
|
|
result.total_cost = usage.total_cost;
|
|
return Object.keys(result).length > 0 ? result : void 0;
|
|
}
|
|
function getModel(input) {
|
|
const context = getContext(input);
|
|
return pickString(
|
|
input.model,
|
|
isRecord(input.llm) ? input.llm.model : void 0,
|
|
isRecord(input.usage) ? input.usage.model : void 0,
|
|
context.model,
|
|
isRecord(context.llm) ? context.llm.model : void 0,
|
|
isRecord(context.usage) ? context.usage.model : void 0
|
|
);
|
|
}
|
|
function getPrompt(input) {
|
|
const context = getContext(input);
|
|
return pickString(
|
|
input.prompt,
|
|
input.text,
|
|
input.message,
|
|
context.prompt,
|
|
context.text,
|
|
context.message
|
|
);
|
|
}
|
|
function getDuration(input) {
|
|
const context = getContext(input);
|
|
return pickNumber(
|
|
input.duration_ms,
|
|
input.elapsed_ms,
|
|
input.duration,
|
|
context.duration_ms,
|
|
context.elapsed_ms,
|
|
context.duration
|
|
);
|
|
}
|
|
function getNotificationType(input) {
|
|
const context = getContext(input);
|
|
return pickString(
|
|
input.type,
|
|
input.notification_type,
|
|
input.event,
|
|
input.event_type,
|
|
context.type,
|
|
context.notification_type,
|
|
context.event,
|
|
context.event_type
|
|
);
|
|
}
|
|
function saveSessionState(sessionKey, state) {
|
|
if (!sessionKey) {
|
|
return;
|
|
}
|
|
saveState(sessionKey, state);
|
|
}
|
|
function ensureSessionStarted(sessionKey, input, state) {
|
|
if (!sessionKey || state.sessionStarted) {
|
|
return state;
|
|
}
|
|
enqueue(buildEnvelope(FRAMEWORK, HOST, "session.start", sessionKey, {
|
|
attributes: {
|
|
synthetic: true,
|
|
recovered_from: "codex-hook"
|
|
}
|
|
}));
|
|
state.sessionStarted = true;
|
|
saveSessionState(sessionKey, state);
|
|
return state;
|
|
}
|
|
function enqueueMetricSnapshot(sessionKey, runId, usage, input) {
|
|
if (!usage) {
|
|
return;
|
|
}
|
|
const metrics = { usage };
|
|
const model = getModel(input);
|
|
if (model) {
|
|
metrics.model = model;
|
|
}
|
|
enqueue(buildEnvelope(FRAMEWORK, HOST, "metric.snapshot", sessionKey, {
|
|
runId,
|
|
payload: { metrics }
|
|
}));
|
|
}
|
|
function startRun(sessionKey, input, state, synthetic = false) {
|
|
ensureSessionStarted(sessionKey, input, state);
|
|
const runId = randomUUID2();
|
|
if (sessionKey) {
|
|
state.runId = runId;
|
|
saveSessionState(sessionKey, state);
|
|
}
|
|
enqueue(buildEnvelope(FRAMEWORK, HOST, "run.start", sessionKey, {
|
|
runId,
|
|
attributes: {
|
|
trigger: pickString(input.trigger_type, input.trigger, input.event, input.event_type),
|
|
...synthetic && { synthetic: true }
|
|
},
|
|
payload: {
|
|
prompt_preview: truncate(getPrompt(input), 200)
|
|
}
|
|
}));
|
|
return runId;
|
|
}
|
|
function ensureRunStarted(sessionKey, input, state) {
|
|
if (!sessionKey) {
|
|
return void 0;
|
|
}
|
|
if (state.runId) {
|
|
return state.runId;
|
|
}
|
|
return startRun(sessionKey, input, state, true);
|
|
}
|
|
function endRun(sessionKey, state, input, duration) {
|
|
const runId = state.runId;
|
|
if (!runId) {
|
|
return;
|
|
}
|
|
const usage = getUsage(input);
|
|
enqueue(buildEnvelope(FRAMEWORK, HOST, "run.end", sessionKey, {
|
|
runId,
|
|
payload: {
|
|
status: "success",
|
|
duration_ms: duration,
|
|
model: getModel(input),
|
|
...usage && { usage }
|
|
}
|
|
}));
|
|
enqueueMetricSnapshot(sessionKey, runId, usage, input);
|
|
state.runId = void 0;
|
|
saveSessionState(sessionKey, state);
|
|
}
|
|
async function handleSessionStart(input) {
|
|
const sessionKey = getSessionKey(input) || randomUUID2();
|
|
const state = loadState(sessionKey);
|
|
if (!state.sessionStarted) {
|
|
enqueue(buildEnvelope(FRAMEWORK, HOST, "session.start", sessionKey));
|
|
state.sessionStarted = true;
|
|
}
|
|
startRun(sessionKey, input, state);
|
|
await flush();
|
|
}
|
|
async function handleSessionEnd(input) {
|
|
const sessionKey = getSessionKey(input);
|
|
const state = sessionKey ? loadState(sessionKey) : {};
|
|
const usage = getUsage(input);
|
|
const duration = getDuration(input);
|
|
ensureSessionStarted(sessionKey, input, state);
|
|
if (!state.runId && sessionKey) {
|
|
ensureRunStarted(sessionKey, input, state);
|
|
}
|
|
endRun(sessionKey, state, input, duration);
|
|
enqueue(buildEnvelope(FRAMEWORK, HOST, "session.end", sessionKey, {
|
|
payload: {
|
|
model: getModel(input),
|
|
...usage && { usage }
|
|
}
|
|
}));
|
|
if (sessionKey) {
|
|
clearState(sessionKey);
|
|
}
|
|
await flush();
|
|
}
|
|
async function handlePromptSubmit(input) {
|
|
const sessionKey = getSessionKey(input);
|
|
const state = sessionKey ? loadState(sessionKey) : {};
|
|
const duration = getDuration(input);
|
|
const prompt = getPrompt(input);
|
|
ensureSessionStarted(sessionKey, input, state);
|
|
if (state.runId && prompt) {
|
|
endRun(sessionKey, state, input, duration);
|
|
}
|
|
startRun(sessionKey, input, state, !state.sessionStarted);
|
|
await flush();
|
|
}
|
|
async function handleNotification(input) {
|
|
const sessionKey = getSessionKey(input);
|
|
const state = sessionKey ? loadState(sessionKey) : {};
|
|
const notificationType = getNotificationType(input);
|
|
const usage = getUsage(input);
|
|
const duration = getDuration(input);
|
|
ensureSessionStarted(sessionKey, input, state);
|
|
if (notificationType === "agent-turn-complete" || notificationType === "Done" || notificationType === "turn.complete") {
|
|
if (!state.runId && sessionKey) {
|
|
ensureRunStarted(sessionKey, input, state);
|
|
}
|
|
endRun(sessionKey, state, input, duration);
|
|
if (getPrompt(input)) {
|
|
startRun(sessionKey, input, state);
|
|
}
|
|
} else if (usage) {
|
|
enqueueMetricSnapshot(sessionKey, state.runId, usage, input);
|
|
}
|
|
await flush();
|
|
}
|
|
var handler = async () => {
|
|
const args = process.argv.slice(2);
|
|
const hookType = args[0] || "unknown";
|
|
let input = {};
|
|
try {
|
|
const stdin = await readStdin();
|
|
if (stdin) {
|
|
input = JSON.parse(stdin);
|
|
}
|
|
} catch {
|
|
input = {};
|
|
}
|
|
try {
|
|
switch (hookType) {
|
|
case "start":
|
|
await handleSessionStart(input);
|
|
break;
|
|
case "stop":
|
|
await handleSessionEnd(input);
|
|
break;
|
|
case "prompt":
|
|
case "prompt-submit":
|
|
await handlePromptSubmit(input);
|
|
break;
|
|
case "notification":
|
|
await handleNotification(input);
|
|
break;
|
|
default:
|
|
console.debug(`[agentmon] unknown hook type: ${hookType}`);
|
|
}
|
|
} catch (err) {
|
|
console.debug("[agentmon] handler error:", err);
|
|
}
|
|
};
|
|
handler();
|