@unieai/rabi-session-telemetry 0.0.0-stage → 0.2.1-rc.3

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