@spellkave/agent-observability 0.0.0-stage → 0.1.0

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/src/otel.ts ADDED
@@ -0,0 +1,594 @@
1
+ // OTel PROJECTION sink (ADR-0074): OTel is a projection, never the source of
2
+ // truth — the canonical store stays file-based JSONL run artifacts.
3
+ //
4
+ // BINDING disambiguation (ADR-0074, "Naming disambiguation"): this package
5
+ // observes WORLD ACTORS. ADR-0030 coding-agent telemetry owns separate trace
6
+ // and metric streams. This sink MUST use the distinct resource/service names
7
+ // below and MUST NOT write into any ADR-0030 stream.
8
+
9
+ import type { AgentRunSink } from "./emit.ts";
10
+ import type { AgentRunEvent } from "./events.ts";
11
+
12
+ /** OTel resource `service.name` for world-actor run events. Distinct from
13
+ * every ADR-0030 coding-agent service name by construction. */
14
+ export const OTEL_SERVICE_NAME = "spellkave-world-actors";
15
+
16
+ /** Target stream name for the OTel logs projection. Never a coding-agent
17
+ * stream. */
18
+ export const OTEL_STREAM_NAME = "world_actor_run_events";
19
+
20
+ export interface OtelSinkOptions {
21
+ /** Transport injected by the host (e.g. an OTLP HTTP poster). S2 ships the
22
+ * sink as a stub around this callback; S5 fills the wiring. */
23
+ export: (resource: { serviceName: string; stream: string }, event: AgentRunEvent) => void;
24
+ }
25
+
26
+ /**
27
+ * Injected-transport projection: each event goes through the host's transport
28
+ * with the world-actor resource names. Kept dependency-free — no OTel SDK
29
+ * import in this package; the host supplies transport.
30
+ */
31
+ export function createOtelProjectionSink(options: OtelSinkOptions): AgentRunSink {
32
+ return {
33
+ write(event) {
34
+ options.export({ serviceName: OTEL_SERVICE_NAME, stream: OTEL_STREAM_NAME }, event);
35
+ },
36
+ };
37
+ }
38
+
39
+ // ── S5 fill: a batteries-included OTLP/HTTP logs exporter ────────────────────
40
+
41
+ export interface OtlpHttpSinkOptions {
42
+ /** OTLP logs endpoint, e.g. `http://host:5080/api/default/v1/logs`. */
43
+ endpoint: string;
44
+ /** Extra request headers (auth, `stream-name`, ...). The stream-name header
45
+ * is always forced to OTEL_STREAM_NAME — never an ADR-0030 stream. */
46
+ headers?: Record<string, string>;
47
+ /** Injectable fetch for tests / non-global environments. */
48
+ fetchFn?: typeof fetch;
49
+ /** Delivery failure hook (default: silent — observability never breaks the run). */
50
+ onError?: (error: unknown) => void;
51
+ /** Maximum concurrent requests; excess projection copies are dropped. Default 64. */
52
+ maxPendingExports?: number;
53
+ /** Records per POST. Default 100. `1` restores one-request-per-event. */
54
+ maxBatchRecords?: number;
55
+ /** Upper bound on how long a record may wait for a partial batch, in
56
+ * milliseconds. Default 2000. Under load the size trigger fires first, so
57
+ * this is the latency ceiling on a quiet world, not the normal path. */
58
+ flushIntervalMs?: number;
59
+ /** Hard cap on buffered records; beyond it, writes are dropped. Default
60
+ * 10000. `0` disables buffering entirely (every write sends or drops).
61
+ * Without this cap an unreachable collector would trade "lose telemetry"
62
+ * for "the host fills up", which is the worse failure. */
63
+ maxBufferedRecords?: number;
64
+ /** Abort each request after this deadline; default 10 seconds. */
65
+ requestTimeoutMs?: number;
66
+ /** Deployed revision for the `service.version` resource attribute. */
67
+ serviceVersion?: string;
68
+ /** Additional resource attributes, filtered through
69
+ * `OTLP_LOG_SAFE_RESOURCE_ATTRIBUTE_KEYS` (sk-jay0.6.38.13). Callers
70
+ * assemble this from env — this module stays dependency-free and never
71
+ * reads env itself. */
72
+ resourceAttributes?: Record<string, string>;
73
+ }
74
+
75
+ /**
76
+ * Event-data fields admitted to the shared OTLP projection. Canonical JSONL
77
+ * intentionally remains richer; this list is the projection's disclosure
78
+ * boundary and must stay scalar-only.
79
+ *
80
+ * ADR-0114 D-4a: `utterance` and `intent` are NOT on this list. Player-authored
81
+ * text on a creation readback (`intent.utterance`) must not inherit into OTLP
82
+ * because a retired stdout projection used to exclude it by construction.
83
+ * Proof: `otel-sink.test.ts` "drops intent.utterance on brain_decision".
84
+ */
85
+ export const OTEL_SAFE_EVENT_DATA_FIELDS = [
86
+ "tool_name",
87
+ "is_error",
88
+ "duration_ms",
89
+ "tool_calls_used",
90
+ "max_tool_calls",
91
+ "dry_streak",
92
+ "max_dry_streak",
93
+ "tokens_used",
94
+ "token_budget",
95
+ "turn",
96
+ "input_tokens",
97
+ "output_tokens",
98
+ "tool_calls",
99
+ "max_events",
100
+ "events_written",
101
+ "terminal",
102
+ "turns",
103
+ "correlation_id",
104
+ "world_slug",
105
+ /** SHA-256 hex prefix of an OAuth subject — never the raw `sub`. */
106
+ "subject_prefix",
107
+ "cause_kind",
108
+ "cause_id",
109
+ "action_id",
110
+ "target_ref",
111
+ "provenance_id",
112
+ "provenance_status",
113
+ "provenance_kind",
114
+ "failure_class",
115
+ "result_status",
116
+ "poll_count",
117
+ "lag_warning",
118
+ "invoke_settled",
119
+ "invoke_failed",
120
+ "error_category",
121
+ "step",
122
+ "error_code",
123
+ // sk-0m4.120.36: constructor name of the throw behind `internal_error`
124
+ // (`RangeError`, `ZodError`, …) — an identifier, never a message.
125
+ "error_class",
126
+ // sk-0m4.120.42: factual PLAYER-context counts — integers and one boolean;
127
+ // never direct-attempt parameters, rows, or text.
128
+ "total_rows",
129
+ "matched",
130
+ "shown",
131
+ "truncated",
132
+ "retry_count",
133
+ // sk-jay0.7.389.3 contract_shape_mismatch — schema names and types only
134
+ // (the module's own table/column/reducer identifiers), never row data.
135
+ "shape_item",
136
+ "shape_detail",
137
+ "shape_mode",
138
+ "shape_database",
139
+ "client_epoch",
140
+ // sk-rax8.7 player_feedback — join keys only; never message/bundle body.
141
+ "category",
142
+ "reference",
143
+ "bundle_sha256",
144
+ "message_chars",
145
+ // sk-0m4.120.10 act receipts — the receipt's closed vocabulary
146
+ // (accepted/rejected/unobserved/travelling) and the reply-window flag; never
147
+ // the utterance, observation, or conversation text.
148
+ "outcome",
149
+ "awaiting_response",
150
+ // sk-0m4.120.11 gateway HTTP edge — route is the matched PATTERN, never a URL.
151
+ "http_status",
152
+ "http_method",
153
+ "route",
154
+ "cf_ray",
155
+ // sk-0m4.120.12 lifecycle — closed-vocabulary scalars only.
156
+ "image_tag",
157
+ "spawned",
158
+ "cause",
159
+ "reason",
160
+ // sk-jay0.6.38.2 world_lifecycle — five new disclosure fields; `world_slug`,
161
+ // `duration_ms`, `image_tag`, `failure_class`, `error_class`, `error_code`
162
+ // above are reused. `job_id`/`artifact_digest` are join keys and a pinned
163
+ // digest, never secret; `phase`/`job_kind`/`boot_ms` are closed-vocabulary
164
+ // or numeric.
165
+ "phase",
166
+ "job_id",
167
+ "job_kind",
168
+ "boot_ms",
169
+ "artifact_digest",
170
+ // ADR-0114 D-2: the decision branch a brain took, as a stable identifier
171
+ // (`wait/no-level-earned-yet`), never prose and never a payload.
172
+ "rule",
173
+ // ADR-0114 D-2 option A (sk-jay0.6.31.15 / .17): seventeen literal
174
+ // decision-input key names, hoisted to the payload top by
175
+ // `emitBrainDecision`. The nested `inputs` map itself is NOT admitted — it
176
+ // is not a scalar. Unlisted input names are dropped here, not renamed and
177
+ // not blobbed.
178
+ //
179
+ // Tripwire: revisit option A if the DISTINCT decision-input name count
180
+ // exceeds 25 (see `OTEL_DECISION_INPUT_FIELDS`). Decision-input census
181
+ // today: 17. World-table projection adds 3 more SAFE keys below (not
182
+ // decision inputs), the Rust npc-host 3 more after those; combined
183
+ // distinct names at this list tail: 23.
184
+ // `step` is already admitted above as cycle-step vocabulary; it is also one
185
+ // of the seventeen names.
186
+ "quest",
187
+ "intendedRule",
188
+ "viewKind",
189
+ "role",
190
+ "desired",
191
+ "myTurn",
192
+ "goal",
193
+ "speaker",
194
+ "retryCount",
195
+ "errorCode",
196
+ // sk-jay0.6.31.17: Aldwin wait-branch keys already emitted on every wait.
197
+ "levelBand",
198
+ "offerPresent",
199
+ "applyPresent",
200
+ "advancementLive",
201
+ "heardQuestion",
202
+ "speakable",
203
+ // sk-jay0.6.31.7: WorldEvent TABLE header projection (not the player-facing
204
+ // `world_event` delivery type). Scalar join keys only; never summary or
205
+ // detail-table content. Not decision-input names — they do not belong on
206
+ // `OTEL_DECISION_INPUT_FIELDS`. Combined distinct names at this list tail:
207
+ // 17 decision-input + 3 world-table + 3 Rust npc-host = 23. Tripwire 25
208
+ // stays on the decision-input census.
209
+ "event_id",
210
+ "tick",
211
+ "event_kind",
212
+ // sk-jay0.1.55.60.35: Rust npc-host `brain_decision` rows. `intent_kind` is
213
+ // the closed intent vocabulary (wait/communicate/manipulate/move/end_turn/
214
+ // react), `record_type` the closed DM record vocabulary (ceremony/layer/
215
+ // setup/boot/class_diagnostic), `repeat_count` the number of identical
216
+ // consecutive waits folded into one row (Slayer sk-w8zx.129). Not
217
+ // decision-input names; the decision-input census stays 17.
218
+ "intent_kind",
219
+ "record_type",
220
+ "repeat_count",
221
+ ] as const;
222
+
223
+ /** The seventeen decision-input key names admitted under option A.
224
+ * Tripwire: if this list grows past 25 distinct names, revisit the choice.
225
+ * Count today: 17. `step` lives in `OTEL_SAFE_EVENT_DATA_FIELDS` already
226
+ * (cycle-step) and is included here so the census stays one list.
227
+ * `closedForLevel` and `offeredForLevel` stay JSONL-only: they live under
228
+ * `reasoning.state`, not in the emitted `inputs` map. */
229
+ export const OTEL_DECISION_INPUT_FIELDS = [
230
+ "quest",
231
+ "intendedRule",
232
+ "viewKind",
233
+ "role",
234
+ "desired",
235
+ "myTurn",
236
+ "goal",
237
+ "speaker",
238
+ "step",
239
+ "retryCount",
240
+ "errorCode",
241
+ "levelBand",
242
+ "offerPresent",
243
+ "applyPresent",
244
+ "advancementLive",
245
+ "heardQuestion",
246
+ "speakable",
247
+ ] as const;
248
+
249
+ export type OtelSafeEventDataField = (typeof OTEL_SAFE_EVENT_DATA_FIELDS)[number];
250
+ export type OtelSafeScalar = string | number | boolean;
251
+
252
+ const MAX_PROJECTED_STRING_LENGTH = 256;
253
+
254
+ /** `hashTranscriptSubject` shape: first 16 hex chars of SHA-256. Anything else
255
+ * (including a raw OAuth `sub`) is refused at the OTLP disclosure boundary. */
256
+ const SUBJECT_PREFIX_PATTERN = /^[a-f0-9]{16}$/;
257
+
258
+ function safeScalar(value: unknown): OtelSafeScalar | undefined {
259
+ if (typeof value === "string") return value.slice(0, MAX_PROJECTED_STRING_LENGTH);
260
+ if (typeof value === "boolean") return value;
261
+ if (typeof value === "number" && Number.isFinite(value)) return value;
262
+ return undefined;
263
+ }
264
+
265
+ function safeSubjectPrefix(value: unknown): string | undefined {
266
+ if (typeof value !== "string") return undefined;
267
+ const trimmed = value.trim().toLowerCase();
268
+ return SUBJECT_PREFIX_PATTERN.test(trimmed) ? trimmed : undefined;
269
+ }
270
+
271
+ /** Central, allowlisted projection of event data. Unknown, nested, and
272
+ * content-bearing fields are dropped even when a caller emits them.
273
+ * `subject_prefix` is admitted only as a 16-char hex hash — never a raw sub. */
274
+ export function projectSafeEventData(
275
+ data: Readonly<Record<string, unknown>>,
276
+ ): Partial<Record<OtelSafeEventDataField, OtelSafeScalar>> {
277
+ const projected: Partial<Record<OtelSafeEventDataField, OtelSafeScalar>> = {};
278
+ for (const key of OTEL_SAFE_EVENT_DATA_FIELDS) {
279
+ const value = key === "subject_prefix" ? safeSubjectPrefix(data[key]) : safeScalar(data[key]);
280
+ if (value !== undefined) projected[key] = value;
281
+ }
282
+ return projected;
283
+ }
284
+
285
+ function otlpAttribute(key: string, value: OtelSafeScalar): Record<string, unknown> {
286
+ if (typeof value === "boolean") return { key, value: { boolValue: value } };
287
+ if (typeof value === "number") {
288
+ return Number.isInteger(value)
289
+ ? { key, value: { intValue: String(value) } }
290
+ : { key, value: { doubleValue: value } };
291
+ }
292
+ return { key, value: { stringValue: value } };
293
+ }
294
+
295
+ /** Map one v1 event to an OTLP LogRecord using only the safe projection. */
296
+ export function toOtlpLogRecord(event: AgentRunEvent): Record<string, unknown> {
297
+ const envelope = {
298
+ run_id: event.run_id,
299
+ run_kind: event.run_kind,
300
+ actor_id: event.actor_id,
301
+ role: event.role,
302
+ controller_kind: event.controller_kind,
303
+ driver: event.driver,
304
+ ...(event.model === undefined ? {} : { model: event.model }),
305
+ seed: event.seed,
306
+ event_type: event.type,
307
+ // The game clock may deliberately be historical for a reproducible
308
+ // adventure. OTLP backends commonly reject such timestamps at ingest, so
309
+ // retain the event time as data while indexing the projection at its real
310
+ // delivery time.
311
+ event_ts: event.ts,
312
+ };
313
+ const data = projectSafeEventData(event.data);
314
+ const attributes = [
315
+ ...Object.entries(envelope).map(([key, value]) =>
316
+ otlpAttribute(key, String(value).slice(0, MAX_PROJECTED_STRING_LENGTH)),
317
+ ),
318
+ ...Object.entries(data).map(([key, value]) => otlpAttribute(`spellkave.${key}`, value)),
319
+ ];
320
+ return {
321
+ timeUnixNano: `${Date.now()}000000`,
322
+ severityText: "INFO",
323
+ body: { stringValue: JSON.stringify({ type: event.type, data }) },
324
+ attributes,
325
+ };
326
+ }
327
+
328
+ /**
329
+ * Extra resource attributes a host may stamp onto the logs projection,
330
+ * restricted to this explicit allowlist — same discipline as
331
+ * `SAFE_RESOURCE_ATTRIBUTE_KEYS` in traces.ts/metrics.ts. Anything outside
332
+ * the list is dropped silently rather than surfacing an unreviewed key on
333
+ * the wire.
334
+ *
335
+ * `deployment.environment` (not `.name`) is the one Spellkave hosts emit
336
+ * (sk-jay0.6.38.13): it is the collector's hygiene key — the shared
337
+ * OpenObserve collector stamps `deployment.environment=otel-sink` only when
338
+ * a record arrives with none — and it is also the LIVE column name
339
+ * (`deployment_environment` on `world_actor_run_events`). The newer
340
+ * `.name` variant is kept alongside for any exporter that already emits it.
341
+ */
342
+ export const OTLP_LOG_SAFE_RESOURCE_ATTRIBUTE_KEYS = new Set([
343
+ "deployment.environment",
344
+ "deployment.environment.name",
345
+ "service.namespace",
346
+ ]);
347
+
348
+ export interface OtlpResourceOptions {
349
+ /** Deployed revision (`SPELLKAVE_IMAGE_TAG`, e.g. `sha-919f9ae5`) projected
350
+ * as the standard OTel `service.version` resource attribute so every
351
+ * exported row names the code that produced it (sk-0m4.120.13). Omitted
352
+ * when unknown — never a placeholder. */
353
+ serviceVersion?: string;
354
+ /** Additional resource attributes, filtered through
355
+ * `OTLP_LOG_SAFE_RESOURCE_ATTRIBUTE_KEYS` (sk-jay0.6.38.13). */
356
+ resourceAttributes?: Record<string, string>;
357
+ }
358
+
359
+ /** Wrap log records in an OTLP/HTTP JSON payload with the WORLD-ACTOR
360
+ * resource — `service.name` distinct from every ADR-0030 coding-agent
361
+ * service by construction. */
362
+ export function toOtlpPayload(
363
+ records: ReadonlyArray<Record<string, unknown>>,
364
+ resource: OtlpResourceOptions = {},
365
+ ): unknown {
366
+ const serviceVersion = resource.serviceVersion?.trim();
367
+ const extraAttributes = Object.entries(resource.resourceAttributes ?? {})
368
+ .filter(([key, value]) => OTLP_LOG_SAFE_RESOURCE_ATTRIBUTE_KEYS.has(key) && value.trim() !== "")
369
+ .map(([key, value]) => ({ key, value: { stringValue: value } }));
370
+ return {
371
+ resourceLogs: [
372
+ {
373
+ resource: {
374
+ attributes: [
375
+ { key: "service.name", value: { stringValue: OTEL_SERVICE_NAME } },
376
+ { key: "spellkave.observes", value: { stringValue: "world_actors" } },
377
+ ...(serviceVersion
378
+ ? [{ key: "service.version", value: { stringValue: serviceVersion } }]
379
+ : []),
380
+ ...extraAttributes,
381
+ ],
382
+ },
383
+ scopeLogs: [
384
+ {
385
+ scope: { name: "@spellkave/agent-observability" },
386
+ logRecords: records,
387
+ },
388
+ ],
389
+ },
390
+ ],
391
+ };
392
+ }
393
+
394
+ /** Sink-lifetime counters; timeout and failure can describe the same request. */
395
+ export interface OtlpTransportSnapshot {
396
+ pending: number;
397
+ dropped: number;
398
+ timedOut: number;
399
+ failed: number;
400
+ }
401
+
402
+ export interface OtlpHttpSink extends AgentRunSink {
403
+ /** Local snapshot for a separate metrics transport; never emits another log. */
404
+ transportSnapshot(): OtlpTransportSnapshot;
405
+ }
406
+
407
+ /** OTLP logs projection: records are batched into one POST, then admitted
408
+ * against a bounded concurrency budget. Saturation loses projection copies,
409
+ * never gameplay state. Requests receive an abort deadline; close flushes the
410
+ * buffer and drains actual settlement, so an injected abort-ignoring transport
411
+ * still requires the caller's bounded shutdown policy.
412
+ *
413
+ * Batching is the point (sk-jay0.6.15.56.21). This sink is ONE PER HOST
414
+ * PROCESS — every seat worker relays its events to the parent, whose single
415
+ * emitter is the one projection sink (`seat-worker-runtime.ts`) — so 71 seats
416
+ * shared the same 64 admission slots. At one request per record that ceiling is
417
+ * reached under a burst of events before any single export settles.
418
+ * At 100 records per POST the same budget absorbs a hundred times the rate.
419
+ *
420
+ * See otel-backpressure.test.ts and otel-batching.test.ts. */
421
+ export function createOtlpHttpSink(options: OtlpHttpSinkOptions): OtlpHttpSink {
422
+ const doFetch = options.fetchFn ?? fetch;
423
+ const pending = new Set<Promise<void>>();
424
+ const configuredMax = options.maxPendingExports ?? 64;
425
+ const maxPending = Number.isFinite(configuredMax) ? Math.max(1, Math.trunc(configuredMax)) : 64;
426
+ const configuredBatch = options.maxBatchRecords ?? 100;
427
+ const maxBatch = Number.isFinite(configuredBatch)
428
+ ? Math.max(1, Math.trunc(configuredBatch))
429
+ : 100;
430
+ const configuredInterval = options.flushIntervalMs ?? 2_000;
431
+ const flushIntervalMs = Number.isFinite(configuredInterval)
432
+ ? Math.max(1, Math.trunc(configuredInterval))
433
+ : 2_000;
434
+ const configuredBuffer = options.maxBufferedRecords ?? 10_000;
435
+ const maxBuffered = Number.isFinite(configuredBuffer)
436
+ ? Math.max(0, Math.trunc(configuredBuffer))
437
+ : 10_000;
438
+ const buffer: Array<Record<string, unknown>> = [];
439
+ let flushTimer: ReturnType<typeof setTimeout> | undefined;
440
+ let saturated = false;
441
+ let dropped = 0;
442
+ let timedOut = 0;
443
+ let failed = 0;
444
+ const configuredTimeout = options.requestTimeoutMs ?? 10_000;
445
+ const timeoutMs = Number.isFinite(configuredTimeout)
446
+ ? Math.max(1, Math.trunc(configuredTimeout))
447
+ : 10_000;
448
+ const reportError = (error: unknown) => {
449
+ try {
450
+ options.onError?.(error);
451
+ } catch {
452
+ // Error reporting must not break the actor or export cleanup.
453
+ }
454
+ };
455
+ return {
456
+ transportSnapshot: () => ({ pending: pending.size, dropped, timedOut, failed }),
457
+ write(event) {
458
+ const record = toOtlpLogRecord(event);
459
+ // Batch only under pressure. With a free slot and nothing already
460
+ // queued there is nothing to gain by waiting: the record goes now, at
461
+ // the latency it has always had. Batches form exactly when admission
462
+ // is full, which is the state that was dropping records.
463
+ if (buffer.length === 0 && sendReady()) {
464
+ send([record]);
465
+ return;
466
+ }
467
+ // The buffer is the last line of defence, not the normal path, and
468
+ // dropping at its ceiling is deliberate. Losing projection copies is
469
+ // the documented trade; growing without bound until the host dies is
470
+ // not.
471
+ if (buffer.length >= maxBuffered) {
472
+ dropped++;
473
+ if (!saturated) {
474
+ saturated = true;
475
+ reportError(new Error("OTLP logs export queue is saturated"));
476
+ }
477
+ return;
478
+ }
479
+ buffer.push(record);
480
+ if (buffer.length >= maxBatch) {
481
+ drainBuffer();
482
+ return;
483
+ }
484
+ // Size trigger missed, so arm the latency ceiling. A quiet world must
485
+ // not hold its last records forever — those are the ones worth having.
486
+ if (flushTimer === undefined) {
487
+ flushTimer = setTimeout(() => {
488
+ flushTimer = undefined;
489
+ drainBuffer();
490
+ }, flushIntervalMs);
491
+ flushTimer.unref?.();
492
+ }
493
+ },
494
+ async close() {
495
+ if (flushTimer !== undefined) {
496
+ clearTimeout(flushTimer);
497
+ flushTimer = undefined;
498
+ }
499
+ // Flush what is buffered, waiting for admission between rounds: a
500
+ // shutdown that abandoned the buffer would discard exactly the records
501
+ // a crash makes interesting. Each round frees at least one slot, so
502
+ // this terminates unless the transport itself never settles — which is
503
+ // the same unbounded case `close` already had.
504
+ while (buffer.length > 0) {
505
+ drainBuffer();
506
+ if (buffer.length === 0) break;
507
+ await Promise.allSettled([...pending]);
508
+ }
509
+ // Drain every in-flight POST — settled, not raced, so a slow or
510
+ // failing delivery can't be abandoned mid-flight by a fast Promise.race.
511
+ await Promise.allSettled([...pending]);
512
+ },
513
+ };
514
+
515
+ function sendReady(): boolean {
516
+ return pending.size < maxPending;
517
+ }
518
+
519
+ /** Send whole batches while admission allows. Anything left stays buffered
520
+ * for the next trigger rather than being discarded here. */
521
+ function drainBuffer(): void {
522
+ while (buffer.length > 0 && sendReady()) {
523
+ send(buffer.splice(0, maxBatch));
524
+ }
525
+ if (buffer.length === 0 && flushTimer !== undefined) {
526
+ clearTimeout(flushTimer);
527
+ flushTimer = undefined;
528
+ }
529
+ }
530
+
531
+ function send(records: Array<Record<string, unknown>>): void {
532
+ const payload = toOtlpPayload(records, {
533
+ ...(options.serviceVersion === undefined ? {} : { serviceVersion: options.serviceVersion }),
534
+ ...(options.resourceAttributes === undefined
535
+ ? {}
536
+ : { resourceAttributes: options.resourceAttributes }),
537
+ });
538
+ // Build through Headers so header-name case-insensitivity works FOR the
539
+ // binding instead of against it: a caller-supplied `Stream-Name` (any
540
+ // casing) is REPLACED, never merged, by the world-actor stream —
541
+ // ADR-0074's rule that these events never route to ADR-0030 streams.
542
+ const headers = new Headers(options.headers);
543
+ headers.set("content-type", "application/json");
544
+ headers.set("stream-name", OTEL_STREAM_NAME);
545
+ // `doFetch` may throw synchronously (not just return a rejected
546
+ // promise) — a broken shim or a malformed URL, for example. Route
547
+ // both failure shapes through the same `onError` path so `write`
548
+ // itself never throws, matching the `AgentRunSink` contract without
549
+ // relying on the emitter's own try/catch as the only backstop.
550
+ let request: Promise<Response>;
551
+ const controller = new AbortController();
552
+ const timer = setTimeout(() => {
553
+ timedOut++;
554
+ controller.abort();
555
+ }, timeoutMs);
556
+ try {
557
+ request = doFetch(options.endpoint, {
558
+ method: "POST",
559
+ headers,
560
+ body: JSON.stringify(payload),
561
+ signal: controller.signal,
562
+ });
563
+ } catch (error) {
564
+ clearTimeout(timer);
565
+ failed++;
566
+ reportError(error);
567
+ return;
568
+ }
569
+ const post: Promise<void> = request
570
+ .then(async (response) => {
571
+ // The projection does not consume collector response content. Release
572
+ // the body on both success and HTTP failure before freeing admission.
573
+ await response.body?.cancel();
574
+ // fetch only rejects on network/transport failure — a 4xx/5xx
575
+ // resolves normally, so an unchecked `.catch` alone would silently
576
+ // drop delivery failures. Treat non-2xx as a delivery error too.
577
+ if (!response.ok) {
578
+ throw new Error(`OTLP export failed: ${response.status} ${response.statusText}`);
579
+ }
580
+ })
581
+ .catch((error) => {
582
+ failed++;
583
+ // Sinks must never throw into the emitting run (see emit.ts) —
584
+ // the only surfacing path is the caller-supplied onError hook.
585
+ reportError(error);
586
+ })
587
+ .finally(() => {
588
+ clearTimeout(timer);
589
+ pending.delete(post);
590
+ if (pending.size < maxPending) saturated = false;
591
+ });
592
+ pending.add(post);
593
+ }
594
+ }