@deepseek-ai/dsh-session-telemetry-otel 0.2.3-alpha.1 → 0.2.3-alpha.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/README.i18n.yaml CHANGED
@@ -21,14 +21,17 @@
21
21
  en: bc7e598148a7f8c3
22
22
  zh: 0209c6aa258ec134
23
23
  /deepseek-ai-dsh-session-telemetry-otel/use-this-package/minimal-configuration:
24
- en: 11845fd50dc0a494
25
- zh: ee990bfca3621bd3
24
+ en: bb5d467582fe6894
25
+ zh: c3056fb1840568d1
26
+ /deepseek-ai-dsh-session-telemetry-otel/use-this-package/rolling-out-per-batch:
27
+ en: c18541849fa2b060
28
+ zh: e70303beabe3d7a8
26
29
  /deepseek-ai-dsh-session-telemetry-otel/use-this-package/what-leaves-the-machine:
27
30
  en: 2a5ddd227e400455
28
31
  zh: 74b7bd9b9161b054
29
32
  /deepseek-ai-dsh-session-telemetry-otel/use-this-package/failures-and-shutdown:
30
- en: a66831cb9de57e04
31
- zh: 3ada28bb868e0932
33
+ en: 9c88ad1d082199ef
34
+ zh: aa2ea792d4a7cbd7
32
35
  /deepseek-ai-dsh-session-telemetry-otel/understand-the-implementation:
33
36
  en: ee672a6a6f0fa02d
34
37
  zh: c3bab8e6b60e768c
@@ -36,14 +39,14 @@
36
39
  en: 34f8a88224a1f6cf
37
40
  zh: 40839dabaea39602
38
41
  /deepseek-ai-dsh-session-telemetry-otel/understand-the-implementation/source-map:
39
- en: 0b99d2e5c27213cd
40
- zh: 3cbdaa7f6a45d81a
42
+ en: f4aa1ced4f1365bb
43
+ zh: 3285ecdc0f146555
41
44
  /deepseek-ai-dsh-session-telemetry-otel/understand-the-implementation/capture-wiring:
42
45
  en: 5c85eb0992eb5b2b
43
46
  zh: a19cdd5814c0e2b9
44
47
  /deepseek-ai-dsh-session-telemetry-otel/understand-the-implementation/field-mapping:
45
- en: a42e9e081fb93bee
46
- zh: b8e817c2455278b9
48
+ en: 474e76e8ff93567b
49
+ zh: 89d75b2546381465
47
50
  /deepseek-ai-dsh-session-telemetry-otel/further-exploration:
48
51
  en: 155b75490ec65d86
49
52
  zh: 07d37d6e4ac90c89
@@ -54,8 +57,8 @@
54
57
  en: 7593cf5d0d2cedd6
55
58
  zh: f57cc48a1b5cbfa9
56
59
  /deepseek-ai-dsh-session-telemetry-otel/known-limitations-and-deferred-work:
57
- en: 5d0b88f8256bd782
58
- zh: 36b8d64645ed6c2e
60
+ en: 6aaa644d23cd4360
61
+ zh: d4fe7d878daf65f3
59
62
  /deepseek-ai-dsh-session-telemetry-otel/known-limitations-and-deferred-work/dev-note:
60
63
  en: e67f633dc6fe7773
61
64
  zh: 3bb0c20c93f16f98
package/README.md CHANGED
@@ -53,6 +53,10 @@ Uploading modes require an exporter URL. Processor settings control the independ
53
53
  headers:
54
54
  authorization: !!js `Bearer ${process.env.OTLP_TOKEN}`
55
55
  processor: {} # optional; byte/count batching and per-request watchdog
56
+ recordFormat: per-event # optional; per-event (default) or per-batch
57
+ maxBatchEvents: 128 # optional; per-batch only
58
+ maxBatchBytes: 1048576 # optional; per-batch only
59
+ batchDelayMillis: 1000 # optional; per-batch only
56
60
  ```
57
61
 
58
62
  | Field | Default | Meaning |
@@ -62,20 +66,41 @@ Uploading modes require an exporter URL. Processor settings control the independ
62
66
  | `exporter`, `processor` | — | SDK transport plus byte/count batching; headers/TLS identity are not inherited from the environment. Agent factories own their returned agent settings, including keepAlive |
63
67
  | `shutdownTimeoutMillis` | `3,000` | Outer deadline for all queued HTTP requests; remaining queued sends stop at expiry |
64
68
  | `maxRequestBytes` | `4,000,000` | Maximum complete OTLP JSON request bytes before gzip; may only be lowered |
69
+ | `recordFormat` | `per-event` | OTLP record granularity: `per-event` keeps the existing one-record-per-event format; `per-batch` sends one record per contiguous Session delivery batch |
70
+ | `maxBatchEvents` | `128` | `per-batch` only: maximum events per record |
71
+ | `maxBatchBytes` | `1,048,576` | `per-batch` only: maximum record body JSON bytes; a larger single event still ships as its own batch |
72
+ | `batchDelayMillis` | `1,000` | `per-batch` only: maximum age of the oldest buffered event before the record is emitted |
65
73
 
66
74
  Direct `ctx.sessionTelemetry.emit()` calls are no-ops in every mode and cannot bypass feedback authorization. Inherited parent feedback does not authorize a child export: the child needs new feedback of its own. Its authorized prefix then includes inherited context.
67
75
 
68
76
  Model requests, request headers, Session creation or adoption, restoration, and plugin mount or HMR do not authorize capture. Stored feedback alone triggers nothing. Scheduled flush and shutdown may finish batches authorized earlier, but never capture new records.
69
77
 
78
+ ### Rolling out per-batch
79
+
80
+ The default is `per-event`. Enable the new format per deployment with a profile overlay that repeats the entry's complete `config`, because an overlay replaces that object instead of merging it. Copy the deployment's existing `mode`, `exporter`, and `processor` values and change only `recordFormat`:
81
+
82
+ ```yaml
83
+ - id: session-telemetry-otel
84
+ config:
85
+ mode: FEEDBACK_ONLY
86
+ exporter:
87
+ url: https://dsh-otel-collector.deepseeksvc.com/v1/logs
88
+ processor: {}
89
+ recordFormat: per-batch
90
+ ```
91
+
92
+ A deployment that enables `per-batch` confirms two things first: the collector accepts the larger single record (default body ceiling 1 MB) and downstream queries unwrap `body.events`.
93
+
70
94
  ### What leaves the machine
71
95
 
72
96
  Each Session event becomes one `eventName: "session-log"` record. `attributes.sessionId` is the collector Session identity; `attributes.content` encodes the complete event envelope with redacted `event.data`. JSON values are preserved, not the original JSONL bytes or key ordering. Legacy `session.id`, `event.seq`, and `event.type` metadata remain for existing consumers. Resources carry application and anonymous-user identity; scope carries the backend package name and version. The base profile uses `https://dsh-otel-collector.deepseeksvc.com/v1/logs`; `DSH_TELEMETRY_OTLP_URL` overrides it. No channel header is added implicitly.
73
97
 
98
+
74
99
  The shared OTel channel measures each record once with the SDK OTLP JSON serializer, including its resource/scope envelope, then greedily packs requests using those conservative sizes. A single oversized event produces one rejection diagnostic without truncation. Session logs never mix with product analytics in a request. Capture handoff and shutdown are not collector acknowledgements.
75
100
 
76
101
  ### Failures and shutdown
77
102
 
78
- Invalid byte limits, non-positive queue/timer values, `maxExportBatchSize > maxQueueSize`, invalid endpoints, and invalid shutdown deadlines fail at load. Processor defaults are 2,048 queued records, 512 records per request, a 1,000 ms scheduling delay, and a 30,000 ms request watchdog. Byte limits may split a count batch into multiple serial HTTP requests. Each request waits for SDK export-queue cleanup after its callback before the next starts. `exportTimeoutMillis` warns per request but never frees an unsettled transport slot; the SDK transport owns network timeout/retry. Shutdown drains these requests until `shutdownTimeoutMillis`; expiry discards the remaining queue and prevents further sends, while an active request may still settle. Large prefixes can therefore remain partially unsent at CLI exit.
103
+ Invalid byte limits, non-positive queue/timer values, `maxExportBatchSize > maxQueueSize`, invalid endpoints, invalid shutdown deadlines, an unknown `recordFormat`, and non-positive or out-of-range `per-batch` ceilings fail at load. Processor defaults are 2,048 queued records, 512 records per request, a 1,000 ms scheduling delay, and a 30,000 ms request watchdog. Byte limits may split a count batch into multiple serial HTTP requests. Each request waits for SDK export-queue cleanup after its callback before the next starts. `exportTimeoutMillis` warns per request but never frees an unsettled transport slot; the SDK transport owns network timeout/retry. Shutdown drains these requests until `shutdownTimeoutMillis`; expiry discards the remaining queue and prevents further sends, while an active request may still settle. Large prefixes can therefore remain partially unsent at CLI exit.
79
104
 
80
105
  -----
81
106
 
@@ -95,7 +120,8 @@ The backend owns feedback authorization, identity, and shutdown. The shared OTel
95
120
 
96
121
  | File | Role |
97
122
  |---|---|
98
- | [`src/index.ts`](src/index.ts) | Plugin entry: mode resolution, fail-closed validation, SDK pipeline wiring, coordinator composition, shutdown deadline |
123
+ | [`src/index.ts`](src/index.ts) | Plugin entry: mode and record-format resolution, fail-closed validation, SDK pipeline wiring, coordinator composition, shutdown deadline |
124
+ | [`src/batch.ts`](src/batch.ts) | Delivery-batch assembly: per-Session buffers, the four flush triggers, sequence watermark, batch ids |
99
125
 
100
126
  ### Capture wiring
101
127
 
@@ -103,7 +129,7 @@ The backend captures history on demand through new own feedback events or commit
103
129
 
104
130
  ### Field mapping
105
131
 
106
- Each capture record supplies a separately copied event envelope and redacted payload to `SessionLogReporter`; serialization retains optional surface metadata and the event sequence/time. Feedback authorizes the complete unhanded prefix, not only the feedback payload.
132
+ Each capture record supplies a separately copied event envelope and redacted payload to `SessionLogReporter`; serialization retains optional surface metadata and the event sequence/time. Feedback authorizes the complete unhanded prefix, not only the feedback payload. In `per-batch` mode the assembler buffers those records per Session and forms exactly one contiguous range per flush, using each event's canonical sequence and the format generation from the record's `session.format_version` attribute.
107
133
 
108
134
  </details>
109
135
 
@@ -141,6 +167,8 @@ These limits define where SDK behavior governs and where export guarantees end.
141
167
  - **Live-collector behavior belongs to the SDK exporter** — authentication, TLS, throttling, and other real OTLP deployment behavior follow the upstream SDK rather than a package-owned compatibility layer.
142
168
  - **Best-effort handoff** — new cold snapshots and a new feedback submission after restart can repeat prefixes; receivers deduplicate by Session id, format version, and event seq. There is no durable outbox, delivery watermark, automatic retry promise, or collector-acceptance guarantee. OTel and the opt-in DeepSeek API path can overlap. Withdrawal exports a deletion event, not remote erasure.
143
169
 
170
+ - **Batch-mode cursor scope** — a Session's sequence watermark lives as long as its assembler state; closing the Session drops it, so a later lifecycle of the same Session id restarts that cursor and can resend a prefix the receiver already holds. Deduplicate by unwrapping the batch body and keying on Session id, format version, and event seq. A batch's `(after_seq, through_seq)` range narrows the work but is not a stable key, because flush timing changes batch boundaries.
171
+
144
172
  - **Backend availability** — feedback submitted while this plugin is disabled or unloaded is recorded locally but not automatically replayed when it returns. Capture requires the subscriber to remain mounted until it observes the submission; unloading during a pending cold write can miss its post-flush notification.
145
173
 
146
174
  <a id="dev-note"></a>
package/README.zh.md CHANGED
@@ -53,6 +53,10 @@ kind: "package-reference"
53
53
  headers:
54
54
  authorization: !!js `Bearer ${process.env.OTLP_TOKEN}`
55
55
  processor: {} # optional; byte/count batching and per-request watchdog
56
+ recordFormat: per-event # optional; per-event (default) or per-batch
57
+ maxBatchEvents: 128 # optional; per-batch only
58
+ maxBatchBytes: 1048576 # optional; per-batch only
59
+ batchDelayMillis: 1000 # optional; per-batch only
56
60
  ```
57
61
 
58
62
  | 字段 | 默认值 | 含义 |
@@ -62,20 +66,41 @@ kind: "package-reference"
62
66
  | `exporter`, `processor` | — | SDK 传输及字节/条数聚合;不继承环境中的头部和 TLS 身份。agent 工厂负责返回实例的设置,包括 keepAlive |
63
67
  | `shutdownTimeoutMillis` | `3,000` | 所有排队 HTTP 请求的外层期限;到期后停止剩余排队发送 |
64
68
  | `maxRequestBytes` | `4,000,000` | gzip 前完整 OTLP JSON 请求的最大字节数;只能调低 |
69
+ | `recordFormat` | `per-event` | OTLP 记录粒度:`per-event` 保持现有逐事件记录格式;`per-batch` 每次连续 Session 投递批次一个记录 |
70
+ | `maxBatchEvents` | `128` | 仅 `per-batch`:单条记录最多事件数 |
71
+ | `maxBatchBytes` | `1,048,576` | 仅 `per-batch`:单条记录 body JSON 字节上限;单条超限事件仍独立成批 |
72
+ | `batchDelayMillis` | `1,000` | 仅 `per-batch`:最早缓冲事件的最长等待时间 |
65
73
 
66
74
  直接调用 `ctx.sessionTelemetry.emit()` 在任何模式下都是空操作,不能绕过反馈授权。继承的父会话反馈不授权子会话导出:子会话需要新的自身反馈。授权后的前缀包含继承的上下文。
67
75
 
68
76
  模型请求、请求头、Session 创建或接纳、恢复,以及插件挂载或 HMR(热模块替换)均不授权捕获。仅凭已存储的反馈不会触发任何操作。定时刷新和关闭可以完成先前已授权的批次,但绝不捕获新记录。
69
77
 
78
+ ### 灰度启用 per-batch
79
+
80
+ 默认值为 `per-event`。按部署启用新格式时,profile overlay 必须**重复该条目的完整 `config`**——overlay 整体替换这个对象而不是按字段合并。把部署原有的 `mode`、`exporter`、`processor` 一并写上,只修改 `recordFormat`:
81
+
82
+ ```yaml
83
+ - id: session-telemetry-otel
84
+ config:
85
+ mode: FEEDBACK_ONLY
86
+ exporter:
87
+ url: https://dsh-otel-collector.deepseeksvc.com/v1/logs
88
+ processor: {}
89
+ recordFormat: per-batch
90
+ ```
91
+
92
+ 启用 `per-batch` 的部署需先确认两件事:采集端接受更大的单条记录(默认 body 上限 1 MB),下游查询会展开 `body.events`。
93
+
70
94
  ### 哪些数据会离开本机
71
95
 
72
96
  每条 Session 事件对应一个 `eventName: "session-log"` 记录。`attributes.sessionId` 是 collector 使用的 Session 身份;`attributes.content` 编码完整事件 envelope 和脱敏后的 `event.data`。保留的是 JSON 值,不保证原 JSONL 字节或键顺序相同。为现有消费者保留 `session.id`、`event.seq` 和 `event.type` 元数据。Resource 携带应用和匿名用户身份;scope 携带后端包名和版本。基础配置使用 `https://dsh-otel-collector.deepseeksvc.com/v1/logs`,可用 `DSH_TELEMETRY_OTLP_URL` 覆盖。不隐式添加 channel 头。
73
97
 
98
+
74
99
  共享 OTel 通道使用 SDK 的 OTLP JSON 序列化器对每条记录计量一次,包含其 resource/scope envelope,再按保守大小顺序组包。单条超限事件产生一次拒绝诊断且不截断。Session 日志不会与产品埋点混在一个请求中。捕获交接和关闭完成不代表 collector 确认。
75
100
 
76
101
  ### 失败与关闭
77
102
 
78
- 无效字节上限、非正队列/计时值、`maxExportBatchSize > maxQueueSize`、无效 endpoint 或关闭期限在加载时失败。processor 默认队列为 2,048 条、单请求最多 512 条、调度延迟 1,000 ms、请求监测期限 30,000 ms。字节上限可能将按条数划分的批次拆成多个串行 HTTP 请求。每个请求在回调后等待 SDK 导出队列清理完成,才启动下一个请求。`exportTimeoutMillis` 针对每个请求告警,但不会释放未结束的传输槽位;SDK transport 负责网络超时和重试。关闭时发送这些请求直到 `shutdownTimeoutMillis`,到期后丢弃剩余队列并禁止后续发送,在途请求仍可能结束。因此较大的授权前缀在 CLI 退出时可能只发送了一部分。
103
+ 无效字节上限、非正队列/计时值、`maxExportBatchSize > maxQueueSize`、无效 endpoint、关闭期限、未知 `recordFormat` 以及非正或越界的 `per-batch` 上限在加载时失败。processor 默认队列为 2,048 条、单请求最多 512 条、调度延迟 1,000 ms、请求监测期限 30,000 ms。字节上限可能将按条数划分的批次拆成多个串行 HTTP 请求。每个请求在回调后等待 SDK 导出队列清理完成,才启动下一个请求。`exportTimeoutMillis` 针对每个请求告警,但不会释放未结束的传输槽位;SDK transport 负责网络超时和重试。关闭时发送这些请求直到 `shutdownTimeoutMillis`,到期后丢弃剩余队列并禁止后续发送,在途请求仍可能结束。因此较大的授权前缀在 CLI 退出时可能只发送了一部分。
79
104
 
80
105
  -----
81
106
 
@@ -95,7 +120,8 @@ kind: "package-reference"
95
120
 
96
121
  | 文件 | 职责 |
97
122
  |---|---|
98
- | [`src/index.ts`](src/index.ts) | 插件入口:模式解析、fail-closed 校验、SDK 流水线接线、协调器组装、关闭截止时间 |
123
+ | [`src/index.ts`](src/index.ts) | 插件入口:模式与记录格式解析、fail-closed 校验、SDK 流水线接线、协调器组装、关闭截止时间 |
124
+ | [`src/batch.ts`](src/batch.ts) | 投递批次组装:按会话缓冲、四个刷新触发条件、seq 水位、批次 id |
99
125
 
100
126
  ### 捕获接线
101
127
 
@@ -103,7 +129,7 @@ kind: "package-reference"
103
129
 
104
130
  ### 字段映射
105
131
 
106
- 每条采集记录向 `SessionLogReporter` 提供单独复制的事件信封和脱敏后的载荷;序列化保留可选的呈现元数据及事件序号和时间。反馈授权整个尚未交接的前缀,而不只是反馈载荷。
132
+ 每条采集记录向 `SessionLogReporter` 提供单独复制的事件信封和脱敏后的载荷;序列化保留可选的呈现元数据及事件序号和时间。反馈授权整个尚未交接的前缀,而不只是反馈载荷。`per-batch` 模式下,组装器按会话缓冲这些记录,每次刷新恰好形成一个连续区间,使用每个事件的权威 seq 和记录 `session.format_version` attribute 中的格式代际。
107
133
 
108
134
  </details>
109
135
 
@@ -141,6 +167,8 @@ kind: "package-reference"
141
167
  - **真实 collector 行为属于 SDK 导出器**——身份验证、TLS、限流及其他真实 OTLP 部署行为遵循上游 SDK,不由本包自有兼容层处理。
142
168
  - **尽力交接**——新冷快照以及重启后的新反馈提交可能重复前缀;接收方按 Session id、格式版本和事件 seq 去重。没有持久化 outbox、投递水位、自动重试承诺或采集端接受保证。OTel 与需显式启用的 DeepSeek API 路径可能重叠。撤回导出删除事件,不是远端擦除。
143
169
 
170
+ - **批次游标范围**——会话的 seq 水位随其组装器状态存活;会话关闭即被丢弃,因此同一 Session id 的后续生命周期重新开始该游标,可能重发接收方已持有的前缀。去重方式是展开批次 body,按 Session id、格式版本和事件 seq 作键;批次自身的 `(after_seq, through_seq)` 区间只能缩小范围,不是稳定键,因为刷新时机会改变批次边界。
171
+
144
172
  - **后端可用性**——本插件禁用或卸载期间提交的反馈会记录在本地,但恢复插件不会自动重放。捕获要求订阅方保持挂载直到观察到提交;在冷写入尚未完成时卸载,可能错过其 flush 后通知。
145
173
 
146
174
  <a id="dev-note"></a>
package/lib/index.js CHANGED
@@ -5,16 +5,174 @@ import { SessionTelemetryBackend, SessionTelemetryCoordinator } from "@deepseek-
5
5
  import { APP_IDENTITY } from "@deepseek-ai/dsh-llm";
6
6
  import { getOrCreateAnonymousUserId } from "@deepseek-ai/dsh-anonymous-user-id";
7
7
  import { SeverityNumber } from "@opentelemetry/api-logs";
8
+ import { Buffer } from "node:buffer";
9
+ import { randomUUID } from "node:crypto";
10
+ //#region lib/types/record-format.js
11
+ /**
12
+ * OTLP record granularity for Session-log delivery, kept outside the plugin
13
+ * entry because a plugin entry exports only its plugin surface.
14
+ *
15
+ * @module @deepseek-ai/dsh-session-telemetry-otel/record-format
16
+ */
17
+ /** Default granularity: one OTLP record per canonical Session event. */
18
+ const DEFAULT_RECORD_FORMAT = "per-event";
19
+ /** Every batch this backend assembles is authorized conversation context. */
20
+ const BATCH_PURPOSE = "conversation";
21
+ /** UTF-8 bytes of the empty body wrapper `{"events":[]}`. */
22
+ const EMPTY_BODY_BYTES = Buffer.byteLength("{\"events\":[]}");
23
+ /**
24
+ * Assembles captured Session events into contiguous delivery batches.
25
+ *
26
+ * Flush triggers, first one wins: the event-count ceiling, the body byte
27
+ * ceiling, the oldest buffered event's age, and an explicit per-Session flush
28
+ * for idle or closed Sessions. A Session's highest appended sequence is its
29
+ * watermark, so one sequence never enters two batches while its state is
30
+ * retained; a flush keeps the watermark, and closing the Session drops it.
31
+ */
32
+ var SessionLogBatcher = class {
33
+ options;
34
+ report;
35
+ warn;
36
+ sessions = /* @__PURE__ */ new Map();
37
+ stopped = false;
38
+ /**
39
+ * @param options - resolved batch limits.
40
+ * @param report - channel handoff for each formed batch; runs synchronously.
41
+ * @param warn - diagnostic sink for unusable records and report failures.
42
+ */
43
+ constructor(options, report, warn) {
44
+ this.options = options;
45
+ this.report = report;
46
+ this.warn = warn;
47
+ }
48
+ /**
49
+ * Buffer one captured event, flushing whatever batch reached a ceiling.
50
+ * @param item - captured ledger event and its Session identity.
51
+ */
52
+ push(item) {
53
+ if (this.stopped) return;
54
+ let state = this.sessions.get(item.sessionId);
55
+ if (state !== void 0 && state.formatVersion !== item.formatVersion) {
56
+ this.flushState(item.sessionId, state);
57
+ this.sessions.delete(item.sessionId);
58
+ state = void 0;
59
+ }
60
+ const seq = Number(item.event.seq);
61
+ if (state !== void 0 && seq <= state.lastSeq) {
62
+ if (!state.duplicateWarned) {
63
+ state.duplicateWarned = true;
64
+ this.warn(`session telemetry ignored batch event ${String(seq)} for session "${String(item.sessionId)}"; it is already covered`);
65
+ }
66
+ return;
67
+ }
68
+ if (state === void 0) {
69
+ state = {
70
+ formatVersion: item.formatVersion,
71
+ cwd: item.cwd,
72
+ parentSessionId: item.parentSessionId,
73
+ seedLength: item.seedLength,
74
+ afterSeq: -1,
75
+ lastSeq: -1,
76
+ events: [],
77
+ bodyBytes: EMPTY_BODY_BYTES,
78
+ severityNumber: SeverityNumber.INFO,
79
+ timer: void 0,
80
+ duplicateWarned: false
81
+ };
82
+ this.sessions.set(item.sessionId, state);
83
+ } else if (state.events.length > 0 && seq !== state.lastSeq + 1) this.flushState(item.sessionId, state);
84
+ const eventBytes = Buffer.byteLength(JSON.stringify(item.event), "utf8");
85
+ if (state.events.length > 0 && state.bodyBytes + 1 + eventBytes > this.options.maxBatchBytes) this.flushState(item.sessionId, state);
86
+ this.append(item.sessionId, state, item, seq, eventBytes);
87
+ if (state.events.length >= this.options.maxBatchEvents || state.bodyBytes >= this.options.maxBatchBytes) this.flushState(item.sessionId, state);
88
+ }
89
+ /** Buffer one event and arm the batch-age timer on a new batch's first event. */
90
+ append(sessionId, state, item, seq, eventBytes) {
91
+ if (state.events.length === 0) {
92
+ state.afterSeq = seq - 1;
93
+ state.timer = setTimeout(() => {
94
+ state.timer = void 0;
95
+ this.flushState(sessionId, state);
96
+ }, this.options.batchDelayMillis);
97
+ state.timer.unref();
98
+ }
99
+ state.bodyBytes += (state.events.length === 0 ? 0 : 1) + eventBytes;
100
+ state.events.push(item.event);
101
+ state.lastSeq = seq;
102
+ if (item.severityNumber > state.severityNumber) state.severityNumber = item.severityNumber;
103
+ }
104
+ /**
105
+ * Flush one Session's buffered batch without forgetting its watermark.
106
+ * @param sessionId - the Session whose idle or checkpoint boundary arrived.
107
+ */
108
+ flushSession(sessionId) {
109
+ const state = this.sessions.get(sessionId);
110
+ if (state !== void 0) this.flushState(sessionId, state);
111
+ }
112
+ /**
113
+ * Flush one Session's buffered batch and drop its watermark, e.g. after disposal.
114
+ * @param sessionId - the closed Session.
115
+ */
116
+ closeSession(sessionId) {
117
+ const state = this.sessions.get(sessionId);
118
+ if (state === void 0) return;
119
+ this.flushState(sessionId, state);
120
+ this.sessions.delete(sessionId);
121
+ }
122
+ /** Flush every buffered batch, release timers, and reject later events. */
123
+ shutdown() {
124
+ this.stopped = true;
125
+ for (const [sessionId, state] of this.sessions) this.flushState(sessionId, state);
126
+ this.sessions.clear();
127
+ }
128
+ /** Form one batch from the buffered prefix, then reset the buffer. */
129
+ flushState(sessionId, state) {
130
+ if (state.timer !== void 0) {
131
+ clearTimeout(state.timer);
132
+ state.timer = void 0;
133
+ }
134
+ if (state.events.length === 0) return;
135
+ const batch = {
136
+ sessionId,
137
+ formatVersion: state.formatVersion,
138
+ ...state.cwd === void 0 ? {} : { cwd: state.cwd },
139
+ ...state.parentSessionId === void 0 ? {} : { parentSessionId: state.parentSessionId },
140
+ ...state.seedLength === void 0 ? {} : { seedLength: state.seedLength },
141
+ afterSeq: state.afterSeq,
142
+ throughSeq: state.lastSeq,
143
+ batchId: randomUUID(),
144
+ purpose: BATCH_PURPOSE,
145
+ events: state.events,
146
+ severityNumber: state.severityNumber
147
+ };
148
+ state.events = [];
149
+ state.bodyBytes = EMPTY_BODY_BYTES;
150
+ state.severityNumber = SeverityNumber.INFO;
151
+ try {
152
+ this.report(batch);
153
+ } catch (error) {
154
+ this.warn(`session telemetry batch report failed: ${String(error)}`);
155
+ }
156
+ }
157
+ };
158
+ //#endregion
8
159
  //#region lib/types/index.js
9
160
  /**
10
161
  * OpenTelemetry Service Provider for the DeepSeek Harness telemetry capability.
11
162
  *
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.
163
+ * Authorizes feedback-bounded capture and hands records to the Session-log
164
+ * reporter, either one OTLP record per event or one per contiguous delivery
165
+ * batch. This plugin owns resource identity, optional batch assembly, and an
166
+ * outer shutdown deadline; the reporter owns byte-bounded SDK delivery.
15
167
  *
16
168
  * @module @deepseek-ai/dsh-session-telemetry-otel
17
169
  */
170
+ /** Request ceiling the OTel channel enforces, mirrored here for load-time validation. */
171
+ const MAX_REQUEST_BYTES = 4e6;
172
+ /** Two-way JSON escaping can double a batch body on the wire. */
173
+ const BATCH_BODY_ESCAPE_FACTOR = 2;
174
+ /** Fixed OTLP resource/scope envelope allowance when a batch body is escaped. */
175
+ const BATCH_ENVELOPE_MARGIN_BYTES = 4096;
18
176
  /** Session-sharing policy selected by {@link Config.mode}. */
19
177
  var SessionTelemetryMode;
20
178
  (function(SessionTelemetryMode) {
@@ -35,18 +193,78 @@ function isFeedback(session, event) {
35
193
  default: return false;
36
194
  }
37
195
  }
196
+ /**
197
+ * Session format generation carried by a ledger record's identity attributes.
198
+ * Absence identifies generation 0, matching the accepted-upload watermark rule.
199
+ * @param attributes - the captured record's identity attributes.
200
+ * @returns the generation the event sequence belongs to.
201
+ */
202
+ function formatVersionOf(attributes) {
203
+ const version = attributes["session.format_version"];
204
+ return typeof version === "number" ? version : 0;
205
+ }
206
+ /**
207
+ * Session-level facts a batch reports once instead of per event. They are the
208
+ * same identity attributes the per-event path carries, and the coordinator
209
+ * derives them from the Session header.
210
+ * @param attributes - the captured record's identity attributes.
211
+ * @returns the present Session facts, omitted when the header has none.
212
+ */
213
+ function sessionDimensionsOf(attributes) {
214
+ const cwd = attributes["session.cwd"];
215
+ const parentSessionId = attributes["session.parent_id"];
216
+ const seedLength = attributes["session.seed_length"];
217
+ return {
218
+ ...typeof cwd === "string" ? { cwd } : {},
219
+ ...typeof parentSessionId === "string" ? { parentSessionId } : {},
220
+ ...typeof seedLength === "number" ? { seedLength } : {}
221
+ };
222
+ }
38
223
  /** Resolve the default and reject unknown runtime values before transport setup. */
39
224
  function resolveMode(mode) {
40
225
  const resolved = mode ?? DEFAULT_TELEMETRY_MODE;
41
226
  switch (resolved) {
42
227
  case SessionTelemetryMode.FEEDBACK_ONLY:
43
228
  case SessionTelemetryMode.DISABLED: return resolved;
44
- default: return assertNever(resolved);
229
+ default: return assertNever(resolved, "mode");
230
+ }
231
+ }
232
+ /** Resolve the default record granularity and reject unknown runtime values before transport setup. */
233
+ function resolveRecordFormat(format) {
234
+ const resolved = format ?? "per-event";
235
+ switch (resolved) {
236
+ case "per-event":
237
+ case "per-batch": return resolved;
238
+ default: return assertNever(resolved, "record format");
45
239
  }
46
240
  }
47
241
  /** 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)}`);
242
+ function assertNever(value, what) {
243
+ throw new Error(`session-telemetry-otel: unsupported ${what} ${JSON.stringify(value)}`);
244
+ }
245
+ /**
246
+ * Validate the batch ceilings against each other and against the request ceiling.
247
+ *
248
+ * A batch body travels as one JSON string value, so escaping can double its
249
+ * bytes; a batch that fits maxBatchBytes but not maxRequestBytes after escaping
250
+ * would be rejected whole, losing every event it carries. Rejecting that
251
+ * combination at load time keeps a legal configuration from discarding events
252
+ * at run time.
253
+ */
254
+ function resolveBatchOptions(config) {
255
+ const maxBatchEvents = config.maxBatchEvents ?? 128;
256
+ const maxBatchBytes = config.maxBatchBytes ?? 1048576;
257
+ const batchDelayMillis = config.batchDelayMillis ?? 1e3;
258
+ if (!Number.isSafeInteger(maxBatchEvents) || maxBatchEvents < 1) throw new Error(`session-telemetry-otel: maxBatchEvents must be a positive integer, got ${String(maxBatchEvents)}`);
259
+ if (!Number.isSafeInteger(maxBatchBytes) || maxBatchBytes < 1) throw new Error(`session-telemetry-otel: maxBatchBytes must be a positive integer, got ${String(maxBatchBytes)}`);
260
+ if (!Number.isSafeInteger(batchDelayMillis) || batchDelayMillis < 1 || batchDelayMillis > MAX_TIMER_DELAY_MILLIS) throw new Error(`session-telemetry-otel: batchDelayMillis must be a positive integer no greater than ${MAX_TIMER_DELAY_MILLIS}, got ${String(batchDelayMillis)}`);
261
+ const maxRequestBytes = config.maxRequestBytes ?? MAX_REQUEST_BYTES;
262
+ if (maxBatchBytes * BATCH_BODY_ESCAPE_FACTOR + BATCH_ENVELOPE_MARGIN_BYTES > maxRequestBytes) throw new Error("session-telemetry-otel: maxBatchBytes " + String(maxBatchBytes) + " cannot fit maxRequestBytes " + String(maxRequestBytes) + " after JSON escaping (x" + String(BATCH_BODY_ESCAPE_FACTOR) + " plus " + String(BATCH_ENVELOPE_MARGIN_BYTES) + " B envelope); lower maxBatchBytes");
263
+ return {
264
+ maxBatchEvents,
265
+ maxBatchBytes,
266
+ batchDelayMillis
267
+ };
50
268
  }
51
269
  /** Map the serialized mode onto the seam's backend-independent sharing vocabulary. */
52
270
  function sharingStatusFor(mode) {
@@ -54,22 +272,26 @@ function sharingStatusFor(mode) {
54
272
  case SessionTelemetryMode.FEEDBACK_ONLY: return "feedback-only";
55
273
  case SessionTelemetryMode.DISABLED: return "disabled";
56
274
  /* v8 ignore next 2 -- resolveMode already rejected unknown values before this switch; the closed enum cannot reach the default. */
57
- default: return assertNever(mode);
275
+ default: return assertNever(mode, "mode");
58
276
  }
59
277
  }
60
278
  /**
61
279
  * 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.
280
+ * starts. The constructor validates endpoint, shutdown, and batch-ceiling
281
+ * requirements; the reporter validates Session byte and queue limits. SDK
282
+ * transport and processor settings use the reporter's accepted option types,
283
+ * which exclude self-observability metering.
66
284
  */
67
285
  const Config = z.object({
68
286
  mode: z.union(Object.values(SessionTelemetryMode)).default(DEFAULT_TELEMETRY_MODE),
69
287
  exporter: z.any(),
70
288
  processor: z.any(),
71
289
  shutdownTimeoutMillis: z.number(),
72
- maxRequestBytes: z.number().step(1).min(1).max(4e6)
290
+ maxRequestBytes: z.number().step(1).min(1).max(4e6),
291
+ recordFormat: z.union(["per-event", "per-batch"]).default(DEFAULT_RECORD_FORMAT),
292
+ maxBatchEvents: z.number().step(1).min(1),
293
+ maxBatchBytes: z.number().step(1).min(1),
294
+ batchDelayMillis: z.number().step(1).min(1).max(2147483647)
73
295
  });
74
296
  /** Default outer allowance for the SDK's complete shutdown sequence. */
75
297
  const DEFAULT_SHUTDOWN_TIMEOUT_MILLIS = 3e3;
@@ -85,19 +307,24 @@ const SEVERITY = {
85
307
  * the `sessionTelemetry` service (duplicate load throws). `FEEDBACK_ONLY` wires the SDK
86
308
  * pipeline and on-demand {@link SessionTelemetryCoordinator}; `DISABLED` constructs no
87
309
  * SDK state and listens only to warn when recorded feedback stays local.
310
+ * `recordFormat: 'per-batch'` assembles contiguous delivery batches before
311
+ * the same byte-bounded channel.
88
312
  */
89
313
  var OpenTelemetrySessionBackend = class extends SessionTelemetryBackend {
90
314
  static inject = ["sessions", "otel"];
91
315
  static Config = Config;
92
316
  provider;
317
+ batcher;
93
318
  shutdownTimeoutMillis;
94
319
  sharing;
95
320
  constructor(ctx, config) {
96
321
  const mode = resolveMode(config.mode);
322
+ const recordFormat = resolveRecordFormat(config.recordFormat);
97
323
  super(ctx);
98
324
  this.sharing = sharingStatusFor(mode);
99
325
  if (mode === SessionTelemetryMode.DISABLED) {
100
326
  this.provider = void 0;
327
+ this.batcher = void 0;
101
328
  this.shutdownTimeoutMillis = DEFAULT_SHUTDOWN_TIMEOUT_MILLIS;
102
329
  ctx.on("session/event", (session, event) => {
103
330
  if (isFeedback(session, event)) ctx.logger.warn(DISABLED_FEEDBACK_WARNING);
@@ -118,6 +345,7 @@ var OpenTelemetrySessionBackend = class extends SessionTelemetryBackend {
118
345
  const shutdownTimeoutMillis = config.shutdownTimeoutMillis ?? 3e3;
119
346
  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
347
  this.shutdownTimeoutMillis = shutdownTimeoutMillis;
348
+ const batchOptions = recordFormat === "per-batch" ? resolveBatchOptions(config) : void 0;
121
349
  const { version } = createRequire(import.meta.url)("../package.json");
122
350
  const reporter = ctx.otel.createSessionLogReporter({
123
351
  scope: {
@@ -140,17 +368,34 @@ var OpenTelemetrySessionBackend = class extends SessionTelemetryBackend {
140
368
  }
141
369
  });
142
370
  this.provider = reporter;
371
+ const batcher = batchOptions === void 0 ? void 0 : new SessionLogBatcher(batchOptions, (batch) => {
372
+ reporter.reportSessionLogBatch(batch);
373
+ }, (message) => {
374
+ ctx.logger.warn(message);
375
+ });
376
+ this.batcher = batcher;
143
377
  const enqueue = (record) => {
144
378
  if (record.sourceEvent === void 0) {
145
379
  ctx.logger.warn("Session log record withheld: redaction removed sourceEvent");
146
380
  return;
147
381
  }
382
+ const event = {
383
+ ...record.sourceEvent.envelope,
384
+ data: record.body
385
+ };
386
+ if (batcher !== void 0) {
387
+ batcher.push({
388
+ sessionId: record.sourceEvent.sessionId,
389
+ formatVersion: formatVersionOf(record.attributes),
390
+ ...sessionDimensionsOf(record.attributes),
391
+ event,
392
+ severityNumber: SEVERITY[record.severity]
393
+ });
394
+ return;
395
+ }
148
396
  reporter.reportSessionLog({
149
397
  sessionId: record.sourceEvent.sessionId,
150
- event: {
151
- ...record.sourceEvent.envelope,
152
- data: record.body
153
- },
398
+ event,
154
399
  severityNumber: SEVERITY[record.severity],
155
400
  attributes: record.attributes
156
401
  });
@@ -177,6 +422,14 @@ var OpenTelemetrySessionBackend = class extends SessionTelemetryBackend {
177
422
  const session = Session.fromRestore(snapshot.meta.id, snapshot.events, snapshot.meta, snapshot.inheritedEventCount, "detached", ctx.sessions.messageProjections);
178
423
  if (isFeedback(session, committed)) coordinator.captureSession(session, committed.seq);
179
424
  });
425
+ if (batcher !== void 0) {
426
+ ctx.on("session/event", (session, event) => {
427
+ if (event.type === "turn/end") batcher.flushSession(session.id);
428
+ });
429
+ ctx.on("session/disposed", (session) => {
430
+ batcher.closeSession(session.id);
431
+ });
432
+ }
180
433
  }
181
434
  /**
182
435
  * Drop direct records. Only a new canonical feedback submission can authorize
@@ -192,6 +445,7 @@ var OpenTelemetrySessionBackend = class extends SessionTelemetryBackend {
192
445
  */
193
446
  async shutdown() {
194
447
  if (this.provider === void 0) return;
448
+ this.batcher?.shutdown();
195
449
  const providerShutdown = this.provider.shutdown();
196
450
  let timer;
197
451
  const deadline = new Promise((_resolve, reject) => {