@osfactory/otel-hook 0.8.0 → 0.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (52) hide show
  1. package/README.md +159 -2
  2. package/dist/{adapter-BJiz6lqM.d.ts → adapter-B9RwW6TO.d.ts} +14 -2
  3. package/dist/cli.js +2514 -1238
  4. package/dist/cli.js.map +1 -1
  5. package/dist/config.d.ts +5 -2
  6. package/dist/config.js +479 -169
  7. package/dist/config.js.map +1 -1
  8. package/dist/destinations-DWOkVxV1.d.ts +169 -0
  9. package/dist/diagnostics.d.ts +8 -0
  10. package/dist/diagnostics.js +2 -1
  11. package/dist/diagnostics.js.map +1 -1
  12. package/dist/{events-B3MHoJTD.d.ts → events-CSD_YiJ2.d.ts} +2 -0
  13. package/dist/{otlp-log-sink-zuHojHSP.d.ts → export-destinations-lORbe25J.d.ts} +241 -9
  14. package/dist/{filesystem-store-r-nNA3BA.d.ts → filesystem-store-DX3dGIgu.d.ts} +1 -1
  15. package/dist/{hook-Dh8OO4Wa.d.ts → hook-BAxXoKsp.d.ts} +10 -5
  16. package/dist/index.d.ts +15 -14
  17. package/dist/index.js +1936 -730
  18. package/dist/index.js.map +1 -1
  19. package/dist/install.d.ts +4 -4
  20. package/dist/install.js +31 -2
  21. package/dist/install.js.map +1 -1
  22. package/dist/integration.d.ts +37 -12
  23. package/dist/integration.js +1942 -617
  24. package/dist/integration.js.map +1 -1
  25. package/dist/lifecycle.d.ts +3 -3
  26. package/dist/lifecycle.js +8 -1
  27. package/dist/lifecycle.js.map +1 -1
  28. package/dist/{memory-Bl9ANVff.d.ts → memory-aJilVG4R.d.ts} +2 -2
  29. package/dist/model.d.ts +1 -1
  30. package/dist/model.js +7 -0
  31. package/dist/model.js.map +1 -1
  32. package/dist/{payload-Ci8_ERm6.d.ts → payload-D7gc0-WQ.d.ts} +41 -2
  33. package/dist/{ports-n7KFOpKo.d.ts → ports-plO5MKrY.d.ts} +63 -2
  34. package/dist/providers.d.ts +146 -10
  35. package/dist/providers.js +397 -13
  36. package/dist/providers.js.map +1 -1
  37. package/dist/{registry-CIVvRlVK.d.ts → registry-C7XO4DzD.d.ts} +2 -2
  38. package/dist/runtime.d.ts +8 -8
  39. package/dist/runtime.js +1426 -1163
  40. package/dist/runtime.js.map +1 -1
  41. package/dist/{schema-Cn0-xz8L.d.ts → schema-CHb3GU1r.d.ts} +98 -3
  42. package/dist/{semconv-fPRb-dpU.d.ts → semconv-Dw7gcQcg.d.ts} +1 -1
  43. package/dist/state.d.ts +4 -4
  44. package/dist/state.js +607 -39
  45. package/dist/state.js.map +1 -1
  46. package/dist/telemetry.d.ts +23 -66
  47. package/dist/telemetry.js +637 -34
  48. package/dist/telemetry.js.map +1 -1
  49. package/dist/testing.d.ts +10 -8
  50. package/dist/testing.js +868 -560
  51. package/dist/testing.js.map +1 -1
  52. package/package.json +1 -1
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,269 @@ 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
+ z10.strictObject({
989
+ kind: z10.literal("read-cursor"),
990
+ source: z10.string().regex(/^[A-Za-z0-9_-]{1,128}$/),
991
+ offset: z10.number().int().min(0).max(Number.MAX_SAFE_INTEGER)
992
+ })
993
+ ]);
994
+ var stateRecordSchema = z10.strictObject({
995
+ /** Incremented on each write; lets callers detect lost updates. */
996
+ revision: z10.number().int().min(0),
997
+ updatedAt: epochMillisSchema,
998
+ value: stateValueSchema
999
+ });
1000
+ var logLevelSchema = z10.enum(["silent", "error", "warn", "info", "debug"]);
1001
+ var LOG_LEVEL_RANK = Object.freeze({
1002
+ silent: 0,
1003
+ error: 1,
1004
+ warn: 2,
1005
+ info: 3,
1006
+ debug: 4
1007
+ });
1008
+
1009
+ // src/runtime/clock.ts
1010
+ var createSystemClock = () => ({
1011
+ now: () => epochMillisSchema.parse(Date.now()),
1012
+ monotonicMillis: () => Number(process.hrtime.bigint() / 1000000n)
1013
+ });
1014
+ var createFixedClock = (options = {}) => {
1015
+ let wall = options.startMillis ?? 17e11;
1016
+ let monotonic = 0;
1017
+ const tick = options.tickMillis ?? 0;
1018
+ return {
1019
+ now: () => {
1020
+ const current = wall;
1021
+ wall += tick;
1022
+ monotonic += tick;
1023
+ return epochMillisSchema.parse(current);
1024
+ },
334
1025
  monotonicMillis: () => monotonic,
335
1026
  advance: (millis) => {
336
1027
  wall += millis;
@@ -426,263 +1117,65 @@ var createStderrLogger = (options = {}) => {
426
1117
  };
427
1118
 
428
1119
  // 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
- };
1120
+ import { z as z11 } from "zod";
1121
+ var otelHookErrorInfoSchema = z11.strictObject({
1122
+ code: otelHookErrorCodeSchema,
1123
+ severity: errorSeveritySchema,
1124
+ phase: errorPhaseSchema,
1125
+ posture: failurePostureSchema,
1126
+ retryable: z11.boolean(),
1127
+ message: z11.string().min(1).max(512),
1128
+ details: attributesSchema.optional(),
1129
+ occurredAt: epochMillisSchema.optional()
1130
+ });
1131
+ var createErrorInfo = (input) => {
1132
+ const descriptor = describeErrorCode(input.code);
1133
+ const message = input.detail === void 0 ? `${input.code} during ${input.phase}: ${descriptor.summary}` : `${input.code} during ${input.phase}: ${input.detail}`;
1134
+ return otelHookErrorInfoSchema.parse({
1135
+ code: descriptor.code,
1136
+ severity: descriptor.severity,
1137
+ phase: input.phase,
1138
+ posture: descriptor.posture,
1139
+ retryable: descriptor.retryable,
1140
+ message: message.slice(0, 512),
1141
+ ...input.details === void 0 ? {} : { details: input.details },
1142
+ ...input.occurredAt === void 0 ? {} : { occurredAt: input.occurredAt }
1143
+ });
1144
+ };
1145
+ var OtelHookError = class _OtelHookError extends Error {
1146
+ info;
1147
+ constructor(info) {
1148
+ super(info.message);
1149
+ this.name = "OtelHookError";
1150
+ this.info = info;
1151
+ }
1152
+ static of(input) {
1153
+ return new _OtelHookError(createErrorInfo(input));
1154
+ }
1155
+ };
1156
+ var isOtelHookError = (value) => value instanceof OtelHookError;
1157
+ var describeThrown = (thrown) => {
1158
+ if (thrown instanceof Error) {
1159
+ return {
1160
+ errorName: thrown.name.slice(0, 64) || "Error",
1161
+ hasMessage: typeof thrown.message === "string" && thrown.message.length > 0
1162
+ };
1163
+ }
1164
+ return { errorName: typeof thrown, hasMessage: false };
1165
+ };
1166
+ var errorInfoFromThrown = (thrown, input) => {
1167
+ if (isOtelHookError(thrown)) {
1168
+ return thrown.info;
1169
+ }
1170
+ const described = describeThrown(thrown);
1171
+ return createErrorInfo({
1172
+ code: input.code ?? "internal-error",
1173
+ phase: input.phase,
1174
+ detail: `contained ${described.errorName}`,
1175
+ details: { "error.name": described.errorName, "error.has_message": described.hasMessage },
1176
+ ...input.occurredAt === void 0 ? {} : { occurredAt: input.occurredAt }
1177
+ });
1178
+ };
686
1179
 
687
1180
  // src/runtime/memory.ts
688
1181
  var createInMemoryStateStore = (options) => {
@@ -837,14 +1330,14 @@ var resolveDeliveryIdentity = (input) => {
837
1330
  };
838
1331
 
839
1332
  // src/runtime/hook.ts
840
- import { z as z16 } from "zod";
1333
+ import { z as z17 } from "zod";
841
1334
 
842
1335
  // src/config/schema.ts
843
- import { z as z8 } from "zod";
1336
+ import { z as z15 } from "zod";
844
1337
 
845
1338
  // src/privacy/policy.ts
846
- import { z as z6 } from "zod";
847
- var contentModeSchema = z6.enum(["omit", "mask", "redact", "raw"]);
1339
+ import { z as z12 } from "zod";
1340
+ var contentModeSchema = z12.enum(["omit", "mask", "redact", "raw"]);
848
1341
  var CONTENT_MODE_DISCLOSURE = Object.freeze({
849
1342
  omit: "omitted",
850
1343
  mask: "masked",
@@ -870,510 +1363,382 @@ var DEFAULT_SECRET_VALUE_PATTERNS = Object.freeze([
870
1363
  "eyJ[A-Za-z0-9_-]{10,}\\.[A-Za-z0-9_-]{10,}\\.[A-Za-z0-9_-]{10,}",
871
1364
  "(?:Bearer|Basic)\\s+[A-Za-z0-9._~+/=-]{12,}"
872
1365
  ]);
873
- var privacyLimitsSchema = z6.strictObject({
1366
+ var privacyLimitsSchema = z12.strictObject({
874
1367
  /** Maximum characters of disclosed text per content fact or string value. */
875
- maxStringLength: z6.number().int().min(0).max(65536),
1368
+ maxStringLength: z12.number().int().min(0).max(65536),
876
1369
  /** Maximum nesting depth walked when sanitizing structured values. */
877
- maxDepth: z6.number().int().min(1).max(32),
1370
+ maxDepth: z12.number().int().min(1).max(32),
878
1371
  /** Maximum array entries retained when sanitizing structured values. */
879
- maxArrayLength: z6.number().int().min(1).max(4096),
1372
+ maxArrayLength: z12.number().int().min(1).max(4096),
880
1373
  /** Maximum canonical events emitted per invocation. */
881
- maxEventsPerInvocation: z6.number().int().min(1).max(1e4),
1374
+ maxEventsPerInvocation: z12.number().int().min(1).max(1e4),
882
1375
  /** Maximum object keys retained per level when sanitizing. */
883
- maxObjectKeys: z6.number().int().min(1).max(1024)
1376
+ maxObjectKeys: z12.number().int().min(1).max(1024)
884
1377
  });
885
- var privacyPolicySchema = z6.strictObject({
1378
+ var privacyPolicySchema = z12.strictObject({
886
1379
  contentMode: contentModeSchema,
887
1380
  /**
888
1381
  * `raw` mode is refused unless this is also true, so a single mistyped
889
1382
  * environment variable cannot start exporting prompts.
890
1383
  */
891
- allowRawContent: z6.boolean(),
1384
+ allowRawContent: z12.boolean(),
892
1385
  /**
893
1386
  * Salt mixed into every hash. A per-deployment salt makes hashes
894
1387
  * non-correlatable across deployments; an empty salt makes them globally
895
1388
  * comparable. Both are legitimate; the choice is explicit.
896
1389
  */
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(),
1390
+ hashSalt: z12.string().max(256),
1391
+ maskCharacter: z12.string().length(1),
1392
+ redactionPlaceholder: z12.string().min(1).max(64),
1393
+ secretKeyPatterns: z12.array(z12.string().min(1)).max(128).readonly(),
1394
+ secretValuePatterns: z12.array(z12.string().min(1)).max(128).readonly(),
902
1395
  limits: privacyLimitsSchema
903
1396
  });
904
1397
  var DEFAULT_PRIVACY_LIMITS = Object.freeze({
905
1398
  maxStringLength: 1024,
906
- maxDepth: 6,
907
- maxArrayLength: 64,
908
- maxEventsPerInvocation: 512,
909
- maxObjectKeys: 128
910
- });
911
- var DEFAULT_PRIVACY_POLICY = Object.freeze({
912
- contentMode: "omit",
913
- allowRawContent: false,
914
- hashSalt: "",
915
- maskCharacter: "*",
916
- redactionPlaceholder: "[redacted]",
917
- secretKeyPatterns: DEFAULT_SECRET_KEY_PATTERNS,
918
- secretValuePatterns: DEFAULT_SECRET_VALUE_PATTERNS,
919
- limits: DEFAULT_PRIVACY_LIMITS
920
- });
921
- var resolvePrivacyPolicy = (policy) => {
922
- const parsed = privacyPolicySchema.parse(policy);
923
- if (parsed.contentMode === "raw" && !parsed.allowRawContent) {
924
- return {
925
- policy: { ...parsed, contentMode: "omit" },
926
- notes: ["contentMode=raw downgraded to omit because allowRawContent is false"]
927
- };
928
- }
929
- return { policy: parsed, notes: [] };
930
- };
931
-
932
- // src/config/resource-attributes.ts
933
- import { z as z7 } from "zod";
934
- var MAX_RESOURCE_ATTRIBUTES = 64;
935
- var MAX_RESOURCE_ATTRIBUTE_KEY_LENGTH = 255;
936
- var MAX_RESOURCE_ATTRIBUTE_VALUE_LENGTH = 2048;
937
- var RESOURCE_ATTRIBUTE_KEY_PATTERN = /^[A-Za-z][A-Za-z0-9_./-]*$/;
938
- var RESERVED_RESOURCE_ATTRIBUTE_KEYS = Object.freeze([
939
- "service.name",
940
- "service.namespace"
941
- ]);
942
- var isReservedResourceAttributeKey = (key) => RESERVED_RESOURCE_ATTRIBUTE_KEYS.includes(key.toLowerCase());
943
- var SECRET_KEY_MATCHERS = Object.freeze(
944
- DEFAULT_SECRET_KEY_PATTERNS.flatMap((source) => {
945
- try {
946
- return [new RegExp(source, "i")];
947
- } catch {
948
- return [];
949
- }
950
- })
951
- );
952
- var isSecretResourceAttributeKey = (key) => SECRET_KEY_MATCHERS.some((pattern) => pattern.test(key));
953
- var RESOURCE_ATTRIBUTE_KEY_REJECTION_DETAIL = Object.freeze({
954
- empty: "resource attribute key is empty",
955
- "too-long": `resource attribute key exceeds ${String(MAX_RESOURCE_ATTRIBUTE_KEY_LENGTH)} characters`,
956
- malformed: "resource attribute key must start with a letter and use only letters, digits, and `_`, `.`, `-`, `/`",
957
- reserved: "service.name and service.namespace are exporter policy (--service-name / OTEL_HOOK_SERVICE_NAME), not resource attributes",
958
- "secret-like": "resource attribute key matches a secret-name pattern, so it is never exported"
959
- });
960
- var checkResourceAttributeKey = (key) => {
961
- if (key.length === 0) {
962
- return "empty";
963
- }
964
- if (key.length > MAX_RESOURCE_ATTRIBUTE_KEY_LENGTH) {
965
- return "too-long";
966
- }
967
- if (!RESOURCE_ATTRIBUTE_KEY_PATTERN.test(key)) {
968
- return "malformed";
969
- }
970
- if (isReservedResourceAttributeKey(key)) {
971
- return "reserved";
972
- }
973
- if (isSecretResourceAttributeKey(key)) {
974
- return "secret-like";
975
- }
976
- return void 0;
977
- };
978
- var resourceAttributeValueSchema = z7.union([
979
- z7.string().max(MAX_RESOURCE_ATTRIBUTE_VALUE_LENGTH),
980
- z7.number().finite(),
981
- z7.boolean()
982
- ]);
983
- var resourceAttributesSchema = z7.record(z7.string(), resourceAttributeValueSchema).superRefine((value, ctx) => {
984
- const keys = Object.keys(value);
985
- if (keys.length > MAX_RESOURCE_ATTRIBUTES) {
986
- ctx.addIssue({
987
- code: "custom",
988
- message: `at most ${String(MAX_RESOURCE_ATTRIBUTES)} resource attributes are accepted`
989
- });
990
- }
991
- for (const key of keys) {
992
- const rejection = checkResourceAttributeKey(key);
993
- if (rejection !== void 0) {
994
- ctx.addIssue({
995
- code: "custom",
996
- path: [key],
997
- message: RESOURCE_ATTRIBUTE_KEY_REJECTION_DETAIL[rejection]
998
- });
999
- }
1000
- }
1001
- }).readonly();
1002
- var EMPTY_RESOURCE_ATTRIBUTES = Object.freeze({});
1003
-
1004
- // src/config/schema.ts
1005
- var logsPolicySchema = z8.strictObject({
1006
- enabled: z8.boolean(),
1007
- /**
1008
- * Full URL for the logs signal.
1009
- *
1010
- * Absent, it is derived from `endpoint`: a trailing `/v1/traces` becomes
1011
- * `/v1/logs`, and an endpoint with no signal path has `/v1/logs` appended.
1012
- */
1013
- endpoint: z8.string().url().max(2048).optional(),
1014
- includeContent: z8.boolean(),
1015
- maxBatchSize: z8.number().int().min(1).max(4096)
1016
- });
1017
- var DEFAULT_LOGS_POLICY = Object.freeze({
1018
- enabled: false,
1019
- includeContent: false,
1020
- maxBatchSize: 128
1021
- });
1022
- var exporterPolicySchema = z8.strictObject({
1023
- enabled: z8.boolean(),
1024
- protocol: z8.enum(["http/protobuf", "http/json", "none"]),
1025
- endpoint: z8.string().url().max(2048).optional(),
1026
- /**
1027
- * Header names only. Values are supplied separately at construction time and
1028
- * are never part of a resolved-config snapshot, which is logged and exported.
1029
- */
1030
- headerNames: z8.array(nonEmptyStringSchema).max(32).readonly(),
1031
- timeoutMillis: z8.number().int().min(1).max(6e5),
1032
- maxBatchSize: z8.number().int().min(1).max(4096),
1033
- maxQueueSize: z8.number().int().min(1).max(65536),
1034
- maxRetryAttempts: z8.number().int().min(0).max(10),
1035
- serviceName: nonEmptyStringSchema,
1036
- serviceNamespace: nonEmptyStringSchema.optional(),
1037
- /**
1038
- * Custom attributes merged into the exported OTLP Resource.
1039
- *
1040
- * Bounded and validated, and refusing `service.name`/`service.namespace`,
1041
- * which are the two fields above. Distinct from an invocation's
1042
- * `consumerAttributes`: this describes the emitting deployment, carries no
1043
- * identity, and is the same for every span this process exports.
1044
- */
1045
- resourceAttributes: resourceAttributesSchema,
1046
- /**
1047
- * The logs signal. Nested under the exporter because it shares the endpoint,
1048
- * headers, timeout, protocol, service identity, and resource attributes above —
1049
- * a second top-level section would invite two of each to drift apart.
1050
- */
1051
- logs: logsPolicySchema
1052
- });
1053
- var detectionPolicySchema = z8.strictObject({
1054
- /** Detections below this confidence resolve to the unknown provider. */
1055
- minimumConfidence: detectionConfidenceSchema,
1056
- /** When false, an ambiguous detection is an error rather than unknown. */
1057
- allowAmbiguousFallback: z8.boolean(),
1058
- /** Optional allow-list of provider ids; empty means "any registered". */
1059
- allowedProviderIds: z8.array(nonEmptyStringSchema).max(32).readonly()
1060
- });
1061
- var diagnosticsPolicySchema = z8.strictObject({
1062
- logLevel: z8.enum(["silent", "error", "warn", "info", "debug"]),
1063
- /** Emit `error.raised` events for contained failures. */
1064
- emitErrorEvents: z8.boolean()
1065
- });
1066
- var otelHookConfigSchema = z8.strictObject({
1067
- exporter: exporterPolicySchema,
1068
- privacy: privacyPolicySchema,
1069
- detection: detectionPolicySchema,
1070
- diagnostics: diagnosticsPolicySchema
1071
- });
1072
- var otelHookConfigPatchSchema = z8.strictObject({
1073
- // `logs` is unwrapped and re-partialled for the same reason `privacy.limits` is:
1074
- // merging happens per leaf, so a layer must be able to set `logs.enabled` alone
1075
- // without also restating the endpoint and the batch size.
1076
- exporter: exporterPolicySchema.omit({ logs: true }).partial().extend({ logs: logsPolicySchema.partial().optional() }).optional(),
1077
- privacy: privacyPolicySchema.omit({ limits: true }).partial().extend({ limits: privacyPolicySchema.shape.limits.partial().optional() }).optional(),
1078
- detection: detectionPolicySchema.partial().optional(),
1079
- diagnostics: diagnosticsPolicySchema.partial().optional()
1080
- });
1081
- var DEFAULT_EXPORTER_POLICY = Object.freeze({
1082
- enabled: true,
1083
- protocol: "http/protobuf",
1084
- headerNames: Object.freeze([]),
1085
- timeoutMillis: 1e4,
1086
- maxBatchSize: 128,
1087
- maxQueueSize: 2048,
1088
- maxRetryAttempts: 2,
1089
- serviceName: "coding-agent",
1090
- resourceAttributes: EMPTY_RESOURCE_ATTRIBUTES,
1091
- logs: DEFAULT_LOGS_POLICY
1092
- });
1093
- var DEFAULT_DETECTION_POLICY = Object.freeze({
1094
- minimumConfidence: "strong",
1095
- allowAmbiguousFallback: true,
1096
- allowedProviderIds: Object.freeze([])
1097
- });
1098
- var DEFAULT_DIAGNOSTICS_POLICY = Object.freeze({
1099
- logLevel: "warn",
1100
- emitErrorEvents: true
1101
- });
1102
- var DEFAULT_CONFIG = Object.freeze({
1103
- exporter: DEFAULT_EXPORTER_POLICY,
1104
- privacy: DEFAULT_PRIVACY_POLICY,
1105
- detection: DEFAULT_DETECTION_POLICY,
1106
- diagnostics: DEFAULT_DIAGNOSTICS_POLICY
1107
- });
1108
-
1109
- // src/model/content.ts
1110
- import { z as z9 } from "zod";
1111
- var contentKindSchema = z9.enum([
1112
- "prompt",
1113
- "response",
1114
- "reasoning",
1115
- "tool-input",
1116
- "tool-output",
1117
- "error-message",
1118
- "system-instruction",
1119
- "attachment"
1120
- ]);
1121
- var contentRoleSchema = z9.enum(["user", "assistant", "system", "tool", "unknown"]);
1122
- var contentDisclosureSchema = z9.enum(["omitted", "masked", "redacted", "raw"]);
1123
- var CONTENT_HASH_PATTERN = /^sha256:[0-9a-f]{64}$/;
1124
- var contentFactSchema = z9.strictObject({
1125
- kind: contentKindSchema,
1126
- role: contentRoleSchema.optional(),
1127
- /** Unicode code point count of the original content. */
1128
- characterLength: z9.number().int().min(0),
1129
- /** UTF-8 byte length of the original content. */
1130
- byteLength: z9.number().int().min(0),
1131
- /** Stable salted digest of the original content. */
1132
- contentHash: z9.string().regex(CONTENT_HASH_PATTERN),
1133
- disclosure: contentDisclosureSchema,
1134
- /** Disclosed text, bounded by the privacy policy. Absent when omitted. */
1135
- text: z9.string().optional(),
1136
- /** True when `text` was cut short by the configured string bound. */
1137
- truncated: z9.boolean(),
1138
- /** Number of secret-looking spans replaced while producing `text`. */
1139
- secretsRedacted: z9.number().int().min(0),
1140
- /** Optional non-sensitive label, e.g. a MIME type or tool name. */
1141
- label: nonEmptyStringSchema.optional()
1142
- });
1143
- var contentFactsSchema = z9.array(contentFactSchema).max(64);
1144
- var isContentFactConsistent = (fact) => fact.disclosure === "omitted" ? fact.text === void 0 : fact.text !== void 0;
1145
- var isUnavailableContentFact = (fact) => fact.disclosure === "omitted" && fact.text === void 0 && fact.characterLength === 0 && fact.byteLength === 0;
1146
-
1147
- // src/model/identity.ts
1148
- import { z as z10 } from "zod";
1149
- var workspaceKeySourceSchema = z10.enum([
1150
- "git-remote",
1151
- "git-root",
1152
- "working-directory",
1153
- "explicit",
1154
- "unknown"
1155
- ]);
1156
- var workspaceIdentitySchema = z10.strictObject({
1157
- workspaceId: workspaceIdSchema,
1158
- keySource: workspaceKeySourceSchema,
1159
- /** Repository name only; never an owner path or URL with credentials. */
1160
- repositoryName: nonEmptyStringSchema.optional(),
1161
- vcsBranchName: nonEmptyStringSchema.optional(),
1162
- /** Opaque handle for the checked-out revision. */
1163
- vcsRevisionId: nonEmptyStringSchema.optional()
1164
- }).readonly();
1165
- var UNKNOWN_WORKSPACE_ID = "unknown:0000000000000000";
1166
- var unknownWorkspaceIdentity = () => workspaceIdentitySchema.parse({
1167
- workspaceId: UNKNOWN_WORKSPACE_ID,
1168
- keySource: "unknown"
1169
- });
1170
- var sourceProvenanceSchema = z10.strictObject({
1171
- providerId: resolvedProviderIdSchema,
1172
- providerVersion: nonEmptyStringSchema.optional(),
1173
- adapterId: nonEmptyStringSchema,
1174
- adapterVersion: nonEmptyStringSchema,
1175
- detectionConfidence: detectionConfidenceSchema,
1176
- /** The provider's own name for the source event, e.g. a hook event name. */
1177
- sourceEventName: nonEmptyStringSchema.optional(),
1178
- transport: sourceTransportSchema
1179
- }).readonly();
1180
- var consumerAttributesSchema = attributesSchema.readonly();
1181
- var invocationIdentitySchema = z10.strictObject({
1182
- invocationId: invocationIdSchema,
1183
- sessionId: sessionIdSchema,
1184
- /** Set when this invocation runs beneath another agent invocation. */
1185
- parentInvocationId: invocationIdSchema.optional(),
1186
- /** Root of the session tree when the provider exposes one. */
1187
- rootSessionId: sessionIdSchema.optional(),
1188
- /** Stable handle for the agent process/instance, when available. */
1189
- agentInstanceId: nonEmptyStringSchema.optional(),
1190
- provenance: sourceProvenanceSchema,
1191
- workspace: workspaceIdentitySchema,
1192
- startedAt: epochMillisSchema,
1193
- consumerAttributes: consumerAttributesSchema
1194
- }).readonly();
1195
- var identityClaimFieldsSchema = z10.strictObject({
1196
- invocationId: invocationIdSchema.optional(),
1197
- sessionId: sessionIdSchema.optional(),
1198
- parentInvocationId: invocationIdSchema.optional(),
1199
- rootSessionId: sessionIdSchema.optional(),
1200
- agentInstanceId: nonEmptyStringSchema.optional(),
1201
- workspace: workspaceIdentitySchema.optional(),
1202
- startedAt: epochMillisSchema.optional()
1203
- });
1204
- var identityClaimSchema = z10.strictObject({
1205
- /** Non-sensitive label, e.g. `adapter:acme-cli` or `env:OTEL_HOOK_SESSION_ID`. */
1206
- source: nonEmptyStringSchema,
1207
- confidence: detectionConfidenceSchema,
1208
- fields: identityClaimFieldsSchema
1209
- });
1210
- var CLAIM_FIELDS = [
1211
- "invocationId",
1212
- "sessionId",
1213
- "parentInvocationId",
1214
- "rootSessionId",
1215
- "agentInstanceId",
1216
- "workspace",
1217
- "startedAt"
1218
- ];
1219
- var renderClaimValue = (value) => {
1220
- if (typeof value === "string") {
1221
- return value;
1222
- }
1223
- if (typeof value === "number" || typeof value === "boolean") {
1224
- return String(value);
1225
- }
1226
- if (value !== null && typeof value === "object" && "workspaceId" in value) {
1227
- const { workspaceId } = value;
1228
- return typeof workspaceId === "string" ? workspaceId : "<workspace>";
1399
+ maxDepth: 6,
1400
+ maxArrayLength: 64,
1401
+ maxEventsPerInvocation: 512,
1402
+ maxObjectKeys: 128
1403
+ });
1404
+ var DEFAULT_PRIVACY_POLICY = Object.freeze({
1405
+ contentMode: "omit",
1406
+ allowRawContent: false,
1407
+ hashSalt: "",
1408
+ maskCharacter: "*",
1409
+ redactionPlaceholder: "[redacted]",
1410
+ secretKeyPatterns: DEFAULT_SECRET_KEY_PATTERNS,
1411
+ secretValuePatterns: DEFAULT_SECRET_VALUE_PATTERNS,
1412
+ limits: DEFAULT_PRIVACY_LIMITS
1413
+ });
1414
+ var resolvePrivacyPolicy = (policy) => {
1415
+ const parsed = privacyPolicySchema.parse(policy);
1416
+ if (parsed.contentMode === "raw" && !parsed.allowRawContent) {
1417
+ return {
1418
+ policy: { ...parsed, contentMode: "omit" },
1419
+ notes: ["contentMode=raw downgraded to omit because allowRawContent is false"]
1420
+ };
1229
1421
  }
1230
- return "<opaque>";
1422
+ return { policy: parsed, notes: [] };
1231
1423
  };
1232
- var resolveInvocationIdentity = (input) => {
1233
- const parsedClaims = [];
1234
- const issues = [];
1235
- for (const [index, claim] of input.claims.entries()) {
1236
- const parsed2 = identityClaimSchema.safeParse(claim);
1237
- if (parsed2.success) {
1238
- parsedClaims.push(parsed2.data);
1239
- } else {
1240
- issues.push(
1241
- `claim[${index}]: ${parsed2.error.issues.map((issue) => `${issue.path.join(".") || "<root>"} ${issue.message}`).join(", ")}`
1242
- );
1243
- }
1244
- }
1245
- if (issues.length > 0) {
1246
- return { status: "invalid", issues };
1247
- }
1248
- const conflicts = [];
1249
- const selected = {};
1250
- for (const field of CLAIM_FIELDS) {
1251
- const contributors = parsedClaims.filter((claim) => claim.fields[field] !== void 0);
1252
- if (contributors.length === 0) {
1253
- continue;
1254
- }
1255
- const bestRank = Math.max(
1256
- ...contributors.map((claim) => DETECTION_CONFIDENCE_RANK[claim.confidence])
1257
- );
1258
- const best = contributors.filter(
1259
- (claim) => DETECTION_CONFIDENCE_RANK[claim.confidence] === bestRank
1260
- );
1261
- const rendered = /* @__PURE__ */ new Map();
1262
- for (const claim of best) {
1263
- const key = JSON.stringify(claim.fields[field]);
1264
- const sources = rendered.get(key) ?? [];
1265
- sources.push(claim.source);
1266
- rendered.set(key, sources);
1424
+
1425
+ // src/config/destinations.ts
1426
+ import { z as z13 } from "zod";
1427
+
1428
+ // src/config/header-value.ts
1429
+ var isUnsafeHeaderValue = (value) => [...value].some((char) => {
1430
+ const code = char.codePointAt(0) ?? 0;
1431
+ return code < 32 && code !== 9 || code === 127 || code > 255;
1432
+ });
1433
+
1434
+ // src/config/otlp-headers.ts
1435
+ var MAX_OTLP_HEADERS = 32;
1436
+ var OTLP_HEADER_VARIABLES = Object.freeze({
1437
+ generic: "OTEL_EXPORTER_OTLP_HEADERS",
1438
+ traces: "OTEL_EXPORTER_OTLP_TRACES_HEADERS",
1439
+ logs: "OTEL_EXPORTER_OTLP_LOGS_HEADERS"
1440
+ });
1441
+
1442
+ // src/config/destinations.ts
1443
+ var DEFAULT_DESTINATION_NAME = "default";
1444
+ var DESTINATION_NAME_PATTERN = /^[a-z0-9][a-z0-9_-]{0,62}$/;
1445
+ var MAX_EXPORT_DESTINATIONS = 16;
1446
+ var MAX_DESTINATION_HEADERS = MAX_OTLP_HEADERS;
1447
+ var HEADER_ENV_REFERENCE_PREFIX = "env:";
1448
+ var HEADER_NAME_PATTERN = /^[A-Za-z0-9!#$%&'*+.^_`|~-]{1,128}$/;
1449
+ var ENV_VARIABLE_NAME_PATTERN = /^[A-Za-z_][A-Za-z0-9_]{0,127}$/;
1450
+ var MAX_HEADER_VALUE_LENGTH = 8192;
1451
+ var exportSignalSchema = z13.enum(["traces", "logs"]);
1452
+ var headerValueSchema = z13.string().min(1).max(MAX_HEADER_VALUE_LENGTH).refine(
1453
+ (value) => !isUnsafeHeaderValue(value),
1454
+ "header values may not contain line breaks, control characters, or characters beyond Latin-1"
1455
+ ).refine(
1456
+ (value) => !value.startsWith(HEADER_ENV_REFERENCE_PREFIX) || ENV_VARIABLE_NAME_PATTERN.test(value.slice(HEADER_ENV_REFERENCE_PREFIX.length)),
1457
+ "an env: header reference must name an environment variable, e.g. env:COLLECTOR_TOKEN"
1458
+ );
1459
+ var endpointSchema = z13.string().url().max(2048);
1460
+ var exportDestinationSchema = z13.strictObject({
1461
+ /** Unique, lowercase, filesystem-safe. `default` is reserved for the single-endpoint settings. */
1462
+ name: z13.string().regex(DESTINATION_NAME_PATTERN, "destination names are lowercase letters, digits, _ and -"),
1463
+ /** Default true. A disabled destination is neither sent to nor drained. */
1464
+ enabled: z13.boolean().optional(),
1465
+ /**
1466
+ * Traces URL, with the same meaning as `exporter.endpoint`: the logs URL is
1467
+ * derived from it (`/v1/traces` becomes `/v1/logs`) unless `logsEndpoint` is set.
1468
+ */
1469
+ endpoint: endpointSchema.optional(),
1470
+ /** Per-signal override of `endpoint` for traces. */
1471
+ tracesEndpoint: endpointSchema.optional(),
1472
+ /** Per-signal override of the derived logs URL. */
1473
+ logsEndpoint: endpointSchema.optional(),
1474
+ /** Defaults to `exporter.protocol`. */
1475
+ protocol: z13.enum(["http/protobuf", "http/json", "none"]).optional(),
1476
+ /**
1477
+ * Header name to value. A value of the form `env:NAME` is read from that
1478
+ * environment variable at send time, so a credential never has to be written
1479
+ * into the file. Values never appear in a snapshot, a diagnostic, or `doctor`.
1480
+ */
1481
+ headers: z13.record(z13.string().regex(HEADER_NAME_PATTERN, "not a valid header name"), headerValueSchema).refine(
1482
+ (headers) => Object.keys(headers).length <= MAX_DESTINATION_HEADERS,
1483
+ `at most ${String(MAX_DESTINATION_HEADERS)} headers per destination`
1484
+ ).optional(),
1485
+ /**
1486
+ * Which signals this destination receives. Default: both. The logs signal is
1487
+ * still governed by `exporter.logs.enabled`, which stays the one opt-in for a
1488
+ * second stream leaving the host.
1489
+ */
1490
+ signals: z13.array(exportSignalSchema).min(1).max(2).readonly().optional()
1491
+ }).refine(
1492
+ (destination) => destination.endpoint !== void 0 || destination.tracesEndpoint !== void 0 || destination.logsEndpoint !== void 0,
1493
+ "a destination needs an endpoint, or a tracesEndpoint / logsEndpoint"
1494
+ );
1495
+ var exportDestinationsSchema = z13.array(exportDestinationSchema).max(MAX_EXPORT_DESTINATIONS).readonly().superRefine((destinations, context) => {
1496
+ const seen = /* @__PURE__ */ new Set();
1497
+ destinations.forEach((destination, index) => {
1498
+ if (destination.name === DEFAULT_DESTINATION_NAME) {
1499
+ context.addIssue({
1500
+ code: "custom",
1501
+ path: [index, "name"],
1502
+ message: 'the name "default" is reserved for exporter.endpoint and the OTEL_EXPORTER_OTLP_* variables'
1503
+ });
1267
1504
  }
1268
- if (rendered.size > 1) {
1269
- const [firstBest] = best;
1270
- conflicts.push({
1271
- field,
1272
- confidence: firstBest?.confidence ?? "none",
1273
- values: best.map((claim) => renderClaimValue(claim.fields[field])),
1274
- sources: best.map((claim) => claim.source)
1505
+ if (seen.has(destination.name)) {
1506
+ context.addIssue({
1507
+ code: "custom",
1508
+ path: [index, "name"],
1509
+ message: `duplicate destination name "${destination.name}"`
1275
1510
  });
1276
- continue;
1277
1511
  }
1278
- const [winner] = best;
1279
- if (winner !== void 0) {
1280
- selected[field] = winner.fields[field];
1512
+ seen.add(destination.name);
1513
+ });
1514
+ });
1515
+ var spoolPolicySchema = z13.strictObject({
1516
+ /** Total bytes of queued batches. Default 16 MiB. */
1517
+ maxBytes: z13.number().int().min(1024).max(1073741824),
1518
+ /** A batch older than this is dropped instead of sent. Default 72 hours. */
1519
+ maxAgeMillis: z13.number().int().min(1e3).max(30 * 24 * 60 * 60 * 1e3),
1520
+ /** Number of queued batches. Default 500. */
1521
+ maxBatches: z13.number().int().min(1).max(65536)
1522
+ });
1523
+ var DEFAULT_SPOOL_POLICY = Object.freeze({
1524
+ maxBytes: 16 * 1024 * 1024,
1525
+ maxAgeMillis: 72 * 60 * 60 * 1e3,
1526
+ maxBatches: 500
1527
+ });
1528
+
1529
+ // src/config/resource-attributes.ts
1530
+ import { z as z14 } from "zod";
1531
+ var MAX_RESOURCE_ATTRIBUTES = 64;
1532
+ var MAX_RESOURCE_ATTRIBUTE_KEY_LENGTH = 255;
1533
+ var MAX_RESOURCE_ATTRIBUTE_VALUE_LENGTH = 2048;
1534
+ var RESOURCE_ATTRIBUTE_KEY_PATTERN = /^[A-Za-z][A-Za-z0-9_./-]*$/;
1535
+ var RESERVED_RESOURCE_ATTRIBUTE_KEYS = Object.freeze([
1536
+ "service.name",
1537
+ "service.namespace"
1538
+ ]);
1539
+ var isReservedResourceAttributeKey = (key) => RESERVED_RESOURCE_ATTRIBUTE_KEYS.includes(key.toLowerCase());
1540
+ var SECRET_KEY_MATCHERS = Object.freeze(
1541
+ DEFAULT_SECRET_KEY_PATTERNS.flatMap((source) => {
1542
+ try {
1543
+ return [new RegExp(source, "i")];
1544
+ } catch {
1545
+ return [];
1281
1546
  }
1547
+ })
1548
+ );
1549
+ var isSecretResourceAttributeKey = (key) => SECRET_KEY_MATCHERS.some((pattern) => pattern.test(key));
1550
+ var RESOURCE_ATTRIBUTE_KEY_REJECTION_DETAIL = Object.freeze({
1551
+ empty: "resource attribute key is empty",
1552
+ "too-long": `resource attribute key exceeds ${String(MAX_RESOURCE_ATTRIBUTE_KEY_LENGTH)} characters`,
1553
+ malformed: "resource attribute key must start with a letter and use only letters, digits, and `_`, `.`, `-`, `/`",
1554
+ reserved: "service.name and service.namespace are exporter policy (--service-name / OTEL_HOOK_SERVICE_NAME), not resource attributes",
1555
+ "secret-like": "resource attribute key matches a secret-name pattern, so it is never exported"
1556
+ });
1557
+ var checkResourceAttributeKey = (key) => {
1558
+ if (key.length === 0) {
1559
+ return "empty";
1282
1560
  }
1283
- if (conflicts.length > 0) {
1284
- return { status: "conflict", conflicts };
1285
- }
1286
- const missing = [];
1287
- if (selected.invocationId === void 0) {
1288
- missing.push("invocationId");
1289
- }
1290
- if (selected.sessionId === void 0) {
1291
- missing.push("sessionId");
1561
+ if (key.length > MAX_RESOURCE_ATTRIBUTE_KEY_LENGTH) {
1562
+ return "too-long";
1292
1563
  }
1293
- if (missing.length > 0) {
1294
- return { status: "incomplete", missing };
1564
+ if (!RESOURCE_ATTRIBUTE_KEY_PATTERN.test(key)) {
1565
+ return "malformed";
1295
1566
  }
1296
- const startedAt = selected.startedAt ?? input.fallback?.startedAt;
1297
- if (startedAt === void 0) {
1298
- return { status: "incomplete", missing: ["startedAt"] };
1567
+ if (isReservedResourceAttributeKey(key)) {
1568
+ return "reserved";
1299
1569
  }
1300
- const workspace = selected.workspace ?? input.fallback?.workspace ?? unknownWorkspaceIdentity();
1301
- const candidate = {
1302
- invocationId: selected.invocationId,
1303
- sessionId: selected.sessionId,
1304
- ...selected.parentInvocationId === void 0 ? {} : { parentInvocationId: selected.parentInvocationId },
1305
- ...selected.rootSessionId === void 0 ? {} : { rootSessionId: selected.rootSessionId },
1306
- ...selected.agentInstanceId === void 0 ? {} : { agentInstanceId: selected.agentInstanceId },
1307
- provenance: input.provenance,
1308
- workspace,
1309
- startedAt,
1310
- consumerAttributes: input.consumerAttributes ?? {}
1311
- };
1312
- const parsed = invocationIdentitySchema.safeParse(candidate);
1313
- if (!parsed.success) {
1314
- return {
1315
- status: "invalid",
1316
- issues: parsed.error.issues.map(
1317
- (issue) => `${issue.path.join(".") || "<root>"}: ${issue.message}`
1318
- )
1319
- };
1570
+ if (isSecretResourceAttributeKey(key)) {
1571
+ return "secret-like";
1320
1572
  }
1321
- return { status: "resolved", identity: parsed.data };
1573
+ return void 0;
1322
1574
  };
1323
-
1324
- // src/model/version.ts
1325
- import { z as z11 } from "zod";
1326
- var CANONICAL_SCHEMA_VERSION = 1;
1327
- var canonicalSchemaVersionSchema = z11.literal(CANONICAL_SCHEMA_VERSION);
1328
-
1329
- // src/privacy/service.ts
1330
- import { createHash as createHash2 } from "crypto";
1331
-
1332
- // src/model/extensions.ts
1333
- import { z as z12 } from "zod";
1334
- var EXTENSION_KEY_PATTERN = /^[a-z][a-z0-9]*(?:[-_][a-z0-9]+)*(?:\.[a-z][a-z0-9]*(?:[-_][a-z0-9]+)*)+$/;
1335
- var RESERVED_EXTENSION_NAMESPACES = Object.freeze([
1336
- "otelhook",
1337
- "otel",
1338
- "telemetry"
1575
+ var resourceAttributeValueSchema = z14.union([
1576
+ z14.string().max(MAX_RESOURCE_ATTRIBUTE_VALUE_LENGTH),
1577
+ z14.number().finite(),
1578
+ z14.boolean()
1339
1579
  ]);
1340
- var MAX_EXTENSION_ENTRIES = 64;
1341
- var extensionKeyNamespace = (key) => key.slice(0, key.indexOf("."));
1342
- var isReservedExtensionNamespace = (key) => RESERVED_EXTENSION_NAMESPACES.includes(extensionKeyNamespace(key));
1343
- var isValidExtensionKey = (key) => EXTENSION_KEY_PATTERN.test(key) && !isReservedExtensionNamespace(key);
1344
- var extensionsSchema = z12.record(z12.string(), attributeValueSchema).check((ctx) => {
1345
- const keys = Object.keys(ctx.value);
1346
- if (keys.length > MAX_EXTENSION_ENTRIES) {
1347
- ctx.issues.push({
1580
+ var resourceAttributesSchema = z14.record(z14.string(), resourceAttributeValueSchema).superRefine((value, ctx) => {
1581
+ const keys = Object.keys(value);
1582
+ if (keys.length > MAX_RESOURCE_ATTRIBUTES) {
1583
+ ctx.addIssue({
1348
1584
  code: "custom",
1349
- input: ctx.value,
1350
- message: `extensions may contain at most ${MAX_EXTENSION_ENTRIES} entries`
1585
+ message: `at most ${String(MAX_RESOURCE_ATTRIBUTES)} resource attributes are accepted`
1351
1586
  });
1352
1587
  }
1353
1588
  for (const key of keys) {
1354
- if (!EXTENSION_KEY_PATTERN.test(key)) {
1355
- ctx.issues.push({
1356
- code: "custom",
1357
- input: ctx.value,
1358
- path: [key],
1359
- message: `extension key ${JSON.stringify(key)} must be namespaced, e.g. "acme.tier"`
1360
- });
1361
- continue;
1362
- }
1363
- if (isReservedExtensionNamespace(key)) {
1364
- ctx.issues.push({
1589
+ const rejection = checkResourceAttributeKey(key);
1590
+ if (rejection !== void 0) {
1591
+ ctx.addIssue({
1365
1592
  code: "custom",
1366
- input: ctx.value,
1367
1593
  path: [key],
1368
- message: `extension namespace ${JSON.stringify(extensionKeyNamespace(key))} is reserved`
1594
+ message: RESOURCE_ATTRIBUTE_KEY_REJECTION_DETAIL[rejection]
1369
1595
  });
1370
1596
  }
1371
1597
  }
1598
+ }).readonly();
1599
+ var EMPTY_RESOURCE_ATTRIBUTES = Object.freeze({});
1600
+
1601
+ // src/config/schema.ts
1602
+ var logsPolicySchema = z15.strictObject({
1603
+ enabled: z15.boolean(),
1604
+ /**
1605
+ * Full URL for the logs signal.
1606
+ *
1607
+ * Absent, it is derived from `endpoint`: a trailing `/v1/traces` becomes
1608
+ * `/v1/logs`, and an endpoint with no signal path has `/v1/logs` appended.
1609
+ */
1610
+ endpoint: z15.string().url().max(2048).optional(),
1611
+ includeContent: z15.boolean(),
1612
+ maxBatchSize: z15.number().int().min(1).max(4096)
1613
+ });
1614
+ var DEFAULT_LOGS_POLICY = Object.freeze({
1615
+ enabled: false,
1616
+ includeContent: false,
1617
+ maxBatchSize: 128
1618
+ });
1619
+ var exporterPolicySchema = z15.strictObject({
1620
+ enabled: z15.boolean(),
1621
+ protocol: z15.enum(["http/protobuf", "http/json", "none"]),
1622
+ endpoint: z15.string().url().max(2048).optional(),
1623
+ /**
1624
+ * Header names only. Values are supplied separately at construction time and
1625
+ * are never part of a resolved-config snapshot, which is logged and exported.
1626
+ */
1627
+ headerNames: z15.array(nonEmptyStringSchema).max(32).readonly(),
1628
+ timeoutMillis: z15.number().int().min(1).max(6e5),
1629
+ maxBatchSize: z15.number().int().min(1).max(4096),
1630
+ maxQueueSize: z15.number().int().min(1).max(65536),
1631
+ maxRetryAttempts: z15.number().int().min(0).max(10),
1632
+ serviceName: nonEmptyStringSchema,
1633
+ serviceNamespace: nonEmptyStringSchema.optional(),
1634
+ /**
1635
+ * Custom attributes merged into the exported OTLP Resource.
1636
+ *
1637
+ * Bounded and validated, and refusing `service.name`/`service.namespace`,
1638
+ * which are the two fields above. Distinct from an invocation's
1639
+ * `consumerAttributes`: this describes the emitting deployment, carries no
1640
+ * identity, and is the same for every span this process exports.
1641
+ */
1642
+ resourceAttributes: resourceAttributesSchema,
1643
+ /**
1644
+ * The logs signal. Nested under the exporter because it shares the endpoint,
1645
+ * headers, timeout, protocol, service identity, and resource attributes above —
1646
+ * a second top-level section would invite two of each to drift apart.
1647
+ */
1648
+ logs: logsPolicySchema,
1649
+ /**
1650
+ * Additional OTLP destinations, each sent every batch in parallel.
1651
+ *
1652
+ * Absent (the default), the exporter has exactly one destination — the
1653
+ * single-endpoint settings above, named `default` — and behaves exactly as it
1654
+ * did before this list existed. See `destinations.ts`.
1655
+ *
1656
+ * Merged as one leaf: a higher layer that sets the list replaces it whole,
1657
+ * because "the union of two partial lists" has no answer an operator could
1658
+ * predict.
1659
+ */
1660
+ destinations: exportDestinationsSchema.optional(),
1661
+ /**
1662
+ * Per-destination retry spool bounds, each optional and merged per leaf; any
1663
+ * bound left unset takes its value from `DEFAULT_SPOOL_POLICY`.
1664
+ */
1665
+ spool: spoolPolicySchema.partial().optional()
1666
+ });
1667
+ var detectionPolicySchema = z15.strictObject({
1668
+ /** Detections below this confidence resolve to the unknown provider. */
1669
+ minimumConfidence: detectionConfidenceSchema,
1670
+ /** When false, an ambiguous detection is an error rather than unknown. */
1671
+ allowAmbiguousFallback: z15.boolean(),
1672
+ /** Optional allow-list of provider ids; empty means "any registered". */
1673
+ allowedProviderIds: z15.array(nonEmptyStringSchema).max(32).readonly()
1674
+ });
1675
+ var diagnosticsPolicySchema = z15.strictObject({
1676
+ logLevel: z15.enum(["silent", "error", "warn", "info", "debug"]),
1677
+ /** Emit `error.raised` events for contained failures. */
1678
+ emitErrorEvents: z15.boolean()
1679
+ });
1680
+ var providersPolicySchema = z15.strictObject({
1681
+ claudeCode: z15.strictObject({
1682
+ readTranscriptUsage: z15.boolean()
1683
+ }).optional()
1684
+ });
1685
+ var otelHookConfigSchema = z15.strictObject({
1686
+ exporter: exporterPolicySchema,
1687
+ privacy: privacyPolicySchema,
1688
+ detection: detectionPolicySchema,
1689
+ diagnostics: diagnosticsPolicySchema,
1690
+ /** Optional so a hand-built configuration from before it existed stays valid. */
1691
+ providers: providersPolicySchema.optional()
1692
+ });
1693
+ var otelHookConfigPatchSchema = z15.strictObject({
1694
+ // `logs` is unwrapped and re-partialled for the same reason `privacy.limits` is:
1695
+ // merging happens per leaf, so a layer must be able to set `logs.enabled` alone
1696
+ // without also restating the endpoint and the batch size.
1697
+ exporter: exporterPolicySchema.omit({ logs: true, spool: true }).partial().extend({
1698
+ logs: logsPolicySchema.partial().optional(),
1699
+ spool: spoolPolicySchema.partial().optional()
1700
+ }).optional(),
1701
+ privacy: privacyPolicySchema.omit({ limits: true }).partial().extend({ limits: privacyPolicySchema.shape.limits.partial().optional() }).optional(),
1702
+ detection: detectionPolicySchema.partial().optional(),
1703
+ diagnostics: diagnosticsPolicySchema.partial().optional(),
1704
+ providers: z15.strictObject({
1705
+ claudeCode: z15.strictObject({ readTranscriptUsage: z15.boolean() }).partial().optional()
1706
+ }).partial().optional()
1707
+ });
1708
+ var DEFAULT_EXPORTER_POLICY = Object.freeze({
1709
+ enabled: true,
1710
+ protocol: "http/protobuf",
1711
+ headerNames: Object.freeze([]),
1712
+ timeoutMillis: 1e4,
1713
+ maxBatchSize: 128,
1714
+ maxQueueSize: 2048,
1715
+ maxRetryAttempts: 2,
1716
+ serviceName: "coding-agent",
1717
+ resourceAttributes: EMPTY_RESOURCE_ATTRIBUTES,
1718
+ logs: DEFAULT_LOGS_POLICY
1719
+ });
1720
+ var DEFAULT_DETECTION_POLICY = Object.freeze({
1721
+ minimumConfidence: "strong",
1722
+ allowAmbiguousFallback: true,
1723
+ allowedProviderIds: Object.freeze([])
1724
+ });
1725
+ var DEFAULT_DIAGNOSTICS_POLICY = Object.freeze({
1726
+ logLevel: "warn",
1727
+ emitErrorEvents: true
1728
+ });
1729
+ var DEFAULT_PROVIDERS_POLICY = Object.freeze({
1730
+ claudeCode: Object.freeze({ readTranscriptUsage: false })
1731
+ });
1732
+ var DEFAULT_CONFIG = Object.freeze({
1733
+ exporter: DEFAULT_EXPORTER_POLICY,
1734
+ privacy: DEFAULT_PRIVACY_POLICY,
1735
+ detection: DEFAULT_DETECTION_POLICY,
1736
+ diagnostics: DEFAULT_DIAGNOSTICS_POLICY,
1737
+ providers: DEFAULT_PROVIDERS_POLICY
1372
1738
  });
1373
- var EMPTY_EXTENSIONS = Object.freeze({});
1374
- var emptyExtensions = () => ({});
1375
1739
 
1376
1740
  // src/privacy/service.ts
1741
+ import { createHash as createHash2 } from "crypto";
1377
1742
  var compilePatterns = (sources, flags) => {
1378
1743
  const compiled = [];
1379
1744
  for (const source of sources) {
@@ -1716,231 +2081,27 @@ var createPrivacyService = (policyInput) => {
1716
2081
  };
1717
2082
 
1718
2083
  // src/providers/adapter.ts
1719
- import { z as z15 } from "zod";
1720
-
1721
- // src/model/events.ts
1722
- import { z as z14 } from "zod";
1723
-
1724
- // src/model/target.ts
1725
- import { z as z13 } from "zod";
1726
- var targetSourceSchema = z13.enum(["tool-path", "shell-cwd", "session-cwd"]);
1727
- var MAX_TARGET_HINT_PATHS = 8;
1728
- var MAX_TARGET_PATH_LENGTH = 4096;
1729
- var localPathSchema = z13.string().min(1).max(MAX_TARGET_PATH_LENGTH).refine((value) => !value.includes("\0"), "path must not contain NUL");
1730
- var targetHintSchema = z13.strictObject({
1731
- source: targetSourceSchema,
1732
- paths: z13.array(localPathSchema).min(1).max(MAX_TARGET_HINT_PATHS).readonly(),
1733
- /** Absolute directory that relative `paths` resolve against. */
1734
- baseDirectory: localPathSchema.optional()
1735
- }).readonly();
1736
- var worktreeKindSchema = z13.enum(["main", "linked"]);
1737
- var workspaceTargetSchema = z13.strictObject({
1738
- workspaceId: workspaceIdSchema,
1739
- /** Branch checked out in that worktree; absent on a detached HEAD. */
1740
- vcsBranchName: nonEmptyStringSchema.optional(),
1741
- source: targetSourceSchema,
1742
- /** `git-root` handle of the repository's main worktree; absent when there is none to name. */
1743
- repositoryId: workspaceIdSchema.optional(),
1744
- worktreeKind: worktreeKindSchema.optional()
1745
- }).readonly();
1746
- var SUBAGENT_ID_PATTERN = /^[A-Za-z0-9_.:@+=-]{1,256}$/;
1747
- var subagentIdSchema = z13.string().regex(SUBAGENT_ID_PATTERN);
1748
-
1749
- // src/model/events.ts
1750
- var modelDescriptorSchema = z14.strictObject({
1751
- modelId: nonEmptyStringSchema,
1752
- /** Vendor of the model, e.g. `anthropic`. Distinct from the agent provider. */
1753
- vendor: nonEmptyStringSchema.optional(),
1754
- family: nonEmptyStringSchema.optional()
1755
- });
1756
- var costFactsSchema = z14.strictObject({
1757
- /** ISO 4217 code. */
1758
- currency: z14.string().length(3),
1759
- amount: z14.number().min(0).finite(),
1760
- source: z14.enum(["provider-reported", "computed"])
1761
- });
1762
- var canonicalEventTypeSchema = z14.enum([
1763
- "session.start",
1764
- "session.end",
1765
- "prompt.submitted",
1766
- "generation.start",
1767
- "generation.end",
1768
- "tool.start",
1769
- "tool.end",
1770
- "subagent.start",
1771
- "subagent.end",
1772
- "compaction.performed",
1773
- "error.raised"
1774
- ]);
1775
- var CANONICAL_EVENT_TYPES = canonicalEventTypeSchema.options;
1776
- var outcomeSchema = z14.enum(["ok", "error", "cancelled", "timeout", "denied", "unknown"]);
1777
- var baseEventFields = {
1778
- schemaVersion: canonicalSchemaVersionSchema,
1779
- eventId: eventIdSchema,
1780
- invocationId: invocationIdSchema,
1781
- sessionId: sessionIdSchema,
1782
- /** Per-invocation ordering key. Stable across replays of the same input. */
1783
- sequence: sequenceNumberSchema,
1784
- occurredAt: epochMillisSchema,
1785
- provenance: sourceProvenanceSchema,
1786
- workspace: workspaceIdentitySchema,
1787
- /**
1788
- * The provider's own id for the subagent this event was emitted inside (e.g.
1789
- * Claude Code's `agent_id`). Absent for the top-level agent. Set by the event
1790
- * factory, never by hand.
1791
- */
1792
- subagentId: subagentIdSchema.optional(),
1793
- extensions: extensionsSchema.default(emptyExtensions)
1794
- };
1795
- var event = (shape) => z14.strictObject({ ...baseEventFields, ...shape });
1796
- var sessionStartEventSchema = event({
1797
- type: z14.literal("session.start"),
1798
- sessionKind: z14.enum(["interactive", "non-interactive", "unknown"]),
1799
- agentName: nonEmptyStringSchema.optional(),
1800
- agentVersion: nonEmptyStringSchema.optional(),
1801
- model: modelDescriptorSchema.optional(),
1802
- /** The git worktree the session runs in, resolved by the core (ADR 0008). */
1803
- target: workspaceTargetSchema.optional()
1804
- });
1805
- var sessionEndEventSchema = event({
1806
- type: z14.literal("session.end"),
1807
- reason: z14.enum(["completed", "aborted", "error", "timeout", "unknown"]),
1808
- durationMillis: durationMillisSchema.optional(),
1809
- /** Session totals, typically cumulative. */
1810
- usage: canonicalUsageSchema.optional(),
1811
- cost: costFactsSchema.optional()
1812
- });
1813
- var promptSubmittedEventSchema = event({
1814
- type: z14.literal("prompt.submitted"),
1815
- promptSource: z14.enum(["user", "automation", "resumed", "unknown"]),
1816
- content: contentFactSchema.optional(),
1817
- turnIndex: z14.number().int().min(0).optional(),
1818
- /** The git worktree the session runs in, resolved by the core (ADR 0008). */
1819
- target: workspaceTargetSchema.optional()
1820
- });
1821
- var generationStartEventSchema = event({
1822
- type: z14.literal("generation.start"),
1823
- generationId: nonEmptyStringSchema,
1824
- model: modelDescriptorSchema,
1825
- requestedMaxOutputTokens: tokenCountSchema.optional(),
1826
- inputContent: contentFactsSchema.optional()
1827
- });
1828
- var generationEndEventSchema = event({
1829
- type: z14.literal("generation.end"),
1830
- generationId: nonEmptyStringSchema,
1831
- model: modelDescriptorSchema,
1832
- outcome: outcomeSchema,
1833
- stopReason: nonEmptyStringSchema.optional(),
1834
- durationMillis: durationMillisSchema.optional(),
1835
- usage: canonicalUsageSchema.optional(),
1836
- cost: costFactsSchema.optional(),
1837
- outputContent: contentFactsSchema.optional()
1838
- });
1839
- var toolKindSchema = z14.enum([
1840
- "read",
1841
- "write",
1842
- "execute",
1843
- "search",
1844
- "network",
1845
- "delegate",
1846
- "other",
1847
- "unknown"
1848
- ]);
1849
- var toolStartEventSchema = event({
1850
- type: z14.literal("tool.start"),
1851
- toolCallId: nonEmptyStringSchema,
1852
- toolName: nonEmptyStringSchema,
1853
- toolKind: toolKindSchema,
1854
- generationId: nonEmptyStringSchema.optional(),
1855
- input: contentFactSchema.optional(),
1856
- /** The git worktree this call targeted, resolved by the core (ADR 0008). */
1857
- target: workspaceTargetSchema.optional()
1858
- });
1859
- var toolEndEventSchema = event({
1860
- type: z14.literal("tool.end"),
1861
- toolCallId: nonEmptyStringSchema,
1862
- toolName: nonEmptyStringSchema,
1863
- outcome: outcomeSchema,
1864
- durationMillis: durationMillisSchema.optional(),
1865
- /** Present when the host asked for or recorded a permission decision. */
1866
- permissionDecision: z14.enum(["allowed", "denied", "deferred", "not-required"]).optional(),
1867
- output: contentFactSchema.optional(),
1868
- /** The git worktree this call targeted, resolved by the core (ADR 0008). */
1869
- target: workspaceTargetSchema.optional()
1870
- });
1871
- var subagentStartEventSchema = event({
1872
- type: z14.literal("subagent.start"),
1873
- subagentInvocationId: invocationIdSchema,
1874
- subagentType: nonEmptyStringSchema.optional(),
1875
- /** 0 for the top-level agent; 1 for its direct children. */
1876
- delegationDepth: z14.number().int().min(0).max(64),
1877
- model: modelDescriptorSchema.optional()
1878
- });
1879
- var subagentEndEventSchema = event({
1880
- type: z14.literal("subagent.end"),
1881
- subagentInvocationId: invocationIdSchema,
1882
- outcome: outcomeSchema,
1883
- durationMillis: durationMillisSchema.optional(),
1884
- usage: canonicalUsageSchema.optional()
1885
- });
1886
- var compactionPerformedEventSchema = event({
1887
- type: z14.literal("compaction.performed"),
1888
- trigger: z14.enum(["automatic", "manual", "unknown"]),
1889
- /** Provider-reported context size before and after compaction, if known. */
1890
- contextTokensBefore: tokenCountSchema.optional(),
1891
- contextTokensAfter: tokenCountSchema.optional(),
1892
- droppedMessageCount: z14.number().int().min(0).optional(),
1893
- usage: canonicalUsageSchema.optional()
1894
- });
1895
- var errorRaisedEventSchema = event({
1896
- type: z14.literal("error.raised"),
1897
- errorCode: otelHookErrorCodeSchema,
1898
- severity: errorSeveritySchema,
1899
- phase: errorPhaseSchema,
1900
- retryable: z14.boolean(),
1901
- /** Error text is content: it is described, never embedded verbatim by default. */
1902
- message: contentFactSchema.optional(),
1903
- /** Non-sensitive, provider-agnostic short label. */
1904
- detail: nonEmptyStringSchema.optional()
1905
- });
1906
- var canonicalEventSchema = z14.discriminatedUnion("type", [
1907
- sessionStartEventSchema,
1908
- sessionEndEventSchema,
1909
- promptSubmittedEventSchema,
1910
- generationStartEventSchema,
1911
- generationEndEventSchema,
1912
- toolStartEventSchema,
1913
- toolEndEventSchema,
1914
- subagentStartEventSchema,
1915
- subagentEndEventSchema,
1916
- compactionPerformedEventSchema,
1917
- errorRaisedEventSchema
1918
- ]);
1919
- var TARGETED_EVENT_TYPES = ["session.start", "prompt.submitted", "tool.start", "tool.end"];
1920
- var TARGETED = new Set(TARGETED_EVENT_TYPES);
1921
- var isTargetedEvent = (event2) => TARGETED.has(event2.type);
1922
-
1923
- // src/providers/adapter.ts
1924
- var providerDetectionSchema = z15.strictObject({
2084
+ import { z as z16 } from "zod";
2085
+ var providerDetectionSchema = z16.strictObject({
1925
2086
  providerId: resolvedProviderIdSchema,
1926
2087
  confidence: detectionConfidenceSchema,
1927
2088
  /**
1928
2089
  * Short, non-sensitive justifications, e.g. `"payload.hook_event_name present"`.
1929
2090
  * Reasons are exported in diagnostics, so they must not quote payload values.
1930
2091
  */
1931
- reasons: z15.array(z15.string().min(1).max(160)).max(8),
2092
+ reasons: z16.array(z16.string().min(1).max(160)).max(8),
1932
2093
  providerVersion: nonEmptyStringSchema.optional(),
1933
2094
  /** The provider's own name for this event, when the payload states one. */
1934
2095
  sourceEventName: nonEmptyStringSchema.optional()
1935
2096
  });
1936
- var deliveryIdentifierSupportSchema = z15.enum(["none", "partial", "all"]);
2097
+ var deliveryIdentifierSupportSchema = z16.enum(["none", "partial", "all"]);
1937
2098
  var DELIVERY_COMPONENT_PATTERN = /^[A-Za-z0-9_.:@+=-]{1,256}$/;
1938
- var deliveryComponentSchema = z15.string().regex(
2099
+ var deliveryComponentSchema = z16.string().regex(
1939
2100
  DELIVERY_COMPONENT_PATTERN,
1940
2101
  "delivery component must be identifier-shaped: no whitespace, no path separators"
1941
2102
  );
1942
2103
  var MAX_DELIVERY_COMPONENTS = 8;
1943
- var providerDeliveryClaimSchema = z15.strictObject({
2104
+ var providerDeliveryClaimSchema = z16.strictObject({
1944
2105
  /**
1945
2106
  * The provider's own session/conversation id. Scopes the callback identity, so
1946
2107
  * two sessions reusing one tool-call id never collide.
@@ -1952,26 +2113,26 @@ var providerDeliveryClaimSchema = z15.strictObject({
1952
2113
  * Identifier-shaped payload fields that, together with `sourceEventName`,
1953
2114
  * name this callback within the session exactly once.
1954
2115
  */
1955
- components: z15.array(deliveryComponentSchema).min(1).max(MAX_DELIVERY_COMPONENTS).readonly(),
2116
+ components: z16.array(deliveryComponentSchema).min(1).max(MAX_DELIVERY_COMPONENTS).readonly(),
1956
2117
  /**
1957
2118
  * Short, non-sensitive justifications, e.g. `"payload.tool_use_id names one
1958
2119
  * tool call"`. Evidence reaches diagnostics, so it must name fields, never
1959
2120
  * quote their values.
1960
2121
  */
1961
- evidence: z15.array(z15.string().min(1).max(160)).min(1).max(4).readonly()
2122
+ evidence: z16.array(z16.string().min(1).max(160)).min(1).max(4).readonly()
1962
2123
  });
1963
2124
  var DELIVERY_GAP_REASON_PATTERN = /^[^\n\r\t\\/]{1,240}$/;
1964
- var deliveryGapReasonSchema = z15.string().regex(
2125
+ var deliveryGapReasonSchema = z16.string().regex(
1965
2126
  DELIVERY_GAP_REASON_PATTERN,
1966
2127
  "delivery gap reason must be one line of prose: no path separators, no control characters"
1967
2128
  );
1968
2129
  var MAX_DELIVERY_GAPS = 48;
1969
- var providerDeliveryGapsSchema = z15.record(deliveryComponentSchema, deliveryGapReasonSchema).refine((gaps) => Object.keys(gaps).length <= MAX_DELIVERY_GAPS, {
2130
+ var providerDeliveryGapsSchema = z16.record(deliveryComponentSchema, deliveryGapReasonSchema).refine((gaps) => Object.keys(gaps).length <= MAX_DELIVERY_GAPS, {
1970
2131
  message: `at most ${String(MAX_DELIVERY_GAPS)} delivery gaps may be declared`
1971
2132
  });
1972
- var providerCapabilitiesSchema = z15.strictObject({
2133
+ var providerCapabilitiesSchema = z16.strictObject({
1973
2134
  /** Event types the adapter can produce. */
1974
- lifecycleEvents: z15.array(canonicalEventTypeSchema).max(32).readonly(),
2135
+ lifecycleEvents: z16.array(canonicalEventTypeSchema).max(32).readonly(),
1975
2136
  usageTemporality: usageTemporalitySchema,
1976
2137
  /**
1977
2138
  * Which accumulator series a `cumulative` report continues — that is, which
@@ -1990,32 +2151,32 @@ var providerCapabilitiesSchema = z15.strictObject({
1990
2151
  * Subagent snapshots keep their own series regardless: a delegated agent's
1991
2152
  * counter is not a point on the parent session's curve.
1992
2153
  */
1993
- cumulativeUsageSeries: z15.enum(["event-scope", "session-lifetime"]).optional(),
1994
- reportsCachedInput: z15.boolean(),
1995
- reportsCacheCreation: z15.boolean(),
2154
+ cumulativeUsageSeries: z16.enum(["event-scope", "session-lifetime"]).optional(),
2155
+ reportsCachedInput: z16.boolean(),
2156
+ reportsCacheCreation: z16.boolean(),
1996
2157
  cacheCreationAccounting: cacheCreationAccountingSchema,
1997
- reportsReasoningOutput: z15.boolean(),
1998
- reportsProviderTotal: z15.boolean(),
1999
- reportsCost: z15.boolean(),
2000
- emitsSubagentEvents: z15.boolean(),
2001
- emitsCompactionEvents: z15.boolean(),
2158
+ reportsReasoningOutput: z16.boolean(),
2159
+ reportsProviderTotal: z16.boolean(),
2160
+ reportsCost: z16.boolean(),
2161
+ emitsSubagentEvents: z16.boolean(),
2162
+ emitsCompactionEvents: z16.boolean(),
2002
2163
  /** True when the provider reads a structured response from stdout. */
2003
- requiresHookResponse: z15.boolean(),
2164
+ requiresHookResponse: z16.boolean(),
2004
2165
  /** How much of this provider's hook traffic is replay-identifiable. */
2005
2166
  deliveryIdentifier: deliveryIdentifierSupportSchema
2006
2167
  });
2007
- var providerHookResponseSchema = z15.strictObject({
2168
+ var providerHookResponseSchema = z16.strictObject({
2008
2169
  /**
2009
2170
  * Always 0. A telemetry hook that can fail the host agent is a liability, so
2010
2171
  * the type forbids expressing anything else (ADR 0004).
2011
2172
  */
2012
- exitCode: z15.literal(0),
2173
+ exitCode: z16.literal(0),
2013
2174
  /** Protocol response text. Omit to write nothing at all. */
2014
- stdout: z15.string().max(8192).optional(),
2175
+ stdout: z16.string().max(8192).optional(),
2015
2176
  /** Non-sensitive diagnostic text for stderr. */
2016
- stderr: z15.string().max(8192).optional(),
2177
+ stderr: z16.string().max(8192).optional(),
2017
2178
  /** Declares which of the two stdout contracts this response follows. */
2018
- contract: z15.enum(["silent", "provider-protocol"])
2179
+ contract: z16.enum(["silent", "provider-protocol"])
2019
2180
  });
2020
2181
  var SILENT_HOOK_RESPONSE = Object.freeze({
2021
2182
  exitCode: 0,
@@ -2347,7 +2508,7 @@ var withOptionalSessionLock = async (store, sessionId, fn, options) => {
2347
2508
  };
2348
2509
 
2349
2510
  // src/runtime/hook.ts
2350
- var usageScopeSchema = z16.enum(["session", "generation", "subagent"]);
2511
+ var usageScopeSchema = z17.enum(["session", "generation", "subagent"]);
2351
2512
  var classifyDurability = (input) => {
2352
2513
  if (!input.attempted) {
2353
2514
  return "nothing-to-deliver";
@@ -2405,6 +2566,22 @@ var usageScopeOf = (event2) => {
2405
2566
  }
2406
2567
  };
2407
2568
  var sequenceKey = (sessionId) => `sequence:${sessionId}`;
2569
+ var sessionModelKey = (sessionId) => `model:${sessionId}`;
2570
+ var readCursorKey = (enricherId, sessionId) => `cursor:${enricherId}:${sessionId}`;
2571
+ var UNKNOWN_MODEL_ID = "unknown";
2572
+ var latestSessionModel = (events) => {
2573
+ let latest;
2574
+ for (const event2 of events) {
2575
+ if (event2.subagentId !== void 0) {
2576
+ continue;
2577
+ }
2578
+ if ((event2.type === "session.start" || event2.type === "generation.start" || event2.type === "generation.end") && event2.model !== void 0 && event2.model.modelId !== UNKNOWN_MODEL_ID) {
2579
+ latest = event2.model;
2580
+ }
2581
+ }
2582
+ return latest;
2583
+ };
2584
+ var sameModel = (left, right) => left !== void 0 && left.modelId === right.modelId && left.vendor === right.vendor && left.family === right.family;
2408
2585
  var usageKey = (sessionId, scope, scopeKey) => `usage:${sessionId}:${scope}:${scopeKey}`;
2409
2586
  var baselineScopeOf = (scope, scopeKey, sessionId, series) => series === "session-lifetime" && scope === "generation" ? { scope: "session", scopeKey: sessionId } : { scope, scopeKey };
2410
2587
  var createOtelHook = (deps) => {
@@ -2452,6 +2629,66 @@ var createOtelHook = (deps) => {
2452
2629
  return 0;
2453
2630
  }
2454
2631
  };
2632
+ const enrichPayload = async (payload, providerId, sessionId, diagnostics) => {
2633
+ let current = payload;
2634
+ for (const enricher of deps.payloadEnrichers ?? []) {
2635
+ if (enricher.providerId !== providerId) {
2636
+ continue;
2637
+ }
2638
+ const key = readCursorKey(enricher.id, sessionId);
2639
+ let cursor;
2640
+ try {
2641
+ const record = await deps.stateStore.read(key);
2642
+ if (record?.value.kind === "read-cursor") {
2643
+ cursor = { source: record.value.source, offset: record.value.offset };
2644
+ }
2645
+ } catch (thrown) {
2646
+ diagnostics.push(
2647
+ errorInfoFromThrown(thrown, { code: "state-store-failure", phase: "state", occurredAt: clock.now() })
2648
+ );
2649
+ continue;
2650
+ }
2651
+ let result;
2652
+ try {
2653
+ result = await enricher.enrich({ payload: current, sessionId, ...cursor === void 0 ? {} : { cursor } });
2654
+ } catch (thrown) {
2655
+ logger.warn("payload enricher failed; parsing the payload as delivered", {
2656
+ "enricher.id": enricher.id,
2657
+ "error.name": thrown instanceof Error ? thrown.name : typeof thrown
2658
+ });
2659
+ continue;
2660
+ }
2661
+ current = result.payload;
2662
+ if (result.notes !== void 0 && result.notes.length > 0) {
2663
+ logger.debug("payload enricher notes", {
2664
+ "enricher.id": enricher.id,
2665
+ "enricher.notes": result.notes.slice(0, 8).map((note) => note.slice(0, 200))
2666
+ });
2667
+ }
2668
+ const next = result.cursor;
2669
+ if (next !== void 0 && (next.source !== cursor?.source || next.offset !== cursor.offset)) {
2670
+ try {
2671
+ await deps.stateStore.write(key, { kind: "read-cursor", source: next.source, offset: next.offset });
2672
+ } catch (thrown) {
2673
+ diagnostics.push(
2674
+ errorInfoFromThrown(thrown, { code: "state-store-failure", phase: "state", occurredAt: clock.now() })
2675
+ );
2676
+ }
2677
+ }
2678
+ }
2679
+ return current;
2680
+ };
2681
+ const readSessionModel = async (sessionId, diagnostics) => {
2682
+ try {
2683
+ const record = await deps.stateStore.read(sessionModelKey(sessionId));
2684
+ return record?.value.kind === "session-model" ? record.value.model : void 0;
2685
+ } catch (thrown) {
2686
+ diagnostics.push(
2687
+ errorInfoFromThrown(thrown, { code: "state-store-failure", phase: "state", occurredAt: clock.now() })
2688
+ );
2689
+ return void 0;
2690
+ }
2691
+ };
2455
2692
  const deriveUsage = async (events, diagnostics, suppress, series) => {
2456
2693
  const observations = [];
2457
2694
  for (const event2 of events) {
@@ -2772,10 +3009,19 @@ var createOtelHook = (deps) => {
2772
3009
  const identity = resolution.identity;
2773
3010
  const prepare = async () => {
2774
3011
  const sequenceBase = await readSequenceBase(identity.sessionId, diagnostics);
3012
+ const sessionModel = await readSessionModel(identity.sessionId, diagnostics);
3013
+ const payload = suppress ? detectionInput.payload : await enrichPayload(detectionInput.payload, detection.providerId, identity.sessionId, diagnostics);
2775
3014
  let parsed;
2776
3015
  try {
2777
3016
  parsed = adapter.parse(
2778
- { ...detectionInput, detection, identity, sequenceBase },
3017
+ {
3018
+ ...detectionInput,
3019
+ payload,
3020
+ detection,
3021
+ identity,
3022
+ sequenceBase,
3023
+ ...sessionModel === void 0 ? {} : { sessionModel }
3024
+ },
2779
3025
  providerContext
2780
3026
  );
2781
3027
  } catch (thrown) {
@@ -2885,6 +3131,23 @@ var createOtelHook = (deps) => {
2885
3131
  })
2886
3132
  );
2887
3133
  }
3134
+ const reportedModel = latestSessionModel(screened.kept);
3135
+ if (reportedModel !== void 0 && !sameModel(sessionModel, reportedModel)) {
3136
+ try {
3137
+ await deps.stateStore.write(sessionModelKey(identity.sessionId), {
3138
+ kind: "session-model",
3139
+ model: reportedModel
3140
+ });
3141
+ } catch (thrown) {
3142
+ diagnostics.push(
3143
+ errorInfoFromThrown(thrown, {
3144
+ code: "state-store-failure",
3145
+ phase: "state",
3146
+ occurredAt: clock.now()
3147
+ })
3148
+ );
3149
+ }
3150
+ }
2888
3151
  }
2889
3152
  return {
2890
3153
  kind: "ready",