@unieai/rabi-session-telemetry-otel 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/locale/de.json ADDED
@@ -0,0 +1,6 @@
1
+ {
2
+ "meta": {
3
+ "title": "Hochladen des Feedback-Sitzungsprotokolls",
4
+ "description": "Gemäß der Feedback-Autorisierungsrichtlinie werden relevante Sitzungsprotokolle über OpenTelemetry hochgeladen."
5
+ }
6
+ }
package/locale/es.json ADDED
@@ -0,0 +1,6 @@
1
+ {
2
+ "meta": {
3
+ "title": "Carga del registro de sesión de comentarios",
4
+ "description": "De acuerdo con la política de autorización de comentarios, los registros de sesiones relevantes se cargan a través de OpenTelemetry."
5
+ }
6
+ }
package/locale/fr.json ADDED
@@ -0,0 +1,6 @@
1
+ {
2
+ "meta": {
3
+ "title": "Téléchargement du journal de la session de commentaires",
4
+ "description": "Conformément à la politique d'autorisation des commentaires, les journaux de session pertinents sont téléchargés via OpenTelemetry."
5
+ }
6
+ }
package/locale/ja.json ADDED
@@ -0,0 +1,6 @@
1
+ {
2
+ "meta": {
3
+ "title": "フィードバック用セッションログ送信",
4
+ "description": "フィードバックの認可ポリシーに従い、OpenTelemetry を通じて関連するセッションログを送信します。"
5
+ }
6
+ }
package/locale/pt.json ADDED
@@ -0,0 +1,6 @@
1
+ {
2
+ "meta": {
3
+ "title": "Upload do log da sessão de feedback",
4
+ "description": "De acordo com a política de autorização de feedback, os logs de sessão relevantes são carregados por meio do OpenTelemetry."
5
+ }
6
+ }
package/locale/ru.json ADDED
@@ -0,0 +1,6 @@
1
+ {
2
+ "meta": {
3
+ "title": "Загрузка журнала сеанса обратной связи",
4
+ "description": "В соответствии с политикой авторизации обратной связи соответствующие журналы сеансов загружаются через OpenTelemetry."
5
+ }
6
+ }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@unieai/rabi-session-telemetry-otel",
3
3
  "description": "Feedback-authorized Session logs over byte-bounded OpenTelemetry HTTP requests",
4
- "version": "0.2.1-rc.3",
4
+ "version": "0.2.2-rc.5",
5
5
  "publishConfig": {
6
6
  "access": "public"
7
7
  },
@@ -21,21 +21,24 @@
21
21
  "locale/*.json",
22
22
  "lib/index.js",
23
23
  "lib/types/**/*.d.ts",
24
+ "lib/types/**/*.d.ts.map",
25
+ "lib/**/*.js.map",
26
+ "src",
24
27
  "README.md"
25
28
  ],
26
29
  "license": "MIT",
27
30
  "dependencies": {
28
31
  "@opentelemetry/api-logs": "0.222.0",
29
- "@unieai/schemastery": "3.18.5"
32
+ "@unieai/schemastery": "3.19.0"
30
33
  },
31
34
  "peerDependencies": {
32
- "@unieai/rabi-command-feedback": "0.2.1-rc.3",
33
- "@unieai/rabi-message-feedback": "0.2.1-rc.3",
34
- "@unieai/rabi-llm": "0.2.1-rc.3",
35
- "@unieai/rabi-session": "0.2.1-rc.3",
36
- "@unieai/rabi-session-telemetry": "0.2.1-rc.3",
37
- "@unieai/rabi-anonymous-user-id": "0.2.1-rc.3",
38
- "@unieai/cordis": "4.0.5",
39
- "@unieai/rabi-otel": "0.2.1-rc.3"
35
+ "@unieai/rabi-command-feedback": "0.2.2-rc.5",
36
+ "@unieai/rabi-message-feedback": "0.2.2-rc.5",
37
+ "@unieai/rabi-llm": "0.2.2-rc.5",
38
+ "@unieai/rabi-session": "0.2.2-rc.5",
39
+ "@unieai/rabi-session-telemetry": "0.2.2-rc.5",
40
+ "@unieai/rabi-anonymous-user-id": "0.2.2-rc.5",
41
+ "@unieai/cordis": "4.1.0",
42
+ "@unieai/rabi-otel": "0.2.2-rc.5"
40
43
  }
41
44
  }
package/src/index.ts ADDED
@@ -0,0 +1,278 @@
1
+ /**
2
+ * OpenTelemetry Service Provider for the Rabi Harness telemetry capability.
3
+ *
4
+ * Authorizes feedback-bounded capture and hands complete event strings to the
5
+ * Session-log reporter. This plugin owns resource identity and an outer
6
+ * shutdown deadline; the reporter owns byte-bounded SDK delivery.
7
+ *
8
+ * @module @unieai/rabi-session-telemetry-otel
9
+ */
10
+
11
+ import { createRequire } from 'node:module'
12
+ import z from '@unieai/schemastery'
13
+ import type { Context } from '@unieai/cordis'
14
+ import type {} from '@unieai/rabi-command-feedback'
15
+ import type {} from '@unieai/rabi-message-feedback'
16
+ import { Session, type SessionEvent } from '@unieai/rabi-session'
17
+ import {
18
+ SessionTelemetryBackend,
19
+ SessionTelemetryCoordinator,
20
+ type SessionTelemetrySink,
21
+ type SessionTelemetryRecord,
22
+ type SessionTelemetrySeverity,
23
+ type SessionTelemetrySharingStatus,
24
+ } from '@unieai/rabi-session-telemetry'
25
+ import { APP_IDENTITY } from '@unieai/rabi-llm'
26
+ import { getOrCreateAnonymousUserId } from '@unieai/rabi-anonymous-user-id'
27
+ import type { LogExporterOptions, SessionLogProcessorOptions, SessionLogReporter } from '@unieai/rabi-otel'
28
+ import { SeverityNumber } from '@opentelemetry/api-logs'
29
+
30
+ /** Session-sharing policy selected by {@link Config.mode}. */
31
+ export enum SessionTelemetryMode {
32
+ FEEDBACK_ONLY = 'FEEDBACK_ONLY',
33
+ DISABLED = 'DISABLED',
34
+ }
35
+
36
+ /** Default session-sharing policy for schema and direct construction. */
37
+ export const DEFAULT_TELEMETRY_MODE = SessionTelemetryMode.FEEDBACK_ONLY
38
+
39
+ const DISABLED_FEEDBACK_WARNING = 'OpenTelemetry session upload is DISABLED; this feedback is not uploaded through OpenTelemetry'
40
+ const NON_CANONICAL_EVENT_WARNING = 'session telemetry ignored an event absent from the canonical session log'
41
+
42
+ /** Only this Session's explicit feedback authorizes replay; fork seeds do not. */
43
+ function isFeedback(session: Session, event: SessionEvent): boolean {
44
+ if (event.seq < session.inheritedEventCount) return false
45
+ switch (event.type) {
46
+ case 'feedback/record': return true
47
+ case 'feedback/message-put':
48
+ case 'feedback/message-delete': return event.data.sessionId === session.id
49
+ default: return false
50
+ }
51
+ }
52
+
53
+ /** Resolve the default and reject unknown runtime values before transport setup. */
54
+ function resolveMode(mode: SessionTelemetryMode | undefined): SessionTelemetryMode {
55
+ const resolved = mode ?? DEFAULT_TELEMETRY_MODE
56
+ switch (resolved) {
57
+ case SessionTelemetryMode.FEEDBACK_ONLY:
58
+ case SessionTelemetryMode.DISABLED:
59
+ return resolved
60
+ default:
61
+ return assertNever(resolved)
62
+ }
63
+ }
64
+
65
+ /** Fail closed when direct construction bypasses the runtime config schema. */
66
+ function assertNever(value: never): never {
67
+ throw new Error(`session-telemetry-otel: unsupported mode ${JSON.stringify(value)}`)
68
+ }
69
+
70
+ /** Map the serialized mode onto the seam's backend-independent sharing vocabulary. */
71
+ function sharingStatusFor(mode: SessionTelemetryMode): SessionTelemetrySharingStatus {
72
+ switch (mode) {
73
+ case SessionTelemetryMode.FEEDBACK_ONLY: return 'feedback-only'
74
+ case SessionTelemetryMode.DISABLED: return 'disabled'
75
+ /* v8 ignore next 2 -- resolveMode already rejected unknown values before this switch; the closed enum cannot reach the default. */
76
+ default: return assertNever(mode)
77
+ }
78
+ }
79
+
80
+ /**
81
+ * Plugin configuration: sharing policy, SDK transport options, byte/count queue
82
+ * settings, and an overall shutdown bound. Uploading modes validate their endpoint
83
+ * and shutdown deadline at plugin load; `DISABLED` reads neither.
84
+ */
85
+ export interface Config {
86
+ /** Defaults to `FEEDBACK_ONLY`: capture session history only when feedback is explicitly submitted. */
87
+ mode?: SessionTelemetryMode
88
+ /**
89
+ * Explicit SDK HTTP transport settings, including optional routing headers.
90
+ * Ambient credentials are not inherited. URL is required while uploading.
91
+ * Exporter self-observability metering is not supported.
92
+ */
93
+ exporter?: Omit<LogExporterOptions, 'url'> & {
94
+ /** Full logs endpoint (e.g. `https://collector.example.com/v1/logs`). Required outside `DISABLED`; validated at load. */
95
+ url?: string
96
+ }
97
+ /**
98
+ * Count, queue, cadence, and per-request watchdog settings for the byte-bounded
99
+ * processor. A watchdog warning never releases an unsettled transport slot.
100
+ * SDK processor self-observability metering is not supported.
101
+ */
102
+ processor?: SessionLogProcessorOptions
103
+ /** Maximum time spent awaiting the SDK provider's complete shutdown path. */
104
+ shutdownTimeoutMillis?: number
105
+ /** Uncompressed OTLP request byte limit, at most 4,000,000. */
106
+ maxRequestBytes?: number
107
+ }
108
+
109
+ /**
110
+ * Schemastery validator for {@link Config}; cordis runs it before the plugin
111
+ * starts. The constructor validates endpoint and shutdown requirements; the
112
+ * reporter validates Session byte and queue limits. SDK transport and
113
+ * processor settings use the reporter's accepted option types, which exclude
114
+ * self-observability metering.
115
+ */
116
+ export const Config: z<Config> = z.object({
117
+ mode: z.union(Object.values(SessionTelemetryMode)).default(DEFAULT_TELEMETRY_MODE),
118
+ exporter: z.any(),
119
+ processor: z.any(),
120
+ shutdownTimeoutMillis: z.number(),
121
+ maxRequestBytes: z.number().step(1).min(1).max(4_000_000),
122
+ })
123
+
124
+ /** Default outer allowance for the SDK's complete shutdown sequence. */
125
+ export const DEFAULT_SHUTDOWN_TIMEOUT_MILLIS = 3_000
126
+
127
+ // Node clamps larger timer delays to one millisecond. This is a runtime
128
+ // protocol limit, not a deployment default.
129
+ const MAX_TIMER_DELAY_MILLIS = 2_147_483_647
130
+
131
+ /** Severity mapping from the Service Definition's three-level vocabulary to OTel severity numbers. */
132
+ const SEVERITY: Record<SessionTelemetrySeverity, SeverityNumber> = {
133
+ info: SeverityNumber.INFO,
134
+ warn: SeverityNumber.WARN,
135
+ error: SeverityNumber.ERROR,
136
+ }
137
+
138
+ /**
139
+ * The backend plugin — the only entry a deployment loads. It always registers
140
+ * the `sessionTelemetry` service (duplicate load throws). `FEEDBACK_ONLY` wires the SDK
141
+ * pipeline and on-demand {@link SessionTelemetryCoordinator}; `DISABLED` constructs no
142
+ * SDK state and listens only to warn when recorded feedback stays local.
143
+ */
144
+ export class OpenTelemetrySessionBackend extends SessionTelemetryBackend {
145
+ static inject = ['sessions', 'otel']
146
+ static Config = Config
147
+
148
+ private readonly provider: SessionLogReporter | undefined
149
+ private readonly shutdownTimeoutMillis: number
150
+ override readonly sharing: SessionTelemetrySharingStatus
151
+
152
+ constructor(ctx: Context, config: Config) {
153
+ const mode = resolveMode(config.mode)
154
+ super(ctx)
155
+ this.sharing = sharingStatusFor(mode)
156
+ if (mode === SessionTelemetryMode.DISABLED) {
157
+ this.provider = undefined
158
+ this.shutdownTimeoutMillis = DEFAULT_SHUTDOWN_TIMEOUT_MILLIS
159
+ ctx.on('session/event', (session, event) => {
160
+ if (isFeedback(session, event)) ctx.logger.warn(DISABLED_FEEDBACK_WARNING)
161
+ })
162
+ return
163
+ }
164
+
165
+ const url = config.exporter?.url
166
+ if (url === undefined || url.length === 0) {
167
+ throw new Error('session-telemetry-otel: exporter.url is required (the full OTLP logs endpoint)')
168
+ }
169
+ let parsed: URL
170
+ try {
171
+ parsed = new URL(url)
172
+ } catch {
173
+ // Re-thrown as a config error: the only way here is a malformed url string.
174
+ throw new Error(`session-telemetry-otel: exporter.url is not a valid URL: ${JSON.stringify(url)}`)
175
+ }
176
+ if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {
177
+ throw new Error(`session-telemetry-otel: exporter.url must be http(s), got ${parsed.protocol}`)
178
+ }
179
+ // Reject empty batches before allocating the reporter.
180
+ const batchSize = config.processor?.maxExportBatchSize
181
+ if (batchSize !== undefined && (!Number.isInteger(batchSize) || batchSize < 1)) {
182
+ throw new Error(`session-telemetry-otel: processor.maxExportBatchSize must be a positive integer, got ${String(batchSize)}`)
183
+ }
184
+ const shutdownTimeoutMillis = config.shutdownTimeoutMillis ?? DEFAULT_SHUTDOWN_TIMEOUT_MILLIS
185
+ if (!Number.isFinite(shutdownTimeoutMillis) || shutdownTimeoutMillis <= 0 || shutdownTimeoutMillis > MAX_TIMER_DELAY_MILLIS) {
186
+ throw new Error(`session-telemetry-otel: shutdownTimeoutMillis must be a positive finite number no greater than ${MAX_TIMER_DELAY_MILLIS}, got ${String(shutdownTimeoutMillis)}`)
187
+ }
188
+ this.shutdownTimeoutMillis = shutdownTimeoutMillis
189
+ const { version } = createRequire(import.meta.url)('../package.json') as { version: string }
190
+ const reporter = ctx.otel.createSessionLogReporter({
191
+ scope: { name: '@unieai/rabi-session-telemetry-otel', version },
192
+ exporter: { ...config.exporter, url },
193
+ ...(config.processor === undefined ? {} : { processor: config.processor }),
194
+ ...(config.maxRequestBytes === undefined ? {} : { maxRequestBytes: config.maxRequestBytes }),
195
+ resourceAttributes: {
196
+ 'service.name': APP_IDENTITY.product,
197
+ 'service.version': APP_IDENTITY.version,
198
+ 'user.id': getOrCreateAnonymousUserId(),
199
+ },
200
+ onFailure: (message, error) => { ctx.logger.warn(message, error) },
201
+ })
202
+ this.provider = reporter
203
+ const enqueue: SessionTelemetrySink['emit'] = (record) => {
204
+ if (record.sourceEvent === undefined) {
205
+ ctx.logger.warn('Session log record withheld: redaction removed sourceEvent')
206
+ return
207
+ }
208
+ reporter.reportSessionLog({
209
+ sessionId: record.sourceEvent.sessionId,
210
+ event: { ...record.sourceEvent.envelope, data: record.body },
211
+ severityNumber: SEVERITY[record.severity],
212
+ attributes: record.attributes,
213
+ })
214
+ }
215
+ const backend: SessionTelemetrySink = {
216
+ emit: enqueue,
217
+ shutdown: () => this.shutdown(),
218
+ }
219
+ const coordinator = new SessionTelemetryCoordinator(ctx, backend, {
220
+ capture: 'on-demand',
221
+ includeHistory: true,
222
+ })
223
+ ctx.on('session/event', (session, event) => {
224
+ if (!isFeedback(session, event)) return
225
+ // Only the canonical appended event authorizes this exact prefix.
226
+ // oxlint-disable-next-line typescript/no-deprecated -- Existing Session history read; migration deferred.
227
+ if (session.eventAt(event.seq) !== event) {
228
+ ctx.logger.warn(NON_CANONICAL_EVENT_WARNING)
229
+ return
230
+ }
231
+ coordinator.captureSession(session, event.seq)
232
+ })
233
+ ctx.on('feedback/committed', (inspection) => {
234
+ const snapshot = structuredClone(inspection)
235
+ const committed = snapshot.events.at(-1)
236
+ if (committed === undefined) return
237
+ const session = Session.fromRestore(
238
+ snapshot.meta.id, snapshot.events, snapshot.meta, snapshot.inheritedEventCount,
239
+ 'detached', ctx.sessions.messageProjections,
240
+ )
241
+ // fromRestore appends a lifecycle marker that this submission did not commit.
242
+ if (isFeedback(session, committed)) coordinator.captureSession(session, committed.seq)
243
+ })
244
+ }
245
+
246
+ /**
247
+ * Drop direct records. Only a new canonical feedback submission can authorize
248
+ * capture through the private coordinator sink, for every provider.
249
+ * @param _record - the direct record, never uploaded.
250
+ */
251
+ emit(_record: SessionTelemetryRecord): void {}
252
+
253
+ /**
254
+ * Drain queued HTTP requests until the deployment deadline. The watchdog
255
+ * never releases an unsettled transport slot. At the outer deadline,
256
+ * queued records are abandoned and no further requests may start.
257
+ * @returns completion after transport shutdown, or rejection at the configured deadline.
258
+ */
259
+ async shutdown(): Promise<void> {
260
+ if (this.provider === undefined) return
261
+ const providerShutdown = this.provider.shutdown()
262
+ let timer: ReturnType<typeof setTimeout> | undefined
263
+ const deadline = new Promise<never>((_resolve, reject) => {
264
+ timer = setTimeout(() => {
265
+ this.provider?.stopPending()
266
+ reject(new Error(`session-telemetry-otel: provider shutdown exceeded ${this.shutdownTimeoutMillis}ms`))
267
+ }, this.shutdownTimeoutMillis)
268
+ })
269
+ try {
270
+ await Promise.race([providerShutdown, deadline])
271
+ } finally {
272
+ /* v8 ignore else -- the Promise executor assigns timer synchronously before this race starts. */
273
+ if (timer !== undefined) clearTimeout(timer)
274
+ }
275
+ }
276
+ }
277
+
278
+ export default OpenTelemetrySessionBackend