feat(hooks): add Hermes telemetry handler

This commit is contained in:
William Valentin
2026-05-20 17:35:56 -07:00
parent 78376bdd83
commit 27d40ce28f
9 changed files with 2452 additions and 0 deletions
+2
View File
@@ -5,5 +5,7 @@
/web-ui
/swarm-monitor
/event-processor
/openclaw-monitor
/hooks/*/node_modules/
/build/
File diff suppressed because it is too large Load Diff
+23
View File
@@ -172,6 +172,7 @@ async function readStdin() {
var INGEST_URL = process.env.AGENTMON_INGEST_URL || "http://localhost:8080";
var FRAMEWORK = process.env.AGENTMON_FRAMEWORK || "claude-code";
var HOST = process.env.AGENTMON_HOST || hostname();
var ALLOW_STARTUP_SESSIONS = process.env.AGENTMON_CLAUDE_ALLOW_STARTUP === "1";
var { enqueue, flush } = createTransport(INGEST_URL);
var STATE_DIR = join(homedir(), ".agentmon-state");
function ensureStateDir() {
@@ -231,6 +232,15 @@ function isNonPersistentClaudeLaunch() {
({ cmd }) => cmd.includes("/claude") && cmd.includes("--no-session-persistence")
);
}
function hasClaudeProcessAncestor() {
return getProcessTree().some(({ cmd }) => {
if (!cmd)
return false;
if (cmd.includes("agentmon-handler") || cmd.includes("/hooks/claude-code/handler"))
return false;
return /(^|[/\s])claude(\s|$)/.test(cmd) || cmd.includes("@anthropic-ai/claude-code");
});
}
var activeRuns = /* @__PURE__ */ new Map();
var activeSpans = /* @__PURE__ */ new Map();
var activeSubagents = /* @__PURE__ */ new Map();
@@ -319,6 +329,10 @@ async function handleSessionStart(input) {
console.error("[agentmon] ignoring claude-code startup from --no-session-persistence launch");
return;
}
if (pickString(input.source) === "startup" && (!ALLOW_STARTUP_SESSIONS || !hasClaudeProcessAncestor())) {
console.error("[agentmon] ignoring claude-code startup session");
return;
}
const runId = randomUUID2();
activeRuns.set(sessionKey, runId);
saveState(sessionKey, { runId, spans: {} });
@@ -388,6 +402,15 @@ async function handlePromptSubmit(input) {
}
}));
}
if (!runId && sessionKey) {
enqueue(buildEnvelope(FRAMEWORK, HOST, "session.start", sessionKey, {
attributes: {
cwd: pickString(input.cwd),
transcript_path: pickString(input.transcript_path),
source: pickString(input.source)
}
}));
}
const newRunId = randomUUID2();
if (sessionKey) {
activeRuns.set(sessionKey, newRunId);
+23
View File
@@ -17,6 +17,7 @@ import {
const INGEST_URL = process.env.AGENTMON_INGEST_URL || 'http://localhost:8080';
const FRAMEWORK = process.env.AGENTMON_FRAMEWORK || 'claude-code';
const HOST = process.env.AGENTMON_HOST || hostname();
const ALLOW_STARTUP_SESSIONS = process.env.AGENTMON_CLAUDE_ALLOW_STARTUP === '1';
const { enqueue, flush } = createTransport(INGEST_URL);
@@ -89,6 +90,14 @@ function isNonPersistentClaudeLaunch() {
cmd.includes('/claude') && cmd.includes('--no-session-persistence')
);
}
function hasClaudeProcessAncestor() {
return getProcessTree().some(({ cmd }) => {
if (!cmd) return false;
if (cmd.includes('agentmon-handler') || cmd.includes('/hooks/claude-code/handler')) return false;
return /(^|[/\s])claude(\s|$)/.test(cmd) || cmd.includes('@anthropic-ai/claude-code');
});
}
// ─────────────────────────────────────────────────────────────────────────────
const activeRuns = new Map<string, string>();
@@ -182,6 +191,10 @@ async function handleSessionStart(input: Dict) {
console.error('[agentmon] ignoring claude-code startup from --no-session-persistence launch');
return;
}
if (pickString(input.source) === 'startup' && (!ALLOW_STARTUP_SESSIONS || !hasClaudeProcessAncestor())) {
console.error('[agentmon] ignoring claude-code startup session');
return;
}
const runId = randomUUID();
activeRuns.set(sessionKey, runId);
@@ -262,6 +275,16 @@ async function handlePromptSubmit(input: Dict) {
}));
}
if (!runId && sessionKey) {
enqueue(buildEnvelope(FRAMEWORK, HOST, 'session.start', sessionKey, {
attributes: {
cwd: pickString(input.cwd),
transcript_path: pickString(input.transcript_path),
source: pickString(input.source),
},
}));
}
const newRunId = randomUUID();
if (sessionKey) {
activeRuns.set(sessionKey, newRunId);
+489
View File
@@ -0,0 +1,489 @@
#!/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 || "hermes";
var HOST = process.env.AGENTMON_HOST || hostname();
var { enqueue, flush } = createTransport(INGEST_URL);
var STATE_DIR = join(homedir(), ".agentmon-state", "hermes");
function ensureStateDir() {
try {
mkdirSync(STATE_DIR, { recursive: true });
} catch {
}
}
function loadState(sessionKey) {
try {
const raw = readFileSync(join(STATE_DIR, sessionKey + ".json"), "utf8");
const state = JSON.parse(raw);
return { spans: {}, ...state };
} catch {
return { spans: {} };
}
}
function saveState(sessionKey, state) {
if (!sessionKey) {
return;
}
ensureStateDir();
try {
writeFileSync(join(STATE_DIR, sessionKey + ".json"), JSON.stringify(state), "utf8");
} catch {
}
}
function clearState(sessionKey) {
if (!sessionKey) {
return;
}
try {
unlinkSync(join(STATE_DIR, sessionKey + ".json"));
} catch {
}
}
function getExtra(input) {
return isRecord(input.extra) ? input.extra : {};
}
function getSessionKey(input) {
const extra = getExtra(input);
return pickString(
input.session_id,
input.sessionId,
input.sessionID,
input.session,
extra.session_id,
extra.sessionId,
extra.sessionID,
extra.parent_session_id,
extra.task_id
);
}
function getToolCallId(input) {
const extra = getExtra(input);
return pickString(input.tool_call_id, extra.tool_call_id, extra.call_id, extra.id);
}
function getToolName(input) {
const extra = getExtra(input);
return pickString(input.tool_name, input.tool, input.name, extra.tool_name, extra.tool, extra.name) || "unknown";
}
function getUsage(input) {
const extra = getExtra(input);
const usage = isRecord(input.usage) ? input.usage : isRecord(extra.usage) ? extra.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.output_tokens !== void 0) result.output_tokens = usage.output_tokens;
if (usage.completion_tokens !== void 0) result.output_tokens = usage.completion_tokens;
if (usage.cache_read_tokens !== void 0) result.cache_read_tokens = usage.cache_read_tokens;
if (usage.cache_write_tokens !== void 0) result.cache_write_tokens = usage.cache_write_tokens;
if (usage.cache_creation_tokens !== void 0) result.cache_write_tokens = usage.cache_creation_tokens;
if (usage.reasoning_tokens !== void 0) result.reasoning_tokens = usage.reasoning_tokens;
if (usage.total_tokens !== void 0) result.total_tokens = usage.total_tokens;
if (usage.total_cost !== void 0) result.total_cost = usage.total_cost;
if (usage.cost !== void 0) result.total_cost = usage.cost;
return Object.keys(result).length > 0 ? result : void 0;
}
function getModel(input) {
const extra = getExtra(input);
return pickString(input.model, extra.model, extra.response_model);
}
function getPlatform(input) {
const extra = getExtra(input);
return pickString(input.platform, extra.platform);
}
function getDuration(input) {
const extra = getExtra(input);
return pickNumber(input.duration_ms, input.elapsed_ms, extra.duration_ms, extra.api_duration, extra.elapsed_ms);
}
function ensureSessionStarted(sessionKey, input, state) {
if (!sessionKey || state.sessionStarted) {
return;
}
enqueue(buildEnvelope(FRAMEWORK, HOST, "session.start", sessionKey, {
attributes: {
synthetic: true,
recovered_from: "hermes-hook",
cwd: pickString(input.cwd),
platform: getPlatform(input),
model: getModel(input)
}
}));
state.sessionStarted = true;
saveState(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, {
attributes: {
cwd: pickString(input.cwd),
platform: getPlatform(input),
model: getModel(input)
}
}));
state.sessionStarted = true;
saveState(sessionKey, state);
}
await flush();
}
async function handleRunStart(input) {
const sessionKey = getSessionKey(input) || randomUUID2();
const state = loadState(sessionKey);
ensureSessionStarted(sessionKey, input, state);
if (state.runId) {
enqueue(buildEnvelope(FRAMEWORK, HOST, "run.end", sessionKey, {
runId: state.runId,
payload: { status: "success" }
}));
}
const runId = randomUUID2();
state.runId = runId;
saveState(sessionKey, state);
const extra = getExtra(input);
enqueue(buildEnvelope(FRAMEWORK, HOST, "run.start", sessionKey, {
runId,
attributes: {
is_first_turn: extra.is_first_turn,
platform: getPlatform(input),
model: getModel(input)
},
payload: {
prompt_preview: truncate(extra.user_message ?? input.user_message, 200)
}
}));
await flush();
}
async function handleRunEnd(input) {
const sessionKey = getSessionKey(input);
if (!sessionKey) {
await flush();
return;
}
const state = loadState(sessionKey);
ensureSessionStarted(sessionKey, input, state);
if (state.runId) {
enqueue(buildEnvelope(FRAMEWORK, HOST, "run.end", sessionKey, {
runId: state.runId,
payload: {
status: "success",
duration_ms: getDuration(input),
model: getModel(input),
response_preview: truncate(getExtra(input).assistant_response, 500)
}
}));
state.runId = void 0;
saveState(sessionKey, state);
}
await flush();
}
async function handleToolStart(input) {
const sessionKey = getSessionKey(input);
const state = sessionKey ? loadState(sessionKey) : { spans: {} };
ensureSessionStarted(sessionKey, input, state);
const toolName = getToolName(input);
const toolCallId = getToolCallId(input);
const spanKey = toolCallId || toolName;
const spanId = randomUUID2();
state.spans[spanKey] = spanId;
saveState(sessionKey, state);
enqueue(buildEnvelope(FRAMEWORK, HOST, "span.start", sessionKey, {
runId: state.runId,
spanId,
attributes: {
span_kind: "tool",
name: toolName,
tool_call_id: toolCallId
},
payload: {
input: truncate(input.tool_input ?? getExtra(input).args, 500)
}
}));
await flush();
}
async function handleToolEnd(input) {
const sessionKey = getSessionKey(input);
const state = sessionKey ? loadState(sessionKey) : { spans: {} };
const toolName = getToolName(input);
const toolCallId = getToolCallId(input);
const spanKey = toolCallId || toolName;
const spanId = state.spans[spanKey];
const extra = getExtra(input);
const result = extra.result ?? input.result;
const resultRecord = isRecord(result) ? result : {};
const success = extra.error === void 0 && resultRecord.error === void 0;
enqueue(buildEnvelope(FRAMEWORK, HOST, "span.end", sessionKey, {
runId: state.runId,
spanId,
attributes: {
span_kind: "tool",
name: toolName,
tool_call_id: toolCallId
},
payload: {
status: success ? "success" : "error",
result_preview: truncate(resultRecord.output ?? resultRecord.error ?? extra.error ?? result, 500),
duration_ms: getDuration(input)
}
}));
delete state.spans[spanKey];
saveState(sessionKey, state);
await flush();
}
async function handleAPIResult(input) {
const sessionKey = getSessionKey(input);
const state = sessionKey ? loadState(sessionKey) : { spans: {} };
const usage = getUsage(input);
if (!usage) {
await flush();
return;
}
enqueue(buildEnvelope(FRAMEWORK, HOST, "metric.snapshot", sessionKey, {
runId: state.runId,
payload: {
metrics: {
usage,
model: getModel(input),
provider: pickString(getExtra(input).provider),
duration_ms: getDuration(input)
}
}
}));
await flush();
}
async function handleSessionEnd(input) {
const sessionKey = getSessionKey(input);
const state = sessionKey ? loadState(sessionKey) : { spans: {} };
if (state.runId) {
enqueue(buildEnvelope(FRAMEWORK, HOST, "run.end", sessionKey, {
runId: state.runId,
payload: {
status: input.interrupted || getExtra(input).interrupted ? "interrupted" : "success",
model: getModel(input)
}
}));
}
enqueue(buildEnvelope(FRAMEWORK, HOST, "session.end", sessionKey, {
payload: {
model: getModel(input),
completed: getExtra(input).completed,
interrupted: getExtra(input).interrupted
}
}));
clearState(sessionKey);
await flush();
}
var handler = async () => {
const hookType = process.argv[2] || "unknown";
let input = {};
try {
const stdin = await readStdin();
if (stdin) {
input = JSON.parse(stdin);
}
} catch {
input = {};
}
try {
switch (hookType) {
case "session-start":
case "start":
await handleSessionStart(input);
break;
case "run-start":
case "pre-llm":
await handleRunStart(input);
break;
case "run-end":
case "post-llm":
await handleRunEnd(input);
break;
case "tool-start":
await handleToolStart(input);
break;
case "tool-end":
await handleToolEnd(input);
break;
case "api-result":
case "post-api":
await handleAPIResult(input);
break;
case "session-end":
case "stop":
await handleSessionEnd(input);
break;
default:
console.debug(`[agentmon] unknown hermes hook type: ${hookType}`);
}
} catch (err) {
console.debug("[agentmon] hermes handler error:", err);
}
};
handler();
+386
View File
@@ -0,0 +1,386 @@
#!/usr/bin/env node
import { randomUUID } from 'node:crypto';
import { mkdirSync, readFileSync, unlinkSync, writeFileSync } from 'node:fs';
import { homedir, hostname } from 'node:os';
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 FRAMEWORK = process.env.AGENTMON_FRAMEWORK || 'hermes';
const HOST = process.env.AGENTMON_HOST || hostname();
const { enqueue, flush } = createTransport(INGEST_URL);
interface SessionState {
sessionStarted?: boolean;
runId?: string;
spans: { [key: string]: string };
}
const STATE_DIR = join(homedir(), '.agentmon-state', 'hermes');
function ensureStateDir() {
try {
mkdirSync(STATE_DIR, { recursive: true });
} catch {
// Hooks should never fail the agent because telemetry state is unavailable.
}
}
function loadState(sessionKey: string): SessionState {
try {
const raw = readFileSync(join(STATE_DIR, sessionKey + '.json'), 'utf8');
const state = JSON.parse(raw) as SessionState;
return { spans: {}, ...state };
} catch {
return { spans: {} };
}
}
function saveState(sessionKey: string | undefined, state: SessionState) {
if (!sessionKey) {
return;
}
ensureStateDir();
try {
writeFileSync(join(STATE_DIR, sessionKey + '.json'), JSON.stringify(state), 'utf8');
} catch {
// Best effort only.
}
}
function clearState(sessionKey: string | undefined) {
if (!sessionKey) {
return;
}
try {
unlinkSync(join(STATE_DIR, sessionKey + '.json'));
} catch {
// Best effort only.
}
}
function getExtra(input: Dict): Dict {
return isRecord(input.extra) ? input.extra : {};
}
function getSessionKey(input: Dict): string | undefined {
const extra = getExtra(input);
return pickString(
input.session_id,
input.sessionId,
input.sessionID,
input.session,
extra.session_id,
extra.sessionId,
extra.sessionID,
extra.parent_session_id,
extra.task_id,
);
}
function getToolCallId(input: Dict): string | undefined {
const extra = getExtra(input);
return pickString(input.tool_call_id, extra.tool_call_id, extra.call_id, extra.id);
}
function getToolName(input: Dict): string {
const extra = getExtra(input);
return pickString(input.tool_name, input.tool, input.name, extra.tool_name, extra.tool, extra.name) || 'unknown';
}
function getUsage(input: Dict): Dict | undefined {
const extra = getExtra(input);
const usage = isRecord(input.usage) ? input.usage :
isRecord(extra.usage) ? extra.usage :
undefined;
if (!usage) return undefined;
const result: Dict = {};
if (usage.input_tokens !== undefined) result.input_tokens = usage.input_tokens;
if (usage.prompt_tokens !== undefined) result.input_tokens = usage.prompt_tokens;
if (usage.output_tokens !== undefined) result.output_tokens = usage.output_tokens;
if (usage.completion_tokens !== undefined) result.output_tokens = usage.completion_tokens;
if (usage.cache_read_tokens !== undefined) result.cache_read_tokens = usage.cache_read_tokens;
if (usage.cache_write_tokens !== undefined) result.cache_write_tokens = usage.cache_write_tokens;
if (usage.cache_creation_tokens !== undefined) result.cache_write_tokens = usage.cache_creation_tokens;
if (usage.reasoning_tokens !== undefined) result.reasoning_tokens = usage.reasoning_tokens;
if (usage.total_tokens !== undefined) result.total_tokens = usage.total_tokens;
if (usage.total_cost !== undefined) result.total_cost = usage.total_cost;
if (usage.cost !== undefined) result.total_cost = usage.cost;
return Object.keys(result).length > 0 ? result : undefined;
}
function getModel(input: Dict): string | undefined {
const extra = getExtra(input);
return pickString(input.model, extra.model, extra.response_model);
}
function getPlatform(input: Dict): string | undefined {
const extra = getExtra(input);
return pickString(input.platform, extra.platform);
}
function getDuration(input: Dict): number | undefined {
const extra = getExtra(input);
return pickNumber(input.duration_ms, input.elapsed_ms, extra.duration_ms, extra.api_duration, extra.elapsed_ms);
}
function ensureSessionStarted(sessionKey: string | undefined, input: Dict, state: SessionState) {
if (!sessionKey || state.sessionStarted) {
return;
}
enqueue(buildEnvelope(FRAMEWORK, HOST, 'session.start', sessionKey, {
attributes: {
synthetic: true,
recovered_from: 'hermes-hook',
cwd: pickString(input.cwd),
platform: getPlatform(input),
model: getModel(input),
},
}));
state.sessionStarted = true;
saveState(sessionKey, state);
}
async function handleSessionStart(input: Dict) {
const sessionKey = getSessionKey(input) || randomUUID();
const state = loadState(sessionKey);
if (!state.sessionStarted) {
enqueue(buildEnvelope(FRAMEWORK, HOST, 'session.start', sessionKey, {
attributes: {
cwd: pickString(input.cwd),
platform: getPlatform(input),
model: getModel(input),
},
}));
state.sessionStarted = true;
saveState(sessionKey, state);
}
await flush();
}
async function handleRunStart(input: Dict) {
const sessionKey = getSessionKey(input) || randomUUID();
const state = loadState(sessionKey);
ensureSessionStarted(sessionKey, input, state);
if (state.runId) {
enqueue(buildEnvelope(FRAMEWORK, HOST, 'run.end', sessionKey, {
runId: state.runId,
payload: { status: 'success' },
}));
}
const runId = randomUUID();
state.runId = runId;
saveState(sessionKey, state);
const extra = getExtra(input);
enqueue(buildEnvelope(FRAMEWORK, HOST, 'run.start', sessionKey, {
runId,
attributes: {
is_first_turn: extra.is_first_turn,
platform: getPlatform(input),
model: getModel(input),
},
payload: {
prompt_preview: truncate(extra.user_message ?? input.user_message, 200),
},
}));
await flush();
}
async function handleRunEnd(input: Dict) {
const sessionKey = getSessionKey(input);
if (!sessionKey) {
await flush();
return;
}
const state = loadState(sessionKey);
ensureSessionStarted(sessionKey, input, state);
if (state.runId) {
enqueue(buildEnvelope(FRAMEWORK, HOST, 'run.end', sessionKey, {
runId: state.runId,
payload: {
status: 'success',
duration_ms: getDuration(input),
model: getModel(input),
response_preview: truncate(getExtra(input).assistant_response, 500),
},
}));
state.runId = undefined;
saveState(sessionKey, state);
}
await flush();
}
async function handleToolStart(input: Dict) {
const sessionKey = getSessionKey(input);
const state = sessionKey ? loadState(sessionKey) : { spans: {} };
ensureSessionStarted(sessionKey, input, state);
const toolName = getToolName(input);
const toolCallId = getToolCallId(input);
const spanKey = toolCallId || toolName;
const spanId = randomUUID();
state.spans[spanKey] = spanId;
saveState(sessionKey, state);
enqueue(buildEnvelope(FRAMEWORK, HOST, 'span.start', sessionKey, {
runId: state.runId,
spanId,
attributes: {
span_kind: 'tool',
name: toolName,
tool_call_id: toolCallId,
},
payload: {
input: truncate(input.tool_input ?? getExtra(input).args, 500),
},
}));
await flush();
}
async function handleToolEnd(input: Dict) {
const sessionKey = getSessionKey(input);
const state = sessionKey ? loadState(sessionKey) : { spans: {} };
const toolName = getToolName(input);
const toolCallId = getToolCallId(input);
const spanKey = toolCallId || toolName;
const spanId = state.spans[spanKey];
const extra = getExtra(input);
const result = extra.result ?? input.result;
const resultRecord = isRecord(result) ? result : {};
const success = extra.error === undefined && resultRecord.error === undefined;
enqueue(buildEnvelope(FRAMEWORK, HOST, 'span.end', sessionKey, {
runId: state.runId,
spanId,
attributes: {
span_kind: 'tool',
name: toolName,
tool_call_id: toolCallId,
},
payload: {
status: success ? 'success' : 'error',
result_preview: truncate(resultRecord.output ?? resultRecord.error ?? extra.error ?? result, 500),
duration_ms: getDuration(input),
},
}));
delete state.spans[spanKey];
saveState(sessionKey, state);
await flush();
}
async function handleAPIResult(input: Dict) {
const sessionKey = getSessionKey(input);
const state = sessionKey ? loadState(sessionKey) : { spans: {} };
const usage = getUsage(input);
if (!usage) {
await flush();
return;
}
enqueue(buildEnvelope(FRAMEWORK, HOST, 'metric.snapshot', sessionKey, {
runId: state.runId,
payload: {
metrics: {
usage,
model: getModel(input),
provider: pickString(getExtra(input).provider),
duration_ms: getDuration(input),
},
},
}));
await flush();
}
async function handleSessionEnd(input: Dict) {
const sessionKey = getSessionKey(input);
const state = sessionKey ? loadState(sessionKey) : { spans: {} };
if (state.runId) {
enqueue(buildEnvelope(FRAMEWORK, HOST, 'run.end', sessionKey, {
runId: state.runId,
payload: {
status: input.interrupted || getExtra(input).interrupted ? 'interrupted' : 'success',
model: getModel(input),
},
}));
}
enqueue(buildEnvelope(FRAMEWORK, HOST, 'session.end', sessionKey, {
payload: {
model: getModel(input),
completed: getExtra(input).completed,
interrupted: getExtra(input).interrupted,
},
}));
clearState(sessionKey);
await flush();
}
const handler = async () => {
const hookType = process.argv[2] || 'unknown';
let input: Dict = {};
try {
const stdin = await readStdin();
if (stdin) {
input = JSON.parse(stdin);
}
} catch {
input = {};
}
try {
switch (hookType) {
case 'session-start':
case 'start':
await handleSessionStart(input);
break;
case 'run-start':
case 'pre-llm':
await handleRunStart(input);
break;
case 'run-end':
case 'post-llm':
await handleRunEnd(input);
break;
case 'tool-start':
await handleToolStart(input);
break;
case 'tool-end':
await handleToolEnd(input);
break;
case 'api-result':
case 'post-api':
await handleAPIResult(input);
break;
case 'session-end':
case 'stop':
await handleSessionEnd(input);
break;
default:
console.debug(`[agentmon] unknown hermes hook type: ${hookType}`);
}
} catch (err) {
console.debug('[agentmon] hermes handler error:', err);
}
};
handler();
+21
View File
@@ -0,0 +1,21 @@
hooks:
on_session_start:
- command: "~/.local/bin/agentmon-hermes-handler session-start"
pre_llm_call:
- command: "~/.local/bin/agentmon-hermes-handler run-start"
post_llm_call:
- command: "~/.local/bin/agentmon-hermes-handler run-end"
pre_tool_call:
- matcher: ".*"
command: "~/.local/bin/agentmon-hermes-handler tool-start"
post_tool_call:
- matcher: ".*"
command: "~/.local/bin/agentmon-hermes-handler tool-end"
post_api_request:
- command: "~/.local/bin/agentmon-hermes-handler api-result"
on_session_finalize:
- command: "~/.local/bin/agentmon-hermes-handler session-end"
on_session_reset:
- command: "~/.local/bin/agentmon-hermes-handler session-start"
hooks_auto_accept: true
+463
View File
@@ -0,0 +1,463 @@
{
"name": "@anthropic-ai/agentmon-hermes",
"version": "1.0.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "@anthropic-ai/agentmon-hermes",
"version": "1.0.0",
"bin": {
"agentmon-hermes-handler": "handler.js"
},
"devDependencies": {
"esbuild": "^0.20.0",
"typescript": "^5.3.0"
}
},
"node_modules/@esbuild/aix-ppc64": {
"version": "0.20.2",
"resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.20.2.tgz",
"integrity": "sha512-D+EBOJHXdNZcLJRBkhENNG8Wji2kgc9AZ9KiPr1JuZjsNtyHzrsfLRrY0tk2H2aoFu6RANO1y1iPPUCDYWkb5g==",
"cpu": [
"ppc64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"aix"
],
"engines": {
"node": ">=12"
}
},
"node_modules/@esbuild/android-arm": {
"version": "0.20.2",
"resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.20.2.tgz",
"integrity": "sha512-t98Ra6pw2VaDhqNWO2Oph2LXbz/EJcnLmKLGBJwEwXX/JAN83Fym1rU8l0JUWK6HkIbWONCSSatf4sf2NBRx/w==",
"cpu": [
"arm"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"android"
],
"engines": {
"node": ">=12"
}
},
"node_modules/@esbuild/android-arm64": {
"version": "0.20.2",
"resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.20.2.tgz",
"integrity": "sha512-mRzjLacRtl/tWU0SvD8lUEwb61yP9cqQo6noDZP/O8VkwafSYwZ4yWy24kan8jE/IMERpYncRt2dw438LP3Xmg==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"android"
],
"engines": {
"node": ">=12"
}
},
"node_modules/@esbuild/android-x64": {
"version": "0.20.2",
"resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.20.2.tgz",
"integrity": "sha512-btzExgV+/lMGDDa194CcUQm53ncxzeBrWJcncOBxuC6ndBkKxnHdFJn86mCIgTELsooUmwUm9FkhSp5HYu00Rg==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"android"
],
"engines": {
"node": ">=12"
}
},
"node_modules/@esbuild/darwin-arm64": {
"version": "0.20.2",
"resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.20.2.tgz",
"integrity": "sha512-4J6IRT+10J3aJH3l1yzEg9y3wkTDgDk7TSDFX+wKFiWjqWp/iCfLIYzGyasx9l0SAFPT1HwSCR+0w/h1ES/MjA==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"darwin"
],
"engines": {
"node": ">=12"
}
},
"node_modules/@esbuild/darwin-x64": {
"version": "0.20.2",
"resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.20.2.tgz",
"integrity": "sha512-tBcXp9KNphnNH0dfhv8KYkZhjc+H3XBkF5DKtswJblV7KlT9EI2+jeA8DgBjp908WEuYll6pF+UStUCfEpdysA==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"darwin"
],
"engines": {
"node": ">=12"
}
},
"node_modules/@esbuild/freebsd-arm64": {
"version": "0.20.2",
"resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.20.2.tgz",
"integrity": "sha512-d3qI41G4SuLiCGCFGUrKsSeTXyWG6yem1KcGZVS+3FYlYhtNoNgYrWcvkOoaqMhwXSMrZRl69ArHsGJ9mYdbbw==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"freebsd"
],
"engines": {
"node": ">=12"
}
},
"node_modules/@esbuild/freebsd-x64": {
"version": "0.20.2",
"resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.20.2.tgz",
"integrity": "sha512-d+DipyvHRuqEeM5zDivKV1KuXn9WeRX6vqSqIDgwIfPQtwMP4jaDsQsDncjTDDsExT4lR/91OLjRo8bmC1e+Cw==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"freebsd"
],
"engines": {
"node": ">=12"
}
},
"node_modules/@esbuild/linux-arm": {
"version": "0.20.2",
"resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.20.2.tgz",
"integrity": "sha512-VhLPeR8HTMPccbuWWcEUD1Az68TqaTYyj6nfE4QByZIQEQVWBB8vup8PpR7y1QHL3CpcF6xd5WVBU/+SBEvGTg==",
"cpu": [
"arm"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=12"
}
},
"node_modules/@esbuild/linux-arm64": {
"version": "0.20.2",
"resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.20.2.tgz",
"integrity": "sha512-9pb6rBjGvTFNira2FLIWqDk/uaf42sSyLE8j1rnUpuzsODBq7FvpwHYZxQ/It/8b+QOS1RYfqgGFNLRI+qlq2A==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=12"
}
},
"node_modules/@esbuild/linux-ia32": {
"version": "0.20.2",
"resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.20.2.tgz",
"integrity": "sha512-o10utieEkNPFDZFQm9CoP7Tvb33UutoJqg3qKf1PWVeeJhJw0Q347PxMvBgVVFgouYLGIhFYG0UGdBumROyiig==",
"cpu": [
"ia32"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=12"
}
},
"node_modules/@esbuild/linux-loong64": {
"version": "0.20.2",
"resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.20.2.tgz",
"integrity": "sha512-PR7sp6R/UC4CFVomVINKJ80pMFlfDfMQMYynX7t1tNTeivQ6XdX5r2XovMmha/VjR1YN/HgHWsVcTRIMkymrgQ==",
"cpu": [
"loong64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=12"
}
},
"node_modules/@esbuild/linux-mips64el": {
"version": "0.20.2",
"resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.20.2.tgz",
"integrity": "sha512-4BlTqeutE/KnOiTG5Y6Sb/Hw6hsBOZapOVF6njAESHInhlQAghVVZL1ZpIctBOoTFbQyGW+LsVYZ8lSSB3wkjA==",
"cpu": [
"mips64el"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=12"
}
},
"node_modules/@esbuild/linux-ppc64": {
"version": "0.20.2",
"resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.20.2.tgz",
"integrity": "sha512-rD3KsaDprDcfajSKdn25ooz5J5/fWBylaaXkuotBDGnMnDP1Uv5DLAN/45qfnf3JDYyJv/ytGHQaziHUdyzaAg==",
"cpu": [
"ppc64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=12"
}
},
"node_modules/@esbuild/linux-riscv64": {
"version": "0.20.2",
"resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.20.2.tgz",
"integrity": "sha512-snwmBKacKmwTMmhLlz/3aH1Q9T8v45bKYGE3j26TsaOVtjIag4wLfWSiZykXzXuE1kbCE+zJRmwp+ZbIHinnVg==",
"cpu": [
"riscv64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=12"
}
},
"node_modules/@esbuild/linux-s390x": {
"version": "0.20.2",
"resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.20.2.tgz",
"integrity": "sha512-wcWISOobRWNm3cezm5HOZcYz1sKoHLd8VL1dl309DiixxVFoFe/o8HnwuIwn6sXre88Nwj+VwZUvJf4AFxkyrQ==",
"cpu": [
"s390x"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=12"
}
},
"node_modules/@esbuild/linux-x64": {
"version": "0.20.2",
"resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.20.2.tgz",
"integrity": "sha512-1MdwI6OOTsfQfek8sLwgyjOXAu+wKhLEoaOLTjbijk6E2WONYpH9ZU2mNtR+lZ2B4uwr+usqGuVfFT9tMtGvGw==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=12"
}
},
"node_modules/@esbuild/netbsd-x64": {
"version": "0.20.2",
"resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.20.2.tgz",
"integrity": "sha512-K8/DhBxcVQkzYc43yJXDSyjlFeHQJBiowJ0uVL6Tor3jGQfSGHNNJcWxNbOI8v5k82prYqzPuwkzHt3J1T1iZQ==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"netbsd"
],
"engines": {
"node": ">=12"
}
},
"node_modules/@esbuild/openbsd-x64": {
"version": "0.20.2",
"resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.20.2.tgz",
"integrity": "sha512-eMpKlV0SThJmmJgiVyN9jTPJ2VBPquf6Kt/nAoo6DgHAoN57K15ZghiHaMvqjCye/uU4X5u3YSMgVBI1h3vKrQ==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"openbsd"
],
"engines": {
"node": ">=12"
}
},
"node_modules/@esbuild/sunos-x64": {
"version": "0.20.2",
"resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.20.2.tgz",
"integrity": "sha512-2UyFtRC6cXLyejf/YEld4Hajo7UHILetzE1vsRcGL3earZEW77JxrFjH4Ez2qaTiEfMgAXxfAZCm1fvM/G/o8w==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"sunos"
],
"engines": {
"node": ">=12"
}
},
"node_modules/@esbuild/win32-arm64": {
"version": "0.20.2",
"resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.20.2.tgz",
"integrity": "sha512-GRibxoawM9ZCnDxnP3usoUDO9vUkpAxIIZ6GQI+IlVmr5kP3zUq+l17xELTHMWTWzjxa2guPNyrpq1GWmPvcGQ==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"win32"
],
"engines": {
"node": ">=12"
}
},
"node_modules/@esbuild/win32-ia32": {
"version": "0.20.2",
"resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.20.2.tgz",
"integrity": "sha512-HfLOfn9YWmkSKRQqovpnITazdtquEW8/SoHW7pWpuEeguaZI4QnCRW6b+oZTztdBnZOS2hqJ6im/D5cPzBTTlQ==",
"cpu": [
"ia32"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"win32"
],
"engines": {
"node": ">=12"
}
},
"node_modules/@esbuild/win32-x64": {
"version": "0.20.2",
"resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.20.2.tgz",
"integrity": "sha512-N49X4lJX27+l9jbLKSqZ6bKNjzQvHaT8IIFUy+YIqmXQdjYCToGWwOItDrfby14c78aDd5NHQl29xingXfCdLQ==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"win32"
],
"engines": {
"node": ">=12"
}
},
"node_modules/esbuild": {
"version": "0.20.2",
"resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.20.2.tgz",
"integrity": "sha512-WdOOppmUNU+IbZ0PaDiTst80zjnrOkyJNHoKupIcVyU8Lvla3Ugx94VzkQ32Ijqd7UhHJy75gNWDMUekcrSJ6g==",
"dev": true,
"hasInstallScript": true,
"license": "MIT",
"bin": {
"esbuild": "bin/esbuild"
},
"engines": {
"node": ">=12"
},
"optionalDependencies": {
"@esbuild/aix-ppc64": "0.20.2",
"@esbuild/android-arm": "0.20.2",
"@esbuild/android-arm64": "0.20.2",
"@esbuild/android-x64": "0.20.2",
"@esbuild/darwin-arm64": "0.20.2",
"@esbuild/darwin-x64": "0.20.2",
"@esbuild/freebsd-arm64": "0.20.2",
"@esbuild/freebsd-x64": "0.20.2",
"@esbuild/linux-arm": "0.20.2",
"@esbuild/linux-arm64": "0.20.2",
"@esbuild/linux-ia32": "0.20.2",
"@esbuild/linux-loong64": "0.20.2",
"@esbuild/linux-mips64el": "0.20.2",
"@esbuild/linux-ppc64": "0.20.2",
"@esbuild/linux-riscv64": "0.20.2",
"@esbuild/linux-s390x": "0.20.2",
"@esbuild/linux-x64": "0.20.2",
"@esbuild/netbsd-x64": "0.20.2",
"@esbuild/openbsd-x64": "0.20.2",
"@esbuild/sunos-x64": "0.20.2",
"@esbuild/win32-arm64": "0.20.2",
"@esbuild/win32-ia32": "0.20.2",
"@esbuild/win32-x64": "0.20.2"
}
},
"node_modules/typescript": {
"version": "5.9.3",
"resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz",
"integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==",
"dev": true,
"license": "Apache-2.0",
"bin": {
"tsc": "bin/tsc",
"tsserver": "bin/tsserver"
},
"engines": {
"node": ">=14.17"
}
}
}
}
+18
View File
@@ -0,0 +1,18 @@
{
"name": "@anthropic-ai/agentmon-hermes",
"version": "1.0.0",
"description": "agentmon hook handler for Hermes Agent",
"main": "handler.js",
"type": "module",
"bin": {
"agentmon-hermes-handler": "./handler.js"
},
"scripts": {
"build": "npx esbuild handler.ts --bundle --platform=node --format=esm --outfile=handler.js"
},
"dependencies": {},
"devDependencies": {
"esbuild": "^0.20.0",
"typescript": "^5.3.0"
}
}