@osfactory/otel-hook 0.9.0 → 0.11.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 (51) hide show
  1. package/README.md +124 -4
  2. package/dist/{adapter-BJiz6lqM.d.ts → adapter-DiLknaTF.d.ts} +14 -2
  3. package/dist/cli.js +2272 -730
  4. package/dist/cli.js.map +1 -1
  5. package/dist/config.d.ts +13 -4
  6. package/dist/config.js +128 -23
  7. package/dist/config.js.map +1 -1
  8. package/dist/{destinations-C6Bm89W6.d.ts → destinations-BIl3gGzx.d.ts} +12 -2
  9. package/dist/diagnostics.d.ts +1 -1
  10. package/dist/diagnostics.js.map +1 -1
  11. package/dist/{events-B3MHoJTD.d.ts → events-CSD_YiJ2.d.ts} +2 -0
  12. package/dist/{export-destinations-d8tZV0G4.d.ts → export-destinations-QWKGGEjk.d.ts} +131 -6
  13. package/dist/{filesystem-store-r-nNA3BA.d.ts → filesystem-store-D3SCNmbX.d.ts} +1 -1
  14. package/dist/{hook-zA1b4cWd.d.ts → hook-BOecWGSz.d.ts} +10 -5
  15. package/dist/index.d.ts +16 -16
  16. package/dist/index.js +1808 -251
  17. package/dist/index.js.map +1 -1
  18. package/dist/install.d.ts +4 -4
  19. package/dist/install.js +31 -2
  20. package/dist/install.js.map +1 -1
  21. package/dist/integration.d.ts +37 -12
  22. package/dist/integration.js +3271 -1551
  23. package/dist/integration.js.map +1 -1
  24. package/dist/lifecycle.d.ts +55 -4
  25. package/dist/lifecycle.js +277 -4
  26. package/dist/lifecycle.js.map +1 -1
  27. package/dist/{memory-Bl9ANVff.d.ts → memory-Cs51jyRk.d.ts} +2 -2
  28. package/dist/{semconv-fPRb-dpU.d.ts → metric-model-DDnWxL9d.d.ts} +154 -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-ChtrEX6A.d.ts} +41 -2
  33. package/dist/{ports-n7KFOpKo.d.ts → ports-CeqLq31i.d.ts} +87 -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-B8ZHc2bc.d.ts → registry-CcJNF3WY.d.ts} +2 -2
  38. package/dist/runtime.d.ts +8 -8
  39. package/dist/runtime.js +1404 -1219
  40. package/dist/runtime.js.map +1 -1
  41. package/dist/{schema-BxiVsU-d.d.ts → schema-DMnoU1V_.d.ts} +93 -1
  42. package/dist/state.d.ts +4 -4
  43. package/dist/state.js +630 -39
  44. package/dist/state.js.map +1 -1
  45. package/dist/telemetry.d.ts +6 -6
  46. package/dist/telemetry.js +872 -19
  47. package/dist/telemetry.js.map +1 -1
  48. package/dist/testing.d.ts +11 -9
  49. package/dist/testing.js +264 -34
  50. package/dist/testing.js.map +1 -1
  51. package/package.json +3 -1
package/dist/runtime.js CHANGED
@@ -1,205 +1,690 @@
1
1
  // src/runtime/ports.ts
2
+ import { z as z10 } from "zod";
3
+
4
+ // src/model/events.ts
5
+ import { z as z9 } from "zod";
6
+
7
+ // src/errors/taxonomy.ts
8
+ import { z } from "zod";
9
+ var otelHookErrorCodeSchema = z.enum([
10
+ /** Input was not usable at all (empty stdin, unparsable JSON). */
11
+ "invalid-input",
12
+ /** Input parsed but failed canonical schema validation. */
13
+ "schema-validation-failed",
14
+ /** No adapter claimed the input with sufficient confidence. */
15
+ "provider-unknown",
16
+ /** Several adapters claimed the input at the same confidence. */
17
+ "provider-detection-ambiguous",
18
+ /** An adapter threw or returned a malformed result. */
19
+ "provider-adapter-failure",
20
+ /** Two identity claims disagreed at equal confidence. */
21
+ "identity-conflict",
22
+ /** Required identity fields were absent. */
23
+ "identity-incomplete",
24
+ /** A usage report violated the canonical usage invariants. */
25
+ "usage-invalid",
26
+ /** The state store could not be read or written. */
27
+ "state-store-failure",
28
+ /** The telemetry sink rejected or could not deliver a batch. */
29
+ "telemetry-export-failure",
30
+ /** Content reached the sink boundary in a state the policy forbids. */
31
+ "privacy-policy-violation",
32
+ /** Configuration could not be resolved. */
33
+ "configuration-invalid",
34
+ /** A configured bound (events, batch size) dropped data. */
35
+ "limit-exceeded",
36
+ /**
37
+ * No replay-stable delivery identifier was available for a callback while
38
+ * deduplication was required.
39
+ */
40
+ "delivery-identifier-unavailable",
41
+ "delivery-claim-superseded",
42
+ /** Anything unanticipated. Always reported, never fatal to the host. */
43
+ "internal-error"
44
+ ]);
45
+ var errorSeveritySchema = z.enum(["warning", "error"]);
46
+ var errorPhaseSchema = z.enum([
47
+ "configuration",
48
+ "detection",
49
+ "identity",
50
+ "parsing",
51
+ "normalization",
52
+ "privacy",
53
+ "state",
54
+ "export",
55
+ "shutdown"
56
+ ]);
57
+ var failurePostureSchema = z.enum(["fail-open", "fail-closed-attribution"]);
58
+ var ERROR_TAXONOMY = Object.freeze({
59
+ "invalid-input": {
60
+ code: "invalid-input",
61
+ severity: "warning",
62
+ posture: "fail-open",
63
+ retryable: false,
64
+ summary: "Input could not be read or decoded."
65
+ },
66
+ "schema-validation-failed": {
67
+ code: "schema-validation-failed",
68
+ severity: "error",
69
+ posture: "fail-closed-attribution",
70
+ retryable: false,
71
+ summary: "A canonical event failed schema validation and was dropped."
72
+ },
73
+ "provider-unknown": {
74
+ code: "provider-unknown",
75
+ severity: "warning",
76
+ posture: "fail-closed-attribution",
77
+ retryable: false,
78
+ summary: "No adapter recognized the source provider; the input stays unattributed."
79
+ },
80
+ "provider-detection-ambiguous": {
81
+ code: "provider-detection-ambiguous",
82
+ severity: "warning",
83
+ posture: "fail-closed-attribution",
84
+ retryable: false,
85
+ summary: "Multiple adapters claimed the input at equal confidence."
86
+ },
87
+ "provider-adapter-failure": {
88
+ code: "provider-adapter-failure",
89
+ severity: "error",
90
+ posture: "fail-open",
91
+ retryable: false,
92
+ summary: "A provider adapter failed while parsing."
93
+ },
94
+ "identity-conflict": {
95
+ code: "identity-conflict",
96
+ severity: "error",
97
+ posture: "fail-closed-attribution",
98
+ retryable: false,
99
+ summary: "Identity claims disagreed; attribution was declined."
100
+ },
101
+ "identity-incomplete": {
102
+ code: "identity-incomplete",
103
+ severity: "warning",
104
+ posture: "fail-closed-attribution",
105
+ retryable: false,
106
+ summary: "Required identity fields were missing; attribution was declined."
107
+ },
108
+ "usage-invalid": {
109
+ code: "usage-invalid",
110
+ severity: "error",
111
+ posture: "fail-open",
112
+ retryable: false,
113
+ summary: "A usage report violated the canonical usage invariants."
114
+ },
115
+ "state-store-failure": {
116
+ code: "state-store-failure",
117
+ severity: "warning",
118
+ posture: "fail-open",
119
+ retryable: true,
120
+ summary: "State could not be read or written; derived values may be incomplete."
121
+ },
122
+ "telemetry-export-failure": {
123
+ code: "telemetry-export-failure",
124
+ severity: "warning",
125
+ posture: "fail-open",
126
+ retryable: true,
127
+ summary: "The telemetry sink could not accept a batch."
128
+ },
129
+ "privacy-policy-violation": {
130
+ code: "privacy-policy-violation",
131
+ severity: "error",
132
+ posture: "fail-closed-attribution",
133
+ retryable: false,
134
+ summary: "Content violated the resolved privacy policy and was dropped."
135
+ },
136
+ "configuration-invalid": {
137
+ code: "configuration-invalid",
138
+ severity: "error",
139
+ posture: "fail-open",
140
+ retryable: false,
141
+ summary: "Configuration could not be resolved; defaults apply."
142
+ },
143
+ "limit-exceeded": {
144
+ code: "limit-exceeded",
145
+ severity: "warning",
146
+ posture: "fail-open",
147
+ retryable: false,
148
+ summary: "A configured bound was reached and data was dropped."
149
+ },
150
+ "delivery-identifier-unavailable": {
151
+ code: "delivery-identifier-unavailable",
152
+ severity: "warning",
153
+ // Fail-open: the observation is still attributed and exported. Only the
154
+ // at-most-once guarantee is missing, and refusing the telemetry to protect
155
+ // a duplicate count would trade a certain loss for a possible one.
156
+ posture: "fail-open",
157
+ retryable: false,
158
+ summary: "No replay-stable delivery identifier was available; this callback was exported without deduplication."
159
+ },
160
+ "delivery-claim-superseded": {
161
+ code: "delivery-claim-superseded",
162
+ severity: "warning",
163
+ // Fail-open, and specifically *not* silent. A peer reclaimed this callback's
164
+ // claim while this process was still working on it, which means the
165
+ // configured stale window is shorter than this installation's real worst
166
+ // case. Both processes may now have exported the callback, so the
167
+ // at-most-once guarantee did not hold for it — the only honest response is
168
+ // to say so and let the operator raise the window.
169
+ posture: "fail-open",
170
+ retryable: false,
171
+ summary: "A delivery claim was reclaimed by another process before this one committed; the callback may have been exported twice."
172
+ },
173
+ "internal-error": {
174
+ code: "internal-error",
175
+ severity: "error",
176
+ posture: "fail-open",
177
+ retryable: false,
178
+ summary: "An unexpected failure was contained."
179
+ }
180
+ });
181
+ var describeErrorCode = (code) => ERROR_TAXONOMY[code];
182
+ var attributionOutcomeSchema = z.enum([
183
+ /** Identity resolved; events carry provider and session identity. */
184
+ "attributed",
185
+ /** Identity could not be established safely; nothing was attributed. */
186
+ "declined",
187
+ /** Attribution was attempted and failed unexpectedly. */
188
+ "failed",
189
+ /** Input was recognized but intentionally carried no telemetry. */
190
+ "not-applicable"
191
+ ]);
192
+ var attributionReasonSchema = z.enum([
193
+ "provider-unknown",
194
+ "provider-detection-ambiguous",
195
+ "identity-conflict",
196
+ "identity-incomplete",
197
+ "adapter-ignored-input",
198
+ "adapter-failure",
199
+ "invalid-input",
200
+ "internal-error"
201
+ ]);
202
+
203
+ // src/model/content.ts
2
204
  import { z as z3 } from "zod";
3
205
 
4
206
  // src/model/primitives.ts
5
- import { z } from "zod";
207
+ import { z as z2 } from "zod";
6
208
  var MAX_IDENTIFIER_LENGTH = 256;
7
209
  var MAX_ATTRIBUTE_STRING_LENGTH = 4096;
8
210
  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);
211
+ var nonEmptyStringSchema = z2.string().min(1).max(MAX_IDENTIFIER_LENGTH);
212
+ var epochMillisSchema = z2.number().int().min(0).max(864e13);
213
+ var durationMillisSchema = z2.number().min(0).finite();
214
+ var tokenCountSchema = z2.number().int().min(0);
215
+ var sequenceNumberSchema = z2.number().int().min(0);
216
+ var brandedIdSchema = () => z2.string().min(1).max(MAX_IDENTIFIER_LENGTH);
15
217
  var invocationIdSchema = brandedIdSchema().brand();
16
218
  var sessionIdSchema = brandedIdSchema().brand();
17
219
  var eventIdSchema = brandedIdSchema().brand();
18
220
  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();
221
+ var workspaceIdSchema = z2.string().regex(WORKSPACE_ID_PATTERN, "workspace id must be an opaque `<scheme>:<token>` handle").brand();
20
222
  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();
223
+ var providerIdSchema = z2.string().min(1).max(64).regex(PROVIDER_ID_PATTERN, "provider id must be lowercase and hyphenated").brand();
22
224
  var UNKNOWN_PROVIDER_ID = "unknown";
23
- var resolvedProviderIdSchema = z.union([
225
+ var resolvedProviderIdSchema = z2.union([
24
226
  providerIdSchema,
25
- z.literal(UNKNOWN_PROVIDER_ID)
227
+ z2.literal(UNKNOWN_PROVIDER_ID)
26
228
  ]);
27
- var attributePrimitiveSchema = z.union([
28
- z.string().max(MAX_ATTRIBUTE_STRING_LENGTH),
29
- z.number().finite(),
30
- z.boolean()
229
+ var attributePrimitiveSchema = z2.union([
230
+ z2.string().max(MAX_ATTRIBUTE_STRING_LENGTH),
231
+ z2.number().finite(),
232
+ z2.boolean()
31
233
  ]);
32
- var attributeValueSchema = z.union([
234
+ var attributeValueSchema = z2.union([
33
235
  attributePrimitiveSchema,
34
- z.array(attributePrimitiveSchema).max(MAX_ATTRIBUTE_ARRAY_LENGTH)
236
+ z2.array(attributePrimitiveSchema).max(MAX_ATTRIBUTE_ARRAY_LENGTH)
35
237
  ]);
36
- var attributesSchema = z.record(z.string().min(1).max(MAX_IDENTIFIER_LENGTH), attributeValueSchema);
37
- var detectionConfidenceSchema = z.enum(["none", "weak", "strong", "exact"]);
238
+ var attributesSchema = z2.record(z2.string().min(1).max(MAX_IDENTIFIER_LENGTH), attributeValueSchema);
239
+ var detectionConfidenceSchema = z2.enum(["none", "weak", "strong", "exact"]);
38
240
  var DETECTION_CONFIDENCE_RANK = Object.freeze({
39
241
  none: 0,
40
242
  weak: 1,
41
243
  strong: 2,
42
244
  exact: 3
43
245
  });
44
- var sourceTransportSchema = z.enum([
246
+ var sourceTransportSchema = z2.enum([
45
247
  "hook-stdin",
46
248
  "cli-argument",
47
249
  "library-call",
48
250
  "test-fixture"
49
251
  ]);
50
252
 
51
- // src/model/usage.ts
52
- import { z as z2 } from "zod";
53
- var usageTemporalitySchema = z2.enum(["delta", "cumulative"]);
54
- var cacheCreationAccountingSchema = z2.enum([
55
- "included-in-input",
56
- "disjoint-from-input",
57
- "not-reported"
253
+ // src/model/content.ts
254
+ var contentKindSchema = z3.enum([
255
+ "prompt",
256
+ "response",
257
+ "reasoning",
258
+ "tool-input",
259
+ "tool-output",
260
+ "error-message",
261
+ "system-instruction",
262
+ "attachment"
58
263
  ]);
59
- var providerTotalAgreementSchema = z2.enum(["unreported", "agrees", "disagrees"]);
60
- var usageReportSchema = z2.strictObject({
61
- temporality: usageTemporalitySchema,
62
- /** Inclusive input tokens. */
63
- inputTokens: tokenCountSchema.optional(),
64
- /** Subset of `inputTokens` served from a prompt cache. */
65
- cachedInputTokens: tokenCountSchema.optional(),
66
- /** Tokens written to a prompt cache. */
67
- cacheCreationInputTokens: tokenCountSchema.optional(),
68
- /** Required when `cacheCreationInputTokens` is present and non-zero. */
69
- cacheCreationAccounting: cacheCreationAccountingSchema.optional(),
70
- /** Inclusive output tokens. */
71
- outputTokens: tokenCountSchema.optional(),
72
- /** Subset of `outputTokens` spent on reasoning. */
73
- reasoningOutputTokens: tokenCountSchema.optional(),
74
- /** Total exactly as the provider reported it, if it reported one. */
75
- providerTotalTokens: tokenCountSchema.optional()
264
+ var contentRoleSchema = z3.enum(["user", "assistant", "system", "tool", "unknown"]);
265
+ var contentDisclosureSchema = z3.enum(["omitted", "masked", "redacted", "raw"]);
266
+ var CONTENT_HASH_PATTERN = /^sha256:[0-9a-f]{64}$/;
267
+ var contentFactSchema = z3.strictObject({
268
+ kind: contentKindSchema,
269
+ role: contentRoleSchema.optional(),
270
+ /** Unicode code point count of the original content. */
271
+ characterLength: z3.number().int().min(0),
272
+ /** UTF-8 byte length of the original content. */
273
+ byteLength: z3.number().int().min(0),
274
+ /** Stable salted digest of the original content. */
275
+ contentHash: z3.string().regex(CONTENT_HASH_PATTERN),
276
+ disclosure: contentDisclosureSchema,
277
+ /** Disclosed text, bounded by the privacy policy. Absent when omitted. */
278
+ text: z3.string().optional(),
279
+ /** True when `text` was cut short by the configured string bound. */
280
+ truncated: z3.boolean(),
281
+ /** Number of secret-looking spans replaced while producing `text`. */
282
+ secretsRedacted: z3.number().int().min(0),
283
+ /** Optional non-sensitive label, e.g. a MIME type or tool name. */
284
+ label: nonEmptyStringSchema.optional()
76
285
  });
77
- var canonicalUsageSchema = z2.strictObject({
78
- temporality: usageTemporalitySchema,
79
- inputTokens: tokenCountSchema,
80
- cachedInputTokens: tokenCountSchema,
81
- cacheCreationInputTokens: tokenCountSchema,
82
- cacheCreationAccounting: cacheCreationAccountingSchema,
83
- outputTokens: tokenCountSchema,
84
- reasoningOutputTokens: tokenCountSchema,
85
- /** Derived: input tokens that were neither cache reads nor cache writes. */
86
- uncachedInputTokens: tokenCountSchema,
87
- /** Derived: canonical billable total. */
88
- totalTokens: tokenCountSchema,
89
- providerTotalTokens: tokenCountSchema.optional(),
90
- providerTotalAgreement: providerTotalAgreementSchema
91
- }).check((ctx) => {
92
- const usage = ctx.value;
93
- const push = (message) => {
94
- ctx.issues.push({ code: "custom", input: usage, message });
95
- };
96
- if (usage.cachedInputTokens > usage.inputTokens) {
97
- push("cachedInputTokens must not exceed inputTokens (it is a subset)");
98
- }
99
- if (usage.reasoningOutputTokens > usage.outputTokens) {
100
- push("reasoningOutputTokens must not exceed outputTokens (it is a subset)");
101
- }
102
- if (usage.cacheCreationAccounting === "not-reported" && usage.cacheCreationInputTokens !== 0) {
103
- push("cacheCreationInputTokens must be 0 when cacheCreationAccounting is not-reported");
104
- }
105
- const creationInsideInput = usage.cacheCreationAccounting === "included-in-input" ? usage.cacheCreationInputTokens : 0;
106
- if (usage.cachedInputTokens + creationInsideInput > usage.inputTokens) {
107
- push(
108
- "cachedInputTokens + cacheCreationInputTokens must not exceed inputTokens when cache creation is included in input"
109
- );
286
+ var contentFactsSchema = z3.array(contentFactSchema).max(64);
287
+ var isContentFactConsistent = (fact) => fact.disclosure === "omitted" ? fact.text === void 0 : fact.text !== void 0;
288
+ var isUnavailableContentFact = (fact) => fact.disclosure === "omitted" && fact.text === void 0 && fact.characterLength === 0 && fact.byteLength === 0;
289
+
290
+ // src/model/extensions.ts
291
+ import { z as z4 } from "zod";
292
+ var EXTENSION_KEY_PATTERN = /^[a-z][a-z0-9]*(?:[-_][a-z0-9]+)*(?:\.[a-z][a-z0-9]*(?:[-_][a-z0-9]+)*)+$/;
293
+ var RESERVED_EXTENSION_NAMESPACES = Object.freeze([
294
+ "otelhook",
295
+ "otel",
296
+ "telemetry"
297
+ ]);
298
+ var MAX_EXTENSION_ENTRIES = 64;
299
+ var extensionKeyNamespace = (key) => key.slice(0, key.indexOf("."));
300
+ var isReservedExtensionNamespace = (key) => RESERVED_EXTENSION_NAMESPACES.includes(extensionKeyNamespace(key));
301
+ var isValidExtensionKey = (key) => EXTENSION_KEY_PATTERN.test(key) && !isReservedExtensionNamespace(key);
302
+ var extensionsSchema = z4.record(z4.string(), attributeValueSchema).check((ctx) => {
303
+ const keys = Object.keys(ctx.value);
304
+ if (keys.length > MAX_EXTENSION_ENTRIES) {
305
+ ctx.issues.push({
306
+ code: "custom",
307
+ input: ctx.value,
308
+ message: `extensions may contain at most ${MAX_EXTENSION_ENTRIES} entries`
309
+ });
110
310
  }
111
- const expectedUncached = usage.inputTokens - usage.cachedInputTokens - creationInsideInput;
112
- if (expectedUncached >= 0 && usage.uncachedInputTokens !== expectedUncached) {
113
- push(`uncachedInputTokens must equal ${expectedUncached}`);
311
+ for (const key of keys) {
312
+ if (!EXTENSION_KEY_PATTERN.test(key)) {
313
+ ctx.issues.push({
314
+ code: "custom",
315
+ input: ctx.value,
316
+ path: [key],
317
+ message: `extension key ${JSON.stringify(key)} must be namespaced, e.g. "acme.tier"`
318
+ });
319
+ continue;
320
+ }
321
+ if (isReservedExtensionNamespace(key)) {
322
+ ctx.issues.push({
323
+ code: "custom",
324
+ input: ctx.value,
325
+ path: [key],
326
+ message: `extension namespace ${JSON.stringify(extensionKeyNamespace(key))} is reserved`
327
+ });
328
+ }
114
329
  }
115
- const creationOutsideInput = usage.cacheCreationAccounting === "disjoint-from-input" ? usage.cacheCreationInputTokens : 0;
116
- const expectedTotal = usage.inputTokens + creationOutsideInput + usage.outputTokens;
117
- if (usage.totalTokens !== expectedTotal) {
118
- push(`totalTokens must equal ${expectedTotal}`);
330
+ });
331
+ var EMPTY_EXTENSIONS = Object.freeze({});
332
+ var emptyExtensions = () => ({});
333
+
334
+ // src/model/identity.ts
335
+ import { z as z5 } from "zod";
336
+ var workspaceKeySourceSchema = z5.enum([
337
+ "git-remote",
338
+ "git-root",
339
+ "working-directory",
340
+ "explicit",
341
+ "unknown"
342
+ ]);
343
+ var workspaceIdentitySchema = z5.strictObject({
344
+ workspaceId: workspaceIdSchema,
345
+ keySource: workspaceKeySourceSchema,
346
+ /** Repository name only; never an owner path or URL with credentials. */
347
+ repositoryName: nonEmptyStringSchema.optional(),
348
+ vcsBranchName: nonEmptyStringSchema.optional(),
349
+ /** Opaque handle for the checked-out revision. */
350
+ vcsRevisionId: nonEmptyStringSchema.optional()
351
+ }).readonly();
352
+ var UNKNOWN_WORKSPACE_ID = "unknown:0000000000000000";
353
+ var unknownWorkspaceIdentity = () => workspaceIdentitySchema.parse({
354
+ workspaceId: UNKNOWN_WORKSPACE_ID,
355
+ keySource: "unknown"
356
+ });
357
+ var sourceProvenanceSchema = z5.strictObject({
358
+ providerId: resolvedProviderIdSchema,
359
+ providerVersion: nonEmptyStringSchema.optional(),
360
+ adapterId: nonEmptyStringSchema,
361
+ adapterVersion: nonEmptyStringSchema,
362
+ detectionConfidence: detectionConfidenceSchema,
363
+ /** The provider's own name for the source event, e.g. a hook event name. */
364
+ sourceEventName: nonEmptyStringSchema.optional(),
365
+ transport: sourceTransportSchema
366
+ }).readonly();
367
+ var consumerAttributesSchema = attributesSchema.readonly();
368
+ var invocationIdentitySchema = z5.strictObject({
369
+ invocationId: invocationIdSchema,
370
+ sessionId: sessionIdSchema,
371
+ /** Set when this invocation runs beneath another agent invocation. */
372
+ parentInvocationId: invocationIdSchema.optional(),
373
+ /** Root of the session tree when the provider exposes one. */
374
+ rootSessionId: sessionIdSchema.optional(),
375
+ /** Stable handle for the agent process/instance, when available. */
376
+ agentInstanceId: nonEmptyStringSchema.optional(),
377
+ provenance: sourceProvenanceSchema,
378
+ workspace: workspaceIdentitySchema,
379
+ startedAt: epochMillisSchema,
380
+ consumerAttributes: consumerAttributesSchema
381
+ }).readonly();
382
+ var identityClaimFieldsSchema = z5.strictObject({
383
+ invocationId: invocationIdSchema.optional(),
384
+ sessionId: sessionIdSchema.optional(),
385
+ parentInvocationId: invocationIdSchema.optional(),
386
+ rootSessionId: sessionIdSchema.optional(),
387
+ agentInstanceId: nonEmptyStringSchema.optional(),
388
+ workspace: workspaceIdentitySchema.optional(),
389
+ startedAt: epochMillisSchema.optional()
390
+ });
391
+ var identityClaimSchema = z5.strictObject({
392
+ /** Non-sensitive label, e.g. `adapter:acme-cli` or `env:OTEL_HOOK_SESSION_ID`. */
393
+ source: nonEmptyStringSchema,
394
+ confidence: detectionConfidenceSchema,
395
+ fields: identityClaimFieldsSchema
396
+ });
397
+ var CLAIM_FIELDS = [
398
+ "invocationId",
399
+ "sessionId",
400
+ "parentInvocationId",
401
+ "rootSessionId",
402
+ "agentInstanceId",
403
+ "workspace",
404
+ "startedAt"
405
+ ];
406
+ var renderClaimValue = (value) => {
407
+ if (typeof value === "string") {
408
+ return value;
119
409
  }
120
- const expectedAgreement = usage.providerTotalTokens === void 0 ? "unreported" : usage.providerTotalTokens === expectedTotal ? "agrees" : "disagrees";
121
- if (usage.providerTotalAgreement !== expectedAgreement) {
122
- push(`providerTotalAgreement must be ${expectedAgreement}`);
410
+ if (typeof value === "number" || typeof value === "boolean") {
411
+ return String(value);
123
412
  }
124
- });
125
- var normalizeUsage = (report) => {
126
- const parsed = usageReportSchema.safeParse(report);
127
- if (!parsed.success) {
128
- return {
129
- status: "invalid",
130
- issues: parsed.error.issues.map((issue) => ({
131
- code: "invalid-report",
132
- message: `${issue.path.join(".") || "<root>"}: ${issue.message}`
133
- }))
134
- };
413
+ if (value !== null && typeof value === "object" && "workspaceId" in value) {
414
+ const { workspaceId } = value;
415
+ return typeof workspaceId === "string" ? workspaceId : "<workspace>";
135
416
  }
136
- const input = parsed.data;
417
+ return "<opaque>";
418
+ };
419
+ var resolveInvocationIdentity = (input) => {
420
+ const parsedClaims = [];
137
421
  const issues = [];
138
- const notes = [];
139
- const inputTokens = input.inputTokens ?? 0;
140
- const cachedInputTokens = input.cachedInputTokens ?? 0;
141
- const cacheCreationInputTokens = input.cacheCreationInputTokens ?? 0;
142
- const outputTokens = input.outputTokens ?? 0;
143
- const reasoningOutputTokens = input.reasoningOutputTokens ?? 0;
144
- let accounting;
145
- if (cacheCreationInputTokens === 0) {
146
- accounting = input.cacheCreationAccounting ?? "not-reported";
147
- if (accounting !== "not-reported") {
148
- notes.push(
149
- `cacheCreationAccounting=${accounting} retained with zero cache-creation tokens`
422
+ for (const [index, claim] of input.claims.entries()) {
423
+ const parsed2 = identityClaimSchema.safeParse(claim);
424
+ if (parsed2.success) {
425
+ parsedClaims.push(parsed2.data);
426
+ } else {
427
+ issues.push(
428
+ `claim[${index}]: ${parsed2.error.issues.map((issue) => `${issue.path.join(".") || "<root>"} ${issue.message}`).join(", ")}`
150
429
  );
151
430
  }
152
- } else if (input.cacheCreationAccounting === void 0) {
153
- issues.push({
154
- code: "cache-creation-accounting-missing",
155
- message: "cacheCreationAccounting is required when cacheCreationInputTokens is non-zero; it cannot be inferred"
156
- });
157
- accounting = "not-reported";
158
- } else if (input.cacheCreationAccounting === "not-reported") {
159
- issues.push({
160
- code: "cache-creation-accounting-missing",
161
- message: "cacheCreationAccounting=not-reported conflicts with non-zero cacheCreationInputTokens"
162
- });
163
- accounting = "not-reported";
164
- } else {
165
- accounting = input.cacheCreationAccounting;
166
- }
167
- if (cachedInputTokens > inputTokens) {
168
- issues.push({
169
- code: "cached-exceeds-input",
170
- message: `cachedInputTokens (${cachedInputTokens}) exceeds inclusive inputTokens (${inputTokens})`
171
- });
172
- }
173
- if (reasoningOutputTokens > outputTokens) {
174
- issues.push({
175
- code: "reasoning-exceeds-output",
176
- message: `reasoningOutputTokens (${reasoningOutputTokens}) exceeds inclusive outputTokens (${outputTokens})`
177
- });
178
- }
179
- const creationInsideInput = accounting === "included-in-input" ? cacheCreationInputTokens : 0;
180
- if (cachedInputTokens + creationInsideInput > inputTokens) {
181
- issues.push({
182
- code: "cache-creation-exceeds-input",
183
- message: `cachedInputTokens + cacheCreationInputTokens (${cachedInputTokens + creationInsideInput}) exceeds inclusive inputTokens (${inputTokens})`
184
- });
185
431
  }
186
432
  if (issues.length > 0) {
187
433
  return { status: "invalid", issues };
188
434
  }
189
- const creationOutsideInput = accounting === "disjoint-from-input" ? cacheCreationInputTokens : 0;
190
- const totalTokens = inputTokens + creationOutsideInput + outputTokens;
191
- const providerTotalAgreement = input.providerTotalTokens === void 0 ? "unreported" : input.providerTotalTokens === totalTokens ? "agrees" : "disagrees";
192
- if (providerTotalAgreement === "disagrees") {
193
- notes.push(
194
- `providerTotalTokens (${input.providerTotalTokens ?? 0}) disagrees with canonical total (${totalTokens}); both retained`
435
+ const conflicts = [];
436
+ const selected = {};
437
+ for (const field of CLAIM_FIELDS) {
438
+ const contributors = parsedClaims.filter((claim) => claim.fields[field] !== void 0);
439
+ if (contributors.length === 0) {
440
+ continue;
441
+ }
442
+ const bestRank = Math.max(
443
+ ...contributors.map((claim) => DETECTION_CONFIDENCE_RANK[claim.confidence])
444
+ );
445
+ const best = contributors.filter(
446
+ (claim) => DETECTION_CONFIDENCE_RANK[claim.confidence] === bestRank
195
447
  );
448
+ const rendered = /* @__PURE__ */ new Map();
449
+ for (const claim of best) {
450
+ const key = JSON.stringify(claim.fields[field]);
451
+ const sources = rendered.get(key) ?? [];
452
+ sources.push(claim.source);
453
+ rendered.set(key, sources);
454
+ }
455
+ if (rendered.size > 1) {
456
+ const [firstBest] = best;
457
+ conflicts.push({
458
+ field,
459
+ confidence: firstBest?.confidence ?? "none",
460
+ values: best.map((claim) => renderClaimValue(claim.fields[field])),
461
+ sources: best.map((claim) => claim.source)
462
+ });
463
+ continue;
464
+ }
465
+ const [winner] = best;
466
+ if (winner !== void 0) {
467
+ selected[field] = winner.fields[field];
468
+ }
196
469
  }
197
- const usage = {
198
- temporality: input.temporality,
199
- inputTokens,
200
- cachedInputTokens,
201
- cacheCreationInputTokens,
202
- cacheCreationAccounting: accounting,
470
+ if (conflicts.length > 0) {
471
+ return { status: "conflict", conflicts };
472
+ }
473
+ const missing = [];
474
+ if (selected.invocationId === void 0) {
475
+ missing.push("invocationId");
476
+ }
477
+ if (selected.sessionId === void 0) {
478
+ missing.push("sessionId");
479
+ }
480
+ if (missing.length > 0) {
481
+ return { status: "incomplete", missing };
482
+ }
483
+ const startedAt = selected.startedAt ?? input.fallback?.startedAt;
484
+ if (startedAt === void 0) {
485
+ return { status: "incomplete", missing: ["startedAt"] };
486
+ }
487
+ const workspace = selected.workspace ?? input.fallback?.workspace ?? unknownWorkspaceIdentity();
488
+ const candidate = {
489
+ invocationId: selected.invocationId,
490
+ sessionId: selected.sessionId,
491
+ ...selected.parentInvocationId === void 0 ? {} : { parentInvocationId: selected.parentInvocationId },
492
+ ...selected.rootSessionId === void 0 ? {} : { rootSessionId: selected.rootSessionId },
493
+ ...selected.agentInstanceId === void 0 ? {} : { agentInstanceId: selected.agentInstanceId },
494
+ provenance: input.provenance,
495
+ workspace,
496
+ startedAt,
497
+ consumerAttributes: input.consumerAttributes ?? {}
498
+ };
499
+ const parsed = invocationIdentitySchema.safeParse(candidate);
500
+ if (!parsed.success) {
501
+ return {
502
+ status: "invalid",
503
+ issues: parsed.error.issues.map(
504
+ (issue) => `${issue.path.join(".") || "<root>"}: ${issue.message}`
505
+ )
506
+ };
507
+ }
508
+ return { status: "resolved", identity: parsed.data };
509
+ };
510
+
511
+ // src/model/target.ts
512
+ import { z as z6 } from "zod";
513
+ var targetSourceSchema = z6.enum(["tool-path", "shell-cwd", "session-cwd"]);
514
+ var MAX_TARGET_HINT_PATHS = 8;
515
+ var MAX_TARGET_PATH_LENGTH = 4096;
516
+ var localPathSchema = z6.string().min(1).max(MAX_TARGET_PATH_LENGTH).refine((value) => !value.includes("\0"), "path must not contain NUL");
517
+ var targetHintSchema = z6.strictObject({
518
+ source: targetSourceSchema,
519
+ paths: z6.array(localPathSchema).min(1).max(MAX_TARGET_HINT_PATHS).readonly(),
520
+ /** Absolute directory that relative `paths` resolve against. */
521
+ baseDirectory: localPathSchema.optional()
522
+ }).readonly();
523
+ var worktreeKindSchema = z6.enum(["main", "linked"]);
524
+ var workspaceTargetSchema = z6.strictObject({
525
+ workspaceId: workspaceIdSchema,
526
+ /** Branch checked out in that worktree; absent on a detached HEAD. */
527
+ vcsBranchName: nonEmptyStringSchema.optional(),
528
+ source: targetSourceSchema,
529
+ /** `git-root` handle of the repository's main worktree; absent when there is none to name. */
530
+ repositoryId: workspaceIdSchema.optional(),
531
+ worktreeKind: worktreeKindSchema.optional()
532
+ }).readonly();
533
+ var SUBAGENT_ID_PATTERN = /^[A-Za-z0-9_.:@+=-]{1,256}$/;
534
+ var subagentIdSchema = z6.string().regex(SUBAGENT_ID_PATTERN);
535
+
536
+ // src/model/usage.ts
537
+ import { z as z7 } from "zod";
538
+ var usageTemporalitySchema = z7.enum(["delta", "cumulative"]);
539
+ var cacheCreationAccountingSchema = z7.enum([
540
+ "included-in-input",
541
+ "disjoint-from-input",
542
+ "not-reported"
543
+ ]);
544
+ var providerTotalAgreementSchema = z7.enum(["unreported", "agrees", "disagrees"]);
545
+ var usageReportSchema = z7.strictObject({
546
+ temporality: usageTemporalitySchema,
547
+ /** Inclusive input tokens. */
548
+ inputTokens: tokenCountSchema.optional(),
549
+ /** Subset of `inputTokens` served from a prompt cache. */
550
+ cachedInputTokens: tokenCountSchema.optional(),
551
+ /** Tokens written to a prompt cache. */
552
+ cacheCreationInputTokens: tokenCountSchema.optional(),
553
+ /** Required when `cacheCreationInputTokens` is present and non-zero. */
554
+ cacheCreationAccounting: cacheCreationAccountingSchema.optional(),
555
+ /** Inclusive output tokens. */
556
+ outputTokens: tokenCountSchema.optional(),
557
+ /** Subset of `outputTokens` spent on reasoning. */
558
+ reasoningOutputTokens: tokenCountSchema.optional(),
559
+ /** Total exactly as the provider reported it, if it reported one. */
560
+ providerTotalTokens: tokenCountSchema.optional()
561
+ });
562
+ var canonicalUsageSchema = z7.strictObject({
563
+ temporality: usageTemporalitySchema,
564
+ inputTokens: tokenCountSchema,
565
+ cachedInputTokens: tokenCountSchema,
566
+ cacheCreationInputTokens: tokenCountSchema,
567
+ cacheCreationAccounting: cacheCreationAccountingSchema,
568
+ outputTokens: tokenCountSchema,
569
+ reasoningOutputTokens: tokenCountSchema,
570
+ /** Derived: input tokens that were neither cache reads nor cache writes. */
571
+ uncachedInputTokens: tokenCountSchema,
572
+ /** Derived: canonical billable total. */
573
+ totalTokens: tokenCountSchema,
574
+ providerTotalTokens: tokenCountSchema.optional(),
575
+ providerTotalAgreement: providerTotalAgreementSchema
576
+ }).check((ctx) => {
577
+ const usage = ctx.value;
578
+ const push = (message) => {
579
+ ctx.issues.push({ code: "custom", input: usage, message });
580
+ };
581
+ if (usage.cachedInputTokens > usage.inputTokens) {
582
+ push("cachedInputTokens must not exceed inputTokens (it is a subset)");
583
+ }
584
+ if (usage.reasoningOutputTokens > usage.outputTokens) {
585
+ push("reasoningOutputTokens must not exceed outputTokens (it is a subset)");
586
+ }
587
+ if (usage.cacheCreationAccounting === "not-reported" && usage.cacheCreationInputTokens !== 0) {
588
+ push("cacheCreationInputTokens must be 0 when cacheCreationAccounting is not-reported");
589
+ }
590
+ const creationInsideInput = usage.cacheCreationAccounting === "included-in-input" ? usage.cacheCreationInputTokens : 0;
591
+ if (usage.cachedInputTokens + creationInsideInput > usage.inputTokens) {
592
+ push(
593
+ "cachedInputTokens + cacheCreationInputTokens must not exceed inputTokens when cache creation is included in input"
594
+ );
595
+ }
596
+ const expectedUncached = usage.inputTokens - usage.cachedInputTokens - creationInsideInput;
597
+ if (expectedUncached >= 0 && usage.uncachedInputTokens !== expectedUncached) {
598
+ push(`uncachedInputTokens must equal ${expectedUncached}`);
599
+ }
600
+ const creationOutsideInput = usage.cacheCreationAccounting === "disjoint-from-input" ? usage.cacheCreationInputTokens : 0;
601
+ const expectedTotal = usage.inputTokens + creationOutsideInput + usage.outputTokens;
602
+ if (usage.totalTokens !== expectedTotal) {
603
+ push(`totalTokens must equal ${expectedTotal}`);
604
+ }
605
+ const expectedAgreement = usage.providerTotalTokens === void 0 ? "unreported" : usage.providerTotalTokens === expectedTotal ? "agrees" : "disagrees";
606
+ if (usage.providerTotalAgreement !== expectedAgreement) {
607
+ push(`providerTotalAgreement must be ${expectedAgreement}`);
608
+ }
609
+ });
610
+ var normalizeUsage = (report) => {
611
+ const parsed = usageReportSchema.safeParse(report);
612
+ if (!parsed.success) {
613
+ return {
614
+ status: "invalid",
615
+ issues: parsed.error.issues.map((issue) => ({
616
+ code: "invalid-report",
617
+ message: `${issue.path.join(".") || "<root>"}: ${issue.message}`
618
+ }))
619
+ };
620
+ }
621
+ const input = parsed.data;
622
+ const issues = [];
623
+ const notes = [];
624
+ const inputTokens = input.inputTokens ?? 0;
625
+ const cachedInputTokens = input.cachedInputTokens ?? 0;
626
+ const cacheCreationInputTokens = input.cacheCreationInputTokens ?? 0;
627
+ const outputTokens = input.outputTokens ?? 0;
628
+ const reasoningOutputTokens = input.reasoningOutputTokens ?? 0;
629
+ let accounting;
630
+ if (cacheCreationInputTokens === 0) {
631
+ accounting = input.cacheCreationAccounting ?? "not-reported";
632
+ if (accounting !== "not-reported") {
633
+ notes.push(
634
+ `cacheCreationAccounting=${accounting} retained with zero cache-creation tokens`
635
+ );
636
+ }
637
+ } else if (input.cacheCreationAccounting === void 0) {
638
+ issues.push({
639
+ code: "cache-creation-accounting-missing",
640
+ message: "cacheCreationAccounting is required when cacheCreationInputTokens is non-zero; it cannot be inferred"
641
+ });
642
+ accounting = "not-reported";
643
+ } else if (input.cacheCreationAccounting === "not-reported") {
644
+ issues.push({
645
+ code: "cache-creation-accounting-missing",
646
+ message: "cacheCreationAccounting=not-reported conflicts with non-zero cacheCreationInputTokens"
647
+ });
648
+ accounting = "not-reported";
649
+ } else {
650
+ accounting = input.cacheCreationAccounting;
651
+ }
652
+ if (cachedInputTokens > inputTokens) {
653
+ issues.push({
654
+ code: "cached-exceeds-input",
655
+ message: `cachedInputTokens (${cachedInputTokens}) exceeds inclusive inputTokens (${inputTokens})`
656
+ });
657
+ }
658
+ if (reasoningOutputTokens > outputTokens) {
659
+ issues.push({
660
+ code: "reasoning-exceeds-output",
661
+ message: `reasoningOutputTokens (${reasoningOutputTokens}) exceeds inclusive outputTokens (${outputTokens})`
662
+ });
663
+ }
664
+ const creationInsideInput = accounting === "included-in-input" ? cacheCreationInputTokens : 0;
665
+ if (cachedInputTokens + creationInsideInput > inputTokens) {
666
+ issues.push({
667
+ code: "cache-creation-exceeds-input",
668
+ message: `cachedInputTokens + cacheCreationInputTokens (${cachedInputTokens + creationInsideInput}) exceeds inclusive inputTokens (${inputTokens})`
669
+ });
670
+ }
671
+ if (issues.length > 0) {
672
+ return { status: "invalid", issues };
673
+ }
674
+ const creationOutsideInput = accounting === "disjoint-from-input" ? cacheCreationInputTokens : 0;
675
+ const totalTokens = inputTokens + creationOutsideInput + outputTokens;
676
+ const providerTotalAgreement = input.providerTotalTokens === void 0 ? "unreported" : input.providerTotalTokens === totalTokens ? "agrees" : "disagrees";
677
+ if (providerTotalAgreement === "disagrees") {
678
+ notes.push(
679
+ `providerTotalTokens (${input.providerTotalTokens ?? 0}) disagrees with canonical total (${totalTokens}); both retained`
680
+ );
681
+ }
682
+ const usage = {
683
+ temporality: input.temporality,
684
+ inputTokens,
685
+ cachedInputTokens,
686
+ cacheCreationInputTokens,
687
+ cacheCreationAccounting: accounting,
203
688
  outputTokens,
204
689
  reasoningOutputTokens,
205
690
  uncachedInputTokens: inputTokens - cachedInputTokens - creationInsideInput,
@@ -274,63 +759,292 @@ var toReport = (usage) => ({
274
759
  ...usage.providerTotalTokens === void 0 ? {} : { providerTotalTokens: usage.providerTotalTokens }
275
760
  });
276
761
 
277
- // src/runtime/ports.ts
278
- var appliedDeliverySchema = z3.strictObject({
279
- callbackId: z3.string().regex(/^[A-Za-z0-9_-]{1,128}$/),
280
- /** How many of that delivery's observations are folded in, counted from one. */
281
- applications: z3.number().int().min(1).max(4096)
282
- });
283
- var stateValueSchema = z3.discriminatedUnion("kind", [
284
- z3.strictObject({
285
- kind: z3.literal("usage-cumulative"),
286
- usage: canonicalUsageSchema,
287
- /**
288
- * Optional: absent on every record written before this field existed, which
289
- * reads as "unknown provenance" and simply forgoes the idempotency check
290
- * rather than resetting a baseline to gain it.
291
- */
292
- appliedDelivery: appliedDeliverySchema.optional()
293
- }),
294
- z3.strictObject({
295
- kind: z3.literal("sequence"),
296
- next: sequenceNumberSchema
297
- }),
298
- z3.strictObject({
299
- kind: z3.literal("attributes"),
300
- attributes: attributesSchema
301
- })
302
- ]);
303
- var stateRecordSchema = z3.strictObject({
304
- /** Incremented on each write; lets callers detect lost updates. */
305
- revision: z3.number().int().min(0),
306
- updatedAt: epochMillisSchema,
307
- value: stateValueSchema
308
- });
309
- var logLevelSchema = z3.enum(["silent", "error", "warn", "info", "debug"]);
310
- var LOG_LEVEL_RANK = Object.freeze({
311
- silent: 0,
312
- error: 1,
313
- warn: 2,
314
- info: 3,
315
- debug: 4
316
- });
762
+ // src/model/version.ts
763
+ import { z as z8 } from "zod";
764
+ var CANONICAL_SCHEMA_VERSION = 1;
765
+ var canonicalSchemaVersionSchema = z8.literal(CANONICAL_SCHEMA_VERSION);
317
766
 
318
- // src/runtime/clock.ts
319
- var createSystemClock = () => ({
320
- now: () => epochMillisSchema.parse(Date.now()),
321
- monotonicMillis: () => Number(process.hrtime.bigint() / 1000000n)
767
+ // src/model/events.ts
768
+ var modelDescriptorSchema = z9.strictObject({
769
+ modelId: nonEmptyStringSchema,
770
+ /** Vendor of the model, e.g. `anthropic`. Distinct from the agent provider. */
771
+ vendor: nonEmptyStringSchema.optional(),
772
+ family: nonEmptyStringSchema.optional()
322
773
  });
323
- var createFixedClock = (options = {}) => {
324
- let wall = options.startMillis ?? 17e11;
325
- let monotonic = 0;
326
- const tick = options.tickMillis ?? 0;
327
- return {
328
- now: () => {
329
- const current = wall;
330
- wall += tick;
331
- monotonic += tick;
332
- return epochMillisSchema.parse(current);
333
- },
774
+ var costFactsSchema = z9.strictObject({
775
+ /** ISO 4217 code. */
776
+ currency: z9.string().length(3),
777
+ amount: z9.number().min(0).finite(),
778
+ source: z9.enum(["provider-reported", "computed"])
779
+ });
780
+ var canonicalEventTypeSchema = z9.enum([
781
+ "session.start",
782
+ "session.end",
783
+ "prompt.submitted",
784
+ "generation.start",
785
+ "generation.end",
786
+ "tool.start",
787
+ "tool.end",
788
+ "subagent.start",
789
+ "subagent.end",
790
+ "compaction.performed",
791
+ "error.raised"
792
+ ]);
793
+ var CANONICAL_EVENT_TYPES = canonicalEventTypeSchema.options;
794
+ var outcomeSchema = z9.enum(["ok", "error", "cancelled", "timeout", "denied", "unknown"]);
795
+ var baseEventFields = {
796
+ schemaVersion: canonicalSchemaVersionSchema,
797
+ eventId: eventIdSchema,
798
+ invocationId: invocationIdSchema,
799
+ sessionId: sessionIdSchema,
800
+ /** Per-invocation ordering key. Stable across replays of the same input. */
801
+ sequence: sequenceNumberSchema,
802
+ occurredAt: epochMillisSchema,
803
+ provenance: sourceProvenanceSchema,
804
+ workspace: workspaceIdentitySchema,
805
+ /**
806
+ * The provider's own id for the subagent this event was emitted inside (e.g.
807
+ * Claude Code's `agent_id`). Absent for the top-level agent. Set by the event
808
+ * factory, never by hand.
809
+ */
810
+ subagentId: subagentIdSchema.optional(),
811
+ extensions: extensionsSchema.default(emptyExtensions)
812
+ };
813
+ var event = (shape) => z9.strictObject({ ...baseEventFields, ...shape });
814
+ var sessionStartEventSchema = event({
815
+ type: z9.literal("session.start"),
816
+ sessionKind: z9.enum(["interactive", "non-interactive", "unknown"]),
817
+ agentName: nonEmptyStringSchema.optional(),
818
+ agentVersion: nonEmptyStringSchema.optional(),
819
+ model: modelDescriptorSchema.optional(),
820
+ /** The git worktree the session runs in, resolved by the core (ADR 0008). */
821
+ target: workspaceTargetSchema.optional()
822
+ });
823
+ var sessionEndEventSchema = event({
824
+ type: z9.literal("session.end"),
825
+ reason: z9.enum(["completed", "aborted", "error", "timeout", "unknown"]),
826
+ durationMillis: durationMillisSchema.optional(),
827
+ /** Session totals, typically cumulative. */
828
+ usage: canonicalUsageSchema.optional(),
829
+ cost: costFactsSchema.optional()
830
+ });
831
+ var promptSubmittedEventSchema = event({
832
+ type: z9.literal("prompt.submitted"),
833
+ promptSource: z9.enum(["user", "automation", "resumed", "unknown"]),
834
+ content: contentFactSchema.optional(),
835
+ turnIndex: z9.number().int().min(0).optional(),
836
+ /** The git worktree the session runs in, resolved by the core (ADR 0008). */
837
+ target: workspaceTargetSchema.optional()
838
+ });
839
+ var generationStartEventSchema = event({
840
+ type: z9.literal("generation.start"),
841
+ generationId: nonEmptyStringSchema,
842
+ model: modelDescriptorSchema,
843
+ requestedMaxOutputTokens: tokenCountSchema.optional(),
844
+ inputContent: contentFactsSchema.optional()
845
+ });
846
+ var generationEndEventSchema = event({
847
+ type: z9.literal("generation.end"),
848
+ generationId: nonEmptyStringSchema,
849
+ model: modelDescriptorSchema,
850
+ outcome: outcomeSchema,
851
+ stopReason: nonEmptyStringSchema.optional(),
852
+ durationMillis: durationMillisSchema.optional(),
853
+ usage: canonicalUsageSchema.optional(),
854
+ /**
855
+ * True when `usage` is known to cover only part of the generation (for
856
+ * example the last model request of a multi-request turn); false when the
857
+ * provider or harness said it is the whole. Absent: not stated. Meaningless
858
+ * without `usage`.
859
+ */
860
+ usagePartial: z9.boolean().optional(),
861
+ cost: costFactsSchema.optional(),
862
+ outputContent: contentFactsSchema.optional()
863
+ });
864
+ var toolKindSchema = z9.enum([
865
+ "read",
866
+ "write",
867
+ "execute",
868
+ "search",
869
+ "network",
870
+ "delegate",
871
+ "other",
872
+ "unknown"
873
+ ]);
874
+ var toolStartEventSchema = event({
875
+ type: z9.literal("tool.start"),
876
+ toolCallId: nonEmptyStringSchema,
877
+ toolName: nonEmptyStringSchema,
878
+ toolKind: toolKindSchema,
879
+ generationId: nonEmptyStringSchema.optional(),
880
+ input: contentFactSchema.optional(),
881
+ /** The git worktree this call targeted, resolved by the core (ADR 0008). */
882
+ target: workspaceTargetSchema.optional()
883
+ });
884
+ var toolEndEventSchema = event({
885
+ type: z9.literal("tool.end"),
886
+ toolCallId: nonEmptyStringSchema,
887
+ toolName: nonEmptyStringSchema,
888
+ outcome: outcomeSchema,
889
+ durationMillis: durationMillisSchema.optional(),
890
+ /** Present when the host asked for or recorded a permission decision. */
891
+ permissionDecision: z9.enum(["allowed", "denied", "deferred", "not-required"]).optional(),
892
+ output: contentFactSchema.optional(),
893
+ /** The git worktree this call targeted, resolved by the core (ADR 0008). */
894
+ target: workspaceTargetSchema.optional()
895
+ });
896
+ var subagentStartEventSchema = event({
897
+ type: z9.literal("subagent.start"),
898
+ subagentInvocationId: invocationIdSchema,
899
+ subagentType: nonEmptyStringSchema.optional(),
900
+ /** 0 for the top-level agent; 1 for its direct children. */
901
+ delegationDepth: z9.number().int().min(0).max(64),
902
+ model: modelDescriptorSchema.optional()
903
+ });
904
+ var subagentEndEventSchema = event({
905
+ type: z9.literal("subagent.end"),
906
+ subagentInvocationId: invocationIdSchema,
907
+ outcome: outcomeSchema,
908
+ durationMillis: durationMillisSchema.optional(),
909
+ usage: canonicalUsageSchema.optional()
910
+ });
911
+ var compactionPerformedEventSchema = event({
912
+ type: z9.literal("compaction.performed"),
913
+ trigger: z9.enum(["automatic", "manual", "unknown"]),
914
+ /** Provider-reported context size before and after compaction, if known. */
915
+ contextTokensBefore: tokenCountSchema.optional(),
916
+ contextTokensAfter: tokenCountSchema.optional(),
917
+ droppedMessageCount: z9.number().int().min(0).optional(),
918
+ usage: canonicalUsageSchema.optional()
919
+ });
920
+ var errorRaisedEventSchema = event({
921
+ type: z9.literal("error.raised"),
922
+ errorCode: otelHookErrorCodeSchema,
923
+ severity: errorSeveritySchema,
924
+ phase: errorPhaseSchema,
925
+ retryable: z9.boolean(),
926
+ /** Error text is content: it is described, never embedded verbatim by default. */
927
+ message: contentFactSchema.optional(),
928
+ /** Non-sensitive, provider-agnostic short label. */
929
+ detail: nonEmptyStringSchema.optional()
930
+ });
931
+ var canonicalEventSchema = z9.discriminatedUnion("type", [
932
+ sessionStartEventSchema,
933
+ sessionEndEventSchema,
934
+ promptSubmittedEventSchema,
935
+ generationStartEventSchema,
936
+ generationEndEventSchema,
937
+ toolStartEventSchema,
938
+ toolEndEventSchema,
939
+ subagentStartEventSchema,
940
+ subagentEndEventSchema,
941
+ compactionPerformedEventSchema,
942
+ errorRaisedEventSchema
943
+ ]);
944
+ var TARGETED_EVENT_TYPES = ["session.start", "prompt.submitted", "tool.start", "tool.end"];
945
+ var TARGETED = new Set(TARGETED_EVENT_TYPES);
946
+ var isTargetedEvent = (event2) => TARGETED.has(event2.type);
947
+
948
+ // src/runtime/ports.ts
949
+ var appliedDeliverySchema = z10.strictObject({
950
+ callbackId: z10.string().regex(/^[A-Za-z0-9_-]{1,128}$/),
951
+ /** How many of that delivery's observations are folded in, counted from one. */
952
+ applications: z10.number().int().min(1).max(4096)
953
+ });
954
+ var stateValueSchema = z10.discriminatedUnion("kind", [
955
+ z10.strictObject({
956
+ kind: z10.literal("usage-cumulative"),
957
+ usage: canonicalUsageSchema,
958
+ /**
959
+ * Optional: absent on every record written before this field existed, which
960
+ * reads as "unknown provenance" and simply forgoes the idempotency check
961
+ * rather than resetting a baseline to gain it.
962
+ */
963
+ appliedDelivery: appliedDeliverySchema.optional()
964
+ }),
965
+ z10.strictObject({
966
+ kind: z10.literal("sequence"),
967
+ next: sequenceNumberSchema
968
+ }),
969
+ z10.strictObject({
970
+ kind: z10.literal("attributes"),
971
+ attributes: attributesSchema
972
+ }),
973
+ /**
974
+ * The model a session last reported, so a later invocation whose payload names
975
+ * none (Claude Code's `Stop`) can still say which model it was. A model id is
976
+ * not sensitive (`modelDescriptorSchema`), and the descriptor is the strict,
977
+ * bounded canonical shape, never a payload fragment.
978
+ */
979
+ z10.strictObject({
980
+ kind: z10.literal("session-model"),
981
+ model: modelDescriptorSchema
982
+ }),
983
+ /**
984
+ * How far a {@link PayloadEnricher} has read a session's append-only source
985
+ * (Claude Code's transcript), so the next read starts where the last ended.
986
+ * `source` is an opaque digest of what was read, never a path.
987
+ */
988
+ /**
989
+ * Running state of one metric series (issue #69), so a cumulative data point
990
+ * exported by a later hook process continues the same total. Holds numbers and
991
+ * a series digest only; the series' attributes are re-supplied by the caller
992
+ * and never read back from disk.
993
+ */
994
+ z10.strictObject({
995
+ kind: z10.literal("metric-series"),
996
+ /** Start of the cumulative interval. */
997
+ startTimeMillis: epochMillisSchema,
998
+ /** Counters: the running total. */
999
+ value: z10.number().finite().min(0).optional(),
1000
+ /** Histograms: the running aggregation. */
1001
+ histogram: z10.strictObject({
1002
+ count: z10.number().int().min(0),
1003
+ sum: z10.number().finite().min(0),
1004
+ min: z10.number().finite(),
1005
+ max: z10.number().finite(),
1006
+ bucketCounts: z10.array(z10.number().int().min(0)).max(64)
1007
+ }).optional(),
1008
+ /** Opaque digest of the last delivery folded in; makes a replay a no-op. */
1009
+ appliedDelivery: z10.string().regex(/^[A-Za-z0-9_-]{1,128}$/).optional()
1010
+ }),
1011
+ z10.strictObject({
1012
+ kind: z10.literal("read-cursor"),
1013
+ source: z10.string().regex(/^[A-Za-z0-9_-]{1,128}$/),
1014
+ offset: z10.number().int().min(0).max(Number.MAX_SAFE_INTEGER)
1015
+ })
1016
+ ]);
1017
+ var stateRecordSchema = z10.strictObject({
1018
+ /** Incremented on each write; lets callers detect lost updates. */
1019
+ revision: z10.number().int().min(0),
1020
+ updatedAt: epochMillisSchema,
1021
+ value: stateValueSchema
1022
+ });
1023
+ var logLevelSchema = z10.enum(["silent", "error", "warn", "info", "debug"]);
1024
+ var LOG_LEVEL_RANK = Object.freeze({
1025
+ silent: 0,
1026
+ error: 1,
1027
+ warn: 2,
1028
+ info: 3,
1029
+ debug: 4
1030
+ });
1031
+
1032
+ // src/runtime/clock.ts
1033
+ var createSystemClock = () => ({
1034
+ now: () => epochMillisSchema.parse(Date.now()),
1035
+ monotonicMillis: () => Number(process.hrtime.bigint() / 1000000n)
1036
+ });
1037
+ var createFixedClock = (options = {}) => {
1038
+ let wall = options.startMillis ?? 17e11;
1039
+ let monotonic = 0;
1040
+ const tick = options.tickMillis ?? 0;
1041
+ return {
1042
+ now: () => {
1043
+ const current = wall;
1044
+ wall += tick;
1045
+ monotonic += tick;
1046
+ return epochMillisSchema.parse(current);
1047
+ },
334
1048
  monotonicMillis: () => monotonic,
335
1049
  advance: (millis) => {
336
1050
  wall += millis;
@@ -426,263 +1140,65 @@ var createStderrLogger = (options = {}) => {
426
1140
  };
427
1141
 
428
1142
  // src/errors/index.ts
429
- import { z as z5 } from "zod";
430
-
431
- // src/errors/taxonomy.ts
432
- import { z as z4 } from "zod";
433
- var otelHookErrorCodeSchema = z4.enum([
434
- /** Input was not usable at all (empty stdin, unparsable JSON). */
435
- "invalid-input",
436
- /** Input parsed but failed canonical schema validation. */
437
- "schema-validation-failed",
438
- /** No adapter claimed the input with sufficient confidence. */
439
- "provider-unknown",
440
- /** Several adapters claimed the input at the same confidence. */
441
- "provider-detection-ambiguous",
442
- /** An adapter threw or returned a malformed result. */
443
- "provider-adapter-failure",
444
- /** Two identity claims disagreed at equal confidence. */
445
- "identity-conflict",
446
- /** Required identity fields were absent. */
447
- "identity-incomplete",
448
- /** A usage report violated the canonical usage invariants. */
449
- "usage-invalid",
450
- /** The state store could not be read or written. */
451
- "state-store-failure",
452
- /** The telemetry sink rejected or could not deliver a batch. */
453
- "telemetry-export-failure",
454
- /** Content reached the sink boundary in a state the policy forbids. */
455
- "privacy-policy-violation",
456
- /** Configuration could not be resolved. */
457
- "configuration-invalid",
458
- /** A configured bound (events, batch size) dropped data. */
459
- "limit-exceeded",
460
- /**
461
- * No replay-stable delivery identifier was available for a callback while
462
- * deduplication was required.
463
- */
464
- "delivery-identifier-unavailable",
465
- "delivery-claim-superseded",
466
- /** Anything unanticipated. Always reported, never fatal to the host. */
467
- "internal-error"
468
- ]);
469
- var errorSeveritySchema = z4.enum(["warning", "error"]);
470
- var errorPhaseSchema = z4.enum([
471
- "configuration",
472
- "detection",
473
- "identity",
474
- "parsing",
475
- "normalization",
476
- "privacy",
477
- "state",
478
- "export",
479
- "shutdown"
480
- ]);
481
- var failurePostureSchema = z4.enum(["fail-open", "fail-closed-attribution"]);
482
- var ERROR_TAXONOMY = Object.freeze({
483
- "invalid-input": {
484
- code: "invalid-input",
485
- severity: "warning",
486
- posture: "fail-open",
487
- retryable: false,
488
- summary: "Input could not be read or decoded."
489
- },
490
- "schema-validation-failed": {
491
- code: "schema-validation-failed",
492
- severity: "error",
493
- posture: "fail-closed-attribution",
494
- retryable: false,
495
- summary: "A canonical event failed schema validation and was dropped."
496
- },
497
- "provider-unknown": {
498
- code: "provider-unknown",
499
- severity: "warning",
500
- posture: "fail-closed-attribution",
501
- retryable: false,
502
- summary: "No adapter recognized the source provider; the input stays unattributed."
503
- },
504
- "provider-detection-ambiguous": {
505
- code: "provider-detection-ambiguous",
506
- severity: "warning",
507
- posture: "fail-closed-attribution",
508
- retryable: false,
509
- summary: "Multiple adapters claimed the input at equal confidence."
510
- },
511
- "provider-adapter-failure": {
512
- code: "provider-adapter-failure",
513
- severity: "error",
514
- posture: "fail-open",
515
- retryable: false,
516
- summary: "A provider adapter failed while parsing."
517
- },
518
- "identity-conflict": {
519
- code: "identity-conflict",
520
- severity: "error",
521
- posture: "fail-closed-attribution",
522
- retryable: false,
523
- summary: "Identity claims disagreed; attribution was declined."
524
- },
525
- "identity-incomplete": {
526
- code: "identity-incomplete",
527
- severity: "warning",
528
- posture: "fail-closed-attribution",
529
- retryable: false,
530
- summary: "Required identity fields were missing; attribution was declined."
531
- },
532
- "usage-invalid": {
533
- code: "usage-invalid",
534
- severity: "error",
535
- posture: "fail-open",
536
- retryable: false,
537
- summary: "A usage report violated the canonical usage invariants."
538
- },
539
- "state-store-failure": {
540
- code: "state-store-failure",
541
- severity: "warning",
542
- posture: "fail-open",
543
- retryable: true,
544
- summary: "State could not be read or written; derived values may be incomplete."
545
- },
546
- "telemetry-export-failure": {
547
- code: "telemetry-export-failure",
548
- severity: "warning",
549
- posture: "fail-open",
550
- retryable: true,
551
- summary: "The telemetry sink could not accept a batch."
552
- },
553
- "privacy-policy-violation": {
554
- code: "privacy-policy-violation",
555
- severity: "error",
556
- posture: "fail-closed-attribution",
557
- retryable: false,
558
- summary: "Content violated the resolved privacy policy and was dropped."
559
- },
560
- "configuration-invalid": {
561
- code: "configuration-invalid",
562
- severity: "error",
563
- posture: "fail-open",
564
- retryable: false,
565
- summary: "Configuration could not be resolved; defaults apply."
566
- },
567
- "limit-exceeded": {
568
- code: "limit-exceeded",
569
- severity: "warning",
570
- posture: "fail-open",
571
- retryable: false,
572
- summary: "A configured bound was reached and data was dropped."
573
- },
574
- "delivery-identifier-unavailable": {
575
- code: "delivery-identifier-unavailable",
576
- severity: "warning",
577
- // Fail-open: the observation is still attributed and exported. Only the
578
- // at-most-once guarantee is missing, and refusing the telemetry to protect
579
- // a duplicate count would trade a certain loss for a possible one.
580
- posture: "fail-open",
581
- retryable: false,
582
- summary: "No replay-stable delivery identifier was available; this callback was exported without deduplication."
583
- },
584
- "delivery-claim-superseded": {
585
- code: "delivery-claim-superseded",
586
- severity: "warning",
587
- // Fail-open, and specifically *not* silent. A peer reclaimed this callback's
588
- // claim while this process was still working on it, which means the
589
- // configured stale window is shorter than this installation's real worst
590
- // case. Both processes may now have exported the callback, so the
591
- // at-most-once guarantee did not hold for it — the only honest response is
592
- // to say so and let the operator raise the window.
593
- posture: "fail-open",
594
- retryable: false,
595
- summary: "A delivery claim was reclaimed by another process before this one committed; the callback may have been exported twice."
596
- },
597
- "internal-error": {
598
- code: "internal-error",
599
- severity: "error",
600
- posture: "fail-open",
601
- retryable: false,
602
- summary: "An unexpected failure was contained."
603
- }
604
- });
605
- var describeErrorCode = (code) => ERROR_TAXONOMY[code];
606
- var attributionOutcomeSchema = z4.enum([
607
- /** Identity resolved; events carry provider and session identity. */
608
- "attributed",
609
- /** Identity could not be established safely; nothing was attributed. */
610
- "declined",
611
- /** Attribution was attempted and failed unexpectedly. */
612
- "failed",
613
- /** Input was recognized but intentionally carried no telemetry. */
614
- "not-applicable"
615
- ]);
616
- var attributionReasonSchema = z4.enum([
617
- "provider-unknown",
618
- "provider-detection-ambiguous",
619
- "identity-conflict",
620
- "identity-incomplete",
621
- "adapter-ignored-input",
622
- "adapter-failure",
623
- "invalid-input",
624
- "internal-error"
625
- ]);
626
-
627
- // src/errors/index.ts
628
- var otelHookErrorInfoSchema = z5.strictObject({
629
- code: otelHookErrorCodeSchema,
630
- severity: errorSeveritySchema,
631
- phase: errorPhaseSchema,
632
- posture: failurePostureSchema,
633
- retryable: z5.boolean(),
634
- message: z5.string().min(1).max(512),
635
- details: attributesSchema.optional(),
636
- occurredAt: epochMillisSchema.optional()
637
- });
638
- var createErrorInfo = (input) => {
639
- const descriptor = describeErrorCode(input.code);
640
- const message = input.detail === void 0 ? `${input.code} during ${input.phase}: ${descriptor.summary}` : `${input.code} during ${input.phase}: ${input.detail}`;
641
- return otelHookErrorInfoSchema.parse({
642
- code: descriptor.code,
643
- severity: descriptor.severity,
644
- phase: input.phase,
645
- posture: descriptor.posture,
646
- retryable: descriptor.retryable,
647
- message: message.slice(0, 512),
648
- ...input.details === void 0 ? {} : { details: input.details },
649
- ...input.occurredAt === void 0 ? {} : { occurredAt: input.occurredAt }
650
- });
651
- };
652
- var OtelHookError = class _OtelHookError extends Error {
653
- info;
654
- constructor(info) {
655
- super(info.message);
656
- this.name = "OtelHookError";
657
- this.info = info;
658
- }
659
- static of(input) {
660
- return new _OtelHookError(createErrorInfo(input));
661
- }
662
- };
663
- var isOtelHookError = (value) => value instanceof OtelHookError;
664
- var describeThrown = (thrown) => {
665
- if (thrown instanceof Error) {
666
- return {
667
- errorName: thrown.name.slice(0, 64) || "Error",
668
- hasMessage: typeof thrown.message === "string" && thrown.message.length > 0
669
- };
670
- }
671
- return { errorName: typeof thrown, hasMessage: false };
672
- };
673
- var errorInfoFromThrown = (thrown, input) => {
674
- if (isOtelHookError(thrown)) {
675
- return thrown.info;
676
- }
677
- const described = describeThrown(thrown);
678
- return createErrorInfo({
679
- code: input.code ?? "internal-error",
680
- phase: input.phase,
681
- detail: `contained ${described.errorName}`,
682
- details: { "error.name": described.errorName, "error.has_message": described.hasMessage },
683
- ...input.occurredAt === void 0 ? {} : { occurredAt: input.occurredAt }
684
- });
685
- };
1143
+ import { z as z11 } from "zod";
1144
+ var otelHookErrorInfoSchema = z11.strictObject({
1145
+ code: otelHookErrorCodeSchema,
1146
+ severity: errorSeveritySchema,
1147
+ phase: errorPhaseSchema,
1148
+ posture: failurePostureSchema,
1149
+ retryable: z11.boolean(),
1150
+ message: z11.string().min(1).max(512),
1151
+ details: attributesSchema.optional(),
1152
+ occurredAt: epochMillisSchema.optional()
1153
+ });
1154
+ var createErrorInfo = (input) => {
1155
+ const descriptor = describeErrorCode(input.code);
1156
+ const message = input.detail === void 0 ? `${input.code} during ${input.phase}: ${descriptor.summary}` : `${input.code} during ${input.phase}: ${input.detail}`;
1157
+ return otelHookErrorInfoSchema.parse({
1158
+ code: descriptor.code,
1159
+ severity: descriptor.severity,
1160
+ phase: input.phase,
1161
+ posture: descriptor.posture,
1162
+ retryable: descriptor.retryable,
1163
+ message: message.slice(0, 512),
1164
+ ...input.details === void 0 ? {} : { details: input.details },
1165
+ ...input.occurredAt === void 0 ? {} : { occurredAt: input.occurredAt }
1166
+ });
1167
+ };
1168
+ var OtelHookError = class _OtelHookError extends Error {
1169
+ info;
1170
+ constructor(info) {
1171
+ super(info.message);
1172
+ this.name = "OtelHookError";
1173
+ this.info = info;
1174
+ }
1175
+ static of(input) {
1176
+ return new _OtelHookError(createErrorInfo(input));
1177
+ }
1178
+ };
1179
+ var isOtelHookError = (value) => value instanceof OtelHookError;
1180
+ var describeThrown = (thrown) => {
1181
+ if (thrown instanceof Error) {
1182
+ return {
1183
+ errorName: thrown.name.slice(0, 64) || "Error",
1184
+ hasMessage: typeof thrown.message === "string" && thrown.message.length > 0
1185
+ };
1186
+ }
1187
+ return { errorName: typeof thrown, hasMessage: false };
1188
+ };
1189
+ var errorInfoFromThrown = (thrown, input) => {
1190
+ if (isOtelHookError(thrown)) {
1191
+ return thrown.info;
1192
+ }
1193
+ const described = describeThrown(thrown);
1194
+ return createErrorInfo({
1195
+ code: input.code ?? "internal-error",
1196
+ phase: input.phase,
1197
+ detail: `contained ${described.errorName}`,
1198
+ details: { "error.name": described.errorName, "error.has_message": described.hasMessage },
1199
+ ...input.occurredAt === void 0 ? {} : { occurredAt: input.occurredAt }
1200
+ });
1201
+ };
686
1202
 
687
1203
  // src/runtime/memory.ts
688
1204
  var createInMemoryStateStore = (options) => {
@@ -840,11 +1356,11 @@ var resolveDeliveryIdentity = (input) => {
840
1356
  import { z as z17 } from "zod";
841
1357
 
842
1358
  // src/config/schema.ts
843
- import { z as z9 } from "zod";
1359
+ import { z as z15 } from "zod";
844
1360
 
845
1361
  // src/privacy/policy.ts
846
- import { z as z6 } from "zod";
847
- var contentModeSchema = z6.enum(["omit", "mask", "redact", "raw"]);
1362
+ import { z as z12 } from "zod";
1363
+ var contentModeSchema = z12.enum(["omit", "mask", "redact", "raw"]);
848
1364
  var CONTENT_MODE_DISCLOSURE = Object.freeze({
849
1365
  omit: "omitted",
850
1366
  mask: "masked",
@@ -870,35 +1386,35 @@ var DEFAULT_SECRET_VALUE_PATTERNS = Object.freeze([
870
1386
  "eyJ[A-Za-z0-9_-]{10,}\\.[A-Za-z0-9_-]{10,}\\.[A-Za-z0-9_-]{10,}",
871
1387
  "(?:Bearer|Basic)\\s+[A-Za-z0-9._~+/=-]{12,}"
872
1388
  ]);
873
- var privacyLimitsSchema = z6.strictObject({
1389
+ var privacyLimitsSchema = z12.strictObject({
874
1390
  /** Maximum characters of disclosed text per content fact or string value. */
875
- maxStringLength: z6.number().int().min(0).max(65536),
1391
+ maxStringLength: z12.number().int().min(0).max(65536),
876
1392
  /** Maximum nesting depth walked when sanitizing structured values. */
877
- maxDepth: z6.number().int().min(1).max(32),
1393
+ maxDepth: z12.number().int().min(1).max(32),
878
1394
  /** Maximum array entries retained when sanitizing structured values. */
879
- maxArrayLength: z6.number().int().min(1).max(4096),
1395
+ maxArrayLength: z12.number().int().min(1).max(4096),
880
1396
  /** Maximum canonical events emitted per invocation. */
881
- maxEventsPerInvocation: z6.number().int().min(1).max(1e4),
1397
+ maxEventsPerInvocation: z12.number().int().min(1).max(1e4),
882
1398
  /** Maximum object keys retained per level when sanitizing. */
883
- maxObjectKeys: z6.number().int().min(1).max(1024)
1399
+ maxObjectKeys: z12.number().int().min(1).max(1024)
884
1400
  });
885
- var privacyPolicySchema = z6.strictObject({
1401
+ var privacyPolicySchema = z12.strictObject({
886
1402
  contentMode: contentModeSchema,
887
1403
  /**
888
1404
  * `raw` mode is refused unless this is also true, so a single mistyped
889
1405
  * environment variable cannot start exporting prompts.
890
1406
  */
891
- allowRawContent: z6.boolean(),
1407
+ allowRawContent: z12.boolean(),
892
1408
  /**
893
1409
  * Salt mixed into every hash. A per-deployment salt makes hashes
894
1410
  * non-correlatable across deployments; an empty salt makes them globally
895
1411
  * comparable. Both are legitimate; the choice is explicit.
896
1412
  */
897
- hashSalt: z6.string().max(256),
898
- maskCharacter: z6.string().length(1),
899
- redactionPlaceholder: z6.string().min(1).max(64),
900
- secretKeyPatterns: z6.array(z6.string().min(1)).max(128).readonly(),
901
- secretValuePatterns: z6.array(z6.string().min(1)).max(128).readonly(),
1413
+ hashSalt: z12.string().max(256),
1414
+ maskCharacter: z12.string().length(1),
1415
+ redactionPlaceholder: z12.string().min(1).max(64),
1416
+ secretKeyPatterns: z12.array(z12.string().min(1)).max(128).readonly(),
1417
+ secretValuePatterns: z12.array(z12.string().min(1)).max(128).readonly(),
902
1418
  limits: privacyLimitsSchema
903
1419
  });
904
1420
  var DEFAULT_PRIVACY_LIMITS = Object.freeze({
@@ -930,7 +1446,7 @@ var resolvePrivacyPolicy = (policy) => {
930
1446
  };
931
1447
 
932
1448
  // src/config/destinations.ts
933
- import { z as z7 } from "zod";
1449
+ import { z as z13 } from "zod";
934
1450
 
935
1451
  // src/config/header-value.ts
936
1452
  var isUnsafeHeaderValue = (value) => [...value].some((char) => {
@@ -946,558 +1462,329 @@ var OTLP_HEADER_VARIABLES = Object.freeze({
946
1462
  logs: "OTEL_EXPORTER_OTLP_LOGS_HEADERS"
947
1463
  });
948
1464
 
949
- // src/config/destinations.ts
950
- var DEFAULT_DESTINATION_NAME = "default";
951
- var DESTINATION_NAME_PATTERN = /^[a-z0-9][a-z0-9_-]{0,62}$/;
952
- var MAX_EXPORT_DESTINATIONS = 16;
953
- var MAX_DESTINATION_HEADERS = MAX_OTLP_HEADERS;
954
- var HEADER_ENV_REFERENCE_PREFIX = "env:";
955
- var HEADER_NAME_PATTERN = /^[A-Za-z0-9!#$%&'*+.^_`|~-]{1,128}$/;
956
- var ENV_VARIABLE_NAME_PATTERN = /^[A-Za-z_][A-Za-z0-9_]{0,127}$/;
957
- var MAX_HEADER_VALUE_LENGTH = 8192;
958
- var exportSignalSchema = z7.enum(["traces", "logs"]);
959
- var headerValueSchema = z7.string().min(1).max(MAX_HEADER_VALUE_LENGTH).refine(
960
- (value) => !isUnsafeHeaderValue(value),
961
- "header values may not contain line breaks, control characters, or characters beyond Latin-1"
962
- ).refine(
963
- (value) => !value.startsWith(HEADER_ENV_REFERENCE_PREFIX) || ENV_VARIABLE_NAME_PATTERN.test(value.slice(HEADER_ENV_REFERENCE_PREFIX.length)),
964
- "an env: header reference must name an environment variable, e.g. env:COLLECTOR_TOKEN"
965
- );
966
- var endpointSchema = z7.string().url().max(2048);
967
- var exportDestinationSchema = z7.strictObject({
968
- /** Unique, lowercase, filesystem-safe. `default` is reserved for the single-endpoint settings. */
969
- name: z7.string().regex(DESTINATION_NAME_PATTERN, "destination names are lowercase letters, digits, _ and -"),
970
- /** Default true. A disabled destination is neither sent to nor drained. */
971
- enabled: z7.boolean().optional(),
972
- /**
973
- * Traces URL, with the same meaning as `exporter.endpoint`: the logs URL is
974
- * derived from it (`/v1/traces` becomes `/v1/logs`) unless `logsEndpoint` is set.
975
- */
976
- endpoint: endpointSchema.optional(),
977
- /** Per-signal override of `endpoint` for traces. */
978
- tracesEndpoint: endpointSchema.optional(),
979
- /** Per-signal override of the derived logs URL. */
980
- logsEndpoint: endpointSchema.optional(),
981
- /** Defaults to `exporter.protocol`. */
982
- protocol: z7.enum(["http/protobuf", "http/json", "none"]).optional(),
983
- /**
984
- * Header name to value. A value of the form `env:NAME` is read from that
985
- * environment variable at send time, so a credential never has to be written
986
- * into the file. Values never appear in a snapshot, a diagnostic, or `doctor`.
987
- */
988
- headers: z7.record(z7.string().regex(HEADER_NAME_PATTERN, "not a valid header name"), headerValueSchema).refine(
989
- (headers) => Object.keys(headers).length <= MAX_DESTINATION_HEADERS,
990
- `at most ${String(MAX_DESTINATION_HEADERS)} headers per destination`
991
- ).optional(),
992
- /**
993
- * Which signals this destination receives. Default: both. The logs signal is
994
- * still governed by `exporter.logs.enabled`, which stays the one opt-in for a
995
- * second stream leaving the host.
996
- */
997
- signals: z7.array(exportSignalSchema).min(1).max(2).readonly().optional()
998
- }).refine(
999
- (destination) => destination.endpoint !== void 0 || destination.tracesEndpoint !== void 0 || destination.logsEndpoint !== void 0,
1000
- "a destination needs an endpoint, or a tracesEndpoint / logsEndpoint"
1001
- );
1002
- var exportDestinationsSchema = z7.array(exportDestinationSchema).max(MAX_EXPORT_DESTINATIONS).readonly().superRefine((destinations, context) => {
1003
- const seen = /* @__PURE__ */ new Set();
1004
- destinations.forEach((destination, index) => {
1005
- if (destination.name === DEFAULT_DESTINATION_NAME) {
1006
- context.addIssue({
1007
- code: "custom",
1008
- path: [index, "name"],
1009
- message: 'the name "default" is reserved for exporter.endpoint and the OTEL_EXPORTER_OTLP_* variables'
1010
- });
1011
- }
1012
- if (seen.has(destination.name)) {
1013
- context.addIssue({
1014
- code: "custom",
1015
- path: [index, "name"],
1016
- message: `duplicate destination name "${destination.name}"`
1017
- });
1018
- }
1019
- seen.add(destination.name);
1020
- });
1021
- });
1022
- var spoolPolicySchema = z7.strictObject({
1023
- /** Total bytes of queued batches. Default 16 MiB. */
1024
- maxBytes: z7.number().int().min(1024).max(1073741824),
1025
- /** A batch older than this is dropped instead of sent. Default 72 hours. */
1026
- maxAgeMillis: z7.number().int().min(1e3).max(30 * 24 * 60 * 60 * 1e3),
1027
- /** Number of queued batches. Default 500. */
1028
- maxBatches: z7.number().int().min(1).max(65536)
1029
- });
1030
- var DEFAULT_SPOOL_POLICY = Object.freeze({
1031
- maxBytes: 16 * 1024 * 1024,
1032
- maxAgeMillis: 72 * 60 * 60 * 1e3,
1033
- maxBatches: 500
1034
- });
1035
-
1036
- // src/config/resource-attributes.ts
1037
- import { z as z8 } from "zod";
1038
- var MAX_RESOURCE_ATTRIBUTES = 64;
1039
- var MAX_RESOURCE_ATTRIBUTE_KEY_LENGTH = 255;
1040
- var MAX_RESOURCE_ATTRIBUTE_VALUE_LENGTH = 2048;
1041
- var RESOURCE_ATTRIBUTE_KEY_PATTERN = /^[A-Za-z][A-Za-z0-9_./-]*$/;
1042
- var RESERVED_RESOURCE_ATTRIBUTE_KEYS = Object.freeze([
1043
- "service.name",
1044
- "service.namespace"
1045
- ]);
1046
- var isReservedResourceAttributeKey = (key) => RESERVED_RESOURCE_ATTRIBUTE_KEYS.includes(key.toLowerCase());
1047
- var SECRET_KEY_MATCHERS = Object.freeze(
1048
- DEFAULT_SECRET_KEY_PATTERNS.flatMap((source) => {
1049
- try {
1050
- return [new RegExp(source, "i")];
1051
- } catch {
1052
- return [];
1053
- }
1054
- })
1055
- );
1056
- var isSecretResourceAttributeKey = (key) => SECRET_KEY_MATCHERS.some((pattern) => pattern.test(key));
1057
- var RESOURCE_ATTRIBUTE_KEY_REJECTION_DETAIL = Object.freeze({
1058
- empty: "resource attribute key is empty",
1059
- "too-long": `resource attribute key exceeds ${String(MAX_RESOURCE_ATTRIBUTE_KEY_LENGTH)} characters`,
1060
- malformed: "resource attribute key must start with a letter and use only letters, digits, and `_`, `.`, `-`, `/`",
1061
- reserved: "service.name and service.namespace are exporter policy (--service-name / OTEL_HOOK_SERVICE_NAME), not resource attributes",
1062
- "secret-like": "resource attribute key matches a secret-name pattern, so it is never exported"
1063
- });
1064
- var checkResourceAttributeKey = (key) => {
1065
- if (key.length === 0) {
1066
- return "empty";
1067
- }
1068
- if (key.length > MAX_RESOURCE_ATTRIBUTE_KEY_LENGTH) {
1069
- return "too-long";
1070
- }
1071
- if (!RESOURCE_ATTRIBUTE_KEY_PATTERN.test(key)) {
1072
- return "malformed";
1073
- }
1074
- if (isReservedResourceAttributeKey(key)) {
1075
- return "reserved";
1076
- }
1077
- if (isSecretResourceAttributeKey(key)) {
1078
- return "secret-like";
1079
- }
1080
- return void 0;
1081
- };
1082
- var resourceAttributeValueSchema = z8.union([
1083
- z8.string().max(MAX_RESOURCE_ATTRIBUTE_VALUE_LENGTH),
1084
- z8.number().finite(),
1085
- z8.boolean()
1086
- ]);
1087
- var resourceAttributesSchema = z8.record(z8.string(), resourceAttributeValueSchema).superRefine((value, ctx) => {
1088
- const keys = Object.keys(value);
1089
- if (keys.length > MAX_RESOURCE_ATTRIBUTES) {
1090
- ctx.addIssue({
1091
- code: "custom",
1092
- message: `at most ${String(MAX_RESOURCE_ATTRIBUTES)} resource attributes are accepted`
1093
- });
1094
- }
1095
- for (const key of keys) {
1096
- const rejection = checkResourceAttributeKey(key);
1097
- if (rejection !== void 0) {
1098
- ctx.addIssue({
1099
- code: "custom",
1100
- path: [key],
1101
- message: RESOURCE_ATTRIBUTE_KEY_REJECTION_DETAIL[rejection]
1102
- });
1103
- }
1104
- }
1105
- }).readonly();
1106
- var EMPTY_RESOURCE_ATTRIBUTES = Object.freeze({});
1107
-
1108
- // src/config/schema.ts
1109
- var logsPolicySchema = z9.strictObject({
1110
- enabled: z9.boolean(),
1111
- /**
1112
- * Full URL for the logs signal.
1113
- *
1114
- * Absent, it is derived from `endpoint`: a trailing `/v1/traces` becomes
1115
- * `/v1/logs`, and an endpoint with no signal path has `/v1/logs` appended.
1116
- */
1117
- endpoint: z9.string().url().max(2048).optional(),
1118
- includeContent: z9.boolean(),
1119
- maxBatchSize: z9.number().int().min(1).max(4096)
1120
- });
1121
- var DEFAULT_LOGS_POLICY = Object.freeze({
1122
- enabled: false,
1123
- includeContent: false,
1124
- maxBatchSize: 128
1125
- });
1126
- var exporterPolicySchema = z9.strictObject({
1127
- enabled: z9.boolean(),
1128
- protocol: z9.enum(["http/protobuf", "http/json", "none"]),
1129
- endpoint: z9.string().url().max(2048).optional(),
1130
- /**
1131
- * Header names only. Values are supplied separately at construction time and
1132
- * are never part of a resolved-config snapshot, which is logged and exported.
1133
- */
1134
- headerNames: z9.array(nonEmptyStringSchema).max(32).readonly(),
1135
- timeoutMillis: z9.number().int().min(1).max(6e5),
1136
- maxBatchSize: z9.number().int().min(1).max(4096),
1137
- maxQueueSize: z9.number().int().min(1).max(65536),
1138
- maxRetryAttempts: z9.number().int().min(0).max(10),
1139
- serviceName: nonEmptyStringSchema,
1140
- serviceNamespace: nonEmptyStringSchema.optional(),
1141
- /**
1142
- * Custom attributes merged into the exported OTLP Resource.
1143
- *
1144
- * Bounded and validated, and refusing `service.name`/`service.namespace`,
1145
- * which are the two fields above. Distinct from an invocation's
1146
- * `consumerAttributes`: this describes the emitting deployment, carries no
1147
- * identity, and is the same for every span this process exports.
1148
- */
1149
- resourceAttributes: resourceAttributesSchema,
1150
- /**
1151
- * The logs signal. Nested under the exporter because it shares the endpoint,
1152
- * headers, timeout, protocol, service identity, and resource attributes above —
1153
- * a second top-level section would invite two of each to drift apart.
1154
- */
1155
- logs: logsPolicySchema,
1156
- /**
1157
- * Additional OTLP destinations, each sent every batch in parallel.
1158
- *
1159
- * Absent (the default), the exporter has exactly one destination — the
1160
- * single-endpoint settings above, named `default` — and behaves exactly as it
1161
- * did before this list existed. See `destinations.ts`.
1162
- *
1163
- * Merged as one leaf: a higher layer that sets the list replaces it whole,
1164
- * because "the union of two partial lists" has no answer an operator could
1165
- * predict.
1166
- */
1167
- destinations: exportDestinationsSchema.optional(),
1168
- /**
1169
- * Per-destination retry spool bounds, each optional and merged per leaf; any
1170
- * bound left unset takes its value from `DEFAULT_SPOOL_POLICY`.
1171
- */
1172
- spool: spoolPolicySchema.partial().optional()
1173
- });
1174
- var detectionPolicySchema = z9.strictObject({
1175
- /** Detections below this confidence resolve to the unknown provider. */
1176
- minimumConfidence: detectionConfidenceSchema,
1177
- /** When false, an ambiguous detection is an error rather than unknown. */
1178
- allowAmbiguousFallback: z9.boolean(),
1179
- /** Optional allow-list of provider ids; empty means "any registered". */
1180
- allowedProviderIds: z9.array(nonEmptyStringSchema).max(32).readonly()
1181
- });
1182
- var diagnosticsPolicySchema = z9.strictObject({
1183
- logLevel: z9.enum(["silent", "error", "warn", "info", "debug"]),
1184
- /** Emit `error.raised` events for contained failures. */
1185
- emitErrorEvents: z9.boolean()
1186
- });
1187
- var otelHookConfigSchema = z9.strictObject({
1188
- exporter: exporterPolicySchema,
1189
- privacy: privacyPolicySchema,
1190
- detection: detectionPolicySchema,
1191
- diagnostics: diagnosticsPolicySchema
1192
- });
1193
- var otelHookConfigPatchSchema = z9.strictObject({
1194
- // `logs` is unwrapped and re-partialled for the same reason `privacy.limits` is:
1195
- // merging happens per leaf, so a layer must be able to set `logs.enabled` alone
1196
- // without also restating the endpoint and the batch size.
1197
- exporter: exporterPolicySchema.omit({ logs: true, spool: true }).partial().extend({
1198
- logs: logsPolicySchema.partial().optional(),
1199
- spool: spoolPolicySchema.partial().optional()
1200
- }).optional(),
1201
- privacy: privacyPolicySchema.omit({ limits: true }).partial().extend({ limits: privacyPolicySchema.shape.limits.partial().optional() }).optional(),
1202
- detection: detectionPolicySchema.partial().optional(),
1203
- diagnostics: diagnosticsPolicySchema.partial().optional()
1204
- });
1205
- var DEFAULT_EXPORTER_POLICY = Object.freeze({
1206
- enabled: true,
1207
- protocol: "http/protobuf",
1208
- headerNames: Object.freeze([]),
1209
- timeoutMillis: 1e4,
1210
- maxBatchSize: 128,
1211
- maxQueueSize: 2048,
1212
- maxRetryAttempts: 2,
1213
- serviceName: "coding-agent",
1214
- resourceAttributes: EMPTY_RESOURCE_ATTRIBUTES,
1215
- logs: DEFAULT_LOGS_POLICY
1216
- });
1217
- var DEFAULT_DETECTION_POLICY = Object.freeze({
1218
- minimumConfidence: "strong",
1219
- allowAmbiguousFallback: true,
1220
- allowedProviderIds: Object.freeze([])
1221
- });
1222
- var DEFAULT_DIAGNOSTICS_POLICY = Object.freeze({
1223
- logLevel: "warn",
1224
- emitErrorEvents: true
1225
- });
1226
- var DEFAULT_CONFIG = Object.freeze({
1227
- exporter: DEFAULT_EXPORTER_POLICY,
1228
- privacy: DEFAULT_PRIVACY_POLICY,
1229
- detection: DEFAULT_DETECTION_POLICY,
1230
- diagnostics: DEFAULT_DIAGNOSTICS_POLICY
1231
- });
1232
-
1233
- // src/model/content.ts
1234
- import { z as z10 } from "zod";
1235
- var contentKindSchema = z10.enum([
1236
- "prompt",
1237
- "response",
1238
- "reasoning",
1239
- "tool-input",
1240
- "tool-output",
1241
- "error-message",
1242
- "system-instruction",
1243
- "attachment"
1244
- ]);
1245
- var contentRoleSchema = z10.enum(["user", "assistant", "system", "tool", "unknown"]);
1246
- var contentDisclosureSchema = z10.enum(["omitted", "masked", "redacted", "raw"]);
1247
- var CONTENT_HASH_PATTERN = /^sha256:[0-9a-f]{64}$/;
1248
- var contentFactSchema = z10.strictObject({
1249
- kind: contentKindSchema,
1250
- role: contentRoleSchema.optional(),
1251
- /** Unicode code point count of the original content. */
1252
- characterLength: z10.number().int().min(0),
1253
- /** UTF-8 byte length of the original content. */
1254
- byteLength: z10.number().int().min(0),
1255
- /** Stable salted digest of the original content. */
1256
- contentHash: z10.string().regex(CONTENT_HASH_PATTERN),
1257
- disclosure: contentDisclosureSchema,
1258
- /** Disclosed text, bounded by the privacy policy. Absent when omitted. */
1259
- text: z10.string().optional(),
1260
- /** True when `text` was cut short by the configured string bound. */
1261
- truncated: z10.boolean(),
1262
- /** Number of secret-looking spans replaced while producing `text`. */
1263
- secretsRedacted: z10.number().int().min(0),
1264
- /** Optional non-sensitive label, e.g. a MIME type or tool name. */
1265
- label: nonEmptyStringSchema.optional()
1266
- });
1267
- var contentFactsSchema = z10.array(contentFactSchema).max(64);
1268
- var isContentFactConsistent = (fact) => fact.disclosure === "omitted" ? fact.text === void 0 : fact.text !== void 0;
1269
- var isUnavailableContentFact = (fact) => fact.disclosure === "omitted" && fact.text === void 0 && fact.characterLength === 0 && fact.byteLength === 0;
1270
-
1271
- // src/model/identity.ts
1272
- import { z as z11 } from "zod";
1273
- var workspaceKeySourceSchema = z11.enum([
1274
- "git-remote",
1275
- "git-root",
1276
- "working-directory",
1277
- "explicit",
1278
- "unknown"
1279
- ]);
1280
- var workspaceIdentitySchema = z11.strictObject({
1281
- workspaceId: workspaceIdSchema,
1282
- keySource: workspaceKeySourceSchema,
1283
- /** Repository name only; never an owner path or URL with credentials. */
1284
- repositoryName: nonEmptyStringSchema.optional(),
1285
- vcsBranchName: nonEmptyStringSchema.optional(),
1286
- /** Opaque handle for the checked-out revision. */
1287
- vcsRevisionId: nonEmptyStringSchema.optional()
1288
- }).readonly();
1289
- var UNKNOWN_WORKSPACE_ID = "unknown:0000000000000000";
1290
- var unknownWorkspaceIdentity = () => workspaceIdentitySchema.parse({
1291
- workspaceId: UNKNOWN_WORKSPACE_ID,
1292
- keySource: "unknown"
1293
- });
1294
- var sourceProvenanceSchema = z11.strictObject({
1295
- providerId: resolvedProviderIdSchema,
1296
- providerVersion: nonEmptyStringSchema.optional(),
1297
- adapterId: nonEmptyStringSchema,
1298
- adapterVersion: nonEmptyStringSchema,
1299
- detectionConfidence: detectionConfidenceSchema,
1300
- /** The provider's own name for the source event, e.g. a hook event name. */
1301
- sourceEventName: nonEmptyStringSchema.optional(),
1302
- transport: sourceTransportSchema
1303
- }).readonly();
1304
- var consumerAttributesSchema = attributesSchema.readonly();
1305
- var invocationIdentitySchema = z11.strictObject({
1306
- invocationId: invocationIdSchema,
1307
- sessionId: sessionIdSchema,
1308
- /** Set when this invocation runs beneath another agent invocation. */
1309
- parentInvocationId: invocationIdSchema.optional(),
1310
- /** Root of the session tree when the provider exposes one. */
1311
- rootSessionId: sessionIdSchema.optional(),
1312
- /** Stable handle for the agent process/instance, when available. */
1313
- agentInstanceId: nonEmptyStringSchema.optional(),
1314
- provenance: sourceProvenanceSchema,
1315
- workspace: workspaceIdentitySchema,
1316
- startedAt: epochMillisSchema,
1317
- consumerAttributes: consumerAttributesSchema
1318
- }).readonly();
1319
- var identityClaimFieldsSchema = z11.strictObject({
1320
- invocationId: invocationIdSchema.optional(),
1321
- sessionId: sessionIdSchema.optional(),
1322
- parentInvocationId: invocationIdSchema.optional(),
1323
- rootSessionId: sessionIdSchema.optional(),
1324
- agentInstanceId: nonEmptyStringSchema.optional(),
1325
- workspace: workspaceIdentitySchema.optional(),
1326
- startedAt: epochMillisSchema.optional()
1327
- });
1328
- var identityClaimSchema = z11.strictObject({
1329
- /** Non-sensitive label, e.g. `adapter:acme-cli` or `env:OTEL_HOOK_SESSION_ID`. */
1330
- source: nonEmptyStringSchema,
1331
- confidence: detectionConfidenceSchema,
1332
- fields: identityClaimFieldsSchema
1333
- });
1334
- var CLAIM_FIELDS = [
1335
- "invocationId",
1336
- "sessionId",
1337
- "parentInvocationId",
1338
- "rootSessionId",
1339
- "agentInstanceId",
1340
- "workspace",
1341
- "startedAt"
1342
- ];
1343
- var renderClaimValue = (value) => {
1344
- if (typeof value === "string") {
1345
- return value;
1346
- }
1347
- if (typeof value === "number" || typeof value === "boolean") {
1348
- return String(value);
1349
- }
1350
- if (value !== null && typeof value === "object" && "workspaceId" in value) {
1351
- const { workspaceId } = value;
1352
- return typeof workspaceId === "string" ? workspaceId : "<workspace>";
1353
- }
1354
- return "<opaque>";
1355
- };
1356
- var resolveInvocationIdentity = (input) => {
1357
- const parsedClaims = [];
1358
- const issues = [];
1359
- for (const [index, claim] of input.claims.entries()) {
1360
- const parsed2 = identityClaimSchema.safeParse(claim);
1361
- if (parsed2.success) {
1362
- parsedClaims.push(parsed2.data);
1363
- } else {
1364
- issues.push(
1365
- `claim[${index}]: ${parsed2.error.issues.map((issue) => `${issue.path.join(".") || "<root>"} ${issue.message}`).join(", ")}`
1366
- );
1367
- }
1368
- }
1369
- if (issues.length > 0) {
1370
- return { status: "invalid", issues };
1371
- }
1372
- const conflicts = [];
1373
- const selected = {};
1374
- for (const field of CLAIM_FIELDS) {
1375
- const contributors = parsedClaims.filter((claim) => claim.fields[field] !== void 0);
1376
- if (contributors.length === 0) {
1377
- continue;
1378
- }
1379
- const bestRank = Math.max(
1380
- ...contributors.map((claim) => DETECTION_CONFIDENCE_RANK[claim.confidence])
1381
- );
1382
- const best = contributors.filter(
1383
- (claim) => DETECTION_CONFIDENCE_RANK[claim.confidence] === bestRank
1384
- );
1385
- const rendered = /* @__PURE__ */ new Map();
1386
- for (const claim of best) {
1387
- const key = JSON.stringify(claim.fields[field]);
1388
- const sources = rendered.get(key) ?? [];
1389
- sources.push(claim.source);
1390
- rendered.set(key, sources);
1465
+ // src/config/destinations.ts
1466
+ var DEFAULT_DESTINATION_NAME = "default";
1467
+ var DESTINATION_NAME_PATTERN = /^[a-z0-9][a-z0-9_-]{0,62}$/;
1468
+ var MAX_EXPORT_DESTINATIONS = 16;
1469
+ var MAX_DESTINATION_HEADERS = MAX_OTLP_HEADERS;
1470
+ var HEADER_ENV_REFERENCE_PREFIX = "env:";
1471
+ var HEADER_NAME_PATTERN = /^[A-Za-z0-9!#$%&'*+.^_`|~-]{1,128}$/;
1472
+ var ENV_VARIABLE_NAME_PATTERN = /^[A-Za-z_][A-Za-z0-9_]{0,127}$/;
1473
+ var MAX_HEADER_VALUE_LENGTH = 8192;
1474
+ var exportSignalSchema = z13.enum(["traces", "logs", "metrics"]);
1475
+ var headerValueSchema = z13.string().min(1).max(MAX_HEADER_VALUE_LENGTH).refine(
1476
+ (value) => !isUnsafeHeaderValue(value),
1477
+ "header values may not contain line breaks, control characters, or characters beyond Latin-1"
1478
+ ).refine(
1479
+ (value) => !value.startsWith(HEADER_ENV_REFERENCE_PREFIX) || ENV_VARIABLE_NAME_PATTERN.test(value.slice(HEADER_ENV_REFERENCE_PREFIX.length)),
1480
+ "an env: header reference must name an environment variable, e.g. env:COLLECTOR_TOKEN"
1481
+ );
1482
+ var endpointSchema = z13.string().url().max(2048);
1483
+ var exportDestinationSchema = z13.strictObject({
1484
+ /** Unique, lowercase, filesystem-safe. `default` is reserved for the single-endpoint settings. */
1485
+ name: z13.string().regex(DESTINATION_NAME_PATTERN, "destination names are lowercase letters, digits, _ and -"),
1486
+ /** Default true. A disabled destination is neither sent to nor drained. */
1487
+ enabled: z13.boolean().optional(),
1488
+ /**
1489
+ * Traces URL, with the same meaning as `exporter.endpoint`: the logs URL is
1490
+ * derived from it (`/v1/traces` becomes `/v1/logs`) unless `logsEndpoint` is set.
1491
+ */
1492
+ endpoint: endpointSchema.optional(),
1493
+ /** Per-signal override of `endpoint` for traces. */
1494
+ tracesEndpoint: endpointSchema.optional(),
1495
+ /** Per-signal override of the derived logs URL. */
1496
+ logsEndpoint: endpointSchema.optional(),
1497
+ /** Per-signal override of the derived metrics URL (`/v1/traces` becomes `/v1/metrics`). */
1498
+ metricsEndpoint: endpointSchema.optional(),
1499
+ /** Defaults to `exporter.protocol`. */
1500
+ protocol: z13.enum(["http/protobuf", "http/json", "none"]).optional(),
1501
+ /**
1502
+ * Header name to value. A value of the form `env:NAME` is read from that
1503
+ * environment variable at send time, so a credential never has to be written
1504
+ * into the file. Values never appear in a snapshot, a diagnostic, or `doctor`.
1505
+ */
1506
+ headers: z13.record(z13.string().regex(HEADER_NAME_PATTERN, "not a valid header name"), headerValueSchema).refine(
1507
+ (headers) => Object.keys(headers).length <= MAX_DESTINATION_HEADERS,
1508
+ `at most ${String(MAX_DESTINATION_HEADERS)} headers per destination`
1509
+ ).optional(),
1510
+ /**
1511
+ * Which signals this destination receives. Default: traces and logs. The logs
1512
+ * signal is still governed by `exporter.logs.enabled`, which stays the one
1513
+ * opt-in for content-bearing records leaving the host. `metrics` is never on by
1514
+ * default: a destination receives hook-derived metrics only when it lists them.
1515
+ */
1516
+ signals: z13.array(exportSignalSchema).min(1).max(3).readonly().optional()
1517
+ }).refine(
1518
+ (destination) => destination.endpoint !== void 0 || destination.tracesEndpoint !== void 0 || destination.logsEndpoint !== void 0 || destination.metricsEndpoint !== void 0,
1519
+ "a destination needs an endpoint, or a tracesEndpoint / logsEndpoint / metricsEndpoint"
1520
+ );
1521
+ var DEFAULT_DESTINATION_SIGNALS = Object.freeze(["traces", "logs"]);
1522
+ var exportDestinationsSchema = z13.array(exportDestinationSchema).max(MAX_EXPORT_DESTINATIONS).readonly().superRefine((destinations, context) => {
1523
+ const seen = /* @__PURE__ */ new Set();
1524
+ destinations.forEach((destination, index) => {
1525
+ if (destination.name === DEFAULT_DESTINATION_NAME) {
1526
+ context.addIssue({
1527
+ code: "custom",
1528
+ path: [index, "name"],
1529
+ message: 'the name "default" is reserved for exporter.endpoint and the OTEL_EXPORTER_OTLP_* variables'
1530
+ });
1391
1531
  }
1392
- if (rendered.size > 1) {
1393
- const [firstBest] = best;
1394
- conflicts.push({
1395
- field,
1396
- confidence: firstBest?.confidence ?? "none",
1397
- values: best.map((claim) => renderClaimValue(claim.fields[field])),
1398
- sources: best.map((claim) => claim.source)
1532
+ if (seen.has(destination.name)) {
1533
+ context.addIssue({
1534
+ code: "custom",
1535
+ path: [index, "name"],
1536
+ message: `duplicate destination name "${destination.name}"`
1399
1537
  });
1400
- continue;
1401
1538
  }
1402
- const [winner] = best;
1403
- if (winner !== void 0) {
1404
- selected[field] = winner.fields[field];
1539
+ seen.add(destination.name);
1540
+ });
1541
+ });
1542
+ var spoolPolicySchema = z13.strictObject({
1543
+ /** Total bytes of queued batches. Default 16 MiB. */
1544
+ maxBytes: z13.number().int().min(1024).max(1073741824),
1545
+ /** A batch older than this is dropped instead of sent. Default 72 hours. */
1546
+ maxAgeMillis: z13.number().int().min(1e3).max(30 * 24 * 60 * 60 * 1e3),
1547
+ /** Number of queued batches. Default 500. */
1548
+ maxBatches: z13.number().int().min(1).max(65536)
1549
+ });
1550
+ var DEFAULT_SPOOL_POLICY = Object.freeze({
1551
+ maxBytes: 16 * 1024 * 1024,
1552
+ maxAgeMillis: 72 * 60 * 60 * 1e3,
1553
+ maxBatches: 500
1554
+ });
1555
+
1556
+ // src/config/resource-attributes.ts
1557
+ import { z as z14 } from "zod";
1558
+ var MAX_RESOURCE_ATTRIBUTES = 64;
1559
+ var MAX_RESOURCE_ATTRIBUTE_KEY_LENGTH = 255;
1560
+ var MAX_RESOURCE_ATTRIBUTE_VALUE_LENGTH = 2048;
1561
+ var RESOURCE_ATTRIBUTE_KEY_PATTERN = /^[A-Za-z][A-Za-z0-9_./-]*$/;
1562
+ var RESERVED_RESOURCE_ATTRIBUTE_KEYS = Object.freeze([
1563
+ "service.name",
1564
+ "service.namespace"
1565
+ ]);
1566
+ var isReservedResourceAttributeKey = (key) => RESERVED_RESOURCE_ATTRIBUTE_KEYS.includes(key.toLowerCase());
1567
+ var SECRET_KEY_MATCHERS = Object.freeze(
1568
+ DEFAULT_SECRET_KEY_PATTERNS.flatMap((source) => {
1569
+ try {
1570
+ return [new RegExp(source, "i")];
1571
+ } catch {
1572
+ return [];
1405
1573
  }
1574
+ })
1575
+ );
1576
+ var isSecretResourceAttributeKey = (key) => SECRET_KEY_MATCHERS.some((pattern) => pattern.test(key));
1577
+ var RESOURCE_ATTRIBUTE_KEY_REJECTION_DETAIL = Object.freeze({
1578
+ empty: "resource attribute key is empty",
1579
+ "too-long": `resource attribute key exceeds ${String(MAX_RESOURCE_ATTRIBUTE_KEY_LENGTH)} characters`,
1580
+ malformed: "resource attribute key must start with a letter and use only letters, digits, and `_`, `.`, `-`, `/`",
1581
+ reserved: "service.name and service.namespace are exporter policy (--service-name / OTEL_HOOK_SERVICE_NAME), not resource attributes",
1582
+ "secret-like": "resource attribute key matches a secret-name pattern, so it is never exported"
1583
+ });
1584
+ var checkResourceAttributeKey = (key) => {
1585
+ if (key.length === 0) {
1586
+ return "empty";
1406
1587
  }
1407
- if (conflicts.length > 0) {
1408
- return { status: "conflict", conflicts };
1409
- }
1410
- const missing = [];
1411
- if (selected.invocationId === void 0) {
1412
- missing.push("invocationId");
1413
- }
1414
- if (selected.sessionId === void 0) {
1415
- missing.push("sessionId");
1588
+ if (key.length > MAX_RESOURCE_ATTRIBUTE_KEY_LENGTH) {
1589
+ return "too-long";
1416
1590
  }
1417
- if (missing.length > 0) {
1418
- return { status: "incomplete", missing };
1591
+ if (!RESOURCE_ATTRIBUTE_KEY_PATTERN.test(key)) {
1592
+ return "malformed";
1419
1593
  }
1420
- const startedAt = selected.startedAt ?? input.fallback?.startedAt;
1421
- if (startedAt === void 0) {
1422
- return { status: "incomplete", missing: ["startedAt"] };
1594
+ if (isReservedResourceAttributeKey(key)) {
1595
+ return "reserved";
1423
1596
  }
1424
- const workspace = selected.workspace ?? input.fallback?.workspace ?? unknownWorkspaceIdentity();
1425
- const candidate = {
1426
- invocationId: selected.invocationId,
1427
- sessionId: selected.sessionId,
1428
- ...selected.parentInvocationId === void 0 ? {} : { parentInvocationId: selected.parentInvocationId },
1429
- ...selected.rootSessionId === void 0 ? {} : { rootSessionId: selected.rootSessionId },
1430
- ...selected.agentInstanceId === void 0 ? {} : { agentInstanceId: selected.agentInstanceId },
1431
- provenance: input.provenance,
1432
- workspace,
1433
- startedAt,
1434
- consumerAttributes: input.consumerAttributes ?? {}
1435
- };
1436
- const parsed = invocationIdentitySchema.safeParse(candidate);
1437
- if (!parsed.success) {
1438
- return {
1439
- status: "invalid",
1440
- issues: parsed.error.issues.map(
1441
- (issue) => `${issue.path.join(".") || "<root>"}: ${issue.message}`
1442
- )
1443
- };
1597
+ if (isSecretResourceAttributeKey(key)) {
1598
+ return "secret-like";
1444
1599
  }
1445
- return { status: "resolved", identity: parsed.data };
1600
+ return void 0;
1446
1601
  };
1447
-
1448
- // src/model/version.ts
1449
- import { z as z12 } from "zod";
1450
- var CANONICAL_SCHEMA_VERSION = 1;
1451
- var canonicalSchemaVersionSchema = z12.literal(CANONICAL_SCHEMA_VERSION);
1452
-
1453
- // src/privacy/service.ts
1454
- import { createHash as createHash2 } from "crypto";
1455
-
1456
- // src/model/extensions.ts
1457
- import { z as z13 } from "zod";
1458
- var EXTENSION_KEY_PATTERN = /^[a-z][a-z0-9]*(?:[-_][a-z0-9]+)*(?:\.[a-z][a-z0-9]*(?:[-_][a-z0-9]+)*)+$/;
1459
- var RESERVED_EXTENSION_NAMESPACES = Object.freeze([
1460
- "otelhook",
1461
- "otel",
1462
- "telemetry"
1602
+ var resourceAttributeValueSchema = z14.union([
1603
+ z14.string().max(MAX_RESOURCE_ATTRIBUTE_VALUE_LENGTH),
1604
+ z14.number().finite(),
1605
+ z14.boolean()
1463
1606
  ]);
1464
- var MAX_EXTENSION_ENTRIES = 64;
1465
- var extensionKeyNamespace = (key) => key.slice(0, key.indexOf("."));
1466
- var isReservedExtensionNamespace = (key) => RESERVED_EXTENSION_NAMESPACES.includes(extensionKeyNamespace(key));
1467
- var isValidExtensionKey = (key) => EXTENSION_KEY_PATTERN.test(key) && !isReservedExtensionNamespace(key);
1468
- var extensionsSchema = z13.record(z13.string(), attributeValueSchema).check((ctx) => {
1469
- const keys = Object.keys(ctx.value);
1470
- if (keys.length > MAX_EXTENSION_ENTRIES) {
1471
- ctx.issues.push({
1607
+ var resourceAttributesSchema = z14.record(z14.string(), resourceAttributeValueSchema).superRefine((value, ctx) => {
1608
+ const keys = Object.keys(value);
1609
+ if (keys.length > MAX_RESOURCE_ATTRIBUTES) {
1610
+ ctx.addIssue({
1472
1611
  code: "custom",
1473
- input: ctx.value,
1474
- message: `extensions may contain at most ${MAX_EXTENSION_ENTRIES} entries`
1612
+ message: `at most ${String(MAX_RESOURCE_ATTRIBUTES)} resource attributes are accepted`
1475
1613
  });
1476
1614
  }
1477
1615
  for (const key of keys) {
1478
- if (!EXTENSION_KEY_PATTERN.test(key)) {
1479
- ctx.issues.push({
1480
- code: "custom",
1481
- input: ctx.value,
1482
- path: [key],
1483
- message: `extension key ${JSON.stringify(key)} must be namespaced, e.g. "acme.tier"`
1484
- });
1485
- continue;
1486
- }
1487
- if (isReservedExtensionNamespace(key)) {
1488
- ctx.issues.push({
1616
+ const rejection = checkResourceAttributeKey(key);
1617
+ if (rejection !== void 0) {
1618
+ ctx.addIssue({
1489
1619
  code: "custom",
1490
- input: ctx.value,
1491
1620
  path: [key],
1492
- message: `extension namespace ${JSON.stringify(extensionKeyNamespace(key))} is reserved`
1621
+ message: RESOURCE_ATTRIBUTE_KEY_REJECTION_DETAIL[rejection]
1493
1622
  });
1494
1623
  }
1495
1624
  }
1625
+ }).readonly();
1626
+ var EMPTY_RESOURCE_ATTRIBUTES = Object.freeze({});
1627
+
1628
+ // src/config/schema.ts
1629
+ var logsPolicySchema = z15.strictObject({
1630
+ enabled: z15.boolean(),
1631
+ /**
1632
+ * Full URL for the logs signal.
1633
+ *
1634
+ * Absent, it is derived from `endpoint`: a trailing `/v1/traces` becomes
1635
+ * `/v1/logs`, and an endpoint with no signal path has `/v1/logs` appended.
1636
+ */
1637
+ endpoint: z15.string().url().max(2048).optional(),
1638
+ includeContent: z15.boolean(),
1639
+ maxBatchSize: z15.number().int().min(1).max(4096)
1640
+ });
1641
+ var DEFAULT_LOGS_POLICY = Object.freeze({
1642
+ enabled: false,
1643
+ includeContent: false,
1644
+ maxBatchSize: 128
1645
+ });
1646
+ var metricsPolicySchema = z15.strictObject({
1647
+ enabled: z15.boolean(),
1648
+ /** Full URL. Absent, derived from `endpoint` (`/v1/traces` becomes `/v1/metrics`). */
1649
+ endpoint: z15.string().url().max(2048).optional(),
1650
+ temporality: z15.enum(["cumulative", "delta"]),
1651
+ includeSessionId: z15.boolean()
1652
+ });
1653
+ var DEFAULT_METRICS_POLICY = Object.freeze({
1654
+ enabled: false,
1655
+ temporality: "cumulative",
1656
+ includeSessionId: true
1657
+ });
1658
+ var exporterPolicySchema = z15.strictObject({
1659
+ enabled: z15.boolean(),
1660
+ protocol: z15.enum(["http/protobuf", "http/json", "none"]),
1661
+ endpoint: z15.string().url().max(2048).optional(),
1662
+ /**
1663
+ * Header names only. Values are supplied separately at construction time and
1664
+ * are never part of a resolved-config snapshot, which is logged and exported.
1665
+ */
1666
+ headerNames: z15.array(nonEmptyStringSchema).max(32).readonly(),
1667
+ timeoutMillis: z15.number().int().min(1).max(6e5),
1668
+ maxBatchSize: z15.number().int().min(1).max(4096),
1669
+ maxQueueSize: z15.number().int().min(1).max(65536),
1670
+ maxRetryAttempts: z15.number().int().min(0).max(10),
1671
+ serviceName: nonEmptyStringSchema,
1672
+ serviceNamespace: nonEmptyStringSchema.optional(),
1673
+ /**
1674
+ * Custom attributes merged into the exported OTLP Resource.
1675
+ *
1676
+ * Bounded and validated, and refusing `service.name`/`service.namespace`,
1677
+ * which are the two fields above. Distinct from an invocation's
1678
+ * `consumerAttributes`: this describes the emitting deployment, carries no
1679
+ * identity, and is the same for every span this process exports.
1680
+ */
1681
+ resourceAttributes: resourceAttributesSchema,
1682
+ /**
1683
+ * The logs signal. Nested under the exporter because it shares the endpoint,
1684
+ * headers, timeout, protocol, service identity, and resource attributes above —
1685
+ * a second top-level section would invite two of each to drift apart.
1686
+ */
1687
+ logs: logsPolicySchema,
1688
+ /**
1689
+ * Hook-derived metrics. Optional so an `ExporterPolicy` built by hand before
1690
+ * metrics existed stays valid; absent reads as {@link DEFAULT_METRICS_POLICY}.
1691
+ */
1692
+ metrics: metricsPolicySchema.optional(),
1693
+ /**
1694
+ * Additional OTLP destinations, each sent every batch in parallel.
1695
+ *
1696
+ * Absent (the default), the exporter has exactly one destination — the
1697
+ * single-endpoint settings above, named `default` — and behaves exactly as it
1698
+ * did before this list existed. See `destinations.ts`.
1699
+ *
1700
+ * Merged as one leaf: a higher layer that sets the list replaces it whole,
1701
+ * because "the union of two partial lists" has no answer an operator could
1702
+ * predict.
1703
+ */
1704
+ destinations: exportDestinationsSchema.optional(),
1705
+ /**
1706
+ * Per-destination retry spool bounds, each optional and merged per leaf; any
1707
+ * bound left unset takes its value from `DEFAULT_SPOOL_POLICY`.
1708
+ */
1709
+ spool: spoolPolicySchema.partial().optional()
1710
+ });
1711
+ var detectionPolicySchema = z15.strictObject({
1712
+ /** Detections below this confidence resolve to the unknown provider. */
1713
+ minimumConfidence: detectionConfidenceSchema,
1714
+ /** When false, an ambiguous detection is an error rather than unknown. */
1715
+ allowAmbiguousFallback: z15.boolean(),
1716
+ /** Optional allow-list of provider ids; empty means "any registered". */
1717
+ allowedProviderIds: z15.array(nonEmptyStringSchema).max(32).readonly()
1718
+ });
1719
+ var diagnosticsPolicySchema = z15.strictObject({
1720
+ logLevel: z15.enum(["silent", "error", "warn", "info", "debug"]),
1721
+ /** Emit `error.raised` events for contained failures. */
1722
+ emitErrorEvents: z15.boolean()
1723
+ });
1724
+ var providersPolicySchema = z15.strictObject({
1725
+ claudeCode: z15.strictObject({
1726
+ readTranscriptUsage: z15.boolean()
1727
+ }).optional()
1728
+ });
1729
+ var otelHookConfigSchema = z15.strictObject({
1730
+ exporter: exporterPolicySchema,
1731
+ privacy: privacyPolicySchema,
1732
+ detection: detectionPolicySchema,
1733
+ diagnostics: diagnosticsPolicySchema,
1734
+ /** Optional so a hand-built configuration from before it existed stays valid. */
1735
+ providers: providersPolicySchema.optional()
1736
+ });
1737
+ var otelHookConfigPatchSchema = z15.strictObject({
1738
+ // `logs` is unwrapped and re-partialled for the same reason `privacy.limits` is:
1739
+ // merging happens per leaf, so a layer must be able to set `logs.enabled` alone
1740
+ // without also restating the endpoint and the batch size.
1741
+ exporter: exporterPolicySchema.omit({ logs: true, metrics: true, spool: true }).partial().extend({
1742
+ logs: logsPolicySchema.partial().optional(),
1743
+ metrics: metricsPolicySchema.partial().optional(),
1744
+ spool: spoolPolicySchema.partial().optional()
1745
+ }).optional(),
1746
+ privacy: privacyPolicySchema.omit({ limits: true }).partial().extend({ limits: privacyPolicySchema.shape.limits.partial().optional() }).optional(),
1747
+ detection: detectionPolicySchema.partial().optional(),
1748
+ diagnostics: diagnosticsPolicySchema.partial().optional(),
1749
+ providers: z15.strictObject({
1750
+ claudeCode: z15.strictObject({ readTranscriptUsage: z15.boolean() }).partial().optional()
1751
+ }).partial().optional()
1752
+ });
1753
+ var DEFAULT_EXPORTER_POLICY = Object.freeze({
1754
+ enabled: true,
1755
+ protocol: "http/protobuf",
1756
+ headerNames: Object.freeze([]),
1757
+ timeoutMillis: 1e4,
1758
+ maxBatchSize: 128,
1759
+ maxQueueSize: 2048,
1760
+ maxRetryAttempts: 2,
1761
+ serviceName: "coding-agent",
1762
+ resourceAttributes: EMPTY_RESOURCE_ATTRIBUTES,
1763
+ logs: DEFAULT_LOGS_POLICY,
1764
+ metrics: DEFAULT_METRICS_POLICY
1765
+ });
1766
+ var DEFAULT_DETECTION_POLICY = Object.freeze({
1767
+ minimumConfidence: "strong",
1768
+ allowAmbiguousFallback: true,
1769
+ allowedProviderIds: Object.freeze([])
1770
+ });
1771
+ var DEFAULT_DIAGNOSTICS_POLICY = Object.freeze({
1772
+ logLevel: "warn",
1773
+ emitErrorEvents: true
1774
+ });
1775
+ var DEFAULT_PROVIDERS_POLICY = Object.freeze({
1776
+ claudeCode: Object.freeze({ readTranscriptUsage: false })
1777
+ });
1778
+ var DEFAULT_CONFIG = Object.freeze({
1779
+ exporter: DEFAULT_EXPORTER_POLICY,
1780
+ privacy: DEFAULT_PRIVACY_POLICY,
1781
+ detection: DEFAULT_DETECTION_POLICY,
1782
+ diagnostics: DEFAULT_DIAGNOSTICS_POLICY,
1783
+ providers: DEFAULT_PROVIDERS_POLICY
1496
1784
  });
1497
- var EMPTY_EXTENSIONS = Object.freeze({});
1498
- var emptyExtensions = () => ({});
1499
1785
 
1500
1786
  // src/privacy/service.ts
1787
+ import { createHash as createHash2 } from "crypto";
1501
1788
  var compilePatterns = (sources, flags) => {
1502
1789
  const compiled = [];
1503
1790
  for (const source of sources) {
@@ -1841,210 +2128,6 @@ var createPrivacyService = (policyInput) => {
1841
2128
 
1842
2129
  // src/providers/adapter.ts
1843
2130
  import { z as z16 } from "zod";
1844
-
1845
- // src/model/events.ts
1846
- import { z as z15 } from "zod";
1847
-
1848
- // src/model/target.ts
1849
- import { z as z14 } from "zod";
1850
- var targetSourceSchema = z14.enum(["tool-path", "shell-cwd", "session-cwd"]);
1851
- var MAX_TARGET_HINT_PATHS = 8;
1852
- var MAX_TARGET_PATH_LENGTH = 4096;
1853
- var localPathSchema = z14.string().min(1).max(MAX_TARGET_PATH_LENGTH).refine((value) => !value.includes("\0"), "path must not contain NUL");
1854
- var targetHintSchema = z14.strictObject({
1855
- source: targetSourceSchema,
1856
- paths: z14.array(localPathSchema).min(1).max(MAX_TARGET_HINT_PATHS).readonly(),
1857
- /** Absolute directory that relative `paths` resolve against. */
1858
- baseDirectory: localPathSchema.optional()
1859
- }).readonly();
1860
- var worktreeKindSchema = z14.enum(["main", "linked"]);
1861
- var workspaceTargetSchema = z14.strictObject({
1862
- workspaceId: workspaceIdSchema,
1863
- /** Branch checked out in that worktree; absent on a detached HEAD. */
1864
- vcsBranchName: nonEmptyStringSchema.optional(),
1865
- source: targetSourceSchema,
1866
- /** `git-root` handle of the repository's main worktree; absent when there is none to name. */
1867
- repositoryId: workspaceIdSchema.optional(),
1868
- worktreeKind: worktreeKindSchema.optional()
1869
- }).readonly();
1870
- var SUBAGENT_ID_PATTERN = /^[A-Za-z0-9_.:@+=-]{1,256}$/;
1871
- var subagentIdSchema = z14.string().regex(SUBAGENT_ID_PATTERN);
1872
-
1873
- // src/model/events.ts
1874
- var modelDescriptorSchema = z15.strictObject({
1875
- modelId: nonEmptyStringSchema,
1876
- /** Vendor of the model, e.g. `anthropic`. Distinct from the agent provider. */
1877
- vendor: nonEmptyStringSchema.optional(),
1878
- family: nonEmptyStringSchema.optional()
1879
- });
1880
- var costFactsSchema = z15.strictObject({
1881
- /** ISO 4217 code. */
1882
- currency: z15.string().length(3),
1883
- amount: z15.number().min(0).finite(),
1884
- source: z15.enum(["provider-reported", "computed"])
1885
- });
1886
- var canonicalEventTypeSchema = z15.enum([
1887
- "session.start",
1888
- "session.end",
1889
- "prompt.submitted",
1890
- "generation.start",
1891
- "generation.end",
1892
- "tool.start",
1893
- "tool.end",
1894
- "subagent.start",
1895
- "subagent.end",
1896
- "compaction.performed",
1897
- "error.raised"
1898
- ]);
1899
- var CANONICAL_EVENT_TYPES = canonicalEventTypeSchema.options;
1900
- var outcomeSchema = z15.enum(["ok", "error", "cancelled", "timeout", "denied", "unknown"]);
1901
- var baseEventFields = {
1902
- schemaVersion: canonicalSchemaVersionSchema,
1903
- eventId: eventIdSchema,
1904
- invocationId: invocationIdSchema,
1905
- sessionId: sessionIdSchema,
1906
- /** Per-invocation ordering key. Stable across replays of the same input. */
1907
- sequence: sequenceNumberSchema,
1908
- occurredAt: epochMillisSchema,
1909
- provenance: sourceProvenanceSchema,
1910
- workspace: workspaceIdentitySchema,
1911
- /**
1912
- * The provider's own id for the subagent this event was emitted inside (e.g.
1913
- * Claude Code's `agent_id`). Absent for the top-level agent. Set by the event
1914
- * factory, never by hand.
1915
- */
1916
- subagentId: subagentIdSchema.optional(),
1917
- extensions: extensionsSchema.default(emptyExtensions)
1918
- };
1919
- var event = (shape) => z15.strictObject({ ...baseEventFields, ...shape });
1920
- var sessionStartEventSchema = event({
1921
- type: z15.literal("session.start"),
1922
- sessionKind: z15.enum(["interactive", "non-interactive", "unknown"]),
1923
- agentName: nonEmptyStringSchema.optional(),
1924
- agentVersion: nonEmptyStringSchema.optional(),
1925
- model: modelDescriptorSchema.optional(),
1926
- /** The git worktree the session runs in, resolved by the core (ADR 0008). */
1927
- target: workspaceTargetSchema.optional()
1928
- });
1929
- var sessionEndEventSchema = event({
1930
- type: z15.literal("session.end"),
1931
- reason: z15.enum(["completed", "aborted", "error", "timeout", "unknown"]),
1932
- durationMillis: durationMillisSchema.optional(),
1933
- /** Session totals, typically cumulative. */
1934
- usage: canonicalUsageSchema.optional(),
1935
- cost: costFactsSchema.optional()
1936
- });
1937
- var promptSubmittedEventSchema = event({
1938
- type: z15.literal("prompt.submitted"),
1939
- promptSource: z15.enum(["user", "automation", "resumed", "unknown"]),
1940
- content: contentFactSchema.optional(),
1941
- turnIndex: z15.number().int().min(0).optional(),
1942
- /** The git worktree the session runs in, resolved by the core (ADR 0008). */
1943
- target: workspaceTargetSchema.optional()
1944
- });
1945
- var generationStartEventSchema = event({
1946
- type: z15.literal("generation.start"),
1947
- generationId: nonEmptyStringSchema,
1948
- model: modelDescriptorSchema,
1949
- requestedMaxOutputTokens: tokenCountSchema.optional(),
1950
- inputContent: contentFactsSchema.optional()
1951
- });
1952
- var generationEndEventSchema = event({
1953
- type: z15.literal("generation.end"),
1954
- generationId: nonEmptyStringSchema,
1955
- model: modelDescriptorSchema,
1956
- outcome: outcomeSchema,
1957
- stopReason: nonEmptyStringSchema.optional(),
1958
- durationMillis: durationMillisSchema.optional(),
1959
- usage: canonicalUsageSchema.optional(),
1960
- cost: costFactsSchema.optional(),
1961
- outputContent: contentFactsSchema.optional()
1962
- });
1963
- var toolKindSchema = z15.enum([
1964
- "read",
1965
- "write",
1966
- "execute",
1967
- "search",
1968
- "network",
1969
- "delegate",
1970
- "other",
1971
- "unknown"
1972
- ]);
1973
- var toolStartEventSchema = event({
1974
- type: z15.literal("tool.start"),
1975
- toolCallId: nonEmptyStringSchema,
1976
- toolName: nonEmptyStringSchema,
1977
- toolKind: toolKindSchema,
1978
- generationId: nonEmptyStringSchema.optional(),
1979
- input: contentFactSchema.optional(),
1980
- /** The git worktree this call targeted, resolved by the core (ADR 0008). */
1981
- target: workspaceTargetSchema.optional()
1982
- });
1983
- var toolEndEventSchema = event({
1984
- type: z15.literal("tool.end"),
1985
- toolCallId: nonEmptyStringSchema,
1986
- toolName: nonEmptyStringSchema,
1987
- outcome: outcomeSchema,
1988
- durationMillis: durationMillisSchema.optional(),
1989
- /** Present when the host asked for or recorded a permission decision. */
1990
- permissionDecision: z15.enum(["allowed", "denied", "deferred", "not-required"]).optional(),
1991
- output: contentFactSchema.optional(),
1992
- /** The git worktree this call targeted, resolved by the core (ADR 0008). */
1993
- target: workspaceTargetSchema.optional()
1994
- });
1995
- var subagentStartEventSchema = event({
1996
- type: z15.literal("subagent.start"),
1997
- subagentInvocationId: invocationIdSchema,
1998
- subagentType: nonEmptyStringSchema.optional(),
1999
- /** 0 for the top-level agent; 1 for its direct children. */
2000
- delegationDepth: z15.number().int().min(0).max(64),
2001
- model: modelDescriptorSchema.optional()
2002
- });
2003
- var subagentEndEventSchema = event({
2004
- type: z15.literal("subagent.end"),
2005
- subagentInvocationId: invocationIdSchema,
2006
- outcome: outcomeSchema,
2007
- durationMillis: durationMillisSchema.optional(),
2008
- usage: canonicalUsageSchema.optional()
2009
- });
2010
- var compactionPerformedEventSchema = event({
2011
- type: z15.literal("compaction.performed"),
2012
- trigger: z15.enum(["automatic", "manual", "unknown"]),
2013
- /** Provider-reported context size before and after compaction, if known. */
2014
- contextTokensBefore: tokenCountSchema.optional(),
2015
- contextTokensAfter: tokenCountSchema.optional(),
2016
- droppedMessageCount: z15.number().int().min(0).optional(),
2017
- usage: canonicalUsageSchema.optional()
2018
- });
2019
- var errorRaisedEventSchema = event({
2020
- type: z15.literal("error.raised"),
2021
- errorCode: otelHookErrorCodeSchema,
2022
- severity: errorSeveritySchema,
2023
- phase: errorPhaseSchema,
2024
- retryable: z15.boolean(),
2025
- /** Error text is content: it is described, never embedded verbatim by default. */
2026
- message: contentFactSchema.optional(),
2027
- /** Non-sensitive, provider-agnostic short label. */
2028
- detail: nonEmptyStringSchema.optional()
2029
- });
2030
- var canonicalEventSchema = z15.discriminatedUnion("type", [
2031
- sessionStartEventSchema,
2032
- sessionEndEventSchema,
2033
- promptSubmittedEventSchema,
2034
- generationStartEventSchema,
2035
- generationEndEventSchema,
2036
- toolStartEventSchema,
2037
- toolEndEventSchema,
2038
- subagentStartEventSchema,
2039
- subagentEndEventSchema,
2040
- compactionPerformedEventSchema,
2041
- errorRaisedEventSchema
2042
- ]);
2043
- var TARGETED_EVENT_TYPES = ["session.start", "prompt.submitted", "tool.start", "tool.end"];
2044
- var TARGETED = new Set(TARGETED_EVENT_TYPES);
2045
- var isTargetedEvent = (event2) => TARGETED.has(event2.type);
2046
-
2047
- // src/providers/adapter.ts
2048
2131
  var providerDetectionSchema = z16.strictObject({
2049
2132
  providerId: resolvedProviderIdSchema,
2050
2133
  confidence: detectionConfidenceSchema,
@@ -2529,6 +2612,22 @@ var usageScopeOf = (event2) => {
2529
2612
  }
2530
2613
  };
2531
2614
  var sequenceKey = (sessionId) => `sequence:${sessionId}`;
2615
+ var sessionModelKey = (sessionId) => `model:${sessionId}`;
2616
+ var readCursorKey = (enricherId, sessionId) => `cursor:${enricherId}:${sessionId}`;
2617
+ var UNKNOWN_MODEL_ID = "unknown";
2618
+ var latestSessionModel = (events) => {
2619
+ let latest;
2620
+ for (const event2 of events) {
2621
+ if (event2.subagentId !== void 0) {
2622
+ continue;
2623
+ }
2624
+ if ((event2.type === "session.start" || event2.type === "generation.start" || event2.type === "generation.end") && event2.model !== void 0 && event2.model.modelId !== UNKNOWN_MODEL_ID) {
2625
+ latest = event2.model;
2626
+ }
2627
+ }
2628
+ return latest;
2629
+ };
2630
+ var sameModel = (left, right) => left !== void 0 && left.modelId === right.modelId && left.vendor === right.vendor && left.family === right.family;
2532
2631
  var usageKey = (sessionId, scope, scopeKey) => `usage:${sessionId}:${scope}:${scopeKey}`;
2533
2632
  var baselineScopeOf = (scope, scopeKey, sessionId, series) => series === "session-lifetime" && scope === "generation" ? { scope: "session", scopeKey: sessionId } : { scope, scopeKey };
2534
2633
  var createOtelHook = (deps) => {
@@ -2576,6 +2675,66 @@ var createOtelHook = (deps) => {
2576
2675
  return 0;
2577
2676
  }
2578
2677
  };
2678
+ const enrichPayload = async (payload, providerId, sessionId, diagnostics) => {
2679
+ let current = payload;
2680
+ for (const enricher of deps.payloadEnrichers ?? []) {
2681
+ if (enricher.providerId !== providerId) {
2682
+ continue;
2683
+ }
2684
+ const key = readCursorKey(enricher.id, sessionId);
2685
+ let cursor;
2686
+ try {
2687
+ const record = await deps.stateStore.read(key);
2688
+ if (record?.value.kind === "read-cursor") {
2689
+ cursor = { source: record.value.source, offset: record.value.offset };
2690
+ }
2691
+ } catch (thrown) {
2692
+ diagnostics.push(
2693
+ errorInfoFromThrown(thrown, { code: "state-store-failure", phase: "state", occurredAt: clock.now() })
2694
+ );
2695
+ continue;
2696
+ }
2697
+ let result;
2698
+ try {
2699
+ result = await enricher.enrich({ payload: current, sessionId, ...cursor === void 0 ? {} : { cursor } });
2700
+ } catch (thrown) {
2701
+ logger.warn("payload enricher failed; parsing the payload as delivered", {
2702
+ "enricher.id": enricher.id,
2703
+ "error.name": thrown instanceof Error ? thrown.name : typeof thrown
2704
+ });
2705
+ continue;
2706
+ }
2707
+ current = result.payload;
2708
+ if (result.notes !== void 0 && result.notes.length > 0) {
2709
+ logger.debug("payload enricher notes", {
2710
+ "enricher.id": enricher.id,
2711
+ "enricher.notes": result.notes.slice(0, 8).map((note) => note.slice(0, 200))
2712
+ });
2713
+ }
2714
+ const next = result.cursor;
2715
+ if (next !== void 0 && (next.source !== cursor?.source || next.offset !== cursor.offset)) {
2716
+ try {
2717
+ await deps.stateStore.write(key, { kind: "read-cursor", source: next.source, offset: next.offset });
2718
+ } catch (thrown) {
2719
+ diagnostics.push(
2720
+ errorInfoFromThrown(thrown, { code: "state-store-failure", phase: "state", occurredAt: clock.now() })
2721
+ );
2722
+ }
2723
+ }
2724
+ }
2725
+ return current;
2726
+ };
2727
+ const readSessionModel = async (sessionId, diagnostics) => {
2728
+ try {
2729
+ const record = await deps.stateStore.read(sessionModelKey(sessionId));
2730
+ return record?.value.kind === "session-model" ? record.value.model : void 0;
2731
+ } catch (thrown) {
2732
+ diagnostics.push(
2733
+ errorInfoFromThrown(thrown, { code: "state-store-failure", phase: "state", occurredAt: clock.now() })
2734
+ );
2735
+ return void 0;
2736
+ }
2737
+ };
2579
2738
  const deriveUsage = async (events, diagnostics, suppress, series) => {
2580
2739
  const observations = [];
2581
2740
  for (const event2 of events) {
@@ -2896,10 +3055,19 @@ var createOtelHook = (deps) => {
2896
3055
  const identity = resolution.identity;
2897
3056
  const prepare = async () => {
2898
3057
  const sequenceBase = await readSequenceBase(identity.sessionId, diagnostics);
3058
+ const sessionModel = await readSessionModel(identity.sessionId, diagnostics);
3059
+ const payload = suppress ? detectionInput.payload : await enrichPayload(detectionInput.payload, detection.providerId, identity.sessionId, diagnostics);
2899
3060
  let parsed;
2900
3061
  try {
2901
3062
  parsed = adapter.parse(
2902
- { ...detectionInput, detection, identity, sequenceBase },
3063
+ {
3064
+ ...detectionInput,
3065
+ payload,
3066
+ detection,
3067
+ identity,
3068
+ sequenceBase,
3069
+ ...sessionModel === void 0 ? {} : { sessionModel }
3070
+ },
2903
3071
  providerContext
2904
3072
  );
2905
3073
  } catch (thrown) {
@@ -3009,6 +3177,23 @@ var createOtelHook = (deps) => {
3009
3177
  })
3010
3178
  );
3011
3179
  }
3180
+ const reportedModel = latestSessionModel(screened.kept);
3181
+ if (reportedModel !== void 0 && !sameModel(sessionModel, reportedModel)) {
3182
+ try {
3183
+ await deps.stateStore.write(sessionModelKey(identity.sessionId), {
3184
+ kind: "session-model",
3185
+ model: reportedModel
3186
+ });
3187
+ } catch (thrown) {
3188
+ diagnostics.push(
3189
+ errorInfoFromThrown(thrown, {
3190
+ code: "state-store-failure",
3191
+ phase: "state",
3192
+ occurredAt: clock.now()
3193
+ })
3194
+ );
3195
+ }
3196
+ }
3012
3197
  }
3013
3198
  return {
3014
3199
  kind: "ready",