@unieai/rabi-session-telemetry-otel 0.0.0-stage → 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/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-otel
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
+ Feedback-authorized Session logs over byte-bounded OpenTelemetry HTTP requests
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,212 @@
1
+ import { createRequire } from "node:module";
2
+ import z from "@unieai/schemastery";
3
+ import { Session } from "@unieai/rabi-session";
4
+ import { SessionTelemetryBackend, SessionTelemetryCoordinator } from "@unieai/rabi-session-telemetry";
5
+ import { APP_IDENTITY } from "@unieai/rabi-llm";
6
+ import { getOrCreateAnonymousUserId } from "@unieai/rabi-anonymous-user-id";
7
+ import { SeverityNumber } from "@opentelemetry/api-logs";
8
+ //#region lib/types/index.js
9
+ /**
10
+ * OpenTelemetry Service Provider for the Rabi Harness telemetry capability.
11
+ *
12
+ * Authorizes feedback-bounded capture and hands complete event strings to the
13
+ * Session-log reporter. This plugin owns resource identity and an outer
14
+ * shutdown deadline; the reporter owns byte-bounded SDK delivery.
15
+ *
16
+ * @module @unieai/rabi-session-telemetry-otel
17
+ */
18
+ /** Session-sharing policy selected by {@link Config.mode}. */
19
+ var SessionTelemetryMode;
20
+ (function(SessionTelemetryMode) {
21
+ SessionTelemetryMode["FEEDBACK_ONLY"] = "FEEDBACK_ONLY";
22
+ SessionTelemetryMode["DISABLED"] = "DISABLED";
23
+ })(SessionTelemetryMode || (SessionTelemetryMode = {}));
24
+ /** Default session-sharing policy for schema and direct construction. */
25
+ const DEFAULT_TELEMETRY_MODE = SessionTelemetryMode.FEEDBACK_ONLY;
26
+ const DISABLED_FEEDBACK_WARNING = "OpenTelemetry session upload is DISABLED; this feedback is not uploaded through OpenTelemetry";
27
+ const NON_CANONICAL_EVENT_WARNING = "session telemetry ignored an event absent from the canonical session log";
28
+ /** Only this Session's explicit feedback authorizes replay; fork seeds do not. */
29
+ function isFeedback(session, event) {
30
+ if (event.seq < session.inheritedEventCount) return false;
31
+ switch (event.type) {
32
+ case "feedback/record": return true;
33
+ case "feedback/message-put":
34
+ case "feedback/message-delete": return event.data.sessionId === session.id;
35
+ default: return false;
36
+ }
37
+ }
38
+ /** Resolve the default and reject unknown runtime values before transport setup. */
39
+ function resolveMode(mode) {
40
+ const resolved = mode ?? DEFAULT_TELEMETRY_MODE;
41
+ switch (resolved) {
42
+ case SessionTelemetryMode.FEEDBACK_ONLY:
43
+ case SessionTelemetryMode.DISABLED: return resolved;
44
+ default: return assertNever(resolved);
45
+ }
46
+ }
47
+ /** Fail closed when direct construction bypasses the runtime config schema. */
48
+ function assertNever(value) {
49
+ throw new Error(`session-telemetry-otel: unsupported mode ${JSON.stringify(value)}`);
50
+ }
51
+ /** Map the serialized mode onto the seam's backend-independent sharing vocabulary. */
52
+ function sharingStatusFor(mode) {
53
+ switch (mode) {
54
+ case SessionTelemetryMode.FEEDBACK_ONLY: return "feedback-only";
55
+ case SessionTelemetryMode.DISABLED: return "disabled";
56
+ /* v8 ignore next 2 -- resolveMode already rejected unknown values before this switch; the closed enum cannot reach the default. */
57
+ default: return assertNever(mode);
58
+ }
59
+ }
60
+ /**
61
+ * Schemastery validator for {@link Config}; cordis runs it before the plugin
62
+ * starts. The constructor validates endpoint and shutdown requirements; the
63
+ * reporter validates Session byte and queue limits. SDK transport and
64
+ * processor settings use the reporter's accepted option types, which exclude
65
+ * self-observability metering.
66
+ */
67
+ const Config = z.object({
68
+ mode: z.union(Object.values(SessionTelemetryMode)).default(DEFAULT_TELEMETRY_MODE),
69
+ exporter: z.any(),
70
+ processor: z.any(),
71
+ shutdownTimeoutMillis: z.number(),
72
+ maxRequestBytes: z.number().step(1).min(1).max(4e6)
73
+ });
74
+ /** Default outer allowance for the SDK's complete shutdown sequence. */
75
+ const DEFAULT_SHUTDOWN_TIMEOUT_MILLIS = 3e3;
76
+ const MAX_TIMER_DELAY_MILLIS = 2147483647;
77
+ /** Severity mapping from the Service Definition's three-level vocabulary to OTel severity numbers. */
78
+ const SEVERITY = {
79
+ info: SeverityNumber.INFO,
80
+ warn: SeverityNumber.WARN,
81
+ error: SeverityNumber.ERROR
82
+ };
83
+ /**
84
+ * The backend plugin — the only entry a deployment loads. It always registers
85
+ * the `sessionTelemetry` service (duplicate load throws). `FEEDBACK_ONLY` wires the SDK
86
+ * pipeline and on-demand {@link SessionTelemetryCoordinator}; `DISABLED` constructs no
87
+ * SDK state and listens only to warn when recorded feedback stays local.
88
+ */
89
+ var OpenTelemetrySessionBackend = class extends SessionTelemetryBackend {
90
+ static inject = ["sessions", "otel"];
91
+ static Config = Config;
92
+ provider;
93
+ shutdownTimeoutMillis;
94
+ sharing;
95
+ constructor(ctx, config) {
96
+ const mode = resolveMode(config.mode);
97
+ super(ctx);
98
+ this.sharing = sharingStatusFor(mode);
99
+ if (mode === SessionTelemetryMode.DISABLED) {
100
+ this.provider = void 0;
101
+ this.shutdownTimeoutMillis = DEFAULT_SHUTDOWN_TIMEOUT_MILLIS;
102
+ ctx.on("session/event", (session, event) => {
103
+ if (isFeedback(session, event)) ctx.logger.warn(DISABLED_FEEDBACK_WARNING);
104
+ });
105
+ return;
106
+ }
107
+ const url = config.exporter?.url;
108
+ if (url === void 0 || url.length === 0) throw new Error("session-telemetry-otel: exporter.url is required (the full OTLP logs endpoint)");
109
+ let parsed;
110
+ try {
111
+ parsed = new URL(url);
112
+ } catch {
113
+ throw new Error(`session-telemetry-otel: exporter.url is not a valid URL: ${JSON.stringify(url)}`);
114
+ }
115
+ if (parsed.protocol !== "http:" && parsed.protocol !== "https:") throw new Error(`session-telemetry-otel: exporter.url must be http(s), got ${parsed.protocol}`);
116
+ const batchSize = config.processor?.maxExportBatchSize;
117
+ if (batchSize !== void 0 && (!Number.isInteger(batchSize) || batchSize < 1)) throw new Error(`session-telemetry-otel: processor.maxExportBatchSize must be a positive integer, got ${String(batchSize)}`);
118
+ const shutdownTimeoutMillis = config.shutdownTimeoutMillis ?? 3e3;
119
+ if (!Number.isFinite(shutdownTimeoutMillis) || shutdownTimeoutMillis <= 0 || shutdownTimeoutMillis > MAX_TIMER_DELAY_MILLIS) throw new Error(`session-telemetry-otel: shutdownTimeoutMillis must be a positive finite number no greater than ${MAX_TIMER_DELAY_MILLIS}, got ${String(shutdownTimeoutMillis)}`);
120
+ this.shutdownTimeoutMillis = shutdownTimeoutMillis;
121
+ const { version } = createRequire(import.meta.url)("../package.json");
122
+ const reporter = ctx.otel.createSessionLogReporter({
123
+ scope: {
124
+ name: "@unieai/rabi-session-telemetry-otel",
125
+ version
126
+ },
127
+ exporter: {
128
+ ...config.exporter,
129
+ url
130
+ },
131
+ ...config.processor === void 0 ? {} : { processor: config.processor },
132
+ ...config.maxRequestBytes === void 0 ? {} : { maxRequestBytes: config.maxRequestBytes },
133
+ resourceAttributes: {
134
+ "service.name": APP_IDENTITY.product,
135
+ "service.version": APP_IDENTITY.version,
136
+ "user.id": getOrCreateAnonymousUserId()
137
+ },
138
+ onFailure: (message, error) => {
139
+ ctx.logger.warn(message, error);
140
+ }
141
+ });
142
+ this.provider = reporter;
143
+ const enqueue = (record) => {
144
+ if (record.sourceEvent === void 0) {
145
+ ctx.logger.warn("Session log record withheld: redaction removed sourceEvent");
146
+ return;
147
+ }
148
+ reporter.reportSessionLog({
149
+ sessionId: record.sourceEvent.sessionId,
150
+ event: {
151
+ ...record.sourceEvent.envelope,
152
+ data: record.body
153
+ },
154
+ severityNumber: SEVERITY[record.severity],
155
+ attributes: record.attributes
156
+ });
157
+ };
158
+ const coordinator = new SessionTelemetryCoordinator(ctx, {
159
+ emit: enqueue,
160
+ shutdown: () => this.shutdown()
161
+ }, {
162
+ capture: "on-demand",
163
+ includeHistory: true
164
+ });
165
+ ctx.on("session/event", (session, event) => {
166
+ if (!isFeedback(session, event)) return;
167
+ if (session.eventAt(event.seq) !== event) {
168
+ ctx.logger.warn(NON_CANONICAL_EVENT_WARNING);
169
+ return;
170
+ }
171
+ coordinator.captureSession(session, event.seq);
172
+ });
173
+ ctx.on("feedback/committed", (inspection) => {
174
+ const snapshot = structuredClone(inspection);
175
+ const committed = snapshot.events.at(-1);
176
+ if (committed === void 0) return;
177
+ const session = Session.fromRestore(snapshot.meta.id, snapshot.events, snapshot.meta, snapshot.inheritedEventCount, "detached", ctx.sessions.messageProjections);
178
+ if (isFeedback(session, committed)) coordinator.captureSession(session, committed.seq);
179
+ });
180
+ }
181
+ /**
182
+ * Drop direct records. Only a new canonical feedback submission can authorize
183
+ * capture through the private coordinator sink, for every provider.
184
+ * @param _record - the direct record, never uploaded.
185
+ */
186
+ emit(_record) {}
187
+ /**
188
+ * Drain queued HTTP requests until the deployment deadline. The watchdog
189
+ * never releases an unsettled transport slot. At the outer deadline,
190
+ * queued records are abandoned and no further requests may start.
191
+ * @returns completion after transport shutdown, or rejection at the configured deadline.
192
+ */
193
+ async shutdown() {
194
+ if (this.provider === void 0) return;
195
+ const providerShutdown = this.provider.shutdown();
196
+ let timer;
197
+ const deadline = new Promise((_resolve, reject) => {
198
+ timer = setTimeout(() => {
199
+ this.provider?.stopPending();
200
+ reject(/* @__PURE__ */ new Error(`session-telemetry-otel: provider shutdown exceeded ${this.shutdownTimeoutMillis}ms`));
201
+ }, this.shutdownTimeoutMillis);
202
+ });
203
+ try {
204
+ await Promise.race([providerShutdown, deadline]);
205
+ } finally {
206
+ /* v8 ignore else -- the Promise executor assigns timer synchronously before this race starts. */
207
+ if (timer !== void 0) clearTimeout(timer);
208
+ }
209
+ }
210
+ };
211
+ //#endregion
212
+ export { Config, DEFAULT_SHUTDOWN_TIMEOUT_MILLIS, DEFAULT_TELEMETRY_MODE, OpenTelemetrySessionBackend, OpenTelemetrySessionBackend as default, SessionTelemetryMode };
@@ -0,0 +1,87 @@
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
+ import z from '@unieai/schemastery';
11
+ import type { Context } from '@unieai/cordis';
12
+ import { SessionTelemetryBackend, type SessionTelemetryRecord, type SessionTelemetrySharingStatus } from '@unieai/rabi-session-telemetry';
13
+ import type { LogExporterOptions, SessionLogProcessorOptions } from '@unieai/rabi-otel';
14
+ /** Session-sharing policy selected by {@link Config.mode}. */
15
+ export declare enum SessionTelemetryMode {
16
+ FEEDBACK_ONLY = "FEEDBACK_ONLY",
17
+ DISABLED = "DISABLED"
18
+ }
19
+ /** Default session-sharing policy for schema and direct construction. */
20
+ export declare const DEFAULT_TELEMETRY_MODE = SessionTelemetryMode.FEEDBACK_ONLY;
21
+ /**
22
+ * Plugin configuration: sharing policy, SDK transport options, byte/count queue
23
+ * settings, and an overall shutdown bound. Uploading modes validate their endpoint
24
+ * and shutdown deadline at plugin load; `DISABLED` reads neither.
25
+ */
26
+ export interface Config {
27
+ /** Defaults to `FEEDBACK_ONLY`: capture session history only when feedback is explicitly submitted. */
28
+ mode?: SessionTelemetryMode;
29
+ /**
30
+ * Explicit SDK HTTP transport settings, including optional routing headers.
31
+ * Ambient credentials are not inherited. URL is required while uploading.
32
+ * Exporter self-observability metering is not supported.
33
+ */
34
+ exporter?: Omit<LogExporterOptions, 'url'> & {
35
+ /** Full logs endpoint (e.g. `https://collector.example.com/v1/logs`). Required outside `DISABLED`; validated at load. */
36
+ url?: string;
37
+ };
38
+ /**
39
+ * Count, queue, cadence, and per-request watchdog settings for the byte-bounded
40
+ * processor. A watchdog warning never releases an unsettled transport slot.
41
+ * SDK processor self-observability metering is not supported.
42
+ */
43
+ processor?: SessionLogProcessorOptions;
44
+ /** Maximum time spent awaiting the SDK provider's complete shutdown path. */
45
+ shutdownTimeoutMillis?: number;
46
+ /** Uncompressed OTLP request byte limit, at most 4,000,000. */
47
+ maxRequestBytes?: number;
48
+ }
49
+ /**
50
+ * Schemastery validator for {@link Config}; cordis runs it before the plugin
51
+ * starts. The constructor validates endpoint and shutdown requirements; the
52
+ * reporter validates Session byte and queue limits. SDK transport and
53
+ * processor settings use the reporter's accepted option types, which exclude
54
+ * self-observability metering.
55
+ */
56
+ export declare const Config: z<Config>;
57
+ /** Default outer allowance for the SDK's complete shutdown sequence. */
58
+ export declare const DEFAULT_SHUTDOWN_TIMEOUT_MILLIS = 3000;
59
+ /**
60
+ * The backend plugin — the only entry a deployment loads. It always registers
61
+ * the `sessionTelemetry` service (duplicate load throws). `FEEDBACK_ONLY` wires the SDK
62
+ * pipeline and on-demand {@link SessionTelemetryCoordinator}; `DISABLED` constructs no
63
+ * SDK state and listens only to warn when recorded feedback stays local.
64
+ */
65
+ export declare class OpenTelemetrySessionBackend extends SessionTelemetryBackend {
66
+ static inject: string[];
67
+ static Config: z<Config>;
68
+ private readonly provider;
69
+ private readonly shutdownTimeoutMillis;
70
+ readonly sharing: SessionTelemetrySharingStatus;
71
+ constructor(ctx: Context, config: Config);
72
+ /**
73
+ * Drop direct records. Only a new canonical feedback submission can authorize
74
+ * capture through the private coordinator sink, for every provider.
75
+ * @param _record - the direct record, never uploaded.
76
+ */
77
+ emit(_record: SessionTelemetryRecord): void;
78
+ /**
79
+ * Drain queued HTTP requests until the deployment deadline. The watchdog
80
+ * never releases an unsettled transport slot. At the outer deadline,
81
+ * queued records are abandoned and no further requests may start.
82
+ * @returns completion after transport shutdown, or rejection at the configured deadline.
83
+ */
84
+ shutdown(): Promise<void>;
85
+ }
86
+ export default OpenTelemetrySessionBackend;
87
+ //# sourceMappingURL=index.d.ts.map
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/en.json ADDED
@@ -0,0 +1,5 @@
1
+ {
2
+ "meta": {
3
+ "title": "session-telemetry-otel"
4
+ }
5
+ }
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/locale/zh.json ADDED
@@ -0,0 +1,6 @@
1
+ {
2
+ "meta": {
3
+ "title": "反馈会话日志上传",
4
+ "description": "按反馈授权策略,通过 OpenTelemetry 上传相关会话日志。"
5
+ }
6
+ }
package/package.json CHANGED
@@ -1,6 +1,44 @@
1
1
  {
2
2
  "name": "@unieai/rabi-session-telemetry-otel",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "description": "Feedback-authorized Session logs over byte-bounded OpenTelemetry HTTP requests",
4
+ "version": "0.2.2-rc.5",
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
+ "./locale/*.json": "./locale/*.json"
19
+ },
20
+ "files": [
21
+ "locale/*.json",
22
+ "lib/index.js",
23
+ "lib/types/**/*.d.ts",
24
+ "lib/types/**/*.d.ts.map",
25
+ "lib/**/*.js.map",
26
+ "src",
27
+ "README.md"
28
+ ],
29
+ "license": "MIT",
30
+ "dependencies": {
31
+ "@opentelemetry/api-logs": "0.222.0",
32
+ "@unieai/schemastery": "3.19.0"
33
+ },
34
+ "peerDependencies": {
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"
43
+ }
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