@osfactory/otel-hook 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.
Files changed (65) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +1020 -0
  3. package/dist/adapter-DIgRACtL.d.ts +303 -0
  4. package/dist/cli.js +12607 -0
  5. package/dist/cli.js.map +1 -0
  6. package/dist/config.d.ts +233 -0
  7. package/dist/config.js +996 -0
  8. package/dist/config.js.map +1 -0
  9. package/dist/content-CoB7aNP1.d.ts +118 -0
  10. package/dist/diagnostics.d.ts +58 -0
  11. package/dist/diagnostics.js +46 -0
  12. package/dist/diagnostics.js.map +1 -0
  13. package/dist/errors.d.ts +91 -0
  14. package/dist/errors.js +322 -0
  15. package/dist/errors.js.map +1 -0
  16. package/dist/events-VxBnDFaO.d.ts +2044 -0
  17. package/dist/filesystem-store-J8jjDMTh.d.ts +65 -0
  18. package/dist/hook-CGpo-vks.d.ts +292 -0
  19. package/dist/identity-BrVBs901.d.ts +227 -0
  20. package/dist/index.d.ts +44 -0
  21. package/dist/index.js +11798 -0
  22. package/dist/index.js.map +1 -0
  23. package/dist/install.d.ts +1021 -0
  24. package/dist/install.js +3271 -0
  25. package/dist/install.js.map +1 -0
  26. package/dist/integration.d.ts +303 -0
  27. package/dist/integration.js +5942 -0
  28. package/dist/integration.js.map +1 -0
  29. package/dist/keys-Dej5bN3L.d.ts +7 -0
  30. package/dist/lifecycle.d.ts +428 -0
  31. package/dist/lifecycle.js +1077 -0
  32. package/dist/lifecycle.js.map +1 -0
  33. package/dist/memory-DXVBc8V9.d.ts +94 -0
  34. package/dist/model.d.ts +45 -0
  35. package/dist/model.js +1023 -0
  36. package/dist/model.js.map +1 -0
  37. package/dist/otlp-log-sink-CeIFDDpn.d.ts +457 -0
  38. package/dist/payload-CHr53E_v.d.ts +201 -0
  39. package/dist/policy-D1CrlYn3.d.ts +73 -0
  40. package/dist/ports-Q8x0ODhs.d.ts +200 -0
  41. package/dist/primitives-CJ8-rn-f.d.ts +75 -0
  42. package/dist/privacy.d.ts +51 -0
  43. package/dist/privacy.js +633 -0
  44. package/dist/privacy.js.map +1 -0
  45. package/dist/providers.d.ts +257 -0
  46. package/dist/providers.js +4398 -0
  47. package/dist/providers.js.map +1 -0
  48. package/dist/registry-BzYmC9OC.d.ts +49 -0
  49. package/dist/runtime.d.ts +32 -0
  50. package/dist/runtime.js +2907 -0
  51. package/dist/runtime.js.map +1 -0
  52. package/dist/schema-Cn0-xz8L.d.ts +224 -0
  53. package/dist/semconv-Baoz-0OI.d.ts +188 -0
  54. package/dist/service-j4jEO6cZ.d.ts +68 -0
  55. package/dist/state.d.ts +36 -0
  56. package/dist/state.js +710 -0
  57. package/dist/state.js.map +1 -0
  58. package/dist/taxonomy-DwhTtuWd.d.ts +87 -0
  59. package/dist/telemetry.d.ts +77 -0
  60. package/dist/telemetry.js +2294 -0
  61. package/dist/telemetry.js.map +1 -0
  62. package/dist/testing.d.ts +155 -0
  63. package/dist/testing.js +6513 -0
  64. package/dist/testing.js.map +1 -0
  65. package/package.json +124 -0
@@ -0,0 +1,2294 @@
1
+ // src/telemetry/semconv.ts
2
+ import { createHash } from "crypto";
3
+ import { SpanKind, SpanStatusCode, TraceFlags } from "@opentelemetry/api";
4
+
5
+ // node_modules/@opentelemetry/core/build/esm/common/time.js
6
+ var NANOSECOND_DIGITS = 9;
7
+ var NANOSECOND_DIGITS_IN_MILLIS = 6;
8
+ var MILLISECONDS_TO_NANOSECONDS = Math.pow(10, NANOSECOND_DIGITS_IN_MILLIS);
9
+ var SECOND_TO_NANOSECONDS = Math.pow(10, NANOSECOND_DIGITS);
10
+ function millisToHrTime(epochMillis) {
11
+ const epochSeconds = epochMillis / 1e3;
12
+ const seconds = Math.trunc(epochSeconds);
13
+ const nanos = Math.round(epochMillis % 1e3 * MILLISECONDS_TO_NANOSECONDS);
14
+ return [seconds, nanos];
15
+ }
16
+
17
+ // node_modules/@opentelemetry/core/build/esm/ExportResult.js
18
+ var ExportResultCode;
19
+ (function(ExportResultCode2) {
20
+ ExportResultCode2[ExportResultCode2["SUCCESS"] = 0] = "SUCCESS";
21
+ ExportResultCode2[ExportResultCode2["FAILED"] = 1] = "FAILED";
22
+ })(ExportResultCode || (ExportResultCode = {}));
23
+
24
+ // src/telemetry/semconv.ts
25
+ import {
26
+ ATTR_ERROR_TYPE,
27
+ ATTR_GEN_AI_OPERATION_NAME,
28
+ ATTR_GEN_AI_REQUEST_MODEL,
29
+ ATTR_GEN_AI_RESPONSE_MODEL,
30
+ ATTR_GEN_AI_SYSTEM,
31
+ ATTR_GEN_AI_TOOL_CALL_ID,
32
+ ATTR_GEN_AI_TOOL_NAME,
33
+ ATTR_GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS,
34
+ ATTR_GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS,
35
+ ATTR_GEN_AI_USAGE_INPUT_TOKENS,
36
+ ATTR_GEN_AI_USAGE_OUTPUT_TOKENS,
37
+ ATTR_GEN_AI_USAGE_REASONING_OUTPUT_TOKENS,
38
+ ATTR_SESSION_ID
39
+ } from "@opentelemetry/semantic-conventions/incubating";
40
+ var SCOPE_NAME = "@osfactory/otel-hook";
41
+ var DEFAULT_INSTRUMENTATION_SCOPE = Object.freeze({
42
+ name: SCOPE_NAME,
43
+ version: "0.1.0"
44
+ });
45
+ var ATTR_OTELHOOK_INVOCATION_ID = "otelhook.invocation.id";
46
+ var ATTR_OTELHOOK_PROVIDER_ID = "otelhook.provider.id";
47
+ var ATTR_OTELHOOK_PROVIDER_VERSION = "otelhook.provider.version";
48
+ var ATTR_OTELHOOK_WORKSPACE_ID = "otelhook.workspace.id";
49
+ var ATTR_OTELHOOK_SPAN_PAIRED = "otelhook.span.paired";
50
+ var ATTR_OTELHOOK_SPAN_PAIRING = "otelhook.span.pairing";
51
+ var ATTR_OTELHOOK_SPAN_ORPHAN = "otelhook.span.orphan";
52
+ var ATTR_OTELHOOK_OUTCOME = "otelhook.outcome";
53
+ var ATTR_OTELHOOK_RESET_DETECTED = "otelhook.usage.reset_detected";
54
+ var ATTR_OTELHOOK_TOOL_KIND = "otelhook.tool.kind";
55
+ var ATTR_OTELHOOK_DELEGATION_DEPTH = "otelhook.delegation_depth";
56
+ var ATTR_OTELHOOK_COMPACTION_TRIGGER = "otelhook.compaction.trigger";
57
+ var ATTR_OTELHOOK_AGENT_NAME = "otelhook.agent.name";
58
+ var ATTR_OTELHOOK_AGENT_VERSION = "otelhook.agent.version";
59
+ var FIELD_SEPARATOR = "\0";
60
+ var digestHex = (parts, length) => createHash("sha256").update(parts.join(FIELD_SEPARATOR)).digest("hex").slice(0, length);
61
+ var MAX_RECOVERED_START_ATTRIBUTES = 16;
62
+ var familyOf = (type) => {
63
+ switch (type) {
64
+ case "session.start":
65
+ case "session.end":
66
+ return "session";
67
+ case "generation.start":
68
+ case "generation.end":
69
+ return "generation";
70
+ case "tool.start":
71
+ case "tool.end":
72
+ return "tool";
73
+ case "subagent.start":
74
+ case "subagent.end":
75
+ return "subagent";
76
+ default:
77
+ return void 0;
78
+ }
79
+ };
80
+ var spanScopeRefOf = (event) => {
81
+ const family = familyOf(event.type);
82
+ if (family === void 0) {
83
+ return void 0;
84
+ }
85
+ switch (event.type) {
86
+ case "session.start":
87
+ case "session.end":
88
+ return { family, scopeKey: event.sessionId };
89
+ case "generation.start":
90
+ case "generation.end":
91
+ return { family, scopeKey: event.generationId };
92
+ case "tool.start":
93
+ case "tool.end":
94
+ return { family, scopeKey: event.toolCallId };
95
+ case "subagent.start":
96
+ case "subagent.end":
97
+ return { family, scopeKey: event.subagentInvocationId };
98
+ default:
99
+ return void 0;
100
+ }
101
+ };
102
+ var parentScopeRefOf = (event) => {
103
+ if (event.type === "session.start" || event.type === "session.end") {
104
+ return void 0;
105
+ }
106
+ if (event.type === "tool.start" && event.generationId !== void 0) {
107
+ return { family: "generation", scopeKey: event.generationId };
108
+ }
109
+ return { family: "session", scopeKey: event.sessionId };
110
+ };
111
+ var startOnlySpanAttributes = (event) => {
112
+ switch (event.type) {
113
+ case "session.start":
114
+ return {
115
+ ...event.agentName === void 0 ? {} : { [ATTR_OTELHOOK_AGENT_NAME]: event.agentName },
116
+ ...event.agentVersion === void 0 ? {} : { [ATTR_OTELHOOK_AGENT_VERSION]: event.agentVersion }
117
+ };
118
+ case "generation.start":
119
+ return {
120
+ [ATTR_GEN_AI_REQUEST_MODEL]: event.model.modelId,
121
+ ...event.model.vendor === void 0 ? {} : { [ATTR_GEN_AI_SYSTEM]: event.model.vendor }
122
+ };
123
+ // `toolName` and `toolCallId` are on both tool edges, so they are not
124
+ // start-only and persisting them would just pad every record.
125
+ case "tool.start":
126
+ return { [ATTR_OTELHOOK_TOOL_KIND]: event.toolKind };
127
+ case "subagent.start":
128
+ return { [ATTR_OTELHOOK_DELEGATION_DEPTH]: event.delegationDepth };
129
+ default:
130
+ return {};
131
+ }
132
+ };
133
+ var deriveTraceId = (providerId, sessionId) => digestHex(["otelhook/trace", providerId, sessionId], 32);
134
+ var deriveSpanId = (providerId, sessionId, ref) => digestHex(["otelhook/span", providerId, sessionId, ref.family, ref.scopeKey], 16);
135
+ var deriveStandaloneSpanId = (providerId, sessionId, eventType, eventId) => digestHex(["otelhook/span", providerId, sessionId, "event", eventType, eventId], 16);
136
+ var correlationKey = (providerId, sessionId, ref) => [providerId, sessionId, ref.family, ref.scopeKey].join(FIELD_SEPARATOR);
137
+ var outcomeStatus = (outcome) => {
138
+ if (outcome === void 0 || outcome === "ok" || outcome === "unknown") {
139
+ return { code: SpanStatusCode.UNSET };
140
+ }
141
+ if (outcome === "cancelled") {
142
+ return { code: SpanStatusCode.UNSET };
143
+ }
144
+ return { code: SpanStatusCode.ERROR, message: outcome };
145
+ };
146
+ var identityAttributes = (event) => ({
147
+ [ATTR_SESSION_ID]: event.sessionId,
148
+ [ATTR_OTELHOOK_INVOCATION_ID]: event.invocationId,
149
+ [ATTR_OTELHOOK_PROVIDER_ID]: event.provenance.providerId,
150
+ ...event.provenance.providerVersion === void 0 ? {} : { [ATTR_OTELHOOK_PROVIDER_VERSION]: event.provenance.providerVersion },
151
+ [ATTR_OTELHOOK_WORKSPACE_ID]: event.workspace.workspaceId
152
+ });
153
+ var usageAttributes = (usage, resetDetected) => {
154
+ if (usage === void 0) {
155
+ return {};
156
+ }
157
+ return {
158
+ [ATTR_GEN_AI_USAGE_INPUT_TOKENS]: usage.inputTokens,
159
+ [ATTR_GEN_AI_USAGE_OUTPUT_TOKENS]: usage.outputTokens,
160
+ [ATTR_GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS]: usage.cachedInputTokens,
161
+ [ATTR_GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS]: usage.cacheCreationInputTokens,
162
+ [ATTR_GEN_AI_USAGE_REASONING_OUTPUT_TOKENS]: usage.reasoningOutputTokens,
163
+ ...resetDetected ? { [ATTR_OTELHOOK_RESET_DETECTED]: true } : {}
164
+ };
165
+ };
166
+ var buildSpanContext = (traceId, spanId) => ({
167
+ traceId,
168
+ spanId,
169
+ traceFlags: TraceFlags.SAMPLED,
170
+ isRemote: false
171
+ });
172
+ var assembleReadableSpan = (input) => toReadableSpan(input);
173
+ var toReadableSpan = (input) => {
174
+ const startTime = millisToHrTime(input.startMillis);
175
+ const endTime = millisToHrTime(Math.max(input.startMillis, input.endMillis));
176
+ const duration = millisToHrTime(Math.max(0, input.endMillis - input.startMillis));
177
+ return {
178
+ name: input.name,
179
+ kind: input.kind,
180
+ spanContext: () => buildSpanContext(input.traceId, input.spanId),
181
+ ...input.parentSpanId === void 0 ? {} : { parentSpanContext: buildSpanContext(input.traceId, input.parentSpanId) },
182
+ startTime,
183
+ endTime,
184
+ status: input.status,
185
+ attributes: input.attributes,
186
+ links: [],
187
+ events: [],
188
+ duration,
189
+ ended: true,
190
+ resource: input.resource,
191
+ instrumentationScope: input.instrumentationScope,
192
+ droppedAttributesCount: 0,
193
+ droppedEventsCount: 0,
194
+ droppedLinksCount: 0
195
+ };
196
+ };
197
+ var resolvePairing = (group, anchor, correlation) => {
198
+ const inBatch = group.start !== void 0 && group.end !== void 0;
199
+ const batchStart = group.start?.occurredAt ?? anchor.occurredAt;
200
+ const batchEnd = group.end?.occurredAt ?? anchor.occurredAt;
201
+ if (correlation === void 0) {
202
+ return {
203
+ pairing: inBatch ? "in-batch" : "unpaired",
204
+ orphan: inBatch ? "none" : group.start === void 0 ? "missing-start" : "missing-end",
205
+ startMillis: batchStart,
206
+ endMillis: inBatch ? batchEnd : batchStart,
207
+ parent: parentScopeRefOf(anchor),
208
+ recovered: {}
209
+ };
210
+ }
211
+ const startMillis = correlation.startMillis ?? (inBatch ? batchStart : batchEnd);
212
+ const endMillis = correlation.endMillis ?? (group.end === void 0 ? startMillis : batchEnd);
213
+ return {
214
+ pairing: correlation.pairing,
215
+ orphan: correlation.orphan,
216
+ startMillis,
217
+ endMillis,
218
+ parent: correlation.parent ?? parentScopeRefOf(anchor),
219
+ recovered: correlation.attributes ?? {}
220
+ };
221
+ };
222
+ var buildLifecycleSpan = (plan, resource, scope) => {
223
+ const group = plan.group;
224
+ const anchor = plan.anchor;
225
+ const correlation = plan.correlation;
226
+ const providerId = anchor.provenance.providerId;
227
+ const sessionId = anchor.sessionId;
228
+ const resolved = resolvePairing(group, anchor, correlation);
229
+ const traceId = plan.traceId;
230
+ const spanId = plan.spanId;
231
+ const parentSpanId = resolved.parent === void 0 ? void 0 : deriveSpanId(providerId, sessionId, resolved.parent);
232
+ let name = group.ref.family;
233
+ let kind = SpanKind.INTERNAL;
234
+ let status = { code: SpanStatusCode.UNSET };
235
+ let attributes = {
236
+ ...identityAttributes(anchor),
237
+ ...resolved.recovered,
238
+ [ATTR_OTELHOOK_SPAN_PAIRED]: resolved.pairing !== "unpaired",
239
+ [ATTR_OTELHOOK_SPAN_PAIRING]: resolved.pairing,
240
+ [ATTR_OTELHOOK_SPAN_ORPHAN]: resolved.orphan
241
+ };
242
+ switch (group.ref.family) {
243
+ case "session": {
244
+ const end = group.end?.type === "session.end" ? group.end : void 0;
245
+ const start = group.start?.type === "session.start" ? group.start : void 0;
246
+ name = "session";
247
+ kind = SpanKind.INTERNAL;
248
+ attributes = {
249
+ ...attributes,
250
+ ...start?.agentName === void 0 ? {} : { [ATTR_OTELHOOK_AGENT_NAME]: start.agentName },
251
+ ...start?.agentVersion === void 0 ? {} : { [ATTR_OTELHOOK_AGENT_VERSION]: start.agentVersion },
252
+ ...end === void 0 ? {} : { [ATTR_OTELHOOK_OUTCOME]: end.reason },
253
+ ...usageAttributes(end?.usage, false)
254
+ };
255
+ if (end?.reason === "error" || end?.reason === "timeout") {
256
+ status = { code: SpanStatusCode.ERROR, message: end.reason };
257
+ }
258
+ break;
259
+ }
260
+ case "generation": {
261
+ const start = group.start?.type === "generation.start" ? group.start : void 0;
262
+ const end = group.end?.type === "generation.end" ? group.end : void 0;
263
+ const model = end?.model ?? start?.model;
264
+ name = model === void 0 ? "generation" : `generation ${model.modelId}`;
265
+ kind = SpanKind.CLIENT;
266
+ attributes = {
267
+ ...attributes,
268
+ [ATTR_GEN_AI_OPERATION_NAME]: "chat",
269
+ ...model?.vendor === void 0 ? {} : { [ATTR_GEN_AI_SYSTEM]: model.vendor },
270
+ ...start?.model?.modelId === void 0 ? {} : { [ATTR_GEN_AI_REQUEST_MODEL]: start.model.modelId },
271
+ ...end?.model?.modelId === void 0 ? {} : { [ATTR_GEN_AI_RESPONSE_MODEL]: end.model.modelId },
272
+ ...end?.outcome === void 0 ? {} : { [ATTR_OTELHOOK_OUTCOME]: end.outcome },
273
+ ...usageAttributes(end?.usage, false)
274
+ };
275
+ status = outcomeStatus(end?.outcome);
276
+ break;
277
+ }
278
+ case "tool": {
279
+ const start = group.start?.type === "tool.start" ? group.start : void 0;
280
+ const end = group.end?.type === "tool.end" ? group.end : void 0;
281
+ const toolName = start?.toolName ?? end?.toolName ?? "unknown";
282
+ name = `tool ${toolName}`;
283
+ kind = SpanKind.CLIENT;
284
+ attributes = {
285
+ ...attributes,
286
+ [ATTR_GEN_AI_TOOL_NAME]: toolName,
287
+ [ATTR_GEN_AI_TOOL_CALL_ID]: start?.toolCallId ?? end?.toolCallId ?? group.ref.scopeKey,
288
+ ...start?.toolKind === void 0 ? {} : { [ATTR_OTELHOOK_TOOL_KIND]: start.toolKind },
289
+ ...end?.outcome === void 0 ? {} : { [ATTR_OTELHOOK_OUTCOME]: end.outcome }
290
+ };
291
+ status = outcomeStatus(end?.outcome);
292
+ break;
293
+ }
294
+ case "subagent": {
295
+ const start = group.start?.type === "subagent.start" ? group.start : void 0;
296
+ const end = group.end?.type === "subagent.end" ? group.end : void 0;
297
+ name = "subagent";
298
+ kind = SpanKind.INTERNAL;
299
+ attributes = {
300
+ ...attributes,
301
+ ...start?.delegationDepth === void 0 ? {} : { [ATTR_OTELHOOK_DELEGATION_DEPTH]: start.delegationDepth },
302
+ ...end?.outcome === void 0 ? {} : { [ATTR_OTELHOOK_OUTCOME]: end.outcome },
303
+ ...usageAttributes(end?.usage, false)
304
+ };
305
+ status = outcomeStatus(end?.outcome);
306
+ break;
307
+ }
308
+ }
309
+ if (status.code === SpanStatusCode.ERROR) {
310
+ attributes = { ...attributes, [ATTR_ERROR_TYPE]: status.message ?? "error" };
311
+ }
312
+ return toReadableSpan({
313
+ name,
314
+ kind,
315
+ startMillis: resolved.startMillis,
316
+ endMillis: resolved.endMillis,
317
+ attributes,
318
+ status,
319
+ traceId,
320
+ spanId,
321
+ ...parentSpanId === void 0 ? {} : { parentSpanId },
322
+ resource,
323
+ instrumentationScope: scope
324
+ });
325
+ };
326
+ var buildStandaloneSpan = (event, resource, scope) => {
327
+ const providerId = event.provenance.providerId;
328
+ const traceId = deriveTraceId(providerId, event.sessionId);
329
+ const spanId = deriveStandaloneSpanId(providerId, event.sessionId, event.type, event.eventId);
330
+ const parent = parentScopeRefOf(event);
331
+ let attributes = { ...identityAttributes(event), [ATTR_OTELHOOK_SPAN_PAIRED]: true };
332
+ let status = { code: SpanStatusCode.UNSET };
333
+ let name = event.type;
334
+ switch (event.type) {
335
+ case "prompt.submitted":
336
+ name = "prompt";
337
+ attributes = { ...attributes, "otelhook.prompt.source": event.promptSource };
338
+ break;
339
+ case "compaction.performed":
340
+ name = "compaction";
341
+ attributes = {
342
+ ...attributes,
343
+ [ATTR_OTELHOOK_COMPACTION_TRIGGER]: event.trigger,
344
+ ...usageAttributes(event.usage, false)
345
+ };
346
+ break;
347
+ case "error.raised":
348
+ name = "error";
349
+ status = { code: SpanStatusCode.ERROR, message: event.errorCode };
350
+ attributes = {
351
+ ...attributes,
352
+ [ATTR_ERROR_TYPE]: event.errorCode,
353
+ "otelhook.error.phase": event.phase,
354
+ "otelhook.error.retryable": event.retryable
355
+ };
356
+ break;
357
+ default:
358
+ break;
359
+ }
360
+ return toReadableSpan({
361
+ name,
362
+ kind: SpanKind.INTERNAL,
363
+ startMillis: event.occurredAt,
364
+ endMillis: event.occurredAt,
365
+ attributes,
366
+ status,
367
+ traceId,
368
+ spanId,
369
+ ...parent === void 0 ? {} : { parentSpanId: deriveSpanId(providerId, event.sessionId, parent) },
370
+ resource,
371
+ instrumentationScope: scope
372
+ });
373
+ };
374
+ var effectiveCorrelation = (group, correlation) => {
375
+ if (correlation !== void 0 || group.end !== void 0 || group.start === void 0) {
376
+ return correlation;
377
+ }
378
+ return {
379
+ providerId: group.start.provenance.providerId,
380
+ sessionId: group.start.sessionId,
381
+ ref: group.ref,
382
+ pairing: "unpaired",
383
+ orphan: "state-unavailable",
384
+ disposition: "emit",
385
+ spanIdDiscriminator: group.start.eventId
386
+ };
387
+ };
388
+ var layoutBatch = (events) => {
389
+ const groups = /* @__PURE__ */ new Map();
390
+ const standalone = [];
391
+ const groupOf = /* @__PURE__ */ new Map();
392
+ for (const event of events) {
393
+ const ref = spanScopeRefOf(event);
394
+ if (ref === void 0) {
395
+ standalone.push(event);
396
+ continue;
397
+ }
398
+ const groupKey = correlationKey(event.provenance.providerId, event.sessionId, ref);
399
+ const group = groups.get(groupKey) ?? { ref };
400
+ if (event.type.endsWith(".start")) {
401
+ group.start = event;
402
+ } else {
403
+ group.end = event;
404
+ }
405
+ groups.set(groupKey, group);
406
+ groupOf.set(event.eventId, groupKey);
407
+ }
408
+ return { groups, standalone, groupOf };
409
+ };
410
+ var indexCorrelations = (correlations) => {
411
+ const indexed = /* @__PURE__ */ new Map();
412
+ for (const correlation of correlations ?? []) {
413
+ indexed.set(
414
+ correlationKey(correlation.providerId, correlation.sessionId, correlation.ref),
415
+ correlation
416
+ );
417
+ }
418
+ return indexed;
419
+ };
420
+ var planGroup = (group, correlation, correlationAvailable) => {
421
+ const anchor = group.start ?? group.end;
422
+ if (anchor === void 0) {
423
+ return void 0;
424
+ }
425
+ const providerId = anchor.provenance.providerId;
426
+ const sessionId = anchor.sessionId;
427
+ const durablyRecorded = group.end === void 0 && (correlation?.disposition === "defer" || // No correlator wired at all: cross-process pairing was never on offer, so
428
+ // this is the documented no-state-root degradation rather than a failure to
429
+ // persist something that should have been persisted.
430
+ correlation === void 0 && correlationAvailable === void 0);
431
+ const effective = durablyRecorded ? correlation : effectiveCorrelation(group, correlation);
432
+ const discriminator = durablyRecorded ? void 0 : effective?.spanIdDiscriminator;
433
+ return {
434
+ group,
435
+ anchor,
436
+ emits: !durablyRecorded,
437
+ correlation: effective,
438
+ traceId: deriveTraceId(providerId, sessionId),
439
+ spanId: discriminator === void 0 ? deriveSpanId(providerId, sessionId, group.ref) : digestHex(
440
+ [
441
+ "otelhook/span",
442
+ providerId,
443
+ sessionId,
444
+ group.ref.family,
445
+ group.ref.scopeKey,
446
+ discriminator
447
+ ],
448
+ 16
449
+ )
450
+ };
451
+ };
452
+ var canonicalEventTraceIdentities = (events, options = {}) => {
453
+ const layout = layoutBatch(events);
454
+ const correlations = indexCorrelations(options.correlations);
455
+ const plans = /* @__PURE__ */ new Map();
456
+ for (const [groupKey, group] of layout.groups) {
457
+ const plan = planGroup(group, correlations.get(groupKey), options.correlationAvailable);
458
+ if (plan !== void 0) {
459
+ plans.set(groupKey, plan);
460
+ }
461
+ }
462
+ const identities = /* @__PURE__ */ new Map();
463
+ for (const event of events) {
464
+ const providerId = event.provenance.providerId;
465
+ const groupKey = layout.groupOf.get(event.eventId);
466
+ const plan = groupKey === void 0 ? void 0 : plans.get(groupKey);
467
+ if (plan === void 0) {
468
+ identities.set(event.eventId, {
469
+ traceId: deriveTraceId(providerId, event.sessionId),
470
+ spanId: deriveStandaloneSpanId(providerId, event.sessionId, event.type, event.eventId)
471
+ });
472
+ continue;
473
+ }
474
+ identities.set(event.eventId, { traceId: plan.traceId, spanId: plan.spanId });
475
+ }
476
+ return identities;
477
+ };
478
+ var canonicalEventsToReadableSpans = (events, options) => {
479
+ const scope = options.instrumentationScope ?? DEFAULT_INSTRUMENTATION_SCOPE;
480
+ const layout = layoutBatch(events);
481
+ const correlations = indexCorrelations(options.correlations);
482
+ const spans = [];
483
+ for (const [groupKey, group] of layout.groups) {
484
+ const plan = planGroup(group, correlations.get(groupKey), options.correlationAvailable);
485
+ if (plan === void 0 || !plan.emits) {
486
+ continue;
487
+ }
488
+ spans.push(buildLifecycleSpan(plan, options.resource, scope));
489
+ }
490
+ for (const event of layout.standalone) {
491
+ spans.push(buildStandaloneSpan(event, options.resource, scope));
492
+ }
493
+ return spans;
494
+ };
495
+
496
+ // src/telemetry/spool-queue.ts
497
+ import { randomBytes } from "crypto";
498
+ import { mkdir, readFile, readdir, rename, unlink, writeFile } from "fs/promises";
499
+ import * as path from "path";
500
+
501
+ // src/state/keys.ts
502
+ import { createHash as createHash2 } from "crypto";
503
+ var SAFE_SEGMENT_PATTERN = /^[A-Za-z0-9_-]{1,128}$/;
504
+ var isSafeSegment = (segment) => SAFE_SEGMENT_PATTERN.test(segment);
505
+ var sanitizeSegment = (segment) => {
506
+ if (isSafeSegment(segment)) {
507
+ return segment;
508
+ }
509
+ return `h_${createHash2("sha256").update(segment, "utf8").digest("hex").slice(0, 32)}`;
510
+ };
511
+ var namespaceSegments = (namespace) => [
512
+ sanitizeSegment(namespace.providerId),
513
+ sanitizeSegment(namespace.installationId)
514
+ ];
515
+
516
+ // src/telemetry/spool-queue.ts
517
+ var DEFAULT_DRAIN_MAX_BATCHES = 20;
518
+ var isErrnoException = (thrown, code) => thrown instanceof Error && thrown.code === code;
519
+ var createSpoolQueue = (options) => {
520
+ const [providerSegment, installationSegment] = namespaceSegments(options);
521
+ const queueDir = path.join(options.rootDir, providerSegment, installationSegment, options.queueName);
522
+ const corruptDir = path.join(
523
+ options.rootDir,
524
+ providerSegment,
525
+ installationSegment,
526
+ `${options.queueName}-corrupt`
527
+ );
528
+ let dirsReady;
529
+ const ensureDirs = async () => {
530
+ if (dirsReady !== void 0) {
531
+ return dirsReady;
532
+ }
533
+ const promise = (async () => {
534
+ await mkdir(queueDir, { recursive: true });
535
+ await mkdir(corruptDir, { recursive: true });
536
+ })();
537
+ dirsReady = promise;
538
+ try {
539
+ await promise;
540
+ } catch (thrown) {
541
+ dirsReady = void 0;
542
+ throw thrown;
543
+ }
544
+ };
545
+ const listSorted = async () => {
546
+ let entries;
547
+ try {
548
+ entries = await readdir(queueDir);
549
+ } catch (thrown) {
550
+ if (isErrnoException(thrown, "ENOENT")) {
551
+ return [];
552
+ }
553
+ throw thrown;
554
+ }
555
+ return entries.filter((entry) => entry.endsWith(".json") && !entry.startsWith(".tmp-")).sort();
556
+ };
557
+ const enqueue = async (batch) => {
558
+ await ensureDirs();
559
+ const existing = await listSorted();
560
+ if (existing.length >= options.maxFiles) {
561
+ options.logger?.warn("durable spool at capacity; batch dropped", {
562
+ "spool.max_files": options.maxFiles,
563
+ "spool.queue": options.queueName
564
+ });
565
+ return { spooled: false, reason: "capacity-exceeded" };
566
+ }
567
+ const fileName = `${String(options.clock.now()).padStart(16, "0")}-${randomBytes(6).toString("hex")}.json`;
568
+ const target = path.join(queueDir, fileName);
569
+ const tmp = path.join(queueDir, `.tmp-${randomBytes(6).toString("hex")}.json`);
570
+ await writeFile(tmp, JSON.stringify(batch), "utf8");
571
+ await rename(tmp, target);
572
+ return { spooled: true };
573
+ };
574
+ const drain = async (send, drainOptions) => {
575
+ await ensureDirs();
576
+ const cap = drainOptions?.maxBatches ?? DEFAULT_DRAIN_MAX_BATCHES;
577
+ const files = await listSorted();
578
+ let drained = 0;
579
+ let failed = 0;
580
+ let quarantined = 0;
581
+ let index = 0;
582
+ for (; index < files.length && index < cap; index += 1) {
583
+ const fileName = files[index];
584
+ if (fileName === void 0) {
585
+ break;
586
+ }
587
+ const filePath = path.join(queueDir, fileName);
588
+ const quarantine = async (rejection) => {
589
+ quarantined += 1;
590
+ options.logger?.error("durable spool quarantined an unusable batch", {
591
+ "spool.rejection": rejection,
592
+ "spool.file": fileName,
593
+ "spool.queue": options.queueName
594
+ });
595
+ try {
596
+ await rename(filePath, path.join(corruptDir, fileName));
597
+ } catch {
598
+ await unlink(filePath).catch(() => void 0);
599
+ }
600
+ };
601
+ let parsed;
602
+ try {
603
+ parsed = JSON.parse(await readFile(filePath, "utf8"));
604
+ } catch {
605
+ await quarantine("unparseable-json");
606
+ continue;
607
+ }
608
+ const validation = options.validate(parsed, {
609
+ providerId: options.providerId,
610
+ installationId: options.installationId
611
+ });
612
+ if ("rejection" in validation) {
613
+ await quarantine(validation.rejection);
614
+ continue;
615
+ }
616
+ let delivered;
617
+ try {
618
+ delivered = await send(validation.batch);
619
+ } catch {
620
+ delivered = false;
621
+ }
622
+ if (delivered) {
623
+ await unlink(filePath).catch(() => void 0);
624
+ drained += 1;
625
+ } else {
626
+ failed += 1;
627
+ break;
628
+ }
629
+ }
630
+ const remaining = (await listSorted()).length;
631
+ return { drained, remaining, failed, quarantined };
632
+ };
633
+ return {
634
+ enqueue,
635
+ drain,
636
+ size: async () => {
637
+ await ensureDirs();
638
+ return (await listSorted()).length;
639
+ }
640
+ };
641
+ };
642
+
643
+ // src/telemetry/durable-spool.ts
644
+ var MAX_SPOOLED_SPANS_PER_BATCH = 4096;
645
+ var MAX_SPOOLED_STRING_LENGTH = 8192;
646
+ var MAX_SPOOLED_ATTRIBUTES_PER_SPAN = 256;
647
+ var TRACE_ID_PATTERN = /^[0-9a-f]{32}$/;
648
+ var SPAN_ID_PATTERN = /^[0-9a-f]{16}$/;
649
+ var isFiniteNonNegative = (value) => typeof value === "number" && Number.isFinite(value) && value >= 0;
650
+ var isBoundedString = (value, maxLength = MAX_SPOOLED_STRING_LENGTH) => typeof value === "string" && value.length > 0 && value.length <= maxLength;
651
+ var isPlainObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
652
+ var isReplayableSpan = (value) => {
653
+ if (!isPlainObject(value)) {
654
+ return false;
655
+ }
656
+ if (!isBoundedString(value.name) || !isFiniteNonNegative(value.kind)) {
657
+ return false;
658
+ }
659
+ if (typeof value.traceId !== "string" || !TRACE_ID_PATTERN.test(value.traceId)) {
660
+ return false;
661
+ }
662
+ if (typeof value.spanId !== "string" || !SPAN_ID_PATTERN.test(value.spanId)) {
663
+ return false;
664
+ }
665
+ if (value.parentSpanId !== void 0 && (typeof value.parentSpanId !== "string" || !SPAN_ID_PATTERN.test(value.parentSpanId))) {
666
+ return false;
667
+ }
668
+ if (!isFiniteNonNegative(value.startMillis) || !isFiniteNonNegative(value.endMillis)) {
669
+ return false;
670
+ }
671
+ if (!isFiniteNonNegative(value.statusCode)) {
672
+ return false;
673
+ }
674
+ if (value.statusMessage !== void 0 && typeof value.statusMessage !== "string") {
675
+ return false;
676
+ }
677
+ if (!isPlainObject(value.attributes)) {
678
+ return false;
679
+ }
680
+ const entries = Object.entries(value.attributes);
681
+ if (entries.length > MAX_SPOOLED_ATTRIBUTES_PER_SPAN) {
682
+ return false;
683
+ }
684
+ return entries.every(([, attribute]) => {
685
+ if (Array.isArray(attribute)) {
686
+ return attribute.every(
687
+ (item) => typeof item === "string" && item.length <= MAX_SPOOLED_STRING_LENGTH || typeof item === "number" && Number.isFinite(item) || typeof item === "boolean" || item === null
688
+ );
689
+ }
690
+ return typeof attribute === "string" && attribute.length <= MAX_SPOOLED_STRING_LENGTH || typeof attribute === "number" && Number.isFinite(attribute) || typeof attribute === "boolean" || attribute === void 0;
691
+ });
692
+ };
693
+ var validateSpoolBatch = (value, identity) => {
694
+ if (!isPlainObject(value)) {
695
+ return { rejection: "not-an-object" };
696
+ }
697
+ if (value.providerId !== identity.providerId || value.installationId !== identity.installationId) {
698
+ return { rejection: "identity-mismatch" };
699
+ }
700
+ if (!isPlainObject(value.resourceAttributes)) {
701
+ return { rejection: "resource-attributes-invalid" };
702
+ }
703
+ if (!isPlainObject(value.instrumentationScope) || !isBoundedString(value.instrumentationScope.name)) {
704
+ return { rejection: "instrumentation-scope-invalid" };
705
+ }
706
+ if (value.instrumentationScope.version !== void 0 && typeof value.instrumentationScope.version !== "string") {
707
+ return { rejection: "instrumentation-scope-invalid" };
708
+ }
709
+ if (!Array.isArray(value.spans) || value.spans.length === 0) {
710
+ return { rejection: "spans-invalid" };
711
+ }
712
+ if (value.spans.length > MAX_SPOOLED_SPANS_PER_BATCH) {
713
+ return { rejection: "spans-invalid" };
714
+ }
715
+ if (!value.spans.every(isReplayableSpan)) {
716
+ return { rejection: "span-field-invalid" };
717
+ }
718
+ if (!isFiniteNonNegative(value.enqueuedAt)) {
719
+ return { rejection: "not-an-object" };
720
+ }
721
+ return { batch: value };
722
+ };
723
+ var DEFAULT_MAX_SPOOL_FILES = 500;
724
+ var createFileDurableSpool = (options) => createSpoolQueue({
725
+ rootDir: options.rootDir,
726
+ providerId: options.providerId,
727
+ installationId: options.installationId,
728
+ clock: options.clock,
729
+ ...options.logger === void 0 ? {} : { logger: options.logger },
730
+ maxFiles: options.maxSpoolFiles ?? DEFAULT_MAX_SPOOL_FILES,
731
+ queueName: "spool",
732
+ validate: validateSpoolBatch
733
+ });
734
+
735
+ // src/telemetry/otlp-sink.ts
736
+ import { OTLPTraceExporter } from "@opentelemetry/exporter-trace-otlp-proto";
737
+
738
+ // src/errors/index.ts
739
+ import { z as z3 } from "zod";
740
+
741
+ // src/model/primitives.ts
742
+ import { z } from "zod";
743
+ var MAX_IDENTIFIER_LENGTH = 256;
744
+ var MAX_ATTRIBUTE_STRING_LENGTH = 4096;
745
+ var MAX_ATTRIBUTE_ARRAY_LENGTH = 128;
746
+ var nonEmptyStringSchema = z.string().min(1).max(MAX_IDENTIFIER_LENGTH);
747
+ var epochMillisSchema = z.number().int().min(0).max(864e13);
748
+ var durationMillisSchema = z.number().min(0).finite();
749
+ var tokenCountSchema = z.number().int().min(0);
750
+ var sequenceNumberSchema = z.number().int().min(0);
751
+ var brandedIdSchema = () => z.string().min(1).max(MAX_IDENTIFIER_LENGTH);
752
+ var invocationIdSchema = brandedIdSchema().brand();
753
+ var sessionIdSchema = brandedIdSchema().brand();
754
+ var eventIdSchema = brandedIdSchema().brand();
755
+ var WORKSPACE_ID_PATTERN = /^[a-z][a-z0-9]{0,15}:[A-Za-z0-9_-]{8,128}$/;
756
+ var workspaceIdSchema = z.string().regex(WORKSPACE_ID_PATTERN, "workspace id must be an opaque `<scheme>:<token>` handle").brand();
757
+ var PROVIDER_ID_PATTERN = /^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/;
758
+ var providerIdSchema = z.string().min(1).max(64).regex(PROVIDER_ID_PATTERN, "provider id must be lowercase and hyphenated").brand();
759
+ var UNKNOWN_PROVIDER_ID = "unknown";
760
+ var resolvedProviderIdSchema = z.union([
761
+ providerIdSchema,
762
+ z.literal(UNKNOWN_PROVIDER_ID)
763
+ ]);
764
+ var attributePrimitiveSchema = z.union([
765
+ z.string().max(MAX_ATTRIBUTE_STRING_LENGTH),
766
+ z.number().finite(),
767
+ z.boolean()
768
+ ]);
769
+ var attributeValueSchema = z.union([
770
+ attributePrimitiveSchema,
771
+ z.array(attributePrimitiveSchema).max(MAX_ATTRIBUTE_ARRAY_LENGTH)
772
+ ]);
773
+ var attributesSchema = z.record(z.string().min(1).max(MAX_IDENTIFIER_LENGTH), attributeValueSchema);
774
+ var detectionConfidenceSchema = z.enum(["none", "weak", "strong", "exact"]);
775
+ var DETECTION_CONFIDENCE_RANK = Object.freeze({
776
+ none: 0,
777
+ weak: 1,
778
+ strong: 2,
779
+ exact: 3
780
+ });
781
+ var sourceTransportSchema = z.enum([
782
+ "hook-stdin",
783
+ "cli-argument",
784
+ "library-call",
785
+ "test-fixture"
786
+ ]);
787
+
788
+ // src/errors/taxonomy.ts
789
+ import { z as z2 } from "zod";
790
+ var otelHookErrorCodeSchema = z2.enum([
791
+ /** Input was not usable at all (empty stdin, unparsable JSON). */
792
+ "invalid-input",
793
+ /** Input parsed but failed canonical schema validation. */
794
+ "schema-validation-failed",
795
+ /** No adapter claimed the input with sufficient confidence. */
796
+ "provider-unknown",
797
+ /** Several adapters claimed the input at the same confidence. */
798
+ "provider-detection-ambiguous",
799
+ /** An adapter threw or returned a malformed result. */
800
+ "provider-adapter-failure",
801
+ /** Two identity claims disagreed at equal confidence. */
802
+ "identity-conflict",
803
+ /** Required identity fields were absent. */
804
+ "identity-incomplete",
805
+ /** A usage report violated the canonical usage invariants. */
806
+ "usage-invalid",
807
+ /** The state store could not be read or written. */
808
+ "state-store-failure",
809
+ /** The telemetry sink rejected or could not deliver a batch. */
810
+ "telemetry-export-failure",
811
+ /** Content reached the sink boundary in a state the policy forbids. */
812
+ "privacy-policy-violation",
813
+ /** Configuration could not be resolved. */
814
+ "configuration-invalid",
815
+ /** A configured bound (events, batch size) dropped data. */
816
+ "limit-exceeded",
817
+ /**
818
+ * No replay-stable delivery identifier was available for a callback while
819
+ * deduplication was required.
820
+ */
821
+ "delivery-identifier-unavailable",
822
+ "delivery-claim-superseded",
823
+ /** Anything unanticipated. Always reported, never fatal to the host. */
824
+ "internal-error"
825
+ ]);
826
+ var errorSeveritySchema = z2.enum(["warning", "error"]);
827
+ var errorPhaseSchema = z2.enum([
828
+ "configuration",
829
+ "detection",
830
+ "identity",
831
+ "parsing",
832
+ "normalization",
833
+ "privacy",
834
+ "state",
835
+ "export",
836
+ "shutdown"
837
+ ]);
838
+ var failurePostureSchema = z2.enum(["fail-open", "fail-closed-attribution"]);
839
+ var ERROR_TAXONOMY = Object.freeze({
840
+ "invalid-input": {
841
+ code: "invalid-input",
842
+ severity: "warning",
843
+ posture: "fail-open",
844
+ retryable: false,
845
+ summary: "Input could not be read or decoded."
846
+ },
847
+ "schema-validation-failed": {
848
+ code: "schema-validation-failed",
849
+ severity: "error",
850
+ posture: "fail-closed-attribution",
851
+ retryable: false,
852
+ summary: "A canonical event failed schema validation and was dropped."
853
+ },
854
+ "provider-unknown": {
855
+ code: "provider-unknown",
856
+ severity: "warning",
857
+ posture: "fail-closed-attribution",
858
+ retryable: false,
859
+ summary: "No adapter recognized the source provider; the input stays unattributed."
860
+ },
861
+ "provider-detection-ambiguous": {
862
+ code: "provider-detection-ambiguous",
863
+ severity: "warning",
864
+ posture: "fail-closed-attribution",
865
+ retryable: false,
866
+ summary: "Multiple adapters claimed the input at equal confidence."
867
+ },
868
+ "provider-adapter-failure": {
869
+ code: "provider-adapter-failure",
870
+ severity: "error",
871
+ posture: "fail-open",
872
+ retryable: false,
873
+ summary: "A provider adapter failed while parsing."
874
+ },
875
+ "identity-conflict": {
876
+ code: "identity-conflict",
877
+ severity: "error",
878
+ posture: "fail-closed-attribution",
879
+ retryable: false,
880
+ summary: "Identity claims disagreed; attribution was declined."
881
+ },
882
+ "identity-incomplete": {
883
+ code: "identity-incomplete",
884
+ severity: "warning",
885
+ posture: "fail-closed-attribution",
886
+ retryable: false,
887
+ summary: "Required identity fields were missing; attribution was declined."
888
+ },
889
+ "usage-invalid": {
890
+ code: "usage-invalid",
891
+ severity: "error",
892
+ posture: "fail-open",
893
+ retryable: false,
894
+ summary: "A usage report violated the canonical usage invariants."
895
+ },
896
+ "state-store-failure": {
897
+ code: "state-store-failure",
898
+ severity: "warning",
899
+ posture: "fail-open",
900
+ retryable: true,
901
+ summary: "State could not be read or written; derived values may be incomplete."
902
+ },
903
+ "telemetry-export-failure": {
904
+ code: "telemetry-export-failure",
905
+ severity: "warning",
906
+ posture: "fail-open",
907
+ retryable: true,
908
+ summary: "The telemetry sink could not accept a batch."
909
+ },
910
+ "privacy-policy-violation": {
911
+ code: "privacy-policy-violation",
912
+ severity: "error",
913
+ posture: "fail-closed-attribution",
914
+ retryable: false,
915
+ summary: "Content violated the resolved privacy policy and was dropped."
916
+ },
917
+ "configuration-invalid": {
918
+ code: "configuration-invalid",
919
+ severity: "error",
920
+ posture: "fail-open",
921
+ retryable: false,
922
+ summary: "Configuration could not be resolved; defaults apply."
923
+ },
924
+ "limit-exceeded": {
925
+ code: "limit-exceeded",
926
+ severity: "warning",
927
+ posture: "fail-open",
928
+ retryable: false,
929
+ summary: "A configured bound was reached and data was dropped."
930
+ },
931
+ "delivery-identifier-unavailable": {
932
+ code: "delivery-identifier-unavailable",
933
+ severity: "warning",
934
+ // Fail-open: the observation is still attributed and exported. Only the
935
+ // at-most-once guarantee is missing, and refusing the telemetry to protect
936
+ // a duplicate count would trade a certain loss for a possible one.
937
+ posture: "fail-open",
938
+ retryable: false,
939
+ summary: "No replay-stable delivery identifier was available; this callback was exported without deduplication."
940
+ },
941
+ "delivery-claim-superseded": {
942
+ code: "delivery-claim-superseded",
943
+ severity: "warning",
944
+ // Fail-open, and specifically *not* silent. A peer reclaimed this callback's
945
+ // claim while this process was still working on it, which means the
946
+ // configured stale window is shorter than this installation's real worst
947
+ // case. Both processes may now have exported the callback, so the
948
+ // at-most-once guarantee did not hold for it — the only honest response is
949
+ // to say so and let the operator raise the window.
950
+ posture: "fail-open",
951
+ retryable: false,
952
+ summary: "A delivery claim was reclaimed by another process before this one committed; the callback may have been exported twice."
953
+ },
954
+ "internal-error": {
955
+ code: "internal-error",
956
+ severity: "error",
957
+ posture: "fail-open",
958
+ retryable: false,
959
+ summary: "An unexpected failure was contained."
960
+ }
961
+ });
962
+ var describeErrorCode = (code) => ERROR_TAXONOMY[code];
963
+ var attributionOutcomeSchema = z2.enum([
964
+ /** Identity resolved; events carry provider and session identity. */
965
+ "attributed",
966
+ /** Identity could not be established safely; nothing was attributed. */
967
+ "declined",
968
+ /** Attribution was attempted and failed unexpectedly. */
969
+ "failed",
970
+ /** Input was recognized but intentionally carried no telemetry. */
971
+ "not-applicable"
972
+ ]);
973
+ var attributionReasonSchema = z2.enum([
974
+ "provider-unknown",
975
+ "provider-detection-ambiguous",
976
+ "identity-conflict",
977
+ "identity-incomplete",
978
+ "adapter-ignored-input",
979
+ "adapter-failure",
980
+ "invalid-input",
981
+ "internal-error"
982
+ ]);
983
+
984
+ // src/errors/index.ts
985
+ var otelHookErrorInfoSchema = z3.strictObject({
986
+ code: otelHookErrorCodeSchema,
987
+ severity: errorSeveritySchema,
988
+ phase: errorPhaseSchema,
989
+ posture: failurePostureSchema,
990
+ retryable: z3.boolean(),
991
+ message: z3.string().min(1).max(512),
992
+ details: attributesSchema.optional(),
993
+ occurredAt: epochMillisSchema.optional()
994
+ });
995
+ var createErrorInfo = (input) => {
996
+ const descriptor = describeErrorCode(input.code);
997
+ const message = input.detail === void 0 ? `${input.code} during ${input.phase}: ${descriptor.summary}` : `${input.code} during ${input.phase}: ${input.detail}`;
998
+ return otelHookErrorInfoSchema.parse({
999
+ code: descriptor.code,
1000
+ severity: descriptor.severity,
1001
+ phase: input.phase,
1002
+ posture: descriptor.posture,
1003
+ retryable: descriptor.retryable,
1004
+ message: message.slice(0, 512),
1005
+ ...input.details === void 0 ? {} : { details: input.details },
1006
+ ...input.occurredAt === void 0 ? {} : { occurredAt: input.occurredAt }
1007
+ });
1008
+ };
1009
+
1010
+ // src/diagnostics/health.ts
1011
+ var createHealthTracker = (subsystem, options = {}) => {
1012
+ const unhealthyThreshold = options.unhealthyAfterConsecutiveFailures ?? 3;
1013
+ let totalAccepted = 0;
1014
+ let totalRejected = 0;
1015
+ let consecutiveFailures = 0;
1016
+ let lastSuccessAt;
1017
+ let lastFailureAt;
1018
+ let lastErrorCode;
1019
+ return {
1020
+ recordSuccess: (count = 1, at) => {
1021
+ totalAccepted += count;
1022
+ consecutiveFailures = 0;
1023
+ if (at !== void 0) {
1024
+ lastSuccessAt = at;
1025
+ }
1026
+ },
1027
+ recordFailure: (code, count = 1, at) => {
1028
+ totalRejected += count;
1029
+ consecutiveFailures += 1;
1030
+ lastErrorCode = code;
1031
+ if (at !== void 0) {
1032
+ lastFailureAt = at;
1033
+ }
1034
+ },
1035
+ snapshot: () => ({
1036
+ subsystem,
1037
+ healthy: consecutiveFailures < unhealthyThreshold,
1038
+ totalAccepted,
1039
+ totalRejected,
1040
+ consecutiveFailures,
1041
+ ...lastSuccessAt === void 0 ? {} : { lastSuccessAt },
1042
+ ...lastFailureAt === void 0 ? {} : { lastFailureAt },
1043
+ ...lastErrorCode === void 0 ? {} : { lastErrorCode }
1044
+ })
1045
+ };
1046
+ };
1047
+
1048
+ // src/telemetry/exporter-resource.ts
1049
+ import { resourceFromAttributes } from "@opentelemetry/resources";
1050
+
1051
+ // src/config/resource-attributes.ts
1052
+ import { z as z5 } from "zod";
1053
+
1054
+ // src/privacy/policy.ts
1055
+ import { z as z4 } from "zod";
1056
+ var contentModeSchema = z4.enum(["omit", "mask", "redact", "raw"]);
1057
+ var CONTENT_MODE_DISCLOSURE = Object.freeze({
1058
+ omit: "omitted",
1059
+ mask: "masked",
1060
+ redact: "redacted",
1061
+ raw: "raw"
1062
+ });
1063
+ var DEFAULT_SECRET_KEY_PATTERNS = Object.freeze([
1064
+ "(^|[._-])(secret|secrets)([._-]|$)",
1065
+ "(^|[._-])(token|tokens)([._-]|$)",
1066
+ "(^|[._-])(password|passwd|pwd)([._-]|$)",
1067
+ "(^|[._-])(credential|credentials)([._-]|$)",
1068
+ "(^|[._-])(api[._-]?key|apikey|access[._-]?key|secret[._-]?key|private[._-]?key)([._-]|$)",
1069
+ "(^|[._-])(authorization|auth[._-]?header|bearer)([._-]|$)",
1070
+ "(^|[._-])(cookie|set[._-]?cookie)([._-]|$)",
1071
+ "(^|[._-])(signature|sig)([._-]|$)"
1072
+ ]);
1073
+ var DEFAULT_SECRET_VALUE_PATTERNS = Object.freeze([
1074
+ "AKIA[0-9A-Z]{16}",
1075
+ "sk-[A-Za-z0-9_-]{16,}",
1076
+ "gh[pousr]_[A-Za-z0-9]{16,}",
1077
+ "xox[abprs]-[A-Za-z0-9-]{10,}",
1078
+ "-----BEGIN[A-Z ]*PRIVATE KEY-----",
1079
+ "eyJ[A-Za-z0-9_-]{10,}\\.[A-Za-z0-9_-]{10,}\\.[A-Za-z0-9_-]{10,}",
1080
+ "(?:Bearer|Basic)\\s+[A-Za-z0-9._~+/=-]{12,}"
1081
+ ]);
1082
+ var privacyLimitsSchema = z4.strictObject({
1083
+ /** Maximum characters of disclosed text per content fact or string value. */
1084
+ maxStringLength: z4.number().int().min(0).max(65536),
1085
+ /** Maximum nesting depth walked when sanitizing structured values. */
1086
+ maxDepth: z4.number().int().min(1).max(32),
1087
+ /** Maximum array entries retained when sanitizing structured values. */
1088
+ maxArrayLength: z4.number().int().min(1).max(4096),
1089
+ /** Maximum canonical events emitted per invocation. */
1090
+ maxEventsPerInvocation: z4.number().int().min(1).max(1e4),
1091
+ /** Maximum object keys retained per level when sanitizing. */
1092
+ maxObjectKeys: z4.number().int().min(1).max(1024)
1093
+ });
1094
+ var privacyPolicySchema = z4.strictObject({
1095
+ contentMode: contentModeSchema,
1096
+ /**
1097
+ * `raw` mode is refused unless this is also true, so a single mistyped
1098
+ * environment variable cannot start exporting prompts.
1099
+ */
1100
+ allowRawContent: z4.boolean(),
1101
+ /**
1102
+ * Salt mixed into every hash. A per-deployment salt makes hashes
1103
+ * non-correlatable across deployments; an empty salt makes them globally
1104
+ * comparable. Both are legitimate; the choice is explicit.
1105
+ */
1106
+ hashSalt: z4.string().max(256),
1107
+ maskCharacter: z4.string().length(1),
1108
+ redactionPlaceholder: z4.string().min(1).max(64),
1109
+ secretKeyPatterns: z4.array(z4.string().min(1)).max(128).readonly(),
1110
+ secretValuePatterns: z4.array(z4.string().min(1)).max(128).readonly(),
1111
+ limits: privacyLimitsSchema
1112
+ });
1113
+ var DEFAULT_PRIVACY_LIMITS = Object.freeze({
1114
+ maxStringLength: 1024,
1115
+ maxDepth: 6,
1116
+ maxArrayLength: 64,
1117
+ maxEventsPerInvocation: 512,
1118
+ maxObjectKeys: 128
1119
+ });
1120
+ var DEFAULT_PRIVACY_POLICY = Object.freeze({
1121
+ contentMode: "omit",
1122
+ allowRawContent: false,
1123
+ hashSalt: "",
1124
+ maskCharacter: "*",
1125
+ redactionPlaceholder: "[redacted]",
1126
+ secretKeyPatterns: DEFAULT_SECRET_KEY_PATTERNS,
1127
+ secretValuePatterns: DEFAULT_SECRET_VALUE_PATTERNS,
1128
+ limits: DEFAULT_PRIVACY_LIMITS
1129
+ });
1130
+
1131
+ // src/config/resource-attributes.ts
1132
+ var MAX_RESOURCE_ATTRIBUTES = 64;
1133
+ var MAX_RESOURCE_ATTRIBUTE_KEY_LENGTH = 255;
1134
+ var MAX_RESOURCE_ATTRIBUTE_VALUE_LENGTH = 2048;
1135
+ var RESOURCE_ATTRIBUTE_KEY_PATTERN = /^[A-Za-z][A-Za-z0-9_./-]*$/;
1136
+ var RESERVED_RESOURCE_ATTRIBUTE_KEYS = Object.freeze([
1137
+ "service.name",
1138
+ "service.namespace"
1139
+ ]);
1140
+ var isReservedResourceAttributeKey = (key) => RESERVED_RESOURCE_ATTRIBUTE_KEYS.includes(key.toLowerCase());
1141
+ var SECRET_KEY_MATCHERS = Object.freeze(
1142
+ DEFAULT_SECRET_KEY_PATTERNS.flatMap((source) => {
1143
+ try {
1144
+ return [new RegExp(source, "i")];
1145
+ } catch {
1146
+ return [];
1147
+ }
1148
+ })
1149
+ );
1150
+ var isSecretResourceAttributeKey = (key) => SECRET_KEY_MATCHERS.some((pattern) => pattern.test(key));
1151
+ var RESOURCE_ATTRIBUTE_KEY_REJECTION_DETAIL = Object.freeze({
1152
+ empty: "resource attribute key is empty",
1153
+ "too-long": `resource attribute key exceeds ${String(MAX_RESOURCE_ATTRIBUTE_KEY_LENGTH)} characters`,
1154
+ malformed: "resource attribute key must start with a letter and use only letters, digits, and `_`, `.`, `-`, `/`",
1155
+ reserved: "service.name and service.namespace are exporter policy (--service-name / OTEL_HOOK_SERVICE_NAME), not resource attributes",
1156
+ "secret-like": "resource attribute key matches a secret-name pattern, so it is never exported"
1157
+ });
1158
+ var checkResourceAttributeKey = (key) => {
1159
+ if (key.length === 0) {
1160
+ return "empty";
1161
+ }
1162
+ if (key.length > MAX_RESOURCE_ATTRIBUTE_KEY_LENGTH) {
1163
+ return "too-long";
1164
+ }
1165
+ if (!RESOURCE_ATTRIBUTE_KEY_PATTERN.test(key)) {
1166
+ return "malformed";
1167
+ }
1168
+ if (isReservedResourceAttributeKey(key)) {
1169
+ return "reserved";
1170
+ }
1171
+ if (isSecretResourceAttributeKey(key)) {
1172
+ return "secret-like";
1173
+ }
1174
+ return void 0;
1175
+ };
1176
+ var resourceAttributeValueSchema = z5.union([
1177
+ z5.string().max(MAX_RESOURCE_ATTRIBUTE_VALUE_LENGTH),
1178
+ z5.number().finite(),
1179
+ z5.boolean()
1180
+ ]);
1181
+ var resourceAttributesSchema = z5.record(z5.string(), resourceAttributeValueSchema).superRefine((value, ctx) => {
1182
+ const keys = Object.keys(value);
1183
+ if (keys.length > MAX_RESOURCE_ATTRIBUTES) {
1184
+ ctx.addIssue({
1185
+ code: "custom",
1186
+ message: `at most ${String(MAX_RESOURCE_ATTRIBUTES)} resource attributes are accepted`
1187
+ });
1188
+ }
1189
+ for (const key of keys) {
1190
+ const rejection = checkResourceAttributeKey(key);
1191
+ if (rejection !== void 0) {
1192
+ ctx.addIssue({
1193
+ code: "custom",
1194
+ path: [key],
1195
+ message: RESOURCE_ATTRIBUTE_KEY_REJECTION_DETAIL[rejection]
1196
+ });
1197
+ }
1198
+ }
1199
+ }).readonly();
1200
+ var EMPTY_RESOURCE_ATTRIBUTES = Object.freeze({});
1201
+ var sanitizeResourceAttributes = (attributes) => {
1202
+ const safe = {};
1203
+ for (const [key, value] of Object.entries(attributes)) {
1204
+ if (checkResourceAttributeKey(key) !== void 0) {
1205
+ continue;
1206
+ }
1207
+ if (Object.keys(safe).length >= MAX_RESOURCE_ATTRIBUTES) {
1208
+ break;
1209
+ }
1210
+ safe[key] = value;
1211
+ }
1212
+ return safe;
1213
+ };
1214
+
1215
+ // src/telemetry/exporter-resource.ts
1216
+ var resourceFromExporterPolicy = (policy) => resourceFromAttributes({
1217
+ ...sanitizeResourceAttributes(policy.resourceAttributes),
1218
+ "service.name": policy.serviceName,
1219
+ ...policy.serviceNamespace === void 0 ? {} : { "service.namespace": policy.serviceNamespace }
1220
+ });
1221
+ var isReplayableValue = (value) => typeof value === "string" && value.length <= MAX_RESOURCE_ATTRIBUTE_VALUE_LENGTH || typeof value === "number" && Number.isFinite(value) || typeof value === "boolean";
1222
+ var replayableServiceIdentity = (value) => typeof value === "string" && value.length > 0 && value.length <= MAX_IDENTIFIER_LENGTH ? value : void 0;
1223
+ var replayResource = (attributes, policy) => {
1224
+ const safe = {};
1225
+ let customCount = 0;
1226
+ for (const [key, value] of Object.entries(attributes)) {
1227
+ if (isReservedResourceAttributeKey(key)) {
1228
+ continue;
1229
+ }
1230
+ if (!isReplayableValue(value)) {
1231
+ continue;
1232
+ }
1233
+ if (checkResourceAttributeKey(key) !== void 0 || customCount >= MAX_RESOURCE_ATTRIBUTES) {
1234
+ continue;
1235
+ }
1236
+ customCount += 1;
1237
+ safe[key] = value;
1238
+ }
1239
+ const recordedName = replayableServiceIdentity(attributes["service.name"]);
1240
+ const recordedNamespace = replayableServiceIdentity(attributes["service.namespace"]);
1241
+ safe["service.name"] = recordedName ?? policy.serviceName;
1242
+ const namespace = recordedNamespace ?? policy.serviceNamespace;
1243
+ if (namespace !== void 0) {
1244
+ safe["service.namespace"] = namespace;
1245
+ }
1246
+ return resourceFromAttributes(safe);
1247
+ };
1248
+
1249
+ // src/telemetry/otlp-sink.ts
1250
+ var chunk = (items, size) => {
1251
+ if (size <= 0 || items.length <= size) {
1252
+ return [items];
1253
+ }
1254
+ const chunks = [];
1255
+ for (let index = 0; index < items.length; index += size) {
1256
+ chunks.push(items.slice(index, index + size));
1257
+ }
1258
+ return chunks;
1259
+ };
1260
+ var serializeSpan = (span) => ({
1261
+ name: span.name,
1262
+ kind: span.kind,
1263
+ traceId: span.spanContext().traceId,
1264
+ spanId: span.spanContext().spanId,
1265
+ ...span.parentSpanContext === void 0 ? {} : { parentSpanId: span.parentSpanContext.spanId },
1266
+ startMillis: span.startTime[0] * 1e3 + Math.round(span.startTime[1] / 1e6),
1267
+ endMillis: span.endTime[0] * 1e3 + Math.round(span.endTime[1] / 1e6),
1268
+ attributes: { ...span.attributes },
1269
+ statusCode: span.status.code,
1270
+ ...span.status.message === void 0 ? {} : { statusMessage: span.status.message }
1271
+ });
1272
+ var deserializeSpan = (serialized, resource, scope) => assembleReadableSpan({
1273
+ name: serialized.name,
1274
+ kind: serialized.kind,
1275
+ startMillis: serialized.startMillis,
1276
+ endMillis: serialized.endMillis,
1277
+ attributes: serialized.attributes,
1278
+ status: { code: serialized.statusCode, ...serialized.statusMessage === void 0 ? {} : { message: serialized.statusMessage } },
1279
+ traceId: serialized.traceId,
1280
+ spanId: serialized.spanId,
1281
+ ...serialized.parentSpanId === void 0 ? {} : { parentSpanId: serialized.parentSpanId },
1282
+ resource,
1283
+ instrumentationScope: scope
1284
+ });
1285
+ var createDisabledSink = () => {
1286
+ const health = createHealthTracker("telemetry-sink");
1287
+ return {
1288
+ emit: (events) => {
1289
+ health.recordSuccess(events.length);
1290
+ return Promise.resolve({ accepted: events.length, rejected: 0, errors: [] });
1291
+ },
1292
+ flush: () => Promise.resolve(),
1293
+ shutdown: () => Promise.resolve(),
1294
+ health: () => health.snapshot(),
1295
+ drainSpool: () => Promise.resolve({ drained: 0, remaining: 0, failed: 0 })
1296
+ };
1297
+ };
1298
+ var createOtlpTraceSink = (options) => {
1299
+ if (!options.exporter.enabled || options.exporter.protocol === "none") {
1300
+ return createDisabledSink();
1301
+ }
1302
+ if (options.exporter.endpoint === void 0) {
1303
+ options.logger?.warn("otlp sink disabled: no endpoint configured", {});
1304
+ return createDisabledSink();
1305
+ }
1306
+ if (options.exporter.protocol !== "http/protobuf") {
1307
+ options.logger?.warn("otlp sink: protocol not supported by this build, falling back to disabled", {
1308
+ "exporter.protocol": options.exporter.protocol
1309
+ });
1310
+ return createDisabledSink();
1311
+ }
1312
+ const scope = options.instrumentationScope ?? DEFAULT_INSTRUMENTATION_SCOPE;
1313
+ const resource = resourceFromExporterPolicy(options.exporter);
1314
+ const health = createHealthTracker("telemetry-sink");
1315
+ const exporter = new OTLPTraceExporter({
1316
+ url: options.exporter.endpoint,
1317
+ headers: { ...options.headers },
1318
+ timeoutMillis: options.exporter.timeoutMillis
1319
+ });
1320
+ let shutdownCompleted = false;
1321
+ const exportSpans = (spans) => new Promise((resolve) => {
1322
+ exporter.export([...spans], (result) => resolve(result));
1323
+ });
1324
+ const toSpoolBatch = (spans) => ({
1325
+ providerId: options.providerId,
1326
+ installationId: options.installationId,
1327
+ resourceAttributes: { ...resource.attributes },
1328
+ instrumentationScope: { name: scope.name, ...scope.version === void 0 ? {} : { version: scope.version } },
1329
+ spans: spans.map(serializeSpan),
1330
+ enqueuedAt: options.clock.now()
1331
+ });
1332
+ const sendSerializedBatch = async (batch) => {
1333
+ const batchResource = replayResource(batch.resourceAttributes, options.exporter);
1334
+ const spans = batch.spans.map((span) => deserializeSpan(span, batchResource, batch.instrumentationScope));
1335
+ const result = await exportSpans(spans);
1336
+ return result.code === ExportResultCode.SUCCESS;
1337
+ };
1338
+ const resolveCorrelations = async (events) => {
1339
+ if (options.correlate === void 0) {
1340
+ return { correlations: [], available: void 0 };
1341
+ }
1342
+ try {
1343
+ return { correlations: await options.correlate(events), available: true };
1344
+ } catch {
1345
+ options.logger?.warn("span correlation unavailable; exporting unpaired spans", {});
1346
+ return { correlations: [], available: false };
1347
+ }
1348
+ };
1349
+ const emit = async (events) => {
1350
+ if (events.length === 0) {
1351
+ return { accepted: 0, rejected: 0, errors: [] };
1352
+ }
1353
+ const resolved = await resolveCorrelations(events);
1354
+ const spans = canonicalEventsToReadableSpans(events, {
1355
+ resource,
1356
+ instrumentationScope: scope,
1357
+ correlations: resolved.correlations,
1358
+ ...resolved.available === void 0 ? {} : { correlationAvailable: resolved.available }
1359
+ });
1360
+ const errors = [];
1361
+ let accepted = 0;
1362
+ let rejected = 0;
1363
+ for (const batch of chunk(spans, options.exporter.maxBatchSize)) {
1364
+ let result;
1365
+ try {
1366
+ result = await exportSpans(batch);
1367
+ } catch (thrown) {
1368
+ result = { code: ExportResultCode.FAILED, error: thrown instanceof Error ? thrown : new Error("export threw") };
1369
+ }
1370
+ if (result.code === ExportResultCode.SUCCESS) {
1371
+ accepted += batch.length;
1372
+ health.recordSuccess(batch.length, options.clock.now());
1373
+ continue;
1374
+ }
1375
+ health.recordFailure("telemetry-export-failure", batch.length, options.clock.now());
1376
+ if (options.spool !== void 0) {
1377
+ const spoolResult = await options.spool.enqueue(toSpoolBatch(batch)).catch(() => ({
1378
+ spooled: false,
1379
+ reason: "capacity-exceeded"
1380
+ }));
1381
+ if (spoolResult.spooled) {
1382
+ accepted += batch.length;
1383
+ continue;
1384
+ }
1385
+ }
1386
+ rejected += batch.length;
1387
+ errors.push(
1388
+ createErrorInfo({
1389
+ code: "telemetry-export-failure",
1390
+ phase: "export",
1391
+ detail: "collector rejected or was unreachable for a span batch",
1392
+ details: { "export.batch_size": batch.length }
1393
+ })
1394
+ );
1395
+ }
1396
+ return { accepted, rejected, errors };
1397
+ };
1398
+ const drainSpool = async (maxBatches) => {
1399
+ if (options.spool === void 0) {
1400
+ return { drained: 0, remaining: 0, failed: 0 };
1401
+ }
1402
+ const result = await options.spool.drain(sendSerializedBatch, { ...maxBatches === void 0 ? {} : { maxBatches } });
1403
+ if (result.drained > 0) {
1404
+ health.recordSuccess(result.drained, options.clock.now());
1405
+ }
1406
+ return result;
1407
+ };
1408
+ const flush = async () => {
1409
+ try {
1410
+ await exporter.forceFlush();
1411
+ } catch {
1412
+ }
1413
+ await drainSpool().catch(() => void 0);
1414
+ };
1415
+ const shutdown = async () => {
1416
+ if (shutdownCompleted) {
1417
+ return;
1418
+ }
1419
+ shutdownCompleted = true;
1420
+ await flush();
1421
+ try {
1422
+ await exporter.shutdown();
1423
+ } catch {
1424
+ }
1425
+ };
1426
+ return {
1427
+ emit,
1428
+ flush,
1429
+ shutdown,
1430
+ health: () => health.snapshot(),
1431
+ drainSpool
1432
+ };
1433
+ };
1434
+
1435
+ // src/telemetry/log-records.ts
1436
+ import { TraceFlags as TraceFlags2 } from "@opentelemetry/api";
1437
+ import { SeverityNumber } from "@opentelemetry/api-logs";
1438
+ import {
1439
+ ATTR_ERROR_TYPE as ATTR_ERROR_TYPE2,
1440
+ ATTR_GEN_AI_OPERATION_NAME as ATTR_GEN_AI_OPERATION_NAME2,
1441
+ ATTR_GEN_AI_REQUEST_MODEL as ATTR_GEN_AI_REQUEST_MODEL2,
1442
+ ATTR_GEN_AI_RESPONSE_MODEL as ATTR_GEN_AI_RESPONSE_MODEL2,
1443
+ ATTR_GEN_AI_SYSTEM as ATTR_GEN_AI_SYSTEM2,
1444
+ ATTR_GEN_AI_TOOL_CALL_ID as ATTR_GEN_AI_TOOL_CALL_ID2,
1445
+ ATTR_GEN_AI_TOOL_NAME as ATTR_GEN_AI_TOOL_NAME2,
1446
+ ATTR_GEN_AI_USAGE_INPUT_TOKENS as ATTR_GEN_AI_USAGE_INPUT_TOKENS2,
1447
+ ATTR_GEN_AI_USAGE_OUTPUT_TOKENS as ATTR_GEN_AI_USAGE_OUTPUT_TOKENS2,
1448
+ ATTR_SESSION_ID as ATTR_SESSION_ID2
1449
+ } from "@opentelemetry/semantic-conventions/incubating";
1450
+ var LOG_MAPPING_VERSION = 1;
1451
+ var LOG_SIGNALS = [
1452
+ "session",
1453
+ "prompt",
1454
+ "response",
1455
+ "reasoning",
1456
+ "tool",
1457
+ "shell",
1458
+ "file-operation",
1459
+ "mcp",
1460
+ "delegation",
1461
+ "compaction",
1462
+ "error"
1463
+ ];
1464
+ var MCP_TOOL_NAME_PATTERN = /^mcp__/i;
1465
+ var MAX_LOG_RECORDS_PER_EVENT = 64;
1466
+ var MAX_LOG_RECORDS_PER_BATCH = 2048;
1467
+ var MAX_LOG_BODY_CHARACTERS = 8192;
1468
+ var ATTR_OTELHOOK_INVOCATION_ID2 = "otelhook.invocation.id";
1469
+ var ATTR_OTELHOOK_PROVIDER_ID2 = "otelhook.provider.id";
1470
+ var ATTR_OTELHOOK_PROVIDER_VERSION2 = "otelhook.provider.version";
1471
+ var ATTR_OTELHOOK_WORKSPACE_ID2 = "otelhook.workspace.id";
1472
+ var ATTR_OTELHOOK_EVENT_TYPE = "otelhook.event.type";
1473
+ var ATTR_OTELHOOK_EVENT_ID = "otelhook.event.id";
1474
+ var ATTR_OTELHOOK_EVENT_SEQUENCE = "otelhook.event.sequence";
1475
+ var ATTR_OTELHOOK_LOG_SIGNAL = "otelhook.log.signal";
1476
+ var ATTR_OTELHOOK_LOG_MAPPING_VERSION = "otelhook.log.mapping_version";
1477
+ var ATTR_OTELHOOK_OUTCOME2 = "otelhook.outcome";
1478
+ var ATTR_OTELHOOK_TOOL_KIND2 = "otelhook.tool.kind";
1479
+ var ATTR_OTELHOOK_TOOL_PERMISSION = "otelhook.tool.permission_decision";
1480
+ var ATTR_OTELHOOK_DELEGATION_DEPTH2 = "otelhook.delegation_depth";
1481
+ var ATTR_OTELHOOK_SUBAGENT_TYPE = "otelhook.subagent.type";
1482
+ var ATTR_OTELHOOK_AGENT_NAME2 = "otelhook.agent.name";
1483
+ var ATTR_OTELHOOK_AGENT_VERSION2 = "otelhook.agent.version";
1484
+ var ATTR_OTELHOOK_SESSION_KIND = "otelhook.session.kind";
1485
+ var ATTR_OTELHOOK_PROMPT_SOURCE = "otelhook.prompt.source";
1486
+ var ATTR_OTELHOOK_PROMPT_TURN_INDEX = "otelhook.prompt.turn_index";
1487
+ var ATTR_OTELHOOK_GENERATION_ID = "otelhook.generation.id";
1488
+ var ATTR_OTELHOOK_STOP_REASON = "otelhook.generation.stop_reason";
1489
+ var ATTR_OTELHOOK_COMPACTION_TRIGGER2 = "otelhook.compaction.trigger";
1490
+ var ATTR_OTELHOOK_CONTEXT_TOKENS_BEFORE = "otelhook.compaction.context_tokens_before";
1491
+ var ATTR_OTELHOOK_CONTEXT_TOKENS_AFTER = "otelhook.compaction.context_tokens_after";
1492
+ var ATTR_OTELHOOK_DROPPED_MESSAGES = "otelhook.compaction.dropped_message_count";
1493
+ var ATTR_OTELHOOK_ERROR_PHASE = "otelhook.error.phase";
1494
+ var ATTR_OTELHOOK_ERROR_RETRYABLE = "otelhook.error.retryable";
1495
+ var ATTR_OTELHOOK_ERROR_SEVERITY = "otelhook.error.severity";
1496
+ var ATTR_CONTENT_KIND = "otelhook.content.kind";
1497
+ var ATTR_CONTENT_ROLE = "otelhook.content.role";
1498
+ var ATTR_CONTENT_DISCLOSURE = "otelhook.content.disclosure";
1499
+ var ATTR_CONTENT_CHARACTER_LENGTH = "otelhook.content.character_length";
1500
+ var ATTR_CONTENT_BYTE_LENGTH = "otelhook.content.byte_length";
1501
+ var ATTR_CONTENT_HASH = "otelhook.content.hash";
1502
+ var ATTR_CONTENT_TRUNCATED = "otelhook.content.truncated";
1503
+ var ATTR_CONTENT_SECRETS_REDACTED = "otelhook.content.secrets_redacted";
1504
+ var ATTR_CONTENT_LABEL = "otelhook.content.label";
1505
+ var ATTR_CONTENT_WITHHELD = "otelhook.content.withheld";
1506
+ var ATTR_CONTENT_BODY_TRUNCATED = "otelhook.content.body_truncated";
1507
+ var NO_LOG_CONTENT = Object.freeze({
1508
+ includeContent: false,
1509
+ allowRawContent: false
1510
+ });
1511
+ var codePointLength = (value) => [...value].length;
1512
+ var sliceCodePoints = (value, max) => {
1513
+ let result = "";
1514
+ let count = 0;
1515
+ for (const char of value) {
1516
+ if (count >= max) {
1517
+ break;
1518
+ }
1519
+ result += char;
1520
+ count += 1;
1521
+ }
1522
+ return result;
1523
+ };
1524
+ var logSignalOf = (event, factKind) => {
1525
+ switch (event.type) {
1526
+ case "session.start":
1527
+ case "session.end":
1528
+ return "session";
1529
+ case "prompt.submitted":
1530
+ return "prompt";
1531
+ case "generation.start":
1532
+ return factKind === "reasoning" ? "reasoning" : "prompt";
1533
+ case "generation.end":
1534
+ return factKind === "reasoning" ? "reasoning" : "response";
1535
+ case "subagent.start":
1536
+ case "subagent.end":
1537
+ return "delegation";
1538
+ case "compaction.performed":
1539
+ return "compaction";
1540
+ case "error.raised":
1541
+ return "error";
1542
+ case "tool.start":
1543
+ return toolSignal(event.toolName, event.toolKind);
1544
+ case "tool.end":
1545
+ return toolSignal(event.toolName, void 0);
1546
+ }
1547
+ };
1548
+ var toolSignal = (toolName, toolKind) => {
1549
+ if (MCP_TOOL_NAME_PATTERN.test(toolName)) {
1550
+ return "mcp";
1551
+ }
1552
+ switch (toolKind) {
1553
+ case "execute":
1554
+ return "shell";
1555
+ case "read":
1556
+ case "write":
1557
+ return "file-operation";
1558
+ case "delegate":
1559
+ return "delegation";
1560
+ default:
1561
+ return "tool";
1562
+ }
1563
+ };
1564
+ var logSignalsForLifecycleEvents = (lifecycleEvents) => {
1565
+ const signals = /* @__PURE__ */ new Set();
1566
+ const add = (...values) => {
1567
+ for (const value of values) {
1568
+ signals.add(value);
1569
+ }
1570
+ };
1571
+ for (const type of lifecycleEvents) {
1572
+ switch (type) {
1573
+ case "session.start":
1574
+ case "session.end":
1575
+ add("session");
1576
+ break;
1577
+ case "prompt.submitted":
1578
+ add("prompt");
1579
+ break;
1580
+ case "generation.start":
1581
+ add("prompt");
1582
+ break;
1583
+ case "generation.end":
1584
+ add("response", "reasoning");
1585
+ break;
1586
+ case "tool.start":
1587
+ case "tool.end":
1588
+ add("tool", "shell", "file-operation", "mcp", "delegation");
1589
+ break;
1590
+ case "subagent.start":
1591
+ case "subagent.end":
1592
+ add("delegation");
1593
+ break;
1594
+ case "compaction.performed":
1595
+ add("compaction");
1596
+ break;
1597
+ case "error.raised":
1598
+ add("error");
1599
+ break;
1600
+ }
1601
+ }
1602
+ return LOG_SIGNALS.filter((signal) => signals.has(signal));
1603
+ };
1604
+ var severityFor = (event) => {
1605
+ switch (event.type) {
1606
+ case "error.raised":
1607
+ return event.severity === "error" ? SeverityNumber.ERROR : SeverityNumber.WARN;
1608
+ case "session.end":
1609
+ return event.reason === "error" || event.reason === "timeout" ? SeverityNumber.ERROR : event.reason === "aborted" ? SeverityNumber.WARN : SeverityNumber.INFO;
1610
+ case "generation.end":
1611
+ case "tool.end":
1612
+ case "subagent.end":
1613
+ return event.outcome === "error" || event.outcome === "timeout" ? SeverityNumber.ERROR : event.outcome === "denied" || event.outcome === "cancelled" ? SeverityNumber.WARN : SeverityNumber.INFO;
1614
+ default:
1615
+ return SeverityNumber.INFO;
1616
+ }
1617
+ };
1618
+ var SEVERITY_TEXT = Object.freeze({
1619
+ [SeverityNumber.INFO]: "INFO",
1620
+ [SeverityNumber.WARN]: "WARN",
1621
+ [SeverityNumber.ERROR]: "ERROR"
1622
+ });
1623
+ var identityAttributes2 = (event) => ({
1624
+ [ATTR_SESSION_ID2]: event.sessionId,
1625
+ [ATTR_OTELHOOK_INVOCATION_ID2]: event.invocationId,
1626
+ [ATTR_OTELHOOK_PROVIDER_ID2]: event.provenance.providerId,
1627
+ ...event.provenance.providerVersion === void 0 ? {} : { [ATTR_OTELHOOK_PROVIDER_VERSION2]: event.provenance.providerVersion },
1628
+ [ATTR_OTELHOOK_WORKSPACE_ID2]: event.workspace.workspaceId
1629
+ });
1630
+ var eventAttributes = (event) => {
1631
+ switch (event.type) {
1632
+ case "session.start":
1633
+ return {
1634
+ [ATTR_OTELHOOK_SESSION_KIND]: event.sessionKind,
1635
+ ...event.agentName === void 0 ? {} : { [ATTR_OTELHOOK_AGENT_NAME2]: event.agentName },
1636
+ ...event.agentVersion === void 0 ? {} : { [ATTR_OTELHOOK_AGENT_VERSION2]: event.agentVersion },
1637
+ ...event.model === void 0 ? {} : { [ATTR_GEN_AI_REQUEST_MODEL2]: event.model.modelId }
1638
+ };
1639
+ case "session.end":
1640
+ return {
1641
+ [ATTR_OTELHOOK_OUTCOME2]: event.reason,
1642
+ ...usageAttributes2(event.usage)
1643
+ };
1644
+ case "prompt.submitted":
1645
+ return {
1646
+ [ATTR_OTELHOOK_PROMPT_SOURCE]: event.promptSource,
1647
+ ...event.turnIndex === void 0 ? {} : { [ATTR_OTELHOOK_PROMPT_TURN_INDEX]: event.turnIndex }
1648
+ };
1649
+ case "generation.start":
1650
+ return {
1651
+ [ATTR_GEN_AI_OPERATION_NAME2]: "chat",
1652
+ [ATTR_OTELHOOK_GENERATION_ID]: event.generationId,
1653
+ [ATTR_GEN_AI_REQUEST_MODEL2]: event.model.modelId,
1654
+ ...event.model.vendor === void 0 ? {} : { [ATTR_GEN_AI_SYSTEM2]: event.model.vendor }
1655
+ };
1656
+ case "generation.end":
1657
+ return {
1658
+ [ATTR_GEN_AI_OPERATION_NAME2]: "chat",
1659
+ [ATTR_OTELHOOK_GENERATION_ID]: event.generationId,
1660
+ [ATTR_GEN_AI_RESPONSE_MODEL2]: event.model.modelId,
1661
+ ...event.model.vendor === void 0 ? {} : { [ATTR_GEN_AI_SYSTEM2]: event.model.vendor },
1662
+ [ATTR_OTELHOOK_OUTCOME2]: event.outcome,
1663
+ ...event.stopReason === void 0 ? {} : { [ATTR_OTELHOOK_STOP_REASON]: event.stopReason },
1664
+ ...usageAttributes2(event.usage)
1665
+ };
1666
+ case "tool.start":
1667
+ return {
1668
+ [ATTR_GEN_AI_TOOL_NAME2]: event.toolName,
1669
+ [ATTR_GEN_AI_TOOL_CALL_ID2]: event.toolCallId,
1670
+ [ATTR_OTELHOOK_TOOL_KIND2]: event.toolKind,
1671
+ ...event.generationId === void 0 ? {} : { [ATTR_OTELHOOK_GENERATION_ID]: event.generationId }
1672
+ };
1673
+ case "tool.end":
1674
+ return {
1675
+ [ATTR_GEN_AI_TOOL_NAME2]: event.toolName,
1676
+ [ATTR_GEN_AI_TOOL_CALL_ID2]: event.toolCallId,
1677
+ [ATTR_OTELHOOK_OUTCOME2]: event.outcome,
1678
+ ...event.permissionDecision === void 0 ? {} : { [ATTR_OTELHOOK_TOOL_PERMISSION]: event.permissionDecision }
1679
+ };
1680
+ case "subagent.start":
1681
+ return {
1682
+ [ATTR_OTELHOOK_DELEGATION_DEPTH2]: event.delegationDepth,
1683
+ ...event.subagentType === void 0 ? {} : { [ATTR_OTELHOOK_SUBAGENT_TYPE]: event.subagentType },
1684
+ ...event.model === void 0 ? {} : { [ATTR_GEN_AI_REQUEST_MODEL2]: event.model.modelId }
1685
+ };
1686
+ case "subagent.end":
1687
+ return {
1688
+ [ATTR_OTELHOOK_OUTCOME2]: event.outcome,
1689
+ ...usageAttributes2(event.usage)
1690
+ };
1691
+ case "compaction.performed":
1692
+ return {
1693
+ [ATTR_OTELHOOK_COMPACTION_TRIGGER2]: event.trigger,
1694
+ ...event.contextTokensBefore === void 0 ? {} : { [ATTR_OTELHOOK_CONTEXT_TOKENS_BEFORE]: event.contextTokensBefore },
1695
+ ...event.contextTokensAfter === void 0 ? {} : { [ATTR_OTELHOOK_CONTEXT_TOKENS_AFTER]: event.contextTokensAfter },
1696
+ ...event.droppedMessageCount === void 0 ? {} : { [ATTR_OTELHOOK_DROPPED_MESSAGES]: event.droppedMessageCount },
1697
+ ...usageAttributes2(event.usage)
1698
+ };
1699
+ case "error.raised":
1700
+ return {
1701
+ [ATTR_ERROR_TYPE2]: event.errorCode,
1702
+ [ATTR_OTELHOOK_ERROR_PHASE]: event.phase,
1703
+ [ATTR_OTELHOOK_ERROR_RETRYABLE]: event.retryable,
1704
+ [ATTR_OTELHOOK_ERROR_SEVERITY]: event.severity
1705
+ };
1706
+ }
1707
+ };
1708
+ var usageAttributes2 = (usage) => usage === void 0 ? {} : {
1709
+ [ATTR_GEN_AI_USAGE_INPUT_TOKENS2]: usage.inputTokens,
1710
+ [ATTR_GEN_AI_USAGE_OUTPUT_TOKENS2]: usage.outputTokens
1711
+ };
1712
+ var contentFactsOf = (event) => {
1713
+ switch (event.type) {
1714
+ case "prompt.submitted":
1715
+ return event.content === void 0 ? [] : [event.content];
1716
+ case "generation.start":
1717
+ return event.inputContent ?? [];
1718
+ case "generation.end":
1719
+ return event.outputContent ?? [];
1720
+ case "tool.start":
1721
+ return event.input === void 0 ? [] : [event.input];
1722
+ case "tool.end":
1723
+ return event.output === void 0 ? [] : [event.output];
1724
+ case "error.raised":
1725
+ return event.message === void 0 ? [] : [event.message];
1726
+ default:
1727
+ return [];
1728
+ }
1729
+ };
1730
+ var discloseBody = (fact, policy) => {
1731
+ if (fact.text === void 0) {
1732
+ return { withheld: "privacy-policy" };
1733
+ }
1734
+ if (!policy.includeContent) {
1735
+ return { withheld: "logs-content-disabled" };
1736
+ }
1737
+ if (fact.disclosure === "raw" && !policy.allowRawContent) {
1738
+ return { withheld: "raw-not-permitted" };
1739
+ }
1740
+ const length = codePointLength(fact.text);
1741
+ return length <= MAX_LOG_BODY_CHARACTERS ? { text: fact.text, truncated: false } : { text: sliceCodePoints(fact.text, MAX_LOG_BODY_CHARACTERS), truncated: true };
1742
+ };
1743
+ var contentAttributes = (fact, body) => ({
1744
+ [ATTR_CONTENT_KIND]: fact.kind,
1745
+ ...fact.role === void 0 ? {} : { [ATTR_CONTENT_ROLE]: fact.role },
1746
+ [ATTR_CONTENT_DISCLOSURE]: fact.disclosure,
1747
+ [ATTR_CONTENT_CHARACTER_LENGTH]: fact.characterLength,
1748
+ [ATTR_CONTENT_BYTE_LENGTH]: fact.byteLength,
1749
+ [ATTR_CONTENT_HASH]: fact.contentHash,
1750
+ [ATTR_CONTENT_TRUNCATED]: fact.truncated,
1751
+ [ATTR_CONTENT_SECRETS_REDACTED]: fact.secretsRedacted,
1752
+ ...fact.label === void 0 ? {} : { [ATTR_CONTENT_LABEL]: fact.label },
1753
+ ..."withheld" in body ? { [ATTR_CONTENT_WITHHELD]: body.withheld } : { [ATTR_CONTENT_BODY_TRUNCATED]: body.truncated }
1754
+ });
1755
+ var buildRecord = (input) => {
1756
+ const severityNumber = severityFor(input.event);
1757
+ const hrTime2 = millisToHrTime(input.event.occurredAt);
1758
+ return {
1759
+ hrTime: hrTime2,
1760
+ // A hook observes an event that already happened, and this mapping is pure —
1761
+ // there is no clock here to read a real observation time from. Reporting the
1762
+ // occurrence time for both is the honest answer: it says "this is when it
1763
+ // happened" twice rather than inventing a second, wrong timestamp.
1764
+ hrTimeObserved: hrTime2,
1765
+ spanContext: input.spanContext,
1766
+ severityNumber,
1767
+ severityText: SEVERITY_TEXT[severityNumber] ?? "INFO",
1768
+ ...input.body === void 0 ? {} : { body: input.body },
1769
+ eventName: `otelhook.${input.event.type}`,
1770
+ resource: input.resource,
1771
+ instrumentationScope: input.scope,
1772
+ attributes: {
1773
+ ...identityAttributes2(input.event),
1774
+ [ATTR_OTELHOOK_EVENT_TYPE]: input.event.type,
1775
+ [ATTR_OTELHOOK_EVENT_ID]: input.event.eventId,
1776
+ [ATTR_OTELHOOK_EVENT_SEQUENCE]: input.event.sequence,
1777
+ [ATTR_OTELHOOK_LOG_SIGNAL]: input.signal,
1778
+ [ATTR_OTELHOOK_LOG_MAPPING_VERSION]: LOG_MAPPING_VERSION,
1779
+ ...input.attributes
1780
+ },
1781
+ droppedAttributesCount: 0
1782
+ };
1783
+ };
1784
+ var canonicalEventsToLogRecords = (events, options) => {
1785
+ const scope = options.instrumentationScope ?? DEFAULT_INSTRUMENTATION_SCOPE;
1786
+ const content = options.content ?? NO_LOG_CONTENT;
1787
+ const identities = canonicalEventTraceIdentities(events, {
1788
+ ...options.correlations === void 0 ? {} : { correlations: options.correlations },
1789
+ ...options.correlationAvailable === void 0 ? {} : { correlationAvailable: options.correlationAvailable }
1790
+ });
1791
+ const records = [];
1792
+ let droppedFacts = 0;
1793
+ for (const event of events) {
1794
+ const identity = identities.get(event.eventId);
1795
+ if (identity === void 0) {
1796
+ continue;
1797
+ }
1798
+ const spanContext = {
1799
+ traceId: identity.traceId,
1800
+ spanId: identity.spanId,
1801
+ traceFlags: TraceFlags2.SAMPLED,
1802
+ isRemote: false
1803
+ };
1804
+ const shared = eventAttributes(event);
1805
+ const facts = contentFactsOf(event);
1806
+ if (facts.length === 0) {
1807
+ if (records.length >= MAX_LOG_RECORDS_PER_BATCH) {
1808
+ droppedFacts += 1;
1809
+ continue;
1810
+ }
1811
+ records.push(
1812
+ buildRecord({
1813
+ event,
1814
+ signal: logSignalOf(event),
1815
+ attributes: shared,
1816
+ spanContext,
1817
+ resource: options.resource,
1818
+ scope
1819
+ })
1820
+ );
1821
+ continue;
1822
+ }
1823
+ let perEvent = 0;
1824
+ for (const fact of facts) {
1825
+ if (perEvent >= MAX_LOG_RECORDS_PER_EVENT || records.length >= MAX_LOG_RECORDS_PER_BATCH) {
1826
+ droppedFacts += 1;
1827
+ continue;
1828
+ }
1829
+ perEvent += 1;
1830
+ const body = discloseBody(fact, content);
1831
+ records.push(
1832
+ buildRecord({
1833
+ event,
1834
+ signal: logSignalOf(event, fact.kind),
1835
+ attributes: { ...shared, ...contentAttributes(fact, body) },
1836
+ ..."withheld" in body ? {} : { body: body.text },
1837
+ spanContext,
1838
+ resource: options.resource,
1839
+ scope
1840
+ })
1841
+ );
1842
+ }
1843
+ }
1844
+ return { records, droppedFacts };
1845
+ };
1846
+
1847
+ // src/telemetry/durable-log-spool.ts
1848
+ var MAX_SPOOLED_LOG_RECORDS_PER_BATCH = 4096;
1849
+ var MAX_SPOOLED_LOG_STRING_LENGTH = 8192;
1850
+ var MAX_SPOOLED_LOG_BODY_LENGTH = 8192;
1851
+ var MAX_SPOOLED_ATTRIBUTES_PER_RECORD = 256;
1852
+ var TRACE_ID_PATTERN2 = /^[0-9a-f]{32}$/;
1853
+ var SPAN_ID_PATTERN2 = /^[0-9a-f]{16}$/;
1854
+ var isFiniteNonNegative2 = (value) => typeof value === "number" && Number.isFinite(value) && value >= 0;
1855
+ var isBoundedString2 = (value, maxLength = MAX_SPOOLED_LOG_STRING_LENGTH) => typeof value === "string" && value.length > 0 && value.length <= maxLength;
1856
+ var isPlainObject2 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
1857
+ var isReplayableAttributeValue = (value) => {
1858
+ if (Array.isArray(value)) {
1859
+ return value.every(
1860
+ (item) => typeof item === "string" && item.length <= MAX_SPOOLED_LOG_STRING_LENGTH || typeof item === "number" && Number.isFinite(item) || typeof item === "boolean" || item === null
1861
+ );
1862
+ }
1863
+ return typeof value === "string" && value.length <= MAX_SPOOLED_LOG_STRING_LENGTH || typeof value === "number" && Number.isFinite(value) || typeof value === "boolean" || value === void 0;
1864
+ };
1865
+ var isReplayableLogRecord = (value) => {
1866
+ if (!isPlainObject2(value)) {
1867
+ return false;
1868
+ }
1869
+ if (!isBoundedString2(value.eventName)) {
1870
+ return false;
1871
+ }
1872
+ if (!isFiniteNonNegative2(value.severityNumber)) {
1873
+ return false;
1874
+ }
1875
+ if (value.severityText !== void 0 && typeof value.severityText !== "string") {
1876
+ return false;
1877
+ }
1878
+ if (value.body !== void 0 && (typeof value.body !== "string" || value.body.length > MAX_SPOOLED_LOG_BODY_LENGTH)) {
1879
+ return false;
1880
+ }
1881
+ if (!isFiniteNonNegative2(value.timeMillis) || !isFiniteNonNegative2(value.observedTimeMillis)) {
1882
+ return false;
1883
+ }
1884
+ const hasTrace = value.traceId !== void 0;
1885
+ const hasSpan = value.spanId !== void 0;
1886
+ if (hasTrace !== hasSpan) {
1887
+ return false;
1888
+ }
1889
+ if (hasTrace && (typeof value.traceId !== "string" || !TRACE_ID_PATTERN2.test(value.traceId))) {
1890
+ return false;
1891
+ }
1892
+ if (hasSpan && (typeof value.spanId !== "string" || !SPAN_ID_PATTERN2.test(value.spanId))) {
1893
+ return false;
1894
+ }
1895
+ if (!isPlainObject2(value.attributes)) {
1896
+ return false;
1897
+ }
1898
+ const entries = Object.entries(value.attributes);
1899
+ if (entries.length > MAX_SPOOLED_ATTRIBUTES_PER_RECORD) {
1900
+ return false;
1901
+ }
1902
+ return entries.every(([, attribute]) => isReplayableAttributeValue(attribute));
1903
+ };
1904
+ var validateLogSpoolBatch = (value, identity) => {
1905
+ if (!isPlainObject2(value)) {
1906
+ return { rejection: "not-an-object" };
1907
+ }
1908
+ if (value.providerId !== identity.providerId || value.installationId !== identity.installationId) {
1909
+ return { rejection: "identity-mismatch" };
1910
+ }
1911
+ if (!isPlainObject2(value.resourceAttributes)) {
1912
+ return { rejection: "resource-attributes-invalid" };
1913
+ }
1914
+ if (!isPlainObject2(value.instrumentationScope) || !isBoundedString2(value.instrumentationScope.name)) {
1915
+ return { rejection: "instrumentation-scope-invalid" };
1916
+ }
1917
+ if (value.instrumentationScope.version !== void 0 && typeof value.instrumentationScope.version !== "string") {
1918
+ return { rejection: "instrumentation-scope-invalid" };
1919
+ }
1920
+ if (!Array.isArray(value.records) || value.records.length === 0) {
1921
+ return { rejection: "records-invalid" };
1922
+ }
1923
+ if (value.records.length > MAX_SPOOLED_LOG_RECORDS_PER_BATCH) {
1924
+ return { rejection: "records-invalid" };
1925
+ }
1926
+ if (!value.records.every(isReplayableLogRecord)) {
1927
+ return { rejection: "record-field-invalid" };
1928
+ }
1929
+ if (!isFiniteNonNegative2(value.enqueuedAt)) {
1930
+ return { rejection: "not-an-object" };
1931
+ }
1932
+ return { batch: value };
1933
+ };
1934
+ var DEFAULT_MAX_LOG_SPOOL_FILES = 500;
1935
+ var createFileDurableLogSpool = (options) => createSpoolQueue({
1936
+ rootDir: options.rootDir,
1937
+ providerId: options.providerId,
1938
+ installationId: options.installationId,
1939
+ clock: options.clock,
1940
+ ...options.logger === void 0 ? {} : { logger: options.logger },
1941
+ maxFiles: options.maxSpoolFiles ?? DEFAULT_MAX_LOG_SPOOL_FILES,
1942
+ queueName: "spool-logs",
1943
+ validate: validateLogSpoolBatch
1944
+ });
1945
+
1946
+ // src/telemetry/otlp-log-sink.ts
1947
+ import { TraceFlags as TraceFlags3 } from "@opentelemetry/api";
1948
+ import { OTLPLogExporter } from "@opentelemetry/exporter-logs-otlp-proto";
1949
+ var OTLP_TRACES_PATH = "/v1/traces";
1950
+ var OTLP_LOGS_PATH = "/v1/logs";
1951
+ var withoutTrailingSlashes = (value) => {
1952
+ let end = value.length;
1953
+ while (end > 0 && value.charCodeAt(end - 1) === 47) {
1954
+ end -= 1;
1955
+ }
1956
+ return value.slice(0, end);
1957
+ };
1958
+ var resolveLogsEndpoint = (exporter) => {
1959
+ if (exporter.logs.endpoint !== void 0) {
1960
+ return { endpoint: exporter.logs.endpoint, derived: false };
1961
+ }
1962
+ if (exporter.endpoint === void 0) {
1963
+ return { unresolvable: "no-endpoint" };
1964
+ }
1965
+ const trimmed = withoutTrailingSlashes(exporter.endpoint);
1966
+ if (trimmed.endsWith(OTLP_LOGS_PATH)) {
1967
+ return { endpoint: trimmed, derived: true };
1968
+ }
1969
+ if (trimmed.endsWith(OTLP_TRACES_PATH)) {
1970
+ return {
1971
+ endpoint: `${trimmed.slice(0, trimmed.length - OTLP_TRACES_PATH.length)}${OTLP_LOGS_PATH}`,
1972
+ derived: true
1973
+ };
1974
+ }
1975
+ return { endpoint: `${trimmed}${OTLP_LOGS_PATH}`, derived: true };
1976
+ };
1977
+ var toSpoolAttributes = (attributes) => {
1978
+ const safe = {};
1979
+ for (const [key, value] of Object.entries(attributes)) {
1980
+ if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
1981
+ safe[key] = value;
1982
+ continue;
1983
+ }
1984
+ if (Array.isArray(value) && value.every((item) => typeof item === "string")) {
1985
+ safe[key] = value;
1986
+ }
1987
+ }
1988
+ return safe;
1989
+ };
1990
+ var serializeRecord = (record) => {
1991
+ const context = record.spanContext;
1992
+ return {
1993
+ eventName: record.eventName ?? "otelhook.record",
1994
+ severityNumber: record.severityNumber ?? 0,
1995
+ ...record.severityText === void 0 ? {} : { severityText: record.severityText },
1996
+ ...typeof record.body === "string" ? { body: record.body } : {},
1997
+ timeMillis: record.hrTime[0] * 1e3 + Math.round(record.hrTime[1] / 1e6),
1998
+ observedTimeMillis: record.hrTimeObserved[0] * 1e3 + Math.round(record.hrTimeObserved[1] / 1e6),
1999
+ ...context === void 0 ? {} : { traceId: context.traceId, spanId: context.spanId },
2000
+ attributes: toSpoolAttributes(record.attributes)
2001
+ };
2002
+ };
2003
+ var deserializeRecord = (serialized, resource, scope) => {
2004
+ const spanContext = serialized.traceId === void 0 || serialized.spanId === void 0 ? void 0 : {
2005
+ traceId: serialized.traceId,
2006
+ spanId: serialized.spanId,
2007
+ traceFlags: TraceFlags3.SAMPLED,
2008
+ isRemote: false
2009
+ };
2010
+ return {
2011
+ hrTime: millisToHrTime(serialized.timeMillis),
2012
+ hrTimeObserved: millisToHrTime(serialized.observedTimeMillis),
2013
+ ...spanContext === void 0 ? {} : { spanContext },
2014
+ severityNumber: serialized.severityNumber,
2015
+ ...serialized.severityText === void 0 ? {} : { severityText: serialized.severityText },
2016
+ ...serialized.body === void 0 ? {} : { body: serialized.body },
2017
+ eventName: serialized.eventName,
2018
+ resource,
2019
+ instrumentationScope: scope,
2020
+ attributes: serialized.attributes,
2021
+ droppedAttributesCount: 0
2022
+ };
2023
+ };
2024
+ var chunk2 = (items, size) => {
2025
+ if (size <= 0 || items.length <= size) {
2026
+ return [items];
2027
+ }
2028
+ const chunks = [];
2029
+ for (let index = 0; index < items.length; index += size) {
2030
+ chunks.push(items.slice(index, index + size));
2031
+ }
2032
+ return chunks;
2033
+ };
2034
+ var createDisabledSink2 = () => {
2035
+ const health = createHealthTracker("telemetry-log-sink");
2036
+ return {
2037
+ emit: (events) => {
2038
+ health.recordSuccess(events.length);
2039
+ return Promise.resolve({ accepted: 0, rejected: 0, errors: [] });
2040
+ },
2041
+ flush: () => Promise.resolve(),
2042
+ shutdown: () => Promise.resolve(),
2043
+ health: () => health.snapshot(),
2044
+ drainSpool: () => Promise.resolve({ drained: 0, remaining: 0, failed: 0 })
2045
+ };
2046
+ };
2047
+ var describeLogsDeliverability = (exporter) => {
2048
+ if (!exporter.logs.enabled) {
2049
+ return { status: "disabled", reason: "logs-disabled" };
2050
+ }
2051
+ if (!exporter.enabled) {
2052
+ return { status: "disabled", reason: "exporter-disabled" };
2053
+ }
2054
+ if (exporter.protocol === "none") {
2055
+ return { status: "disabled", reason: "protocol-none" };
2056
+ }
2057
+ if (exporter.protocol !== "http/protobuf") {
2058
+ return { status: "disabled", reason: "protocol-unsupported" };
2059
+ }
2060
+ const resolved = resolveLogsEndpoint(exporter);
2061
+ if ("unresolvable" in resolved) {
2062
+ return { status: "disabled", reason: "no-endpoint" };
2063
+ }
2064
+ return { status: "configured", endpoint: resolved.endpoint, derivedEndpoint: resolved.derived };
2065
+ };
2066
+ var DISABLED_DETAIL = Object.freeze({
2067
+ "logs-disabled": "otlp log sink disabled: exporter.logs.enabled is false",
2068
+ "exporter-disabled": "otlp log sink disabled: the exporter is disabled",
2069
+ "protocol-none": "otlp log sink disabled: protocol is none",
2070
+ "protocol-unsupported": "otlp log sink disabled: protocol not supported by this build, falling back to disabled",
2071
+ "no-endpoint": "otlp log sink disabled: no logs endpoint configured and none could be derived"
2072
+ });
2073
+ var createOtlpLogSink = (options) => {
2074
+ const deliverability = describeLogsDeliverability(options.exporter);
2075
+ if (deliverability.status === "disabled") {
2076
+ if (deliverability.reason !== "logs-disabled") {
2077
+ options.logger?.warn(DISABLED_DETAIL[deliverability.reason], {
2078
+ "exporter.protocol": options.exporter.protocol
2079
+ });
2080
+ }
2081
+ return createDisabledSink2();
2082
+ }
2083
+ const scope = options.instrumentationScope ?? DEFAULT_INSTRUMENTATION_SCOPE;
2084
+ const resource = resourceFromExporterPolicy(options.exporter);
2085
+ const content = options.content ?? NO_LOG_CONTENT;
2086
+ const health = createHealthTracker("telemetry-log-sink");
2087
+ const exporter = new OTLPLogExporter({
2088
+ url: deliverability.endpoint,
2089
+ headers: { ...options.headers },
2090
+ timeoutMillis: options.exporter.timeoutMillis
2091
+ });
2092
+ let shutdownCompleted = false;
2093
+ const exportRecords = (records) => new Promise((resolve) => {
2094
+ exporter.export([...records], (result) => resolve(result));
2095
+ });
2096
+ const toSpoolBatch = (records) => ({
2097
+ providerId: options.providerId,
2098
+ installationId: options.installationId,
2099
+ resourceAttributes: { ...resource.attributes },
2100
+ instrumentationScope: {
2101
+ name: scope.name,
2102
+ ...scope.version === void 0 ? {} : { version: scope.version }
2103
+ },
2104
+ records: records.map(serializeRecord),
2105
+ enqueuedAt: options.clock.now()
2106
+ });
2107
+ const sendSerializedBatch = async (batch) => {
2108
+ const batchResource = replayResource(batch.resourceAttributes, options.exporter);
2109
+ const records = batch.records.map(
2110
+ (record) => deserializeRecord(record, batchResource, batch.instrumentationScope)
2111
+ );
2112
+ const result = await exportRecords(records);
2113
+ return result.code === ExportResultCode.SUCCESS;
2114
+ };
2115
+ const resolveCorrelations = async (events) => {
2116
+ if (options.correlate === void 0) {
2117
+ return { correlations: [], available: void 0 };
2118
+ }
2119
+ try {
2120
+ return { correlations: await options.correlate(events), available: true };
2121
+ } catch {
2122
+ options.logger?.warn("span correlation unavailable; exporting uncorrelated log records", {});
2123
+ return { correlations: [], available: false };
2124
+ }
2125
+ };
2126
+ const emit = async (events) => {
2127
+ if (events.length === 0) {
2128
+ return { accepted: 0, rejected: 0, errors: [] };
2129
+ }
2130
+ const resolved = await resolveCorrelations(events);
2131
+ const mapped = canonicalEventsToLogRecords(events, {
2132
+ resource,
2133
+ instrumentationScope: scope,
2134
+ content,
2135
+ correlations: resolved.correlations,
2136
+ ...resolved.available === void 0 ? {} : { correlationAvailable: resolved.available }
2137
+ });
2138
+ if (mapped.droppedFacts > 0) {
2139
+ options.logger?.warn("log records dropped: batch or per-event bound reached", {
2140
+ "logs.dropped_facts": mapped.droppedFacts
2141
+ });
2142
+ }
2143
+ const errors = [];
2144
+ let accepted = 0;
2145
+ let rejected = 0;
2146
+ for (const batch of chunk2(mapped.records, options.exporter.logs.maxBatchSize)) {
2147
+ if (batch.length === 0) {
2148
+ continue;
2149
+ }
2150
+ let result;
2151
+ try {
2152
+ result = await exportRecords(batch);
2153
+ } catch (thrown) {
2154
+ result = {
2155
+ code: ExportResultCode.FAILED,
2156
+ error: thrown instanceof Error ? thrown : new Error("export threw")
2157
+ };
2158
+ }
2159
+ if (result.code === ExportResultCode.SUCCESS) {
2160
+ accepted += batch.length;
2161
+ health.recordSuccess(batch.length, options.clock.now());
2162
+ continue;
2163
+ }
2164
+ health.recordFailure("telemetry-export-failure", batch.length, options.clock.now());
2165
+ if (options.spool !== void 0) {
2166
+ const spoolResult = await options.spool.enqueue(toSpoolBatch(batch)).catch(() => ({
2167
+ spooled: false,
2168
+ reason: "capacity-exceeded"
2169
+ }));
2170
+ if (spoolResult.spooled) {
2171
+ accepted += batch.length;
2172
+ continue;
2173
+ }
2174
+ }
2175
+ rejected += batch.length;
2176
+ errors.push(
2177
+ createErrorInfo({
2178
+ code: "telemetry-export-failure",
2179
+ phase: "export",
2180
+ detail: "collector rejected or was unreachable for a log record batch",
2181
+ details: { "export.batch_size": batch.length, "export.signal": "logs" }
2182
+ })
2183
+ );
2184
+ }
2185
+ return { accepted, rejected, errors };
2186
+ };
2187
+ const drainSpool = async (maxBatches) => {
2188
+ if (options.spool === void 0) {
2189
+ return { drained: 0, remaining: 0, failed: 0 };
2190
+ }
2191
+ const result = await options.spool.drain(sendSerializedBatch, {
2192
+ ...maxBatches === void 0 ? {} : { maxBatches }
2193
+ });
2194
+ if (result.drained > 0) {
2195
+ health.recordSuccess(result.drained, options.clock.now());
2196
+ }
2197
+ return result;
2198
+ };
2199
+ const flush = async () => {
2200
+ try {
2201
+ await exporter.forceFlush();
2202
+ } catch {
2203
+ }
2204
+ await drainSpool().catch(() => void 0);
2205
+ };
2206
+ const shutdown = async () => {
2207
+ if (shutdownCompleted) {
2208
+ return;
2209
+ }
2210
+ shutdownCompleted = true;
2211
+ await flush();
2212
+ try {
2213
+ await exporter.shutdown();
2214
+ } catch {
2215
+ }
2216
+ };
2217
+ return {
2218
+ emit,
2219
+ flush,
2220
+ shutdown,
2221
+ health: () => health.snapshot(),
2222
+ drainSpool
2223
+ };
2224
+ };
2225
+
2226
+ // src/telemetry/signal-fanout.ts
2227
+ var createSignalFanout = (options) => {
2228
+ const emit = async (events) => {
2229
+ const traces = await options.traces.emit(events);
2230
+ const logs = await options.logs.emit(events);
2231
+ const errors = [...traces.errors, ...logs.errors];
2232
+ return {
2233
+ accepted: traces.accepted + logs.accepted,
2234
+ rejected: traces.rejected + logs.rejected,
2235
+ errors
2236
+ };
2237
+ };
2238
+ const flush = async () => {
2239
+ await options.traces.flush().catch(() => void 0);
2240
+ await options.logs.flush().catch(() => void 0);
2241
+ };
2242
+ const shutdown = async () => {
2243
+ await options.traces.shutdown().catch(() => void 0);
2244
+ await options.logs.shutdown().catch(() => void 0);
2245
+ };
2246
+ return {
2247
+ emit,
2248
+ flush,
2249
+ shutdown,
2250
+ health: () => [
2251
+ options.traces.health(),
2252
+ options.logs.health()
2253
+ ]
2254
+ };
2255
+ };
2256
+ var shareCorrelationPerBatch = (correlate) => {
2257
+ let pending;
2258
+ return (events) => {
2259
+ if (pending?.events === events) {
2260
+ return pending.result;
2261
+ }
2262
+ const result = correlate(events);
2263
+ pending = { events, result };
2264
+ return result;
2265
+ };
2266
+ };
2267
+ export {
2268
+ DEFAULT_INSTRUMENTATION_SCOPE,
2269
+ LOG_MAPPING_VERSION,
2270
+ LOG_SIGNALS,
2271
+ MAX_LOG_BODY_CHARACTERS,
2272
+ MAX_LOG_RECORDS_PER_BATCH,
2273
+ MAX_LOG_RECORDS_PER_EVENT,
2274
+ MAX_RECOVERED_START_ATTRIBUTES,
2275
+ MCP_TOOL_NAME_PATTERN,
2276
+ NO_LOG_CONTENT,
2277
+ canonicalEventTraceIdentities,
2278
+ canonicalEventsToLogRecords,
2279
+ canonicalEventsToReadableSpans,
2280
+ createFileDurableLogSpool,
2281
+ createFileDurableSpool,
2282
+ createOtlpLogSink,
2283
+ createOtlpTraceSink,
2284
+ createSignalFanout,
2285
+ describeLogsDeliverability,
2286
+ logSignalOf,
2287
+ logSignalsForLifecycleEvents,
2288
+ parentScopeRefOf,
2289
+ resolveLogsEndpoint,
2290
+ shareCorrelationPerBatch,
2291
+ spanScopeRefOf,
2292
+ startOnlySpanAttributes
2293
+ };
2294
+ //# sourceMappingURL=telemetry.js.map