@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/state.js CHANGED
@@ -77,65 +77,428 @@ var withOptionalSessionLock = async (store, sessionId, fn, options) => {
77
77
  };
78
78
 
79
79
  // src/runtime/ports.ts
80
+ import { z as z10 } from "zod";
81
+
82
+ // src/model/events.ts
83
+ import { z as z9 } from "zod";
84
+
85
+ // src/errors/taxonomy.ts
86
+ import { z } from "zod";
87
+ var otelHookErrorCodeSchema = z.enum([
88
+ /** Input was not usable at all (empty stdin, unparsable JSON). */
89
+ "invalid-input",
90
+ /** Input parsed but failed canonical schema validation. */
91
+ "schema-validation-failed",
92
+ /** No adapter claimed the input with sufficient confidence. */
93
+ "provider-unknown",
94
+ /** Several adapters claimed the input at the same confidence. */
95
+ "provider-detection-ambiguous",
96
+ /** An adapter threw or returned a malformed result. */
97
+ "provider-adapter-failure",
98
+ /** Two identity claims disagreed at equal confidence. */
99
+ "identity-conflict",
100
+ /** Required identity fields were absent. */
101
+ "identity-incomplete",
102
+ /** A usage report violated the canonical usage invariants. */
103
+ "usage-invalid",
104
+ /** The state store could not be read or written. */
105
+ "state-store-failure",
106
+ /** The telemetry sink rejected or could not deliver a batch. */
107
+ "telemetry-export-failure",
108
+ /** Content reached the sink boundary in a state the policy forbids. */
109
+ "privacy-policy-violation",
110
+ /** Configuration could not be resolved. */
111
+ "configuration-invalid",
112
+ /** A configured bound (events, batch size) dropped data. */
113
+ "limit-exceeded",
114
+ /**
115
+ * No replay-stable delivery identifier was available for a callback while
116
+ * deduplication was required.
117
+ */
118
+ "delivery-identifier-unavailable",
119
+ "delivery-claim-superseded",
120
+ /** Anything unanticipated. Always reported, never fatal to the host. */
121
+ "internal-error"
122
+ ]);
123
+ var errorSeveritySchema = z.enum(["warning", "error"]);
124
+ var errorPhaseSchema = z.enum([
125
+ "configuration",
126
+ "detection",
127
+ "identity",
128
+ "parsing",
129
+ "normalization",
130
+ "privacy",
131
+ "state",
132
+ "export",
133
+ "shutdown"
134
+ ]);
135
+ var failurePostureSchema = z.enum(["fail-open", "fail-closed-attribution"]);
136
+ var ERROR_TAXONOMY = Object.freeze({
137
+ "invalid-input": {
138
+ code: "invalid-input",
139
+ severity: "warning",
140
+ posture: "fail-open",
141
+ retryable: false,
142
+ summary: "Input could not be read or decoded."
143
+ },
144
+ "schema-validation-failed": {
145
+ code: "schema-validation-failed",
146
+ severity: "error",
147
+ posture: "fail-closed-attribution",
148
+ retryable: false,
149
+ summary: "A canonical event failed schema validation and was dropped."
150
+ },
151
+ "provider-unknown": {
152
+ code: "provider-unknown",
153
+ severity: "warning",
154
+ posture: "fail-closed-attribution",
155
+ retryable: false,
156
+ summary: "No adapter recognized the source provider; the input stays unattributed."
157
+ },
158
+ "provider-detection-ambiguous": {
159
+ code: "provider-detection-ambiguous",
160
+ severity: "warning",
161
+ posture: "fail-closed-attribution",
162
+ retryable: false,
163
+ summary: "Multiple adapters claimed the input at equal confidence."
164
+ },
165
+ "provider-adapter-failure": {
166
+ code: "provider-adapter-failure",
167
+ severity: "error",
168
+ posture: "fail-open",
169
+ retryable: false,
170
+ summary: "A provider adapter failed while parsing."
171
+ },
172
+ "identity-conflict": {
173
+ code: "identity-conflict",
174
+ severity: "error",
175
+ posture: "fail-closed-attribution",
176
+ retryable: false,
177
+ summary: "Identity claims disagreed; attribution was declined."
178
+ },
179
+ "identity-incomplete": {
180
+ code: "identity-incomplete",
181
+ severity: "warning",
182
+ posture: "fail-closed-attribution",
183
+ retryable: false,
184
+ summary: "Required identity fields were missing; attribution was declined."
185
+ },
186
+ "usage-invalid": {
187
+ code: "usage-invalid",
188
+ severity: "error",
189
+ posture: "fail-open",
190
+ retryable: false,
191
+ summary: "A usage report violated the canonical usage invariants."
192
+ },
193
+ "state-store-failure": {
194
+ code: "state-store-failure",
195
+ severity: "warning",
196
+ posture: "fail-open",
197
+ retryable: true,
198
+ summary: "State could not be read or written; derived values may be incomplete."
199
+ },
200
+ "telemetry-export-failure": {
201
+ code: "telemetry-export-failure",
202
+ severity: "warning",
203
+ posture: "fail-open",
204
+ retryable: true,
205
+ summary: "The telemetry sink could not accept a batch."
206
+ },
207
+ "privacy-policy-violation": {
208
+ code: "privacy-policy-violation",
209
+ severity: "error",
210
+ posture: "fail-closed-attribution",
211
+ retryable: false,
212
+ summary: "Content violated the resolved privacy policy and was dropped."
213
+ },
214
+ "configuration-invalid": {
215
+ code: "configuration-invalid",
216
+ severity: "error",
217
+ posture: "fail-open",
218
+ retryable: false,
219
+ summary: "Configuration could not be resolved; defaults apply."
220
+ },
221
+ "limit-exceeded": {
222
+ code: "limit-exceeded",
223
+ severity: "warning",
224
+ posture: "fail-open",
225
+ retryable: false,
226
+ summary: "A configured bound was reached and data was dropped."
227
+ },
228
+ "delivery-identifier-unavailable": {
229
+ code: "delivery-identifier-unavailable",
230
+ severity: "warning",
231
+ // Fail-open: the observation is still attributed and exported. Only the
232
+ // at-most-once guarantee is missing, and refusing the telemetry to protect
233
+ // a duplicate count would trade a certain loss for a possible one.
234
+ posture: "fail-open",
235
+ retryable: false,
236
+ summary: "No replay-stable delivery identifier was available; this callback was exported without deduplication."
237
+ },
238
+ "delivery-claim-superseded": {
239
+ code: "delivery-claim-superseded",
240
+ severity: "warning",
241
+ // Fail-open, and specifically *not* silent. A peer reclaimed this callback's
242
+ // claim while this process was still working on it, which means the
243
+ // configured stale window is shorter than this installation's real worst
244
+ // case. Both processes may now have exported the callback, so the
245
+ // at-most-once guarantee did not hold for it — the only honest response is
246
+ // to say so and let the operator raise the window.
247
+ posture: "fail-open",
248
+ retryable: false,
249
+ summary: "A delivery claim was reclaimed by another process before this one committed; the callback may have been exported twice."
250
+ },
251
+ "internal-error": {
252
+ code: "internal-error",
253
+ severity: "error",
254
+ posture: "fail-open",
255
+ retryable: false,
256
+ summary: "An unexpected failure was contained."
257
+ }
258
+ });
259
+ var attributionOutcomeSchema = z.enum([
260
+ /** Identity resolved; events carry provider and session identity. */
261
+ "attributed",
262
+ /** Identity could not be established safely; nothing was attributed. */
263
+ "declined",
264
+ /** Attribution was attempted and failed unexpectedly. */
265
+ "failed",
266
+ /** Input was recognized but intentionally carried no telemetry. */
267
+ "not-applicable"
268
+ ]);
269
+ var attributionReasonSchema = z.enum([
270
+ "provider-unknown",
271
+ "provider-detection-ambiguous",
272
+ "identity-conflict",
273
+ "identity-incomplete",
274
+ "adapter-ignored-input",
275
+ "adapter-failure",
276
+ "invalid-input",
277
+ "internal-error"
278
+ ]);
279
+
280
+ // src/model/content.ts
80
281
  import { z as z3 } from "zod";
81
282
 
82
283
  // src/model/primitives.ts
83
- import { z } from "zod";
284
+ import { z as z2 } from "zod";
84
285
  var MAX_IDENTIFIER_LENGTH = 256;
85
286
  var MAX_ATTRIBUTE_STRING_LENGTH = 4096;
86
287
  var MAX_ATTRIBUTE_ARRAY_LENGTH = 128;
87
- var nonEmptyStringSchema = z.string().min(1).max(MAX_IDENTIFIER_LENGTH);
88
- var epochMillisSchema = z.number().int().min(0).max(864e13);
89
- var durationMillisSchema = z.number().min(0).finite();
90
- var tokenCountSchema = z.number().int().min(0);
91
- var sequenceNumberSchema = z.number().int().min(0);
92
- var brandedIdSchema = () => z.string().min(1).max(MAX_IDENTIFIER_LENGTH);
288
+ var nonEmptyStringSchema = z2.string().min(1).max(MAX_IDENTIFIER_LENGTH);
289
+ var epochMillisSchema = z2.number().int().min(0).max(864e13);
290
+ var durationMillisSchema = z2.number().min(0).finite();
291
+ var tokenCountSchema = z2.number().int().min(0);
292
+ var sequenceNumberSchema = z2.number().int().min(0);
293
+ var brandedIdSchema = () => z2.string().min(1).max(MAX_IDENTIFIER_LENGTH);
93
294
  var invocationIdSchema = brandedIdSchema().brand();
94
295
  var sessionIdSchema = brandedIdSchema().brand();
95
296
  var eventIdSchema = brandedIdSchema().brand();
96
297
  var WORKSPACE_ID_PATTERN = /^[a-z][a-z0-9]{0,15}:[A-Za-z0-9_-]{8,128}$/;
97
- var workspaceIdSchema = z.string().regex(WORKSPACE_ID_PATTERN, "workspace id must be an opaque `<scheme>:<token>` handle").brand();
298
+ var workspaceIdSchema = z2.string().regex(WORKSPACE_ID_PATTERN, "workspace id must be an opaque `<scheme>:<token>` handle").brand();
98
299
  var PROVIDER_ID_PATTERN = /^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/;
99
- var providerIdSchema = z.string().min(1).max(64).regex(PROVIDER_ID_PATTERN, "provider id must be lowercase and hyphenated").brand();
300
+ var providerIdSchema = z2.string().min(1).max(64).regex(PROVIDER_ID_PATTERN, "provider id must be lowercase and hyphenated").brand();
100
301
  var UNKNOWN_PROVIDER_ID = "unknown";
101
- var resolvedProviderIdSchema = z.union([
302
+ var resolvedProviderIdSchema = z2.union([
102
303
  providerIdSchema,
103
- z.literal(UNKNOWN_PROVIDER_ID)
304
+ z2.literal(UNKNOWN_PROVIDER_ID)
104
305
  ]);
105
- var attributePrimitiveSchema = z.union([
106
- z.string().max(MAX_ATTRIBUTE_STRING_LENGTH),
107
- z.number().finite(),
108
- z.boolean()
306
+ var attributePrimitiveSchema = z2.union([
307
+ z2.string().max(MAX_ATTRIBUTE_STRING_LENGTH),
308
+ z2.number().finite(),
309
+ z2.boolean()
109
310
  ]);
110
- var attributeValueSchema = z.union([
311
+ var attributeValueSchema = z2.union([
111
312
  attributePrimitiveSchema,
112
- z.array(attributePrimitiveSchema).max(MAX_ATTRIBUTE_ARRAY_LENGTH)
313
+ z2.array(attributePrimitiveSchema).max(MAX_ATTRIBUTE_ARRAY_LENGTH)
113
314
  ]);
114
- var attributesSchema = z.record(z.string().min(1).max(MAX_IDENTIFIER_LENGTH), attributeValueSchema);
115
- var detectionConfidenceSchema = z.enum(["none", "weak", "strong", "exact"]);
315
+ var attributesSchema = z2.record(z2.string().min(1).max(MAX_IDENTIFIER_LENGTH), attributeValueSchema);
316
+ var detectionConfidenceSchema = z2.enum(["none", "weak", "strong", "exact"]);
116
317
  var DETECTION_CONFIDENCE_RANK = Object.freeze({
117
318
  none: 0,
118
319
  weak: 1,
119
320
  strong: 2,
120
321
  exact: 3
121
322
  });
122
- var sourceTransportSchema = z.enum([
323
+ var sourceTransportSchema = z2.enum([
123
324
  "hook-stdin",
124
325
  "cli-argument",
125
326
  "library-call",
126
327
  "test-fixture"
127
328
  ]);
128
329
 
330
+ // src/model/content.ts
331
+ var contentKindSchema = z3.enum([
332
+ "prompt",
333
+ "response",
334
+ "reasoning",
335
+ "tool-input",
336
+ "tool-output",
337
+ "error-message",
338
+ "system-instruction",
339
+ "attachment"
340
+ ]);
341
+ var contentRoleSchema = z3.enum(["user", "assistant", "system", "tool", "unknown"]);
342
+ var contentDisclosureSchema = z3.enum(["omitted", "masked", "redacted", "raw"]);
343
+ var CONTENT_HASH_PATTERN = /^sha256:[0-9a-f]{64}$/;
344
+ var contentFactSchema = z3.strictObject({
345
+ kind: contentKindSchema,
346
+ role: contentRoleSchema.optional(),
347
+ /** Unicode code point count of the original content. */
348
+ characterLength: z3.number().int().min(0),
349
+ /** UTF-8 byte length of the original content. */
350
+ byteLength: z3.number().int().min(0),
351
+ /** Stable salted digest of the original content. */
352
+ contentHash: z3.string().regex(CONTENT_HASH_PATTERN),
353
+ disclosure: contentDisclosureSchema,
354
+ /** Disclosed text, bounded by the privacy policy. Absent when omitted. */
355
+ text: z3.string().optional(),
356
+ /** True when `text` was cut short by the configured string bound. */
357
+ truncated: z3.boolean(),
358
+ /** Number of secret-looking spans replaced while producing `text`. */
359
+ secretsRedacted: z3.number().int().min(0),
360
+ /** Optional non-sensitive label, e.g. a MIME type or tool name. */
361
+ label: nonEmptyStringSchema.optional()
362
+ });
363
+ var contentFactsSchema = z3.array(contentFactSchema).max(64);
364
+
365
+ // src/model/extensions.ts
366
+ import { z as z4 } from "zod";
367
+ var EXTENSION_KEY_PATTERN = /^[a-z][a-z0-9]*(?:[-_][a-z0-9]+)*(?:\.[a-z][a-z0-9]*(?:[-_][a-z0-9]+)*)+$/;
368
+ var RESERVED_EXTENSION_NAMESPACES = Object.freeze([
369
+ "otelhook",
370
+ "otel",
371
+ "telemetry"
372
+ ]);
373
+ var MAX_EXTENSION_ENTRIES = 64;
374
+ var extensionKeyNamespace = (key) => key.slice(0, key.indexOf("."));
375
+ var isReservedExtensionNamespace = (key) => RESERVED_EXTENSION_NAMESPACES.includes(extensionKeyNamespace(key));
376
+ var extensionsSchema = z4.record(z4.string(), attributeValueSchema).check((ctx) => {
377
+ const keys = Object.keys(ctx.value);
378
+ if (keys.length > MAX_EXTENSION_ENTRIES) {
379
+ ctx.issues.push({
380
+ code: "custom",
381
+ input: ctx.value,
382
+ message: `extensions may contain at most ${MAX_EXTENSION_ENTRIES} entries`
383
+ });
384
+ }
385
+ for (const key of keys) {
386
+ if (!EXTENSION_KEY_PATTERN.test(key)) {
387
+ ctx.issues.push({
388
+ code: "custom",
389
+ input: ctx.value,
390
+ path: [key],
391
+ message: `extension key ${JSON.stringify(key)} must be namespaced, e.g. "acme.tier"`
392
+ });
393
+ continue;
394
+ }
395
+ if (isReservedExtensionNamespace(key)) {
396
+ ctx.issues.push({
397
+ code: "custom",
398
+ input: ctx.value,
399
+ path: [key],
400
+ message: `extension namespace ${JSON.stringify(extensionKeyNamespace(key))} is reserved`
401
+ });
402
+ }
403
+ }
404
+ });
405
+ var EMPTY_EXTENSIONS = Object.freeze({});
406
+ var emptyExtensions = () => ({});
407
+
408
+ // src/model/identity.ts
409
+ import { z as z5 } from "zod";
410
+ var workspaceKeySourceSchema = z5.enum([
411
+ "git-remote",
412
+ "git-root",
413
+ "working-directory",
414
+ "explicit",
415
+ "unknown"
416
+ ]);
417
+ var workspaceIdentitySchema = z5.strictObject({
418
+ workspaceId: workspaceIdSchema,
419
+ keySource: workspaceKeySourceSchema,
420
+ /** Repository name only; never an owner path or URL with credentials. */
421
+ repositoryName: nonEmptyStringSchema.optional(),
422
+ vcsBranchName: nonEmptyStringSchema.optional(),
423
+ /** Opaque handle for the checked-out revision. */
424
+ vcsRevisionId: nonEmptyStringSchema.optional()
425
+ }).readonly();
426
+ var sourceProvenanceSchema = z5.strictObject({
427
+ providerId: resolvedProviderIdSchema,
428
+ providerVersion: nonEmptyStringSchema.optional(),
429
+ adapterId: nonEmptyStringSchema,
430
+ adapterVersion: nonEmptyStringSchema,
431
+ detectionConfidence: detectionConfidenceSchema,
432
+ /** The provider's own name for the source event, e.g. a hook event name. */
433
+ sourceEventName: nonEmptyStringSchema.optional(),
434
+ transport: sourceTransportSchema
435
+ }).readonly();
436
+ var consumerAttributesSchema = attributesSchema.readonly();
437
+ var invocationIdentitySchema = z5.strictObject({
438
+ invocationId: invocationIdSchema,
439
+ sessionId: sessionIdSchema,
440
+ /** Set when this invocation runs beneath another agent invocation. */
441
+ parentInvocationId: invocationIdSchema.optional(),
442
+ /** Root of the session tree when the provider exposes one. */
443
+ rootSessionId: sessionIdSchema.optional(),
444
+ /** Stable handle for the agent process/instance, when available. */
445
+ agentInstanceId: nonEmptyStringSchema.optional(),
446
+ provenance: sourceProvenanceSchema,
447
+ workspace: workspaceIdentitySchema,
448
+ startedAt: epochMillisSchema,
449
+ consumerAttributes: consumerAttributesSchema
450
+ }).readonly();
451
+ var identityClaimFieldsSchema = z5.strictObject({
452
+ invocationId: invocationIdSchema.optional(),
453
+ sessionId: sessionIdSchema.optional(),
454
+ parentInvocationId: invocationIdSchema.optional(),
455
+ rootSessionId: sessionIdSchema.optional(),
456
+ agentInstanceId: nonEmptyStringSchema.optional(),
457
+ workspace: workspaceIdentitySchema.optional(),
458
+ startedAt: epochMillisSchema.optional()
459
+ });
460
+ var identityClaimSchema = z5.strictObject({
461
+ /** Non-sensitive label, e.g. `adapter:acme-cli` or `env:OTEL_HOOK_SESSION_ID`. */
462
+ source: nonEmptyStringSchema,
463
+ confidence: detectionConfidenceSchema,
464
+ fields: identityClaimFieldsSchema
465
+ });
466
+
467
+ // src/model/target.ts
468
+ import { z as z6 } from "zod";
469
+ var targetSourceSchema = z6.enum(["tool-path", "shell-cwd", "session-cwd"]);
470
+ var MAX_TARGET_HINT_PATHS = 8;
471
+ var MAX_TARGET_PATH_LENGTH = 4096;
472
+ var localPathSchema = z6.string().min(1).max(MAX_TARGET_PATH_LENGTH).refine((value) => !value.includes("\0"), "path must not contain NUL");
473
+ var targetHintSchema = z6.strictObject({
474
+ source: targetSourceSchema,
475
+ paths: z6.array(localPathSchema).min(1).max(MAX_TARGET_HINT_PATHS).readonly(),
476
+ /** Absolute directory that relative `paths` resolve against. */
477
+ baseDirectory: localPathSchema.optional()
478
+ }).readonly();
479
+ var worktreeKindSchema = z6.enum(["main", "linked"]);
480
+ var workspaceTargetSchema = z6.strictObject({
481
+ workspaceId: workspaceIdSchema,
482
+ /** Branch checked out in that worktree; absent on a detached HEAD. */
483
+ vcsBranchName: nonEmptyStringSchema.optional(),
484
+ source: targetSourceSchema,
485
+ /** `git-root` handle of the repository's main worktree; absent when there is none to name. */
486
+ repositoryId: workspaceIdSchema.optional(),
487
+ worktreeKind: worktreeKindSchema.optional()
488
+ }).readonly();
489
+ var SUBAGENT_ID_PATTERN = /^[A-Za-z0-9_.:@+=-]{1,256}$/;
490
+ var subagentIdSchema = z6.string().regex(SUBAGENT_ID_PATTERN);
491
+
129
492
  // src/model/usage.ts
130
- import { z as z2 } from "zod";
131
- var usageTemporalitySchema = z2.enum(["delta", "cumulative"]);
132
- var cacheCreationAccountingSchema = z2.enum([
493
+ import { z as z7 } from "zod";
494
+ var usageTemporalitySchema = z7.enum(["delta", "cumulative"]);
495
+ var cacheCreationAccountingSchema = z7.enum([
133
496
  "included-in-input",
134
497
  "disjoint-from-input",
135
498
  "not-reported"
136
499
  ]);
137
- var providerTotalAgreementSchema = z2.enum(["unreported", "agrees", "disagrees"]);
138
- var usageReportSchema = z2.strictObject({
500
+ var providerTotalAgreementSchema = z7.enum(["unreported", "agrees", "disagrees"]);
501
+ var usageReportSchema = z7.strictObject({
139
502
  temporality: usageTemporalitySchema,
140
503
  /** Inclusive input tokens. */
141
504
  inputTokens: tokenCountSchema.optional(),
@@ -152,7 +515,7 @@ var usageReportSchema = z2.strictObject({
152
515
  /** Total exactly as the provider reported it, if it reported one. */
153
516
  providerTotalTokens: tokenCountSchema.optional()
154
517
  });
155
- var canonicalUsageSchema = z2.strictObject({
518
+ var canonicalUsageSchema = z7.strictObject({
156
519
  temporality: usageTemporalitySchema,
157
520
  inputTokens: tokenCountSchema,
158
521
  cachedInputTokens: tokenCountSchema,
@@ -306,15 +669,200 @@ var EMPTY_DELTA_USAGE = Object.freeze(
306
669
  normalizeUsageOrThrow({ temporality: "delta" })
307
670
  );
308
671
 
672
+ // src/model/version.ts
673
+ import { z as z8 } from "zod";
674
+ var CANONICAL_SCHEMA_VERSION = 1;
675
+ var canonicalSchemaVersionSchema = z8.literal(CANONICAL_SCHEMA_VERSION);
676
+
677
+ // src/model/events.ts
678
+ var modelDescriptorSchema = z9.strictObject({
679
+ modelId: nonEmptyStringSchema,
680
+ /** Vendor of the model, e.g. `anthropic`. Distinct from the agent provider. */
681
+ vendor: nonEmptyStringSchema.optional(),
682
+ family: nonEmptyStringSchema.optional()
683
+ });
684
+ var costFactsSchema = z9.strictObject({
685
+ /** ISO 4217 code. */
686
+ currency: z9.string().length(3),
687
+ amount: z9.number().min(0).finite(),
688
+ source: z9.enum(["provider-reported", "computed"])
689
+ });
690
+ var canonicalEventTypeSchema = z9.enum([
691
+ "session.start",
692
+ "session.end",
693
+ "prompt.submitted",
694
+ "generation.start",
695
+ "generation.end",
696
+ "tool.start",
697
+ "tool.end",
698
+ "subagent.start",
699
+ "subagent.end",
700
+ "compaction.performed",
701
+ "error.raised"
702
+ ]);
703
+ var CANONICAL_EVENT_TYPES = canonicalEventTypeSchema.options;
704
+ var outcomeSchema = z9.enum(["ok", "error", "cancelled", "timeout", "denied", "unknown"]);
705
+ var baseEventFields = {
706
+ schemaVersion: canonicalSchemaVersionSchema,
707
+ eventId: eventIdSchema,
708
+ invocationId: invocationIdSchema,
709
+ sessionId: sessionIdSchema,
710
+ /** Per-invocation ordering key. Stable across replays of the same input. */
711
+ sequence: sequenceNumberSchema,
712
+ occurredAt: epochMillisSchema,
713
+ provenance: sourceProvenanceSchema,
714
+ workspace: workspaceIdentitySchema,
715
+ /**
716
+ * The provider's own id for the subagent this event was emitted inside (e.g.
717
+ * Claude Code's `agent_id`). Absent for the top-level agent. Set by the event
718
+ * factory, never by hand.
719
+ */
720
+ subagentId: subagentIdSchema.optional(),
721
+ extensions: extensionsSchema.default(emptyExtensions)
722
+ };
723
+ var event = (shape) => z9.strictObject({ ...baseEventFields, ...shape });
724
+ var sessionStartEventSchema = event({
725
+ type: z9.literal("session.start"),
726
+ sessionKind: z9.enum(["interactive", "non-interactive", "unknown"]),
727
+ agentName: nonEmptyStringSchema.optional(),
728
+ agentVersion: nonEmptyStringSchema.optional(),
729
+ model: modelDescriptorSchema.optional(),
730
+ /** The git worktree the session runs in, resolved by the core (ADR 0008). */
731
+ target: workspaceTargetSchema.optional()
732
+ });
733
+ var sessionEndEventSchema = event({
734
+ type: z9.literal("session.end"),
735
+ reason: z9.enum(["completed", "aborted", "error", "timeout", "unknown"]),
736
+ durationMillis: durationMillisSchema.optional(),
737
+ /** Session totals, typically cumulative. */
738
+ usage: canonicalUsageSchema.optional(),
739
+ cost: costFactsSchema.optional()
740
+ });
741
+ var promptSubmittedEventSchema = event({
742
+ type: z9.literal("prompt.submitted"),
743
+ promptSource: z9.enum(["user", "automation", "resumed", "unknown"]),
744
+ content: contentFactSchema.optional(),
745
+ turnIndex: z9.number().int().min(0).optional(),
746
+ /** The git worktree the session runs in, resolved by the core (ADR 0008). */
747
+ target: workspaceTargetSchema.optional()
748
+ });
749
+ var generationStartEventSchema = event({
750
+ type: z9.literal("generation.start"),
751
+ generationId: nonEmptyStringSchema,
752
+ model: modelDescriptorSchema,
753
+ requestedMaxOutputTokens: tokenCountSchema.optional(),
754
+ inputContent: contentFactsSchema.optional()
755
+ });
756
+ var generationEndEventSchema = event({
757
+ type: z9.literal("generation.end"),
758
+ generationId: nonEmptyStringSchema,
759
+ model: modelDescriptorSchema,
760
+ outcome: outcomeSchema,
761
+ stopReason: nonEmptyStringSchema.optional(),
762
+ durationMillis: durationMillisSchema.optional(),
763
+ usage: canonicalUsageSchema.optional(),
764
+ /**
765
+ * True when `usage` is known to cover only part of the generation (for
766
+ * example the last model request of a multi-request turn); false when the
767
+ * provider or harness said it is the whole. Absent: not stated. Meaningless
768
+ * without `usage`.
769
+ */
770
+ usagePartial: z9.boolean().optional(),
771
+ cost: costFactsSchema.optional(),
772
+ outputContent: contentFactsSchema.optional()
773
+ });
774
+ var toolKindSchema = z9.enum([
775
+ "read",
776
+ "write",
777
+ "execute",
778
+ "search",
779
+ "network",
780
+ "delegate",
781
+ "other",
782
+ "unknown"
783
+ ]);
784
+ var toolStartEventSchema = event({
785
+ type: z9.literal("tool.start"),
786
+ toolCallId: nonEmptyStringSchema,
787
+ toolName: nonEmptyStringSchema,
788
+ toolKind: toolKindSchema,
789
+ generationId: nonEmptyStringSchema.optional(),
790
+ input: contentFactSchema.optional(),
791
+ /** The git worktree this call targeted, resolved by the core (ADR 0008). */
792
+ target: workspaceTargetSchema.optional()
793
+ });
794
+ var toolEndEventSchema = event({
795
+ type: z9.literal("tool.end"),
796
+ toolCallId: nonEmptyStringSchema,
797
+ toolName: nonEmptyStringSchema,
798
+ outcome: outcomeSchema,
799
+ durationMillis: durationMillisSchema.optional(),
800
+ /** Present when the host asked for or recorded a permission decision. */
801
+ permissionDecision: z9.enum(["allowed", "denied", "deferred", "not-required"]).optional(),
802
+ output: contentFactSchema.optional(),
803
+ /** The git worktree this call targeted, resolved by the core (ADR 0008). */
804
+ target: workspaceTargetSchema.optional()
805
+ });
806
+ var subagentStartEventSchema = event({
807
+ type: z9.literal("subagent.start"),
808
+ subagentInvocationId: invocationIdSchema,
809
+ subagentType: nonEmptyStringSchema.optional(),
810
+ /** 0 for the top-level agent; 1 for its direct children. */
811
+ delegationDepth: z9.number().int().min(0).max(64),
812
+ model: modelDescriptorSchema.optional()
813
+ });
814
+ var subagentEndEventSchema = event({
815
+ type: z9.literal("subagent.end"),
816
+ subagentInvocationId: invocationIdSchema,
817
+ outcome: outcomeSchema,
818
+ durationMillis: durationMillisSchema.optional(),
819
+ usage: canonicalUsageSchema.optional()
820
+ });
821
+ var compactionPerformedEventSchema = event({
822
+ type: z9.literal("compaction.performed"),
823
+ trigger: z9.enum(["automatic", "manual", "unknown"]),
824
+ /** Provider-reported context size before and after compaction, if known. */
825
+ contextTokensBefore: tokenCountSchema.optional(),
826
+ contextTokensAfter: tokenCountSchema.optional(),
827
+ droppedMessageCount: z9.number().int().min(0).optional(),
828
+ usage: canonicalUsageSchema.optional()
829
+ });
830
+ var errorRaisedEventSchema = event({
831
+ type: z9.literal("error.raised"),
832
+ errorCode: otelHookErrorCodeSchema,
833
+ severity: errorSeveritySchema,
834
+ phase: errorPhaseSchema,
835
+ retryable: z9.boolean(),
836
+ /** Error text is content: it is described, never embedded verbatim by default. */
837
+ message: contentFactSchema.optional(),
838
+ /** Non-sensitive, provider-agnostic short label. */
839
+ detail: nonEmptyStringSchema.optional()
840
+ });
841
+ var canonicalEventSchema = z9.discriminatedUnion("type", [
842
+ sessionStartEventSchema,
843
+ sessionEndEventSchema,
844
+ promptSubmittedEventSchema,
845
+ generationStartEventSchema,
846
+ generationEndEventSchema,
847
+ toolStartEventSchema,
848
+ toolEndEventSchema,
849
+ subagentStartEventSchema,
850
+ subagentEndEventSchema,
851
+ compactionPerformedEventSchema,
852
+ errorRaisedEventSchema
853
+ ]);
854
+ var TARGETED_EVENT_TYPES = ["session.start", "prompt.submitted", "tool.start", "tool.end"];
855
+ var TARGETED = new Set(TARGETED_EVENT_TYPES);
856
+
309
857
  // src/runtime/ports.ts
310
- var appliedDeliverySchema = z3.strictObject({
311
- callbackId: z3.string().regex(/^[A-Za-z0-9_-]{1,128}$/),
858
+ var appliedDeliverySchema = z10.strictObject({
859
+ callbackId: z10.string().regex(/^[A-Za-z0-9_-]{1,128}$/),
312
860
  /** How many of that delivery's observations are folded in, counted from one. */
313
- applications: z3.number().int().min(1).max(4096)
861
+ applications: z10.number().int().min(1).max(4096)
314
862
  });
315
- var stateValueSchema = z3.discriminatedUnion("kind", [
316
- z3.strictObject({
317
- kind: z3.literal("usage-cumulative"),
863
+ var stateValueSchema = z10.discriminatedUnion("kind", [
864
+ z10.strictObject({
865
+ kind: z10.literal("usage-cumulative"),
318
866
  usage: canonicalUsageSchema,
319
867
  /**
320
868
  * Optional: absent on every record written before this field existed, which
@@ -323,22 +871,42 @@ var stateValueSchema = z3.discriminatedUnion("kind", [
323
871
  */
324
872
  appliedDelivery: appliedDeliverySchema.optional()
325
873
  }),
326
- z3.strictObject({
327
- kind: z3.literal("sequence"),
874
+ z10.strictObject({
875
+ kind: z10.literal("sequence"),
328
876
  next: sequenceNumberSchema
329
877
  }),
330
- z3.strictObject({
331
- kind: z3.literal("attributes"),
878
+ z10.strictObject({
879
+ kind: z10.literal("attributes"),
332
880
  attributes: attributesSchema
881
+ }),
882
+ /**
883
+ * The model a session last reported, so a later invocation whose payload names
884
+ * none (Claude Code's `Stop`) can still say which model it was. A model id is
885
+ * not sensitive (`modelDescriptorSchema`), and the descriptor is the strict,
886
+ * bounded canonical shape, never a payload fragment.
887
+ */
888
+ z10.strictObject({
889
+ kind: z10.literal("session-model"),
890
+ model: modelDescriptorSchema
891
+ }),
892
+ /**
893
+ * How far a {@link PayloadEnricher} has read a session's append-only source
894
+ * (Claude Code's transcript), so the next read starts where the last ended.
895
+ * `source` is an opaque digest of what was read, never a path.
896
+ */
897
+ z10.strictObject({
898
+ kind: z10.literal("read-cursor"),
899
+ source: z10.string().regex(/^[A-Za-z0-9_-]{1,128}$/),
900
+ offset: z10.number().int().min(0).max(Number.MAX_SAFE_INTEGER)
333
901
  })
334
902
  ]);
335
- var stateRecordSchema = z3.strictObject({
903
+ var stateRecordSchema = z10.strictObject({
336
904
  /** Incremented on each write; lets callers detect lost updates. */
337
- revision: z3.number().int().min(0),
905
+ revision: z10.number().int().min(0),
338
906
  updatedAt: epochMillisSchema,
339
907
  value: stateValueSchema
340
908
  });
341
- var logLevelSchema = z3.enum(["silent", "error", "warn", "info", "debug"]);
909
+ var logLevelSchema = z10.enum(["silent", "error", "warn", "info", "debug"]);
342
910
  var LOG_LEVEL_RANK = Object.freeze({
343
911
  silent: 0,
344
912
  error: 1,