@unieai/rabi-session-telemetry 0.2.1-rc.3 → 0.2.2-rc.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@unieai/rabi-session-telemetry",
3
3
  "description": "SessionTelemetryBackend seam for the Rabi Harness: session-event capture, projection, redaction, and handoff to a reporting backend",
4
- "version": "0.2.1-rc.3",
4
+ "version": "0.2.2-rc.5",
5
5
  "publishConfig": {
6
6
  "access": "public"
7
7
  },
@@ -19,12 +19,15 @@
19
19
  "files": [
20
20
  "lib/index.js",
21
21
  "lib/types/**/*.d.ts",
22
+ "lib/types/**/*.d.ts.map",
23
+ "lib/**/*.js.map",
24
+ "src",
22
25
  "README.md"
23
26
  ],
24
27
  "license": "MIT",
25
28
  "peerDependencies": {
26
- "@unieai/rabi-agent": "0.2.1-rc.3",
27
- "@unieai/rabi-session": "0.2.1-rc.3",
28
- "@unieai/cordis": "4.0.5"
29
+ "@unieai/rabi-agent": "0.2.2-rc.5",
30
+ "@unieai/rabi-session": "0.2.2-rc.5",
31
+ "@unieai/cordis": "4.1.0"
29
32
  }
30
33
  }
@@ -0,0 +1,305 @@
1
+ /**
2
+ * Capture coordinator for the telemetry capability. Live capture subscribes to
3
+ * the session firehose plus the one live-bus relay (`agent/error`). Both
4
+ * capture paths build one logical record per canonical Session event and run
5
+ * each through the
6
+ * `session-telemetry/record` waterfall (deployment-mounted redaction rules;
7
+ * pass-through when none), then hands the result to the backend. Live capture
8
+ * follows the session firehose; on-demand capture replays the canonical log
9
+ * only when requested. Every synchronous handler is self-contained so a
10
+ * failing backend can never starve other subscribers (cordis `emit` is
11
+ * stop-on-throw) or touch the agent loop. Composed by a backend in its
12
+ * constructor.
13
+ *
14
+ * @module @unieai/rabi-session-telemetry/coordinator
15
+ */
16
+
17
+ import type { Context } from '@unieai/cordis'
18
+ import {
19
+ SessionSeq,
20
+ SessionLogOffset,
21
+ type Session,
22
+ type SessionEvent,
23
+ type SessionSeq as SessionSeqType,
24
+ type SessionSeqCursor,
25
+ } from '@unieai/rabi-session'
26
+ import type { Agent } from '@unieai/rabi-agent'
27
+ import type { SessionTelemetrySink, SessionTelemetryRecord, SessionTelemetrySeverity } from './index.ts'
28
+
29
+ /** Whether capture follows live events or reads the canonical log only when requested. */
30
+ export type SessionTelemetryCapture = 'live' | 'on-demand'
31
+
32
+ /** Backend-selected capture mode and history policy. */
33
+ export interface SessionTelemetryCaptureOptions {
34
+ /** Follow live events, or wait for explicit capture; defaults to live. */
35
+ capture?: SessionTelemetryCapture
36
+ /** Include inherited fork history and stored history from earlier lifecycles; defaults to false. */
37
+ includeHistory?: boolean
38
+ }
39
+
40
+ /** One record ready for backend handoff. */
41
+ interface PendingRecord {
42
+ readonly record: SessionTelemetryRecord
43
+ /** Ledger cursor advanced only after the backend accepts this record. */
44
+ readonly seq?: SessionSeqType
45
+ }
46
+
47
+ /**
48
+ * The handoff cursor: per session, the highest `seq` handed to a backend.
49
+ * Deliberately MODULE-scope ambient state — a narrow, documented exception
50
+ * to the registrations-are-effects discipline: cordis has no HMR
51
+ * state-handover API, and keying by the `Session` object (which belongs to
52
+ * the session store and outlives any telemetry fiber) is the only in-process
53
+ * lifetime that lets a re-adopting fiber resume instead of re-handing
54
+ * history. Entries die with their sessions; a missing entry safely means
55
+ * "re-hand everything". Advanced only at emit time — the cursor marks
56
+ * handed-off, not delivered.
57
+ */
58
+ const handoffCursor = new WeakMap<Session, SessionSeqCursor>()
59
+
60
+ /**
61
+ * Install the telemetry capture side onto a context for one backend.
62
+ *
63
+ * Live capture registers its own `session/created` / `session/event` /
64
+ * `session/disposed` listener set plus the `agent/error` relay, all through
65
+ * `ctx.effect()`/`ctx.on()` on the composing fiber, and sweeps already-live
66
+ * sessions (a hot reload does not replay `session/created`). A `session/disposed` captures the session's `shutdown`
67
+ * operational record at its own termination edge and retires it from the
68
+ * adopted set. On-demand capture registers none of those continuous listeners;
69
+ * {@link captureSession} reads the canonical log explicitly and never creates
70
+ * operational records. Disposal captures shutdown markers for live-adopted
71
+ * sessions, then awaits the backend's `shutdown()`; a failure there warns
72
+ * instead of throwing — best-effort reporting must not fail application
73
+ * teardown.
74
+ */
75
+ export class SessionTelemetryCoordinator {
76
+ /**
77
+ * Sessions adopted by THIS fiber and still live, for double-adoption
78
+ * protection and the teardown sweep of unmarked sessions;
79
+ * `session/disposed` marks and retires entries.
80
+ */
81
+ private readonly adopted = new Set<Session>()
82
+ /**
83
+ * @param ctx - the composing backend's context; listeners bind to its fiber.
84
+ * @param backend - the backend receiving records; owned elsewhere, never disposed here beyond `shutdown()` forwarding.
85
+ * @param options - capture mode and history policy.
86
+ */
87
+ constructor(
88
+ private readonly ctx: Context,
89
+ private readonly backend: SessionTelemetrySink,
90
+ private readonly options: SessionTelemetryCaptureOptions = {},
91
+ ) {
92
+ if ((options.capture ?? 'live') === 'live') {
93
+ ctx.on('session/created', (session) => {
94
+ this.adopt(session)
95
+ })
96
+ // Capture the shutdown marker at the session's own termination edge,
97
+ // then retire the only strong reference owned by this coordinator.
98
+ ctx.on('session/disposed', (session) => {
99
+ this.contain(() => {
100
+ if (!this.adopted.delete(session)) return
101
+ this.deliver(session, { record: this.redact(shutdownRecord(session)) })
102
+ })
103
+ })
104
+ ctx.on('session/event', (session, event) => {
105
+ this.contain(() => {
106
+ this.captureEvent(session, event)
107
+ })
108
+ })
109
+ // Parallel listeners are awaited by the loop at turn end; returning void
110
+ // (not the SDK's flush promise) is the turn-latency contract.
111
+ ctx.on('session/flush', (session) => {
112
+ this.contain(() => {
113
+ this.hintFlush(session)
114
+ })
115
+ })
116
+ ctx.on('agent/error', ({ agent, turn, step, error }) => {
117
+ this.contain(() => {
118
+ this.relayAgentError(agent, turn, step, error)
119
+ })
120
+ })
121
+ for (const session of ctx.sessions.list()) {
122
+ this.adopt(session)
123
+ }
124
+ }
125
+ ctx.effect(() => async () => {
126
+ // Sessions still adopted here are alive through whole-application
127
+ // teardown, so capture the marker before the backend quiesces.
128
+ for (const session of this.adopted) {
129
+ this.contain(() => {
130
+ this.deliver(session, { record: this.redact(shutdownRecord(session)) })
131
+ })
132
+ }
133
+ try {
134
+ await this.backend.shutdown()
135
+ } catch (error) {
136
+ this.ctx.logger.warn(`telemetry: backend shutdown failed: ${String(error)}`)
137
+ }
138
+ }, 'telemetry capture')
139
+ }
140
+
141
+ /**
142
+ * Copy, redact, and hand over the canonical session-log suffix after the handoff
143
+ * cursor, optionally stopping at an inclusive sequence boundary. Redaction
144
+ * runs during this call, so an on-demand caller retains no copied records
145
+ * before requesting capture and uses the policy mounted at that time.
146
+ * Backend and policy failures remain contained per event and do not starve
147
+ * later events in the same replay.
148
+ * @param session - session whose current canonical-log prefix may be handed over.
149
+ * @param throughSeq - optional last sequence included in this capture.
150
+ */
151
+ captureSession(session: Session, throughSeq?: SessionSeqType): void {
152
+ const start = session.firstLifecycleSeq
153
+ const cursor = handoffCursor.get(session)
154
+ ?? (this.options.includeHistory === true || start === 0 ? -1 : SessionSeq(start - 1))
155
+ // Containment is PER EVENT: one rejected record is withheld fail-closed
156
+ // while the rest of the historical replay proceeds.
157
+ // oxlint-disable-next-line typescript/no-deprecated -- Existing Session history read; migration deferred.
158
+ for (const event of session.snapshotEvents(SessionLogOffset(cursor + 1))) {
159
+ if (throughSeq !== undefined && event.seq > throughSeq) break
160
+ this.contain(() => {
161
+ this.captureEvent(session, event)
162
+ })
163
+ }
164
+ }
165
+
166
+ /**
167
+ * Adopt a session and replay after its handoff cursor, then follow live events.
168
+ * New fork objects include child-owned seed markers and closers. Restored
169
+ * objects start after the stored prefix, including restored forks. includeHistory starts either object at seq 0;
170
+ * re-adopting the same object resumes after its cursor.
171
+ * @param session - the live session to adopt; a second adoption is a no-op.
172
+ */
173
+ private adopt(session: Session): void {
174
+ if (this.adopted.has(session)) return
175
+ this.adopted.add(session)
176
+ this.captureSession(session)
177
+ }
178
+
179
+ /** Copy, redact, and hand one canonical event to the backend. */
180
+ private captureEvent(session: Session, event: SessionEvent): void {
181
+ const { data, ...envelope } = event
182
+ this.deliver(session, {
183
+ record: this.redact({
184
+ sourceEvent: { sessionId: session.id, envelope: structuredClone(envelope) },
185
+ channel: 'ledger',
186
+ time: event.time,
187
+ severity: severityOf(event),
188
+ attributes: identityOf(session, event),
189
+ // The canonical event object is mutable and the backend serializes
190
+ // later; append-time validation guarantees this clone cannot throw.
191
+ body: structuredClone(data),
192
+ }),
193
+ seq: event.seq,
194
+ })
195
+ }
196
+
197
+ /**
198
+ * Run the `session-telemetry/record` waterfall at capture time. The innermost `next`
199
+ * passes the record through unchanged — this package ships no rules; exported
200
+ * data is as clean as the listeners a deployment mounts. Callers run inside
201
+ * {@link contain}, so a throwing rule withholds the record instead of
202
+ * reaching the loop (fail-closed). On-demand capture invokes this waterfall
203
+ * while reading the canonical session log, not when the event was appended.
204
+ */
205
+ private redact(record: SessionTelemetryRecord): SessionTelemetryRecord {
206
+ return this.ctx.waterfall('session-telemetry/record', record, () => record)
207
+ }
208
+
209
+ /** Hand one redacted record to the backend, then advance its ledger cursor. */
210
+ private deliver(session: Session, pending: PendingRecord): void {
211
+ this.backend.emit(pending.record)
212
+ if (pending.seq !== undefined) handoffCursor.set(session, pending.seq)
213
+ }
214
+
215
+ /** Forward the turn-end boundary to the backend's optional flush hint. */
216
+ private hintFlush(session: Session): void {
217
+ if (this.adopted.has(session)) this.backend.flush?.()
218
+ }
219
+
220
+ /** Relay one `agent/error` bus emission as an `agent-error` operational record. */
221
+ private relayAgentError(agent: Agent, turn: number, step: number, error: unknown): void {
222
+ const detail = errorDetail(error)
223
+ this.deliver(agent.session, {
224
+ record: this.redact({
225
+ channel: 'ops',
226
+ time: Date.now(),
227
+ severity: 'error',
228
+ attributes: {
229
+ 'telemetry.op': 'agent-error',
230
+ 'session.id': String(agent.session.id),
231
+ 'agent.id': agent.id,
232
+ 'error.name': detail.name,
233
+ turn,
234
+ step,
235
+ },
236
+ body: detail,
237
+ }),
238
+ })
239
+ }
240
+
241
+ /**
242
+ * Run one capture-side step with its exception contained: cordis `emit`
243
+ * is stop-on-throw, so a throwing listener would starve every subscriber
244
+ * registered after this plugin — nothing from the backend may escape.
245
+ */
246
+ private contain(step: () => void): void {
247
+ try {
248
+ step()
249
+ } catch (error) {
250
+ this.ctx.logger.warn(`telemetry: capture step failed: ${String(error)}`)
251
+ }
252
+ }
253
+ }
254
+
255
+ /**
256
+ * Build the per-session clean-exit marker: emitted at the session's own
257
+ * disposal edge, or at coordinator dispose for sessions still alive then.
258
+ */
259
+ function shutdownRecord(session: Session): SessionTelemetryRecord {
260
+ return {
261
+ channel: 'ops',
262
+ time: Date.now(),
263
+ severity: 'info',
264
+ attributes: { 'telemetry.op': 'shutdown', 'session.id': String(session.id) },
265
+ body: { op: 'shutdown' },
266
+ }
267
+ }
268
+
269
+ /** Map an event's own outcome flag to the pre-baked alerting severity. */
270
+ function severityOf(event: SessionEvent): SessionTelemetrySeverity {
271
+ switch (event.type) {
272
+ case 'tool/result':
273
+ return event.data.message.isError === true ? 'error' : 'info'
274
+ case 'turn/end':
275
+ return event.data.reason.kind === 'error' ? 'error' : 'info'
276
+ default:
277
+ // Merge-extensible fall-through (no assertNever): event types this coordinator
278
+ // does not depend on — including plugin-merged ones it never heard of —
279
+ // pass through as info; their owners' outcome semantics stay theirs.
280
+ return 'info'
281
+ }
282
+ }
283
+
284
+ /** Normalize the live bus's arbitrary thrown value into the stable operational-record shape. */
285
+ function errorDetail(error: unknown): { name: string; message: string } {
286
+ const normalized = error instanceof Error ? error : new Error(String(error))
287
+ return { name: normalized.name, message: normalized.message }
288
+ }
289
+
290
+ /** Build the minimal identity attributes: envelope plus self-contained header facts. */
291
+ function identityOf(session: Session, event: SessionEvent): Record<string, string | number> {
292
+ const attributes: Record<string, string | number> = {
293
+ 'session.id': String(session.id),
294
+ 'session.format_version': session.header.version,
295
+ 'event.type': event.type,
296
+ 'event.seq': event.seq,
297
+ }
298
+ const { cwd, parentSession, isSeeded } = session.header
299
+ if (cwd !== undefined) attributes['session.cwd'] = cwd
300
+ if (parentSession !== undefined) attributes['session.parent_id'] = String(parentSession)
301
+ // The durable fork boundary and lineage: the child ledger is complete;
302
+ // parent_id and seed_length identify which leading events were inherited.
303
+ if (isSeeded) attributes['session.seed_length'] = session.inheritedEventCount
304
+ return attributes
305
+ }
package/src/index.ts ADDED
@@ -0,0 +1,174 @@
1
+ /**
2
+ * SessionTelemetryBackend Service Definition for the Rabi Harness.
3
+ *
4
+ * This package owns the CAPTURE side of session-event reporting — the complete
5
+ * one-record-per-event ledger mirror, what records carry, when
6
+ * they are captured (adoption, the per-append firehose, lifecycle
7
+ * forwarding), live versus on-demand canonical-log capture, and the HMR
8
+ * cursor. Everything downstream of
9
+ * {@link SessionTelemetryBackend.emit} — batching, retry, queueing, and loss policy — is the
10
+ * backend's responsibility and is deliberately not modelled here. Capture and
11
+ * backend responsibilities are documented in the
12
+ * [Session telemetry reference](../README.md#understand-the-implementation).
13
+ *
14
+ * @module @unieai/rabi-session-telemetry
15
+ */
16
+
17
+ import { Context, Service } from '@unieai/cordis'
18
+ import type { SessionEvent, SessionId } from '@unieai/rabi-session'
19
+
20
+ declare module '@unieai/cordis' {
21
+ interface Context {
22
+ sessionTelemetry: SessionTelemetryBackend
23
+ }
24
+
25
+ interface Events {
26
+ /**
27
+ * Transform one outbound record before it reaches the backend. This
28
+ * waterfall is the Service Definition's redaction extension point. It ships NO rules
29
+ * of its own: the
30
+ * innermost `next()` passes the record through unchanged, and with no
31
+ * listener mounted records reach the backend as captured, so exported
32
+ * data is exactly as clean as the rules a deployment mounts. Listeners
33
+ * stack by transforming `next()`'s return value; returning without
34
+ * `next()` replaces everything beneath. Dispatched synchronously on the
35
+ * capture hot path inside the coordinator's containment: a throwing
36
+ * listener withholds that one record (fail-closed) and never reaches the
37
+ * agent loop. Live capture dispatches at append time; on-demand capture
38
+ * dispatches while reading the canonical log. Redaction applies to the
39
+ * exported copy only; the canonical session log is never rewritten.
40
+ * @param record - the candidate record, already the coordinator's own deep
41
+ * copy; listeners return a (possibly new) record and must not mutate it.
42
+ * @mode waterfall
43
+ */
44
+ 'session-telemetry/record'(record: SessionTelemetryRecord, next: () => SessionTelemetryRecord): SessionTelemetryRecord
45
+ }
46
+ }
47
+
48
+ /**
49
+ * Severity of a telemetry record, pre-mapped at capture so a receiver can
50
+ * alert with zero configuration: `error` for events whose own outcome flag
51
+ * says so (the tool message's `isError`, `turn/end` error reasons) and for
52
+ * `agent-error` operational records. Captured events otherwise default to
53
+ * `info`; `warn` remains available to `session-telemetry/record` policies and
54
+ * backends.
55
+ */
56
+ export type SessionTelemetrySeverity = 'info' | 'warn' | 'error'
57
+
58
+ /**
59
+ * One logical record handed to a backend — the capture contract's whole outbound
60
+ * vocabulary. Ledger records mirror session-log events one-to-one;
61
+ * operational records (`channel: 'ops'`) carry the two signals with no log
62
+ * home (`agent-error`, `shutdown`) and deliberately omit `event.seq`-style
63
+ * identity so they can never be mistaken for ledger rows.
64
+ */
65
+ export interface SessionTelemetryRecord {
66
+ /** Canonical envelope without data; body carries the separately redacted payload. Absent for operational records. */
67
+ sourceEvent?: { sessionId: SessionId; envelope: Omit<SessionEvent, 'data'> }
68
+ /** Ledger (session-log mirror) or ops (operational signal) channel; backends keep the two under separate instrumentation scopes. */
69
+ channel: 'ledger' | 'ops'
70
+ /** Unix epoch milliseconds — the source event's append time for ledger records, the emission time for ops records. */
71
+ time: number
72
+ /** Pre-mapped alerting severity; see {@link SessionTelemetrySeverity}. */
73
+ severity: SessionTelemetrySeverity
74
+ /**
75
+ * Identity attributes, deliberately minimal: ledger records carry
76
+ * `session.id`, `session.format_version`, `event.type`, `event.seq`, plus optional
77
+ * `session.cwd` / `session.parent_id`; a seeded Session also carries
78
+ * `session.seed_length` from its exact inherited event count;
79
+ * ops records carry `telemetry.op`, `session.id`, and (for `agent-error`)
80
+ * `agent.id`, `turn`, `step`, `error.name`. Anything recoverable from the
81
+ * body is intentionally NOT duplicated here.
82
+ */
83
+ attributes: Record<string, string | number>
84
+ /**
85
+ * The complete payload: a deep copy of the session event's `data` for
86
+ * ledger records (JSON-serializable by `Session.append`'s own
87
+ * validation), or the op payload for ops records. Never mutated after
88
+ * handoff.
89
+ */
90
+ body: unknown
91
+ }
92
+
93
+ /**
94
+ * The minimum backend contract the coordinator requires. {@link SessionTelemetryBackend} is
95
+ * its service-registered form; tests compose the coordinator with a bare
96
+ * implementation of this interface.
97
+ */
98
+ export interface SessionTelemetrySink {
99
+ /**
100
+ * Hand one record to the backend's pipeline. MUST be a non-blocking
101
+ * enqueue — the coordinator calls this synchronously from the
102
+ * `session/event` hot path or an explicit canonical-log capture, so anything
103
+ * slower than a queue push would tax the agent loop or feedback handling.
104
+ * Errors thrown here are contained by the coordinator and logged; they
105
+ * never reach the loop.
106
+ * @param record - the logical record to report; owned by the backend after the call.
107
+ */
108
+ emit(record: SessionTelemetryRecord): void
109
+ /**
110
+ * Optional hint that a turn ended. A backend may forward it to its SDK's
111
+ * flush so records are exported after each turn. Called
112
+ * fire-and-forget; implementations must not block and must not throw
113
+ * meaningfully (the coordinator contains exceptions). Most backends should
114
+ * leave this unimplemented and let their SDK's own batching cadence govern
115
+ * export timing: a backend that does implement it owns the interaction
116
+ * between its concurrent flushes and {@link shutdown}'s drain (the OTel
117
+ * backend leaves it unimplemented for exactly that hazard — see the
118
+ * revival Agent Note).
119
+ */
120
+ flush?(): void
121
+ /**
122
+ * Forward the fiber's disposal to the SDK: flush whatever is queued and
123
+ * reach quiescence, per the SDK's own shutdown contract. Everything
124
+ * emitted before this call must still be delivered — including records
125
+ * enqueued while a {@link flush} hint is in flight, so a backend whose SDK
126
+ * guards against concurrent flushes orders behind the outstanding one (the
127
+ * coordinator emits its dispose-time `shutdown` markers immediately before
128
+ * calling this). Awaited by the coordinator's dispose; a rejection is
129
+ * logged as a warning and never fails application teardown.
130
+ * The coordinator captures dispose-time shutdown markers immediately before
131
+ * this call for live capture; on-demand capture creates no ops records.
132
+ * @returns resolves when the backend's pipeline has quiesced.
133
+ */
134
+ shutdown(): Promise<void>
135
+ }
136
+
137
+ /**
138
+ * Deployment-selected session-sharing mode, not confirmation of SDK delivery.
139
+ */
140
+ export type SessionTelemetrySharingStatus = 'full' | 'feedback-only' | 'disabled'
141
+
142
+ /**
143
+ * Loadable form of the backend contract: one implementation per context —
144
+ * the cordis `Service` registration under the `telemetry` key throws on a
145
+ * duplicate, cordis' standard behavior. A backend composes a
146
+ * {@link SessionTelemetryCoordinator} in its constructor to install the capture side.
147
+ */
148
+ export abstract class SessionTelemetryBackend extends Service implements SessionTelemetrySink {
149
+ constructor(ctx: Context) {
150
+ super(ctx, 'sessionTelemetry')
151
+ }
152
+
153
+ /**
154
+ * Deployment-selected sharing mode, independent of SDK delivery.
155
+ */
156
+ abstract readonly sharing: SessionTelemetrySharingStatus
157
+
158
+ /**
159
+ * See {@link SessionTelemetrySink.emit} — that declaration is the contract's one home.
160
+ * @param record - the logical record to report; owned by the backend after the call.
161
+ */
162
+ abstract emit(record: SessionTelemetryRecord): void
163
+
164
+ /** See {@link SessionTelemetrySink.flush}. */
165
+ flush?(): void
166
+
167
+ /**
168
+ * See {@link SessionTelemetrySink.shutdown}.
169
+ * @returns resolves when the backend's pipeline has quiesced.
170
+ */
171
+ abstract shutdown(): Promise<void>
172
+ }
173
+
174
+ export { SessionTelemetryCoordinator, type SessionTelemetryCapture, type SessionTelemetryCaptureOptions } from './coordinator.ts'