@osfactory/otel-hook 0.8.0 → 0.10.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 (52) hide show
  1. package/README.md +159 -2
  2. package/dist/{adapter-BJiz6lqM.d.ts → adapter-B9RwW6TO.d.ts} +14 -2
  3. package/dist/cli.js +2514 -1238
  4. package/dist/cli.js.map +1 -1
  5. package/dist/config.d.ts +5 -2
  6. package/dist/config.js +479 -169
  7. package/dist/config.js.map +1 -1
  8. package/dist/destinations-DWOkVxV1.d.ts +169 -0
  9. package/dist/diagnostics.d.ts +8 -0
  10. package/dist/diagnostics.js +2 -1
  11. package/dist/diagnostics.js.map +1 -1
  12. package/dist/{events-B3MHoJTD.d.ts → events-CSD_YiJ2.d.ts} +2 -0
  13. package/dist/{otlp-log-sink-zuHojHSP.d.ts → export-destinations-lORbe25J.d.ts} +241 -9
  14. package/dist/{filesystem-store-r-nNA3BA.d.ts → filesystem-store-DX3dGIgu.d.ts} +1 -1
  15. package/dist/{hook-Dh8OO4Wa.d.ts → hook-BAxXoKsp.d.ts} +10 -5
  16. package/dist/index.d.ts +15 -14
  17. package/dist/index.js +1936 -730
  18. package/dist/index.js.map +1 -1
  19. package/dist/install.d.ts +4 -4
  20. package/dist/install.js +31 -2
  21. package/dist/install.js.map +1 -1
  22. package/dist/integration.d.ts +37 -12
  23. package/dist/integration.js +1942 -617
  24. package/dist/integration.js.map +1 -1
  25. package/dist/lifecycle.d.ts +3 -3
  26. package/dist/lifecycle.js +8 -1
  27. package/dist/lifecycle.js.map +1 -1
  28. package/dist/{memory-Bl9ANVff.d.ts → memory-aJilVG4R.d.ts} +2 -2
  29. package/dist/model.d.ts +1 -1
  30. package/dist/model.js +7 -0
  31. package/dist/model.js.map +1 -1
  32. package/dist/{payload-Ci8_ERm6.d.ts → payload-D7gc0-WQ.d.ts} +41 -2
  33. package/dist/{ports-n7KFOpKo.d.ts → ports-plO5MKrY.d.ts} +63 -2
  34. package/dist/providers.d.ts +146 -10
  35. package/dist/providers.js +397 -13
  36. package/dist/providers.js.map +1 -1
  37. package/dist/{registry-CIVvRlVK.d.ts → registry-C7XO4DzD.d.ts} +2 -2
  38. package/dist/runtime.d.ts +8 -8
  39. package/dist/runtime.js +1426 -1163
  40. package/dist/runtime.js.map +1 -1
  41. package/dist/{schema-Cn0-xz8L.d.ts → schema-CHb3GU1r.d.ts} +98 -3
  42. package/dist/{semconv-fPRb-dpU.d.ts → semconv-Dw7gcQcg.d.ts} +1 -1
  43. package/dist/state.d.ts +4 -4
  44. package/dist/state.js +607 -39
  45. package/dist/state.js.map +1 -1
  46. package/dist/telemetry.d.ts +23 -66
  47. package/dist/telemetry.js +637 -34
  48. package/dist/telemetry.js.map +1 -1
  49. package/dist/testing.d.ts +10 -8
  50. package/dist/testing.js +868 -560
  51. package/dist/testing.js.map +1 -1
  52. package/package.json +1 -1
@@ -1,3 +1,532 @@
1
+ // src/config/schema.ts
2
+ import { z as z5 } from "zod";
3
+
4
+ // src/model/primitives.ts
5
+ import { z } from "zod";
6
+ var MAX_IDENTIFIER_LENGTH = 256;
7
+ var MAX_ATTRIBUTE_STRING_LENGTH = 4096;
8
+ var MAX_ATTRIBUTE_ARRAY_LENGTH = 128;
9
+ var nonEmptyStringSchema = z.string().min(1).max(MAX_IDENTIFIER_LENGTH);
10
+ var epochMillisSchema = z.number().int().min(0).max(864e13);
11
+ var durationMillisSchema = z.number().min(0).finite();
12
+ var tokenCountSchema = z.number().int().min(0);
13
+ var sequenceNumberSchema = z.number().int().min(0);
14
+ var brandedIdSchema = () => z.string().min(1).max(MAX_IDENTIFIER_LENGTH);
15
+ var invocationIdSchema = brandedIdSchema().brand();
16
+ var sessionIdSchema = brandedIdSchema().brand();
17
+ var eventIdSchema = brandedIdSchema().brand();
18
+ var WORKSPACE_ID_PATTERN = /^[a-z][a-z0-9]{0,15}:[A-Za-z0-9_-]{8,128}$/;
19
+ var workspaceIdSchema = z.string().regex(WORKSPACE_ID_PATTERN, "workspace id must be an opaque `<scheme>:<token>` handle").brand();
20
+ var PROVIDER_ID_PATTERN = /^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/;
21
+ var providerIdSchema = z.string().min(1).max(64).regex(PROVIDER_ID_PATTERN, "provider id must be lowercase and hyphenated").brand();
22
+ var UNKNOWN_PROVIDER_ID = "unknown";
23
+ var resolvedProviderIdSchema = z.union([
24
+ providerIdSchema,
25
+ z.literal(UNKNOWN_PROVIDER_ID)
26
+ ]);
27
+ var attributePrimitiveSchema = z.union([
28
+ z.string().max(MAX_ATTRIBUTE_STRING_LENGTH),
29
+ z.number().finite(),
30
+ z.boolean()
31
+ ]);
32
+ var attributeValueSchema = z.union([
33
+ attributePrimitiveSchema,
34
+ z.array(attributePrimitiveSchema).max(MAX_ATTRIBUTE_ARRAY_LENGTH)
35
+ ]);
36
+ var attributesSchema = z.record(z.string().min(1).max(MAX_IDENTIFIER_LENGTH), attributeValueSchema);
37
+ var detectionConfidenceSchema = z.enum(["none", "weak", "strong", "exact"]);
38
+ var DETECTION_CONFIDENCE_RANK = Object.freeze({
39
+ none: 0,
40
+ weak: 1,
41
+ strong: 2,
42
+ exact: 3
43
+ });
44
+ var sourceTransportSchema = z.enum([
45
+ "hook-stdin",
46
+ "cli-argument",
47
+ "library-call",
48
+ "test-fixture"
49
+ ]);
50
+
51
+ // src/privacy/policy.ts
52
+ import { z as z2 } from "zod";
53
+ var contentModeSchema = z2.enum(["omit", "mask", "redact", "raw"]);
54
+ var CONTENT_MODE_DISCLOSURE = Object.freeze({
55
+ omit: "omitted",
56
+ mask: "masked",
57
+ redact: "redacted",
58
+ raw: "raw"
59
+ });
60
+ var DEFAULT_SECRET_KEY_PATTERNS = Object.freeze([
61
+ "(^|[._-])(secret|secrets)([._-]|$)",
62
+ "(^|[._-])(token|tokens)([._-]|$)",
63
+ "(^|[._-])(password|passwd|pwd)([._-]|$)",
64
+ "(^|[._-])(credential|credentials)([._-]|$)",
65
+ "(^|[._-])(api[._-]?key|apikey|access[._-]?key|secret[._-]?key|private[._-]?key)([._-]|$)",
66
+ "(^|[._-])(authorization|auth[._-]?header|bearer)([._-]|$)",
67
+ "(^|[._-])(cookie|set[._-]?cookie)([._-]|$)",
68
+ "(^|[._-])(signature|sig)([._-]|$)"
69
+ ]);
70
+ var DEFAULT_SECRET_VALUE_PATTERNS = Object.freeze([
71
+ "AKIA[0-9A-Z]{16}",
72
+ "sk-[A-Za-z0-9_-]{16,}",
73
+ "gh[pousr]_[A-Za-z0-9]{16,}",
74
+ "xox[abprs]-[A-Za-z0-9-]{10,}",
75
+ "-----BEGIN[A-Z ]*PRIVATE KEY-----",
76
+ "eyJ[A-Za-z0-9_-]{10,}\\.[A-Za-z0-9_-]{10,}\\.[A-Za-z0-9_-]{10,}",
77
+ "(?:Bearer|Basic)\\s+[A-Za-z0-9._~+/=-]{12,}"
78
+ ]);
79
+ var privacyLimitsSchema = z2.strictObject({
80
+ /** Maximum characters of disclosed text per content fact or string value. */
81
+ maxStringLength: z2.number().int().min(0).max(65536),
82
+ /** Maximum nesting depth walked when sanitizing structured values. */
83
+ maxDepth: z2.number().int().min(1).max(32),
84
+ /** Maximum array entries retained when sanitizing structured values. */
85
+ maxArrayLength: z2.number().int().min(1).max(4096),
86
+ /** Maximum canonical events emitted per invocation. */
87
+ maxEventsPerInvocation: z2.number().int().min(1).max(1e4),
88
+ /** Maximum object keys retained per level when sanitizing. */
89
+ maxObjectKeys: z2.number().int().min(1).max(1024)
90
+ });
91
+ var privacyPolicySchema = z2.strictObject({
92
+ contentMode: contentModeSchema,
93
+ /**
94
+ * `raw` mode is refused unless this is also true, so a single mistyped
95
+ * environment variable cannot start exporting prompts.
96
+ */
97
+ allowRawContent: z2.boolean(),
98
+ /**
99
+ * Salt mixed into every hash. A per-deployment salt makes hashes
100
+ * non-correlatable across deployments; an empty salt makes them globally
101
+ * comparable. Both are legitimate; the choice is explicit.
102
+ */
103
+ hashSalt: z2.string().max(256),
104
+ maskCharacter: z2.string().length(1),
105
+ redactionPlaceholder: z2.string().min(1).max(64),
106
+ secretKeyPatterns: z2.array(z2.string().min(1)).max(128).readonly(),
107
+ secretValuePatterns: z2.array(z2.string().min(1)).max(128).readonly(),
108
+ limits: privacyLimitsSchema
109
+ });
110
+ var DEFAULT_PRIVACY_LIMITS = Object.freeze({
111
+ maxStringLength: 1024,
112
+ maxDepth: 6,
113
+ maxArrayLength: 64,
114
+ maxEventsPerInvocation: 512,
115
+ maxObjectKeys: 128
116
+ });
117
+ var DEFAULT_PRIVACY_POLICY = Object.freeze({
118
+ contentMode: "omit",
119
+ allowRawContent: false,
120
+ hashSalt: "",
121
+ maskCharacter: "*",
122
+ redactionPlaceholder: "[redacted]",
123
+ secretKeyPatterns: DEFAULT_SECRET_KEY_PATTERNS,
124
+ secretValuePatterns: DEFAULT_SECRET_VALUE_PATTERNS,
125
+ limits: DEFAULT_PRIVACY_LIMITS
126
+ });
127
+ var resolvePrivacyPolicy = (policy) => {
128
+ const parsed = privacyPolicySchema.parse(policy);
129
+ if (parsed.contentMode === "raw" && !parsed.allowRawContent) {
130
+ return {
131
+ policy: { ...parsed, contentMode: "omit" },
132
+ notes: ["contentMode=raw downgraded to omit because allowRawContent is false"]
133
+ };
134
+ }
135
+ return { policy: parsed, notes: [] };
136
+ };
137
+
138
+ // src/config/destinations.ts
139
+ import { z as z3 } from "zod";
140
+
141
+ // src/config/header-value.ts
142
+ var isUnsafeHeaderValue = (value) => [...value].some((char) => {
143
+ const code = char.codePointAt(0) ?? 0;
144
+ return code < 32 && code !== 9 || code === 127 || code > 255;
145
+ });
146
+
147
+ // src/config/otlp-headers.ts
148
+ var MAX_OTLP_HEADERS = 32;
149
+ var OTLP_HEADER_VARIABLES = Object.freeze({
150
+ generic: "OTEL_EXPORTER_OTLP_HEADERS",
151
+ traces: "OTEL_EXPORTER_OTLP_TRACES_HEADERS",
152
+ logs: "OTEL_EXPORTER_OTLP_LOGS_HEADERS"
153
+ });
154
+
155
+ // src/config/destinations.ts
156
+ var DEFAULT_DESTINATION_NAME = "default";
157
+ var DESTINATION_NAME_PATTERN = /^[a-z0-9][a-z0-9_-]{0,62}$/;
158
+ var MAX_EXPORT_DESTINATIONS = 16;
159
+ var MAX_DESTINATION_HEADERS = MAX_OTLP_HEADERS;
160
+ var HEADER_ENV_REFERENCE_PREFIX = "env:";
161
+ var HEADER_NAME_PATTERN = /^[A-Za-z0-9!#$%&'*+.^_`|~-]{1,128}$/;
162
+ var ENV_VARIABLE_NAME_PATTERN = /^[A-Za-z_][A-Za-z0-9_]{0,127}$/;
163
+ var MAX_HEADER_VALUE_LENGTH = 8192;
164
+ var exportSignalSchema = z3.enum(["traces", "logs"]);
165
+ var headerValueSchema = z3.string().min(1).max(MAX_HEADER_VALUE_LENGTH).refine(
166
+ (value) => !isUnsafeHeaderValue(value),
167
+ "header values may not contain line breaks, control characters, or characters beyond Latin-1"
168
+ ).refine(
169
+ (value) => !value.startsWith(HEADER_ENV_REFERENCE_PREFIX) || ENV_VARIABLE_NAME_PATTERN.test(value.slice(HEADER_ENV_REFERENCE_PREFIX.length)),
170
+ "an env: header reference must name an environment variable, e.g. env:COLLECTOR_TOKEN"
171
+ );
172
+ var endpointSchema = z3.string().url().max(2048);
173
+ var exportDestinationSchema = z3.strictObject({
174
+ /** Unique, lowercase, filesystem-safe. `default` is reserved for the single-endpoint settings. */
175
+ name: z3.string().regex(DESTINATION_NAME_PATTERN, "destination names are lowercase letters, digits, _ and -"),
176
+ /** Default true. A disabled destination is neither sent to nor drained. */
177
+ enabled: z3.boolean().optional(),
178
+ /**
179
+ * Traces URL, with the same meaning as `exporter.endpoint`: the logs URL is
180
+ * derived from it (`/v1/traces` becomes `/v1/logs`) unless `logsEndpoint` is set.
181
+ */
182
+ endpoint: endpointSchema.optional(),
183
+ /** Per-signal override of `endpoint` for traces. */
184
+ tracesEndpoint: endpointSchema.optional(),
185
+ /** Per-signal override of the derived logs URL. */
186
+ logsEndpoint: endpointSchema.optional(),
187
+ /** Defaults to `exporter.protocol`. */
188
+ protocol: z3.enum(["http/protobuf", "http/json", "none"]).optional(),
189
+ /**
190
+ * Header name to value. A value of the form `env:NAME` is read from that
191
+ * environment variable at send time, so a credential never has to be written
192
+ * into the file. Values never appear in a snapshot, a diagnostic, or `doctor`.
193
+ */
194
+ headers: z3.record(z3.string().regex(HEADER_NAME_PATTERN, "not a valid header name"), headerValueSchema).refine(
195
+ (headers) => Object.keys(headers).length <= MAX_DESTINATION_HEADERS,
196
+ `at most ${String(MAX_DESTINATION_HEADERS)} headers per destination`
197
+ ).optional(),
198
+ /**
199
+ * Which signals this destination receives. Default: both. The logs signal is
200
+ * still governed by `exporter.logs.enabled`, which stays the one opt-in for a
201
+ * second stream leaving the host.
202
+ */
203
+ signals: z3.array(exportSignalSchema).min(1).max(2).readonly().optional()
204
+ }).refine(
205
+ (destination) => destination.endpoint !== void 0 || destination.tracesEndpoint !== void 0 || destination.logsEndpoint !== void 0,
206
+ "a destination needs an endpoint, or a tracesEndpoint / logsEndpoint"
207
+ );
208
+ var exportDestinationsSchema = z3.array(exportDestinationSchema).max(MAX_EXPORT_DESTINATIONS).readonly().superRefine((destinations, context) => {
209
+ const seen = /* @__PURE__ */ new Set();
210
+ destinations.forEach((destination, index) => {
211
+ if (destination.name === DEFAULT_DESTINATION_NAME) {
212
+ context.addIssue({
213
+ code: "custom",
214
+ path: [index, "name"],
215
+ message: 'the name "default" is reserved for exporter.endpoint and the OTEL_EXPORTER_OTLP_* variables'
216
+ });
217
+ }
218
+ if (seen.has(destination.name)) {
219
+ context.addIssue({
220
+ code: "custom",
221
+ path: [index, "name"],
222
+ message: `duplicate destination name "${destination.name}"`
223
+ });
224
+ }
225
+ seen.add(destination.name);
226
+ });
227
+ });
228
+ var spoolPolicySchema = z3.strictObject({
229
+ /** Total bytes of queued batches. Default 16 MiB. */
230
+ maxBytes: z3.number().int().min(1024).max(1073741824),
231
+ /** A batch older than this is dropped instead of sent. Default 72 hours. */
232
+ maxAgeMillis: z3.number().int().min(1e3).max(30 * 24 * 60 * 60 * 1e3),
233
+ /** Number of queued batches. Default 500. */
234
+ maxBatches: z3.number().int().min(1).max(65536)
235
+ });
236
+ var DEFAULT_SPOOL_POLICY = Object.freeze({
237
+ maxBytes: 16 * 1024 * 1024,
238
+ maxAgeMillis: 72 * 60 * 60 * 1e3,
239
+ maxBatches: 500
240
+ });
241
+ var effectiveSpoolPolicy = (exporter) => ({
242
+ maxBytes: exporter.spool?.maxBytes ?? DEFAULT_SPOOL_POLICY.maxBytes,
243
+ maxAgeMillis: exporter.spool?.maxAgeMillis ?? DEFAULT_SPOOL_POLICY.maxAgeMillis,
244
+ maxBatches: exporter.spool?.maxBatches ?? DEFAULT_SPOOL_POLICY.maxBatches
245
+ });
246
+ var legacyDestination = (exporter) => ({
247
+ name: DEFAULT_DESTINATION_NAME,
248
+ source: "exporter",
249
+ protocol: exporter.protocol,
250
+ ...exporter.endpoint === void 0 ? {} : { endpoint: exporter.endpoint },
251
+ ...exporter.logs.endpoint === void 0 ? {} : { logsEndpoint: exporter.logs.endpoint },
252
+ signals: { traces: true, logs: exporter.logs.enabled },
253
+ headers: {}
254
+ });
255
+ var hasConfiguredDestinations = (exporter) => exporter.destinations !== void 0 && exporter.destinations.length > 0;
256
+ var resolveExportDestinations = (exporter) => {
257
+ if (!hasConfiguredDestinations(exporter)) {
258
+ return [legacyDestination(exporter)];
259
+ }
260
+ const resolved = [];
261
+ if (exporter.endpoint !== void 0 || exporter.logs.endpoint !== void 0) {
262
+ resolved.push(legacyDestination(exporter));
263
+ }
264
+ for (const destination of exporter.destinations ?? []) {
265
+ if (destination.enabled === false) {
266
+ continue;
267
+ }
268
+ const signals = destination.signals ?? exportSignalSchema.options;
269
+ resolved.push({
270
+ name: destination.name,
271
+ source: "destinations",
272
+ protocol: destination.protocol ?? exporter.protocol,
273
+ ...destination.endpoint === void 0 ? {} : { endpoint: destination.endpoint },
274
+ ...destination.tracesEndpoint === void 0 ? {} : { tracesEndpoint: destination.tracesEndpoint },
275
+ ...destination.logsEndpoint === void 0 ? {} : { logsEndpoint: destination.logsEndpoint },
276
+ signals: {
277
+ traces: signals.includes("traces"),
278
+ logs: exporter.logs.enabled && signals.includes("logs")
279
+ },
280
+ headers: { ...destination.headers ?? {} }
281
+ });
282
+ }
283
+ return resolved;
284
+ };
285
+ var parseHeaderValueReference = (value) => value.startsWith(HEADER_ENV_REFERENCE_PREFIX) ? { kind: "env", variable: value.slice(HEADER_ENV_REFERENCE_PREFIX.length) } : { kind: "literal" };
286
+ var resolveDestinationHeaders = (headers, environment) => {
287
+ const values = {};
288
+ const missing = [];
289
+ for (const [name, value] of Object.entries(headers)) {
290
+ const reference = parseHeaderValueReference(value);
291
+ if (reference.kind === "literal") {
292
+ values[name] = value;
293
+ continue;
294
+ }
295
+ const resolved = environment?.[reference.variable];
296
+ if (resolved === void 0 || resolved === "") {
297
+ missing.push(reference.variable);
298
+ continue;
299
+ }
300
+ values[name] = resolved;
301
+ }
302
+ return { values, missingVariables: [...new Set(missing)].sort() };
303
+ };
304
+
305
+ // src/config/resource-attributes.ts
306
+ import { z as z4 } from "zod";
307
+ var MAX_RESOURCE_ATTRIBUTES = 64;
308
+ var MAX_RESOURCE_ATTRIBUTE_KEY_LENGTH = 255;
309
+ var MAX_RESOURCE_ATTRIBUTE_VALUE_LENGTH = 2048;
310
+ var RESOURCE_ATTRIBUTE_KEY_PATTERN = /^[A-Za-z][A-Za-z0-9_./-]*$/;
311
+ var RESERVED_RESOURCE_ATTRIBUTE_KEYS = Object.freeze([
312
+ "service.name",
313
+ "service.namespace"
314
+ ]);
315
+ var isReservedResourceAttributeKey = (key) => RESERVED_RESOURCE_ATTRIBUTE_KEYS.includes(key.toLowerCase());
316
+ var SECRET_KEY_MATCHERS = Object.freeze(
317
+ DEFAULT_SECRET_KEY_PATTERNS.flatMap((source) => {
318
+ try {
319
+ return [new RegExp(source, "i")];
320
+ } catch {
321
+ return [];
322
+ }
323
+ })
324
+ );
325
+ var isSecretResourceAttributeKey = (key) => SECRET_KEY_MATCHERS.some((pattern) => pattern.test(key));
326
+ var RESOURCE_ATTRIBUTE_KEY_REJECTION_DETAIL = Object.freeze({
327
+ empty: "resource attribute key is empty",
328
+ "too-long": `resource attribute key exceeds ${String(MAX_RESOURCE_ATTRIBUTE_KEY_LENGTH)} characters`,
329
+ malformed: "resource attribute key must start with a letter and use only letters, digits, and `_`, `.`, `-`, `/`",
330
+ reserved: "service.name and service.namespace are exporter policy (--service-name / OTEL_HOOK_SERVICE_NAME), not resource attributes",
331
+ "secret-like": "resource attribute key matches a secret-name pattern, so it is never exported"
332
+ });
333
+ var checkResourceAttributeKey = (key) => {
334
+ if (key.length === 0) {
335
+ return "empty";
336
+ }
337
+ if (key.length > MAX_RESOURCE_ATTRIBUTE_KEY_LENGTH) {
338
+ return "too-long";
339
+ }
340
+ if (!RESOURCE_ATTRIBUTE_KEY_PATTERN.test(key)) {
341
+ return "malformed";
342
+ }
343
+ if (isReservedResourceAttributeKey(key)) {
344
+ return "reserved";
345
+ }
346
+ if (isSecretResourceAttributeKey(key)) {
347
+ return "secret-like";
348
+ }
349
+ return void 0;
350
+ };
351
+ var resourceAttributeValueSchema = z4.union([
352
+ z4.string().max(MAX_RESOURCE_ATTRIBUTE_VALUE_LENGTH),
353
+ z4.number().finite(),
354
+ z4.boolean()
355
+ ]);
356
+ var resourceAttributesSchema = z4.record(z4.string(), resourceAttributeValueSchema).superRefine((value, ctx) => {
357
+ const keys = Object.keys(value);
358
+ if (keys.length > MAX_RESOURCE_ATTRIBUTES) {
359
+ ctx.addIssue({
360
+ code: "custom",
361
+ message: `at most ${String(MAX_RESOURCE_ATTRIBUTES)} resource attributes are accepted`
362
+ });
363
+ }
364
+ for (const key of keys) {
365
+ const rejection = checkResourceAttributeKey(key);
366
+ if (rejection !== void 0) {
367
+ ctx.addIssue({
368
+ code: "custom",
369
+ path: [key],
370
+ message: RESOURCE_ATTRIBUTE_KEY_REJECTION_DETAIL[rejection]
371
+ });
372
+ }
373
+ }
374
+ }).readonly();
375
+ var EMPTY_RESOURCE_ATTRIBUTES = Object.freeze({});
376
+ var sanitizeResourceAttributes = (attributes) => {
377
+ const safe = {};
378
+ for (const [key, value] of Object.entries(attributes)) {
379
+ if (checkResourceAttributeKey(key) !== void 0) {
380
+ continue;
381
+ }
382
+ if (Object.keys(safe).length >= MAX_RESOURCE_ATTRIBUTES) {
383
+ break;
384
+ }
385
+ safe[key] = value;
386
+ }
387
+ return safe;
388
+ };
389
+
390
+ // src/config/schema.ts
391
+ var logsPolicySchema = z5.strictObject({
392
+ enabled: z5.boolean(),
393
+ /**
394
+ * Full URL for the logs signal.
395
+ *
396
+ * Absent, it is derived from `endpoint`: a trailing `/v1/traces` becomes
397
+ * `/v1/logs`, and an endpoint with no signal path has `/v1/logs` appended.
398
+ */
399
+ endpoint: z5.string().url().max(2048).optional(),
400
+ includeContent: z5.boolean(),
401
+ maxBatchSize: z5.number().int().min(1).max(4096)
402
+ });
403
+ var DEFAULT_LOGS_POLICY = Object.freeze({
404
+ enabled: false,
405
+ includeContent: false,
406
+ maxBatchSize: 128
407
+ });
408
+ var exporterPolicySchema = z5.strictObject({
409
+ enabled: z5.boolean(),
410
+ protocol: z5.enum(["http/protobuf", "http/json", "none"]),
411
+ endpoint: z5.string().url().max(2048).optional(),
412
+ /**
413
+ * Header names only. Values are supplied separately at construction time and
414
+ * are never part of a resolved-config snapshot, which is logged and exported.
415
+ */
416
+ headerNames: z5.array(nonEmptyStringSchema).max(32).readonly(),
417
+ timeoutMillis: z5.number().int().min(1).max(6e5),
418
+ maxBatchSize: z5.number().int().min(1).max(4096),
419
+ maxQueueSize: z5.number().int().min(1).max(65536),
420
+ maxRetryAttempts: z5.number().int().min(0).max(10),
421
+ serviceName: nonEmptyStringSchema,
422
+ serviceNamespace: nonEmptyStringSchema.optional(),
423
+ /**
424
+ * Custom attributes merged into the exported OTLP Resource.
425
+ *
426
+ * Bounded and validated, and refusing `service.name`/`service.namespace`,
427
+ * which are the two fields above. Distinct from an invocation's
428
+ * `consumerAttributes`: this describes the emitting deployment, carries no
429
+ * identity, and is the same for every span this process exports.
430
+ */
431
+ resourceAttributes: resourceAttributesSchema,
432
+ /**
433
+ * The logs signal. Nested under the exporter because it shares the endpoint,
434
+ * headers, timeout, protocol, service identity, and resource attributes above —
435
+ * a second top-level section would invite two of each to drift apart.
436
+ */
437
+ logs: logsPolicySchema,
438
+ /**
439
+ * Additional OTLP destinations, each sent every batch in parallel.
440
+ *
441
+ * Absent (the default), the exporter has exactly one destination — the
442
+ * single-endpoint settings above, named `default` — and behaves exactly as it
443
+ * did before this list existed. See `destinations.ts`.
444
+ *
445
+ * Merged as one leaf: a higher layer that sets the list replaces it whole,
446
+ * because "the union of two partial lists" has no answer an operator could
447
+ * predict.
448
+ */
449
+ destinations: exportDestinationsSchema.optional(),
450
+ /**
451
+ * Per-destination retry spool bounds, each optional and merged per leaf; any
452
+ * bound left unset takes its value from `DEFAULT_SPOOL_POLICY`.
453
+ */
454
+ spool: spoolPolicySchema.partial().optional()
455
+ });
456
+ var detectionPolicySchema = z5.strictObject({
457
+ /** Detections below this confidence resolve to the unknown provider. */
458
+ minimumConfidence: detectionConfidenceSchema,
459
+ /** When false, an ambiguous detection is an error rather than unknown. */
460
+ allowAmbiguousFallback: z5.boolean(),
461
+ /** Optional allow-list of provider ids; empty means "any registered". */
462
+ allowedProviderIds: z5.array(nonEmptyStringSchema).max(32).readonly()
463
+ });
464
+ var diagnosticsPolicySchema = z5.strictObject({
465
+ logLevel: z5.enum(["silent", "error", "warn", "info", "debug"]),
466
+ /** Emit `error.raised` events for contained failures. */
467
+ emitErrorEvents: z5.boolean()
468
+ });
469
+ var providersPolicySchema = z5.strictObject({
470
+ claudeCode: z5.strictObject({
471
+ readTranscriptUsage: z5.boolean()
472
+ }).optional()
473
+ });
474
+ var otelHookConfigSchema = z5.strictObject({
475
+ exporter: exporterPolicySchema,
476
+ privacy: privacyPolicySchema,
477
+ detection: detectionPolicySchema,
478
+ diagnostics: diagnosticsPolicySchema,
479
+ /** Optional so a hand-built configuration from before it existed stays valid. */
480
+ providers: providersPolicySchema.optional()
481
+ });
482
+ var otelHookConfigPatchSchema = z5.strictObject({
483
+ // `logs` is unwrapped and re-partialled for the same reason `privacy.limits` is:
484
+ // merging happens per leaf, so a layer must be able to set `logs.enabled` alone
485
+ // without also restating the endpoint and the batch size.
486
+ exporter: exporterPolicySchema.omit({ logs: true, spool: true }).partial().extend({
487
+ logs: logsPolicySchema.partial().optional(),
488
+ spool: spoolPolicySchema.partial().optional()
489
+ }).optional(),
490
+ privacy: privacyPolicySchema.omit({ limits: true }).partial().extend({ limits: privacyPolicySchema.shape.limits.partial().optional() }).optional(),
491
+ detection: detectionPolicySchema.partial().optional(),
492
+ diagnostics: diagnosticsPolicySchema.partial().optional(),
493
+ providers: z5.strictObject({
494
+ claudeCode: z5.strictObject({ readTranscriptUsage: z5.boolean() }).partial().optional()
495
+ }).partial().optional()
496
+ });
497
+ var DEFAULT_EXPORTER_POLICY = Object.freeze({
498
+ enabled: true,
499
+ protocol: "http/protobuf",
500
+ headerNames: Object.freeze([]),
501
+ timeoutMillis: 1e4,
502
+ maxBatchSize: 128,
503
+ maxQueueSize: 2048,
504
+ maxRetryAttempts: 2,
505
+ serviceName: "coding-agent",
506
+ resourceAttributes: EMPTY_RESOURCE_ATTRIBUTES,
507
+ logs: DEFAULT_LOGS_POLICY
508
+ });
509
+ var DEFAULT_DETECTION_POLICY = Object.freeze({
510
+ minimumConfidence: "strong",
511
+ allowAmbiguousFallback: true,
512
+ allowedProviderIds: Object.freeze([])
513
+ });
514
+ var DEFAULT_DIAGNOSTICS_POLICY = Object.freeze({
515
+ logLevel: "warn",
516
+ emitErrorEvents: true
517
+ });
518
+ var DEFAULT_PROVIDERS_POLICY = Object.freeze({
519
+ claudeCode: Object.freeze({ readTranscriptUsage: false })
520
+ });
521
+ var DEFAULT_CONFIG = Object.freeze({
522
+ exporter: DEFAULT_EXPORTER_POLICY,
523
+ privacy: DEFAULT_PRIVACY_POLICY,
524
+ detection: DEFAULT_DETECTION_POLICY,
525
+ diagnostics: DEFAULT_DIAGNOSTICS_POLICY,
526
+ providers: DEFAULT_PROVIDERS_POLICY
527
+ });
528
+ var readsClaudeTranscriptUsage = (config) => config.providers?.claudeCode?.readTranscriptUsage === true;
529
+
1
530
  // src/diagnostics/health.ts
2
531
  var createHealthTracker = (subsystem, options = {}) => {
3
532
  const unhealthyThreshold = options.unhealthyAfterConsecutiveFailures ?? 3;
@@ -31,7 +560,8 @@ var createHealthTracker = (subsystem, options = {}) => {
31
560
  consecutiveFailures,
32
561
  ...lastSuccessAt === void 0 ? {} : { lastSuccessAt },
33
562
  ...lastFailureAt === void 0 ? {} : { lastFailureAt },
34
- ...lastErrorCode === void 0 ? {} : { lastErrorCode }
563
+ ...lastErrorCode === void 0 ? {} : { lastErrorCode },
564
+ ...options.destination === void 0 ? {} : { destination: options.destination }
35
565
  })
36
566
  };
37
567
  };
@@ -41,58 +571,11 @@ var summarizeHealth = (snapshots) => ({
41
571
  });
42
572
 
43
573
  // src/errors/index.ts
44
- import { z as z3 } from "zod";
45
-
46
- // src/model/primitives.ts
47
- import { z } from "zod";
48
- var MAX_IDENTIFIER_LENGTH = 256;
49
- var MAX_ATTRIBUTE_STRING_LENGTH = 4096;
50
- var MAX_ATTRIBUTE_ARRAY_LENGTH = 128;
51
- var nonEmptyStringSchema = z.string().min(1).max(MAX_IDENTIFIER_LENGTH);
52
- var epochMillisSchema = z.number().int().min(0).max(864e13);
53
- var durationMillisSchema = z.number().min(0).finite();
54
- var tokenCountSchema = z.number().int().min(0);
55
- var sequenceNumberSchema = z.number().int().min(0);
56
- var brandedIdSchema = () => z.string().min(1).max(MAX_IDENTIFIER_LENGTH);
57
- var invocationIdSchema = brandedIdSchema().brand();
58
- var sessionIdSchema = brandedIdSchema().brand();
59
- var eventIdSchema = brandedIdSchema().brand();
60
- var WORKSPACE_ID_PATTERN = /^[a-z][a-z0-9]{0,15}:[A-Za-z0-9_-]{8,128}$/;
61
- var workspaceIdSchema = z.string().regex(WORKSPACE_ID_PATTERN, "workspace id must be an opaque `<scheme>:<token>` handle").brand();
62
- var PROVIDER_ID_PATTERN = /^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/;
63
- var providerIdSchema = z.string().min(1).max(64).regex(PROVIDER_ID_PATTERN, "provider id must be lowercase and hyphenated").brand();
64
- var UNKNOWN_PROVIDER_ID = "unknown";
65
- var resolvedProviderIdSchema = z.union([
66
- providerIdSchema,
67
- z.literal(UNKNOWN_PROVIDER_ID)
68
- ]);
69
- var attributePrimitiveSchema = z.union([
70
- z.string().max(MAX_ATTRIBUTE_STRING_LENGTH),
71
- z.number().finite(),
72
- z.boolean()
73
- ]);
74
- var attributeValueSchema = z.union([
75
- attributePrimitiveSchema,
76
- z.array(attributePrimitiveSchema).max(MAX_ATTRIBUTE_ARRAY_LENGTH)
77
- ]);
78
- var attributesSchema = z.record(z.string().min(1).max(MAX_IDENTIFIER_LENGTH), attributeValueSchema);
79
- var detectionConfidenceSchema = z.enum(["none", "weak", "strong", "exact"]);
80
- var DETECTION_CONFIDENCE_RANK = Object.freeze({
81
- none: 0,
82
- weak: 1,
83
- strong: 2,
84
- exact: 3
85
- });
86
- var sourceTransportSchema = z.enum([
87
- "hook-stdin",
88
- "cli-argument",
89
- "library-call",
90
- "test-fixture"
91
- ]);
574
+ import { z as z7 } from "zod";
92
575
 
93
576
  // src/errors/taxonomy.ts
94
- import { z as z2 } from "zod";
95
- var otelHookErrorCodeSchema = z2.enum([
577
+ import { z as z6 } from "zod";
578
+ var otelHookErrorCodeSchema = z6.enum([
96
579
  /** Input was not usable at all (empty stdin, unparsable JSON). */
97
580
  "invalid-input",
98
581
  /** Input parsed but failed canonical schema validation. */
@@ -128,8 +611,8 @@ var otelHookErrorCodeSchema = z2.enum([
128
611
  /** Anything unanticipated. Always reported, never fatal to the host. */
129
612
  "internal-error"
130
613
  ]);
131
- var errorSeveritySchema = z2.enum(["warning", "error"]);
132
- var errorPhaseSchema = z2.enum([
614
+ var errorSeveritySchema = z6.enum(["warning", "error"]);
615
+ var errorPhaseSchema = z6.enum([
133
616
  "configuration",
134
617
  "detection",
135
618
  "identity",
@@ -140,7 +623,7 @@ var errorPhaseSchema = z2.enum([
140
623
  "export",
141
624
  "shutdown"
142
625
  ]);
143
- var failurePostureSchema = z2.enum(["fail-open", "fail-closed-attribution"]);
626
+ var failurePostureSchema = z6.enum(["fail-open", "fail-closed-attribution"]);
144
627
  var ERROR_TAXONOMY = Object.freeze({
145
628
  "invalid-input": {
146
629
  code: "invalid-input",
@@ -265,7 +748,7 @@ var ERROR_TAXONOMY = Object.freeze({
265
748
  }
266
749
  });
267
750
  var describeErrorCode = (code) => ERROR_TAXONOMY[code];
268
- var attributionOutcomeSchema = z2.enum([
751
+ var attributionOutcomeSchema = z6.enum([
269
752
  /** Identity resolved; events carry provider and session identity. */
270
753
  "attributed",
271
754
  /** Identity could not be established safely; nothing was attributed. */
@@ -275,7 +758,7 @@ var attributionOutcomeSchema = z2.enum([
275
758
  /** Input was recognized but intentionally carried no telemetry. */
276
759
  "not-applicable"
277
760
  ]);
278
- var attributionReasonSchema = z2.enum([
761
+ var attributionReasonSchema = z6.enum([
279
762
  "provider-unknown",
280
763
  "provider-detection-ambiguous",
281
764
  "identity-conflict",
@@ -287,13 +770,13 @@ var attributionReasonSchema = z2.enum([
287
770
  ]);
288
771
 
289
772
  // src/errors/index.ts
290
- var otelHookErrorInfoSchema = z3.strictObject({
773
+ var otelHookErrorInfoSchema = z7.strictObject({
291
774
  code: otelHookErrorCodeSchema,
292
775
  severity: errorSeveritySchema,
293
776
  phase: errorPhaseSchema,
294
777
  posture: failurePostureSchema,
295
- retryable: z3.boolean(),
296
- message: z3.string().min(1).max(512),
778
+ retryable: z7.boolean(),
779
+ message: z7.string().min(1).max(512),
297
780
  details: attributesSchema.optional(),
298
781
  occurredAt: epochMillisSchema.optional()
299
782
  });
@@ -672,17 +1155,17 @@ import {
672
1155
  } from "@opentelemetry/semantic-conventions/incubating";
673
1156
 
674
1157
  // src/version.ts
675
- var VERSION = "0.8.0";
1158
+ var VERSION = "0.10.0";
676
1159
 
677
1160
  // src/telemetry/export-identity.ts
678
1161
  import { ATTR_SESSION_ID } from "@opentelemetry/semantic-conventions/incubating";
679
1162
 
680
1163
  // src/model/events.ts
681
- import { z as z10 } from "zod";
1164
+ import { z as z14 } from "zod";
682
1165
 
683
1166
  // src/model/content.ts
684
- import { z as z4 } from "zod";
685
- var contentKindSchema = z4.enum([
1167
+ import { z as z8 } from "zod";
1168
+ var contentKindSchema = z8.enum([
686
1169
  "prompt",
687
1170
  "response",
688
1171
  "reasoning",
@@ -692,34 +1175,34 @@ var contentKindSchema = z4.enum([
692
1175
  "system-instruction",
693
1176
  "attachment"
694
1177
  ]);
695
- var contentRoleSchema = z4.enum(["user", "assistant", "system", "tool", "unknown"]);
696
- var contentDisclosureSchema = z4.enum(["omitted", "masked", "redacted", "raw"]);
1178
+ var contentRoleSchema = z8.enum(["user", "assistant", "system", "tool", "unknown"]);
1179
+ var contentDisclosureSchema = z8.enum(["omitted", "masked", "redacted", "raw"]);
697
1180
  var CONTENT_HASH_PATTERN = /^sha256:[0-9a-f]{64}$/;
698
- var contentFactSchema = z4.strictObject({
1181
+ var contentFactSchema = z8.strictObject({
699
1182
  kind: contentKindSchema,
700
1183
  role: contentRoleSchema.optional(),
701
1184
  /** Unicode code point count of the original content. */
702
- characterLength: z4.number().int().min(0),
1185
+ characterLength: z8.number().int().min(0),
703
1186
  /** UTF-8 byte length of the original content. */
704
- byteLength: z4.number().int().min(0),
1187
+ byteLength: z8.number().int().min(0),
705
1188
  /** Stable salted digest of the original content. */
706
- contentHash: z4.string().regex(CONTENT_HASH_PATTERN),
1189
+ contentHash: z8.string().regex(CONTENT_HASH_PATTERN),
707
1190
  disclosure: contentDisclosureSchema,
708
1191
  /** Disclosed text, bounded by the privacy policy. Absent when omitted. */
709
- text: z4.string().optional(),
1192
+ text: z8.string().optional(),
710
1193
  /** True when `text` was cut short by the configured string bound. */
711
- truncated: z4.boolean(),
1194
+ truncated: z8.boolean(),
712
1195
  /** Number of secret-looking spans replaced while producing `text`. */
713
- secretsRedacted: z4.number().int().min(0),
1196
+ secretsRedacted: z8.number().int().min(0),
714
1197
  /** Optional non-sensitive label, e.g. a MIME type or tool name. */
715
1198
  label: nonEmptyStringSchema.optional()
716
1199
  });
717
- var contentFactsSchema = z4.array(contentFactSchema).max(64);
1200
+ var contentFactsSchema = z8.array(contentFactSchema).max(64);
718
1201
  var isContentFactConsistent = (fact) => fact.disclosure === "omitted" ? fact.text === void 0 : fact.text !== void 0;
719
1202
  var isUnavailableContentFact = (fact) => fact.disclosure === "omitted" && fact.text === void 0 && fact.characterLength === 0 && fact.byteLength === 0;
720
1203
 
721
1204
  // src/model/extensions.ts
722
- import { z as z5 } from "zod";
1205
+ import { z as z9 } from "zod";
723
1206
  var EXTENSION_KEY_PATTERN = /^[a-z][a-z0-9]*(?:[-_][a-z0-9]+)*(?:\.[a-z][a-z0-9]*(?:[-_][a-z0-9]+)*)+$/;
724
1207
  var RESERVED_EXTENSION_NAMESPACES = Object.freeze([
725
1208
  "otelhook",
@@ -730,7 +1213,7 @@ var MAX_EXTENSION_ENTRIES = 64;
730
1213
  var extensionKeyNamespace = (key) => key.slice(0, key.indexOf("."));
731
1214
  var isReservedExtensionNamespace = (key) => RESERVED_EXTENSION_NAMESPACES.includes(extensionKeyNamespace(key));
732
1215
  var isValidExtensionKey = (key) => EXTENSION_KEY_PATTERN.test(key) && !isReservedExtensionNamespace(key);
733
- var extensionsSchema = z5.record(z5.string(), attributeValueSchema).check((ctx) => {
1216
+ var extensionsSchema = z9.record(z9.string(), attributeValueSchema).check((ctx) => {
734
1217
  const keys = Object.keys(ctx.value);
735
1218
  if (keys.length > MAX_EXTENSION_ENTRIES) {
736
1219
  ctx.issues.push({
@@ -763,15 +1246,15 @@ var EMPTY_EXTENSIONS = Object.freeze({});
763
1246
  var emptyExtensions = () => ({});
764
1247
 
765
1248
  // src/model/identity.ts
766
- import { z as z6 } from "zod";
767
- var workspaceKeySourceSchema = z6.enum([
1249
+ import { z as z10 } from "zod";
1250
+ var workspaceKeySourceSchema = z10.enum([
768
1251
  "git-remote",
769
1252
  "git-root",
770
1253
  "working-directory",
771
1254
  "explicit",
772
1255
  "unknown"
773
1256
  ]);
774
- var workspaceIdentitySchema = z6.strictObject({
1257
+ var workspaceIdentitySchema = z10.strictObject({
775
1258
  workspaceId: workspaceIdSchema,
776
1259
  keySource: workspaceKeySourceSchema,
777
1260
  /** Repository name only; never an owner path or URL with credentials. */
@@ -785,7 +1268,7 @@ var unknownWorkspaceIdentity = () => workspaceIdentitySchema.parse({
785
1268
  workspaceId: UNKNOWN_WORKSPACE_ID,
786
1269
  keySource: "unknown"
787
1270
  });
788
- var sourceProvenanceSchema = z6.strictObject({
1271
+ var sourceProvenanceSchema = z10.strictObject({
789
1272
  providerId: resolvedProviderIdSchema,
790
1273
  providerVersion: nonEmptyStringSchema.optional(),
791
1274
  adapterId: nonEmptyStringSchema,
@@ -796,7 +1279,7 @@ var sourceProvenanceSchema = z6.strictObject({
796
1279
  transport: sourceTransportSchema
797
1280
  }).readonly();
798
1281
  var consumerAttributesSchema = attributesSchema.readonly();
799
- var invocationIdentitySchema = z6.strictObject({
1282
+ var invocationIdentitySchema = z10.strictObject({
800
1283
  invocationId: invocationIdSchema,
801
1284
  sessionId: sessionIdSchema,
802
1285
  /** Set when this invocation runs beneath another agent invocation. */
@@ -810,7 +1293,7 @@ var invocationIdentitySchema = z6.strictObject({
810
1293
  startedAt: epochMillisSchema,
811
1294
  consumerAttributes: consumerAttributesSchema
812
1295
  }).readonly();
813
- var identityClaimFieldsSchema = z6.strictObject({
1296
+ var identityClaimFieldsSchema = z10.strictObject({
814
1297
  invocationId: invocationIdSchema.optional(),
815
1298
  sessionId: sessionIdSchema.optional(),
816
1299
  parentInvocationId: invocationIdSchema.optional(),
@@ -819,7 +1302,7 @@ var identityClaimFieldsSchema = z6.strictObject({
819
1302
  workspace: workspaceIdentitySchema.optional(),
820
1303
  startedAt: epochMillisSchema.optional()
821
1304
  });
822
- var identityClaimSchema = z6.strictObject({
1305
+ var identityClaimSchema = z10.strictObject({
823
1306
  /** Non-sensitive label, e.g. `adapter:acme-cli` or `env:OTEL_HOOK_SESSION_ID`. */
824
1307
  source: nonEmptyStringSchema,
825
1308
  confidence: detectionConfidenceSchema,
@@ -940,19 +1423,19 @@ var resolveInvocationIdentity = (input) => {
940
1423
  };
941
1424
 
942
1425
  // src/model/target.ts
943
- import { z as z7 } from "zod";
944
- var targetSourceSchema = z7.enum(["tool-path", "shell-cwd", "session-cwd"]);
1426
+ import { z as z11 } from "zod";
1427
+ var targetSourceSchema = z11.enum(["tool-path", "shell-cwd", "session-cwd"]);
945
1428
  var MAX_TARGET_HINT_PATHS = 8;
946
1429
  var MAX_TARGET_PATH_LENGTH = 4096;
947
- var localPathSchema = z7.string().min(1).max(MAX_TARGET_PATH_LENGTH).refine((value) => !value.includes("\0"), "path must not contain NUL");
948
- var targetHintSchema = z7.strictObject({
1430
+ var localPathSchema = z11.string().min(1).max(MAX_TARGET_PATH_LENGTH).refine((value) => !value.includes("\0"), "path must not contain NUL");
1431
+ var targetHintSchema = z11.strictObject({
949
1432
  source: targetSourceSchema,
950
- paths: z7.array(localPathSchema).min(1).max(MAX_TARGET_HINT_PATHS).readonly(),
1433
+ paths: z11.array(localPathSchema).min(1).max(MAX_TARGET_HINT_PATHS).readonly(),
951
1434
  /** Absolute directory that relative `paths` resolve against. */
952
1435
  baseDirectory: localPathSchema.optional()
953
1436
  }).readonly();
954
- var worktreeKindSchema = z7.enum(["main", "linked"]);
955
- var workspaceTargetSchema = z7.strictObject({
1437
+ var worktreeKindSchema = z11.enum(["main", "linked"]);
1438
+ var workspaceTargetSchema = z11.strictObject({
956
1439
  workspaceId: workspaceIdSchema,
957
1440
  /** Branch checked out in that worktree; absent on a detached HEAD. */
958
1441
  vcsBranchName: nonEmptyStringSchema.optional(),
@@ -962,18 +1445,18 @@ var workspaceTargetSchema = z7.strictObject({
962
1445
  worktreeKind: worktreeKindSchema.optional()
963
1446
  }).readonly();
964
1447
  var SUBAGENT_ID_PATTERN = /^[A-Za-z0-9_.:@+=-]{1,256}$/;
965
- var subagentIdSchema = z7.string().regex(SUBAGENT_ID_PATTERN);
1448
+ var subagentIdSchema = z11.string().regex(SUBAGENT_ID_PATTERN);
966
1449
 
967
1450
  // src/model/usage.ts
968
- import { z as z8 } from "zod";
969
- var usageTemporalitySchema = z8.enum(["delta", "cumulative"]);
970
- var cacheCreationAccountingSchema = z8.enum([
1451
+ import { z as z12 } from "zod";
1452
+ var usageTemporalitySchema = z12.enum(["delta", "cumulative"]);
1453
+ var cacheCreationAccountingSchema = z12.enum([
971
1454
  "included-in-input",
972
1455
  "disjoint-from-input",
973
1456
  "not-reported"
974
1457
  ]);
975
- var providerTotalAgreementSchema = z8.enum(["unreported", "agrees", "disagrees"]);
976
- var usageReportSchema = z8.strictObject({
1458
+ var providerTotalAgreementSchema = z12.enum(["unreported", "agrees", "disagrees"]);
1459
+ var usageReportSchema = z12.strictObject({
977
1460
  temporality: usageTemporalitySchema,
978
1461
  /** Inclusive input tokens. */
979
1462
  inputTokens: tokenCountSchema.optional(),
@@ -990,7 +1473,7 @@ var usageReportSchema = z8.strictObject({
990
1473
  /** Total exactly as the provider reported it, if it reported one. */
991
1474
  providerTotalTokens: tokenCountSchema.optional()
992
1475
  });
993
- var canonicalUsageSchema = z8.strictObject({
1476
+ var canonicalUsageSchema = z12.strictObject({
994
1477
  temporality: usageTemporalitySchema,
995
1478
  inputTokens: tokenCountSchema,
996
1479
  cachedInputTokens: tokenCountSchema,
@@ -1191,24 +1674,24 @@ var toReport = (usage) => ({
1191
1674
  });
1192
1675
 
1193
1676
  // src/model/version.ts
1194
- import { z as z9 } from "zod";
1677
+ import { z as z13 } from "zod";
1195
1678
  var CANONICAL_SCHEMA_VERSION = 1;
1196
- var canonicalSchemaVersionSchema = z9.literal(CANONICAL_SCHEMA_VERSION);
1679
+ var canonicalSchemaVersionSchema = z13.literal(CANONICAL_SCHEMA_VERSION);
1197
1680
 
1198
1681
  // src/model/events.ts
1199
- var modelDescriptorSchema = z10.strictObject({
1682
+ var modelDescriptorSchema = z14.strictObject({
1200
1683
  modelId: nonEmptyStringSchema,
1201
1684
  /** Vendor of the model, e.g. `anthropic`. Distinct from the agent provider. */
1202
1685
  vendor: nonEmptyStringSchema.optional(),
1203
1686
  family: nonEmptyStringSchema.optional()
1204
1687
  });
1205
- var costFactsSchema = z10.strictObject({
1688
+ var costFactsSchema = z14.strictObject({
1206
1689
  /** ISO 4217 code. */
1207
- currency: z10.string().length(3),
1208
- amount: z10.number().min(0).finite(),
1209
- source: z10.enum(["provider-reported", "computed"])
1690
+ currency: z14.string().length(3),
1691
+ amount: z14.number().min(0).finite(),
1692
+ source: z14.enum(["provider-reported", "computed"])
1210
1693
  });
1211
- var canonicalEventTypeSchema = z10.enum([
1694
+ var canonicalEventTypeSchema = z14.enum([
1212
1695
  "session.start",
1213
1696
  "session.end",
1214
1697
  "prompt.submitted",
@@ -1222,7 +1705,7 @@ var canonicalEventTypeSchema = z10.enum([
1222
1705
  "error.raised"
1223
1706
  ]);
1224
1707
  var CANONICAL_EVENT_TYPES = canonicalEventTypeSchema.options;
1225
- var outcomeSchema = z10.enum(["ok", "error", "cancelled", "timeout", "denied", "unknown"]);
1708
+ var outcomeSchema = z14.enum(["ok", "error", "cancelled", "timeout", "denied", "unknown"]);
1226
1709
  var baseEventFields = {
1227
1710
  schemaVersion: canonicalSchemaVersionSchema,
1228
1711
  eventId: eventIdSchema,
@@ -1241,10 +1724,10 @@ var baseEventFields = {
1241
1724
  subagentId: subagentIdSchema.optional(),
1242
1725
  extensions: extensionsSchema.default(emptyExtensions)
1243
1726
  };
1244
- var event = (shape) => z10.strictObject({ ...baseEventFields, ...shape });
1727
+ var event = (shape) => z14.strictObject({ ...baseEventFields, ...shape });
1245
1728
  var sessionStartEventSchema = event({
1246
- type: z10.literal("session.start"),
1247
- sessionKind: z10.enum(["interactive", "non-interactive", "unknown"]),
1729
+ type: z14.literal("session.start"),
1730
+ sessionKind: z14.enum(["interactive", "non-interactive", "unknown"]),
1248
1731
  agentName: nonEmptyStringSchema.optional(),
1249
1732
  agentVersion: nonEmptyStringSchema.optional(),
1250
1733
  model: modelDescriptorSchema.optional(),
@@ -1252,40 +1735,47 @@ var sessionStartEventSchema = event({
1252
1735
  target: workspaceTargetSchema.optional()
1253
1736
  });
1254
1737
  var sessionEndEventSchema = event({
1255
- type: z10.literal("session.end"),
1256
- reason: z10.enum(["completed", "aborted", "error", "timeout", "unknown"]),
1738
+ type: z14.literal("session.end"),
1739
+ reason: z14.enum(["completed", "aborted", "error", "timeout", "unknown"]),
1257
1740
  durationMillis: durationMillisSchema.optional(),
1258
1741
  /** Session totals, typically cumulative. */
1259
1742
  usage: canonicalUsageSchema.optional(),
1260
1743
  cost: costFactsSchema.optional()
1261
1744
  });
1262
1745
  var promptSubmittedEventSchema = event({
1263
- type: z10.literal("prompt.submitted"),
1264
- promptSource: z10.enum(["user", "automation", "resumed", "unknown"]),
1746
+ type: z14.literal("prompt.submitted"),
1747
+ promptSource: z14.enum(["user", "automation", "resumed", "unknown"]),
1265
1748
  content: contentFactSchema.optional(),
1266
- turnIndex: z10.number().int().min(0).optional(),
1749
+ turnIndex: z14.number().int().min(0).optional(),
1267
1750
  /** The git worktree the session runs in, resolved by the core (ADR 0008). */
1268
1751
  target: workspaceTargetSchema.optional()
1269
1752
  });
1270
1753
  var generationStartEventSchema = event({
1271
- type: z10.literal("generation.start"),
1754
+ type: z14.literal("generation.start"),
1272
1755
  generationId: nonEmptyStringSchema,
1273
1756
  model: modelDescriptorSchema,
1274
1757
  requestedMaxOutputTokens: tokenCountSchema.optional(),
1275
1758
  inputContent: contentFactsSchema.optional()
1276
1759
  });
1277
1760
  var generationEndEventSchema = event({
1278
- type: z10.literal("generation.end"),
1761
+ type: z14.literal("generation.end"),
1279
1762
  generationId: nonEmptyStringSchema,
1280
1763
  model: modelDescriptorSchema,
1281
1764
  outcome: outcomeSchema,
1282
1765
  stopReason: nonEmptyStringSchema.optional(),
1283
1766
  durationMillis: durationMillisSchema.optional(),
1284
1767
  usage: canonicalUsageSchema.optional(),
1768
+ /**
1769
+ * True when `usage` is known to cover only part of the generation (for
1770
+ * example the last model request of a multi-request turn); false when the
1771
+ * provider or harness said it is the whole. Absent: not stated. Meaningless
1772
+ * without `usage`.
1773
+ */
1774
+ usagePartial: z14.boolean().optional(),
1285
1775
  cost: costFactsSchema.optional(),
1286
1776
  outputContent: contentFactsSchema.optional()
1287
1777
  });
1288
- var toolKindSchema = z10.enum([
1778
+ var toolKindSchema = z14.enum([
1289
1779
  "read",
1290
1780
  "write",
1291
1781
  "execute",
@@ -1296,7 +1786,7 @@ var toolKindSchema = z10.enum([
1296
1786
  "unknown"
1297
1787
  ]);
1298
1788
  var toolStartEventSchema = event({
1299
- type: z10.literal("tool.start"),
1789
+ type: z14.literal("tool.start"),
1300
1790
  toolCallId: nonEmptyStringSchema,
1301
1791
  toolName: nonEmptyStringSchema,
1302
1792
  toolKind: toolKindSchema,
@@ -1306,53 +1796,53 @@ var toolStartEventSchema = event({
1306
1796
  target: workspaceTargetSchema.optional()
1307
1797
  });
1308
1798
  var toolEndEventSchema = event({
1309
- type: z10.literal("tool.end"),
1799
+ type: z14.literal("tool.end"),
1310
1800
  toolCallId: nonEmptyStringSchema,
1311
1801
  toolName: nonEmptyStringSchema,
1312
1802
  outcome: outcomeSchema,
1313
1803
  durationMillis: durationMillisSchema.optional(),
1314
1804
  /** Present when the host asked for or recorded a permission decision. */
1315
- permissionDecision: z10.enum(["allowed", "denied", "deferred", "not-required"]).optional(),
1805
+ permissionDecision: z14.enum(["allowed", "denied", "deferred", "not-required"]).optional(),
1316
1806
  output: contentFactSchema.optional(),
1317
1807
  /** The git worktree this call targeted, resolved by the core (ADR 0008). */
1318
1808
  target: workspaceTargetSchema.optional()
1319
1809
  });
1320
1810
  var subagentStartEventSchema = event({
1321
- type: z10.literal("subagent.start"),
1811
+ type: z14.literal("subagent.start"),
1322
1812
  subagentInvocationId: invocationIdSchema,
1323
1813
  subagentType: nonEmptyStringSchema.optional(),
1324
1814
  /** 0 for the top-level agent; 1 for its direct children. */
1325
- delegationDepth: z10.number().int().min(0).max(64),
1815
+ delegationDepth: z14.number().int().min(0).max(64),
1326
1816
  model: modelDescriptorSchema.optional()
1327
1817
  });
1328
1818
  var subagentEndEventSchema = event({
1329
- type: z10.literal("subagent.end"),
1819
+ type: z14.literal("subagent.end"),
1330
1820
  subagentInvocationId: invocationIdSchema,
1331
1821
  outcome: outcomeSchema,
1332
1822
  durationMillis: durationMillisSchema.optional(),
1333
1823
  usage: canonicalUsageSchema.optional()
1334
1824
  });
1335
1825
  var compactionPerformedEventSchema = event({
1336
- type: z10.literal("compaction.performed"),
1337
- trigger: z10.enum(["automatic", "manual", "unknown"]),
1826
+ type: z14.literal("compaction.performed"),
1827
+ trigger: z14.enum(["automatic", "manual", "unknown"]),
1338
1828
  /** Provider-reported context size before and after compaction, if known. */
1339
1829
  contextTokensBefore: tokenCountSchema.optional(),
1340
1830
  contextTokensAfter: tokenCountSchema.optional(),
1341
- droppedMessageCount: z10.number().int().min(0).optional(),
1831
+ droppedMessageCount: z14.number().int().min(0).optional(),
1342
1832
  usage: canonicalUsageSchema.optional()
1343
1833
  });
1344
1834
  var errorRaisedEventSchema = event({
1345
- type: z10.literal("error.raised"),
1835
+ type: z14.literal("error.raised"),
1346
1836
  errorCode: otelHookErrorCodeSchema,
1347
1837
  severity: errorSeveritySchema,
1348
1838
  phase: errorPhaseSchema,
1349
- retryable: z10.boolean(),
1839
+ retryable: z14.boolean(),
1350
1840
  /** Error text is content: it is described, never embedded verbatim by default. */
1351
1841
  message: contentFactSchema.optional(),
1352
1842
  /** Non-sensitive, provider-agnostic short label. */
1353
1843
  detail: nonEmptyStringSchema.optional()
1354
1844
  });
1355
- var canonicalEventSchema = z10.discriminatedUnion("type", [
1845
+ var canonicalEventSchema = z14.discriminatedUnion("type", [
1356
1846
  sessionStartEventSchema,
1357
1847
  sessionEndEventSchema,
1358
1848
  promptSubmittedEventSchema,
@@ -1463,6 +1953,7 @@ var ATTR_OTELHOOK_SPAN_PAIRING = "otelhook.span.pairing";
1463
1953
  var ATTR_OTELHOOK_SPAN_ORPHAN = "otelhook.span.orphan";
1464
1954
  var ATTR_OTELHOOK_OUTCOME = "otelhook.outcome";
1465
1955
  var ATTR_OTELHOOK_RESET_DETECTED = "otelhook.usage.reset_detected";
1956
+ var ATTR_OTELHOOK_USAGE_PARTIAL = "otelhook.usage.partial";
1466
1957
  var ATTR_OTELHOOK_TOOL_KIND = "otelhook.tool.kind";
1467
1958
  var ATTR_OTELHOOK_DELEGATION_DEPTH = "otelhook.delegation_depth";
1468
1959
  var ATTR_OTELHOOK_COMPACTION_TRIGGER = "otelhook.compaction.trigger";
@@ -1735,7 +2226,8 @@ var buildLifecycleSpan = (plan, resource, scope) => {
1735
2226
  // Codex turn): the key a consumer stores a usage observation under.
1736
2227
  [ATTR_OTELHOOK_GENERATION_ID]: group.ref.scopeKey,
1737
2228
  ...end?.outcome === void 0 ? {} : { [ATTR_OTELHOOK_OUTCOME]: end.outcome },
1738
- ...usageAttributes(end?.usage, false)
2229
+ ...usageAttributes(end?.usage, false),
2230
+ ...end?.usage === void 0 || end.usagePartial === void 0 ? {} : { [ATTR_OTELHOOK_USAGE_PARTIAL]: end.usagePartial }
1739
2231
  };
1740
2232
  status = outcomeStatus(end?.outcome);
1741
2233
  break;
@@ -2488,95 +2980,6 @@ var createUsageAccumulator = (deps) => {
2488
2980
 
2489
2981
  // src/privacy/service.ts
2490
2982
  import { createHash as createHash2 } from "crypto";
2491
-
2492
- // src/privacy/policy.ts
2493
- import { z as z11 } from "zod";
2494
- var contentModeSchema = z11.enum(["omit", "mask", "redact", "raw"]);
2495
- var CONTENT_MODE_DISCLOSURE = Object.freeze({
2496
- omit: "omitted",
2497
- mask: "masked",
2498
- redact: "redacted",
2499
- raw: "raw"
2500
- });
2501
- var DEFAULT_SECRET_KEY_PATTERNS = Object.freeze([
2502
- "(^|[._-])(secret|secrets)([._-]|$)",
2503
- "(^|[._-])(token|tokens)([._-]|$)",
2504
- "(^|[._-])(password|passwd|pwd)([._-]|$)",
2505
- "(^|[._-])(credential|credentials)([._-]|$)",
2506
- "(^|[._-])(api[._-]?key|apikey|access[._-]?key|secret[._-]?key|private[._-]?key)([._-]|$)",
2507
- "(^|[._-])(authorization|auth[._-]?header|bearer)([._-]|$)",
2508
- "(^|[._-])(cookie|set[._-]?cookie)([._-]|$)",
2509
- "(^|[._-])(signature|sig)([._-]|$)"
2510
- ]);
2511
- var DEFAULT_SECRET_VALUE_PATTERNS = Object.freeze([
2512
- "AKIA[0-9A-Z]{16}",
2513
- "sk-[A-Za-z0-9_-]{16,}",
2514
- "gh[pousr]_[A-Za-z0-9]{16,}",
2515
- "xox[abprs]-[A-Za-z0-9-]{10,}",
2516
- "-----BEGIN[A-Z ]*PRIVATE KEY-----",
2517
- "eyJ[A-Za-z0-9_-]{10,}\\.[A-Za-z0-9_-]{10,}\\.[A-Za-z0-9_-]{10,}",
2518
- "(?:Bearer|Basic)\\s+[A-Za-z0-9._~+/=-]{12,}"
2519
- ]);
2520
- var privacyLimitsSchema = z11.strictObject({
2521
- /** Maximum characters of disclosed text per content fact or string value. */
2522
- maxStringLength: z11.number().int().min(0).max(65536),
2523
- /** Maximum nesting depth walked when sanitizing structured values. */
2524
- maxDepth: z11.number().int().min(1).max(32),
2525
- /** Maximum array entries retained when sanitizing structured values. */
2526
- maxArrayLength: z11.number().int().min(1).max(4096),
2527
- /** Maximum canonical events emitted per invocation. */
2528
- maxEventsPerInvocation: z11.number().int().min(1).max(1e4),
2529
- /** Maximum object keys retained per level when sanitizing. */
2530
- maxObjectKeys: z11.number().int().min(1).max(1024)
2531
- });
2532
- var privacyPolicySchema = z11.strictObject({
2533
- contentMode: contentModeSchema,
2534
- /**
2535
- * `raw` mode is refused unless this is also true, so a single mistyped
2536
- * environment variable cannot start exporting prompts.
2537
- */
2538
- allowRawContent: z11.boolean(),
2539
- /**
2540
- * Salt mixed into every hash. A per-deployment salt makes hashes
2541
- * non-correlatable across deployments; an empty salt makes them globally
2542
- * comparable. Both are legitimate; the choice is explicit.
2543
- */
2544
- hashSalt: z11.string().max(256),
2545
- maskCharacter: z11.string().length(1),
2546
- redactionPlaceholder: z11.string().min(1).max(64),
2547
- secretKeyPatterns: z11.array(z11.string().min(1)).max(128).readonly(),
2548
- secretValuePatterns: z11.array(z11.string().min(1)).max(128).readonly(),
2549
- limits: privacyLimitsSchema
2550
- });
2551
- var DEFAULT_PRIVACY_LIMITS = Object.freeze({
2552
- maxStringLength: 1024,
2553
- maxDepth: 6,
2554
- maxArrayLength: 64,
2555
- maxEventsPerInvocation: 512,
2556
- maxObjectKeys: 128
2557
- });
2558
- var DEFAULT_PRIVACY_POLICY = Object.freeze({
2559
- contentMode: "omit",
2560
- allowRawContent: false,
2561
- hashSalt: "",
2562
- maskCharacter: "*",
2563
- redactionPlaceholder: "[redacted]",
2564
- secretKeyPatterns: DEFAULT_SECRET_KEY_PATTERNS,
2565
- secretValuePatterns: DEFAULT_SECRET_VALUE_PATTERNS,
2566
- limits: DEFAULT_PRIVACY_LIMITS
2567
- });
2568
- var resolvePrivacyPolicy = (policy) => {
2569
- const parsed = privacyPolicySchema.parse(policy);
2570
- if (parsed.contentMode === "raw" && !parsed.allowRawContent) {
2571
- return {
2572
- policy: { ...parsed, contentMode: "omit" },
2573
- notes: ["contentMode=raw downgraded to omit because allowRawContent is false"]
2574
- };
2575
- }
2576
- return { policy: parsed, notes: [] };
2577
- };
2578
-
2579
- // src/privacy/service.ts
2580
2983
  var compilePatterns = (sources, flags) => {
2581
2984
  const compiled = [];
2582
2985
  for (const source of sources) {
@@ -2794,11 +3197,11 @@ var createPrivacyService = (policyInput) => {
2794
3197
  };
2795
3198
  const flattenToAttributes = (value, prefix) => {
2796
3199
  const attributes = {};
2797
- const walk = (current, path5) => {
3200
+ const walk = (current, path6) => {
2798
3201
  if (typeof current === "string" || typeof current === "number" || typeof current === "boolean") {
2799
3202
  const primitive = toAttributePrimitive(current);
2800
3203
  if (primitive !== void 0) {
2801
- attributes[path5] = primitive;
3204
+ attributes[path6] = primitive;
2802
3205
  }
2803
3206
  return;
2804
3207
  }
@@ -2817,16 +3220,16 @@ var createPrivacyService = (policyInput) => {
2817
3220
  primitives.push(entryPrimitive);
2818
3221
  }
2819
3222
  if (uniform) {
2820
- attributes[path5] = primitives.slice(0, MAX_ATTRIBUTE_ARRAY_LENGTH);
3223
+ attributes[path6] = primitives.slice(0, MAX_ATTRIBUTE_ARRAY_LENGTH);
2821
3224
  return;
2822
3225
  }
2823
3226
  for (const [index, entry] of current.entries()) {
2824
- walk(entry, `${path5}.${index}`);
3227
+ walk(entry, `${path6}.${index}`);
2825
3228
  }
2826
3229
  return;
2827
3230
  }
2828
3231
  for (const [key, entry] of Object.entries(current)) {
2829
- walk(entry, path5 === "" ? key : `${path5}.${key}`);
3232
+ walk(entry, path6 === "" ? key : `${path6}.${key}`);
2830
3233
  }
2831
3234
  };
2832
3235
  walk(value, prefix);
@@ -2887,261 +3290,64 @@ var createPrivacyService = (policyInput) => {
2887
3290
  disclosure: "omitted",
2888
3291
  truncated: false,
2889
3292
  secretsRedacted: 0,
2890
- ...input.label === void 0 ? {} : { label: input.label }
2891
- }),
2892
- describeStructured: (input) => {
2893
- const serialized = stableStringify(input.value);
2894
- const sanitized = sanitizeStructured(input.value);
2895
- const base = describeText({
2896
- kind: input.kind,
2897
- text: serialized,
2898
- ...input.role === void 0 ? {} : { role: input.role },
2899
- ...input.label === void 0 ? {} : { label: input.label }
2900
- });
2901
- if (base.text === void 0) {
2902
- return base;
2903
- }
2904
- const disclosed = disclose(stableStringify(sanitized.value));
2905
- return {
2906
- ...base,
2907
- ...disclosed.text === void 0 ? {} : { text: disclosed.text },
2908
- truncated: base.truncated || disclosed.truncated,
2909
- secretsRedacted: disclosed.secretsRedacted + sanitized.stats.redactedKeys
2910
- };
2911
- },
2912
- isSecretKey,
2913
- sanitizeStructured,
2914
- flattenToAttributes,
2915
- sanitizeAttributes,
2916
- sanitizeExtensions,
2917
- boundString
2918
- };
2919
- };
2920
-
2921
- // src/runtime/clock.ts
2922
- var createSystemClock = () => ({
2923
- now: () => epochMillisSchema.parse(Date.now()),
2924
- monotonicMillis: () => Number(process.hrtime.bigint() / 1000000n)
2925
- });
2926
-
2927
- // src/runtime/hook.ts
2928
- import { z as z16 } from "zod";
2929
-
2930
- // src/config/schema.ts
2931
- import { z as z13 } from "zod";
2932
-
2933
- // src/config/resource-attributes.ts
2934
- import { z as z12 } from "zod";
2935
- var MAX_RESOURCE_ATTRIBUTES = 64;
2936
- var MAX_RESOURCE_ATTRIBUTE_KEY_LENGTH = 255;
2937
- var MAX_RESOURCE_ATTRIBUTE_VALUE_LENGTH = 2048;
2938
- var RESOURCE_ATTRIBUTE_KEY_PATTERN = /^[A-Za-z][A-Za-z0-9_./-]*$/;
2939
- var RESERVED_RESOURCE_ATTRIBUTE_KEYS = Object.freeze([
2940
- "service.name",
2941
- "service.namespace"
2942
- ]);
2943
- var isReservedResourceAttributeKey = (key) => RESERVED_RESOURCE_ATTRIBUTE_KEYS.includes(key.toLowerCase());
2944
- var SECRET_KEY_MATCHERS = Object.freeze(
2945
- DEFAULT_SECRET_KEY_PATTERNS.flatMap((source) => {
2946
- try {
2947
- return [new RegExp(source, "i")];
2948
- } catch {
2949
- return [];
2950
- }
2951
- })
2952
- );
2953
- var isSecretResourceAttributeKey = (key) => SECRET_KEY_MATCHERS.some((pattern) => pattern.test(key));
2954
- var RESOURCE_ATTRIBUTE_KEY_REJECTION_DETAIL = Object.freeze({
2955
- empty: "resource attribute key is empty",
2956
- "too-long": `resource attribute key exceeds ${String(MAX_RESOURCE_ATTRIBUTE_KEY_LENGTH)} characters`,
2957
- malformed: "resource attribute key must start with a letter and use only letters, digits, and `_`, `.`, `-`, `/`",
2958
- reserved: "service.name and service.namespace are exporter policy (--service-name / OTEL_HOOK_SERVICE_NAME), not resource attributes",
2959
- "secret-like": "resource attribute key matches a secret-name pattern, so it is never exported"
2960
- });
2961
- var checkResourceAttributeKey = (key) => {
2962
- if (key.length === 0) {
2963
- return "empty";
2964
- }
2965
- if (key.length > MAX_RESOURCE_ATTRIBUTE_KEY_LENGTH) {
2966
- return "too-long";
2967
- }
2968
- if (!RESOURCE_ATTRIBUTE_KEY_PATTERN.test(key)) {
2969
- return "malformed";
2970
- }
2971
- if (isReservedResourceAttributeKey(key)) {
2972
- return "reserved";
2973
- }
2974
- if (isSecretResourceAttributeKey(key)) {
2975
- return "secret-like";
2976
- }
2977
- return void 0;
2978
- };
2979
- var resourceAttributeValueSchema = z12.union([
2980
- z12.string().max(MAX_RESOURCE_ATTRIBUTE_VALUE_LENGTH),
2981
- z12.number().finite(),
2982
- z12.boolean()
2983
- ]);
2984
- var resourceAttributesSchema = z12.record(z12.string(), resourceAttributeValueSchema).superRefine((value, ctx) => {
2985
- const keys = Object.keys(value);
2986
- if (keys.length > MAX_RESOURCE_ATTRIBUTES) {
2987
- ctx.addIssue({
2988
- code: "custom",
2989
- message: `at most ${String(MAX_RESOURCE_ATTRIBUTES)} resource attributes are accepted`
2990
- });
2991
- }
2992
- for (const key of keys) {
2993
- const rejection = checkResourceAttributeKey(key);
2994
- if (rejection !== void 0) {
2995
- ctx.addIssue({
2996
- code: "custom",
2997
- path: [key],
2998
- message: RESOURCE_ATTRIBUTE_KEY_REJECTION_DETAIL[rejection]
3293
+ ...input.label === void 0 ? {} : { label: input.label }
3294
+ }),
3295
+ describeStructured: (input) => {
3296
+ const serialized = stableStringify(input.value);
3297
+ const sanitized = sanitizeStructured(input.value);
3298
+ const base = describeText({
3299
+ kind: input.kind,
3300
+ text: serialized,
3301
+ ...input.role === void 0 ? {} : { role: input.role },
3302
+ ...input.label === void 0 ? {} : { label: input.label }
2999
3303
  });
3000
- }
3001
- }
3002
- }).readonly();
3003
- var EMPTY_RESOURCE_ATTRIBUTES = Object.freeze({});
3004
- var sanitizeResourceAttributes = (attributes) => {
3005
- const safe = {};
3006
- for (const [key, value] of Object.entries(attributes)) {
3007
- if (checkResourceAttributeKey(key) !== void 0) {
3008
- continue;
3009
- }
3010
- if (Object.keys(safe).length >= MAX_RESOURCE_ATTRIBUTES) {
3011
- break;
3012
- }
3013
- safe[key] = value;
3014
- }
3015
- return safe;
3304
+ if (base.text === void 0) {
3305
+ return base;
3306
+ }
3307
+ const disclosed = disclose(stableStringify(sanitized.value));
3308
+ return {
3309
+ ...base,
3310
+ ...disclosed.text === void 0 ? {} : { text: disclosed.text },
3311
+ truncated: base.truncated || disclosed.truncated,
3312
+ secretsRedacted: disclosed.secretsRedacted + sanitized.stats.redactedKeys
3313
+ };
3314
+ },
3315
+ isSecretKey,
3316
+ sanitizeStructured,
3317
+ flattenToAttributes,
3318
+ sanitizeAttributes,
3319
+ sanitizeExtensions,
3320
+ boundString
3321
+ };
3016
3322
  };
3017
3323
 
3018
- // src/config/schema.ts
3019
- var logsPolicySchema = z13.strictObject({
3020
- enabled: z13.boolean(),
3021
- /**
3022
- * Full URL for the logs signal.
3023
- *
3024
- * Absent, it is derived from `endpoint`: a trailing `/v1/traces` becomes
3025
- * `/v1/logs`, and an endpoint with no signal path has `/v1/logs` appended.
3026
- */
3027
- endpoint: z13.string().url().max(2048).optional(),
3028
- includeContent: z13.boolean(),
3029
- maxBatchSize: z13.number().int().min(1).max(4096)
3030
- });
3031
- var DEFAULT_LOGS_POLICY = Object.freeze({
3032
- enabled: false,
3033
- includeContent: false,
3034
- maxBatchSize: 128
3035
- });
3036
- var exporterPolicySchema = z13.strictObject({
3037
- enabled: z13.boolean(),
3038
- protocol: z13.enum(["http/protobuf", "http/json", "none"]),
3039
- endpoint: z13.string().url().max(2048).optional(),
3040
- /**
3041
- * Header names only. Values are supplied separately at construction time and
3042
- * are never part of a resolved-config snapshot, which is logged and exported.
3043
- */
3044
- headerNames: z13.array(nonEmptyStringSchema).max(32).readonly(),
3045
- timeoutMillis: z13.number().int().min(1).max(6e5),
3046
- maxBatchSize: z13.number().int().min(1).max(4096),
3047
- maxQueueSize: z13.number().int().min(1).max(65536),
3048
- maxRetryAttempts: z13.number().int().min(0).max(10),
3049
- serviceName: nonEmptyStringSchema,
3050
- serviceNamespace: nonEmptyStringSchema.optional(),
3051
- /**
3052
- * Custom attributes merged into the exported OTLP Resource.
3053
- *
3054
- * Bounded and validated, and refusing `service.name`/`service.namespace`,
3055
- * which are the two fields above. Distinct from an invocation's
3056
- * `consumerAttributes`: this describes the emitting deployment, carries no
3057
- * identity, and is the same for every span this process exports.
3058
- */
3059
- resourceAttributes: resourceAttributesSchema,
3060
- /**
3061
- * The logs signal. Nested under the exporter because it shares the endpoint,
3062
- * headers, timeout, protocol, service identity, and resource attributes above —
3063
- * a second top-level section would invite two of each to drift apart.
3064
- */
3065
- logs: logsPolicySchema
3066
- });
3067
- var detectionPolicySchema = z13.strictObject({
3068
- /** Detections below this confidence resolve to the unknown provider. */
3069
- minimumConfidence: detectionConfidenceSchema,
3070
- /** When false, an ambiguous detection is an error rather than unknown. */
3071
- allowAmbiguousFallback: z13.boolean(),
3072
- /** Optional allow-list of provider ids; empty means "any registered". */
3073
- allowedProviderIds: z13.array(nonEmptyStringSchema).max(32).readonly()
3074
- });
3075
- var diagnosticsPolicySchema = z13.strictObject({
3076
- logLevel: z13.enum(["silent", "error", "warn", "info", "debug"]),
3077
- /** Emit `error.raised` events for contained failures. */
3078
- emitErrorEvents: z13.boolean()
3079
- });
3080
- var otelHookConfigSchema = z13.strictObject({
3081
- exporter: exporterPolicySchema,
3082
- privacy: privacyPolicySchema,
3083
- detection: detectionPolicySchema,
3084
- diagnostics: diagnosticsPolicySchema
3085
- });
3086
- var otelHookConfigPatchSchema = z13.strictObject({
3087
- // `logs` is unwrapped and re-partialled for the same reason `privacy.limits` is:
3088
- // merging happens per leaf, so a layer must be able to set `logs.enabled` alone
3089
- // without also restating the endpoint and the batch size.
3090
- exporter: exporterPolicySchema.omit({ logs: true }).partial().extend({ logs: logsPolicySchema.partial().optional() }).optional(),
3091
- privacy: privacyPolicySchema.omit({ limits: true }).partial().extend({ limits: privacyPolicySchema.shape.limits.partial().optional() }).optional(),
3092
- detection: detectionPolicySchema.partial().optional(),
3093
- diagnostics: diagnosticsPolicySchema.partial().optional()
3094
- });
3095
- var DEFAULT_EXPORTER_POLICY = Object.freeze({
3096
- enabled: true,
3097
- protocol: "http/protobuf",
3098
- headerNames: Object.freeze([]),
3099
- timeoutMillis: 1e4,
3100
- maxBatchSize: 128,
3101
- maxQueueSize: 2048,
3102
- maxRetryAttempts: 2,
3103
- serviceName: "coding-agent",
3104
- resourceAttributes: EMPTY_RESOURCE_ATTRIBUTES,
3105
- logs: DEFAULT_LOGS_POLICY
3106
- });
3107
- var DEFAULT_DETECTION_POLICY = Object.freeze({
3108
- minimumConfidence: "strong",
3109
- allowAmbiguousFallback: true,
3110
- allowedProviderIds: Object.freeze([])
3111
- });
3112
- var DEFAULT_DIAGNOSTICS_POLICY = Object.freeze({
3113
- logLevel: "warn",
3114
- emitErrorEvents: true
3115
- });
3116
- var DEFAULT_CONFIG = Object.freeze({
3117
- exporter: DEFAULT_EXPORTER_POLICY,
3118
- privacy: DEFAULT_PRIVACY_POLICY,
3119
- detection: DEFAULT_DETECTION_POLICY,
3120
- diagnostics: DEFAULT_DIAGNOSTICS_POLICY
3121
- });
3324
+ // src/providers/claude/transcript.ts
3325
+ import { createHash as createHash3 } from "crypto";
3326
+ import { open, stat } from "fs/promises";
3327
+ import path from "path";
3122
3328
 
3123
3329
  // src/providers/adapter.ts
3124
- import { z as z14 } from "zod";
3125
- var providerDetectionSchema = z14.strictObject({
3330
+ import { z as z15 } from "zod";
3331
+ var providerDetectionSchema = z15.strictObject({
3126
3332
  providerId: resolvedProviderIdSchema,
3127
3333
  confidence: detectionConfidenceSchema,
3128
3334
  /**
3129
3335
  * Short, non-sensitive justifications, e.g. `"payload.hook_event_name present"`.
3130
3336
  * Reasons are exported in diagnostics, so they must not quote payload values.
3131
3337
  */
3132
- reasons: z14.array(z14.string().min(1).max(160)).max(8),
3338
+ reasons: z15.array(z15.string().min(1).max(160)).max(8),
3133
3339
  providerVersion: nonEmptyStringSchema.optional(),
3134
3340
  /** The provider's own name for this event, when the payload states one. */
3135
3341
  sourceEventName: nonEmptyStringSchema.optional()
3136
3342
  });
3137
- var deliveryIdentifierSupportSchema = z14.enum(["none", "partial", "all"]);
3343
+ var deliveryIdentifierSupportSchema = z15.enum(["none", "partial", "all"]);
3138
3344
  var DELIVERY_COMPONENT_PATTERN = /^[A-Za-z0-9_.:@+=-]{1,256}$/;
3139
- var deliveryComponentSchema = z14.string().regex(
3345
+ var deliveryComponentSchema = z15.string().regex(
3140
3346
  DELIVERY_COMPONENT_PATTERN,
3141
3347
  "delivery component must be identifier-shaped: no whitespace, no path separators"
3142
3348
  );
3143
3349
  var MAX_DELIVERY_COMPONENTS = 8;
3144
- var providerDeliveryClaimSchema = z14.strictObject({
3350
+ var providerDeliveryClaimSchema = z15.strictObject({
3145
3351
  /**
3146
3352
  * The provider's own session/conversation id. Scopes the callback identity, so
3147
3353
  * two sessions reusing one tool-call id never collide.
@@ -3153,26 +3359,26 @@ var providerDeliveryClaimSchema = z14.strictObject({
3153
3359
  * Identifier-shaped payload fields that, together with `sourceEventName`,
3154
3360
  * name this callback within the session exactly once.
3155
3361
  */
3156
- components: z14.array(deliveryComponentSchema).min(1).max(MAX_DELIVERY_COMPONENTS).readonly(),
3362
+ components: z15.array(deliveryComponentSchema).min(1).max(MAX_DELIVERY_COMPONENTS).readonly(),
3157
3363
  /**
3158
3364
  * Short, non-sensitive justifications, e.g. `"payload.tool_use_id names one
3159
3365
  * tool call"`. Evidence reaches diagnostics, so it must name fields, never
3160
3366
  * quote their values.
3161
3367
  */
3162
- evidence: z14.array(z14.string().min(1).max(160)).min(1).max(4).readonly()
3368
+ evidence: z15.array(z15.string().min(1).max(160)).min(1).max(4).readonly()
3163
3369
  });
3164
3370
  var DELIVERY_GAP_REASON_PATTERN = /^[^\n\r\t\\/]{1,240}$/;
3165
- var deliveryGapReasonSchema = z14.string().regex(
3371
+ var deliveryGapReasonSchema = z15.string().regex(
3166
3372
  DELIVERY_GAP_REASON_PATTERN,
3167
3373
  "delivery gap reason must be one line of prose: no path separators, no control characters"
3168
3374
  );
3169
3375
  var MAX_DELIVERY_GAPS = 48;
3170
- var providerDeliveryGapsSchema = z14.record(deliveryComponentSchema, deliveryGapReasonSchema).refine((gaps) => Object.keys(gaps).length <= MAX_DELIVERY_GAPS, {
3376
+ var providerDeliveryGapsSchema = z15.record(deliveryComponentSchema, deliveryGapReasonSchema).refine((gaps) => Object.keys(gaps).length <= MAX_DELIVERY_GAPS, {
3171
3377
  message: `at most ${String(MAX_DELIVERY_GAPS)} delivery gaps may be declared`
3172
3378
  });
3173
- var providerCapabilitiesSchema = z14.strictObject({
3379
+ var providerCapabilitiesSchema = z15.strictObject({
3174
3380
  /** Event types the adapter can produce. */
3175
- lifecycleEvents: z14.array(canonicalEventTypeSchema).max(32).readonly(),
3381
+ lifecycleEvents: z15.array(canonicalEventTypeSchema).max(32).readonly(),
3176
3382
  usageTemporality: usageTemporalitySchema,
3177
3383
  /**
3178
3384
  * Which accumulator series a `cumulative` report continues — that is, which
@@ -3191,32 +3397,32 @@ var providerCapabilitiesSchema = z14.strictObject({
3191
3397
  * Subagent snapshots keep their own series regardless: a delegated agent's
3192
3398
  * counter is not a point on the parent session's curve.
3193
3399
  */
3194
- cumulativeUsageSeries: z14.enum(["event-scope", "session-lifetime"]).optional(),
3195
- reportsCachedInput: z14.boolean(),
3196
- reportsCacheCreation: z14.boolean(),
3400
+ cumulativeUsageSeries: z15.enum(["event-scope", "session-lifetime"]).optional(),
3401
+ reportsCachedInput: z15.boolean(),
3402
+ reportsCacheCreation: z15.boolean(),
3197
3403
  cacheCreationAccounting: cacheCreationAccountingSchema,
3198
- reportsReasoningOutput: z14.boolean(),
3199
- reportsProviderTotal: z14.boolean(),
3200
- reportsCost: z14.boolean(),
3201
- emitsSubagentEvents: z14.boolean(),
3202
- emitsCompactionEvents: z14.boolean(),
3404
+ reportsReasoningOutput: z15.boolean(),
3405
+ reportsProviderTotal: z15.boolean(),
3406
+ reportsCost: z15.boolean(),
3407
+ emitsSubagentEvents: z15.boolean(),
3408
+ emitsCompactionEvents: z15.boolean(),
3203
3409
  /** True when the provider reads a structured response from stdout. */
3204
- requiresHookResponse: z14.boolean(),
3410
+ requiresHookResponse: z15.boolean(),
3205
3411
  /** How much of this provider's hook traffic is replay-identifiable. */
3206
3412
  deliveryIdentifier: deliveryIdentifierSupportSchema
3207
3413
  });
3208
- var providerHookResponseSchema = z14.strictObject({
3414
+ var providerHookResponseSchema = z15.strictObject({
3209
3415
  /**
3210
3416
  * Always 0. A telemetry hook that can fail the host agent is a liability, so
3211
3417
  * the type forbids expressing anything else (ADR 0004).
3212
3418
  */
3213
- exitCode: z14.literal(0),
3419
+ exitCode: z15.literal(0),
3214
3420
  /** Protocol response text. Omit to write nothing at all. */
3215
- stdout: z14.string().max(8192).optional(),
3421
+ stdout: z15.string().max(8192).optional(),
3216
3422
  /** Non-sensitive diagnostic text for stderr. */
3217
- stderr: z14.string().max(8192).optional(),
3423
+ stderr: z15.string().max(8192).optional(),
3218
3424
  /** Declares which of the two stdout contracts this response follows. */
3219
- contract: z14.enum(["silent", "provider-protocol"])
3425
+ contract: z15.enum(["silent", "provider-protocol"])
3220
3426
  });
3221
3427
  var SILENT_HOOK_RESPONSE = Object.freeze({
3222
3428
  exitCode: 0,
@@ -3235,30 +3441,645 @@ var readDeliveryClaim = (adapter, input, context) => {
3235
3441
  if (candidate === void 0) {
3236
3442
  return {};
3237
3443
  }
3238
- const parsed = providerDeliveryClaimSchema.safeParse(candidate);
3239
- if (!parsed.success) {
3444
+ const parsed = providerDeliveryClaimSchema.safeParse(candidate);
3445
+ if (!parsed.success) {
3446
+ return {
3447
+ rejection: `adapter ${adapter.id} reported a malformed delivery identity: ${parsed.error.issues.map((issue) => `${issue.path.join(".") || "<root>"} ${issue.message}`).join("; ")}`.slice(0, 240)
3448
+ };
3449
+ }
3450
+ return { claim: parsed.data };
3451
+ };
3452
+ var readDeliveryGap = (adapter, sourceEventName) => {
3453
+ if (sourceEventName === void 0 || adapter.deliveryGaps === void 0) {
3454
+ return void 0;
3455
+ }
3456
+ if (!Object.prototype.hasOwnProperty.call(adapter.deliveryGaps, sourceEventName)) {
3457
+ return void 0;
3458
+ }
3459
+ const parsed = deliveryGapReasonSchema.safeParse(adapter.deliveryGaps[sourceEventName]);
3460
+ return parsed.success ? parsed.data : void 0;
3461
+ };
3462
+ var asProviderId = (value) => providerIdSchema.parse(value);
3463
+ var unknownDetection = (reasons = ["no adapter recognized the input"]) => providerDetectionSchema.parse({
3464
+ providerId: "unknown",
3465
+ confidence: "none",
3466
+ reasons: reasons.slice(0, 8)
3467
+ });
3468
+
3469
+ // src/providers/claude/schema.ts
3470
+ import { z as z16 } from "zod";
3471
+ var commonFields = {
3472
+ session_id: z16.string().min(1),
3473
+ transcript_path: z16.string().min(1).optional(),
3474
+ cwd: z16.string().min(1).optional(),
3475
+ permission_mode: z16.string().min(1).optional(),
3476
+ /** Correlates a hook firing with the user prompt that triggered it (Claude Code v2.1.196+). */
3477
+ prompt_id: z16.string().min(1).optional(),
3478
+ /** Present when the hook fired while running inside a subagent. */
3479
+ agent_id: z16.string().min(1).optional(),
3480
+ agent_type: z16.string().min(1).optional()
3481
+ };
3482
+ var claudeCacheCreationSchema = z16.object({
3483
+ ephemeral_5m_input_tokens: z16.number().int().min(0).optional(),
3484
+ ephemeral_1h_input_tokens: z16.number().int().min(0).optional()
3485
+ });
3486
+ var claudeUsageIterationSchema = z16.object({
3487
+ input_tokens: z16.number().int().min(0).optional(),
3488
+ output_tokens: z16.number().int().min(0).optional(),
3489
+ cache_creation_input_tokens: z16.number().int().min(0).optional(),
3490
+ cache_read_input_tokens: z16.number().int().min(0).optional()
3491
+ });
3492
+ var claudeUsageSchema = z16.object({
3493
+ input_tokens: z16.number().int().min(0),
3494
+ output_tokens: z16.number().int().min(0),
3495
+ cache_creation_input_tokens: z16.number().int().min(0).optional(),
3496
+ cache_read_input_tokens: z16.number().int().min(0).optional(),
3497
+ cache_creation: claudeCacheCreationSchema.optional(),
3498
+ iterations: z16.array(claudeUsageIterationSchema).optional(),
3499
+ /**
3500
+ * Counters the canonical model has a home for but Claude Code never reports:
3501
+ * 0 of 4,999 real usage objects carried either (finding 5).
3502
+ *
3503
+ * Named here rather than left to the object's forward-compatible looseness so
3504
+ * that a harness attaching one gets told it was excluded, instead of watching
3505
+ * it vanish. See `CLAUDE_EXCLUDED_USAGE_COUNTERS`.
3506
+ */
3507
+ total_tokens: z16.number().int().min(0).optional(),
3508
+ reasoning_output_tokens: z16.number().int().min(0).optional()
3509
+ });
3510
+ var sessionStartPayloadSchema = z16.object({
3511
+ ...commonFields,
3512
+ hook_event_name: z16.literal("SessionStart"),
3513
+ /** Matcher values: startup | resume | clear | compact | fork. Forward-compatible: any string. */
3514
+ source: z16.string().min(1).optional(),
3515
+ model: z16.string().min(1).optional(),
3516
+ session_title: z16.string().min(1).optional()
3517
+ });
3518
+ var sessionEndPayloadSchema = z16.object({
3519
+ ...commonFields,
3520
+ hook_event_name: z16.literal("SessionEnd"),
3521
+ /** Current Claude Code field; values include clear, logout, prompt_input_exit, and other. */
3522
+ reason: z16.string().min(1).optional(),
3523
+ /** Compatibility alias emitted by older wrappers and hook integrations. */
3524
+ end_reason: z16.string().min(1).optional()
3525
+ });
3526
+ var userPromptSubmitPayloadSchema = z16.object({
3527
+ ...commonFields,
3528
+ hook_event_name: z16.literal("UserPromptSubmit"),
3529
+ prompt: z16.string()
3530
+ });
3531
+ var preToolUsePayloadSchema = z16.object({
3532
+ ...commonFields,
3533
+ hook_event_name: z16.literal("PreToolUse"),
3534
+ tool_name: z16.string().min(1),
3535
+ tool_input: z16.unknown(),
3536
+ tool_use_id: z16.string().min(1)
3537
+ });
3538
+ var postToolUsePayloadSchema = z16.object({
3539
+ ...commonFields,
3540
+ hook_event_name: z16.literal("PostToolUse"),
3541
+ tool_name: z16.string().min(1),
3542
+ tool_input: z16.unknown().optional(),
3543
+ tool_response: z16.unknown(),
3544
+ tool_use_id: z16.string().min(1)
3545
+ });
3546
+ var postToolUseFailurePayloadSchema = z16.object({
3547
+ ...commonFields,
3548
+ hook_event_name: z16.literal("PostToolUseFailure"),
3549
+ tool_name: z16.string().min(1),
3550
+ tool_input: z16.unknown().optional(),
3551
+ tool_error: z16.unknown(),
3552
+ tool_use_id: z16.string().min(1)
3553
+ });
3554
+ var permissionRequestPayloadSchema = z16.object({
3555
+ ...commonFields,
3556
+ hook_event_name: z16.literal("PermissionRequest"),
3557
+ tool_name: z16.string().min(1),
3558
+ tool_input: z16.unknown().optional(),
3559
+ tool_use_id: z16.string().min(1)
3560
+ });
3561
+ var subagentStartPayloadSchema = z16.object({
3562
+ ...commonFields,
3563
+ hook_event_name: z16.literal("SubagentStart"),
3564
+ agent_type: z16.string().min(1),
3565
+ agent_id: z16.string().min(1)
3566
+ });
3567
+ var subagentStopPayloadSchema = z16.object({
3568
+ ...commonFields,
3569
+ hook_event_name: z16.literal("SubagentStop"),
3570
+ agent_type: z16.string().min(1),
3571
+ agent_id: z16.string().min(1),
3572
+ last_assistant_message: z16.string().optional(),
3573
+ /** True when this stop fired because a hook continued the subagent's turn. */
3574
+ stop_hook_active: z16.boolean().optional(),
3575
+ usage: claudeUsageSchema.optional()
3576
+ });
3577
+ var preCompactPayloadSchema = z16.object({
3578
+ ...commonFields,
3579
+ hook_event_name: z16.literal("PreCompact"),
3580
+ /** Upstream values: manual | auto. Forward-compatible: any string. */
3581
+ trigger: z16.string().min(1).optional(),
3582
+ /** Compatibility alias emitted by older wrappers and hook integrations. */
3583
+ compact_trigger: z16.string().min(1).optional(),
3584
+ /**
3585
+ * Harness-supplied, never upstream. Reported as an explicit exclusion rather
3586
+ * than carried across the process boundary: see `events.ts`.
3587
+ */
3588
+ context_tokens_before: z16.number().int().min(0).optional(),
3589
+ estimated_tokens_removed: z16.number().int().min(0).optional()
3590
+ });
3591
+ var postCompactPayloadSchema = z16.object({
3592
+ ...commonFields,
3593
+ hook_event_name: z16.literal("PostCompact"),
3594
+ trigger: z16.string().min(1).optional(),
3595
+ compact_trigger: z16.string().min(1).optional(),
3596
+ /** Harness-supplied, never upstream; accepted here because one callback carries both. */
3597
+ context_tokens_before: z16.number().int().min(0).optional(),
3598
+ context_tokens_after: z16.number().int().min(0).optional(),
3599
+ dropped_message_count: z16.number().int().min(0).optional(),
3600
+ usage: claudeUsageSchema.optional()
3601
+ });
3602
+ var stopPayloadSchema = z16.object({
3603
+ ...commonFields,
3604
+ hook_event_name: z16.literal("Stop"),
3605
+ /**
3606
+ * Interactive Stop field (Claude Code ≥ 2.1.47). Print / `-p` / Agent SDK
3607
+ * result messages use `result` instead; `events.ts` reads both (and camelCase
3608
+ * `lastAssistantMessage`) through `extractClaudeAssistantText`.
3609
+ */
3610
+ last_assistant_message: z16.string().optional(),
3611
+ /** Print / `-p` JSON result field; accepted so a harness can attach it as-is. */
3612
+ result: z16.string().optional(),
3613
+ /**
3614
+ * True when this stop fired because a hook continued the turn.
3615
+ *
3616
+ * Required upstream, optional here. It is what separates the once-per-prompt
3617
+ * stop from a continuation stop, which is what lets `delivery.ts` deduplicate
3618
+ * the former without suppressing the latter.
3619
+ */
3620
+ stop_hook_active: z16.boolean().optional(),
3621
+ usage: claudeUsageSchema.optional(),
3622
+ /**
3623
+ * The model that answered this turn — harness-supplied, never upstream.
3624
+ *
3625
+ * Claude Code's `Stop` carries no model id; the per-turn model sits only at
3626
+ * `message.model` in the transcript, beside `message.usage`. A wrapping harness
3627
+ * that read it (for instance with `readClaudeTranscriptTurn`) attaches it here
3628
+ * with `usage`, and it becomes the generation's response model. An unusable
3629
+ * value (empty, over 256 characters, not a string) is dropped rather than
3630
+ * failing the whole payload: the turn is still worth reporting without it.
3631
+ */
3632
+ model: z16.string().min(1).max(256).optional().catch(void 0),
3633
+ /**
3634
+ * Harness-supplied, never upstream: whether `usage` covers only part of the
3635
+ * turn. `true` when it is the last model request alone (the tail fallback),
3636
+ * `false` when it sums every request since the previous stop. Exported as
3637
+ * `otelhook.usage.partial`; absent means the attacher did not say.
3638
+ */
3639
+ usage_partial: z16.boolean().optional().catch(void 0)
3640
+ });
3641
+ var stopFailurePayloadSchema = z16.object({
3642
+ ...commonFields,
3643
+ hook_event_name: z16.literal("StopFailure"),
3644
+ /**
3645
+ * Matcher values: rate_limit | overloaded | authentication_failed |
3646
+ * oauth_org_not_allowed | billing_error | invalid_request | model_not_found
3647
+ * | server_error | max_output_tokens | unknown.
3648
+ */
3649
+ error_type: z16.string().min(1),
3650
+ error_message: z16.string().optional(),
3651
+ usage: claudeUsageSchema.optional(),
3652
+ /** Harness-supplied, never upstream: see `stopPayloadSchema.model`. */
3653
+ model: z16.string().min(1).max(256).optional().catch(void 0),
3654
+ /** Harness-supplied, never upstream: see `stopPayloadSchema.usage_partial`. */
3655
+ usage_partial: z16.boolean().optional().catch(void 0)
3656
+ });
3657
+ var claudeHookPayloadSchema = z16.discriminatedUnion("hook_event_name", [
3658
+ sessionStartPayloadSchema,
3659
+ sessionEndPayloadSchema,
3660
+ userPromptSubmitPayloadSchema,
3661
+ preToolUsePayloadSchema,
3662
+ postToolUsePayloadSchema,
3663
+ postToolUseFailurePayloadSchema,
3664
+ permissionRequestPayloadSchema,
3665
+ subagentStartPayloadSchema,
3666
+ subagentStopPayloadSchema,
3667
+ preCompactPayloadSchema,
3668
+ postCompactPayloadSchema,
3669
+ stopPayloadSchema,
3670
+ stopFailurePayloadSchema
3671
+ ]);
3672
+ var CLAUDE_HOOK_EVENT_NAMES = [
3673
+ "SessionStart",
3674
+ "SessionEnd",
3675
+ "UserPromptSubmit",
3676
+ "PreToolUse",
3677
+ "PostToolUse",
3678
+ "PostToolUseFailure",
3679
+ "PermissionRequest",
3680
+ "SubagentStart",
3681
+ "SubagentStop",
3682
+ "PreCompact",
3683
+ "PostCompact",
3684
+ "Stop",
3685
+ "StopFailure"
3686
+ ];
3687
+ var claudeIdentityFieldsSchema = z16.object({
3688
+ session_id: z16.string().min(1),
3689
+ hook_event_name: z16.string().min(1),
3690
+ cwd: z16.string().min(1).optional(),
3691
+ prompt_id: z16.string().min(1).optional(),
3692
+ agent_id: z16.string().min(1).optional(),
3693
+ tool_use_id: z16.string().min(1).optional(),
3694
+ /** Read by `delivery.ts` to tell a once-per-prompt stop from a continuation. */
3695
+ stop_hook_active: z16.boolean().optional()
3696
+ });
3697
+
3698
+ // src/providers/claude/usage.ts
3699
+ var CLAUDE_EXCLUDED_USAGE_COUNTERS = Object.freeze({
3700
+ total_tokens: `usage.total_tokens is outside Claude Code's usage contract (capability reportsProviderTotal=false): it is not read, so providerTotalAgreement stays "unreported"`,
3701
+ reasoning_output_tokens: "usage.reasoning_output_tokens is outside Claude Code's usage contract (capability reportsReasoningOutput=false): Anthropic bills thinking tokens inside output_tokens with no separate counter, so it is not read and reasoningOutputTokens stays 0"
3702
+ });
3703
+ var asRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
3704
+ var asNonNegativeInt = (value) => typeof value === "number" && Number.isInteger(value) && value >= 0 ? value : void 0;
3705
+ var coerceClaudeUsage = (value) => {
3706
+ const record = asRecord(value);
3707
+ if (record === void 0) {
3708
+ return void 0;
3709
+ }
3710
+ const inputTokens = asNonNegativeInt(record.input_tokens ?? record.inputTokens);
3711
+ const outputTokens = asNonNegativeInt(record.output_tokens ?? record.outputTokens);
3712
+ if (inputTokens === void 0 || outputTokens === void 0) {
3713
+ return void 0;
3714
+ }
3715
+ const cacheCreation = asRecord(record.cache_creation ?? record.cacheCreation);
3716
+ const parsed = claudeUsageSchema.safeParse({
3717
+ input_tokens: inputTokens,
3718
+ output_tokens: outputTokens,
3719
+ ...asNonNegativeInt(record.cache_creation_input_tokens ?? record.cacheCreationInputTokens) === void 0 ? {} : {
3720
+ cache_creation_input_tokens: asNonNegativeInt(
3721
+ record.cache_creation_input_tokens ?? record.cacheCreationInputTokens
3722
+ )
3723
+ },
3724
+ ...asNonNegativeInt(record.cache_read_input_tokens ?? record.cacheReadInputTokens) === void 0 ? {} : {
3725
+ cache_read_input_tokens: asNonNegativeInt(
3726
+ record.cache_read_input_tokens ?? record.cacheReadInputTokens
3727
+ )
3728
+ },
3729
+ ...cacheCreation === void 0 ? {} : {
3730
+ cache_creation: {
3731
+ ...asNonNegativeInt(
3732
+ cacheCreation.ephemeral_5m_input_tokens ?? cacheCreation.ephemeral5mInputTokens
3733
+ ) === void 0 ? {} : {
3734
+ ephemeral_5m_input_tokens: asNonNegativeInt(
3735
+ cacheCreation.ephemeral_5m_input_tokens ?? cacheCreation.ephemeral5mInputTokens
3736
+ )
3737
+ },
3738
+ ...asNonNegativeInt(
3739
+ cacheCreation.ephemeral_1h_input_tokens ?? cacheCreation.ephemeral1hInputTokens
3740
+ ) === void 0 ? {} : {
3741
+ ephemeral_1h_input_tokens: asNonNegativeInt(
3742
+ cacheCreation.ephemeral_1h_input_tokens ?? cacheCreation.ephemeral1hInputTokens
3743
+ )
3744
+ }
3745
+ }
3746
+ },
3747
+ ...Array.isArray(record.iterations) ? { iterations: record.iterations } : {},
3748
+ ...asNonNegativeInt(record.total_tokens ?? record.totalTokens) === void 0 ? {} : { total_tokens: asNonNegativeInt(record.total_tokens ?? record.totalTokens) },
3749
+ ...asNonNegativeInt(record.reasoning_output_tokens ?? record.reasoningOutputTokens) === void 0 ? {} : {
3750
+ reasoning_output_tokens: asNonNegativeInt(
3751
+ record.reasoning_output_tokens ?? record.reasoningOutputTokens
3752
+ )
3753
+ }
3754
+ });
3755
+ return parsed.success ? parsed.data : void 0;
3756
+ };
3757
+
3758
+ // src/providers/claude/payload-normalize.ts
3759
+ var FIELD_ALIASES = Object.freeze({
3760
+ hookEventName: "hook_event_name",
3761
+ sessionId: "session_id",
3762
+ lastAssistantMessage: "last_assistant_message",
3763
+ transcriptPath: "transcript_path",
3764
+ promptId: "prompt_id",
3765
+ toolUseId: "tool_use_id",
3766
+ toolName: "tool_name",
3767
+ toolInput: "tool_input",
3768
+ toolResponse: "tool_response",
3769
+ toolError: "tool_error",
3770
+ stopHookActive: "stop_hook_active",
3771
+ agentId: "agent_id",
3772
+ agentType: "agent_type",
3773
+ errorType: "error_type",
3774
+ errorMessage: "error_message",
3775
+ tokenUsage: "token_usage"
3776
+ });
3777
+
3778
+ // src/providers/claude/detect.ts
3779
+ var CLAUDE_CODE_PROVIDER_ID = asProviderId("claude-code");
3780
+ var KNOWN_EVENT_NAMES = new Set(CLAUDE_HOOK_EVENT_NAMES);
3781
+
3782
+ // src/providers/claude/transcript.ts
3783
+ var DEFAULT_CLAUDE_TRANSCRIPT_TAIL_BYTES = 1048576;
3784
+ var DEFAULT_CLAUDE_TRANSCRIPT_TIMEOUT_MILLIS = 250;
3785
+ var DEFAULT_CLAUDE_TRANSCRIPT_RANGE_BYTES = 8388608;
3786
+ var DEFAULT_CLAUDE_TRANSCRIPT_RANGE_TIMEOUT_MILLIS = 500;
3787
+ var MIN_TAIL_BYTES = 65536;
3788
+ var MAX_TAIL_BYTES = 16777216;
3789
+ var MAX_RANGE_BYTES = 67108864;
3790
+ var MIN_TIMEOUT_MILLIS = 10;
3791
+ var MAX_TIMEOUT_MILLIS = 5e3;
3792
+ var MAX_MODEL_ID_LENGTH = 256;
3793
+ var MAX_REQUESTS_PER_RANGE = 1e4;
3794
+ var SYNTHETIC_MODEL = "<synthetic>";
3795
+ var TIMED_OUT = /* @__PURE__ */ Symbol("timed-out");
3796
+ var clamp = (value, fallback, min, max) => {
3797
+ if (value === void 0 || !Number.isFinite(value)) {
3798
+ return fallback;
3799
+ }
3800
+ return Math.min(max, Math.max(min, Math.floor(value)));
3801
+ };
3802
+ var asRecord2 = (value) => typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
3803
+ var isTranscriptPath = (transcriptPath) => typeof transcriptPath === "string" && transcriptPath.length > 0 && !transcriptPath.includes("\0") && path.isAbsolute(transcriptPath) && path.extname(transcriptPath) === ".jsonl";
3804
+ var assistantRecordOf = (line) => {
3805
+ if (!line.includes('"assistant"')) {
3806
+ return void 0;
3807
+ }
3808
+ let parsed;
3809
+ try {
3810
+ parsed = JSON.parse(line);
3811
+ } catch {
3812
+ return void 0;
3813
+ }
3814
+ const record = asRecord2(parsed);
3815
+ if (record === void 0 || record.type !== "assistant" || record.isSidechain === true) {
3816
+ return void 0;
3817
+ }
3818
+ const message = asRecord2(record.message);
3819
+ if (message === void 0 || message.model === SYNTHETIC_MODEL) {
3820
+ return void 0;
3821
+ }
3822
+ const model = typeof message.model === "string" && message.model.length > 0 && message.model.length <= MAX_MODEL_ID_LENGTH ? message.model : void 0;
3823
+ const usage = coerceClaudeUsage(message.usage);
3824
+ if (model === void 0 && usage === void 0) {
3825
+ return void 0;
3826
+ }
3827
+ const id = typeof message.id === "string" && message.id.length > 0 && message.id.length <= 256 ? message.id : void 0;
3828
+ return {
3829
+ ...id === void 0 ? {} : { id },
3830
+ ...model === void 0 ? {} : { model },
3831
+ ...usage === void 0 ? {} : { usage }
3832
+ };
3833
+ };
3834
+ var cacheCreationOf = (usage) => usage.cache_creation_input_tokens ?? (usage.cache_creation === void 0 ? 0 : (usage.cache_creation.ephemeral_5m_input_tokens ?? 0) + (usage.cache_creation.ephemeral_1h_input_tokens ?? 0));
3835
+ var sumUsage = (usages) => {
3836
+ let input = 0;
3837
+ let output = 0;
3838
+ let cacheRead = 0;
3839
+ let cacheCreation = 0;
3840
+ for (const usage of usages) {
3841
+ input += usage.input_tokens;
3842
+ output += usage.output_tokens;
3843
+ cacheRead += usage.cache_read_input_tokens ?? 0;
3844
+ cacheCreation += cacheCreationOf(usage);
3845
+ }
3846
+ return {
3847
+ input_tokens: input,
3848
+ output_tokens: output,
3849
+ cache_read_input_tokens: cacheRead,
3850
+ cache_creation_input_tokens: cacheCreation
3851
+ };
3852
+ };
3853
+ var withTimeout = async (work, timeoutMillis, onError) => {
3854
+ let timer;
3855
+ const timeout = new Promise((resolve3) => {
3856
+ timer = setTimeout(() => {
3857
+ resolve3(TIMED_OUT);
3858
+ }, timeoutMillis);
3859
+ timer.unref();
3860
+ });
3861
+ try {
3862
+ return await Promise.race([work.catch(() => onError), timeout]);
3863
+ } finally {
3864
+ clearTimeout(timer);
3865
+ }
3866
+ };
3867
+ var withRegularFile = async (transcriptPath, body) => {
3868
+ let info;
3869
+ try {
3870
+ info = await stat(transcriptPath);
3871
+ } catch {
3872
+ return { status: "unavailable", reason: "unreadable" };
3873
+ }
3874
+ if (!info.isFile()) {
3875
+ return { status: "unavailable", reason: "not-a-file" };
3876
+ }
3877
+ let handle;
3878
+ try {
3879
+ handle = await open(transcriptPath, "r");
3880
+ } catch {
3881
+ return { status: "unavailable", reason: "unreadable" };
3882
+ }
3883
+ try {
3884
+ const { size } = await handle.stat();
3885
+ return await body(handle, size);
3886
+ } catch {
3887
+ return { status: "unavailable", reason: "unreadable" };
3888
+ } finally {
3889
+ await handle.close().catch(() => void 0);
3890
+ }
3891
+ };
3892
+ var readBytes = async (handle, start, length) => {
3893
+ const buffer = Buffer.alloc(length);
3894
+ let filled = 0;
3895
+ while (filled < length) {
3896
+ const { bytesRead } = await handle.read(buffer, filled, length - filled, start + filled);
3897
+ if (bytesRead === 0) {
3898
+ break;
3899
+ }
3900
+ filled += bytesRead;
3901
+ }
3902
+ return buffer.subarray(0, filled);
3903
+ };
3904
+ var completeLinesEnd = (bytes, start) => {
3905
+ const lastNewline = bytes.lastIndexOf(10);
3906
+ return lastNewline < 0 ? start : start + lastNewline + 1;
3907
+ };
3908
+ var readTail = (transcriptPath, maxTailBytes) => withRegularFile(transcriptPath, async (handle, size) => {
3909
+ const length = Math.min(size, maxTailBytes);
3910
+ const start = size - length;
3911
+ const bytes = await readBytes(handle, start, length);
3912
+ const endOffset = completeLinesEnd(bytes, start);
3913
+ const lines = bytes.toString("utf8").split("\n");
3914
+ if (start > 0) {
3915
+ lines.shift();
3916
+ }
3917
+ for (let index = lines.length - 1; index >= 0; index -= 1) {
3918
+ const record = assistantRecordOf((lines[index] ?? "").trim());
3919
+ if (record !== void 0) {
3920
+ return {
3921
+ turn: {
3922
+ status: "found",
3923
+ ...record.model === void 0 ? {} : { model: record.model },
3924
+ ...record.usage === void 0 ? {} : { usage: record.usage }
3925
+ },
3926
+ endOffset
3927
+ };
3928
+ }
3929
+ }
3930
+ return { turn: { status: "unavailable", reason: "no-assistant-message" }, endOffset };
3931
+ });
3932
+ var boundedTail = async (transcriptPath, options) => withTimeout(
3933
+ readTail(
3934
+ transcriptPath,
3935
+ clamp(options.maxTailBytes, DEFAULT_CLAUDE_TRANSCRIPT_TAIL_BYTES, MIN_TAIL_BYTES, MAX_TAIL_BYTES)
3936
+ ),
3937
+ clamp(options.timeoutMillis, DEFAULT_CLAUDE_TRANSCRIPT_TIMEOUT_MILLIS, MIN_TIMEOUT_MILLIS, MAX_TIMEOUT_MILLIS),
3938
+ { status: "unavailable", reason: "unreadable" }
3939
+ );
3940
+ var readClaudeTranscriptRange = async (transcriptPath, fromOffset, options = {}) => {
3941
+ if (!isTranscriptPath(transcriptPath) || !Number.isSafeInteger(fromOffset) || fromOffset < 0) {
3942
+ return { status: "unavailable", reason: "invalid-path" };
3943
+ }
3944
+ const maxRangeBytes = clamp(options.maxRangeBytes, DEFAULT_CLAUDE_TRANSCRIPT_RANGE_BYTES, MIN_TAIL_BYTES, MAX_RANGE_BYTES);
3945
+ const timeoutMillis = clamp(
3946
+ options.rangeTimeoutMillis,
3947
+ DEFAULT_CLAUDE_TRANSCRIPT_RANGE_TIMEOUT_MILLIS,
3948
+ MIN_TIMEOUT_MILLIS,
3949
+ MAX_TIMEOUT_MILLIS
3950
+ );
3951
+ const work = withRegularFile(transcriptPath, async (handle, size) => {
3952
+ if (size < fromOffset) {
3953
+ return { status: "unavailable", reason: "truncated" };
3954
+ }
3955
+ if (size - fromOffset > maxRangeBytes) {
3956
+ return { status: "unavailable", reason: "over-cap" };
3957
+ }
3958
+ const bytes = await readBytes(handle, fromOffset, size - fromOffset);
3959
+ const endOffset = completeLinesEnd(bytes, fromOffset);
3960
+ const complete = bytes.subarray(0, endOffset - fromOffset).toString("utf8");
3961
+ const requests = /* @__PURE__ */ new Map();
3962
+ let anonymous = 0;
3963
+ let model;
3964
+ for (const line of complete.split("\n")) {
3965
+ const record = assistantRecordOf(line.trim());
3966
+ if (record === void 0) {
3967
+ continue;
3968
+ }
3969
+ if (record.model !== void 0) {
3970
+ model = record.model;
3971
+ }
3972
+ anonymous += record.id === void 0 ? 1 : 0;
3973
+ requests.set(record.id ?? `#${String(anonymous)}`, record);
3974
+ if (requests.size > MAX_REQUESTS_PER_RANGE) {
3975
+ return { status: "unavailable", reason: "over-cap" };
3976
+ }
3977
+ }
3978
+ const usages = [...requests.values()].flatMap((record) => record.usage === void 0 ? [] : [record.usage]);
3240
3979
  return {
3241
- rejection: `adapter ${adapter.id} reported a malformed delivery identity: ${parsed.error.issues.map((issue) => `${issue.path.join(".") || "<root>"} ${issue.message}`).join("; ")}`.slice(0, 240)
3980
+ status: "found",
3981
+ ...model === void 0 ? {} : { model },
3982
+ ...usages.length === 0 ? {} : { usage: sumUsage(usages) },
3983
+ requestCount: requests.size,
3984
+ endOffset
3242
3985
  };
3243
- }
3244
- return { claim: parsed.data };
3986
+ });
3987
+ const result = await withTimeout(work, timeoutMillis, {
3988
+ status: "unavailable",
3989
+ reason: "unreadable"
3990
+ });
3991
+ return result === TIMED_OUT ? { status: "unavailable", reason: "timeout" } : result;
3245
3992
  };
3246
- var readDeliveryGap = (adapter, sourceEventName) => {
3247
- if (sourceEventName === void 0 || adapter.deliveryGaps === void 0) {
3248
- return void 0;
3249
- }
3250
- if (!Object.prototype.hasOwnProperty.call(adapter.deliveryGaps, sourceEventName)) {
3251
- return void 0;
3252
- }
3253
- const parsed = deliveryGapReasonSchema.safeParse(adapter.deliveryGaps[sourceEventName]);
3254
- return parsed.success ? parsed.data : void 0;
3993
+ var STOP_EVENTS = /* @__PURE__ */ new Set(["Stop", "StopFailure"]);
3994
+ var hasUsage = (record) => record.usage !== void 0 || record.token_usage !== void 0 || record.tokenUsage !== void 0;
3995
+ var eventNameOf = (record) => record.hook_event_name ?? record.hookEventName;
3996
+ var transcriptPathOf = (record) => record.transcript_path ?? record.transcriptPath;
3997
+ var CLAUDE_TRANSCRIPT_USAGE_ENRICHER_ID = "claude-transcript-usage";
3998
+ var sourceDigest = (transcriptPath) => createHash3("sha256").update(transcriptPath, "utf8").digest("hex").slice(0, 32);
3999
+ var createClaudeTranscriptUsageEnricher = (options = {}) => {
4000
+ const fileSize = async (transcriptPath) => {
4001
+ try {
4002
+ const info = await stat(transcriptPath);
4003
+ return info.isFile() ? info.size : void 0;
4004
+ } catch (thrown) {
4005
+ return thrown?.code === "ENOENT" ? "absent" : void 0;
4006
+ }
4007
+ };
4008
+ const enrich = async (input) => {
4009
+ const unchanged = { payload: input.payload };
4010
+ const record = asRecord2(input.payload);
4011
+ if (record === void 0) {
4012
+ return unchanged;
4013
+ }
4014
+ const eventName = eventNameOf(record);
4015
+ const transcriptPath = transcriptPathOf(record);
4016
+ if (typeof eventName !== "string" || !isTranscriptPath(transcriptPath)) {
4017
+ return unchanged;
4018
+ }
4019
+ const source = sourceDigest(transcriptPath);
4020
+ const cursor = input.cursor?.source === source ? input.cursor : void 0;
4021
+ if (eventName === "SessionStart") {
4022
+ if (cursor !== void 0) {
4023
+ return unchanged;
4024
+ }
4025
+ const size = await fileSize(transcriptPath);
4026
+ if (size === void 0) {
4027
+ return { ...unchanged, notes: ["transcript is not a readable regular file; no cursor recorded"] };
4028
+ }
4029
+ return { payload: input.payload, cursor: { source, offset: size === "absent" ? 0 : size } };
4030
+ }
4031
+ if (!STOP_EVENTS.has(eventName)) {
4032
+ return unchanged;
4033
+ }
4034
+ if (hasUsage(record)) {
4035
+ const size = await fileSize(transcriptPath);
4036
+ return typeof size === "number" ? { payload: input.payload, cursor: { source, offset: size } } : unchanged;
4037
+ }
4038
+ const attach = (model, usage, partial) => ({
4039
+ ...record,
4040
+ ...record.model === void 0 && model !== void 0 ? { model } : {},
4041
+ ...usage === void 0 ? {} : { usage, usage_partial: partial }
4042
+ });
4043
+ if (cursor !== void 0) {
4044
+ const range = await readClaudeTranscriptRange(transcriptPath, cursor.offset, options);
4045
+ if (range.status === "found") {
4046
+ return {
4047
+ payload: attach(range.model, range.usage, false),
4048
+ cursor: { source, offset: range.endOffset },
4049
+ notes: [`summed ${String(range.requestCount)} request(s) since the last stop`]
4050
+ };
4051
+ }
4052
+ if (range.reason !== "truncated" && range.reason !== "over-cap") {
4053
+ return { ...unchanged, notes: [`transcript range not read (${range.reason}); cursor kept`] };
4054
+ }
4055
+ }
4056
+ const tail = await boundedTail(transcriptPath, options);
4057
+ if (tail === TIMED_OUT || !("turn" in tail)) {
4058
+ return { ...unchanged, notes: [`transcript tail not read (${tail === TIMED_OUT ? "timeout" : tail.reason})`] };
4059
+ }
4060
+ const why = cursor === void 0 ? "no cursor for this transcript" : "range not summable within bounds";
4061
+ return {
4062
+ payload: tail.turn.status === "found" ? attach(tail.turn.model, tail.turn.usage, true) : input.payload,
4063
+ cursor: { source, offset: tail.endOffset },
4064
+ notes: [`${why}; attached the last request only (usage_partial)`]
4065
+ };
4066
+ };
4067
+ return Object.freeze({
4068
+ id: CLAUDE_TRANSCRIPT_USAGE_ENRICHER_ID,
4069
+ providerId: CLAUDE_CODE_PROVIDER_ID,
4070
+ enrich
4071
+ });
3255
4072
  };
3256
- var unknownDetection = (reasons = ["no adapter recognized the input"]) => providerDetectionSchema.parse({
3257
- providerId: "unknown",
3258
- confidence: "none",
3259
- reasons: reasons.slice(0, 8)
4073
+
4074
+ // src/runtime/clock.ts
4075
+ var createSystemClock = () => ({
4076
+ now: () => epochMillisSchema.parse(Date.now()),
4077
+ monotonicMillis: () => Number(process.hrtime.bigint() / 1000000n)
3260
4078
  });
3261
4079
 
4080
+ // src/runtime/hook.ts
4081
+ import { z as z18 } from "zod";
4082
+
3262
4083
  // src/providers/registry.ts
3263
4084
  var createProviderRegistry = (adapters) => {
3264
4085
  const byId = /* @__PURE__ */ new Map();
@@ -3412,9 +4233,9 @@ var resolveDeliveryIdentity = (input) => {
3412
4233
  };
3413
4234
 
3414
4235
  // src/runtime/ids.ts
3415
- import { createHash as createHash3, randomUUID } from "crypto";
4236
+ import { createHash as createHash4, randomUUID } from "crypto";
3416
4237
  var digest = (namespace, parts) => {
3417
- const hash = createHash3("sha256");
4238
+ const hash = createHash4("sha256");
3418
4239
  hash.update(namespace);
3419
4240
  for (const part of parts) {
3420
4241
  hash.update("\0");
@@ -3453,15 +4274,15 @@ var createDeterministicIdGenerator = (options = {}) => {
3453
4274
  };
3454
4275
 
3455
4276
  // src/runtime/ports.ts
3456
- import { z as z15 } from "zod";
3457
- var appliedDeliverySchema = z15.strictObject({
3458
- callbackId: z15.string().regex(/^[A-Za-z0-9_-]{1,128}$/),
4277
+ import { z as z17 } from "zod";
4278
+ var appliedDeliverySchema = z17.strictObject({
4279
+ callbackId: z17.string().regex(/^[A-Za-z0-9_-]{1,128}$/),
3459
4280
  /** How many of that delivery's observations are folded in, counted from one. */
3460
- applications: z15.number().int().min(1).max(4096)
4281
+ applications: z17.number().int().min(1).max(4096)
3461
4282
  });
3462
- var stateValueSchema = z15.discriminatedUnion("kind", [
3463
- z15.strictObject({
3464
- kind: z15.literal("usage-cumulative"),
4283
+ var stateValueSchema = z17.discriminatedUnion("kind", [
4284
+ z17.strictObject({
4285
+ kind: z17.literal("usage-cumulative"),
3465
4286
  usage: canonicalUsageSchema,
3466
4287
  /**
3467
4288
  * Optional: absent on every record written before this field existed, which
@@ -3470,22 +4291,42 @@ var stateValueSchema = z15.discriminatedUnion("kind", [
3470
4291
  */
3471
4292
  appliedDelivery: appliedDeliverySchema.optional()
3472
4293
  }),
3473
- z15.strictObject({
3474
- kind: z15.literal("sequence"),
4294
+ z17.strictObject({
4295
+ kind: z17.literal("sequence"),
3475
4296
  next: sequenceNumberSchema
3476
4297
  }),
3477
- z15.strictObject({
3478
- kind: z15.literal("attributes"),
4298
+ z17.strictObject({
4299
+ kind: z17.literal("attributes"),
3479
4300
  attributes: attributesSchema
4301
+ }),
4302
+ /**
4303
+ * The model a session last reported, so a later invocation whose payload names
4304
+ * none (Claude Code's `Stop`) can still say which model it was. A model id is
4305
+ * not sensitive (`modelDescriptorSchema`), and the descriptor is the strict,
4306
+ * bounded canonical shape, never a payload fragment.
4307
+ */
4308
+ z17.strictObject({
4309
+ kind: z17.literal("session-model"),
4310
+ model: modelDescriptorSchema
4311
+ }),
4312
+ /**
4313
+ * How far a {@link PayloadEnricher} has read a session's append-only source
4314
+ * (Claude Code's transcript), so the next read starts where the last ended.
4315
+ * `source` is an opaque digest of what was read, never a path.
4316
+ */
4317
+ z17.strictObject({
4318
+ kind: z17.literal("read-cursor"),
4319
+ source: z17.string().regex(/^[A-Za-z0-9_-]{1,128}$/),
4320
+ offset: z17.number().int().min(0).max(Number.MAX_SAFE_INTEGER)
3480
4321
  })
3481
4322
  ]);
3482
- var stateRecordSchema = z15.strictObject({
4323
+ var stateRecordSchema = z17.strictObject({
3483
4324
  /** Incremented on each write; lets callers detect lost updates. */
3484
- revision: z15.number().int().min(0),
4325
+ revision: z17.number().int().min(0),
3485
4326
  updatedAt: epochMillisSchema,
3486
4327
  value: stateValueSchema
3487
4328
  });
3488
- var logLevelSchema = z15.enum(["silent", "error", "warn", "info", "debug"]);
4329
+ var logLevelSchema = z17.enum(["silent", "error", "warn", "info", "debug"]);
3489
4330
  var LOG_LEVEL_RANK = Object.freeze({
3490
4331
  silent: 0,
3491
4332
  error: 1,
@@ -3503,7 +4344,7 @@ var createNullLogger = () => ({
3503
4344
  });
3504
4345
 
3505
4346
  // src/runtime/target-resolution.ts
3506
- import * as path from "path";
4347
+ import * as path2 from "path";
3507
4348
 
3508
4349
  // src/privacy/workspace.ts
3509
4350
  var canonicalizeGitRemote = (remoteUrl) => {
@@ -3555,13 +4396,13 @@ var deriveWorkspaceIdentity = (privacy, input, labels = {}) => {
3555
4396
  // src/runtime/target-resolution.ts
3556
4397
  var DEFAULT_TARGET_RESOLUTION_BUDGET_MILLIS = 50;
3557
4398
  var absolutePathsOf = (hint) => {
3558
- const base = hint.baseDirectory !== void 0 && path.isAbsolute(hint.baseDirectory) ? hint.baseDirectory : void 0;
4399
+ const base = hint.baseDirectory !== void 0 && path2.isAbsolute(hint.baseDirectory) ? hint.baseDirectory : void 0;
3559
4400
  const resolved = [];
3560
4401
  for (const candidate of hint.paths) {
3561
- if (path.isAbsolute(candidate)) {
3562
- resolved.push(path.resolve(candidate));
4402
+ if (path2.isAbsolute(candidate)) {
4403
+ resolved.push(path2.resolve(candidate));
3563
4404
  } else if (base !== void 0) {
3564
- resolved.push(path.resolve(base, candidate));
4405
+ resolved.push(path2.resolve(base, candidate));
3565
4406
  } else {
3566
4407
  return void 0;
3567
4408
  }
@@ -3640,7 +4481,7 @@ var resolveEventTargets = async (input) => {
3640
4481
  };
3641
4482
 
3642
4483
  // src/runtime/hook.ts
3643
- var usageScopeSchema = z16.enum(["session", "generation", "subagent"]);
4484
+ var usageScopeSchema = z18.enum(["session", "generation", "subagent"]);
3644
4485
  var classifyDurability = (input) => {
3645
4486
  if (!input.attempted) {
3646
4487
  return "nothing-to-deliver";
@@ -3698,6 +4539,22 @@ var usageScopeOf = (event2) => {
3698
4539
  }
3699
4540
  };
3700
4541
  var sequenceKey = (sessionId) => `sequence:${sessionId}`;
4542
+ var sessionModelKey = (sessionId) => `model:${sessionId}`;
4543
+ var readCursorKey = (enricherId, sessionId) => `cursor:${enricherId}:${sessionId}`;
4544
+ var UNKNOWN_MODEL_ID = "unknown";
4545
+ var latestSessionModel = (events) => {
4546
+ let latest;
4547
+ for (const event2 of events) {
4548
+ if (event2.subagentId !== void 0) {
4549
+ continue;
4550
+ }
4551
+ if ((event2.type === "session.start" || event2.type === "generation.start" || event2.type === "generation.end") && event2.model !== void 0 && event2.model.modelId !== UNKNOWN_MODEL_ID) {
4552
+ latest = event2.model;
4553
+ }
4554
+ }
4555
+ return latest;
4556
+ };
4557
+ var sameModel = (left, right) => left !== void 0 && left.modelId === right.modelId && left.vendor === right.vendor && left.family === right.family;
3701
4558
  var usageKey = (sessionId, scope, scopeKey) => `usage:${sessionId}:${scope}:${scopeKey}`;
3702
4559
  var baselineScopeOf = (scope, scopeKey, sessionId, series) => series === "session-lifetime" && scope === "generation" ? { scope: "session", scopeKey: sessionId } : { scope, scopeKey };
3703
4560
  var createOtelHook = (deps) => {
@@ -3745,6 +4602,66 @@ var createOtelHook = (deps) => {
3745
4602
  return 0;
3746
4603
  }
3747
4604
  };
4605
+ const enrichPayload = async (payload, providerId, sessionId, diagnostics) => {
4606
+ let current = payload;
4607
+ for (const enricher of deps.payloadEnrichers ?? []) {
4608
+ if (enricher.providerId !== providerId) {
4609
+ continue;
4610
+ }
4611
+ const key = readCursorKey(enricher.id, sessionId);
4612
+ let cursor;
4613
+ try {
4614
+ const record = await deps.stateStore.read(key);
4615
+ if (record?.value.kind === "read-cursor") {
4616
+ cursor = { source: record.value.source, offset: record.value.offset };
4617
+ }
4618
+ } catch (thrown) {
4619
+ diagnostics.push(
4620
+ errorInfoFromThrown(thrown, { code: "state-store-failure", phase: "state", occurredAt: clock.now() })
4621
+ );
4622
+ continue;
4623
+ }
4624
+ let result;
4625
+ try {
4626
+ result = await enricher.enrich({ payload: current, sessionId, ...cursor === void 0 ? {} : { cursor } });
4627
+ } catch (thrown) {
4628
+ logger.warn("payload enricher failed; parsing the payload as delivered", {
4629
+ "enricher.id": enricher.id,
4630
+ "error.name": thrown instanceof Error ? thrown.name : typeof thrown
4631
+ });
4632
+ continue;
4633
+ }
4634
+ current = result.payload;
4635
+ if (result.notes !== void 0 && result.notes.length > 0) {
4636
+ logger.debug("payload enricher notes", {
4637
+ "enricher.id": enricher.id,
4638
+ "enricher.notes": result.notes.slice(0, 8).map((note) => note.slice(0, 200))
4639
+ });
4640
+ }
4641
+ const next = result.cursor;
4642
+ if (next !== void 0 && (next.source !== cursor?.source || next.offset !== cursor.offset)) {
4643
+ try {
4644
+ await deps.stateStore.write(key, { kind: "read-cursor", source: next.source, offset: next.offset });
4645
+ } catch (thrown) {
4646
+ diagnostics.push(
4647
+ errorInfoFromThrown(thrown, { code: "state-store-failure", phase: "state", occurredAt: clock.now() })
4648
+ );
4649
+ }
4650
+ }
4651
+ }
4652
+ return current;
4653
+ };
4654
+ const readSessionModel = async (sessionId, diagnostics) => {
4655
+ try {
4656
+ const record = await deps.stateStore.read(sessionModelKey(sessionId));
4657
+ return record?.value.kind === "session-model" ? record.value.model : void 0;
4658
+ } catch (thrown) {
4659
+ diagnostics.push(
4660
+ errorInfoFromThrown(thrown, { code: "state-store-failure", phase: "state", occurredAt: clock.now() })
4661
+ );
4662
+ return void 0;
4663
+ }
4664
+ };
3748
4665
  const deriveUsage = async (events, diagnostics, suppress, series) => {
3749
4666
  const observations = [];
3750
4667
  for (const event2 of events) {
@@ -4065,10 +4982,19 @@ var createOtelHook = (deps) => {
4065
4982
  const identity = resolution.identity;
4066
4983
  const prepare = async () => {
4067
4984
  const sequenceBase = await readSequenceBase(identity.sessionId, diagnostics);
4985
+ const sessionModel = await readSessionModel(identity.sessionId, diagnostics);
4986
+ const payload = suppress ? detectionInput.payload : await enrichPayload(detectionInput.payload, detection.providerId, identity.sessionId, diagnostics);
4068
4987
  let parsed;
4069
4988
  try {
4070
4989
  parsed = adapter.parse(
4071
- { ...detectionInput, detection, identity, sequenceBase },
4990
+ {
4991
+ ...detectionInput,
4992
+ payload,
4993
+ detection,
4994
+ identity,
4995
+ sequenceBase,
4996
+ ...sessionModel === void 0 ? {} : { sessionModel }
4997
+ },
4072
4998
  providerContext
4073
4999
  );
4074
5000
  } catch (thrown) {
@@ -4178,6 +5104,23 @@ var createOtelHook = (deps) => {
4178
5104
  })
4179
5105
  );
4180
5106
  }
5107
+ const reportedModel = latestSessionModel(screened.kept);
5108
+ if (reportedModel !== void 0 && !sameModel(sessionModel, reportedModel)) {
5109
+ try {
5110
+ await deps.stateStore.write(sessionModelKey(identity.sessionId), {
5111
+ kind: "session-model",
5112
+ model: reportedModel
5113
+ });
5114
+ } catch (thrown) {
5115
+ diagnostics.push(
5116
+ errorInfoFromThrown(thrown, {
5117
+ code: "state-store-failure",
5118
+ phase: "state",
5119
+ occurredAt: clock.now()
5120
+ })
5121
+ );
5122
+ }
5123
+ }
4181
5124
  }
4182
5125
  return {
4183
5126
  kind: "ready",
@@ -4396,8 +5339,8 @@ var buildErrorEvents = (diagnostics, identity, sequenceBase, ids, privacy) => {
4396
5339
  };
4397
5340
 
4398
5341
  // src/runtime/git-worktree.ts
4399
- import { lstat, open, stat } from "fs/promises";
4400
- import * as path2 from "path";
5342
+ import { lstat, open as open2, stat as stat2 } from "fs/promises";
5343
+ import * as path3 from "path";
4401
5344
  var MAX_WORKTREE_WALK_DEPTH = 128;
4402
5345
  var MAX_GIT_FILE_BYTES = 4096;
4403
5346
  var MAX_CACHE_ENTRIES = 1024;
@@ -4408,7 +5351,7 @@ var INVALID = Object.freeze({ kind: "invalid" });
4408
5351
  var readBounded = async (filePath) => {
4409
5352
  let handle;
4410
5353
  try {
4411
- handle = await open(filePath, "r");
5354
+ handle = await open2(filePath, "r");
4412
5355
  const buffer = Buffer.alloc(MAX_GIT_FILE_BYTES);
4413
5356
  const { bytesRead } = await handle.read(buffer, 0, MAX_GIT_FILE_BYTES, 0);
4414
5357
  return buffer.subarray(0, bytesRead).toString("utf8");
@@ -4429,7 +5372,7 @@ var parseHeadBranch = (head) => {
4429
5372
  return branch;
4430
5373
  };
4431
5374
  var firstLine = (content) => content.split(/\r?\n/, 1)[0]?.trim() ?? "";
4432
- var resolveGitPath = (target, base) => target === void 0 || target.length === 0 || target.includes("\0") ? void 0 : path2.resolve(base, target);
5375
+ var resolveGitPath = (target, base) => target === void 0 || target.length === 0 || target.includes("\0") ? void 0 : path3.resolve(base, target);
4433
5376
  var parseGitDirFile = (content, worktreeRoot) => {
4434
5377
  const line = firstLine(content);
4435
5378
  return resolveGitPath(
@@ -4449,26 +5392,26 @@ var isMissing = async (filePath) => {
4449
5392
  };
4450
5393
  var isDirectory = async (directory) => {
4451
5394
  try {
4452
- return (await stat(directory)).isDirectory();
5395
+ return (await stat2(directory)).isDirectory();
4453
5396
  } catch {
4454
5397
  return false;
4455
5398
  }
4456
5399
  };
4457
5400
  var repositoryOf = async (worktreeRoot, gitDir) => {
4458
- const commonDirFile = path2.join(gitDir, "commondir");
5401
+ const commonDirFile = path3.join(gitDir, "commondir");
4459
5402
  const content = await readBounded(commonDirFile);
4460
5403
  if (content === void 0) {
4461
5404
  return await isMissing(commonDirFile) ? { kind: "main", mainRoot: worktreeRoot } : { kind: "linked" };
4462
5405
  }
4463
5406
  const commonDir = parseCommonDirFile(content, gitDir);
4464
- const mainRoot = commonDir !== void 0 && path2.basename(commonDir) === ".git" && await isDirectory(commonDir) ? path2.dirname(commonDir) : void 0;
5407
+ const mainRoot = commonDir !== void 0 && path3.basename(commonDir) === ".git" && await isDirectory(commonDir) ? path3.dirname(commonDir) : void 0;
4465
5408
  return { kind: "linked", ...mainRoot === void 0 ? {} : { mainRoot } };
4466
5409
  };
4467
5410
  var probeDirectory = async (directory) => {
4468
- const dotGit = path2.join(directory, ".git");
5411
+ const dotGit = path3.join(directory, ".git");
4469
5412
  let info;
4470
5413
  try {
4471
- info = await stat(dotGit);
5414
+ info = await stat2(dotGit);
4472
5415
  } catch {
4473
5416
  return ABSENT;
4474
5417
  }
@@ -4482,7 +5425,7 @@ var probeDirectory = async (directory) => {
4482
5425
  if (gitDir === void 0) {
4483
5426
  return INVALID;
4484
5427
  }
4485
- const head = await readBounded(path2.join(gitDir, "HEAD"));
5428
+ const head = await readBounded(path3.join(gitDir, "HEAD"));
4486
5429
  if (head === void 0) {
4487
5430
  return INVALID;
4488
5431
  }
@@ -4512,10 +5455,10 @@ var createFilesystemWorktreeLocator = (options = {}) => {
4512
5455
  };
4513
5456
  const locate = async (absolutePath) => {
4514
5457
  try {
4515
- if (!path2.isAbsolute(absolutePath) || absolutePath.includes("\0")) {
5458
+ if (!path3.isAbsolute(absolutePath) || absolutePath.includes("\0")) {
4516
5459
  return void 0;
4517
5460
  }
4518
- let directory = path2.resolve(absolutePath);
5461
+ let directory = path3.resolve(absolutePath);
4519
5462
  for (let depth = 0; depth < MAX_WORKTREE_WALK_DEPTH; depth += 1) {
4520
5463
  const probe = await cachedProbe(directory);
4521
5464
  if (probe.kind === "worktree") {
@@ -4524,7 +5467,7 @@ var createFilesystemWorktreeLocator = (options = {}) => {
4524
5467
  if (probe.kind === "invalid") {
4525
5468
  return void 0;
4526
5469
  }
4527
- const parent = path2.dirname(directory);
5470
+ const parent = path3.dirname(directory);
4528
5471
  if (parent === directory) {
4529
5472
  return void 0;
4530
5473
  }
@@ -4540,24 +5483,24 @@ var createFilesystemWorktreeLocator = (options = {}) => {
4540
5483
 
4541
5484
  // src/state/filesystem-store.ts
4542
5485
  import { randomBytes as randomBytes2 } from "crypto";
4543
- import { mkdir, open as open2, readFile, readdir, rename, unlink, writeFile } from "fs/promises";
4544
- import * as path3 from "path";
5486
+ import { mkdir, open as open3, readFile, readdir, rename, unlink, writeFile } from "fs/promises";
5487
+ import * as path4 from "path";
4545
5488
 
4546
5489
  // src/state/keys.ts
4547
- import { createHash as createHash4 } from "crypto";
5490
+ import { createHash as createHash5 } from "crypto";
4548
5491
  var SAFE_SEGMENT_PATTERN = /^[A-Za-z0-9_-]{1,128}$/;
4549
5492
  var isSafeSegment = (segment) => SAFE_SEGMENT_PATTERN.test(segment);
4550
5493
  var sanitizeSegment = (segment) => {
4551
5494
  if (isSafeSegment(segment)) {
4552
5495
  return segment;
4553
5496
  }
4554
- return `h_${createHash4("sha256").update(segment, "utf8").digest("hex").slice(0, 32)}`;
5497
+ return `h_${createHash5("sha256").update(segment, "utf8").digest("hex").slice(0, 32)}`;
4555
5498
  };
4556
5499
  var namespaceSegments = (namespace) => [
4557
5500
  sanitizeSegment(namespace.providerId),
4558
5501
  sanitizeSegment(namespace.installationId)
4559
5502
  ];
4560
- var keyDigest = (key) => createHash4("sha256").update(key, "utf8").digest("hex");
5503
+ var keyDigest = (key) => createHash5("sha256").update(key, "utf8").digest("hex");
4561
5504
 
4562
5505
  // src/state/filesystem-store.ts
4563
5506
  var isErrnoException = (thrown, code) => thrown instanceof Error && thrown.code === code;
@@ -4573,10 +5516,10 @@ var wrapFsError = (thrown, operation) => {
4573
5516
  };
4574
5517
  var createFilesystemStateStore = (options) => {
4575
5518
  const [providerSegment, installationSegment] = namespaceSegments(options);
4576
- const baseDir = path3.join(options.rootDir, providerSegment, installationSegment);
4577
- const recordsDir = path3.join(baseDir, "records");
4578
- const quarantineDir = path3.join(baseDir, "quarantine");
4579
- const locksDir = path3.join(baseDir, "locks");
5519
+ const baseDir = path4.join(options.rootDir, providerSegment, installationSegment);
5520
+ const recordsDir = path4.join(baseDir, "records");
5521
+ const quarantineDir = path4.join(baseDir, "quarantine");
5522
+ const locksDir = path4.join(baseDir, "locks");
4580
5523
  const lockTimeoutMillis = options.lockTimeoutMillis ?? 5e3;
4581
5524
  const lockStaleMillis = options.lockStaleMillis ?? 3e4;
4582
5525
  const lockPollIntervalMillis = options.lockPollIntervalMillis ?? 25;
@@ -4600,11 +5543,11 @@ var createFilesystemStateStore = (options) => {
4600
5543
  throw wrapFsError(thrown, "ensure-dirs");
4601
5544
  }
4602
5545
  };
4603
- const recordPath = (key) => path3.join(recordsDir, `${keyDigest(key)}.json`);
4604
- const tempPath = (key) => path3.join(recordsDir, `.tmp-${keyDigest(key)}-${randomBytes2(6).toString("hex")}.json`);
4605
- const lockPath = (sessionId) => path3.join(locksDir, `${sanitizeSegment(sessionId)}.lock`);
5546
+ const recordPath = (key) => path4.join(recordsDir, `${keyDigest(key)}.json`);
5547
+ const tempPath = (key) => path4.join(recordsDir, `.tmp-${keyDigest(key)}-${randomBytes2(6).toString("hex")}.json`);
5548
+ const lockPath = (sessionId) => path4.join(locksDir, `${sanitizeSegment(sessionId)}.lock`);
4606
5549
  const quarantine = async (filePath, key, reason) => {
4607
- const dest = path3.join(quarantineDir, `${options.clock.now()}-${keyDigest(key)}-${reason}.json`);
5550
+ const dest = path4.join(quarantineDir, `${options.clock.now()}-${keyDigest(key)}-${reason}.json`);
4608
5551
  try {
4609
5552
  await rename(filePath, dest);
4610
5553
  } catch {
@@ -4668,7 +5611,7 @@ var createFilesystemStateStore = (options) => {
4668
5611
  const startedAt = options.clock.monotonicMillis();
4669
5612
  for (; ; ) {
4670
5613
  try {
4671
- const handle = await open2(filePath, "wx");
5614
+ const handle = await open3(filePath, "wx");
4672
5615
  try {
4673
5616
  await handle.writeFile(JSON.stringify({ pid: process.pid, acquiredAt: options.clock.now() }));
4674
5617
  } finally {
@@ -4736,7 +5679,7 @@ var createFilesystemStateStore = (options) => {
4736
5679
  }
4737
5680
  let raw;
4738
5681
  try {
4739
- raw = await readFile(path3.join(recordsDir, entry), "utf8");
5682
+ raw = await readFile(path4.join(recordsDir, entry), "utf8");
4740
5683
  } catch {
4741
5684
  continue;
4742
5685
  }
@@ -4789,7 +5732,7 @@ var createFilesystemStateStore = (options) => {
4789
5732
  continue;
4790
5733
  }
4791
5734
  scanned += 1;
4792
- const filePath = path3.join(recordsDir, entry);
5735
+ const filePath = path4.join(recordsDir, entry);
4793
5736
  try {
4794
5737
  const raw = await readFile(filePath, "utf8");
4795
5738
  const envelope = JSON.parse(raw);
@@ -4809,7 +5752,7 @@ var createFilesystemStateStore = (options) => {
4809
5752
  lockEntries = [];
4810
5753
  }
4811
5754
  for (const entry of lockEntries) {
4812
- const filePath = path3.join(locksDir, entry);
5755
+ const filePath = path4.join(locksDir, entry);
4813
5756
  try {
4814
5757
  const raw = await readFile(filePath, "utf8");
4815
5758
  const parsed = JSON.parse(raw);
@@ -4827,14 +5770,70 @@ var createFilesystemStateStore = (options) => {
4827
5770
 
4828
5771
  // src/telemetry/spool-queue.ts
4829
5772
  import { randomBytes as randomBytes3 } from "crypto";
4830
- import { mkdir as mkdir2, readFile as readFile2, readdir as readdir2, rename as rename2, unlink as unlink2, writeFile as writeFile2 } from "fs/promises";
4831
- import * as path4 from "path";
5773
+ import { mkdir as mkdir2, readFile as readFile2, readdir as readdir2, rename as rename2, stat as stat3, unlink as unlink2, writeFile as writeFile2 } from "fs/promises";
5774
+ import * as path5 from "path";
5775
+ var EMPTY_SPOOL_DROP_COUNTS = Object.freeze({
5776
+ total: 0,
5777
+ age: 0,
5778
+ size: 0,
5779
+ count: 0,
5780
+ rejected: 0
5781
+ });
5782
+ var SPOOL_DROPS_FILE = ".drops";
5783
+ var enqueuedAtOf = (fileName) => {
5784
+ const match = /^(\d{16})-/.exec(fileName);
5785
+ return match?.[1] === void 0 ? void 0 : Number(match[1]);
5786
+ };
5787
+ var isCount = (value) => typeof value === "number" && Number.isInteger(value) && value >= 0;
5788
+ var readSpoolDropCounts = async (queueDir) => {
5789
+ try {
5790
+ const parsed = JSON.parse(await readFile2(path5.join(queueDir, SPOOL_DROPS_FILE), "utf8"));
5791
+ if (typeof parsed !== "object" || parsed === null) {
5792
+ return EMPTY_SPOOL_DROP_COUNTS;
5793
+ }
5794
+ const record = parsed;
5795
+ const field = (name) => isCount(record[name]) ? record[name] : 0;
5796
+ return {
5797
+ total: field("total"),
5798
+ age: field("age"),
5799
+ size: field("size"),
5800
+ count: field("count"),
5801
+ rejected: field("rejected"),
5802
+ ...isCount(record.lastDroppedAt) ? { lastDroppedAt: record.lastDroppedAt } : {}
5803
+ };
5804
+ } catch {
5805
+ return EMPTY_SPOOL_DROP_COUNTS;
5806
+ }
5807
+ };
5808
+ var readSpoolQueueStats = async (queueDir) => {
5809
+ let entries;
5810
+ try {
5811
+ entries = await readdir2(queueDir);
5812
+ } catch {
5813
+ return { batches: 0, bytes: 0, dropped: await readSpoolDropCounts(queueDir) };
5814
+ }
5815
+ const files = entries.filter((entry) => entry.endsWith(".json") && !entry.startsWith(".tmp-")).sort();
5816
+ let bytes = 0;
5817
+ for (const file of files) {
5818
+ try {
5819
+ bytes += (await stat3(path5.join(queueDir, file))).size;
5820
+ } catch {
5821
+ }
5822
+ }
5823
+ const oldest = files[0] === void 0 ? void 0 : enqueuedAtOf(files[0]);
5824
+ return {
5825
+ batches: files.length,
5826
+ bytes,
5827
+ ...oldest === void 0 ? {} : { oldestEnqueuedAt: oldest },
5828
+ dropped: await readSpoolDropCounts(queueDir)
5829
+ };
5830
+ };
4832
5831
  var DEFAULT_DRAIN_MAX_BATCHES = 20;
4833
5832
  var isErrnoException2 = (thrown, code) => thrown instanceof Error && thrown.code === code;
4834
5833
  var createSpoolQueue = (options) => {
4835
5834
  const [providerSegment, installationSegment] = namespaceSegments(options);
4836
- const queueDir = path4.join(options.rootDir, providerSegment, installationSegment, options.queueName);
4837
- const corruptDir = path4.join(
5835
+ const queueDir = path5.join(options.rootDir, providerSegment, installationSegment, options.queueName);
5836
+ const corruptDir = path5.join(
4838
5837
  options.rootDir,
4839
5838
  providerSegment,
4840
5839
  installationSegment,
@@ -4869,27 +5868,132 @@ var createSpoolQueue = (options) => {
4869
5868
  }
4870
5869
  return entries.filter((entry) => entry.endsWith(".json") && !entry.startsWith(".tmp-")).sort();
4871
5870
  };
5871
+ const recordDrops = async (reason, dropped) => {
5872
+ if (dropped <= 0) {
5873
+ return;
5874
+ }
5875
+ try {
5876
+ const current = await readSpoolDropCounts(queueDir);
5877
+ const next = {
5878
+ ...current,
5879
+ total: current.total + dropped,
5880
+ [reason]: current[reason] + dropped,
5881
+ lastDroppedAt: options.clock.now()
5882
+ };
5883
+ const tmp = path5.join(queueDir, `.tmp-${randomBytes3(6).toString("hex")}.drops`);
5884
+ await writeFile2(tmp, JSON.stringify(next), "utf8");
5885
+ await rename2(tmp, path5.join(queueDir, SPOOL_DROPS_FILE));
5886
+ } catch {
5887
+ }
5888
+ options.logger?.warn("durable spool dropped batches", {
5889
+ "spool.queue": options.queueName,
5890
+ "spool.drop_reason": reason,
5891
+ "spool.dropped": dropped
5892
+ });
5893
+ };
5894
+ const listWithSizes = async () => {
5895
+ const names = await listSorted();
5896
+ const files = [];
5897
+ for (const name of names) {
5898
+ let bytes = 0;
5899
+ if (options.maxBytes !== void 0) {
5900
+ try {
5901
+ bytes = (await stat3(path5.join(queueDir, name))).size;
5902
+ } catch {
5903
+ continue;
5904
+ }
5905
+ }
5906
+ const enqueuedAt = enqueuedAtOf(name);
5907
+ files.push({ name, bytes, ...enqueuedAt === void 0 ? {} : { enqueuedAt } });
5908
+ }
5909
+ return files;
5910
+ };
5911
+ const evict = async (files) => {
5912
+ let removed = 0;
5913
+ for (const file of files) {
5914
+ try {
5915
+ await unlink2(path5.join(queueDir, file.name));
5916
+ removed += 1;
5917
+ } catch {
5918
+ }
5919
+ }
5920
+ return removed;
5921
+ };
5922
+ const isExpired = (file, now) => options.maxAgeMillis !== void 0 && file.enqueuedAt !== void 0 && now - file.enqueuedAt > options.maxAgeMillis;
4872
5923
  const enqueue = async (batch) => {
4873
5924
  await ensureDirs();
4874
- const existing = await listSorted();
4875
- if (existing.length >= options.maxFiles) {
5925
+ const serialized = JSON.stringify(batch);
5926
+ const bytes = Buffer.byteLength(serialized, "utf8");
5927
+ const refuse = async (reason) => {
4876
5928
  options.logger?.warn("durable spool at capacity; batch dropped", {
4877
5929
  "spool.max_files": options.maxFiles,
5930
+ ...options.maxBytes === void 0 ? {} : { "spool.max_bytes": options.maxBytes },
4878
5931
  "spool.queue": options.queueName
4879
5932
  });
5933
+ await recordDrops(reason, 1);
4880
5934
  return { spooled: false, reason: "capacity-exceeded" };
5935
+ };
5936
+ if (options.maxBytes !== void 0 && bytes > options.maxBytes) {
5937
+ return refuse("size");
5938
+ }
5939
+ let queued = await listWithSizes();
5940
+ const now = options.clock.now();
5941
+ const expired = queued.filter((file) => isExpired(file, now));
5942
+ if (expired.length > 0) {
5943
+ await recordDrops("age", await evict(expired));
5944
+ queued = queued.filter((file) => !isExpired(file, now));
5945
+ }
5946
+ const overflow = options.overflow ?? "refuse-new";
5947
+ const totalBytes = () => queued.reduce((sum, file) => sum + file.bytes, 0);
5948
+ if (overflow === "refuse-new") {
5949
+ if (queued.length >= options.maxFiles) {
5950
+ return refuse("count");
5951
+ }
5952
+ if (options.maxBytes !== void 0 && totalBytes() + bytes > options.maxBytes) {
5953
+ return refuse("size");
5954
+ }
5955
+ } else {
5956
+ const overCount = Math.max(0, queued.length + 1 - options.maxFiles);
5957
+ if (overCount > 0) {
5958
+ await recordDrops("count", await evict(queued.slice(0, overCount)));
5959
+ queued = queued.slice(overCount);
5960
+ }
5961
+ if (options.maxBytes !== void 0) {
5962
+ let excess = totalBytes() + bytes - options.maxBytes;
5963
+ let cut = 0;
5964
+ while (excess > 0 && cut < queued.length) {
5965
+ excess -= queued[cut]?.bytes ?? 0;
5966
+ cut += 1;
5967
+ }
5968
+ if (cut > 0) {
5969
+ await recordDrops("size", await evict(queued.slice(0, cut)));
5970
+ queued = queued.slice(cut);
5971
+ }
5972
+ }
4881
5973
  }
4882
- const fileName = `${String(options.clock.now()).padStart(16, "0")}-${randomBytes3(6).toString("hex")}.json`;
4883
- const target = path4.join(queueDir, fileName);
4884
- const tmp = path4.join(queueDir, `.tmp-${randomBytes3(6).toString("hex")}.json`);
4885
- await writeFile2(tmp, JSON.stringify(batch), "utf8");
5974
+ const fileName = `${String(now).padStart(16, "0")}-${randomBytes3(6).toString("hex")}.json`;
5975
+ const target = path5.join(queueDir, fileName);
5976
+ const tmp = path5.join(queueDir, `.tmp-${randomBytes3(6).toString("hex")}.json`);
5977
+ await writeFile2(tmp, serialized, "utf8");
4886
5978
  await rename2(tmp, target);
4887
5979
  return { spooled: true };
4888
5980
  };
4889
5981
  const drain = async (send, drainOptions) => {
4890
5982
  await ensureDirs();
4891
5983
  const cap = drainOptions?.maxBatches ?? DEFAULT_DRAIN_MAX_BATCHES;
4892
- const files = await listSorted();
5984
+ let files = await listSorted();
5985
+ if (options.maxAgeMillis !== void 0) {
5986
+ const now = options.clock.now();
5987
+ const expired = files.map((name) => {
5988
+ const enqueuedAt = enqueuedAtOf(name);
5989
+ return { name, bytes: 0, ...enqueuedAt === void 0 ? {} : { enqueuedAt } };
5990
+ }).filter((file) => isExpired(file, now));
5991
+ if (expired.length > 0) {
5992
+ await recordDrops("age", await evict(expired));
5993
+ const gone = new Set(expired.map((file) => file.name));
5994
+ files = files.filter((name) => !gone.has(name));
5995
+ }
5996
+ }
4893
5997
  let drained = 0;
4894
5998
  let failed = 0;
4895
5999
  let quarantined = 0;
@@ -4899,7 +6003,7 @@ var createSpoolQueue = (options) => {
4899
6003
  if (fileName === void 0) {
4900
6004
  break;
4901
6005
  }
4902
- const filePath = path4.join(queueDir, fileName);
6006
+ const filePath = path5.join(queueDir, fileName);
4903
6007
  const quarantine = async (rejection) => {
4904
6008
  quarantined += 1;
4905
6009
  options.logger?.error("durable spool quarantined an unusable batch", {
@@ -4908,7 +6012,7 @@ var createSpoolQueue = (options) => {
4908
6012
  "spool.queue": options.queueName
4909
6013
  });
4910
6014
  try {
4911
- await rename2(filePath, path4.join(corruptDir, fileName));
6015
+ await rename2(filePath, path5.join(corruptDir, fileName));
4912
6016
  } catch {
4913
6017
  await unlink2(filePath).catch(() => void 0);
4914
6018
  }
@@ -4934,6 +6038,12 @@ var createSpoolQueue = (options) => {
4934
6038
  } catch {
4935
6039
  delivered = false;
4936
6040
  }
6041
+ if (delivered === "discard") {
6042
+ if (await unlink2(filePath).then(() => true, () => false)) {
6043
+ await recordDrops("rejected", 1);
6044
+ }
6045
+ continue;
6046
+ }
4937
6047
  if (delivered) {
4938
6048
  await unlink2(filePath).catch(() => void 0);
4939
6049
  drained += 1;
@@ -4951,7 +6061,8 @@ var createSpoolQueue = (options) => {
4951
6061
  size: async () => {
4952
6062
  await ensureDirs();
4953
6063
  return (await listSorted()).length;
4954
- }
6064
+ },
6065
+ stats: () => readSpoolQueueStats(queueDir)
4955
6066
  };
4956
6067
  };
4957
6068
 
@@ -5050,7 +6161,10 @@ var createFileDurableLogSpool = (options) => createSpoolQueue({
5050
6161
  clock: options.clock,
5051
6162
  ...options.logger === void 0 ? {} : { logger: options.logger },
5052
6163
  maxFiles: options.maxSpoolFiles ?? DEFAULT_MAX_LOG_SPOOL_FILES,
5053
- queueName: "spool-logs",
6164
+ queueName: options.queueName ?? "spool-logs",
6165
+ ...options.maxBytes === void 0 ? {} : { maxBytes: options.maxBytes },
6166
+ ...options.maxAgeMillis === void 0 ? {} : { maxAgeMillis: options.maxAgeMillis },
6167
+ ...options.overflow === void 0 ? {} : { overflow: options.overflow },
5054
6168
  validate: validateLogSpoolBatch
5055
6169
  });
5056
6170
 
@@ -5142,7 +6256,10 @@ var createFileDurableSpool = (options) => createSpoolQueue({
5142
6256
  clock: options.clock,
5143
6257
  ...options.logger === void 0 ? {} : { logger: options.logger },
5144
6258
  maxFiles: options.maxSpoolFiles ?? DEFAULT_MAX_SPOOL_FILES,
5145
- queueName: "spool",
6259
+ queueName: options.queueName ?? "spool",
6260
+ ...options.maxBytes === void 0 ? {} : { maxBytes: options.maxBytes },
6261
+ ...options.maxAgeMillis === void 0 ? {} : { maxAgeMillis: options.maxAgeMillis },
6262
+ ...options.overflow === void 0 ? {} : { overflow: options.overflow },
5146
6263
  validate: validateSpoolBatch
5147
6264
  });
5148
6265
 
@@ -5168,6 +6285,13 @@ var withoutTrailingSlashes = (value) => {
5168
6285
  return value.slice(0, end);
5169
6286
  };
5170
6287
 
6288
+ // src/telemetry/export-failure.ts
6289
+ var RETRYABLE_HTTP_STATUSES = /* @__PURE__ */ new Set([408, 429, 500, 502, 503, 504]);
6290
+ var isPermanentExportFailure = (result) => {
6291
+ const code = result.error?.code;
6292
+ return typeof code === "number" && Number.isInteger(code) && code >= 400 && code < 600 && !RETRYABLE_HTTP_STATUSES.has(code);
6293
+ };
6294
+
5171
6295
  // src/telemetry/exporter-resource.ts
5172
6296
  import { resourceFromAttributes } from "@opentelemetry/resources";
5173
6297
  var resourceFromExporterPolicy = (policy) => resourceFromAttributes({
@@ -5372,7 +6496,8 @@ var eventAttributes = (event2) => {
5372
6496
  ...event2.model.vendor === void 0 ? {} : { [ATTR_GEN_AI_SYSTEM2]: event2.model.vendor },
5373
6497
  [ATTR_OTELHOOK_OUTCOME2]: event2.outcome,
5374
6498
  ...event2.stopReason === void 0 ? {} : { [ATTR_OTELHOOK_STOP_REASON]: event2.stopReason },
5375
- ...usageAttributes2(event2.usage)
6499
+ ...usageAttributes2(event2.usage),
6500
+ ...event2.usage === void 0 || event2.usagePartial === void 0 ? {} : { [ATTR_OTELHOOK_USAGE_PARTIAL]: event2.usagePartial }
5376
6501
  };
5377
6502
  case "tool.start":
5378
6503
  return {
@@ -5646,8 +6771,11 @@ var chunk = (items, size) => {
5646
6771
  }
5647
6772
  return chunks;
5648
6773
  };
5649
- var createDisabledSink = () => {
5650
- const health = createHealthTracker("telemetry-log-sink");
6774
+ var createDisabledSink = (destination) => {
6775
+ const health = createHealthTracker(
6776
+ "telemetry-log-sink",
6777
+ destination === void 0 ? {} : { destination }
6778
+ );
5651
6779
  return {
5652
6780
  emit: (events) => {
5653
6781
  health.recordSuccess(events.length);
@@ -5686,19 +6814,24 @@ var DISABLED_DETAIL = Object.freeze({
5686
6814
  "no-endpoint": "otlp log sink disabled: no logs endpoint configured and none could be derived"
5687
6815
  });
5688
6816
  var createOtlpLogSink = (options) => {
6817
+ const destinationFields = options.destination === void 0 ? {} : { "export.destination": options.destination };
5689
6818
  const deliverability = describeLogsDeliverability(options.exporter);
5690
6819
  if (deliverability.status === "disabled") {
5691
6820
  if (deliverability.reason !== "logs-disabled") {
5692
6821
  options.logger?.warn(DISABLED_DETAIL[deliverability.reason], {
5693
- "exporter.protocol": options.exporter.protocol
6822
+ "exporter.protocol": options.exporter.protocol,
6823
+ ...destinationFields
5694
6824
  });
5695
6825
  }
5696
- return createDisabledSink();
6826
+ return createDisabledSink(options.destination);
5697
6827
  }
5698
6828
  const scope = options.instrumentationScope ?? DEFAULT_INSTRUMENTATION_SCOPE;
5699
6829
  const resource = resourceFromExporterPolicy(options.exporter);
5700
6830
  const content = options.content ?? NO_LOG_CONTENT;
5701
- const health = createHealthTracker("telemetry-log-sink");
6831
+ const health = createHealthTracker(
6832
+ "telemetry-log-sink",
6833
+ options.destination === void 0 ? {} : { destination: options.destination }
6834
+ );
5702
6835
  const exporter = new OTLPLogExporter({
5703
6836
  url: deliverability.endpoint,
5704
6837
  headers: { ...options.headers },
@@ -5725,7 +6858,10 @@ var createOtlpLogSink = (options) => {
5725
6858
  (record) => deserializeRecord(record, batchResource, batch.instrumentationScope)
5726
6859
  );
5727
6860
  const result = await exportRecords(records);
5728
- return result.code === ExportResultCode.SUCCESS;
6861
+ if (result.code === ExportResultCode.SUCCESS) {
6862
+ return true;
6863
+ }
6864
+ return isPermanentExportFailure(result) ? "discard" : false;
5729
6865
  };
5730
6866
  const resolveCorrelations = async (events) => {
5731
6867
  if (options.correlate === void 0) {
@@ -5777,13 +6913,18 @@ var createOtlpLogSink = (options) => {
5777
6913
  continue;
5778
6914
  }
5779
6915
  health.recordFailure("telemetry-export-failure", batch.length, options.clock.now());
5780
- if (options.spool !== void 0) {
6916
+ const permanent = isPermanentExportFailure(result);
6917
+ if (options.spool !== void 0 && !permanent) {
5781
6918
  const spoolResult = await options.spool.enqueue(toSpoolBatch(batch)).catch(() => ({
5782
6919
  spooled: false,
5783
6920
  reason: "capacity-exceeded"
5784
6921
  }));
5785
6922
  if (spoolResult.spooled) {
5786
6923
  accepted += batch.length;
6924
+ options.logger?.warn("log record batch not delivered; spooled for the next invocation", {
6925
+ "export.batch_size": batch.length,
6926
+ ...destinationFields
6927
+ });
5787
6928
  continue;
5788
6929
  }
5789
6930
  }
@@ -5792,8 +6933,12 @@ var createOtlpLogSink = (options) => {
5792
6933
  createErrorInfo({
5793
6934
  code: "telemetry-export-failure",
5794
6935
  phase: "export",
5795
- detail: "collector rejected or was unreachable for a log record batch",
5796
- details: { "export.batch_size": batch.length, "export.signal": "logs" }
6936
+ detail: permanent ? "collector refused a log record batch with a non-retryable status" : "collector rejected or was unreachable for a log record batch",
6937
+ details: {
6938
+ "export.batch_size": batch.length,
6939
+ "export.signal": "logs",
6940
+ ...destinationFields
6941
+ }
5797
6942
  })
5798
6943
  );
5799
6944
  }
@@ -5876,8 +7021,11 @@ var deserializeSpan = (serialized, resource, scope) => assembleReadableSpan({
5876
7021
  resource,
5877
7022
  instrumentationScope: scope
5878
7023
  });
5879
- var createDisabledSink2 = () => {
5880
- const health = createHealthTracker("telemetry-sink");
7024
+ var createDisabledSink2 = (destination) => {
7025
+ const health = createHealthTracker(
7026
+ "telemetry-sink",
7027
+ destination === void 0 ? {} : { destination }
7028
+ );
5881
7029
  return {
5882
7030
  emit: (events) => {
5883
7031
  health.recordSuccess(events.length);
@@ -5890,22 +7038,27 @@ var createDisabledSink2 = () => {
5890
7038
  };
5891
7039
  };
5892
7040
  var createOtlpTraceSink = (options) => {
7041
+ const destinationFields = options.destination === void 0 ? {} : { "export.destination": options.destination };
5893
7042
  if (!options.exporter.enabled || options.exporter.protocol === "none") {
5894
- return createDisabledSink2();
7043
+ return createDisabledSink2(options.destination);
5895
7044
  }
5896
7045
  if (options.exporter.endpoint === void 0) {
5897
- options.logger?.warn("otlp sink disabled: no endpoint configured", {});
5898
- return createDisabledSink2();
7046
+ options.logger?.warn("otlp sink disabled: no endpoint configured", destinationFields);
7047
+ return createDisabledSink2(options.destination);
5899
7048
  }
5900
7049
  if (options.exporter.protocol !== "http/protobuf") {
5901
7050
  options.logger?.warn("otlp sink: protocol not supported by this build, falling back to disabled", {
5902
- "exporter.protocol": options.exporter.protocol
7051
+ "exporter.protocol": options.exporter.protocol,
7052
+ ...destinationFields
5903
7053
  });
5904
- return createDisabledSink2();
7054
+ return createDisabledSink2(options.destination);
5905
7055
  }
5906
7056
  const scope = options.instrumentationScope ?? DEFAULT_INSTRUMENTATION_SCOPE;
5907
7057
  const resource = resourceFromExporterPolicy(options.exporter);
5908
- const health = createHealthTracker("telemetry-sink");
7058
+ const health = createHealthTracker(
7059
+ "telemetry-sink",
7060
+ options.destination === void 0 ? {} : { destination: options.destination }
7061
+ );
5909
7062
  const exporter = new OTLPTraceExporter({
5910
7063
  url: options.exporter.endpoint,
5911
7064
  headers: { ...options.headers },
@@ -5927,7 +7080,10 @@ var createOtlpTraceSink = (options) => {
5927
7080
  const batchResource = replayResource(batch.resourceAttributes, options.exporter);
5928
7081
  const spans = batch.spans.map((span) => deserializeSpan(span, batchResource, batch.instrumentationScope));
5929
7082
  const result = await exportSpans(spans);
5930
- return result.code === ExportResultCode2.SUCCESS;
7083
+ if (result.code === ExportResultCode2.SUCCESS) {
7084
+ return true;
7085
+ }
7086
+ return isPermanentExportFailure(result) ? "discard" : false;
5931
7087
  };
5932
7088
  const resolveCorrelations = async (events) => {
5933
7089
  if (options.correlate === void 0) {
@@ -5955,6 +7111,9 @@ var createOtlpTraceSink = (options) => {
5955
7111
  let accepted = 0;
5956
7112
  let rejected = 0;
5957
7113
  for (const batch of chunk2(spans, options.exporter.maxBatchSize)) {
7114
+ if (batch.length === 0) {
7115
+ continue;
7116
+ }
5958
7117
  let result;
5959
7118
  try {
5960
7119
  result = await exportSpans(batch);
@@ -5967,13 +7126,18 @@ var createOtlpTraceSink = (options) => {
5967
7126
  continue;
5968
7127
  }
5969
7128
  health.recordFailure("telemetry-export-failure", batch.length, options.clock.now());
5970
- if (options.spool !== void 0) {
7129
+ const permanent = isPermanentExportFailure(result);
7130
+ if (options.spool !== void 0 && !permanent) {
5971
7131
  const spoolResult = await options.spool.enqueue(toSpoolBatch(batch)).catch(() => ({
5972
7132
  spooled: false,
5973
7133
  reason: "capacity-exceeded"
5974
7134
  }));
5975
7135
  if (spoolResult.spooled) {
5976
7136
  accepted += batch.length;
7137
+ options.logger?.warn("span batch not delivered; spooled for the next invocation", {
7138
+ "export.batch_size": batch.length,
7139
+ ...destinationFields
7140
+ });
5977
7141
  continue;
5978
7142
  }
5979
7143
  }
@@ -5982,8 +7146,8 @@ var createOtlpTraceSink = (options) => {
5982
7146
  createErrorInfo({
5983
7147
  code: "telemetry-export-failure",
5984
7148
  phase: "export",
5985
- detail: "collector rejected or was unreachable for a span batch",
5986
- details: { "export.batch_size": batch.length }
7149
+ detail: permanent ? "collector refused a span batch with a non-retryable status" : "collector rejected or was unreachable for a span batch",
7150
+ details: { "export.batch_size": batch.length, ...destinationFields }
5987
7151
  })
5988
7152
  );
5989
7153
  }
@@ -6068,6 +7232,172 @@ var shareCorrelationPerBatch = (correlate) => {
6068
7232
  };
6069
7233
  };
6070
7234
 
7235
+ // src/telemetry/export-destinations.ts
7236
+ var spoolQueueNamesFor = (destination) => destination === DEFAULT_DESTINATION_NAME ? { traces: "spool", logs: "spool-logs" } : { traces: `destinations/${destination}/spool`, logs: `destinations/${destination}/spool-logs` };
7237
+ var exporterPolicyForDestination = (exporter, destination) => {
7238
+ if (destination.source === "exporter") {
7239
+ return exporter;
7240
+ }
7241
+ const { destinations, endpoint, logs, ...shared } = exporter;
7242
+ void destinations;
7243
+ void endpoint;
7244
+ const tracesEndpoint = destination.tracesEndpoint ?? destination.endpoint;
7245
+ const derivedLogs = destination.logsEndpoint ?? (destination.endpoint === void 0 ? void 0 : (() => {
7246
+ const derived = resolveLogsEndpoint({
7247
+ ...exporter,
7248
+ endpoint: destination.endpoint,
7249
+ logs: { enabled: true, includeContent: false, maxBatchSize: logs.maxBatchSize }
7250
+ });
7251
+ return "endpoint" in derived ? derived.endpoint : void 0;
7252
+ })());
7253
+ return {
7254
+ ...shared,
7255
+ protocol: destination.protocol,
7256
+ ...tracesEndpoint === void 0 ? {} : { endpoint: tracesEndpoint },
7257
+ headerNames: Object.keys(destination.headers).sort(),
7258
+ logs: {
7259
+ ...logs,
7260
+ enabled: destination.signals.logs,
7261
+ ...derivedLogs === void 0 ? {} : { endpoint: derivedLogs }
7262
+ }
7263
+ };
7264
+ };
7265
+ var createOptedOutTraceSink = (destination) => {
7266
+ const health = createHealthTracker(
7267
+ "telemetry-sink",
7268
+ destination === void 0 ? {} : { destination }
7269
+ );
7270
+ return {
7271
+ emit: () => Promise.resolve({ accepted: 0, rejected: 0, errors: [] }),
7272
+ flush: () => Promise.resolve(),
7273
+ shutdown: () => Promise.resolve(),
7274
+ health: () => health.snapshot(),
7275
+ drainSpool: () => Promise.resolve({ drained: 0, remaining: 0, failed: 0 })
7276
+ };
7277
+ };
7278
+ var createExportDestinationSinks = (options) => {
7279
+ const labelled = hasConfiguredDestinations(options.exporter);
7280
+ const spoolPolicy = effectiveSpoolPolicy(options.exporter);
7281
+ const destinations = [];
7282
+ const skipped = [];
7283
+ for (const destination of resolveExportDestinations(options.exporter)) {
7284
+ let headers;
7285
+ let logHeaders;
7286
+ if (destination.source === "exporter") {
7287
+ headers = options.defaultHeaders;
7288
+ logHeaders = options.defaultLogHeaders ?? options.defaultHeaders;
7289
+ } else {
7290
+ const resolved = resolveDestinationHeaders(destination.headers, options.headerEnvironment);
7291
+ if (resolved.missingVariables.length > 0) {
7292
+ options.logger?.warn("export destination skipped: a header references an unset environment variable", {
7293
+ "export.destination": destination.name,
7294
+ "config.variables": [...resolved.missingVariables]
7295
+ });
7296
+ skipped.push({
7297
+ name: destination.name,
7298
+ reason: "header-variable-missing",
7299
+ missingVariables: resolved.missingVariables
7300
+ });
7301
+ continue;
7302
+ }
7303
+ headers = resolved.values;
7304
+ logHeaders = resolved.values;
7305
+ }
7306
+ const label = labelled ? destination.name : void 0;
7307
+ const policy = exporterPolicyForDestination(options.exporter, destination);
7308
+ const queues = spoolQueueNamesFor(destination.name);
7309
+ const bounds = {
7310
+ maxSpoolFiles: spoolPolicy.maxBatches,
7311
+ maxBytes: spoolPolicy.maxBytes,
7312
+ maxAgeMillis: spoolPolicy.maxAgeMillis,
7313
+ overflow: "drop-oldest"
7314
+ };
7315
+ const shared = {
7316
+ providerId: options.providerId,
7317
+ installationId: options.installationId,
7318
+ clock: options.clock,
7319
+ ...options.logger === void 0 ? {} : { logger: options.logger }
7320
+ };
7321
+ const spool = options.spoolRootDir === void 0 || !destination.signals.traces ? void 0 : createFileDurableSpool({
7322
+ rootDir: options.spoolRootDir,
7323
+ ...shared,
7324
+ ...bounds,
7325
+ queueName: queues.traces
7326
+ });
7327
+ const logSpool = options.spoolRootDir === void 0 || !destination.signals.logs ? void 0 : createFileDurableLogSpool({
7328
+ rootDir: options.spoolRootDir,
7329
+ ...shared,
7330
+ ...bounds,
7331
+ queueName: queues.logs
7332
+ });
7333
+ const sinkShared = {
7334
+ exporter: policy,
7335
+ ...shared,
7336
+ ...options.correlate === void 0 ? {} : { correlate: options.correlate },
7337
+ ...label === void 0 ? {} : { destination: label }
7338
+ };
7339
+ const traces = destination.signals.traces ? createOtlpTraceSink({
7340
+ ...sinkShared,
7341
+ ...headers === void 0 || Object.keys(headers).length === 0 ? {} : { headers },
7342
+ ...spool === void 0 ? {} : { spool }
7343
+ }) : createOptedOutTraceSink(label);
7344
+ const logs = createOtlpLogSink({
7345
+ ...sinkShared,
7346
+ ...logHeaders === void 0 || Object.keys(logHeaders).length === 0 ? {} : { headers: logHeaders },
7347
+ ...logSpool === void 0 ? {} : { spool: logSpool },
7348
+ content: options.logContent
7349
+ });
7350
+ destinations.push({
7351
+ name: destination.name,
7352
+ traces,
7353
+ logs,
7354
+ ...spool === void 0 ? {} : { spool },
7355
+ ...logSpool === void 0 ? {} : { logSpool }
7356
+ });
7357
+ }
7358
+ return { destinations, skipped };
7359
+ };
7360
+ var createDestinationFanout = (destinations) => {
7361
+ const fanouts = destinations.map((destination) => ({
7362
+ name: destination.name,
7363
+ sink: createSignalFanout({ traces: destination.traces, logs: destination.logs })
7364
+ }));
7365
+ const only = fanouts.length === 1 ? fanouts[0] : void 0;
7366
+ if (only !== void 0) {
7367
+ return only.sink;
7368
+ }
7369
+ const emit = async (events) => {
7370
+ const results = await Promise.all(
7371
+ fanouts.map(
7372
+ (fanout) => fanout.sink.emit(events).catch(
7373
+ (thrown) => ({
7374
+ accepted: 0,
7375
+ rejected: events.length,
7376
+ errors: [errorInfoFromThrown(thrown, { code: "telemetry-export-failure", phase: "export" })]
7377
+ })
7378
+ )
7379
+ )
7380
+ );
7381
+ const errors = results.flatMap((result) => result.errors);
7382
+ return {
7383
+ accepted: results.reduce((sum, result) => sum + result.accepted, 0),
7384
+ rejected: results.reduce((sum, result) => sum + result.rejected, 0),
7385
+ errors
7386
+ };
7387
+ };
7388
+ const settleAll = async (run) => {
7389
+ await Promise.all(fanouts.map((fanout) => run(fanout.sink).catch(() => void 0)));
7390
+ };
7391
+ return {
7392
+ emit,
7393
+ // Each destination drains its own spool in its flush; in parallel, so one
7394
+ // unreachable destination's drain cannot use up the others' flush window.
7395
+ flush: () => settleAll((sink) => sink.flush()),
7396
+ shutdown: () => settleAll((sink) => sink.shutdown()),
7397
+ health: () => fanouts.flatMap((fanout) => fanout.sink.health())
7398
+ };
7399
+ };
7400
+
6071
7401
  // src/integration/hook-runtime.ts
6072
7402
  var DEFAULT_FLUSH_TIMEOUT_MILLIS = 2e3;
6073
7403
  var DEFAULT_STATE_LOCK_TIMEOUT_MILLIS = 1e3;
@@ -6130,46 +7460,23 @@ var createHookRuntime = (options) => {
6130
7460
  logger,
6131
7461
  lockTimeoutMillis: stateLockTimeoutMillis
6132
7462
  });
6133
- const spool = options.enableSpool === false ? void 0 : createFileDurableSpool({
6134
- rootDir: options.stateRootDir,
6135
- providerId: options.providerNamespace,
6136
- installationId: options.installationId,
6137
- clock,
6138
- logger
6139
- });
6140
- const logSpool = options.enableSpool === false || !options.config.exporter.logs.enabled ? void 0 : createFileDurableLogSpool({
6141
- rootDir: options.stateRootDir,
6142
- providerId: options.providerNamespace,
6143
- installationId: options.installationId,
6144
- clock,
6145
- logger
6146
- });
6147
7463
  const spanCorrelator = createSpanCorrelator({
6148
7464
  stateStore,
6149
7465
  clock,
6150
7466
  maxStartAgeMillis: lifecycleMaxAge
6151
7467
  });
6152
7468
  const correlate = shareCorrelationPerBatch((events) => spanCorrelator.correlateBatch(events));
6153
- const traceSink = createOtlpTraceSink({
6154
- exporter: options.config.exporter,
6155
- ...options.headers === void 0 ? {} : { headers: options.headers },
6156
- providerId: options.providerNamespace,
6157
- installationId: options.installationId,
6158
- clock,
6159
- logger,
6160
- ...spool === void 0 ? {} : { spool },
6161
- correlate
6162
- });
6163
- const logHeaders = options.logHeaders ?? options.headers;
6164
- const logSink = createOtlpLogSink({
7469
+ const exportDestinations = createExportDestinationSinks({
6165
7470
  exporter: options.config.exporter,
6166
- ...logHeaders === void 0 ? {} : { headers: logHeaders },
7471
+ ...options.headers === void 0 ? {} : { defaultHeaders: options.headers },
7472
+ ...options.logHeaders === void 0 ? {} : { defaultLogHeaders: options.logHeaders },
7473
+ ...options.headerEnvironment === void 0 ? {} : { headerEnvironment: options.headerEnvironment },
6167
7474
  providerId: options.providerNamespace,
6168
7475
  installationId: options.installationId,
6169
7476
  clock,
6170
7477
  logger,
6171
- ...logSpool === void 0 ? {} : { spool: logSpool },
6172
- content: {
7478
+ ...options.enableSpool === false ? {} : { spoolRootDir: options.stateRootDir },
7479
+ logContent: {
6173
7480
  includeContent: options.config.exporter.logs.includeContent,
6174
7481
  // The pre-existing verbatim-content opt-in, passed through rather than
6175
7482
  // re-derived: `raw` disclosure in a log body is governed by the same flag it
@@ -6178,7 +7485,22 @@ var createHookRuntime = (options) => {
6178
7485
  },
6179
7486
  correlate
6180
7487
  });
6181
- const sink = createSignalFanout({ traces: traceSink, logs: logSink });
7488
+ const primary = exportDestinations.destinations[0];
7489
+ const traceSink = primary?.traces ?? createOtlpTraceSink({
7490
+ exporter: { ...options.config.exporter, enabled: false },
7491
+ providerId: options.providerNamespace,
7492
+ installationId: options.installationId,
7493
+ clock
7494
+ });
7495
+ const logSink = primary?.logs ?? createOtlpLogSink({
7496
+ exporter: { ...options.config.exporter, logs: { ...options.config.exporter.logs, enabled: false } },
7497
+ providerId: options.providerNamespace,
7498
+ installationId: options.installationId,
7499
+ clock
7500
+ });
7501
+ const spool = primary?.spool;
7502
+ const logSpool = primary?.logSpool;
7503
+ const sink = createDestinationFanout(exportDestinations.destinations);
6182
7504
  const hookDeps = {
6183
7505
  stateStore,
6184
7506
  config: options.config,
@@ -6188,6 +7510,7 @@ var createHookRuntime = (options) => {
6188
7510
  privacy,
6189
7511
  logger,
6190
7512
  installationId: options.installationId,
7513
+ payloadEnrichers: options.payloadEnrichers ?? (readsClaudeTranscriptUsage(options.config) ? [createClaudeTranscriptUsageEnricher()] : []),
6191
7514
  ...options.worktreeLocator === null ? {} : {
6192
7515
  worktreeLocator: options.worktreeLocator ?? createFilesystemWorktreeLocator({ monotonicMillis: () => clock.monotonicMillis() })
6193
7516
  }
@@ -6447,6 +7770,8 @@ var createHookRuntime = (options) => {
6447
7770
  logSink,
6448
7771
  ...spool === void 0 ? {} : { spool },
6449
7772
  ...logSpool === void 0 ? {} : { logSpool },
7773
+ destinations: exportDestinations.destinations,
7774
+ skippedDestinations: exportDestinations.skipped,
6450
7775
  privacy,
6451
7776
  deduplicator,
6452
7777
  usageAccumulator,