Structured event log for mods: `$.modEvents.emit` writes per-session OTel log records as JSONL

Telemetry for mods. It adds $.modEvents.emit, which writes each mod's events to per-session JSONL. Each line is an OpenTelemetry log record, so a collector can tail the files, and the observability:session index ingests them as mod_events.
register.ts provides emit and records at session start whether the session is local or reached over mosh or ssh, with each attached client's reach for the multiplexer named by the multiplexer option (for example herdr). Empty, the default, classifies from SSH_CONNECTION alone.types/index.d.ts declares $.modEvents.emit.A mod lists "dependencies": ["mod-events"] in its plugin.json, adds "../../mod-events/types" to its mod/tsconfig.json include, and calls:
void $.modEvents.emit({ mod: "herdr", event: "herdr.call", ok: exitCode === 0, ms, detail: { command, exitCode, stderr } });
emit never rejects. Without this plugin enabled, the default emit drops events. Every mod emits session.start from its session.start hook, so a query can tell whether it was live.
Records land in <config>/mod-events/<session>/<mod>.<instance>.<n>.jsonl, <config> being CLAUDE_CONFIG_DIR or ~/.claude. <instance> is the first event's timestamp, so a reload starts new files, and <n> rolls at 64 KB.
Each line is one OTel log record with the data model's field names, flat rather than wrapped in an OTLP resourceLogs envelope:
{"timestamp":"2026-10-06T17:00:00.012Z","severity_text":"WARN","severity_number":13,"event_name":"herdr.herdr.call","attributes":{"command":"pane.report-agent","exitCode":1,"stderr":"…","duration_ms":12,"session.id":"<session-id>"},"resource":{"service.name":"claude-code","service.version":"2.1.291","claude_code.surface":"mosh"},"scope":{"name":"herdr"}}
timestamp is ISO 8601 in UTC, like Claude Code's own event.timestamp.severity_text is INFO (9), or WARN (13) when ok is false. A failing mod degrades the session without ending it, so nothing logs ERROR.event_name is <mod>.<event>.attributes holds detail, plus duration_ms from ms and session.id. Both keys match Claude Code's native OTel events, so a backend can join a mod's records to the session's own telemetry.resource carries service.name (claude-code, as the native exporter uses) and service.version. Once the session's heartbeat has judged it, it also carries claude_code.surface (local, mosh, or ssh).scope.name is the mod. The engine doesn't expose a calling plugin's version, so scope has no version.$.fs can only replace a file whole, so each event rewrites its chunk. The new text always extends the old, and a rolled chunk is never written again, so a tailer's fingerprint and offset stay valid. $.fs.write truncates and then writes in place rather than renaming a temp file over the chunk, and $.fs has no rename. A tailer polling inside that window reads an empty file. The collector's filelog receiver skips a file whose fingerprint is empty, then resumes at its offset once the bytes are back.
An otelcol-contrib filelog receiver maps each line into a log record. event_name lands as the event.name attribute, as Claude Code's own events carry it:
receivers:
filelog/mod_events:
include: ["${env:HOME}/.claude/mod-events/**/*.jsonl"]
start_at: beginning
operators:
- type: json_parser
parse_to: body
timestamp:
parse_from: body.timestamp
layout_type: gotime
layout: "2006-01-02T15:04:05.000Z07:00"
severity:
parse_from: body.severity_text
scope_name:
parse_from: body.scope.name
- type: move
from: body.attributes
to: attributes
- type: move
from: body.event_name
to: attributes["event.name"]
- type: move
from: body.resource
to: resource
- type: remove
field: body
Retention deletes the oldest files once the directory passes 500 MB. The session index keeps rows it has already ingested.
In a test, stub $.modEvents from your own engine.create hook and collect events at modEvents.emit:
on("engine.create", async ($, e, next) => ({ ...(await next(e)), modEvents: { emit: () => Promise.resolve() } }));
on("modEvents.emit", ($, e) => (events.push(e), { value: undefined }));
bun scripts/mod-test.ts mod-events runs the mod's tests.
mod/register.ts 233 lines1import type { EngineInterface, On, PluginOptions } from "claude-code";
2import type { ModEventsInput, ModEventsRecord } from "../types";
3
4const MOD = "mod-events";
5const CHUNK_BYTES = 64 * 1024;
6
7interface Chunk {
8 path: string;
9 text: string;
10 version: number;
11 written: number;
12 inFlight: Promise<void> | undefined;
13}
14
15interface Log {
16 root: string | undefined;
17 instance: number | undefined;
18 resource: Record<string, string> | undefined;
19 chunks: Map<string, { chunk: Chunk; n: number }>;
20}
21
22export type Surface = "local" | "mosh" | "ssh";
23
24interface Process {
25 pid: number;
26 ppid: number;
27 name: string;
28}
29
30function parsePs(stdout: string): Map<number, Process> {
31 const table = new Map<number, Process>();
32 for (const line of stdout.split("\n")) {
33 const match = /^\s*(\d+)\s+(\d+)\s+(.+?)\s*$/.exec(line);
34 if (match === null) continue;
35 const [, pid, ppid, command] = match;
36 const name = command?.split("/").at(-1) ?? "";
37 table.set(Number(pid), { pid: Number(pid), ppid: Number(ppid), name });
38 }
39 return table;
40}
41
42function reachOf(table: Map<number, Process>, pid: number): Surface {
43 for (let p = table.get(pid); p !== undefined && p.pid > 1; p = table.get(p.ppid)) {
44 if (p.name === "mosh-server") return "mosh";
45 if (p.name === "sshd" || p.name.startsWith("sshd-")) return "ssh";
46 }
47 return "local";
48}
49
50function summarize(clients: Surface[], isSsh: boolean): Surface {
51 if (clients.includes("mosh")) return "mosh";
52 if (isSsh || clients.includes("ssh")) return "ssh";
53 return "local";
54}
55
56/**
57 * Classifies each attached multiplexer client by its ancestry. The server is
58 * the `multiplexer` process whose parent is launchd, and every other one is a
59 * client.
60 */
61export function surfaceOf(
62 ps: string | undefined,
63 sshConnection: string | undefined,
64 multiplexer: string,
65): { surface: Surface; clients: Surface[] } {
66 const clients: Surface[] = [];
67 if (ps !== undefined) {
68 const table = parsePs(ps);
69 for (const p of table.values()) {
70 if (p.name === multiplexer && p.ppid > 1) clients.push(reachOf(table, p.pid));
71 }
72 }
73 // Panes inherit the multiplexer server's env, so `SSH_CONNECTION` speaks for the session only without clients.
74 const isSsh = clients.length === 0 && sshConnection !== undefined && sshConnection !== "";
75 return { surface: summarize(clients, isSsh), clients: clients.toSorted() };
76}
77
78async function write($: EngineInterface, chunk: Chunk): Promise<void> {
79 const version = chunk.version;
80 try {
81 await $.fs.write(chunk.path, chunk.text);
82 chunk.written = Math.max(chunk.written, version);
83 } finally {
84 chunk.inFlight = undefined;
85 }
86}
87
88// One write runs at a time, so an older text cannot land over a newer one.
89async function flush($: EngineInterface, chunk: Chunk): Promise<void> {
90 const target = chunk.version;
91 while (chunk.written < target) {
92 chunk.inFlight ??= write($, chunk);
93 // oxlint-disable-next-line no-await-in-loop -- a write already in flight may predate this line.
94 await chunk.inFlight;
95 }
96}
97
98async function rootOf($: EngineInterface, log: Log): Promise<string | undefined> {
99 if (log.root !== undefined) return log.root;
100 const [config, home] = await Promise.all([$.env.get("CLAUDE_CONFIG_DIR"), $.env.get("HOME")]);
101 if (config !== undefined && config !== "") log.root = `${config}/mod-events`;
102 else if (home !== undefined) log.root = `${home}/.claude/mod-events`;
103 return log.root;
104}
105
106const fileSafe = (name: string) => name.replaceAll(/[^\w.-]/g, "_");
107
108async function resourceOf($: EngineInterface, log: Log): Promise<Record<string, string>> {
109 log.resource ??= {
110 "service.name": "claude-code",
111 "service.version": (await $.session.version()).version,
112 };
113 return log.resource;
114}
115
116function toRecord(
117 input: ModEventsInput,
118 ts: number,
119 session: string,
120 resource: Record<string, string>,
121): ModEventsRecord {
122 const isOk = input.ok ?? true;
123 return {
124 timestamp: new Date(ts).toISOString(),
125 severity_text: isOk ? "INFO" : "WARN",
126 severity_number: isOk ? 9 : 13,
127 event_name: `${input.mod}.${input.event}`,
128 attributes: {
129 ...input.detail,
130 ...(input.ms !== undefined && { duration_ms: input.ms }),
131 "session.id": session,
132 },
133 resource,
134 scope: { name: input.mod },
135 };
136}
137
138async function record($: EngineInterface, log: Log, input: ModEventsInput): Promise<void> {
139 const [root, ts, session, resource] = await Promise.all([
140 rootOf($, log),
141 $.clock.now(),
142 $.session.id(),
143 resourceOf($, log),
144 ]);
145 if (root === undefined) return;
146 log.instance ??= ts;
147 const line = toRecord(input, ts, session, resource);
148 const text = `${JSON.stringify(line)}\n`;
149 const key = `${session}/${fileSafe(input.mod)}`;
150 let slot = log.chunks.get(key);
151 if (
152 slot === undefined ||
153 (slot.chunk.text !== "" && slot.chunk.text.length + text.length > CHUNK_BYTES)
154 ) {
155 const n = slot === undefined ? 0 : slot.n + 1;
156 slot = {
157 n,
158 chunk: {
159 path: `${root}/${key}.${log.instance}.${n}.jsonl`,
160 text: "",
161 version: 0,
162 written: 0,
163 inFlight: undefined,
164 },
165 };
166 log.chunks.set(key, slot);
167 }
168 slot.chunk.text += text;
169 slot.chunk.version += 1;
170 await flush($, slot.chunk);
171}
172
173async function emit($: EngineInterface, log: Log, input: ModEventsInput): Promise<void> {
174 try {
175 await record($, log, input);
176 } catch (error) {
177 $.ui.log(`mod-events: ${input.mod} ${input.event} not recorded: ${String(error)}`, {
178 to: "debug",
179 });
180 }
181}
182
183async function readSurface(
184 $: EngineInterface,
185 multiplexer: string,
186): Promise<ReturnType<typeof surfaceOf>> {
187 const [ssh, ps] = await Promise.all([
188 $.env.get("SSH_CONNECTION"),
189 multiplexer === ""
190 ? undefined
191 : $.process
192 .run(["ps", "-axo", "pid=,ppid=,comm="], { timeoutMs: 5000 })
193 .then((r) => (r.exitCode === 0 ? r.stdout : undefined))
194 .catch(() => undefined),
195 ]);
196 return surfaceOf(ps, ssh, multiplexer);
197}
198
199/**
200 * Seats `$.modEvents` for every mod that depends on this plugin and writes
201 * what they emit as OTel log records to
202 * `<config>/mod-events/<session>/<mod>.<instance>.<n>.jsonl`. A chunk is
203 * rewritten whole on each event, since `$.fs` has no append, so chunks roll at
204 * 64 KB and a reload starts a new instance. Each rewrite only appends, and a
205 * rolled chunk is never written again, so a tailer's offset stays valid.
206 */
207export function register(on: On, options: PluginOptions): void {
208 const multiplexer = typeof options.multiplexer === "string" ? options.multiplexer : "";
209 const log: Log = { root: undefined, instance: undefined, resource: undefined, chunks: new Map() };
210
211 on("engine.create", async ($, e, next) => {
212 const built = await next(e);
213 return { ...built, modEvents: { emit: () => Promise.resolve() } };
214 });
215
216 on("modEvents.emit", async ($, e, next) => {
217 await emit($, log, e);
218 return next(e);
219 }).catch(($, e, next) => (next.called ? next(e) : { value: undefined }));
220
221 on("session.start", async ($, e, next) => {
222 const started = await next(e);
223 const { surface, clients } = await readSurface($, multiplexer);
224 log.resource = { ...(await resourceOf($, log)), "claude_code.surface": surface };
225 await emit($, log, {
226 mod: MOD,
227 event: "session.start",
228 detail: { clients, surfaceKind: e.surface, isInteractive: e.isInteractive },
229 });
230 return started;
231 });
232}
233types/index.d.ts 46 lines1/**
2 * What a mod passes to `$.modEvents.emit`.
3 */
4export interface ModEventsInput {
5 /** The emitting plugin's name. */
6 mod: string;
7 /** What happened, dotted: `session.start`, `herdr.call`, `pick`. */
8 event: string;
9 /** False when what the event records failed. Defaults to true. */
10 ok?: boolean;
11 /** How long it took, for an event with a duration. */
12 ms?: number;
13 /** Event-specific fields, as JSON data. */
14 detail?: Record<string, unknown>;
15}
16
17/**
18 * One line of `<config>/mod-events/<session>/<mod>.<instance>.<n>.jsonl`: an
19 * OTel log record with its fields flat, the shape the session index ingests as
20 * `mod_events`.
21 */
22export interface ModEventsRecord {
23 /** ISO 8601, as Claude Code's own `event.timestamp`. */
24 timestamp: string;
25 severity_text: "INFO" | "WARN";
26 severity_number: 9 | 13;
27 /** `<mod>.<event>`. */
28 event_name: string;
29 /** The event's detail, plus `duration_ms` and `session.id`. */
30 attributes: Record<string, unknown>;
31 /** `service.name`, `service.version`, and `claude_code.surface` once known. */
32 resource: Record<string, string>;
33 scope: { name: string };
34}
35
36export interface ModEvents {
37 /** Records one event. Never rejects, so a caller need not await it. */
38 emit: (event: ModEventsInput) => Promise<void>;
39}
40
41declare module "claude-code" {
42 interface EngineInterface {
43 modEvents: ModEvents;
44 }
45}
46