@osfactory/otel-hook 0.5.0 → 0.7.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 (45) hide show
  1. package/README.md +72 -7
  2. package/dist/{adapter-BS7xHKGQ.d.ts → adapter-BJiz6lqM.d.ts} +2 -2
  3. package/dist/cli.js +207 -34
  4. package/dist/cli.js.map +1 -1
  5. package/dist/config.d.ts +85 -1
  6. package/dist/config.js +135 -1
  7. package/dist/config.js.map +1 -1
  8. package/dist/{events-CzZ5kukS.d.ts → events-B3MHoJTD.d.ts} +72 -1
  9. package/dist/{filesystem-store-BcOveJYY.d.ts → filesystem-store-r-nNA3BA.d.ts} +1 -1
  10. package/dist/{hook-DxTakjAD.d.ts → hook-Dh8OO4Wa.d.ts} +4 -4
  11. package/dist/index.d.ts +12 -12
  12. package/dist/index.js +197 -31
  13. package/dist/index.js.map +1 -1
  14. package/dist/install.d.ts +4 -4
  15. package/dist/install.js +8 -2
  16. package/dist/install.js.map +1 -1
  17. package/dist/integration.d.ts +13 -8
  18. package/dist/integration.js +2273 -2256
  19. package/dist/integration.js.map +1 -1
  20. package/dist/lifecycle.d.ts +3 -3
  21. package/dist/lifecycle.js +761 -212
  22. package/dist/lifecycle.js.map +1 -1
  23. package/dist/{memory-DkTohdIa.d.ts → memory-Bl9ANVff.d.ts} +2 -2
  24. package/dist/model.d.ts +1 -1
  25. package/dist/model.js +13 -2
  26. package/dist/model.js.map +1 -1
  27. package/dist/{otlp-log-sink-DaZDPKnR.d.ts → otlp-log-sink-eUEjaLhk.d.ts} +3 -3
  28. package/dist/{payload-2lnpKodw.d.ts → payload-Ci8_ERm6.d.ts} +1 -1
  29. package/dist/{ports-B0rC49b3.d.ts → ports-n7KFOpKo.d.ts} +1 -1
  30. package/dist/providers.d.ts +10 -10
  31. package/dist/providers.js +32 -13
  32. package/dist/providers.js.map +1 -1
  33. package/dist/{registry-DVnPA_b6.d.ts → registry-CIVvRlVK.d.ts} +1 -1
  34. package/dist/runtime.d.ts +8 -8
  35. package/dist/runtime.js +11 -6
  36. package/dist/runtime.js.map +1 -1
  37. package/dist/{semconv-CtnDdsPk.d.ts → semconv-fPRb-dpU.d.ts} +1 -1
  38. package/dist/state.d.ts +4 -4
  39. package/dist/telemetry.d.ts +6 -6
  40. package/dist/telemetry.js +956 -418
  41. package/dist/telemetry.js.map +1 -1
  42. package/dist/testing.d.ts +14 -8
  43. package/dist/testing.js +36 -18
  44. package/dist/testing.js.map +1 -1
  45. package/package.json +1 -1
package/dist/telemetry.js CHANGED
@@ -38,10 +38,782 @@ import {
38
38
  } from "@opentelemetry/semantic-conventions/incubating";
39
39
 
40
40
  // src/version.ts
41
- var VERSION = "0.5.0";
41
+ var VERSION = "0.7.0";
42
42
 
43
43
  // src/telemetry/export-identity.ts
44
44
  import { ATTR_SESSION_ID } from "@opentelemetry/semantic-conventions/incubating";
45
+
46
+ // src/model/events.ts
47
+ import { z as z9 } from "zod";
48
+
49
+ // src/errors/taxonomy.ts
50
+ import { z } from "zod";
51
+ var otelHookErrorCodeSchema = z.enum([
52
+ /** Input was not usable at all (empty stdin, unparsable JSON). */
53
+ "invalid-input",
54
+ /** Input parsed but failed canonical schema validation. */
55
+ "schema-validation-failed",
56
+ /** No adapter claimed the input with sufficient confidence. */
57
+ "provider-unknown",
58
+ /** Several adapters claimed the input at the same confidence. */
59
+ "provider-detection-ambiguous",
60
+ /** An adapter threw or returned a malformed result. */
61
+ "provider-adapter-failure",
62
+ /** Two identity claims disagreed at equal confidence. */
63
+ "identity-conflict",
64
+ /** Required identity fields were absent. */
65
+ "identity-incomplete",
66
+ /** A usage report violated the canonical usage invariants. */
67
+ "usage-invalid",
68
+ /** The state store could not be read or written. */
69
+ "state-store-failure",
70
+ /** The telemetry sink rejected or could not deliver a batch. */
71
+ "telemetry-export-failure",
72
+ /** Content reached the sink boundary in a state the policy forbids. */
73
+ "privacy-policy-violation",
74
+ /** Configuration could not be resolved. */
75
+ "configuration-invalid",
76
+ /** A configured bound (events, batch size) dropped data. */
77
+ "limit-exceeded",
78
+ /**
79
+ * No replay-stable delivery identifier was available for a callback while
80
+ * deduplication was required.
81
+ */
82
+ "delivery-identifier-unavailable",
83
+ "delivery-claim-superseded",
84
+ /** Anything unanticipated. Always reported, never fatal to the host. */
85
+ "internal-error"
86
+ ]);
87
+ var errorSeveritySchema = z.enum(["warning", "error"]);
88
+ var errorPhaseSchema = z.enum([
89
+ "configuration",
90
+ "detection",
91
+ "identity",
92
+ "parsing",
93
+ "normalization",
94
+ "privacy",
95
+ "state",
96
+ "export",
97
+ "shutdown"
98
+ ]);
99
+ var failurePostureSchema = z.enum(["fail-open", "fail-closed-attribution"]);
100
+ var ERROR_TAXONOMY = Object.freeze({
101
+ "invalid-input": {
102
+ code: "invalid-input",
103
+ severity: "warning",
104
+ posture: "fail-open",
105
+ retryable: false,
106
+ summary: "Input could not be read or decoded."
107
+ },
108
+ "schema-validation-failed": {
109
+ code: "schema-validation-failed",
110
+ severity: "error",
111
+ posture: "fail-closed-attribution",
112
+ retryable: false,
113
+ summary: "A canonical event failed schema validation and was dropped."
114
+ },
115
+ "provider-unknown": {
116
+ code: "provider-unknown",
117
+ severity: "warning",
118
+ posture: "fail-closed-attribution",
119
+ retryable: false,
120
+ summary: "No adapter recognized the source provider; the input stays unattributed."
121
+ },
122
+ "provider-detection-ambiguous": {
123
+ code: "provider-detection-ambiguous",
124
+ severity: "warning",
125
+ posture: "fail-closed-attribution",
126
+ retryable: false,
127
+ summary: "Multiple adapters claimed the input at equal confidence."
128
+ },
129
+ "provider-adapter-failure": {
130
+ code: "provider-adapter-failure",
131
+ severity: "error",
132
+ posture: "fail-open",
133
+ retryable: false,
134
+ summary: "A provider adapter failed while parsing."
135
+ },
136
+ "identity-conflict": {
137
+ code: "identity-conflict",
138
+ severity: "error",
139
+ posture: "fail-closed-attribution",
140
+ retryable: false,
141
+ summary: "Identity claims disagreed; attribution was declined."
142
+ },
143
+ "identity-incomplete": {
144
+ code: "identity-incomplete",
145
+ severity: "warning",
146
+ posture: "fail-closed-attribution",
147
+ retryable: false,
148
+ summary: "Required identity fields were missing; attribution was declined."
149
+ },
150
+ "usage-invalid": {
151
+ code: "usage-invalid",
152
+ severity: "error",
153
+ posture: "fail-open",
154
+ retryable: false,
155
+ summary: "A usage report violated the canonical usage invariants."
156
+ },
157
+ "state-store-failure": {
158
+ code: "state-store-failure",
159
+ severity: "warning",
160
+ posture: "fail-open",
161
+ retryable: true,
162
+ summary: "State could not be read or written; derived values may be incomplete."
163
+ },
164
+ "telemetry-export-failure": {
165
+ code: "telemetry-export-failure",
166
+ severity: "warning",
167
+ posture: "fail-open",
168
+ retryable: true,
169
+ summary: "The telemetry sink could not accept a batch."
170
+ },
171
+ "privacy-policy-violation": {
172
+ code: "privacy-policy-violation",
173
+ severity: "error",
174
+ posture: "fail-closed-attribution",
175
+ retryable: false,
176
+ summary: "Content violated the resolved privacy policy and was dropped."
177
+ },
178
+ "configuration-invalid": {
179
+ code: "configuration-invalid",
180
+ severity: "error",
181
+ posture: "fail-open",
182
+ retryable: false,
183
+ summary: "Configuration could not be resolved; defaults apply."
184
+ },
185
+ "limit-exceeded": {
186
+ code: "limit-exceeded",
187
+ severity: "warning",
188
+ posture: "fail-open",
189
+ retryable: false,
190
+ summary: "A configured bound was reached and data was dropped."
191
+ },
192
+ "delivery-identifier-unavailable": {
193
+ code: "delivery-identifier-unavailable",
194
+ severity: "warning",
195
+ // Fail-open: the observation is still attributed and exported. Only the
196
+ // at-most-once guarantee is missing, and refusing the telemetry to protect
197
+ // a duplicate count would trade a certain loss for a possible one.
198
+ posture: "fail-open",
199
+ retryable: false,
200
+ summary: "No replay-stable delivery identifier was available; this callback was exported without deduplication."
201
+ },
202
+ "delivery-claim-superseded": {
203
+ code: "delivery-claim-superseded",
204
+ severity: "warning",
205
+ // Fail-open, and specifically *not* silent. A peer reclaimed this callback's
206
+ // claim while this process was still working on it, which means the
207
+ // configured stale window is shorter than this installation's real worst
208
+ // case. Both processes may now have exported the callback, so the
209
+ // at-most-once guarantee did not hold for it — the only honest response is
210
+ // to say so and let the operator raise the window.
211
+ posture: "fail-open",
212
+ retryable: false,
213
+ summary: "A delivery claim was reclaimed by another process before this one committed; the callback may have been exported twice."
214
+ },
215
+ "internal-error": {
216
+ code: "internal-error",
217
+ severity: "error",
218
+ posture: "fail-open",
219
+ retryable: false,
220
+ summary: "An unexpected failure was contained."
221
+ }
222
+ });
223
+ var describeErrorCode = (code) => ERROR_TAXONOMY[code];
224
+ var attributionOutcomeSchema = z.enum([
225
+ /** Identity resolved; events carry provider and session identity. */
226
+ "attributed",
227
+ /** Identity could not be established safely; nothing was attributed. */
228
+ "declined",
229
+ /** Attribution was attempted and failed unexpectedly. */
230
+ "failed",
231
+ /** Input was recognized but intentionally carried no telemetry. */
232
+ "not-applicable"
233
+ ]);
234
+ var attributionReasonSchema = z.enum([
235
+ "provider-unknown",
236
+ "provider-detection-ambiguous",
237
+ "identity-conflict",
238
+ "identity-incomplete",
239
+ "adapter-ignored-input",
240
+ "adapter-failure",
241
+ "invalid-input",
242
+ "internal-error"
243
+ ]);
244
+
245
+ // src/model/content.ts
246
+ import { z as z3 } from "zod";
247
+
248
+ // src/model/primitives.ts
249
+ import { z as z2 } from "zod";
250
+ var MAX_IDENTIFIER_LENGTH = 256;
251
+ var MAX_ATTRIBUTE_STRING_LENGTH = 4096;
252
+ var MAX_ATTRIBUTE_ARRAY_LENGTH = 128;
253
+ var nonEmptyStringSchema = z2.string().min(1).max(MAX_IDENTIFIER_LENGTH);
254
+ var epochMillisSchema = z2.number().int().min(0).max(864e13);
255
+ var durationMillisSchema = z2.number().min(0).finite();
256
+ var tokenCountSchema = z2.number().int().min(0);
257
+ var sequenceNumberSchema = z2.number().int().min(0);
258
+ var brandedIdSchema = () => z2.string().min(1).max(MAX_IDENTIFIER_LENGTH);
259
+ var invocationIdSchema = brandedIdSchema().brand();
260
+ var sessionIdSchema = brandedIdSchema().brand();
261
+ var eventIdSchema = brandedIdSchema().brand();
262
+ var WORKSPACE_ID_PATTERN = /^[a-z][a-z0-9]{0,15}:[A-Za-z0-9_-]{8,128}$/;
263
+ var workspaceIdSchema = z2.string().regex(WORKSPACE_ID_PATTERN, "workspace id must be an opaque `<scheme>:<token>` handle").brand();
264
+ var PROVIDER_ID_PATTERN = /^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/;
265
+ var providerIdSchema = z2.string().min(1).max(64).regex(PROVIDER_ID_PATTERN, "provider id must be lowercase and hyphenated").brand();
266
+ var UNKNOWN_PROVIDER_ID = "unknown";
267
+ var resolvedProviderIdSchema = z2.union([
268
+ providerIdSchema,
269
+ z2.literal(UNKNOWN_PROVIDER_ID)
270
+ ]);
271
+ var attributePrimitiveSchema = z2.union([
272
+ z2.string().max(MAX_ATTRIBUTE_STRING_LENGTH),
273
+ z2.number().finite(),
274
+ z2.boolean()
275
+ ]);
276
+ var attributeValueSchema = z2.union([
277
+ attributePrimitiveSchema,
278
+ z2.array(attributePrimitiveSchema).max(MAX_ATTRIBUTE_ARRAY_LENGTH)
279
+ ]);
280
+ var attributesSchema = z2.record(z2.string().min(1).max(MAX_IDENTIFIER_LENGTH), attributeValueSchema);
281
+ var detectionConfidenceSchema = z2.enum(["none", "weak", "strong", "exact"]);
282
+ var DETECTION_CONFIDENCE_RANK = Object.freeze({
283
+ none: 0,
284
+ weak: 1,
285
+ strong: 2,
286
+ exact: 3
287
+ });
288
+ var sourceTransportSchema = z2.enum([
289
+ "hook-stdin",
290
+ "cli-argument",
291
+ "library-call",
292
+ "test-fixture"
293
+ ]);
294
+
295
+ // src/model/content.ts
296
+ var contentKindSchema = z3.enum([
297
+ "prompt",
298
+ "response",
299
+ "reasoning",
300
+ "tool-input",
301
+ "tool-output",
302
+ "error-message",
303
+ "system-instruction",
304
+ "attachment"
305
+ ]);
306
+ var contentRoleSchema = z3.enum(["user", "assistant", "system", "tool", "unknown"]);
307
+ var contentDisclosureSchema = z3.enum(["omitted", "masked", "redacted", "raw"]);
308
+ var CONTENT_HASH_PATTERN = /^sha256:[0-9a-f]{64}$/;
309
+ var contentFactSchema = z3.strictObject({
310
+ kind: contentKindSchema,
311
+ role: contentRoleSchema.optional(),
312
+ /** Unicode code point count of the original content. */
313
+ characterLength: z3.number().int().min(0),
314
+ /** UTF-8 byte length of the original content. */
315
+ byteLength: z3.number().int().min(0),
316
+ /** Stable salted digest of the original content. */
317
+ contentHash: z3.string().regex(CONTENT_HASH_PATTERN),
318
+ disclosure: contentDisclosureSchema,
319
+ /** Disclosed text, bounded by the privacy policy. Absent when omitted. */
320
+ text: z3.string().optional(),
321
+ /** True when `text` was cut short by the configured string bound. */
322
+ truncated: z3.boolean(),
323
+ /** Number of secret-looking spans replaced while producing `text`. */
324
+ secretsRedacted: z3.number().int().min(0),
325
+ /** Optional non-sensitive label, e.g. a MIME type or tool name. */
326
+ label: nonEmptyStringSchema.optional()
327
+ });
328
+ var contentFactsSchema = z3.array(contentFactSchema).max(64);
329
+
330
+ // src/model/extensions.ts
331
+ import { z as z4 } from "zod";
332
+ var EXTENSION_KEY_PATTERN = /^[a-z][a-z0-9]*(?:[-_][a-z0-9]+)*(?:\.[a-z][a-z0-9]*(?:[-_][a-z0-9]+)*)+$/;
333
+ var RESERVED_EXTENSION_NAMESPACES = Object.freeze([
334
+ "otelhook",
335
+ "otel",
336
+ "telemetry"
337
+ ]);
338
+ var MAX_EXTENSION_ENTRIES = 64;
339
+ var extensionKeyNamespace = (key) => key.slice(0, key.indexOf("."));
340
+ var isReservedExtensionNamespace = (key) => RESERVED_EXTENSION_NAMESPACES.includes(extensionKeyNamespace(key));
341
+ var extensionsSchema = z4.record(z4.string(), attributeValueSchema).check((ctx) => {
342
+ const keys = Object.keys(ctx.value);
343
+ if (keys.length > MAX_EXTENSION_ENTRIES) {
344
+ ctx.issues.push({
345
+ code: "custom",
346
+ input: ctx.value,
347
+ message: `extensions may contain at most ${MAX_EXTENSION_ENTRIES} entries`
348
+ });
349
+ }
350
+ for (const key of keys) {
351
+ if (!EXTENSION_KEY_PATTERN.test(key)) {
352
+ ctx.issues.push({
353
+ code: "custom",
354
+ input: ctx.value,
355
+ path: [key],
356
+ message: `extension key ${JSON.stringify(key)} must be namespaced, e.g. "acme.tier"`
357
+ });
358
+ continue;
359
+ }
360
+ if (isReservedExtensionNamespace(key)) {
361
+ ctx.issues.push({
362
+ code: "custom",
363
+ input: ctx.value,
364
+ path: [key],
365
+ message: `extension namespace ${JSON.stringify(extensionKeyNamespace(key))} is reserved`
366
+ });
367
+ }
368
+ }
369
+ });
370
+ var EMPTY_EXTENSIONS = Object.freeze({});
371
+ var emptyExtensions = () => ({});
372
+
373
+ // src/model/identity.ts
374
+ import { z as z5 } from "zod";
375
+ var workspaceKeySourceSchema = z5.enum([
376
+ "git-remote",
377
+ "git-root",
378
+ "working-directory",
379
+ "explicit",
380
+ "unknown"
381
+ ]);
382
+ var workspaceIdentitySchema = z5.strictObject({
383
+ workspaceId: workspaceIdSchema,
384
+ keySource: workspaceKeySourceSchema,
385
+ /** Repository name only; never an owner path or URL with credentials. */
386
+ repositoryName: nonEmptyStringSchema.optional(),
387
+ vcsBranchName: nonEmptyStringSchema.optional(),
388
+ /** Opaque handle for the checked-out revision. */
389
+ vcsRevisionId: nonEmptyStringSchema.optional()
390
+ }).readonly();
391
+ var sourceProvenanceSchema = z5.strictObject({
392
+ providerId: resolvedProviderIdSchema,
393
+ providerVersion: nonEmptyStringSchema.optional(),
394
+ adapterId: nonEmptyStringSchema,
395
+ adapterVersion: nonEmptyStringSchema,
396
+ detectionConfidence: detectionConfidenceSchema,
397
+ /** The provider's own name for the source event, e.g. a hook event name. */
398
+ sourceEventName: nonEmptyStringSchema.optional(),
399
+ transport: sourceTransportSchema
400
+ }).readonly();
401
+ var consumerAttributesSchema = attributesSchema.readonly();
402
+ var invocationIdentitySchema = z5.strictObject({
403
+ invocationId: invocationIdSchema,
404
+ sessionId: sessionIdSchema,
405
+ /** Set when this invocation runs beneath another agent invocation. */
406
+ parentInvocationId: invocationIdSchema.optional(),
407
+ /** Root of the session tree when the provider exposes one. */
408
+ rootSessionId: sessionIdSchema.optional(),
409
+ /** Stable handle for the agent process/instance, when available. */
410
+ agentInstanceId: nonEmptyStringSchema.optional(),
411
+ provenance: sourceProvenanceSchema,
412
+ workspace: workspaceIdentitySchema,
413
+ startedAt: epochMillisSchema,
414
+ consumerAttributes: consumerAttributesSchema
415
+ }).readonly();
416
+ var identityClaimFieldsSchema = z5.strictObject({
417
+ invocationId: invocationIdSchema.optional(),
418
+ sessionId: sessionIdSchema.optional(),
419
+ parentInvocationId: invocationIdSchema.optional(),
420
+ rootSessionId: sessionIdSchema.optional(),
421
+ agentInstanceId: nonEmptyStringSchema.optional(),
422
+ workspace: workspaceIdentitySchema.optional(),
423
+ startedAt: epochMillisSchema.optional()
424
+ });
425
+ var identityClaimSchema = z5.strictObject({
426
+ /** Non-sensitive label, e.g. `adapter:acme-cli` or `env:OTEL_HOOK_SESSION_ID`. */
427
+ source: nonEmptyStringSchema,
428
+ confidence: detectionConfidenceSchema,
429
+ fields: identityClaimFieldsSchema
430
+ });
431
+
432
+ // src/model/target.ts
433
+ import { z as z6 } from "zod";
434
+ var targetSourceSchema = z6.enum(["tool-path", "shell-cwd", "session-cwd"]);
435
+ var MAX_TARGET_HINT_PATHS = 8;
436
+ var MAX_TARGET_PATH_LENGTH = 4096;
437
+ var localPathSchema = z6.string().min(1).max(MAX_TARGET_PATH_LENGTH).refine((value) => !value.includes("\0"), "path must not contain NUL");
438
+ var targetHintSchema = z6.strictObject({
439
+ source: targetSourceSchema,
440
+ paths: z6.array(localPathSchema).min(1).max(MAX_TARGET_HINT_PATHS).readonly(),
441
+ /** Absolute directory that relative `paths` resolve against. */
442
+ baseDirectory: localPathSchema.optional()
443
+ }).readonly();
444
+ var worktreeKindSchema = z6.enum(["main", "linked"]);
445
+ var workspaceTargetSchema = z6.strictObject({
446
+ workspaceId: workspaceIdSchema,
447
+ /** Branch checked out in that worktree; absent on a detached HEAD. */
448
+ vcsBranchName: nonEmptyStringSchema.optional(),
449
+ source: targetSourceSchema,
450
+ /** `git-root` handle of the repository's main worktree; absent when there is none to name. */
451
+ repositoryId: workspaceIdSchema.optional(),
452
+ worktreeKind: worktreeKindSchema.optional()
453
+ }).readonly();
454
+ var SUBAGENT_ID_PATTERN = /^[A-Za-z0-9_.:@+=-]{1,256}$/;
455
+ var subagentIdSchema = z6.string().regex(SUBAGENT_ID_PATTERN);
456
+
457
+ // src/model/usage.ts
458
+ import { z as z7 } from "zod";
459
+ var usageTemporalitySchema = z7.enum(["delta", "cumulative"]);
460
+ var cacheCreationAccountingSchema = z7.enum([
461
+ "included-in-input",
462
+ "disjoint-from-input",
463
+ "not-reported"
464
+ ]);
465
+ var providerTotalAgreementSchema = z7.enum(["unreported", "agrees", "disagrees"]);
466
+ var usageReportSchema = z7.strictObject({
467
+ temporality: usageTemporalitySchema,
468
+ /** Inclusive input tokens. */
469
+ inputTokens: tokenCountSchema.optional(),
470
+ /** Subset of `inputTokens` served from a prompt cache. */
471
+ cachedInputTokens: tokenCountSchema.optional(),
472
+ /** Tokens written to a prompt cache. */
473
+ cacheCreationInputTokens: tokenCountSchema.optional(),
474
+ /** Required when `cacheCreationInputTokens` is present and non-zero. */
475
+ cacheCreationAccounting: cacheCreationAccountingSchema.optional(),
476
+ /** Inclusive output tokens. */
477
+ outputTokens: tokenCountSchema.optional(),
478
+ /** Subset of `outputTokens` spent on reasoning. */
479
+ reasoningOutputTokens: tokenCountSchema.optional(),
480
+ /** Total exactly as the provider reported it, if it reported one. */
481
+ providerTotalTokens: tokenCountSchema.optional()
482
+ });
483
+ var canonicalUsageSchema = z7.strictObject({
484
+ temporality: usageTemporalitySchema,
485
+ inputTokens: tokenCountSchema,
486
+ cachedInputTokens: tokenCountSchema,
487
+ cacheCreationInputTokens: tokenCountSchema,
488
+ cacheCreationAccounting: cacheCreationAccountingSchema,
489
+ outputTokens: tokenCountSchema,
490
+ reasoningOutputTokens: tokenCountSchema,
491
+ /** Derived: input tokens that were neither cache reads nor cache writes. */
492
+ uncachedInputTokens: tokenCountSchema,
493
+ /** Derived: canonical billable total. */
494
+ totalTokens: tokenCountSchema,
495
+ providerTotalTokens: tokenCountSchema.optional(),
496
+ providerTotalAgreement: providerTotalAgreementSchema
497
+ }).check((ctx) => {
498
+ const usage = ctx.value;
499
+ const push = (message) => {
500
+ ctx.issues.push({ code: "custom", input: usage, message });
501
+ };
502
+ if (usage.cachedInputTokens > usage.inputTokens) {
503
+ push("cachedInputTokens must not exceed inputTokens (it is a subset)");
504
+ }
505
+ if (usage.reasoningOutputTokens > usage.outputTokens) {
506
+ push("reasoningOutputTokens must not exceed outputTokens (it is a subset)");
507
+ }
508
+ if (usage.cacheCreationAccounting === "not-reported" && usage.cacheCreationInputTokens !== 0) {
509
+ push("cacheCreationInputTokens must be 0 when cacheCreationAccounting is not-reported");
510
+ }
511
+ const creationInsideInput = usage.cacheCreationAccounting === "included-in-input" ? usage.cacheCreationInputTokens : 0;
512
+ if (usage.cachedInputTokens + creationInsideInput > usage.inputTokens) {
513
+ push(
514
+ "cachedInputTokens + cacheCreationInputTokens must not exceed inputTokens when cache creation is included in input"
515
+ );
516
+ }
517
+ const expectedUncached = usage.inputTokens - usage.cachedInputTokens - creationInsideInput;
518
+ if (expectedUncached >= 0 && usage.uncachedInputTokens !== expectedUncached) {
519
+ push(`uncachedInputTokens must equal ${expectedUncached}`);
520
+ }
521
+ const creationOutsideInput = usage.cacheCreationAccounting === "disjoint-from-input" ? usage.cacheCreationInputTokens : 0;
522
+ const expectedTotal = usage.inputTokens + creationOutsideInput + usage.outputTokens;
523
+ if (usage.totalTokens !== expectedTotal) {
524
+ push(`totalTokens must equal ${expectedTotal}`);
525
+ }
526
+ const expectedAgreement = usage.providerTotalTokens === void 0 ? "unreported" : usage.providerTotalTokens === expectedTotal ? "agrees" : "disagrees";
527
+ if (usage.providerTotalAgreement !== expectedAgreement) {
528
+ push(`providerTotalAgreement must be ${expectedAgreement}`);
529
+ }
530
+ });
531
+ var normalizeUsage = (report) => {
532
+ const parsed = usageReportSchema.safeParse(report);
533
+ if (!parsed.success) {
534
+ return {
535
+ status: "invalid",
536
+ issues: parsed.error.issues.map((issue) => ({
537
+ code: "invalid-report",
538
+ message: `${issue.path.join(".") || "<root>"}: ${issue.message}`
539
+ }))
540
+ };
541
+ }
542
+ const input = parsed.data;
543
+ const issues = [];
544
+ const notes = [];
545
+ const inputTokens = input.inputTokens ?? 0;
546
+ const cachedInputTokens = input.cachedInputTokens ?? 0;
547
+ const cacheCreationInputTokens = input.cacheCreationInputTokens ?? 0;
548
+ const outputTokens = input.outputTokens ?? 0;
549
+ const reasoningOutputTokens = input.reasoningOutputTokens ?? 0;
550
+ let accounting;
551
+ if (cacheCreationInputTokens === 0) {
552
+ accounting = input.cacheCreationAccounting ?? "not-reported";
553
+ if (accounting !== "not-reported") {
554
+ notes.push(
555
+ `cacheCreationAccounting=${accounting} retained with zero cache-creation tokens`
556
+ );
557
+ }
558
+ } else if (input.cacheCreationAccounting === void 0) {
559
+ issues.push({
560
+ code: "cache-creation-accounting-missing",
561
+ message: "cacheCreationAccounting is required when cacheCreationInputTokens is non-zero; it cannot be inferred"
562
+ });
563
+ accounting = "not-reported";
564
+ } else if (input.cacheCreationAccounting === "not-reported") {
565
+ issues.push({
566
+ code: "cache-creation-accounting-missing",
567
+ message: "cacheCreationAccounting=not-reported conflicts with non-zero cacheCreationInputTokens"
568
+ });
569
+ accounting = "not-reported";
570
+ } else {
571
+ accounting = input.cacheCreationAccounting;
572
+ }
573
+ if (cachedInputTokens > inputTokens) {
574
+ issues.push({
575
+ code: "cached-exceeds-input",
576
+ message: `cachedInputTokens (${cachedInputTokens}) exceeds inclusive inputTokens (${inputTokens})`
577
+ });
578
+ }
579
+ if (reasoningOutputTokens > outputTokens) {
580
+ issues.push({
581
+ code: "reasoning-exceeds-output",
582
+ message: `reasoningOutputTokens (${reasoningOutputTokens}) exceeds inclusive outputTokens (${outputTokens})`
583
+ });
584
+ }
585
+ const creationInsideInput = accounting === "included-in-input" ? cacheCreationInputTokens : 0;
586
+ if (cachedInputTokens + creationInsideInput > inputTokens) {
587
+ issues.push({
588
+ code: "cache-creation-exceeds-input",
589
+ message: `cachedInputTokens + cacheCreationInputTokens (${cachedInputTokens + creationInsideInput}) exceeds inclusive inputTokens (${inputTokens})`
590
+ });
591
+ }
592
+ if (issues.length > 0) {
593
+ return { status: "invalid", issues };
594
+ }
595
+ const creationOutsideInput = accounting === "disjoint-from-input" ? cacheCreationInputTokens : 0;
596
+ const totalTokens = inputTokens + creationOutsideInput + outputTokens;
597
+ const providerTotalAgreement = input.providerTotalTokens === void 0 ? "unreported" : input.providerTotalTokens === totalTokens ? "agrees" : "disagrees";
598
+ if (providerTotalAgreement === "disagrees") {
599
+ notes.push(
600
+ `providerTotalTokens (${input.providerTotalTokens ?? 0}) disagrees with canonical total (${totalTokens}); both retained`
601
+ );
602
+ }
603
+ const usage = {
604
+ temporality: input.temporality,
605
+ inputTokens,
606
+ cachedInputTokens,
607
+ cacheCreationInputTokens,
608
+ cacheCreationAccounting: accounting,
609
+ outputTokens,
610
+ reasoningOutputTokens,
611
+ uncachedInputTokens: inputTokens - cachedInputTokens - creationInsideInput,
612
+ totalTokens,
613
+ ...input.providerTotalTokens === void 0 ? {} : { providerTotalTokens: input.providerTotalTokens },
614
+ providerTotalAgreement
615
+ };
616
+ return { status: "ok", usage, notes };
617
+ };
618
+ var UsageNormalizationError = class extends Error {
619
+ issues;
620
+ constructor(issues) {
621
+ super(`invalid usage report: ${issues.map((issue) => issue.message).join("; ")}`);
622
+ this.name = "UsageNormalizationError";
623
+ this.issues = issues;
624
+ }
625
+ };
626
+ var normalizeUsageOrThrow = (report) => {
627
+ const result = normalizeUsage(report);
628
+ if (result.status === "invalid") {
629
+ throw new UsageNormalizationError(result.issues);
630
+ }
631
+ return result.usage;
632
+ };
633
+ var EMPTY_DELTA_USAGE = Object.freeze(
634
+ normalizeUsageOrThrow({ temporality: "delta" })
635
+ );
636
+
637
+ // src/model/version.ts
638
+ import { z as z8 } from "zod";
639
+ var CANONICAL_SCHEMA_VERSION = 1;
640
+ var canonicalSchemaVersionSchema = z8.literal(CANONICAL_SCHEMA_VERSION);
641
+
642
+ // src/model/events.ts
643
+ var modelDescriptorSchema = z9.strictObject({
644
+ modelId: nonEmptyStringSchema,
645
+ /** Vendor of the model, e.g. `anthropic`. Distinct from the agent provider. */
646
+ vendor: nonEmptyStringSchema.optional(),
647
+ family: nonEmptyStringSchema.optional()
648
+ });
649
+ var costFactsSchema = z9.strictObject({
650
+ /** ISO 4217 code. */
651
+ currency: z9.string().length(3),
652
+ amount: z9.number().min(0).finite(),
653
+ source: z9.enum(["provider-reported", "computed"])
654
+ });
655
+ var canonicalEventTypeSchema = z9.enum([
656
+ "session.start",
657
+ "session.end",
658
+ "prompt.submitted",
659
+ "generation.start",
660
+ "generation.end",
661
+ "tool.start",
662
+ "tool.end",
663
+ "subagent.start",
664
+ "subagent.end",
665
+ "compaction.performed",
666
+ "error.raised"
667
+ ]);
668
+ var CANONICAL_EVENT_TYPES = canonicalEventTypeSchema.options;
669
+ var outcomeSchema = z9.enum(["ok", "error", "cancelled", "timeout", "denied", "unknown"]);
670
+ var baseEventFields = {
671
+ schemaVersion: canonicalSchemaVersionSchema,
672
+ eventId: eventIdSchema,
673
+ invocationId: invocationIdSchema,
674
+ sessionId: sessionIdSchema,
675
+ /** Per-invocation ordering key. Stable across replays of the same input. */
676
+ sequence: sequenceNumberSchema,
677
+ occurredAt: epochMillisSchema,
678
+ provenance: sourceProvenanceSchema,
679
+ workspace: workspaceIdentitySchema,
680
+ /**
681
+ * The provider's own id for the subagent this event was emitted inside (e.g.
682
+ * Claude Code's `agent_id`). Absent for the top-level agent. Set by the event
683
+ * factory, never by hand.
684
+ */
685
+ subagentId: subagentIdSchema.optional(),
686
+ extensions: extensionsSchema.default(emptyExtensions)
687
+ };
688
+ var event = (shape) => z9.strictObject({ ...baseEventFields, ...shape });
689
+ var sessionStartEventSchema = event({
690
+ type: z9.literal("session.start"),
691
+ sessionKind: z9.enum(["interactive", "non-interactive", "unknown"]),
692
+ agentName: nonEmptyStringSchema.optional(),
693
+ agentVersion: nonEmptyStringSchema.optional(),
694
+ model: modelDescriptorSchema.optional(),
695
+ /** The git worktree the session runs in, resolved by the core (ADR 0008). */
696
+ target: workspaceTargetSchema.optional()
697
+ });
698
+ var sessionEndEventSchema = event({
699
+ type: z9.literal("session.end"),
700
+ reason: z9.enum(["completed", "aborted", "error", "timeout", "unknown"]),
701
+ durationMillis: durationMillisSchema.optional(),
702
+ /** Session totals, typically cumulative. */
703
+ usage: canonicalUsageSchema.optional(),
704
+ cost: costFactsSchema.optional()
705
+ });
706
+ var promptSubmittedEventSchema = event({
707
+ type: z9.literal("prompt.submitted"),
708
+ promptSource: z9.enum(["user", "automation", "resumed", "unknown"]),
709
+ content: contentFactSchema.optional(),
710
+ turnIndex: z9.number().int().min(0).optional(),
711
+ /** The git worktree the session runs in, resolved by the core (ADR 0008). */
712
+ target: workspaceTargetSchema.optional()
713
+ });
714
+ var generationStartEventSchema = event({
715
+ type: z9.literal("generation.start"),
716
+ generationId: nonEmptyStringSchema,
717
+ model: modelDescriptorSchema,
718
+ requestedMaxOutputTokens: tokenCountSchema.optional(),
719
+ inputContent: contentFactsSchema.optional()
720
+ });
721
+ var generationEndEventSchema = event({
722
+ type: z9.literal("generation.end"),
723
+ generationId: nonEmptyStringSchema,
724
+ model: modelDescriptorSchema,
725
+ outcome: outcomeSchema,
726
+ stopReason: nonEmptyStringSchema.optional(),
727
+ durationMillis: durationMillisSchema.optional(),
728
+ usage: canonicalUsageSchema.optional(),
729
+ cost: costFactsSchema.optional(),
730
+ outputContent: contentFactsSchema.optional()
731
+ });
732
+ var toolKindSchema = z9.enum([
733
+ "read",
734
+ "write",
735
+ "execute",
736
+ "search",
737
+ "network",
738
+ "delegate",
739
+ "other",
740
+ "unknown"
741
+ ]);
742
+ var toolStartEventSchema = event({
743
+ type: z9.literal("tool.start"),
744
+ toolCallId: nonEmptyStringSchema,
745
+ toolName: nonEmptyStringSchema,
746
+ toolKind: toolKindSchema,
747
+ generationId: nonEmptyStringSchema.optional(),
748
+ input: contentFactSchema.optional(),
749
+ /** The git worktree this call targeted, resolved by the core (ADR 0008). */
750
+ target: workspaceTargetSchema.optional()
751
+ });
752
+ var toolEndEventSchema = event({
753
+ type: z9.literal("tool.end"),
754
+ toolCallId: nonEmptyStringSchema,
755
+ toolName: nonEmptyStringSchema,
756
+ outcome: outcomeSchema,
757
+ durationMillis: durationMillisSchema.optional(),
758
+ /** Present when the host asked for or recorded a permission decision. */
759
+ permissionDecision: z9.enum(["allowed", "denied", "deferred", "not-required"]).optional(),
760
+ output: contentFactSchema.optional(),
761
+ /** The git worktree this call targeted, resolved by the core (ADR 0008). */
762
+ target: workspaceTargetSchema.optional()
763
+ });
764
+ var subagentStartEventSchema = event({
765
+ type: z9.literal("subagent.start"),
766
+ subagentInvocationId: invocationIdSchema,
767
+ subagentType: nonEmptyStringSchema.optional(),
768
+ /** 0 for the top-level agent; 1 for its direct children. */
769
+ delegationDepth: z9.number().int().min(0).max(64),
770
+ model: modelDescriptorSchema.optional()
771
+ });
772
+ var subagentEndEventSchema = event({
773
+ type: z9.literal("subagent.end"),
774
+ subagentInvocationId: invocationIdSchema,
775
+ outcome: outcomeSchema,
776
+ durationMillis: durationMillisSchema.optional(),
777
+ usage: canonicalUsageSchema.optional()
778
+ });
779
+ var compactionPerformedEventSchema = event({
780
+ type: z9.literal("compaction.performed"),
781
+ trigger: z9.enum(["automatic", "manual", "unknown"]),
782
+ /** Provider-reported context size before and after compaction, if known. */
783
+ contextTokensBefore: tokenCountSchema.optional(),
784
+ contextTokensAfter: tokenCountSchema.optional(),
785
+ droppedMessageCount: z9.number().int().min(0).optional(),
786
+ usage: canonicalUsageSchema.optional()
787
+ });
788
+ var errorRaisedEventSchema = event({
789
+ type: z9.literal("error.raised"),
790
+ errorCode: otelHookErrorCodeSchema,
791
+ severity: errorSeveritySchema,
792
+ phase: errorPhaseSchema,
793
+ retryable: z9.boolean(),
794
+ /** Error text is content: it is described, never embedded verbatim by default. */
795
+ message: contentFactSchema.optional(),
796
+ /** Non-sensitive, provider-agnostic short label. */
797
+ detail: nonEmptyStringSchema.optional()
798
+ });
799
+ var canonicalEventSchema = z9.discriminatedUnion("type", [
800
+ sessionStartEventSchema,
801
+ sessionEndEventSchema,
802
+ promptSubmittedEventSchema,
803
+ generationStartEventSchema,
804
+ generationEndEventSchema,
805
+ toolStartEventSchema,
806
+ toolEndEventSchema,
807
+ subagentStartEventSchema,
808
+ subagentEndEventSchema,
809
+ compactionPerformedEventSchema,
810
+ errorRaisedEventSchema
811
+ ]);
812
+ var TARGETED_EVENT_TYPES = ["session.start", "prompt.submitted", "tool.start", "tool.end"];
813
+ var TARGETED = new Set(TARGETED_EVENT_TYPES);
814
+ var isTargetedEvent = (event2) => TARGETED.has(event2.type);
815
+
816
+ // src/telemetry/export-identity.ts
45
817
  var ATTR_TRACE_ID = "trace_id";
46
818
  var ATTR_SPAN_ID = "span_id";
47
819
  var ATTR_PARENT_SPAN_ID = "parent_span_id";
@@ -53,7 +825,10 @@ var ATTR_OTELHOOK_INVOCATION_ID = "otelhook.invocation.id";
53
825
  var ATTR_OTELHOOK_PROVIDER_ID = "otelhook.provider.id";
54
826
  var ATTR_OTELHOOK_PROVIDER_VERSION = "otelhook.provider.version";
55
827
  var ATTR_OTELHOOK_WORKSPACE_ID = "otelhook.workspace.id";
56
- var HAR_SESSION_KEY = "har.session_key";
828
+ var EXTERNAL_SESSION_KEY_ATTRIBUTES = Object.freeze([
829
+ ATTR_SESSION_ID,
830
+ "har.session_key"
831
+ ]);
57
832
  var ATTR_OTELHOOK_SUBAGENT_ID = "otelhook.subagent.id";
58
833
  var ATTR_VCS_REF_HEAD_NAME = "vcs.ref.head.name";
59
834
  var ATTR_OTELHOOK_TARGET_WORKSPACE_ID = "otelhook.target.workspace.id";
@@ -61,11 +836,11 @@ var ATTR_OTELHOOK_TARGET_SOURCE = "otelhook.target.source";
61
836
  var ATTR_OTELHOOK_TARGET_REPOSITORY_ID = "otelhook.target.repository.id";
62
837
  var ATTR_OTELHOOK_TARGET_WORKTREE_KIND = "otelhook.target.worktree.kind";
63
838
  var ATTR_OTELHOOK_USAGE_TEMPORALITY = "otelhook.usage.temporality";
64
- var targetAttributes = (event) => {
65
- if (event.type !== "tool.start" && event.type !== "tool.end" || event.target === void 0) {
839
+ var targetAttributes = (event2) => {
840
+ if (!isTargetedEvent(event2) || event2.target === void 0) {
66
841
  return {};
67
842
  }
68
- const { target } = event;
843
+ const { target } = event2;
69
844
  return {
70
845
  [ATTR_OTELHOOK_TARGET_WORKSPACE_ID]: target.workspaceId,
71
846
  [ATTR_OTELHOOK_TARGET_SOURCE]: target.source,
@@ -86,11 +861,13 @@ var passthroughHarAttributes = (resource) => {
86
861
  return attributes;
87
862
  };
88
863
  var resolveExportedSessionId = (eventSessionId, resource) => {
89
- const har = resource.attributes[HAR_SESSION_KEY];
90
- if (typeof har === "string") {
91
- const trimmed = har.trim();
92
- if (trimmed.length > 0) {
93
- return { sessionId: trimmed, providerSessionId: eventSessionId };
864
+ for (const key of EXTERNAL_SESSION_KEY_ATTRIBUTES) {
865
+ const supplied = resource.attributes[key];
866
+ if (typeof supplied === "string") {
867
+ const trimmed = supplied.trim();
868
+ if (trimmed.length > 0) {
869
+ return { sessionId: trimmed, providerSessionId: eventSessionId };
870
+ }
94
871
  }
95
872
  }
96
873
  return { sessionId: eventSessionId, providerSessionId: eventSessionId };
@@ -100,17 +877,17 @@ var hexTraceAttributes = (ids) => ({
100
877
  ...SPAN_ID_HEX_PATTERN.test(ids.spanId) ? { [ATTR_SPAN_ID]: ids.spanId } : {},
101
878
  ...ids.parentSpanId !== void 0 && SPAN_ID_HEX_PATTERN.test(ids.parentSpanId) ? { [ATTR_PARENT_SPAN_ID]: ids.parentSpanId } : {}
102
879
  });
103
- var exportIdentityAttributes = (event, resource, ids) => {
104
- const { sessionId, providerSessionId } = resolveExportedSessionId(event.sessionId, resource);
880
+ var exportIdentityAttributes = (event2, resource, ids) => {
881
+ const { sessionId, providerSessionId } = resolveExportedSessionId(event2.sessionId, resource);
105
882
  return {
106
883
  [ATTR_SESSION_ID]: sessionId,
107
884
  [ATTR_OTELHOOK_SESSION_ID]: providerSessionId,
108
885
  [ATTR_GEN_AI_CONVERSATION_ID]: providerSessionId,
109
- [ATTR_OTELHOOK_INVOCATION_ID]: event.invocationId,
110
- [ATTR_OTELHOOK_PROVIDER_ID]: event.provenance.providerId,
111
- ...event.provenance.providerVersion === void 0 ? {} : { [ATTR_OTELHOOK_PROVIDER_VERSION]: event.provenance.providerVersion },
112
- [ATTR_OTELHOOK_WORKSPACE_ID]: event.workspace.workspaceId,
113
- ...event.subagentId === void 0 ? {} : { [ATTR_OTELHOOK_SUBAGENT_ID]: event.subagentId },
886
+ [ATTR_OTELHOOK_INVOCATION_ID]: event2.invocationId,
887
+ [ATTR_OTELHOOK_PROVIDER_ID]: event2.provenance.providerId,
888
+ ...event2.provenance.providerVersion === void 0 ? {} : { [ATTR_OTELHOOK_PROVIDER_VERSION]: event2.provenance.providerVersion },
889
+ [ATTR_OTELHOOK_WORKSPACE_ID]: event2.workspace.workspaceId,
890
+ ...event2.subagentId === void 0 ? {} : { [ATTR_OTELHOOK_SUBAGENT_ID]: event2.subagentId },
114
891
  ...passthroughHarAttributes(resource),
115
892
  ...hexTraceAttributes(ids)
116
893
  };
@@ -154,57 +931,60 @@ var familyOf = (type) => {
154
931
  return void 0;
155
932
  }
156
933
  };
157
- var spanScopeRefOf = (event) => {
158
- const family = familyOf(event.type);
934
+ var spanScopeRefOf = (event2) => {
935
+ const family = familyOf(event2.type);
159
936
  if (family === void 0) {
160
937
  return void 0;
161
938
  }
162
- switch (event.type) {
939
+ switch (event2.type) {
163
940
  case "session.start":
164
941
  case "session.end":
165
- return { family, scopeKey: event.sessionId };
942
+ return { family, scopeKey: event2.sessionId };
166
943
  case "generation.start":
167
944
  case "generation.end":
168
- return { family, scopeKey: event.generationId };
945
+ return { family, scopeKey: event2.generationId };
169
946
  case "tool.start":
170
947
  case "tool.end":
171
- return { family, scopeKey: event.toolCallId };
948
+ return { family, scopeKey: event2.toolCallId };
172
949
  case "subagent.start":
173
950
  case "subagent.end":
174
- return { family, scopeKey: event.subagentInvocationId };
951
+ return { family, scopeKey: event2.subagentInvocationId };
175
952
  default:
176
953
  return void 0;
177
954
  }
178
955
  };
179
- var parentScopeRefOf = (event) => {
180
- if (event.type === "session.start" || event.type === "session.end") {
956
+ var parentScopeRefOf = (event2) => {
957
+ if (event2.type === "session.start" || event2.type === "session.end") {
181
958
  return void 0;
182
959
  }
183
- if (event.type === "tool.start" && event.generationId !== void 0) {
184
- return { family: "generation", scopeKey: event.generationId };
960
+ if (event2.type === "tool.start" && event2.generationId !== void 0) {
961
+ return { family: "generation", scopeKey: event2.generationId };
185
962
  }
186
- return { family: "session", scopeKey: event.sessionId };
963
+ return { family: "session", scopeKey: event2.sessionId };
187
964
  };
188
- var startOnlySpanAttributes = (event) => {
189
- switch (event.type) {
965
+ var startOnlySpanAttributes = (event2) => {
966
+ switch (event2.type) {
967
+ // The session's own worktree is carried forward like a tool's target, so
968
+ // the session span a later `session.end` process exports still names it.
190
969
  case "session.start":
191
970
  return {
192
- ...event.agentName === void 0 ? {} : { [ATTR_OTELHOOK_AGENT_NAME]: event.agentName },
193
- ...event.agentVersion === void 0 ? {} : { [ATTR_OTELHOOK_AGENT_VERSION]: event.agentVersion }
971
+ ...event2.agentName === void 0 ? {} : { [ATTR_OTELHOOK_AGENT_NAME]: event2.agentName },
972
+ ...event2.agentVersion === void 0 ? {} : { [ATTR_OTELHOOK_AGENT_VERSION]: event2.agentVersion },
973
+ ...targetAttributes(event2)
194
974
  };
195
975
  case "generation.start":
196
976
  return {
197
- [ATTR_GEN_AI_REQUEST_MODEL]: event.model.modelId,
198
- ...event.model.vendor === void 0 ? {} : { [ATTR_GEN_AI_SYSTEM]: event.model.vendor }
977
+ [ATTR_GEN_AI_REQUEST_MODEL]: event2.model.modelId,
978
+ ...event2.model.vendor === void 0 ? {} : { [ATTR_GEN_AI_SYSTEM]: event2.model.vendor }
199
979
  };
200
980
  // `toolName` and `toolCallId` are on both tool edges, so they are not
201
981
  // start-only and persisting them would just pad every record.
202
982
  // The target is carried forward too: an end-only process may see a payload
203
983
  // with less to go on (no tool input), and the start's evidence still holds.
204
984
  case "tool.start":
205
- return { [ATTR_OTELHOOK_TOOL_KIND]: event.toolKind, ...targetAttributes(event) };
985
+ return { [ATTR_OTELHOOK_TOOL_KIND]: event2.toolKind, ...targetAttributes(event2) };
206
986
  case "subagent.start":
207
- return { [ATTR_OTELHOOK_DELEGATION_DEPTH]: event.delegationDepth };
987
+ return { [ATTR_OTELHOOK_DELEGATION_DEPTH]: event2.delegationDepth };
208
988
  default:
209
989
  return {};
210
990
  }
@@ -222,7 +1002,7 @@ var outcomeStatus = (outcome) => {
222
1002
  }
223
1003
  return { code: SpanStatusCode.ERROR, message: outcome };
224
1004
  };
225
- var identityAttributes = (event, resource, ids) => exportIdentityAttributes(event, resource, ids);
1005
+ var identityAttributes = (event2, resource, ids) => exportIdentityAttributes(event2, resource, ids);
226
1006
  var usageAttributes = (usage, resetDetected) => {
227
1007
  if (usage === void 0) {
228
1008
  return {};
@@ -368,7 +1148,8 @@ var buildLifecycleSpan = (plan, resource, scope) => {
368
1148
  name = "session";
369
1149
  kind = SpanKind.INTERNAL;
370
1150
  attributes = {
371
- ...attributes,
1151
+ ...withoutTarget(attributes),
1152
+ ...strongestTarget([pickTarget(resolved.recovered), start === void 0 ? {} : targetAttributes(start)]),
372
1153
  ...start?.agentName === void 0 ? {} : { [ATTR_OTELHOOK_AGENT_NAME]: start.agentName },
373
1154
  ...start?.agentVersion === void 0 ? {} : { [ATTR_OTELHOOK_AGENT_VERSION]: start.agentVersion },
374
1155
  ...end === void 0 ? {} : { [ATTR_OTELHOOK_OUTCOME]: end.reason },
@@ -454,14 +1235,14 @@ var buildLifecycleSpan = (plan, resource, scope) => {
454
1235
  instrumentationScope: scope
455
1236
  });
456
1237
  };
457
- var buildStandaloneSpan = (event, resource, scope) => {
458
- const providerId = event.provenance.providerId;
459
- const traceId = deriveTraceId(providerId, event.sessionId);
460
- const spanId = deriveStandaloneSpanId(providerId, event.sessionId, event.type, event.eventId);
461
- const parent = parentScopeRefOf(event);
462
- const parentSpanId = parent === void 0 ? void 0 : deriveSpanId(providerId, event.sessionId, parent);
1238
+ var buildStandaloneSpan = (event2, resource, scope) => {
1239
+ const providerId = event2.provenance.providerId;
1240
+ const traceId = deriveTraceId(providerId, event2.sessionId);
1241
+ const spanId = deriveStandaloneSpanId(providerId, event2.sessionId, event2.type, event2.eventId);
1242
+ const parent = parentScopeRefOf(event2);
1243
+ const parentSpanId = parent === void 0 ? void 0 : deriveSpanId(providerId, event2.sessionId, parent);
463
1244
  let attributes = {
464
- ...identityAttributes(event, resource, {
1245
+ ...identityAttributes(event2, resource, {
465
1246
  traceId,
466
1247
  spanId,
467
1248
  ...parentSpanId === void 0 ? {} : { parentSpanId }
@@ -469,28 +1250,28 @@ var buildStandaloneSpan = (event, resource, scope) => {
469
1250
  [ATTR_OTELHOOK_SPAN_PAIRED]: true
470
1251
  };
471
1252
  let status = { code: SpanStatusCode.UNSET };
472
- let name = event.type;
473
- switch (event.type) {
1253
+ let name = event2.type;
1254
+ switch (event2.type) {
474
1255
  case "prompt.submitted":
475
1256
  name = "prompt";
476
- attributes = { ...attributes, "otelhook.prompt.source": event.promptSource };
1257
+ attributes = { ...attributes, "otelhook.prompt.source": event2.promptSource, ...targetAttributes(event2) };
477
1258
  break;
478
1259
  case "compaction.performed":
479
1260
  name = "compaction";
480
1261
  attributes = {
481
1262
  ...attributes,
482
- [ATTR_OTELHOOK_COMPACTION_TRIGGER]: event.trigger,
483
- ...usageAttributes(event.usage, false)
1263
+ [ATTR_OTELHOOK_COMPACTION_TRIGGER]: event2.trigger,
1264
+ ...usageAttributes(event2.usage, false)
484
1265
  };
485
1266
  break;
486
1267
  case "error.raised":
487
1268
  name = "error";
488
- status = { code: SpanStatusCode.ERROR, message: event.errorCode };
1269
+ status = { code: SpanStatusCode.ERROR, message: event2.errorCode };
489
1270
  attributes = {
490
1271
  ...attributes,
491
- [ATTR_ERROR_TYPE]: event.errorCode,
492
- "otelhook.error.phase": event.phase,
493
- "otelhook.error.retryable": event.retryable
1272
+ [ATTR_ERROR_TYPE]: event2.errorCode,
1273
+ "otelhook.error.phase": event2.phase,
1274
+ "otelhook.error.retryable": event2.retryable
494
1275
  };
495
1276
  break;
496
1277
  default:
@@ -499,8 +1280,8 @@ var buildStandaloneSpan = (event, resource, scope) => {
499
1280
  return toReadableSpan({
500
1281
  name,
501
1282
  kind: SpanKind.INTERNAL,
502
- startMillis: event.occurredAt,
503
- endMillis: event.occurredAt,
1283
+ startMillis: event2.occurredAt,
1284
+ endMillis: event2.occurredAt,
504
1285
  attributes,
505
1286
  status,
506
1287
  traceId,
@@ -528,21 +1309,21 @@ var layoutBatch = (events) => {
528
1309
  const groups = /* @__PURE__ */ new Map();
529
1310
  const standalone = [];
530
1311
  const groupOf = /* @__PURE__ */ new Map();
531
- for (const event of events) {
532
- const ref = spanScopeRefOf(event);
1312
+ for (const event2 of events) {
1313
+ const ref = spanScopeRefOf(event2);
533
1314
  if (ref === void 0) {
534
- standalone.push(event);
1315
+ standalone.push(event2);
535
1316
  continue;
536
1317
  }
537
- const groupKey = correlationKey(event.provenance.providerId, event.sessionId, ref);
1318
+ const groupKey = correlationKey(event2.provenance.providerId, event2.sessionId, ref);
538
1319
  const group = groups.get(groupKey) ?? { ref };
539
- if (event.type.endsWith(".start")) {
540
- group.start = event;
1320
+ if (event2.type.endsWith(".start")) {
1321
+ group.start = event2;
541
1322
  } else {
542
- group.end = event;
1323
+ group.end = event2;
543
1324
  }
544
1325
  groups.set(groupKey, group);
545
- groupOf.set(event.eventId, groupKey);
1326
+ groupOf.set(event2.eventId, groupKey);
546
1327
  }
547
1328
  return { groups, standalone, groupOf };
548
1329
  };
@@ -599,24 +1380,24 @@ var canonicalEventTraceIdentities = (events, options = {}) => {
599
1380
  }
600
1381
  }
601
1382
  const identities = /* @__PURE__ */ new Map();
602
- for (const event of events) {
603
- const providerId = event.provenance.providerId;
604
- const groupKey = layout.groupOf.get(event.eventId);
1383
+ for (const event2 of events) {
1384
+ const providerId = event2.provenance.providerId;
1385
+ const groupKey = layout.groupOf.get(event2.eventId);
605
1386
  const plan = groupKey === void 0 ? void 0 : plans.get(groupKey);
606
1387
  if (plan === void 0) {
607
- const parent2 = parentScopeRefOf(event);
608
- identities.set(event.eventId, {
609
- traceId: deriveTraceId(providerId, event.sessionId),
610
- spanId: deriveStandaloneSpanId(providerId, event.sessionId, event.type, event.eventId),
611
- ...parent2 === void 0 ? {} : { parentSpanId: deriveSpanId(providerId, event.sessionId, parent2) }
1388
+ const parent2 = parentScopeRefOf(event2);
1389
+ identities.set(event2.eventId, {
1390
+ traceId: deriveTraceId(providerId, event2.sessionId),
1391
+ spanId: deriveStandaloneSpanId(providerId, event2.sessionId, event2.type, event2.eventId),
1392
+ ...parent2 === void 0 ? {} : { parentSpanId: deriveSpanId(providerId, event2.sessionId, parent2) }
612
1393
  });
613
1394
  continue;
614
1395
  }
615
- const parent = plan.correlation?.parent ?? parentScopeRefOf(event);
616
- identities.set(event.eventId, {
1396
+ const parent = plan.correlation?.parent ?? parentScopeRefOf(event2);
1397
+ identities.set(event2.eventId, {
617
1398
  traceId: plan.traceId,
618
1399
  spanId: plan.spanId,
619
- ...parent === void 0 ? {} : { parentSpanId: deriveSpanId(providerId, event.sessionId, parent) }
1400
+ ...parent === void 0 ? {} : { parentSpanId: deriveSpanId(providerId, event2.sessionId, parent) }
620
1401
  });
621
1402
  }
622
1403
  return identities;
@@ -633,8 +1414,8 @@ var canonicalEventsToReadableSpans = (events, options) => {
633
1414
  }
634
1415
  spans.push(buildLifecycleSpan(plan, options.resource, scope));
635
1416
  }
636
- for (const event of layout.standalone) {
637
- spans.push(buildStandaloneSpan(event, options.resource, scope));
1417
+ for (const event2 of layout.standalone) {
1418
+ spans.push(buildStandaloneSpan(event2, options.resource, scope));
638
1419
  }
639
1420
  return spans;
640
1421
  };
@@ -882,259 +1663,14 @@ var createFileDurableSpool = (options) => createSpoolQueue({
882
1663
  import { OTLPTraceExporter } from "@opentelemetry/exporter-trace-otlp-proto";
883
1664
 
884
1665
  // src/errors/index.ts
885
- import { z as z3 } from "zod";
886
-
887
- // src/model/primitives.ts
888
- import { z } from "zod";
889
- var MAX_IDENTIFIER_LENGTH = 256;
890
- var MAX_ATTRIBUTE_STRING_LENGTH = 4096;
891
- var MAX_ATTRIBUTE_ARRAY_LENGTH = 128;
892
- var nonEmptyStringSchema = z.string().min(1).max(MAX_IDENTIFIER_LENGTH);
893
- var epochMillisSchema = z.number().int().min(0).max(864e13);
894
- var durationMillisSchema = z.number().min(0).finite();
895
- var tokenCountSchema = z.number().int().min(0);
896
- var sequenceNumberSchema = z.number().int().min(0);
897
- var brandedIdSchema = () => z.string().min(1).max(MAX_IDENTIFIER_LENGTH);
898
- var invocationIdSchema = brandedIdSchema().brand();
899
- var sessionIdSchema = brandedIdSchema().brand();
900
- var eventIdSchema = brandedIdSchema().brand();
901
- var WORKSPACE_ID_PATTERN = /^[a-z][a-z0-9]{0,15}:[A-Za-z0-9_-]{8,128}$/;
902
- var workspaceIdSchema = z.string().regex(WORKSPACE_ID_PATTERN, "workspace id must be an opaque `<scheme>:<token>` handle").brand();
903
- var PROVIDER_ID_PATTERN = /^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/;
904
- var providerIdSchema = z.string().min(1).max(64).regex(PROVIDER_ID_PATTERN, "provider id must be lowercase and hyphenated").brand();
905
- var UNKNOWN_PROVIDER_ID = "unknown";
906
- var resolvedProviderIdSchema = z.union([
907
- providerIdSchema,
908
- z.literal(UNKNOWN_PROVIDER_ID)
909
- ]);
910
- var attributePrimitiveSchema = z.union([
911
- z.string().max(MAX_ATTRIBUTE_STRING_LENGTH),
912
- z.number().finite(),
913
- z.boolean()
914
- ]);
915
- var attributeValueSchema = z.union([
916
- attributePrimitiveSchema,
917
- z.array(attributePrimitiveSchema).max(MAX_ATTRIBUTE_ARRAY_LENGTH)
918
- ]);
919
- var attributesSchema = z.record(z.string().min(1).max(MAX_IDENTIFIER_LENGTH), attributeValueSchema);
920
- var detectionConfidenceSchema = z.enum(["none", "weak", "strong", "exact"]);
921
- var DETECTION_CONFIDENCE_RANK = Object.freeze({
922
- none: 0,
923
- weak: 1,
924
- strong: 2,
925
- exact: 3
926
- });
927
- var sourceTransportSchema = z.enum([
928
- "hook-stdin",
929
- "cli-argument",
930
- "library-call",
931
- "test-fixture"
932
- ]);
933
-
934
- // src/errors/taxonomy.ts
935
- import { z as z2 } from "zod";
936
- var otelHookErrorCodeSchema = z2.enum([
937
- /** Input was not usable at all (empty stdin, unparsable JSON). */
938
- "invalid-input",
939
- /** Input parsed but failed canonical schema validation. */
940
- "schema-validation-failed",
941
- /** No adapter claimed the input with sufficient confidence. */
942
- "provider-unknown",
943
- /** Several adapters claimed the input at the same confidence. */
944
- "provider-detection-ambiguous",
945
- /** An adapter threw or returned a malformed result. */
946
- "provider-adapter-failure",
947
- /** Two identity claims disagreed at equal confidence. */
948
- "identity-conflict",
949
- /** Required identity fields were absent. */
950
- "identity-incomplete",
951
- /** A usage report violated the canonical usage invariants. */
952
- "usage-invalid",
953
- /** The state store could not be read or written. */
954
- "state-store-failure",
955
- /** The telemetry sink rejected or could not deliver a batch. */
956
- "telemetry-export-failure",
957
- /** Content reached the sink boundary in a state the policy forbids. */
958
- "privacy-policy-violation",
959
- /** Configuration could not be resolved. */
960
- "configuration-invalid",
961
- /** A configured bound (events, batch size) dropped data. */
962
- "limit-exceeded",
963
- /**
964
- * No replay-stable delivery identifier was available for a callback while
965
- * deduplication was required.
966
- */
967
- "delivery-identifier-unavailable",
968
- "delivery-claim-superseded",
969
- /** Anything unanticipated. Always reported, never fatal to the host. */
970
- "internal-error"
971
- ]);
972
- var errorSeveritySchema = z2.enum(["warning", "error"]);
973
- var errorPhaseSchema = z2.enum([
974
- "configuration",
975
- "detection",
976
- "identity",
977
- "parsing",
978
- "normalization",
979
- "privacy",
980
- "state",
981
- "export",
982
- "shutdown"
983
- ]);
984
- var failurePostureSchema = z2.enum(["fail-open", "fail-closed-attribution"]);
985
- var ERROR_TAXONOMY = Object.freeze({
986
- "invalid-input": {
987
- code: "invalid-input",
988
- severity: "warning",
989
- posture: "fail-open",
990
- retryable: false,
991
- summary: "Input could not be read or decoded."
992
- },
993
- "schema-validation-failed": {
994
- code: "schema-validation-failed",
995
- severity: "error",
996
- posture: "fail-closed-attribution",
997
- retryable: false,
998
- summary: "A canonical event failed schema validation and was dropped."
999
- },
1000
- "provider-unknown": {
1001
- code: "provider-unknown",
1002
- severity: "warning",
1003
- posture: "fail-closed-attribution",
1004
- retryable: false,
1005
- summary: "No adapter recognized the source provider; the input stays unattributed."
1006
- },
1007
- "provider-detection-ambiguous": {
1008
- code: "provider-detection-ambiguous",
1009
- severity: "warning",
1010
- posture: "fail-closed-attribution",
1011
- retryable: false,
1012
- summary: "Multiple adapters claimed the input at equal confidence."
1013
- },
1014
- "provider-adapter-failure": {
1015
- code: "provider-adapter-failure",
1016
- severity: "error",
1017
- posture: "fail-open",
1018
- retryable: false,
1019
- summary: "A provider adapter failed while parsing."
1020
- },
1021
- "identity-conflict": {
1022
- code: "identity-conflict",
1023
- severity: "error",
1024
- posture: "fail-closed-attribution",
1025
- retryable: false,
1026
- summary: "Identity claims disagreed; attribution was declined."
1027
- },
1028
- "identity-incomplete": {
1029
- code: "identity-incomplete",
1030
- severity: "warning",
1031
- posture: "fail-closed-attribution",
1032
- retryable: false,
1033
- summary: "Required identity fields were missing; attribution was declined."
1034
- },
1035
- "usage-invalid": {
1036
- code: "usage-invalid",
1037
- severity: "error",
1038
- posture: "fail-open",
1039
- retryable: false,
1040
- summary: "A usage report violated the canonical usage invariants."
1041
- },
1042
- "state-store-failure": {
1043
- code: "state-store-failure",
1044
- severity: "warning",
1045
- posture: "fail-open",
1046
- retryable: true,
1047
- summary: "State could not be read or written; derived values may be incomplete."
1048
- },
1049
- "telemetry-export-failure": {
1050
- code: "telemetry-export-failure",
1051
- severity: "warning",
1052
- posture: "fail-open",
1053
- retryable: true,
1054
- summary: "The telemetry sink could not accept a batch."
1055
- },
1056
- "privacy-policy-violation": {
1057
- code: "privacy-policy-violation",
1058
- severity: "error",
1059
- posture: "fail-closed-attribution",
1060
- retryable: false,
1061
- summary: "Content violated the resolved privacy policy and was dropped."
1062
- },
1063
- "configuration-invalid": {
1064
- code: "configuration-invalid",
1065
- severity: "error",
1066
- posture: "fail-open",
1067
- retryable: false,
1068
- summary: "Configuration could not be resolved; defaults apply."
1069
- },
1070
- "limit-exceeded": {
1071
- code: "limit-exceeded",
1072
- severity: "warning",
1073
- posture: "fail-open",
1074
- retryable: false,
1075
- summary: "A configured bound was reached and data was dropped."
1076
- },
1077
- "delivery-identifier-unavailable": {
1078
- code: "delivery-identifier-unavailable",
1079
- severity: "warning",
1080
- // Fail-open: the observation is still attributed and exported. Only the
1081
- // at-most-once guarantee is missing, and refusing the telemetry to protect
1082
- // a duplicate count would trade a certain loss for a possible one.
1083
- posture: "fail-open",
1084
- retryable: false,
1085
- summary: "No replay-stable delivery identifier was available; this callback was exported without deduplication."
1086
- },
1087
- "delivery-claim-superseded": {
1088
- code: "delivery-claim-superseded",
1089
- severity: "warning",
1090
- // Fail-open, and specifically *not* silent. A peer reclaimed this callback's
1091
- // claim while this process was still working on it, which means the
1092
- // configured stale window is shorter than this installation's real worst
1093
- // case. Both processes may now have exported the callback, so the
1094
- // at-most-once guarantee did not hold for it — the only honest response is
1095
- // to say so and let the operator raise the window.
1096
- posture: "fail-open",
1097
- retryable: false,
1098
- summary: "A delivery claim was reclaimed by another process before this one committed; the callback may have been exported twice."
1099
- },
1100
- "internal-error": {
1101
- code: "internal-error",
1102
- severity: "error",
1103
- posture: "fail-open",
1104
- retryable: false,
1105
- summary: "An unexpected failure was contained."
1106
- }
1107
- });
1108
- var describeErrorCode = (code) => ERROR_TAXONOMY[code];
1109
- var attributionOutcomeSchema = z2.enum([
1110
- /** Identity resolved; events carry provider and session identity. */
1111
- "attributed",
1112
- /** Identity could not be established safely; nothing was attributed. */
1113
- "declined",
1114
- /** Attribution was attempted and failed unexpectedly. */
1115
- "failed",
1116
- /** Input was recognized but intentionally carried no telemetry. */
1117
- "not-applicable"
1118
- ]);
1119
- var attributionReasonSchema = z2.enum([
1120
- "provider-unknown",
1121
- "provider-detection-ambiguous",
1122
- "identity-conflict",
1123
- "identity-incomplete",
1124
- "adapter-ignored-input",
1125
- "adapter-failure",
1126
- "invalid-input",
1127
- "internal-error"
1128
- ]);
1129
-
1130
- // src/errors/index.ts
1131
- var otelHookErrorInfoSchema = z3.strictObject({
1666
+ import { z as z10 } from "zod";
1667
+ var otelHookErrorInfoSchema = z10.strictObject({
1132
1668
  code: otelHookErrorCodeSchema,
1133
1669
  severity: errorSeveritySchema,
1134
1670
  phase: errorPhaseSchema,
1135
1671
  posture: failurePostureSchema,
1136
- retryable: z3.boolean(),
1137
- message: z3.string().min(1).max(512),
1672
+ retryable: z10.boolean(),
1673
+ message: z10.string().min(1).max(512),
1138
1674
  details: attributesSchema.optional(),
1139
1675
  occurredAt: epochMillisSchema.optional()
1140
1676
  });
@@ -1195,11 +1731,11 @@ var createHealthTracker = (subsystem, options = {}) => {
1195
1731
  import { resourceFromAttributes } from "@opentelemetry/resources";
1196
1732
 
1197
1733
  // src/config/resource-attributes.ts
1198
- import { z as z5 } from "zod";
1734
+ import { z as z12 } from "zod";
1199
1735
 
1200
1736
  // src/privacy/policy.ts
1201
- import { z as z4 } from "zod";
1202
- var contentModeSchema = z4.enum(["omit", "mask", "redact", "raw"]);
1737
+ import { z as z11 } from "zod";
1738
+ var contentModeSchema = z11.enum(["omit", "mask", "redact", "raw"]);
1203
1739
  var CONTENT_MODE_DISCLOSURE = Object.freeze({
1204
1740
  omit: "omitted",
1205
1741
  mask: "masked",
@@ -1225,35 +1761,35 @@ var DEFAULT_SECRET_VALUE_PATTERNS = Object.freeze([
1225
1761
  "eyJ[A-Za-z0-9_-]{10,}\\.[A-Za-z0-9_-]{10,}\\.[A-Za-z0-9_-]{10,}",
1226
1762
  "(?:Bearer|Basic)\\s+[A-Za-z0-9._~+/=-]{12,}"
1227
1763
  ]);
1228
- var privacyLimitsSchema = z4.strictObject({
1764
+ var privacyLimitsSchema = z11.strictObject({
1229
1765
  /** Maximum characters of disclosed text per content fact or string value. */
1230
- maxStringLength: z4.number().int().min(0).max(65536),
1766
+ maxStringLength: z11.number().int().min(0).max(65536),
1231
1767
  /** Maximum nesting depth walked when sanitizing structured values. */
1232
- maxDepth: z4.number().int().min(1).max(32),
1768
+ maxDepth: z11.number().int().min(1).max(32),
1233
1769
  /** Maximum array entries retained when sanitizing structured values. */
1234
- maxArrayLength: z4.number().int().min(1).max(4096),
1770
+ maxArrayLength: z11.number().int().min(1).max(4096),
1235
1771
  /** Maximum canonical events emitted per invocation. */
1236
- maxEventsPerInvocation: z4.number().int().min(1).max(1e4),
1772
+ maxEventsPerInvocation: z11.number().int().min(1).max(1e4),
1237
1773
  /** Maximum object keys retained per level when sanitizing. */
1238
- maxObjectKeys: z4.number().int().min(1).max(1024)
1774
+ maxObjectKeys: z11.number().int().min(1).max(1024)
1239
1775
  });
1240
- var privacyPolicySchema = z4.strictObject({
1776
+ var privacyPolicySchema = z11.strictObject({
1241
1777
  contentMode: contentModeSchema,
1242
1778
  /**
1243
1779
  * `raw` mode is refused unless this is also true, so a single mistyped
1244
1780
  * environment variable cannot start exporting prompts.
1245
1781
  */
1246
- allowRawContent: z4.boolean(),
1782
+ allowRawContent: z11.boolean(),
1247
1783
  /**
1248
1784
  * Salt mixed into every hash. A per-deployment salt makes hashes
1249
1785
  * non-correlatable across deployments; an empty salt makes them globally
1250
1786
  * comparable. Both are legitimate; the choice is explicit.
1251
1787
  */
1252
- hashSalt: z4.string().max(256),
1253
- maskCharacter: z4.string().length(1),
1254
- redactionPlaceholder: z4.string().min(1).max(64),
1255
- secretKeyPatterns: z4.array(z4.string().min(1)).max(128).readonly(),
1256
- secretValuePatterns: z4.array(z4.string().min(1)).max(128).readonly(),
1788
+ hashSalt: z11.string().max(256),
1789
+ maskCharacter: z11.string().length(1),
1790
+ redactionPlaceholder: z11.string().min(1).max(64),
1791
+ secretKeyPatterns: z11.array(z11.string().min(1)).max(128).readonly(),
1792
+ secretValuePatterns: z11.array(z11.string().min(1)).max(128).readonly(),
1257
1793
  limits: privacyLimitsSchema
1258
1794
  });
1259
1795
  var DEFAULT_PRIVACY_LIMITS = Object.freeze({
@@ -1319,12 +1855,12 @@ var checkResourceAttributeKey = (key) => {
1319
1855
  }
1320
1856
  return void 0;
1321
1857
  };
1322
- var resourceAttributeValueSchema = z5.union([
1323
- z5.string().max(MAX_RESOURCE_ATTRIBUTE_VALUE_LENGTH),
1324
- z5.number().finite(),
1325
- z5.boolean()
1858
+ var resourceAttributeValueSchema = z12.union([
1859
+ z12.string().max(MAX_RESOURCE_ATTRIBUTE_VALUE_LENGTH),
1860
+ z12.number().finite(),
1861
+ z12.boolean()
1326
1862
  ]);
1327
- var resourceAttributesSchema = z5.record(z5.string(), resourceAttributeValueSchema).superRefine((value, ctx) => {
1863
+ var resourceAttributesSchema = z12.record(z12.string(), resourceAttributeValueSchema).superRefine((value, ctx) => {
1328
1864
  const keys = Object.keys(value);
1329
1865
  if (keys.length > MAX_RESOURCE_ATTRIBUTES) {
1330
1866
  ctx.addIssue({
@@ -1664,8 +2200,8 @@ var sliceCodePoints = (value, max) => {
1664
2200
  }
1665
2201
  return result;
1666
2202
  };
1667
- var logSignalOf = (event, factKind) => {
1668
- switch (event.type) {
2203
+ var logSignalOf = (event2, factKind) => {
2204
+ switch (event2.type) {
1669
2205
  case "session.start":
1670
2206
  case "session.end":
1671
2207
  return "session";
@@ -1683,9 +2219,9 @@ var logSignalOf = (event, factKind) => {
1683
2219
  case "error.raised":
1684
2220
  return "error";
1685
2221
  case "tool.start":
1686
- return toolSignal(event.toolName, event.toolKind);
2222
+ return toolSignal(event2.toolName, event2.toolKind);
1687
2223
  case "tool.end":
1688
- return toolSignal(event.toolName, void 0);
2224
+ return toolSignal(event2.toolName, void 0);
1689
2225
  }
1690
2226
  };
1691
2227
  var toolSignal = (toolName, toolKind) => {
@@ -1744,16 +2280,16 @@ var logSignalsForLifecycleEvents = (lifecycleEvents) => {
1744
2280
  }
1745
2281
  return LOG_SIGNALS.filter((signal) => signals.has(signal));
1746
2282
  };
1747
- var severityFor = (event) => {
1748
- switch (event.type) {
2283
+ var severityFor = (event2) => {
2284
+ switch (event2.type) {
1749
2285
  case "error.raised":
1750
- return event.severity === "error" ? SeverityNumber.ERROR : SeverityNumber.WARN;
2286
+ return event2.severity === "error" ? SeverityNumber.ERROR : SeverityNumber.WARN;
1751
2287
  case "session.end":
1752
- return event.reason === "error" || event.reason === "timeout" ? SeverityNumber.ERROR : event.reason === "aborted" ? SeverityNumber.WARN : SeverityNumber.INFO;
2288
+ return event2.reason === "error" || event2.reason === "timeout" ? SeverityNumber.ERROR : event2.reason === "aborted" ? SeverityNumber.WARN : SeverityNumber.INFO;
1753
2289
  case "generation.end":
1754
2290
  case "tool.end":
1755
2291
  case "subagent.end":
1756
- return event.outcome === "error" || event.outcome === "timeout" ? SeverityNumber.ERROR : event.outcome === "denied" || event.outcome === "cancelled" ? SeverityNumber.WARN : SeverityNumber.INFO;
2292
+ return event2.outcome === "error" || event2.outcome === "timeout" ? SeverityNumber.ERROR : event2.outcome === "denied" || event2.outcome === "cancelled" ? SeverityNumber.WARN : SeverityNumber.INFO;
1757
2293
  default:
1758
2294
  return SeverityNumber.INFO;
1759
2295
  }
@@ -1763,84 +2299,86 @@ var SEVERITY_TEXT = Object.freeze({
1763
2299
  [SeverityNumber.WARN]: "WARN",
1764
2300
  [SeverityNumber.ERROR]: "ERROR"
1765
2301
  });
1766
- var identityAttributes2 = (event, resource, ids) => exportIdentityAttributes(event, resource, ids);
1767
- var eventAttributes = (event) => {
1768
- switch (event.type) {
2302
+ var identityAttributes2 = (event2, resource, ids) => exportIdentityAttributes(event2, resource, ids);
2303
+ var eventAttributes = (event2) => {
2304
+ switch (event2.type) {
1769
2305
  case "session.start":
1770
2306
  return {
1771
- [ATTR_OTELHOOK_SESSION_KIND]: event.sessionKind,
1772
- ...event.agentName === void 0 ? {} : { [ATTR_OTELHOOK_AGENT_NAME2]: event.agentName },
1773
- ...event.agentVersion === void 0 ? {} : { [ATTR_OTELHOOK_AGENT_VERSION2]: event.agentVersion },
1774
- ...event.model === void 0 ? {} : { [ATTR_GEN_AI_REQUEST_MODEL2]: event.model.modelId }
2307
+ [ATTR_OTELHOOK_SESSION_KIND]: event2.sessionKind,
2308
+ ...event2.agentName === void 0 ? {} : { [ATTR_OTELHOOK_AGENT_NAME2]: event2.agentName },
2309
+ ...event2.agentVersion === void 0 ? {} : { [ATTR_OTELHOOK_AGENT_VERSION2]: event2.agentVersion },
2310
+ ...event2.model === void 0 ? {} : { [ATTR_GEN_AI_REQUEST_MODEL2]: event2.model.modelId },
2311
+ ...targetAttributes(event2)
1775
2312
  };
1776
2313
  case "session.end":
1777
2314
  return {
1778
- [ATTR_OTELHOOK_OUTCOME2]: event.reason,
1779
- ...usageAttributes2(event.usage)
2315
+ [ATTR_OTELHOOK_OUTCOME2]: event2.reason,
2316
+ ...usageAttributes2(event2.usage)
1780
2317
  };
1781
2318
  case "prompt.submitted":
1782
2319
  return {
1783
- [ATTR_OTELHOOK_PROMPT_SOURCE]: event.promptSource,
1784
- ...event.turnIndex === void 0 ? {} : { [ATTR_OTELHOOK_PROMPT_TURN_INDEX]: event.turnIndex }
2320
+ [ATTR_OTELHOOK_PROMPT_SOURCE]: event2.promptSource,
2321
+ ...event2.turnIndex === void 0 ? {} : { [ATTR_OTELHOOK_PROMPT_TURN_INDEX]: event2.turnIndex },
2322
+ ...targetAttributes(event2)
1785
2323
  };
1786
2324
  case "generation.start":
1787
2325
  return {
1788
2326
  [ATTR_GEN_AI_OPERATION_NAME2]: "chat",
1789
- [ATTR_OTELHOOK_GENERATION_ID2]: event.generationId,
1790
- [ATTR_GEN_AI_REQUEST_MODEL2]: event.model.modelId,
1791
- ...event.model.vendor === void 0 ? {} : { [ATTR_GEN_AI_SYSTEM2]: event.model.vendor }
2327
+ [ATTR_OTELHOOK_GENERATION_ID2]: event2.generationId,
2328
+ [ATTR_GEN_AI_REQUEST_MODEL2]: event2.model.modelId,
2329
+ ...event2.model.vendor === void 0 ? {} : { [ATTR_GEN_AI_SYSTEM2]: event2.model.vendor }
1792
2330
  };
1793
2331
  case "generation.end":
1794
2332
  return {
1795
2333
  [ATTR_GEN_AI_OPERATION_NAME2]: "chat",
1796
- [ATTR_OTELHOOK_GENERATION_ID2]: event.generationId,
1797
- [ATTR_GEN_AI_RESPONSE_MODEL2]: event.model.modelId,
1798
- ...event.model.vendor === void 0 ? {} : { [ATTR_GEN_AI_SYSTEM2]: event.model.vendor },
1799
- [ATTR_OTELHOOK_OUTCOME2]: event.outcome,
1800
- ...event.stopReason === void 0 ? {} : { [ATTR_OTELHOOK_STOP_REASON]: event.stopReason },
1801
- ...usageAttributes2(event.usage)
2334
+ [ATTR_OTELHOOK_GENERATION_ID2]: event2.generationId,
2335
+ [ATTR_GEN_AI_RESPONSE_MODEL2]: event2.model.modelId,
2336
+ ...event2.model.vendor === void 0 ? {} : { [ATTR_GEN_AI_SYSTEM2]: event2.model.vendor },
2337
+ [ATTR_OTELHOOK_OUTCOME2]: event2.outcome,
2338
+ ...event2.stopReason === void 0 ? {} : { [ATTR_OTELHOOK_STOP_REASON]: event2.stopReason },
2339
+ ...usageAttributes2(event2.usage)
1802
2340
  };
1803
2341
  case "tool.start":
1804
2342
  return {
1805
- [ATTR_GEN_AI_TOOL_NAME2]: event.toolName,
1806
- [ATTR_GEN_AI_TOOL_CALL_ID2]: event.toolCallId,
1807
- [ATTR_OTELHOOK_TOOL_KIND2]: event.toolKind,
1808
- ...event.generationId === void 0 ? {} : { [ATTR_OTELHOOK_GENERATION_ID2]: event.generationId },
1809
- ...targetAttributes(event)
2343
+ [ATTR_GEN_AI_TOOL_NAME2]: event2.toolName,
2344
+ [ATTR_GEN_AI_TOOL_CALL_ID2]: event2.toolCallId,
2345
+ [ATTR_OTELHOOK_TOOL_KIND2]: event2.toolKind,
2346
+ ...event2.generationId === void 0 ? {} : { [ATTR_OTELHOOK_GENERATION_ID2]: event2.generationId },
2347
+ ...targetAttributes(event2)
1810
2348
  };
1811
2349
  case "tool.end":
1812
2350
  return {
1813
- [ATTR_GEN_AI_TOOL_NAME2]: event.toolName,
1814
- [ATTR_GEN_AI_TOOL_CALL_ID2]: event.toolCallId,
1815
- [ATTR_OTELHOOK_OUTCOME2]: event.outcome,
1816
- ...event.permissionDecision === void 0 ? {} : { [ATTR_OTELHOOK_TOOL_PERMISSION]: event.permissionDecision },
1817
- ...targetAttributes(event)
2351
+ [ATTR_GEN_AI_TOOL_NAME2]: event2.toolName,
2352
+ [ATTR_GEN_AI_TOOL_CALL_ID2]: event2.toolCallId,
2353
+ [ATTR_OTELHOOK_OUTCOME2]: event2.outcome,
2354
+ ...event2.permissionDecision === void 0 ? {} : { [ATTR_OTELHOOK_TOOL_PERMISSION]: event2.permissionDecision },
2355
+ ...targetAttributes(event2)
1818
2356
  };
1819
2357
  case "subagent.start":
1820
2358
  return {
1821
- [ATTR_OTELHOOK_DELEGATION_DEPTH2]: event.delegationDepth,
1822
- ...event.subagentType === void 0 ? {} : { [ATTR_OTELHOOK_SUBAGENT_TYPE]: event.subagentType },
1823
- ...event.model === void 0 ? {} : { [ATTR_GEN_AI_REQUEST_MODEL2]: event.model.modelId }
2359
+ [ATTR_OTELHOOK_DELEGATION_DEPTH2]: event2.delegationDepth,
2360
+ ...event2.subagentType === void 0 ? {} : { [ATTR_OTELHOOK_SUBAGENT_TYPE]: event2.subagentType },
2361
+ ...event2.model === void 0 ? {} : { [ATTR_GEN_AI_REQUEST_MODEL2]: event2.model.modelId }
1824
2362
  };
1825
2363
  case "subagent.end":
1826
2364
  return {
1827
- [ATTR_OTELHOOK_OUTCOME2]: event.outcome,
1828
- ...usageAttributes2(event.usage)
2365
+ [ATTR_OTELHOOK_OUTCOME2]: event2.outcome,
2366
+ ...usageAttributes2(event2.usage)
1829
2367
  };
1830
2368
  case "compaction.performed":
1831
2369
  return {
1832
- [ATTR_OTELHOOK_COMPACTION_TRIGGER2]: event.trigger,
1833
- ...event.contextTokensBefore === void 0 ? {} : { [ATTR_OTELHOOK_CONTEXT_TOKENS_BEFORE]: event.contextTokensBefore },
1834
- ...event.contextTokensAfter === void 0 ? {} : { [ATTR_OTELHOOK_CONTEXT_TOKENS_AFTER]: event.contextTokensAfter },
1835
- ...event.droppedMessageCount === void 0 ? {} : { [ATTR_OTELHOOK_DROPPED_MESSAGES]: event.droppedMessageCount },
1836
- ...usageAttributes2(event.usage)
2370
+ [ATTR_OTELHOOK_COMPACTION_TRIGGER2]: event2.trigger,
2371
+ ...event2.contextTokensBefore === void 0 ? {} : { [ATTR_OTELHOOK_CONTEXT_TOKENS_BEFORE]: event2.contextTokensBefore },
2372
+ ...event2.contextTokensAfter === void 0 ? {} : { [ATTR_OTELHOOK_CONTEXT_TOKENS_AFTER]: event2.contextTokensAfter },
2373
+ ...event2.droppedMessageCount === void 0 ? {} : { [ATTR_OTELHOOK_DROPPED_MESSAGES]: event2.droppedMessageCount },
2374
+ ...usageAttributes2(event2.usage)
1837
2375
  };
1838
2376
  case "error.raised":
1839
2377
  return {
1840
- [ATTR_ERROR_TYPE2]: event.errorCode,
1841
- [ATTR_OTELHOOK_ERROR_PHASE]: event.phase,
1842
- [ATTR_OTELHOOK_ERROR_RETRYABLE]: event.retryable,
1843
- [ATTR_OTELHOOK_ERROR_SEVERITY]: event.severity
2378
+ [ATTR_ERROR_TYPE2]: event2.errorCode,
2379
+ [ATTR_OTELHOOK_ERROR_PHASE]: event2.phase,
2380
+ [ATTR_OTELHOOK_ERROR_RETRYABLE]: event2.retryable,
2381
+ [ATTR_OTELHOOK_ERROR_SEVERITY]: event2.severity
1844
2382
  };
1845
2383
  }
1846
2384
  };
@@ -1851,20 +2389,20 @@ var usageAttributes2 = (usage) => usage === void 0 ? {} : {
1851
2389
  [ATTR_GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS2]: usage.cacheCreationInputTokens,
1852
2390
  ...usageTemporalityAttributes(usage)
1853
2391
  };
1854
- var contentFactsOf = (event) => {
1855
- switch (event.type) {
2392
+ var contentFactsOf = (event2) => {
2393
+ switch (event2.type) {
1856
2394
  case "prompt.submitted":
1857
- return event.content === void 0 ? [] : [event.content];
2395
+ return event2.content === void 0 ? [] : [event2.content];
1858
2396
  case "generation.start":
1859
- return event.inputContent ?? [];
2397
+ return event2.inputContent ?? [];
1860
2398
  case "generation.end":
1861
- return event.outputContent ?? [];
2399
+ return event2.outputContent ?? [];
1862
2400
  case "tool.start":
1863
- return event.input === void 0 ? [] : [event.input];
2401
+ return event2.input === void 0 ? [] : [event2.input];
1864
2402
  case "tool.end":
1865
- return event.output === void 0 ? [] : [event.output];
2403
+ return event2.output === void 0 ? [] : [event2.output];
1866
2404
  case "error.raised":
1867
- return event.message === void 0 ? [] : [event.message];
2405
+ return event2.message === void 0 ? [] : [event2.message];
1868
2406
  default:
1869
2407
  return [];
1870
2408
  }
@@ -1939,8 +2477,8 @@ var canonicalEventsToLogRecords = (events, options) => {
1939
2477
  });
1940
2478
  const records = [];
1941
2479
  let droppedFacts = 0;
1942
- for (const event of events) {
1943
- const identity = identities.get(event.eventId);
2480
+ for (const event2 of events) {
2481
+ const identity = identities.get(event2.eventId);
1944
2482
  if (identity === void 0) {
1945
2483
  continue;
1946
2484
  }
@@ -1950,8 +2488,8 @@ var canonicalEventsToLogRecords = (events, options) => {
1950
2488
  traceFlags: TraceFlags2.SAMPLED,
1951
2489
  isRemote: false
1952
2490
  };
1953
- const shared = eventAttributes(event);
1954
- const facts = contentFactsOf(event);
2491
+ const shared = eventAttributes(event2);
2492
+ const facts = contentFactsOf(event2);
1955
2493
  if (facts.length === 0) {
1956
2494
  if (records.length >= MAX_LOG_RECORDS_PER_BATCH) {
1957
2495
  droppedFacts += 1;
@@ -1959,9 +2497,9 @@ var canonicalEventsToLogRecords = (events, options) => {
1959
2497
  }
1960
2498
  records.push(
1961
2499
  buildRecord({
1962
- event,
1963
- signal: logSignalOf(event),
1964
- attributes: event.type === "generation.end" ? { ...shared, [ATTR_CONTENT_KIND]: "response", [ATTR_CONTENT_DISCLOSURE]: "metadata_only" } : shared,
2500
+ event: event2,
2501
+ signal: logSignalOf(event2),
2502
+ attributes: event2.type === "generation.end" ? { ...shared, [ATTR_CONTENT_KIND]: "response", [ATTR_CONTENT_DISCLOSURE]: "metadata_only" } : shared,
1965
2503
  spanContext,
1966
2504
  ...identity.parentSpanId === void 0 ? {} : { parentSpanId: identity.parentSpanId },
1967
2505
  resource: options.resource,
@@ -1980,8 +2518,8 @@ var canonicalEventsToLogRecords = (events, options) => {
1980
2518
  const body = discloseBody(fact, content);
1981
2519
  records.push(
1982
2520
  buildRecord({
1983
- event,
1984
- signal: logSignalOf(event, fact.kind),
2521
+ event: event2,
2522
+ signal: logSignalOf(event2, fact.kind),
1985
2523
  attributes: { ...shared, ...contentAttributes(fact, body) },
1986
2524
  ..."text" in body ? { body: body.text } : {},
1987
2525
  spanContext,