@osfactory/otel-hook 0.1.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 (65) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +1020 -0
  3. package/dist/adapter-DIgRACtL.d.ts +303 -0
  4. package/dist/cli.js +12607 -0
  5. package/dist/cli.js.map +1 -0
  6. package/dist/config.d.ts +233 -0
  7. package/dist/config.js +996 -0
  8. package/dist/config.js.map +1 -0
  9. package/dist/content-CoB7aNP1.d.ts +118 -0
  10. package/dist/diagnostics.d.ts +58 -0
  11. package/dist/diagnostics.js +46 -0
  12. package/dist/diagnostics.js.map +1 -0
  13. package/dist/errors.d.ts +91 -0
  14. package/dist/errors.js +322 -0
  15. package/dist/errors.js.map +1 -0
  16. package/dist/events-VxBnDFaO.d.ts +2044 -0
  17. package/dist/filesystem-store-J8jjDMTh.d.ts +65 -0
  18. package/dist/hook-CGpo-vks.d.ts +292 -0
  19. package/dist/identity-BrVBs901.d.ts +227 -0
  20. package/dist/index.d.ts +44 -0
  21. package/dist/index.js +11798 -0
  22. package/dist/index.js.map +1 -0
  23. package/dist/install.d.ts +1021 -0
  24. package/dist/install.js +3271 -0
  25. package/dist/install.js.map +1 -0
  26. package/dist/integration.d.ts +303 -0
  27. package/dist/integration.js +5942 -0
  28. package/dist/integration.js.map +1 -0
  29. package/dist/keys-Dej5bN3L.d.ts +7 -0
  30. package/dist/lifecycle.d.ts +428 -0
  31. package/dist/lifecycle.js +1077 -0
  32. package/dist/lifecycle.js.map +1 -0
  33. package/dist/memory-DXVBc8V9.d.ts +94 -0
  34. package/dist/model.d.ts +45 -0
  35. package/dist/model.js +1023 -0
  36. package/dist/model.js.map +1 -0
  37. package/dist/otlp-log-sink-CeIFDDpn.d.ts +457 -0
  38. package/dist/payload-CHr53E_v.d.ts +201 -0
  39. package/dist/policy-D1CrlYn3.d.ts +73 -0
  40. package/dist/ports-Q8x0ODhs.d.ts +200 -0
  41. package/dist/primitives-CJ8-rn-f.d.ts +75 -0
  42. package/dist/privacy.d.ts +51 -0
  43. package/dist/privacy.js +633 -0
  44. package/dist/privacy.js.map +1 -0
  45. package/dist/providers.d.ts +257 -0
  46. package/dist/providers.js +4398 -0
  47. package/dist/providers.js.map +1 -0
  48. package/dist/registry-BzYmC9OC.d.ts +49 -0
  49. package/dist/runtime.d.ts +32 -0
  50. package/dist/runtime.js +2907 -0
  51. package/dist/runtime.js.map +1 -0
  52. package/dist/schema-Cn0-xz8L.d.ts +224 -0
  53. package/dist/semconv-Baoz-0OI.d.ts +188 -0
  54. package/dist/service-j4jEO6cZ.d.ts +68 -0
  55. package/dist/state.d.ts +36 -0
  56. package/dist/state.js +710 -0
  57. package/dist/state.js.map +1 -0
  58. package/dist/taxonomy-DwhTtuWd.d.ts +87 -0
  59. package/dist/telemetry.d.ts +77 -0
  60. package/dist/telemetry.js +2294 -0
  61. package/dist/telemetry.js.map +1 -0
  62. package/dist/testing.d.ts +155 -0
  63. package/dist/testing.js +6513 -0
  64. package/dist/testing.js.map +1 -0
  65. package/package.json +124 -0
@@ -0,0 +1,4398 @@
1
+ // src/providers/adapter.ts
2
+ import { z as z9 } from "zod";
3
+
4
+ // src/model/events.ts
5
+ import { z as z8 } 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
204
+ import { z as z3 } from "zod";
205
+
206
+ // src/model/primitives.ts
207
+ import { z as z2 } from "zod";
208
+ var MAX_IDENTIFIER_LENGTH = 256;
209
+ var MAX_ATTRIBUTE_STRING_LENGTH = 4096;
210
+ var MAX_ATTRIBUTE_ARRAY_LENGTH = 128;
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);
217
+ var invocationIdSchema = brandedIdSchema().brand();
218
+ var sessionIdSchema = brandedIdSchema().brand();
219
+ var eventIdSchema = brandedIdSchema().brand();
220
+ var WORKSPACE_ID_PATTERN = /^[a-z][a-z0-9]{0,15}:[A-Za-z0-9_-]{8,128}$/;
221
+ var workspaceIdSchema = z2.string().regex(WORKSPACE_ID_PATTERN, "workspace id must be an opaque `<scheme>:<token>` handle").brand();
222
+ var PROVIDER_ID_PATTERN = /^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/;
223
+ var providerIdSchema = z2.string().min(1).max(64).regex(PROVIDER_ID_PATTERN, "provider id must be lowercase and hyphenated").brand();
224
+ var UNKNOWN_PROVIDER_ID = "unknown";
225
+ var resolvedProviderIdSchema = z2.union([
226
+ providerIdSchema,
227
+ z2.literal(UNKNOWN_PROVIDER_ID)
228
+ ]);
229
+ var attributePrimitiveSchema = z2.union([
230
+ z2.string().max(MAX_ATTRIBUTE_STRING_LENGTH),
231
+ z2.number().finite(),
232
+ z2.boolean()
233
+ ]);
234
+ var attributeValueSchema = z2.union([
235
+ attributePrimitiveSchema,
236
+ z2.array(attributePrimitiveSchema).max(MAX_ATTRIBUTE_ARRAY_LENGTH)
237
+ ]);
238
+ var attributesSchema = z2.record(z2.string().min(1).max(MAX_IDENTIFIER_LENGTH), attributeValueSchema);
239
+ var detectionConfidenceSchema = z2.enum(["none", "weak", "strong", "exact"]);
240
+ var DETECTION_CONFIDENCE_RANK = Object.freeze({
241
+ none: 0,
242
+ weak: 1,
243
+ strong: 2,
244
+ exact: 3
245
+ });
246
+ var sourceTransportSchema = z2.enum([
247
+ "hook-stdin",
248
+ "cli-argument",
249
+ "library-call",
250
+ "test-fixture"
251
+ ]);
252
+
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"
263
+ ]);
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()
285
+ });
286
+ var contentFactsSchema = z3.array(contentFactSchema).max(64);
287
+
288
+ // src/model/extensions.ts
289
+ import { z as z4 } from "zod";
290
+ var EXTENSION_KEY_PATTERN = /^[a-z][a-z0-9]*(?:[-_][a-z0-9]+)*(?:\.[a-z][a-z0-9]*(?:[-_][a-z0-9]+)*)+$/;
291
+ var RESERVED_EXTENSION_NAMESPACES = Object.freeze([
292
+ "otelhook",
293
+ "otel",
294
+ "telemetry"
295
+ ]);
296
+ var MAX_EXTENSION_ENTRIES = 64;
297
+ var extensionKeyNamespace = (key) => key.slice(0, key.indexOf("."));
298
+ var isReservedExtensionNamespace = (key) => RESERVED_EXTENSION_NAMESPACES.includes(extensionKeyNamespace(key));
299
+ var extensionsSchema = z4.record(z4.string(), attributeValueSchema).check((ctx) => {
300
+ const keys = Object.keys(ctx.value);
301
+ if (keys.length > MAX_EXTENSION_ENTRIES) {
302
+ ctx.issues.push({
303
+ code: "custom",
304
+ input: ctx.value,
305
+ message: `extensions may contain at most ${MAX_EXTENSION_ENTRIES} entries`
306
+ });
307
+ }
308
+ for (const key of keys) {
309
+ if (!EXTENSION_KEY_PATTERN.test(key)) {
310
+ ctx.issues.push({
311
+ code: "custom",
312
+ input: ctx.value,
313
+ path: [key],
314
+ message: `extension key ${JSON.stringify(key)} must be namespaced, e.g. "acme.tier"`
315
+ });
316
+ continue;
317
+ }
318
+ if (isReservedExtensionNamespace(key)) {
319
+ ctx.issues.push({
320
+ code: "custom",
321
+ input: ctx.value,
322
+ path: [key],
323
+ message: `extension namespace ${JSON.stringify(extensionKeyNamespace(key))} is reserved`
324
+ });
325
+ }
326
+ }
327
+ });
328
+ var EMPTY_EXTENSIONS = Object.freeze({});
329
+ var emptyExtensions = () => ({});
330
+
331
+ // src/model/identity.ts
332
+ import { z as z5 } from "zod";
333
+ var workspaceKeySourceSchema = z5.enum([
334
+ "git-remote",
335
+ "git-root",
336
+ "working-directory",
337
+ "explicit",
338
+ "unknown"
339
+ ]);
340
+ var workspaceIdentitySchema = z5.strictObject({
341
+ workspaceId: workspaceIdSchema,
342
+ keySource: workspaceKeySourceSchema,
343
+ /** Repository name only; never an owner path or URL with credentials. */
344
+ repositoryName: nonEmptyStringSchema.optional(),
345
+ vcsBranchName: nonEmptyStringSchema.optional(),
346
+ /** Opaque handle for the checked-out revision. */
347
+ vcsRevisionId: nonEmptyStringSchema.optional()
348
+ }).readonly();
349
+ var UNKNOWN_WORKSPACE_ID = "unknown:0000000000000000";
350
+ var unknownWorkspaceIdentity = () => workspaceIdentitySchema.parse({
351
+ workspaceId: UNKNOWN_WORKSPACE_ID,
352
+ keySource: "unknown"
353
+ });
354
+ var sourceProvenanceSchema = z5.strictObject({
355
+ providerId: resolvedProviderIdSchema,
356
+ providerVersion: nonEmptyStringSchema.optional(),
357
+ adapterId: nonEmptyStringSchema,
358
+ adapterVersion: nonEmptyStringSchema,
359
+ detectionConfidence: detectionConfidenceSchema,
360
+ /** The provider's own name for the source event, e.g. a hook event name. */
361
+ sourceEventName: nonEmptyStringSchema.optional(),
362
+ transport: sourceTransportSchema
363
+ }).readonly();
364
+ var consumerAttributesSchema = attributesSchema.readonly();
365
+ var invocationIdentitySchema = z5.strictObject({
366
+ invocationId: invocationIdSchema,
367
+ sessionId: sessionIdSchema,
368
+ /** Set when this invocation runs beneath another agent invocation. */
369
+ parentInvocationId: invocationIdSchema.optional(),
370
+ /** Root of the session tree when the provider exposes one. */
371
+ rootSessionId: sessionIdSchema.optional(),
372
+ /** Stable handle for the agent process/instance, when available. */
373
+ agentInstanceId: nonEmptyStringSchema.optional(),
374
+ provenance: sourceProvenanceSchema,
375
+ workspace: workspaceIdentitySchema,
376
+ startedAt: epochMillisSchema,
377
+ consumerAttributes: consumerAttributesSchema
378
+ }).readonly();
379
+ var identityClaimFieldsSchema = z5.strictObject({
380
+ invocationId: invocationIdSchema.optional(),
381
+ sessionId: sessionIdSchema.optional(),
382
+ parentInvocationId: invocationIdSchema.optional(),
383
+ rootSessionId: sessionIdSchema.optional(),
384
+ agentInstanceId: nonEmptyStringSchema.optional(),
385
+ workspace: workspaceIdentitySchema.optional(),
386
+ startedAt: epochMillisSchema.optional()
387
+ });
388
+ var identityClaimSchema = z5.strictObject({
389
+ /** Non-sensitive label, e.g. `adapter:acme-cli` or `env:OTEL_HOOK_SESSION_ID`. */
390
+ source: nonEmptyStringSchema,
391
+ confidence: detectionConfidenceSchema,
392
+ fields: identityClaimFieldsSchema
393
+ });
394
+
395
+ // src/model/usage.ts
396
+ import { z as z6 } from "zod";
397
+ var usageTemporalitySchema = z6.enum(["delta", "cumulative"]);
398
+ var cacheCreationAccountingSchema = z6.enum([
399
+ "included-in-input",
400
+ "disjoint-from-input",
401
+ "not-reported"
402
+ ]);
403
+ var providerTotalAgreementSchema = z6.enum(["unreported", "agrees", "disagrees"]);
404
+ var usageReportSchema = z6.strictObject({
405
+ temporality: usageTemporalitySchema,
406
+ /** Inclusive input tokens. */
407
+ inputTokens: tokenCountSchema.optional(),
408
+ /** Subset of `inputTokens` served from a prompt cache. */
409
+ cachedInputTokens: tokenCountSchema.optional(),
410
+ /** Tokens written to a prompt cache. */
411
+ cacheCreationInputTokens: tokenCountSchema.optional(),
412
+ /** Required when `cacheCreationInputTokens` is present and non-zero. */
413
+ cacheCreationAccounting: cacheCreationAccountingSchema.optional(),
414
+ /** Inclusive output tokens. */
415
+ outputTokens: tokenCountSchema.optional(),
416
+ /** Subset of `outputTokens` spent on reasoning. */
417
+ reasoningOutputTokens: tokenCountSchema.optional(),
418
+ /** Total exactly as the provider reported it, if it reported one. */
419
+ providerTotalTokens: tokenCountSchema.optional()
420
+ });
421
+ var canonicalUsageSchema = z6.strictObject({
422
+ temporality: usageTemporalitySchema,
423
+ inputTokens: tokenCountSchema,
424
+ cachedInputTokens: tokenCountSchema,
425
+ cacheCreationInputTokens: tokenCountSchema,
426
+ cacheCreationAccounting: cacheCreationAccountingSchema,
427
+ outputTokens: tokenCountSchema,
428
+ reasoningOutputTokens: tokenCountSchema,
429
+ /** Derived: input tokens that were neither cache reads nor cache writes. */
430
+ uncachedInputTokens: tokenCountSchema,
431
+ /** Derived: canonical billable total. */
432
+ totalTokens: tokenCountSchema,
433
+ providerTotalTokens: tokenCountSchema.optional(),
434
+ providerTotalAgreement: providerTotalAgreementSchema
435
+ }).check((ctx) => {
436
+ const usage = ctx.value;
437
+ const push = (message) => {
438
+ ctx.issues.push({ code: "custom", input: usage, message });
439
+ };
440
+ if (usage.cachedInputTokens > usage.inputTokens) {
441
+ push("cachedInputTokens must not exceed inputTokens (it is a subset)");
442
+ }
443
+ if (usage.reasoningOutputTokens > usage.outputTokens) {
444
+ push("reasoningOutputTokens must not exceed outputTokens (it is a subset)");
445
+ }
446
+ if (usage.cacheCreationAccounting === "not-reported" && usage.cacheCreationInputTokens !== 0) {
447
+ push("cacheCreationInputTokens must be 0 when cacheCreationAccounting is not-reported");
448
+ }
449
+ const creationInsideInput = usage.cacheCreationAccounting === "included-in-input" ? usage.cacheCreationInputTokens : 0;
450
+ if (usage.cachedInputTokens + creationInsideInput > usage.inputTokens) {
451
+ push(
452
+ "cachedInputTokens + cacheCreationInputTokens must not exceed inputTokens when cache creation is included in input"
453
+ );
454
+ }
455
+ const expectedUncached = usage.inputTokens - usage.cachedInputTokens - creationInsideInput;
456
+ if (expectedUncached >= 0 && usage.uncachedInputTokens !== expectedUncached) {
457
+ push(`uncachedInputTokens must equal ${expectedUncached}`);
458
+ }
459
+ const creationOutsideInput = usage.cacheCreationAccounting === "disjoint-from-input" ? usage.cacheCreationInputTokens : 0;
460
+ const expectedTotal = usage.inputTokens + creationOutsideInput + usage.outputTokens;
461
+ if (usage.totalTokens !== expectedTotal) {
462
+ push(`totalTokens must equal ${expectedTotal}`);
463
+ }
464
+ const expectedAgreement = usage.providerTotalTokens === void 0 ? "unreported" : usage.providerTotalTokens === expectedTotal ? "agrees" : "disagrees";
465
+ if (usage.providerTotalAgreement !== expectedAgreement) {
466
+ push(`providerTotalAgreement must be ${expectedAgreement}`);
467
+ }
468
+ });
469
+ var normalizeUsage = (report) => {
470
+ const parsed = usageReportSchema.safeParse(report);
471
+ if (!parsed.success) {
472
+ return {
473
+ status: "invalid",
474
+ issues: parsed.error.issues.map((issue) => ({
475
+ code: "invalid-report",
476
+ message: `${issue.path.join(".") || "<root>"}: ${issue.message}`
477
+ }))
478
+ };
479
+ }
480
+ const input = parsed.data;
481
+ const issues = [];
482
+ const notes = [];
483
+ const inputTokens = input.inputTokens ?? 0;
484
+ const cachedInputTokens = input.cachedInputTokens ?? 0;
485
+ const cacheCreationInputTokens = input.cacheCreationInputTokens ?? 0;
486
+ const outputTokens = input.outputTokens ?? 0;
487
+ const reasoningOutputTokens = input.reasoningOutputTokens ?? 0;
488
+ let accounting;
489
+ if (cacheCreationInputTokens === 0) {
490
+ accounting = input.cacheCreationAccounting ?? "not-reported";
491
+ if (accounting !== "not-reported") {
492
+ notes.push(
493
+ `cacheCreationAccounting=${accounting} retained with zero cache-creation tokens`
494
+ );
495
+ }
496
+ } else if (input.cacheCreationAccounting === void 0) {
497
+ issues.push({
498
+ code: "cache-creation-accounting-missing",
499
+ message: "cacheCreationAccounting is required when cacheCreationInputTokens is non-zero; it cannot be inferred"
500
+ });
501
+ accounting = "not-reported";
502
+ } else if (input.cacheCreationAccounting === "not-reported") {
503
+ issues.push({
504
+ code: "cache-creation-accounting-missing",
505
+ message: "cacheCreationAccounting=not-reported conflicts with non-zero cacheCreationInputTokens"
506
+ });
507
+ accounting = "not-reported";
508
+ } else {
509
+ accounting = input.cacheCreationAccounting;
510
+ }
511
+ if (cachedInputTokens > inputTokens) {
512
+ issues.push({
513
+ code: "cached-exceeds-input",
514
+ message: `cachedInputTokens (${cachedInputTokens}) exceeds inclusive inputTokens (${inputTokens})`
515
+ });
516
+ }
517
+ if (reasoningOutputTokens > outputTokens) {
518
+ issues.push({
519
+ code: "reasoning-exceeds-output",
520
+ message: `reasoningOutputTokens (${reasoningOutputTokens}) exceeds inclusive outputTokens (${outputTokens})`
521
+ });
522
+ }
523
+ const creationInsideInput = accounting === "included-in-input" ? cacheCreationInputTokens : 0;
524
+ if (cachedInputTokens + creationInsideInput > inputTokens) {
525
+ issues.push({
526
+ code: "cache-creation-exceeds-input",
527
+ message: `cachedInputTokens + cacheCreationInputTokens (${cachedInputTokens + creationInsideInput}) exceeds inclusive inputTokens (${inputTokens})`
528
+ });
529
+ }
530
+ if (issues.length > 0) {
531
+ return { status: "invalid", issues };
532
+ }
533
+ const creationOutsideInput = accounting === "disjoint-from-input" ? cacheCreationInputTokens : 0;
534
+ const totalTokens = inputTokens + creationOutsideInput + outputTokens;
535
+ const providerTotalAgreement = input.providerTotalTokens === void 0 ? "unreported" : input.providerTotalTokens === totalTokens ? "agrees" : "disagrees";
536
+ if (providerTotalAgreement === "disagrees") {
537
+ notes.push(
538
+ `providerTotalTokens (${input.providerTotalTokens ?? 0}) disagrees with canonical total (${totalTokens}); both retained`
539
+ );
540
+ }
541
+ const usage = {
542
+ temporality: input.temporality,
543
+ inputTokens,
544
+ cachedInputTokens,
545
+ cacheCreationInputTokens,
546
+ cacheCreationAccounting: accounting,
547
+ outputTokens,
548
+ reasoningOutputTokens,
549
+ uncachedInputTokens: inputTokens - cachedInputTokens - creationInsideInput,
550
+ totalTokens,
551
+ ...input.providerTotalTokens === void 0 ? {} : { providerTotalTokens: input.providerTotalTokens },
552
+ providerTotalAgreement
553
+ };
554
+ return { status: "ok", usage, notes };
555
+ };
556
+ var UsageNormalizationError = class extends Error {
557
+ issues;
558
+ constructor(issues) {
559
+ super(`invalid usage report: ${issues.map((issue) => issue.message).join("; ")}`);
560
+ this.name = "UsageNormalizationError";
561
+ this.issues = issues;
562
+ }
563
+ };
564
+ var normalizeUsageOrThrow = (report) => {
565
+ const result = normalizeUsage(report);
566
+ if (result.status === "invalid") {
567
+ throw new UsageNormalizationError(result.issues);
568
+ }
569
+ return result.usage;
570
+ };
571
+ var EMPTY_DELTA_USAGE = Object.freeze(
572
+ normalizeUsageOrThrow({ temporality: "delta" })
573
+ );
574
+
575
+ // src/model/version.ts
576
+ import { z as z7 } from "zod";
577
+ var CANONICAL_SCHEMA_VERSION = 1;
578
+ var canonicalSchemaVersionSchema = z7.literal(CANONICAL_SCHEMA_VERSION);
579
+
580
+ // src/model/events.ts
581
+ var modelDescriptorSchema = z8.strictObject({
582
+ modelId: nonEmptyStringSchema,
583
+ /** Vendor of the model, e.g. `anthropic`. Distinct from the agent provider. */
584
+ vendor: nonEmptyStringSchema.optional(),
585
+ family: nonEmptyStringSchema.optional()
586
+ });
587
+ var costFactsSchema = z8.strictObject({
588
+ /** ISO 4217 code. */
589
+ currency: z8.string().length(3),
590
+ amount: z8.number().min(0).finite(),
591
+ source: z8.enum(["provider-reported", "computed"])
592
+ });
593
+ var canonicalEventTypeSchema = z8.enum([
594
+ "session.start",
595
+ "session.end",
596
+ "prompt.submitted",
597
+ "generation.start",
598
+ "generation.end",
599
+ "tool.start",
600
+ "tool.end",
601
+ "subagent.start",
602
+ "subagent.end",
603
+ "compaction.performed",
604
+ "error.raised"
605
+ ]);
606
+ var CANONICAL_EVENT_TYPES = canonicalEventTypeSchema.options;
607
+ var outcomeSchema = z8.enum(["ok", "error", "cancelled", "timeout", "denied", "unknown"]);
608
+ var baseEventFields = {
609
+ schemaVersion: canonicalSchemaVersionSchema,
610
+ eventId: eventIdSchema,
611
+ invocationId: invocationIdSchema,
612
+ sessionId: sessionIdSchema,
613
+ /** Per-invocation ordering key. Stable across replays of the same input. */
614
+ sequence: sequenceNumberSchema,
615
+ occurredAt: epochMillisSchema,
616
+ provenance: sourceProvenanceSchema,
617
+ workspace: workspaceIdentitySchema,
618
+ extensions: extensionsSchema.default(emptyExtensions)
619
+ };
620
+ var event = (shape) => z8.strictObject({ ...baseEventFields, ...shape });
621
+ var sessionStartEventSchema = event({
622
+ type: z8.literal("session.start"),
623
+ sessionKind: z8.enum(["interactive", "non-interactive", "unknown"]),
624
+ agentName: nonEmptyStringSchema.optional(),
625
+ agentVersion: nonEmptyStringSchema.optional(),
626
+ model: modelDescriptorSchema.optional()
627
+ });
628
+ var sessionEndEventSchema = event({
629
+ type: z8.literal("session.end"),
630
+ reason: z8.enum(["completed", "aborted", "error", "timeout", "unknown"]),
631
+ durationMillis: durationMillisSchema.optional(),
632
+ /** Session totals, typically cumulative. */
633
+ usage: canonicalUsageSchema.optional(),
634
+ cost: costFactsSchema.optional()
635
+ });
636
+ var promptSubmittedEventSchema = event({
637
+ type: z8.literal("prompt.submitted"),
638
+ promptSource: z8.enum(["user", "automation", "resumed", "unknown"]),
639
+ content: contentFactSchema.optional(),
640
+ turnIndex: z8.number().int().min(0).optional()
641
+ });
642
+ var generationStartEventSchema = event({
643
+ type: z8.literal("generation.start"),
644
+ generationId: nonEmptyStringSchema,
645
+ model: modelDescriptorSchema,
646
+ requestedMaxOutputTokens: tokenCountSchema.optional(),
647
+ inputContent: contentFactsSchema.optional()
648
+ });
649
+ var generationEndEventSchema = event({
650
+ type: z8.literal("generation.end"),
651
+ generationId: nonEmptyStringSchema,
652
+ model: modelDescriptorSchema,
653
+ outcome: outcomeSchema,
654
+ stopReason: nonEmptyStringSchema.optional(),
655
+ durationMillis: durationMillisSchema.optional(),
656
+ usage: canonicalUsageSchema.optional(),
657
+ cost: costFactsSchema.optional(),
658
+ outputContent: contentFactsSchema.optional()
659
+ });
660
+ var toolKindSchema = z8.enum([
661
+ "read",
662
+ "write",
663
+ "execute",
664
+ "search",
665
+ "network",
666
+ "delegate",
667
+ "other",
668
+ "unknown"
669
+ ]);
670
+ var toolStartEventSchema = event({
671
+ type: z8.literal("tool.start"),
672
+ toolCallId: nonEmptyStringSchema,
673
+ toolName: nonEmptyStringSchema,
674
+ toolKind: toolKindSchema,
675
+ generationId: nonEmptyStringSchema.optional(),
676
+ input: contentFactSchema.optional()
677
+ });
678
+ var toolEndEventSchema = event({
679
+ type: z8.literal("tool.end"),
680
+ toolCallId: nonEmptyStringSchema,
681
+ toolName: nonEmptyStringSchema,
682
+ outcome: outcomeSchema,
683
+ durationMillis: durationMillisSchema.optional(),
684
+ /** Present when the host asked for or recorded a permission decision. */
685
+ permissionDecision: z8.enum(["allowed", "denied", "deferred", "not-required"]).optional(),
686
+ output: contentFactSchema.optional()
687
+ });
688
+ var subagentStartEventSchema = event({
689
+ type: z8.literal("subagent.start"),
690
+ subagentInvocationId: invocationIdSchema,
691
+ subagentType: nonEmptyStringSchema.optional(),
692
+ /** 0 for the top-level agent; 1 for its direct children. */
693
+ delegationDepth: z8.number().int().min(0).max(64),
694
+ model: modelDescriptorSchema.optional()
695
+ });
696
+ var subagentEndEventSchema = event({
697
+ type: z8.literal("subagent.end"),
698
+ subagentInvocationId: invocationIdSchema,
699
+ outcome: outcomeSchema,
700
+ durationMillis: durationMillisSchema.optional(),
701
+ usage: canonicalUsageSchema.optional()
702
+ });
703
+ var compactionPerformedEventSchema = event({
704
+ type: z8.literal("compaction.performed"),
705
+ trigger: z8.enum(["automatic", "manual", "unknown"]),
706
+ /** Provider-reported context size before and after compaction, if known. */
707
+ contextTokensBefore: tokenCountSchema.optional(),
708
+ contextTokensAfter: tokenCountSchema.optional(),
709
+ droppedMessageCount: z8.number().int().min(0).optional(),
710
+ usage: canonicalUsageSchema.optional()
711
+ });
712
+ var errorRaisedEventSchema = event({
713
+ type: z8.literal("error.raised"),
714
+ errorCode: otelHookErrorCodeSchema,
715
+ severity: errorSeveritySchema,
716
+ phase: errorPhaseSchema,
717
+ retryable: z8.boolean(),
718
+ /** Error text is content: it is described, never embedded verbatim by default. */
719
+ message: contentFactSchema.optional(),
720
+ /** Non-sensitive, provider-agnostic short label. */
721
+ detail: nonEmptyStringSchema.optional()
722
+ });
723
+ var canonicalEventSchema = z8.discriminatedUnion("type", [
724
+ sessionStartEventSchema,
725
+ sessionEndEventSchema,
726
+ promptSubmittedEventSchema,
727
+ generationStartEventSchema,
728
+ generationEndEventSchema,
729
+ toolStartEventSchema,
730
+ toolEndEventSchema,
731
+ subagentStartEventSchema,
732
+ subagentEndEventSchema,
733
+ compactionPerformedEventSchema,
734
+ errorRaisedEventSchema
735
+ ]);
736
+
737
+ // src/providers/adapter.ts
738
+ var providerDetectionSchema = z9.strictObject({
739
+ providerId: resolvedProviderIdSchema,
740
+ confidence: detectionConfidenceSchema,
741
+ /**
742
+ * Short, non-sensitive justifications, e.g. `"payload.hook_event_name present"`.
743
+ * Reasons are exported in diagnostics, so they must not quote payload values.
744
+ */
745
+ reasons: z9.array(z9.string().min(1).max(160)).max(8),
746
+ providerVersion: nonEmptyStringSchema.optional(),
747
+ /** The provider's own name for this event, when the payload states one. */
748
+ sourceEventName: nonEmptyStringSchema.optional()
749
+ });
750
+ var deliveryIdentifierSupportSchema = z9.enum(["none", "partial", "all"]);
751
+ var DELIVERY_COMPONENT_PATTERN = /^[A-Za-z0-9_.:@+=-]{1,256}$/;
752
+ var deliveryComponentSchema = z9.string().regex(
753
+ DELIVERY_COMPONENT_PATTERN,
754
+ "delivery component must be identifier-shaped: no whitespace, no path separators"
755
+ );
756
+ var MAX_DELIVERY_COMPONENTS = 8;
757
+ var providerDeliveryClaimSchema = z9.strictObject({
758
+ /**
759
+ * The provider's own session/conversation id. Scopes the callback identity, so
760
+ * two sessions reusing one tool-call id never collide.
761
+ */
762
+ sessionId: nonEmptyStringSchema,
763
+ /** The provider's own name for this callback, e.g. `PostToolUse`. */
764
+ sourceEventName: deliveryComponentSchema,
765
+ /**
766
+ * Identifier-shaped payload fields that, together with `sourceEventName`,
767
+ * name this callback within the session exactly once.
768
+ */
769
+ components: z9.array(deliveryComponentSchema).min(1).max(MAX_DELIVERY_COMPONENTS).readonly(),
770
+ /**
771
+ * Short, non-sensitive justifications, e.g. `"payload.tool_use_id names one
772
+ * tool call"`. Evidence reaches diagnostics, so it must name fields, never
773
+ * quote their values.
774
+ */
775
+ evidence: z9.array(z9.string().min(1).max(160)).min(1).max(4).readonly()
776
+ });
777
+ var DELIVERY_GAP_REASON_PATTERN = /^[^\n\r\t\\/]{1,240}$/;
778
+ var deliveryGapReasonSchema = z9.string().regex(
779
+ DELIVERY_GAP_REASON_PATTERN,
780
+ "delivery gap reason must be one line of prose: no path separators, no control characters"
781
+ );
782
+ var MAX_DELIVERY_GAPS = 48;
783
+ var providerDeliveryGapsSchema = z9.record(deliveryComponentSchema, deliveryGapReasonSchema).refine((gaps) => Object.keys(gaps).length <= MAX_DELIVERY_GAPS, {
784
+ message: `at most ${String(MAX_DELIVERY_GAPS)} delivery gaps may be declared`
785
+ });
786
+ var providerCapabilitiesSchema = z9.strictObject({
787
+ /** Event types the adapter can produce. */
788
+ lifecycleEvents: z9.array(canonicalEventTypeSchema).max(32).readonly(),
789
+ usageTemporality: usageTemporalitySchema,
790
+ /**
791
+ * Which accumulator series a `cumulative` report continues — that is, which
792
+ * previous snapshot the next one should be diffed against.
793
+ *
794
+ * Only meaningful when `usageTemporality` is `cumulative`; omit otherwise.
795
+ *
796
+ * - `event-scope` (the default when omitted) — each event scope keeps its own
797
+ * running total, so a `generation.end` snapshot is diffed against the
798
+ * previous snapshot *for that same generation*.
799
+ * - `session-lifetime` — the provider maintains **one** running total for the
800
+ * whole session and stamps it onto whichever callback happens to report it.
801
+ * Diffing such a snapshot per event scope would restart the baseline on
802
+ * every new generation id and re-count the entire session total each turn,
803
+ * so session-level and generation-level snapshots share one baseline.
804
+ * Subagent snapshots keep their own series regardless: a delegated agent's
805
+ * counter is not a point on the parent session's curve.
806
+ */
807
+ cumulativeUsageSeries: z9.enum(["event-scope", "session-lifetime"]).optional(),
808
+ reportsCachedInput: z9.boolean(),
809
+ reportsCacheCreation: z9.boolean(),
810
+ cacheCreationAccounting: cacheCreationAccountingSchema,
811
+ reportsReasoningOutput: z9.boolean(),
812
+ reportsProviderTotal: z9.boolean(),
813
+ reportsCost: z9.boolean(),
814
+ emitsSubagentEvents: z9.boolean(),
815
+ emitsCompactionEvents: z9.boolean(),
816
+ /** True when the provider reads a structured response from stdout. */
817
+ requiresHookResponse: z9.boolean(),
818
+ /** How much of this provider's hook traffic is replay-identifiable. */
819
+ deliveryIdentifier: deliveryIdentifierSupportSchema
820
+ });
821
+ var providerHookResponseSchema = z9.strictObject({
822
+ /**
823
+ * Always 0. A telemetry hook that can fail the host agent is a liability, so
824
+ * the type forbids expressing anything else (ADR 0004).
825
+ */
826
+ exitCode: z9.literal(0),
827
+ /** Protocol response text. Omit to write nothing at all. */
828
+ stdout: z9.string().max(8192).optional(),
829
+ /** Non-sensitive diagnostic text for stderr. */
830
+ stderr: z9.string().max(8192).optional(),
831
+ /** Declares which of the two stdout contracts this response follows. */
832
+ contract: z9.enum(["silent", "provider-protocol"])
833
+ });
834
+ var SILENT_HOOK_RESPONSE = Object.freeze({
835
+ exitCode: 0,
836
+ contract: "silent"
837
+ });
838
+ var adapterSupports = (adapter, eventType) => adapter.capabilities.lifecycleEvents.includes(eventType);
839
+ var describeAdapter = (adapter) => ({
840
+ id: adapter.id,
841
+ version: adapter.version,
842
+ lifecycleEvents: [...adapter.capabilities.lifecycleEvents],
843
+ usageTemporality: adapter.capabilities.usageTemporality,
844
+ deliveryIdentifier: adapter.capabilities.deliveryIdentifier
845
+ });
846
+ var readDeliveryClaim = (adapter, input, context) => {
847
+ if (adapter.deliveryIdentity === void 0) {
848
+ return {};
849
+ }
850
+ let candidate;
851
+ try {
852
+ candidate = adapter.deliveryIdentity(input, context);
853
+ } catch {
854
+ return { rejection: `adapter ${adapter.id} threw while reporting a delivery identity` };
855
+ }
856
+ if (candidate === void 0) {
857
+ return {};
858
+ }
859
+ const parsed = providerDeliveryClaimSchema.safeParse(candidate);
860
+ if (!parsed.success) {
861
+ return {
862
+ rejection: `adapter ${adapter.id} reported a malformed delivery identity: ${parsed.error.issues.map((issue) => `${issue.path.join(".") || "<root>"} ${issue.message}`).join("; ")}`.slice(0, 240)
863
+ };
864
+ }
865
+ return { claim: parsed.data };
866
+ };
867
+ var readDeliveryGap = (adapter, sourceEventName) => {
868
+ if (sourceEventName === void 0 || adapter.deliveryGaps === void 0) {
869
+ return void 0;
870
+ }
871
+ if (!Object.prototype.hasOwnProperty.call(adapter.deliveryGaps, sourceEventName)) {
872
+ return void 0;
873
+ }
874
+ const parsed = deliveryGapReasonSchema.safeParse(adapter.deliveryGaps[sourceEventName]);
875
+ return parsed.success ? parsed.data : void 0;
876
+ };
877
+ var asProviderId = (value) => providerIdSchema.parse(value);
878
+ var unknownDetection = (reasons = ["no adapter recognized the input"]) => providerDetectionSchema.parse({
879
+ providerId: "unknown",
880
+ confidence: "none",
881
+ reasons: reasons.slice(0, 8)
882
+ });
883
+
884
+ // src/errors/index.ts
885
+ import { z as z10 } from "zod";
886
+ var otelHookErrorInfoSchema = z10.strictObject({
887
+ code: otelHookErrorCodeSchema,
888
+ severity: errorSeveritySchema,
889
+ phase: errorPhaseSchema,
890
+ posture: failurePostureSchema,
891
+ retryable: z10.boolean(),
892
+ message: z10.string().min(1).max(512),
893
+ details: attributesSchema.optional(),
894
+ occurredAt: epochMillisSchema.optional()
895
+ });
896
+ var createErrorInfo = (input) => {
897
+ const descriptor = describeErrorCode(input.code);
898
+ const message = input.detail === void 0 ? `${input.code} during ${input.phase}: ${descriptor.summary}` : `${input.code} during ${input.phase}: ${input.detail}`;
899
+ return otelHookErrorInfoSchema.parse({
900
+ code: descriptor.code,
901
+ severity: descriptor.severity,
902
+ phase: input.phase,
903
+ posture: descriptor.posture,
904
+ retryable: descriptor.retryable,
905
+ message: message.slice(0, 512),
906
+ ...input.details === void 0 ? {} : { details: input.details },
907
+ ...input.occurredAt === void 0 ? {} : { occurredAt: input.occurredAt }
908
+ });
909
+ };
910
+ var OtelHookError = class _OtelHookError extends Error {
911
+ info;
912
+ constructor(info) {
913
+ super(info.message);
914
+ this.name = "OtelHookError";
915
+ this.info = info;
916
+ }
917
+ static of(input) {
918
+ return new _OtelHookError(createErrorInfo(input));
919
+ }
920
+ };
921
+ var isOtelHookError = (value) => value instanceof OtelHookError;
922
+ var describeThrown = (thrown) => {
923
+ if (thrown instanceof Error) {
924
+ return {
925
+ errorName: thrown.name.slice(0, 64) || "Error",
926
+ hasMessage: typeof thrown.message === "string" && thrown.message.length > 0
927
+ };
928
+ }
929
+ return { errorName: typeof thrown, hasMessage: false };
930
+ };
931
+ var errorInfoFromThrown = (thrown, input) => {
932
+ if (isOtelHookError(thrown)) {
933
+ return thrown.info;
934
+ }
935
+ const described = describeThrown(thrown);
936
+ return createErrorInfo({
937
+ code: input.code ?? "internal-error",
938
+ phase: input.phase,
939
+ detail: `contained ${described.errorName}`,
940
+ details: { "error.name": described.errorName, "error.has_message": described.hasMessage },
941
+ ...input.occurredAt === void 0 ? {} : { occurredAt: input.occurredAt }
942
+ });
943
+ };
944
+
945
+ // src/providers/builder.ts
946
+ var createEventFactory = (input) => {
947
+ const { identity, context } = input;
948
+ const built = [];
949
+ const dropped = [];
950
+ let sequence = input.sequenceBase;
951
+ return {
952
+ build: (draft) => {
953
+ const { occurredAt, extensions, idDiscriminator, ...rest } = draft;
954
+ const sanitized = extensions === void 0 ? { extensions: {}, droppedKeys: [] } : context.privacy.sanitizeExtensions(extensions);
955
+ dropped.push(...sanitized.droppedKeys);
956
+ const currentSequence = sequence;
957
+ sequence += 1;
958
+ const candidate = {
959
+ ...rest,
960
+ schemaVersion: CANONICAL_SCHEMA_VERSION,
961
+ eventId: context.ids.newEventId({
962
+ invocationId: identity.invocationId,
963
+ sequence: currentSequence,
964
+ eventType: rest.type,
965
+ ...idDiscriminator === void 0 ? {} : { discriminator: idDiscriminator }
966
+ }),
967
+ invocationId: identity.invocationId,
968
+ sessionId: identity.sessionId,
969
+ sequence: currentSequence,
970
+ occurredAt: occurredAt ?? context.clock.now(),
971
+ provenance: identity.provenance,
972
+ workspace: identity.workspace,
973
+ extensions: sanitized.extensions
974
+ };
975
+ const parsed = canonicalEventSchema.safeParse(candidate);
976
+ if (!parsed.success) {
977
+ throw OtelHookError.of({
978
+ code: "schema-validation-failed",
979
+ phase: "parsing",
980
+ detail: `event ${rest.type} rejected: ${parsed.error.issues.map((issue) => `${issue.path.join(".") || "<root>"} ${issue.message}`).join("; ")}`.slice(0, 480),
981
+ details: { "event.type": rest.type, "event.sequence": currentSequence }
982
+ });
983
+ }
984
+ built.push(parsed.data);
985
+ return parsed.data;
986
+ },
987
+ events: () => [...built],
988
+ nextSequence: () => sequence,
989
+ droppedExtensionKeys: () => [...dropped]
990
+ };
991
+ };
992
+
993
+ // src/providers/registry.ts
994
+ var createProviderRegistry = (adapters) => {
995
+ const byId = /* @__PURE__ */ new Map();
996
+ for (const adapter of adapters) {
997
+ if (byId.has(adapter.id)) {
998
+ throw createDuplicateAdapterError(adapter.id);
999
+ }
1000
+ byId.set(adapter.id, adapter);
1001
+ }
1002
+ const frozen = Object.freeze([...adapters]);
1003
+ return {
1004
+ adapters: frozen,
1005
+ get: (id) => byId.get(id),
1006
+ detect: (input, context, policy) => {
1007
+ const errors = [];
1008
+ const candidates = [];
1009
+ if (frozen.length === 0) {
1010
+ return {
1011
+ status: "unknown",
1012
+ reason: "no-adapters-registered",
1013
+ detection: unknownDetection(["no adapters registered"]),
1014
+ candidates,
1015
+ errors
1016
+ };
1017
+ }
1018
+ for (const adapter of frozen) {
1019
+ let detection;
1020
+ try {
1021
+ detection = providerDetectionSchema.parse(adapter.detect(input, context));
1022
+ } catch (thrown) {
1023
+ errors.push(errorInfoFromThrown(thrown, { code: "provider-adapter-failure", phase: "detection" }));
1024
+ continue;
1025
+ }
1026
+ if (detection.confidence === "none") {
1027
+ continue;
1028
+ }
1029
+ if (detection.providerId !== adapter.id) {
1030
+ errors.push(
1031
+ createErrorInfo({
1032
+ code: "provider-adapter-failure",
1033
+ phase: "detection",
1034
+ detail: `adapter ${adapter.id} claimed provider id ${detection.providerId}`,
1035
+ details: { "adapter.id": adapter.id, "detection.provider_id": detection.providerId }
1036
+ })
1037
+ );
1038
+ continue;
1039
+ }
1040
+ candidates.push({ adapter, detection });
1041
+ }
1042
+ if (candidates.length === 0) {
1043
+ return {
1044
+ status: "unknown",
1045
+ reason: "no-candidates",
1046
+ detection: unknownDetection(),
1047
+ candidates,
1048
+ errors
1049
+ };
1050
+ }
1051
+ const bestRank = Math.max(
1052
+ ...candidates.map((candidate) => DETECTION_CONFIDENCE_RANK[candidate.detection.confidence])
1053
+ );
1054
+ const best = candidates.filter(
1055
+ (candidate) => DETECTION_CONFIDENCE_RANK[candidate.detection.confidence] === bestRank
1056
+ );
1057
+ if (best.length > 1) {
1058
+ return {
1059
+ status: "ambiguous",
1060
+ detection: unknownDetection([
1061
+ `${best.length} adapters matched at equal confidence`,
1062
+ ...best.map((candidate) => `candidate ${candidate.adapter.id}`)
1063
+ ]),
1064
+ candidates,
1065
+ errors
1066
+ };
1067
+ }
1068
+ const [winner] = best;
1069
+ if (winner === void 0) {
1070
+ return {
1071
+ status: "unknown",
1072
+ reason: "no-candidates",
1073
+ detection: unknownDetection(),
1074
+ candidates,
1075
+ errors
1076
+ };
1077
+ }
1078
+ if (bestRank < DETECTION_CONFIDENCE_RANK[policy.minimumConfidence]) {
1079
+ return {
1080
+ status: "unknown",
1081
+ reason: "below-minimum-confidence",
1082
+ detection: unknownDetection([
1083
+ `best confidence ${winner.detection.confidence} is below required ${policy.minimumConfidence}`
1084
+ ]),
1085
+ candidates,
1086
+ errors
1087
+ };
1088
+ }
1089
+ if (policy.allowedProviderIds.length > 0 && !policy.allowedProviderIds.includes(winner.adapter.id)) {
1090
+ return {
1091
+ status: "unknown",
1092
+ reason: "provider-not-allowed",
1093
+ detection: unknownDetection([`provider ${winner.adapter.id} is not in the allow-list`]),
1094
+ candidates,
1095
+ errors
1096
+ };
1097
+ }
1098
+ return {
1099
+ status: "selected",
1100
+ adapter: winner.adapter,
1101
+ detection: winner.detection,
1102
+ candidates,
1103
+ errors
1104
+ };
1105
+ }
1106
+ };
1107
+ };
1108
+ var createDuplicateAdapterError = (id) => new Error(`duplicate provider adapter id: ${id}`);
1109
+ var BUILT_IN_PROVIDERS = Object.freeze([]);
1110
+
1111
+ // src/providers/claude/capabilities.ts
1112
+ var CLAUDE_CODE_CAPABILITIES = Object.freeze({
1113
+ lifecycleEvents: Object.freeze([
1114
+ "session.start",
1115
+ "session.end",
1116
+ "prompt.submitted",
1117
+ "generation.start",
1118
+ "generation.end",
1119
+ "tool.start",
1120
+ "tool.end",
1121
+ "subagent.start",
1122
+ "subagent.end",
1123
+ "compaction.performed"
1124
+ ]),
1125
+ usageTemporality: "delta",
1126
+ reportsCachedInput: true,
1127
+ reportsCacheCreation: true,
1128
+ cacheCreationAccounting: "included-in-input",
1129
+ reportsReasoningOutput: false,
1130
+ reportsProviderTotal: false,
1131
+ reportsCost: false,
1132
+ emitsSubagentEvents: true,
1133
+ emitsCompactionEvents: true,
1134
+ // The hook is telemetry-only and must never influence Claude Code's own
1135
+ // permission/continuation decisions (ADR 0004: fail-open).
1136
+ requiresHookResponse: false,
1137
+ // Tool, subagent, and prompt callbacks carry a replay-stable id, and so does
1138
+ // the once-per-prompt `Stop` (`stop_hook_active: false`). Session, compaction,
1139
+ // and continuation stops do not. See `./delivery.ts` for which and why.
1140
+ deliveryIdentifier: "partial"
1141
+ });
1142
+
1143
+ // src/providers/claude/schema.ts
1144
+ import { z as z11 } from "zod";
1145
+ var commonFields = {
1146
+ session_id: z11.string().min(1),
1147
+ transcript_path: z11.string().min(1).optional(),
1148
+ cwd: z11.string().min(1).optional(),
1149
+ permission_mode: z11.string().min(1).optional(),
1150
+ /** Correlates a hook firing with the user prompt that triggered it (Claude Code v2.1.196+). */
1151
+ prompt_id: z11.string().min(1).optional(),
1152
+ /** Present when the hook fired while running inside a subagent. */
1153
+ agent_id: z11.string().min(1).optional(),
1154
+ agent_type: z11.string().min(1).optional()
1155
+ };
1156
+ var claudeCacheCreationSchema = z11.object({
1157
+ ephemeral_5m_input_tokens: z11.number().int().min(0).optional(),
1158
+ ephemeral_1h_input_tokens: z11.number().int().min(0).optional()
1159
+ });
1160
+ var claudeUsageIterationSchema = z11.object({
1161
+ input_tokens: z11.number().int().min(0).optional(),
1162
+ output_tokens: z11.number().int().min(0).optional(),
1163
+ cache_creation_input_tokens: z11.number().int().min(0).optional(),
1164
+ cache_read_input_tokens: z11.number().int().min(0).optional()
1165
+ });
1166
+ var claudeUsageSchema = z11.object({
1167
+ input_tokens: z11.number().int().min(0),
1168
+ output_tokens: z11.number().int().min(0),
1169
+ cache_creation_input_tokens: z11.number().int().min(0).optional(),
1170
+ cache_read_input_tokens: z11.number().int().min(0).optional(),
1171
+ cache_creation: claudeCacheCreationSchema.optional(),
1172
+ iterations: z11.array(claudeUsageIterationSchema).optional(),
1173
+ /**
1174
+ * Counters the canonical model has a home for but Claude Code never reports:
1175
+ * 0 of 4,999 real usage objects carried either (finding 5).
1176
+ *
1177
+ * Named here rather than left to the object's forward-compatible looseness so
1178
+ * that a harness attaching one gets told it was excluded, instead of watching
1179
+ * it vanish. See `CLAUDE_EXCLUDED_USAGE_COUNTERS`.
1180
+ */
1181
+ total_tokens: z11.number().int().min(0).optional(),
1182
+ reasoning_output_tokens: z11.number().int().min(0).optional()
1183
+ });
1184
+ var sessionStartPayloadSchema = z11.object({
1185
+ ...commonFields,
1186
+ hook_event_name: z11.literal("SessionStart"),
1187
+ /** Matcher values: startup | resume | clear | compact | fork. Forward-compatible: any string. */
1188
+ source: z11.string().min(1).optional(),
1189
+ model: z11.string().min(1).optional(),
1190
+ session_title: z11.string().min(1).optional()
1191
+ });
1192
+ var sessionEndPayloadSchema = z11.object({
1193
+ ...commonFields,
1194
+ hook_event_name: z11.literal("SessionEnd"),
1195
+ /** Current Claude Code field; values include clear, logout, prompt_input_exit, and other. */
1196
+ reason: z11.string().min(1).optional(),
1197
+ /** Compatibility alias emitted by older wrappers and hook integrations. */
1198
+ end_reason: z11.string().min(1).optional()
1199
+ });
1200
+ var userPromptSubmitPayloadSchema = z11.object({
1201
+ ...commonFields,
1202
+ hook_event_name: z11.literal("UserPromptSubmit"),
1203
+ prompt: z11.string()
1204
+ });
1205
+ var preToolUsePayloadSchema = z11.object({
1206
+ ...commonFields,
1207
+ hook_event_name: z11.literal("PreToolUse"),
1208
+ tool_name: z11.string().min(1),
1209
+ tool_input: z11.unknown(),
1210
+ tool_use_id: z11.string().min(1)
1211
+ });
1212
+ var postToolUsePayloadSchema = z11.object({
1213
+ ...commonFields,
1214
+ hook_event_name: z11.literal("PostToolUse"),
1215
+ tool_name: z11.string().min(1),
1216
+ tool_input: z11.unknown().optional(),
1217
+ tool_response: z11.unknown(),
1218
+ tool_use_id: z11.string().min(1)
1219
+ });
1220
+ var postToolUseFailurePayloadSchema = z11.object({
1221
+ ...commonFields,
1222
+ hook_event_name: z11.literal("PostToolUseFailure"),
1223
+ tool_name: z11.string().min(1),
1224
+ tool_input: z11.unknown().optional(),
1225
+ tool_error: z11.unknown(),
1226
+ tool_use_id: z11.string().min(1)
1227
+ });
1228
+ var permissionRequestPayloadSchema = z11.object({
1229
+ ...commonFields,
1230
+ hook_event_name: z11.literal("PermissionRequest"),
1231
+ tool_name: z11.string().min(1),
1232
+ tool_input: z11.unknown().optional(),
1233
+ tool_use_id: z11.string().min(1)
1234
+ });
1235
+ var subagentStartPayloadSchema = z11.object({
1236
+ ...commonFields,
1237
+ hook_event_name: z11.literal("SubagentStart"),
1238
+ agent_type: z11.string().min(1),
1239
+ agent_id: z11.string().min(1)
1240
+ });
1241
+ var subagentStopPayloadSchema = z11.object({
1242
+ ...commonFields,
1243
+ hook_event_name: z11.literal("SubagentStop"),
1244
+ agent_type: z11.string().min(1),
1245
+ agent_id: z11.string().min(1),
1246
+ last_assistant_message: z11.string().optional(),
1247
+ /** True when this stop fired because a hook continued the subagent's turn. */
1248
+ stop_hook_active: z11.boolean().optional(),
1249
+ usage: claudeUsageSchema.optional()
1250
+ });
1251
+ var preCompactPayloadSchema = z11.object({
1252
+ ...commonFields,
1253
+ hook_event_name: z11.literal("PreCompact"),
1254
+ /** Upstream values: manual | auto. Forward-compatible: any string. */
1255
+ trigger: z11.string().min(1).optional(),
1256
+ /** Compatibility alias emitted by older wrappers and hook integrations. */
1257
+ compact_trigger: z11.string().min(1).optional(),
1258
+ /**
1259
+ * Harness-supplied, never upstream. Reported as an explicit exclusion rather
1260
+ * than carried across the process boundary: see `events.ts`.
1261
+ */
1262
+ context_tokens_before: z11.number().int().min(0).optional(),
1263
+ estimated_tokens_removed: z11.number().int().min(0).optional()
1264
+ });
1265
+ var postCompactPayloadSchema = z11.object({
1266
+ ...commonFields,
1267
+ hook_event_name: z11.literal("PostCompact"),
1268
+ trigger: z11.string().min(1).optional(),
1269
+ compact_trigger: z11.string().min(1).optional(),
1270
+ /** Harness-supplied, never upstream; accepted here because one callback carries both. */
1271
+ context_tokens_before: z11.number().int().min(0).optional(),
1272
+ context_tokens_after: z11.number().int().min(0).optional(),
1273
+ dropped_message_count: z11.number().int().min(0).optional(),
1274
+ usage: claudeUsageSchema.optional()
1275
+ });
1276
+ var stopPayloadSchema = z11.object({
1277
+ ...commonFields,
1278
+ hook_event_name: z11.literal("Stop"),
1279
+ last_assistant_message: z11.string().optional(),
1280
+ /**
1281
+ * True when this stop fired because a hook continued the turn.
1282
+ *
1283
+ * Required upstream, optional here. It is what separates the once-per-prompt
1284
+ * stop from a continuation stop, which is what lets `delivery.ts` deduplicate
1285
+ * the former without suppressing the latter.
1286
+ */
1287
+ stop_hook_active: z11.boolean().optional(),
1288
+ usage: claudeUsageSchema.optional()
1289
+ });
1290
+ var stopFailurePayloadSchema = z11.object({
1291
+ ...commonFields,
1292
+ hook_event_name: z11.literal("StopFailure"),
1293
+ /**
1294
+ * Matcher values: rate_limit | overloaded | authentication_failed |
1295
+ * oauth_org_not_allowed | billing_error | invalid_request | model_not_found
1296
+ * | server_error | max_output_tokens | unknown.
1297
+ */
1298
+ error_type: z11.string().min(1),
1299
+ error_message: z11.string().optional(),
1300
+ usage: claudeUsageSchema.optional()
1301
+ });
1302
+ var claudeHookPayloadSchema = z11.discriminatedUnion("hook_event_name", [
1303
+ sessionStartPayloadSchema,
1304
+ sessionEndPayloadSchema,
1305
+ userPromptSubmitPayloadSchema,
1306
+ preToolUsePayloadSchema,
1307
+ postToolUsePayloadSchema,
1308
+ postToolUseFailurePayloadSchema,
1309
+ permissionRequestPayloadSchema,
1310
+ subagentStartPayloadSchema,
1311
+ subagentStopPayloadSchema,
1312
+ preCompactPayloadSchema,
1313
+ postCompactPayloadSchema,
1314
+ stopPayloadSchema,
1315
+ stopFailurePayloadSchema
1316
+ ]);
1317
+ var CLAUDE_HOOK_EVENT_NAMES = [
1318
+ "SessionStart",
1319
+ "SessionEnd",
1320
+ "UserPromptSubmit",
1321
+ "PreToolUse",
1322
+ "PostToolUse",
1323
+ "PostToolUseFailure",
1324
+ "PermissionRequest",
1325
+ "SubagentStart",
1326
+ "SubagentStop",
1327
+ "PreCompact",
1328
+ "PostCompact",
1329
+ "Stop",
1330
+ "StopFailure"
1331
+ ];
1332
+ var claudeIdentityFieldsSchema = z11.object({
1333
+ session_id: z11.string().min(1),
1334
+ hook_event_name: z11.string().min(1),
1335
+ cwd: z11.string().min(1).optional(),
1336
+ prompt_id: z11.string().min(1).optional(),
1337
+ agent_id: z11.string().min(1).optional(),
1338
+ tool_use_id: z11.string().min(1).optional(),
1339
+ /** Read by `delivery.ts` to tell a once-per-prompt stop from a continuation. */
1340
+ stop_hook_active: z11.boolean().optional()
1341
+ });
1342
+
1343
+ // src/providers/claude/delivery.ts
1344
+ var TOOL_SCOPED_EVENTS = [
1345
+ "PreToolUse",
1346
+ "PostToolUse",
1347
+ "PostToolUseFailure",
1348
+ "PermissionRequest"
1349
+ ];
1350
+ var claudeDeliveryIdentity = (input) => {
1351
+ const parsed = claudeIdentityFieldsSchema.safeParse(input.payload);
1352
+ if (!parsed.success) {
1353
+ return void 0;
1354
+ }
1355
+ const fields = parsed.data;
1356
+ const base = { sessionId: fields.session_id, sourceEventName: fields.hook_event_name };
1357
+ if (TOOL_SCOPED_EVENTS.includes(fields.hook_event_name) && fields.tool_use_id !== void 0) {
1358
+ return {
1359
+ ...base,
1360
+ components: [fields.tool_use_id],
1361
+ evidence: ["payload.tool_use_id names one tool call and repeats on redelivery"]
1362
+ };
1363
+ }
1364
+ if (fields.hook_event_name === "SubagentStart" && fields.agent_id !== void 0) {
1365
+ return {
1366
+ ...base,
1367
+ components: [fields.agent_id],
1368
+ evidence: ["payload.agent_id names one subagent instance"]
1369
+ };
1370
+ }
1371
+ if (fields.hook_event_name === "SubagentStop" && fields.agent_id !== void 0 && fields.stop_hook_active !== true) {
1372
+ return {
1373
+ ...base,
1374
+ components: [fields.agent_id],
1375
+ evidence: [
1376
+ "payload.agent_id names one subagent instance",
1377
+ "payload.stop_hook_active is not true, so this is not a hook-continued second stop"
1378
+ ]
1379
+ };
1380
+ }
1381
+ if (fields.hook_event_name === "UserPromptSubmit" && fields.prompt_id !== void 0) {
1382
+ return {
1383
+ ...base,
1384
+ components: [fields.prompt_id],
1385
+ evidence: ["payload.prompt_id names one prompt, submitted exactly once"]
1386
+ };
1387
+ }
1388
+ if (fields.hook_event_name === "Stop" && fields.prompt_id !== void 0 && fields.stop_hook_active === false) {
1389
+ return {
1390
+ ...base,
1391
+ // `agent_id` is present when the stop fired inside a subagent, where the
1392
+ // prompt is shared with the main thread's own stop.
1393
+ components: fields.agent_id === void 0 ? [fields.prompt_id] : [fields.prompt_id, fields.agent_id],
1394
+ evidence: [
1395
+ "payload.prompt_id names one prompt",
1396
+ "payload.stop_hook_active is false, so this is the once-per-prompt stop rather than a continuation"
1397
+ ]
1398
+ };
1399
+ }
1400
+ return void 0;
1401
+ };
1402
+ var CLAUDE_DELIVERY_GAPS = Object.freeze({
1403
+ SessionStart: "no per-firing id; payload `source` (startup, resume, clear, compact, fork) means SessionStart fires repeatedly under one session_id",
1404
+ SessionEnd: "no per-firing id; a cleared and a resumed session end under the same session_id",
1405
+ PreCompact: "no compaction id; payload `trigger` does not separate two genuine compactions",
1406
+ PostCompact: "no compaction id; payload `trigger` does not separate two genuine compactions",
1407
+ Stop: "prompt_id is not a delivery identity here: Claude Code can fire Stop more than once per prompt when a hook continues the turn (stop_hook_active)",
1408
+ StopFailure: "prompt_id is not a delivery identity here: one prompt can fail more than once, and error_type names a class rather than a firing",
1409
+ PreToolUse: "payload.tool_use_id absent; nothing else in this callback names one tool call",
1410
+ PostToolUse: "payload.tool_use_id absent; nothing else in this callback names one tool call",
1411
+ PostToolUseFailure: "payload.tool_use_id absent; nothing else in this callback names one tool call",
1412
+ PermissionRequest: "payload.tool_use_id absent; nothing else in this callback names one tool call",
1413
+ SubagentStart: "payload.agent_id absent; agent_type names a class of subagents, not an instance",
1414
+ SubagentStop: "payload.agent_id absent; agent_type names a class of subagents, not an instance",
1415
+ UserPromptSubmit: "payload.prompt_id absent; requires Claude Code v2.1.196 or later"
1416
+ });
1417
+
1418
+ // src/providers/claude/detect.ts
1419
+ var CLAUDE_CODE_PROVIDER_ID = asProviderId("claude-code");
1420
+ var KNOWN_EVENT_NAMES = new Set(CLAUDE_HOOK_EVENT_NAMES);
1421
+ var none = (reason) => providerDetectionSchema.parse({
1422
+ providerId: "unknown",
1423
+ confidence: "none",
1424
+ reasons: [reason]
1425
+ });
1426
+ var detectClaudeCode = (input) => {
1427
+ const { payload } = input;
1428
+ if (typeof payload !== "object" || payload === null || Array.isArray(payload)) {
1429
+ return none("payload is not a JSON object");
1430
+ }
1431
+ const record = payload;
1432
+ const hookEventName = record.hook_event_name;
1433
+ if (typeof hookEventName !== "string" || !KNOWN_EVENT_NAMES.has(hookEventName)) {
1434
+ return none("hook_event_name is missing or not a recognized Claude Code hook event");
1435
+ }
1436
+ const sessionId = record.session_id;
1437
+ if (typeof sessionId !== "string" || sessionId.length === 0) {
1438
+ return none("session_id is missing");
1439
+ }
1440
+ const hasTranscriptPath = typeof record.transcript_path === "string" && record.transcript_path.length > 0;
1441
+ const hinted = input.providerHint === CLAUDE_CODE_PROVIDER_ID;
1442
+ return providerDetectionSchema.parse({
1443
+ providerId: CLAUDE_CODE_PROVIDER_ID,
1444
+ confidence: hinted ? "exact" : hasTranscriptPath ? "strong" : "weak",
1445
+ reasons: [
1446
+ `hook_event_name=${hookEventName} matches the Claude Code hooks protocol`,
1447
+ "session_id present",
1448
+ ...hasTranscriptPath ? ["transcript_path present"] : [],
1449
+ ...hinted ? ["caller asserted providerHint=claude-code"] : []
1450
+ ],
1451
+ sourceEventName: hookEventName
1452
+ });
1453
+ };
1454
+
1455
+ // src/privacy/workspace.ts
1456
+ var canonicalizeGitRemote = (remoteUrl) => {
1457
+ const trimmed = remoteUrl.trim();
1458
+ const scpLike = /^([^@/]+)@([^:]+):(.+)$/.exec(trimmed);
1459
+ const withoutScheme = scpLike ? `${scpLike[2] ?? ""}/${scpLike[3] ?? ""}` : trimmed.replace(/^[a-zA-Z][a-zA-Z0-9+.-]*:\/\//, "").replace(/^[^@/]+@/, "");
1460
+ return withoutScheme.replace(/:\d+\//, "/").replace(/\/+$/, "").replace(/\.git$/i, "").replace(/\/+$/, "").toLowerCase();
1461
+ };
1462
+ var keySourceOf = (input) => {
1463
+ switch (input.kind) {
1464
+ case "git-remote":
1465
+ return "git-remote";
1466
+ case "git-root":
1467
+ return "git-root";
1468
+ case "working-directory":
1469
+ return "working-directory";
1470
+ case "explicit":
1471
+ return "explicit";
1472
+ case "unknown":
1473
+ return "unknown";
1474
+ }
1475
+ };
1476
+ var keyMaterialOf = (input) => {
1477
+ switch (input.kind) {
1478
+ case "git-remote":
1479
+ return canonicalizeGitRemote(input.remoteUrl);
1480
+ case "git-root":
1481
+ case "working-directory":
1482
+ return input.absolutePath.replace(/[/\\]+$/, "");
1483
+ case "explicit":
1484
+ return input.value;
1485
+ case "unknown":
1486
+ return void 0;
1487
+ }
1488
+ };
1489
+ var deriveWorkspaceIdentity = (privacy, input, labels = {}) => {
1490
+ const keySource = keySourceOf(input);
1491
+ const material = keyMaterialOf(input);
1492
+ const workspaceId = material === void 0 || material === "" ? "unknown:0000000000000000" : privacy.deriveOpaqueId(`workspace/${keySource}`, material);
1493
+ return workspaceIdentitySchema.parse({
1494
+ workspaceId,
1495
+ keySource: material === void 0 || material === "" ? "unknown" : keySource,
1496
+ ...labels.repositoryName === void 0 ? {} : { repositoryName: labels.repositoryName.slice(0, 128) },
1497
+ ...labels.vcsBranchName === void 0 ? {} : { vcsBranchName: labels.vcsBranchName.slice(0, 128) },
1498
+ ...labels.vcsRevisionId === void 0 ? {} : { vcsRevisionId: privacy.deriveOpaqueId("workspace/revision", labels.vcsRevisionId) }
1499
+ });
1500
+ };
1501
+
1502
+ // src/providers/claude/identity.ts
1503
+ var subagentInvocationIdFor = (context, sessionId, agentId) => invocationIdSchema.parse(`subagent_${context.ids.newOpaqueId(["claude-subagent", sessionId, agentId])}`);
1504
+ var identifyClaudeCode = (input, context) => {
1505
+ const parsed = claudeIdentityFieldsSchema.safeParse(input.payload);
1506
+ if (!parsed.success) {
1507
+ return [];
1508
+ }
1509
+ const fields = parsed.data;
1510
+ const sessionId = sessionIdSchema.parse(fields.session_id);
1511
+ const occurredAt = context.clock.now();
1512
+ const discriminator = fields.tool_use_id ?? fields.prompt_id ?? fields.agent_id;
1513
+ const invocationId = context.ids.newInvocationId({
1514
+ providerId: CLAUDE_CODE_PROVIDER_ID,
1515
+ sessionId,
1516
+ sourceEventName: fields.hook_event_name,
1517
+ occurredAt,
1518
+ ...discriminator === void 0 ? {} : { discriminator }
1519
+ });
1520
+ const isSubagentLifecycleEvent = fields.hook_event_name === "SubagentStart" || fields.hook_event_name === "SubagentStop";
1521
+ const parentInvocationId = fields.agent_id !== void 0 && !isSubagentLifecycleEvent ? subagentInvocationIdFor(context, sessionId, fields.agent_id) : void 0;
1522
+ const claim = identityClaimSchema.parse({
1523
+ source: `adapter:${CLAUDE_CODE_PROVIDER_ID}`,
1524
+ confidence: input.detection.confidence,
1525
+ fields: {
1526
+ sessionId,
1527
+ invocationId,
1528
+ startedAt: occurredAt,
1529
+ ...fields.cwd === void 0 ? {} : { workspace: deriveWorkspaceIdentity(context.privacy, { kind: "working-directory", absolutePath: fields.cwd }) },
1530
+ ...parentInvocationId === void 0 ? {} : { parentInvocationId },
1531
+ ...fields.agent_id === void 0 ? {} : { agentInstanceId: fields.agent_id }
1532
+ }
1533
+ });
1534
+ return [claim];
1535
+ };
1536
+
1537
+ // src/providers/claude/tool-kind.ts
1538
+ var BUILT_IN_TOOL_KIND = Object.freeze({
1539
+ Bash: "execute",
1540
+ BashOutput: "execute",
1541
+ KillShell: "execute",
1542
+ Read: "read",
1543
+ NotebookRead: "read",
1544
+ Write: "write",
1545
+ Edit: "write",
1546
+ MultiEdit: "write",
1547
+ NotebookEdit: "write",
1548
+ Glob: "search",
1549
+ Grep: "search",
1550
+ WebFetch: "network",
1551
+ WebSearch: "network",
1552
+ Task: "delegate",
1553
+ TodoWrite: "other",
1554
+ ExitPlanMode: "other",
1555
+ AskUserQuestion: "other",
1556
+ SlashCommand: "other"
1557
+ });
1558
+ var inferToolKind = (toolName) => {
1559
+ if (toolName.startsWith("mcp__")) {
1560
+ return "unknown";
1561
+ }
1562
+ return BUILT_IN_TOOL_KIND[toolName] ?? "unknown";
1563
+ };
1564
+
1565
+ // src/providers/claude/usage.ts
1566
+ var CLAUDE_EXCLUDED_USAGE_COUNTERS = Object.freeze({
1567
+ total_tokens: `usage.total_tokens is outside Claude Code's usage contract (capability reportsProviderTotal=false): it is not read, so providerTotalAgreement stays "unreported"`,
1568
+ reasoning_output_tokens: "usage.reasoning_output_tokens is outside Claude Code's usage contract (capability reportsReasoningOutput=false): Anthropic bills thinking tokens inside output_tokens with no separate counter, so it is not read and reasoningOutputTokens stays 0"
1569
+ });
1570
+ var ITERATION_COUNTERS = [
1571
+ "input_tokens",
1572
+ "output_tokens",
1573
+ "cache_read_input_tokens",
1574
+ "cache_creation_input_tokens"
1575
+ ];
1576
+ var ttlSplitTotal = (raw) => {
1577
+ const split = raw.cache_creation;
1578
+ if (split === void 0) {
1579
+ return void 0;
1580
+ }
1581
+ return (split.ephemeral_5m_input_tokens ?? 0) + (split.ephemeral_1h_input_tokens ?? 0);
1582
+ };
1583
+ var resolveCacheCreationTokens = (raw, warnings) => {
1584
+ const declared = raw.cache_creation_input_tokens;
1585
+ const split = ttlSplitTotal(raw);
1586
+ if (declared === void 0) {
1587
+ return split ?? 0;
1588
+ }
1589
+ if (split !== void 0 && split !== declared) {
1590
+ warnings.push(
1591
+ `usage.cache_creation TTL buckets sum to ${String(split)} but usage.cache_creation_input_tokens reports ${String(declared)}; the explicit counter is used and the buckets are never added to it`
1592
+ );
1593
+ }
1594
+ return declared;
1595
+ };
1596
+ var auditIterations = (raw, cacheCreationInputTokens, warnings) => {
1597
+ const iterations = raw.iterations;
1598
+ if (iterations === void 0 || iterations.length === 0) {
1599
+ return;
1600
+ }
1601
+ const outer = {
1602
+ input_tokens: raw.input_tokens,
1603
+ output_tokens: raw.output_tokens,
1604
+ cache_read_input_tokens: raw.cache_read_input_tokens ?? 0,
1605
+ cache_creation_input_tokens: cacheCreationInputTokens
1606
+ };
1607
+ for (const counter of ITERATION_COUNTERS) {
1608
+ const summed = iterations.reduce((total, iteration) => total + (iteration[counter] ?? 0), 0);
1609
+ if (summed !== outer[counter]) {
1610
+ warnings.push(
1611
+ `usage.iterations[].${counter} sums to ${String(summed)} but usage.${counter} reports ${String(outer[counter])}; the outer counter is used and per-iteration figures are never added to it`
1612
+ );
1613
+ }
1614
+ }
1615
+ };
1616
+ var auditExcludedCounters = (raw, warnings) => {
1617
+ if (raw.total_tokens !== void 0) {
1618
+ warnings.push(CLAUDE_EXCLUDED_USAGE_COUNTERS.total_tokens);
1619
+ }
1620
+ if (raw.reasoning_output_tokens !== void 0) {
1621
+ warnings.push(CLAUDE_EXCLUDED_USAGE_COUNTERS.reasoning_output_tokens);
1622
+ }
1623
+ };
1624
+ var ACCOUNTING_RETAINED_NOTE_PREFIX = "cacheCreationAccounting=";
1625
+ var forwardableNotes = (notes) => notes.filter((note) => !note.startsWith(ACCOUNTING_RETAINED_NOTE_PREFIX));
1626
+ var normalizeClaudeUsage = (raw) => {
1627
+ if (raw === void 0) {
1628
+ return { warnings: [] };
1629
+ }
1630
+ const warnings = [];
1631
+ const cachedInputTokens = raw.cache_read_input_tokens ?? 0;
1632
+ const cacheCreationInputTokens = resolveCacheCreationTokens(raw, warnings);
1633
+ auditIterations(raw, cacheCreationInputTokens, warnings);
1634
+ auditExcludedCounters(raw, warnings);
1635
+ const result = normalizeUsage({
1636
+ temporality: "delta",
1637
+ inputTokens: raw.input_tokens + cachedInputTokens + cacheCreationInputTokens,
1638
+ cachedInputTokens,
1639
+ cacheCreationInputTokens,
1640
+ cacheCreationAccounting: "included-in-input",
1641
+ outputTokens: raw.output_tokens
1642
+ });
1643
+ if (result.status === "invalid") {
1644
+ return { warnings: [...warnings, ...result.issues.map((issue) => issue.message)] };
1645
+ }
1646
+ return { usage: result.usage, warnings: [...warnings, ...forwardableNotes(result.notes)] };
1647
+ };
1648
+
1649
+ // src/providers/claude/events.ts
1650
+ var UNKNOWN_MODEL = { modelId: "unknown" };
1651
+ var SESSION_END_REASON = Object.freeze({
1652
+ completed: "completed",
1653
+ aborted: "aborted",
1654
+ error: "error",
1655
+ timeout: "timeout",
1656
+ clear: "completed",
1657
+ resume: "completed",
1658
+ prompt_input_exit: "completed",
1659
+ logout: "aborted",
1660
+ bypass_permissions_disabled: "aborted",
1661
+ other: "unknown"
1662
+ });
1663
+ var mapSessionEndReason = (raw) => raw === void 0 ? "unknown" : SESSION_END_REASON[raw] ?? "unknown";
1664
+ var mapCompactTrigger = (raw) => {
1665
+ if (raw === "auto" || raw === "automatic") {
1666
+ return "automatic";
1667
+ }
1668
+ if (raw === "manual") {
1669
+ return "manual";
1670
+ }
1671
+ return "unknown";
1672
+ };
1673
+ var DENIED_STOP_FAILURE_TYPES = /* @__PURE__ */ new Set([
1674
+ "authentication_failed",
1675
+ "oauth_org_not_allowed",
1676
+ "billing_error"
1677
+ ]);
1678
+ var mapStopFailureOutcome = (errorType) => DENIED_STOP_FAILURE_TYPES.has(errorType) ? "denied" : "error";
1679
+ var applyUsage = (normalized) => normalized.usage === void 0 ? {} : { usage: normalized.usage };
1680
+ var parseClaudeCode = (input, context) => {
1681
+ const parsed = claudeHookPayloadSchema.safeParse(input.payload);
1682
+ if (!parsed.success) {
1683
+ const rawEventName = typeof input.payload === "object" && input.payload !== null ? input.payload.hook_event_name : void 0;
1684
+ return {
1685
+ status: "failed",
1686
+ error: createErrorInfo({
1687
+ code: "invalid-input",
1688
+ phase: "parsing",
1689
+ detail: `payload failed Claude Code schema validation: ${parsed.error.issues.map((issue) => `${issue.path.join(".") || "<root>"} ${issue.message}`).join("; ")}`.slice(0, 480),
1690
+ details: { "hook.event_name": typeof rawEventName === "string" ? rawEventName : "" }
1691
+ })
1692
+ };
1693
+ }
1694
+ const payload = parsed.data;
1695
+ const factory = createEventFactory({
1696
+ identity: input.identity,
1697
+ sequenceBase: input.sequenceBase,
1698
+ context
1699
+ });
1700
+ const warnings = [];
1701
+ const withUsage = (usage) => {
1702
+ const normalized = normalizeClaudeUsage(usage);
1703
+ warnings.push(...normalized.warnings);
1704
+ return applyUsage(normalized);
1705
+ };
1706
+ switch (payload.hook_event_name) {
1707
+ case "SessionStart":
1708
+ factory.build({
1709
+ type: "session.start",
1710
+ sessionKind: "unknown",
1711
+ agentName: "claude-code",
1712
+ ...payload.model === void 0 ? {} : { model: { modelId: payload.model } }
1713
+ });
1714
+ break;
1715
+ case "SessionEnd":
1716
+ factory.build({
1717
+ type: "session.end",
1718
+ reason: mapSessionEndReason(payload.reason ?? payload.end_reason)
1719
+ });
1720
+ break;
1721
+ case "UserPromptSubmit":
1722
+ factory.build({
1723
+ type: "prompt.submitted",
1724
+ promptSource: "user",
1725
+ content: context.privacy.describeContent({ kind: "prompt", role: "user", text: payload.prompt })
1726
+ });
1727
+ break;
1728
+ case "PreToolUse":
1729
+ factory.build({
1730
+ type: "tool.start",
1731
+ toolCallId: payload.tool_use_id,
1732
+ toolName: payload.tool_name,
1733
+ toolKind: inferToolKind(payload.tool_name),
1734
+ ...payload.tool_input === void 0 ? {} : {
1735
+ input: context.privacy.describeStructured({
1736
+ kind: "tool-input",
1737
+ value: payload.tool_input,
1738
+ label: payload.tool_name
1739
+ })
1740
+ }
1741
+ });
1742
+ break;
1743
+ case "PostToolUse":
1744
+ factory.build({
1745
+ type: "tool.end",
1746
+ toolCallId: payload.tool_use_id,
1747
+ toolName: payload.tool_name,
1748
+ outcome: "ok",
1749
+ output: context.privacy.describeStructured({
1750
+ kind: "tool-output",
1751
+ value: payload.tool_response,
1752
+ label: payload.tool_name
1753
+ })
1754
+ });
1755
+ break;
1756
+ case "PostToolUseFailure":
1757
+ factory.build({
1758
+ type: "tool.end",
1759
+ toolCallId: payload.tool_use_id,
1760
+ toolName: payload.tool_name,
1761
+ outcome: "error",
1762
+ output: context.privacy.describeStructured({
1763
+ kind: "tool-output",
1764
+ value: payload.tool_error,
1765
+ label: payload.tool_name
1766
+ })
1767
+ });
1768
+ break;
1769
+ case "PermissionRequest":
1770
+ return {
1771
+ status: "ignored",
1772
+ reason: "permission requests carry no telemetry independent of the tool call they gate"
1773
+ };
1774
+ case "SubagentStart":
1775
+ factory.build({
1776
+ type: "subagent.start",
1777
+ subagentInvocationId: subagentInvocationIdFor(context, payload.session_id, payload.agent_id),
1778
+ subagentType: payload.agent_type,
1779
+ delegationDepth: 1
1780
+ });
1781
+ break;
1782
+ case "SubagentStop":
1783
+ factory.build({
1784
+ type: "subagent.end",
1785
+ subagentInvocationId: subagentInvocationIdFor(context, payload.session_id, payload.agent_id),
1786
+ outcome: "ok",
1787
+ ...withUsage(payload.usage)
1788
+ });
1789
+ break;
1790
+ case "PreCompact":
1791
+ return {
1792
+ status: "ignored",
1793
+ reason: payload.context_tokens_before === void 0 ? "compaction is reported once it completes, at PostCompact" : "contextTokensBefore is an explicit exclusion for this provider: attach context_tokens_before to PostCompact, which carries both ends in one callback"
1794
+ };
1795
+ case "PostCompact":
1796
+ factory.build({
1797
+ type: "compaction.performed",
1798
+ trigger: mapCompactTrigger(payload.trigger ?? payload.compact_trigger),
1799
+ ...payload.context_tokens_before === void 0 ? {} : { contextTokensBefore: payload.context_tokens_before },
1800
+ ...payload.context_tokens_after === void 0 ? {} : { contextTokensAfter: payload.context_tokens_after },
1801
+ ...payload.dropped_message_count === void 0 ? {} : { droppedMessageCount: payload.dropped_message_count },
1802
+ ...withUsage(payload.usage)
1803
+ });
1804
+ break;
1805
+ case "Stop": {
1806
+ const generationId = context.ids.newOpaqueId([
1807
+ "claude-generation",
1808
+ payload.session_id,
1809
+ payload.prompt_id ?? String(input.sequenceBase)
1810
+ ]);
1811
+ factory.build({ type: "generation.start", generationId, model: UNKNOWN_MODEL });
1812
+ factory.build({
1813
+ type: "generation.end",
1814
+ generationId,
1815
+ model: UNKNOWN_MODEL,
1816
+ outcome: "ok",
1817
+ ...withUsage(payload.usage)
1818
+ });
1819
+ break;
1820
+ }
1821
+ case "StopFailure": {
1822
+ const generationId = context.ids.newOpaqueId([
1823
+ "claude-generation",
1824
+ payload.session_id,
1825
+ payload.prompt_id ?? String(input.sequenceBase)
1826
+ ]);
1827
+ factory.build({ type: "generation.start", generationId, model: UNKNOWN_MODEL });
1828
+ factory.build({
1829
+ type: "generation.end",
1830
+ generationId,
1831
+ model: UNKNOWN_MODEL,
1832
+ outcome: mapStopFailureOutcome(payload.error_type),
1833
+ stopReason: payload.error_type,
1834
+ ...withUsage(payload.usage)
1835
+ });
1836
+ break;
1837
+ }
1838
+ }
1839
+ return {
1840
+ status: "parsed",
1841
+ events: factory.events(),
1842
+ ...warnings.length === 0 ? {} : { warnings }
1843
+ };
1844
+ };
1845
+
1846
+ // src/providers/claude/adapter.ts
1847
+ var createClaudeCodeAdapter = (options = {}) => ({
1848
+ id: CLAUDE_CODE_PROVIDER_ID,
1849
+ version: options.version ?? "1.0.0",
1850
+ capabilities: CLAUDE_CODE_CAPABILITIES,
1851
+ detect: (input) => detectClaudeCode(input),
1852
+ identify: (input, context) => identifyClaudeCode(input, context),
1853
+ deliveryIdentity: (input) => claudeDeliveryIdentity(input),
1854
+ deliveryGaps: CLAUDE_DELIVERY_GAPS,
1855
+ parse: (input, context) => parseClaudeCode(input, context),
1856
+ hookResponse: () => SILENT_HOOK_RESPONSE
1857
+ });
1858
+
1859
+ // src/providers/cursor/payload.ts
1860
+ import { z as z12 } from "zod";
1861
+ var CURSOR_PROVIDER_ID = "cursor";
1862
+ var CURSOR_HOOK_EVENT_NAMES = [
1863
+ "sessionStart",
1864
+ "sessionEnd",
1865
+ "beforeSubmitPrompt",
1866
+ "afterAgentResponse",
1867
+ "afterAgentThought",
1868
+ "preToolUse",
1869
+ "postToolUse",
1870
+ "postToolUseFailure",
1871
+ "beforeShellExecution",
1872
+ "afterShellExecution",
1873
+ "beforeMCPExecution",
1874
+ "afterMCPExecution",
1875
+ "beforeReadFile",
1876
+ "afterFileEdit",
1877
+ "subagentStart",
1878
+ "subagentStop",
1879
+ "preCompact",
1880
+ "stop"
1881
+ ];
1882
+ var CURSOR_UNMODELLED_HOOK_EVENT_NAMES = Object.freeze({
1883
+ beforeTabFileRead: "a Tab (inline-completion) hook, not an agent-session hook; it belongs to no generation or tool lifecycle this model expresses",
1884
+ afterTabFileEdit: "a Tab (inline-completion) hook, as above",
1885
+ workspaceOpen: "an app-lifecycle hook that the reference states omits conversation_id, generation_id, model, session_id, and transcript_path, so it carries no session to attribute telemetry to"
1886
+ });
1887
+ var CURSOR_DECISION_EVENTS = Object.freeze({
1888
+ preToolUse: "permission",
1889
+ beforeShellExecution: "permission",
1890
+ beforeMCPExecution: "permission",
1891
+ beforeReadFile: "permission",
1892
+ subagentStart: "permission",
1893
+ beforeSubmitPrompt: "continue"
1894
+ });
1895
+ var modelParamSchema = z12.object({
1896
+ id: z12.string(),
1897
+ value: z12.string()
1898
+ });
1899
+ var attachmentSchema = z12.object({
1900
+ type: z12.string().optional(),
1901
+ file_path: z12.string().optional()
1902
+ });
1903
+ var fileEditSchema = z12.object({
1904
+ old_string: z12.string().optional(),
1905
+ new_string: z12.string().optional()
1906
+ });
1907
+ var usageFields = {
1908
+ input_tokens: z12.number().int().min(0).optional(),
1909
+ output_tokens: z12.number().int().min(0).optional(),
1910
+ cache_read_tokens: z12.number().int().min(0).optional(),
1911
+ cache_write_tokens: z12.number().int().min(0).optional()
1912
+ };
1913
+ var envelopeShape = {
1914
+ conversation_id: z12.string().min(1),
1915
+ generation_id: z12.string().optional(),
1916
+ session_id: z12.string().optional(),
1917
+ model: z12.string().optional(),
1918
+ model_id: z12.string().optional(),
1919
+ model_params: z12.array(modelParamSchema).max(64).optional(),
1920
+ cursor_version: z12.string().optional(),
1921
+ workspace_roots: z12.array(z12.string()).max(64).optional(),
1922
+ cwd: z12.string().optional(),
1923
+ /** Never propagated. */
1924
+ user_email: z12.string().nullish(),
1925
+ /** Never propagated. */
1926
+ transcript_path: z12.string().nullish()
1927
+ };
1928
+ var event2 = (name, shape) => z12.object({ ...envelopeShape, hook_event_name: z12.literal(name), ...shape });
1929
+ var sessionStartPayloadSchema2 = event2("sessionStart", {
1930
+ is_background_agent: z12.boolean().optional(),
1931
+ composer_mode: z12.string().optional()
1932
+ });
1933
+ var sessionEndPayloadSchema2 = event2("sessionEnd", {
1934
+ reason: z12.string().optional(),
1935
+ duration_ms: z12.number().min(0).optional(),
1936
+ is_background_agent: z12.boolean().optional(),
1937
+ final_status: z12.string().optional(),
1938
+ error_message: z12.string().optional()
1939
+ });
1940
+ var beforeSubmitPromptPayloadSchema = event2("beforeSubmitPrompt", {
1941
+ prompt: z12.string().optional(),
1942
+ attachments: z12.array(attachmentSchema).max(256).optional(),
1943
+ composer_mode: z12.string().optional()
1944
+ });
1945
+ var afterAgentResponsePayloadSchema = event2("afterAgentResponse", {
1946
+ text: z12.string().optional(),
1947
+ ...usageFields
1948
+ });
1949
+ var afterAgentThoughtPayloadSchema = event2("afterAgentThought", {
1950
+ text: z12.string().optional(),
1951
+ duration_ms: z12.number().min(0).optional()
1952
+ });
1953
+ var preToolUsePayloadSchema2 = event2("preToolUse", {
1954
+ tool_name: z12.string().min(1),
1955
+ tool_input: z12.unknown().optional(),
1956
+ tool_use_id: z12.string().optional(),
1957
+ agent_message: z12.string().optional()
1958
+ });
1959
+ var postToolUsePayloadSchema2 = event2("postToolUse", {
1960
+ tool_name: z12.string().min(1),
1961
+ tool_input: z12.unknown().optional(),
1962
+ tool_output: z12.unknown().optional(),
1963
+ tool_use_id: z12.string().optional(),
1964
+ duration: z12.number().min(0).optional()
1965
+ });
1966
+ var postToolUseFailurePayloadSchema2 = event2("postToolUseFailure", {
1967
+ tool_name: z12.string().min(1),
1968
+ tool_input: z12.unknown().optional(),
1969
+ tool_use_id: z12.string().optional(),
1970
+ error_message: z12.string().optional(),
1971
+ failure_type: z12.string().optional(),
1972
+ duration: z12.number().min(0).optional(),
1973
+ is_interrupt: z12.boolean().optional()
1974
+ });
1975
+ var beforeShellExecutionPayloadSchema = event2("beforeShellExecution", {
1976
+ command: z12.string(),
1977
+ sandbox: z12.boolean().optional()
1978
+ });
1979
+ var afterShellExecutionPayloadSchema = event2("afterShellExecution", {
1980
+ command: z12.string(),
1981
+ output: z12.string().optional(),
1982
+ duration: z12.number().min(0).optional(),
1983
+ sandbox: z12.boolean().optional()
1984
+ });
1985
+ var beforeMcpExecutionPayloadSchema = event2("beforeMCPExecution", {
1986
+ tool_name: z12.string().min(1),
1987
+ tool_input: z12.unknown().optional(),
1988
+ url: z12.string().optional(),
1989
+ command: z12.string().optional()
1990
+ });
1991
+ var afterMcpExecutionPayloadSchema = event2("afterMCPExecution", {
1992
+ tool_name: z12.string().min(1),
1993
+ tool_input: z12.unknown().optional(),
1994
+ result_json: z12.string().optional(),
1995
+ duration: z12.number().min(0).optional()
1996
+ });
1997
+ var beforeReadFilePayloadSchema = event2("beforeReadFile", {
1998
+ file_path: z12.string(),
1999
+ content: z12.string().optional(),
2000
+ attachments: z12.array(attachmentSchema).max(256).optional()
2001
+ });
2002
+ var afterFileEditPayloadSchema = event2("afterFileEdit", {
2003
+ file_path: z12.string(),
2004
+ edits: z12.array(fileEditSchema).max(1024).optional()
2005
+ });
2006
+ var subagentStartPayloadSchema2 = event2("subagentStart", {
2007
+ subagent_id: z12.string().optional(),
2008
+ subagent_type: z12.string().optional(),
2009
+ task: z12.string().optional(),
2010
+ parent_conversation_id: z12.string().optional(),
2011
+ tool_call_id: z12.string().optional(),
2012
+ subagent_model: z12.string().optional(),
2013
+ is_parallel_worker: z12.boolean().optional(),
2014
+ git_branch: z12.string().optional()
2015
+ });
2016
+ var subagentStopPayloadSchema2 = event2("subagentStop", {
2017
+ subagent_type: z12.string().optional(),
2018
+ status: z12.string().optional(),
2019
+ task: z12.string().optional(),
2020
+ description: z12.string().optional(),
2021
+ summary: z12.string().optional(),
2022
+ duration_ms: z12.number().min(0).optional(),
2023
+ message_count: z12.number().int().min(0).optional(),
2024
+ tool_call_count: z12.number().int().min(0).optional(),
2025
+ loop_count: z12.number().int().min(0).optional(),
2026
+ modified_files: z12.array(z12.string()).max(1024).optional(),
2027
+ agent_transcript_path: z12.string().nullish()
2028
+ });
2029
+ var preCompactPayloadSchema2 = event2("preCompact", {
2030
+ trigger: z12.string().optional(),
2031
+ context_usage_percent: z12.number().optional(),
2032
+ context_tokens: z12.number().int().min(0).optional(),
2033
+ context_window_size: z12.number().int().min(0).optional(),
2034
+ message_count: z12.number().int().min(0).optional(),
2035
+ messages_to_compact: z12.number().int().min(0).optional(),
2036
+ is_first_compaction: z12.boolean().optional()
2037
+ });
2038
+ var stopPayloadSchema2 = event2("stop", {
2039
+ status: z12.string().optional(),
2040
+ loop_count: z12.number().int().min(0).optional(),
2041
+ ...usageFields
2042
+ });
2043
+ var cursorPayloadSchema = z12.discriminatedUnion("hook_event_name", [
2044
+ sessionStartPayloadSchema2,
2045
+ sessionEndPayloadSchema2,
2046
+ beforeSubmitPromptPayloadSchema,
2047
+ afterAgentResponsePayloadSchema,
2048
+ afterAgentThoughtPayloadSchema,
2049
+ preToolUsePayloadSchema2,
2050
+ postToolUsePayloadSchema2,
2051
+ postToolUseFailurePayloadSchema2,
2052
+ beforeShellExecutionPayloadSchema,
2053
+ afterShellExecutionPayloadSchema,
2054
+ beforeMcpExecutionPayloadSchema,
2055
+ afterMcpExecutionPayloadSchema,
2056
+ beforeReadFilePayloadSchema,
2057
+ afterFileEditPayloadSchema,
2058
+ subagentStartPayloadSchema2,
2059
+ subagentStopPayloadSchema2,
2060
+ preCompactPayloadSchema2,
2061
+ stopPayloadSchema2
2062
+ ]);
2063
+ var isPlainObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
2064
+ var recognizeCursorPayload = (payload) => {
2065
+ if (!isPlainObject(payload)) {
2066
+ return void 0;
2067
+ }
2068
+ const eventName = payload.hook_event_name;
2069
+ if (typeof eventName !== "string") {
2070
+ return void 0;
2071
+ }
2072
+ const unmodelled = CURSOR_UNMODELLED_HOOK_EVENT_NAMES[eventName];
2073
+ if (unmodelled !== void 0) {
2074
+ return { status: "unmodelled", eventName, reason: unmodelled };
2075
+ }
2076
+ if (!CURSOR_HOOK_EVENT_NAMES.includes(eventName)) {
2077
+ return void 0;
2078
+ }
2079
+ const parsed = cursorPayloadSchema.safeParse(payload);
2080
+ if (!parsed.success) {
2081
+ const [issue] = parsed.error.issues;
2082
+ return {
2083
+ status: "invalid",
2084
+ eventName,
2085
+ detail: issue === void 0 ? "payload does not satisfy the cursor hook schema" : `${issue.path.join(".") || "<root>"}: ${issue.message}`
2086
+ };
2087
+ }
2088
+ return { status: "modelled", payload: parsed.data };
2089
+ };
2090
+ var normalizeCursorPayload = (payload) => {
2091
+ const recognized = recognizeCursorPayload(payload);
2092
+ return recognized?.status === "modelled" ? recognized.payload : void 0;
2093
+ };
2094
+
2095
+ // src/providers/cursor/delivery.ts
2096
+ var deliveryComponents = (payload) => {
2097
+ switch (payload.hook_event_name) {
2098
+ case "sessionStart":
2099
+ case "sessionEnd":
2100
+ return {
2101
+ components: [payload.hook_event_name],
2102
+ evidence: [`cursor fires ${payload.hook_event_name} once per conversation`]
2103
+ };
2104
+ case "beforeSubmitPrompt":
2105
+ case "stop":
2106
+ return payload.generation_id === void 0 || payload.generation_id.length === 0 ? void 0 : {
2107
+ components: [payload.generation_id],
2108
+ evidence: [
2109
+ `payload.generation_id names one generation, which fires ${payload.hook_event_name} once`
2110
+ ]
2111
+ };
2112
+ case "preToolUse":
2113
+ case "postToolUse":
2114
+ case "postToolUseFailure":
2115
+ return payload.tool_use_id === void 0 || payload.tool_use_id.length === 0 ? void 0 : {
2116
+ components: [payload.tool_use_id],
2117
+ evidence: ["payload.tool_use_id names one tool call and repeats on redelivery"]
2118
+ };
2119
+ case "afterAgentResponse":
2120
+ case "afterAgentThought":
2121
+ case "beforeShellExecution":
2122
+ case "afterShellExecution":
2123
+ case "beforeMCPExecution":
2124
+ case "afterMCPExecution":
2125
+ case "beforeReadFile":
2126
+ case "afterFileEdit":
2127
+ case "subagentStart":
2128
+ case "subagentStop":
2129
+ case "preCompact":
2130
+ return void 0;
2131
+ }
2132
+ };
2133
+ var CURSOR_DELIVERY_GAPS = Object.freeze({
2134
+ preCompact: "no compaction id; payload `trigger` does not separate two genuine compactions",
2135
+ afterAgentResponse: "generation_id alone would collide with stop for the same generation; Cursor fires both with the same token snapshot",
2136
+ afterAgentThought: "payload.thoughtIndex absent; generationId alone names the generation, not one thought within it",
2137
+ subagentStart: "subagentStop carries no subagent id, so the pair cannot be correlated and neither edge is identified",
2138
+ subagentStop: "subagentStop carries no subagent id, so the pair cannot be correlated and neither edge is identified",
2139
+ beforeShellExecution: "payload.toolCallId absent; the only remaining field is the command line, which is content and may not become an id",
2140
+ afterShellExecution: "payload.toolCallId absent; the only remaining field is the command line, which is content and may not become an id",
2141
+ beforeMCPExecution: "payload.toolCallId absent; the only remaining fields are the tool name and its arguments, which are content",
2142
+ afterMCPExecution: "payload.toolCallId absent; the only remaining fields are the tool name and its arguments, which are content",
2143
+ afterFileEdit: "payload.toolCallId absent; the only remaining field is the file path, which is content and may not become an id",
2144
+ beforeReadFile: "payload.toolCallId absent; the only remaining field is the file path, which is content and may not become an id"
2145
+ });
2146
+ var cursorDeliveryIdentity = (input) => {
2147
+ const payload = normalizeCursorPayload(input.payload);
2148
+ if (payload === void 0) {
2149
+ return void 0;
2150
+ }
2151
+ const identified = deliveryComponents(payload);
2152
+ if (identified === void 0) {
2153
+ return void 0;
2154
+ }
2155
+ return {
2156
+ sessionId: payload.conversation_id,
2157
+ sourceEventName: payload.hook_event_name,
2158
+ components: identified.components,
2159
+ evidence: identified.evidence
2160
+ };
2161
+ };
2162
+
2163
+ // src/providers/cursor/usage.ts
2164
+ var normalizeCursorUsage = (raw) => {
2165
+ const inputTokens = raw.input_tokens;
2166
+ const outputTokens = raw.output_tokens;
2167
+ const cacheReadTokens = raw.cache_read_tokens;
2168
+ const cacheWriteTokens = raw.cache_write_tokens;
2169
+ const dropped = cacheWriteTokens === void 0 || cacheWriteTokens === 0 ? [] : [
2170
+ `cursor reported cache_write_tokens (${String(cacheWriteTokens)}), whose accounting relative to input_tokens is undocumented, so it was not folded into canonical usage`
2171
+ ];
2172
+ if (inputTokens === void 0 && outputTokens === void 0 && cacheReadTokens === void 0) {
2173
+ return { warnings: dropped };
2174
+ }
2175
+ const warnings = [...dropped];
2176
+ const contradictsInclusive = cacheReadTokens !== void 0 && inputTokens !== void 0 && cacheReadTokens > inputTokens;
2177
+ if (contradictsInclusive) {
2178
+ warnings.push(
2179
+ `cursor reported cache_read_tokens (${String(cacheReadTokens)}) above input_tokens (${String(inputTokens)}); the cache breakdown was dropped rather than reinterpreted`
2180
+ );
2181
+ }
2182
+ const result = normalizeUsage({
2183
+ temporality: "delta",
2184
+ ...inputTokens === void 0 ? {} : { inputTokens },
2185
+ ...outputTokens === void 0 ? {} : { outputTokens },
2186
+ ...cacheReadTokens === void 0 || contradictsInclusive ? {} : { cachedInputTokens: cacheReadTokens }
2187
+ });
2188
+ if (result.status === "invalid") {
2189
+ return { warnings: [...warnings, ...result.issues.map((issue) => issue.message)] };
2190
+ }
2191
+ return { usage: result.usage, warnings: [...warnings, ...result.notes] };
2192
+ };
2193
+
2194
+ // src/providers/cursor/adapter.ts
2195
+ var CURSOR_CAPABILITIES = Object.freeze({
2196
+ lifecycleEvents: Object.freeze([
2197
+ "session.start",
2198
+ "session.end",
2199
+ "prompt.submitted",
2200
+ "generation.start",
2201
+ "generation.end",
2202
+ "tool.start",
2203
+ "tool.end",
2204
+ "compaction.performed"
2205
+ ]),
2206
+ usageTemporality: "delta",
2207
+ // Cursor's `cache_read_tokens` is read as a subset of `input_tokens`; see
2208
+ // `./usage.ts` for the captured evidence and the guard when a payload
2209
+ // contradicts it.
2210
+ reportsCachedInput: true,
2211
+ // `cache_write_tokens` is reported by Cursor but its accounting is
2212
+ // undocumented, so it is surfaced as an extension rather than folded into a
2213
+ // canonical total. See `./usage.ts`.
2214
+ reportsCacheCreation: false,
2215
+ cacheCreationAccounting: "not-reported",
2216
+ reportsReasoningOutput: false,
2217
+ reportsProviderTotal: false,
2218
+ reportsCost: false,
2219
+ // `subagentStop` carries no subagent id, so no pairable subagent lifecycle can
2220
+ // be produced. See the `ignored` branch below.
2221
+ emitsSubagentEvents: false,
2222
+ emitsCompactionEvents: true,
2223
+ requiresHookResponse: true,
2224
+ // Tool and generation callbacks carry a replay-stable id; the dedicated
2225
+ // shell/MCP/file callbacks and `preCompact` do not. See `./delivery.ts`.
2226
+ deliveryIdentifier: "partial"
2227
+ });
2228
+ var UNKNOWN_MODEL2 = Object.freeze({ modelId: "unknown" });
2229
+ var toModelDescriptor = (payload) => {
2230
+ const modelId = payload.model;
2231
+ if (modelId === void 0 || modelId.length === 0) {
2232
+ return UNKNOWN_MODEL2;
2233
+ }
2234
+ const family = payload.model_id;
2235
+ return {
2236
+ modelId,
2237
+ ...family === void 0 || family.length === 0 || family === modelId ? {} : { family }
2238
+ };
2239
+ };
2240
+ var SESSION_END_REASONS = Object.freeze({
2241
+ completed: "completed",
2242
+ aborted: "aborted",
2243
+ error: "error",
2244
+ // Both documented "the window/user closed it" reasons are an abort from the
2245
+ // agent's point of view: work stopped without finishing.
2246
+ window_close: "aborted",
2247
+ user_close: "aborted"
2248
+ });
2249
+ var STOP_STATUS_TO_OUTCOME = Object.freeze({
2250
+ completed: "ok",
2251
+ aborted: "cancelled",
2252
+ error: "error"
2253
+ });
2254
+ var COMPACT_TRIGGERS = Object.freeze({
2255
+ auto: "automatic",
2256
+ manual: "manual"
2257
+ });
2258
+ var deriveWorkspace = (context, payload) => {
2259
+ const roots = (payload.workspace_roots ?? []).filter((root) => root.length > 0);
2260
+ if (roots.length === 1) {
2261
+ return deriveWorkspaceIdentity(context.privacy, {
2262
+ kind: "working-directory",
2263
+ absolutePath: roots[0] ?? ""
2264
+ });
2265
+ }
2266
+ if (roots.length > 1) {
2267
+ return deriveWorkspaceIdentity(context.privacy, {
2268
+ kind: "explicit",
2269
+ value: [...roots].sort().join("\n")
2270
+ });
2271
+ }
2272
+ if (payload.cwd !== void 0 && payload.cwd.length > 0) {
2273
+ return deriveWorkspaceIdentity(context.privacy, {
2274
+ kind: "working-directory",
2275
+ absolutePath: payload.cwd
2276
+ });
2277
+ }
2278
+ return void 0;
2279
+ };
2280
+ var invocationDiscriminator = (payload) => {
2281
+ switch (payload.hook_event_name) {
2282
+ case "sessionStart":
2283
+ case "sessionEnd":
2284
+ return void 0;
2285
+ case "preToolUse":
2286
+ case "postToolUse":
2287
+ case "postToolUseFailure":
2288
+ return payload.tool_use_id ?? payload.tool_name;
2289
+ case "beforeShellExecution":
2290
+ case "afterShellExecution":
2291
+ return payload.generation_id;
2292
+ case "beforeMCPExecution":
2293
+ case "afterMCPExecution":
2294
+ return payload.tool_name;
2295
+ case "beforeReadFile":
2296
+ case "afterFileEdit":
2297
+ return payload.generation_id;
2298
+ case "subagentStart":
2299
+ return payload.subagent_id;
2300
+ case "subagentStop":
2301
+ return payload.subagent_type;
2302
+ case "preCompact":
2303
+ return payload.trigger;
2304
+ default:
2305
+ return payload.generation_id;
2306
+ }
2307
+ };
2308
+ var derivedToolCallId = (context, sessionId, parts) => context.ids.newOpaqueId([sessionId, ...parts]);
2309
+ var asModelled = (payload) => {
2310
+ const recognized = recognizeCursorPayload(payload);
2311
+ return recognized?.status === "modelled" ? recognized.payload : void 0;
2312
+ };
2313
+ var MAX_DETECTION_REASON_LENGTH = 160;
2314
+ var bounded = (reason) => reason.length <= MAX_DETECTION_REASON_LENGTH ? reason : `${reason.slice(0, MAX_DETECTION_REASON_LENGTH - 1)}\u2026`;
2315
+ var CURSOR_ADAPTER_VERSION = "2.0.0";
2316
+ var createCursorAdapter = (options = {}) => {
2317
+ const id = asProviderId(CURSOR_PROVIDER_ID);
2318
+ const version = options.version ?? CURSOR_ADAPTER_VERSION;
2319
+ const capabilities = CURSOR_CAPABILITIES;
2320
+ const detect2 = (input) => {
2321
+ const recognized = recognizeCursorPayload(input.payload);
2322
+ if (recognized === void 0) {
2323
+ return unknownDetection(["payload does not match the cursor hook contract"]);
2324
+ }
2325
+ if (recognized.status === "unmodelled") {
2326
+ return unknownDetection([
2327
+ bounded(`cursor documents "${recognized.eventName}" but this adapter does not model it`)
2328
+ ]);
2329
+ }
2330
+ if (recognized.status === "invalid") {
2331
+ return unknownDetection([
2332
+ bounded(
2333
+ `cursor "${recognized.eventName}" payload does not satisfy its contract: ${recognized.detail}`
2334
+ )
2335
+ ]);
2336
+ }
2337
+ const { payload } = recognized;
2338
+ return providerDetectionSchema.parse({
2339
+ providerId: id,
2340
+ confidence: "exact",
2341
+ reasons: [`payload.hook_event_name "${payload.hook_event_name}" recognized`],
2342
+ ...payload.cursor_version === void 0 || payload.cursor_version.length === 0 ? {} : { providerVersion: payload.cursor_version },
2343
+ sourceEventName: payload.hook_event_name
2344
+ });
2345
+ };
2346
+ const identify2 = (input, context) => {
2347
+ const payload = asModelled(input.payload);
2348
+ if (payload === void 0) {
2349
+ return [];
2350
+ }
2351
+ const workspace = deriveWorkspace(context, payload);
2352
+ const discriminator = invocationDiscriminator(payload);
2353
+ const occurredAt = context.clock.now();
2354
+ const invocationId = context.ids.newInvocationId({
2355
+ providerId: id,
2356
+ sessionId: payload.conversation_id,
2357
+ sourceEventName: payload.hook_event_name,
2358
+ occurredAt,
2359
+ ...discriminator === void 0 ? {} : { discriminator }
2360
+ });
2361
+ const claim = identityClaimSchema.parse({
2362
+ source: `adapter:${id}`,
2363
+ confidence: input.detection.confidence,
2364
+ fields: {
2365
+ // Cursor's own conversation id, used exactly as reported: never
2366
+ // normalized, parent/child matched, or substituted for a derived value.
2367
+ // `session_id` repeats it in every capture and is not preferred over it.
2368
+ sessionId: payload.conversation_id,
2369
+ invocationId,
2370
+ startedAt: occurredAt,
2371
+ ...workspace === void 0 ? {} : { workspace }
2372
+ }
2373
+ });
2374
+ return [claim];
2375
+ };
2376
+ const parse2 = (input, context) => {
2377
+ const recognized = recognizeCursorPayload(input.payload);
2378
+ if (recognized === void 0) {
2379
+ return {
2380
+ status: "failed",
2381
+ error: createErrorInfo({
2382
+ code: "invalid-input",
2383
+ phase: "parsing",
2384
+ detail: "payload does not match the cursor hook contract"
2385
+ })
2386
+ };
2387
+ }
2388
+ if (recognized.status === "unmodelled") {
2389
+ return {
2390
+ status: "ignored",
2391
+ reason: `cursor "${recognized.eventName}" is not modelled: ${recognized.reason}`
2392
+ };
2393
+ }
2394
+ if (recognized.status === "invalid") {
2395
+ return {
2396
+ status: "failed",
2397
+ error: createErrorInfo({
2398
+ code: "invalid-input",
2399
+ phase: "parsing",
2400
+ detail: `cursor "${recognized.eventName}" payload is malformed (${recognized.detail})`
2401
+ })
2402
+ };
2403
+ }
2404
+ const { payload } = recognized;
2405
+ if (payload.hook_event_name === "afterAgentResponse") {
2406
+ return {
2407
+ status: "ignored",
2408
+ reason: "the generation's terminal outcome is reported from stop, which carries a status field and the identical token snapshot (captured: 43859/1076/28384/0 on both callbacks of one generation); emitting generation.end from both would double-count usage, and this adapter holds no cross-invocation state to deduplicate them"
2409
+ };
2410
+ }
2411
+ if (payload.hook_event_name === "afterAgentThought") {
2412
+ return {
2413
+ status: "ignored",
2414
+ reason: "afterAgentThought is a reasoning notification, not a generation lifecycle event; no canonical event type represents it and thought text is never exported"
2415
+ };
2416
+ }
2417
+ if (payload.hook_event_name === "beforeReadFile") {
2418
+ return {
2419
+ status: "ignored",
2420
+ reason: "beforeReadFile has no completion callback in the cursor hook protocol, so emitting tool.start here would leave a tool lifecycle that never closes"
2421
+ };
2422
+ }
2423
+ if (payload.hook_event_name === "subagentStart" || payload.hook_event_name === "subagentStop") {
2424
+ return {
2425
+ status: "ignored",
2426
+ reason: "cursor's subagentStop payload carries no subagent identifier \u2014 the reference gives subagent_id to subagentStart only \u2014 so the two callbacks cannot be paired; emitting subagent.start alone would leave a delegation that never closes, and minting an id for the end would produce an unpairable one"
2427
+ };
2428
+ }
2429
+ const factory = createEventFactory({
2430
+ identity: input.identity,
2431
+ sequenceBase: input.sequenceBase,
2432
+ context
2433
+ });
2434
+ const warnings = [];
2435
+ const sessionId = input.identity.sessionId;
2436
+ const model = toModelDescriptor(payload);
2437
+ switch (payload.hook_event_name) {
2438
+ case "sessionStart":
2439
+ factory.build({
2440
+ type: "session.start",
2441
+ // A background agent runs unattended; an interactive session is the
2442
+ // only other state Cursor reports here.
2443
+ sessionKind: payload.is_background_agent === void 0 ? "unknown" : payload.is_background_agent ? "non-interactive" : "interactive",
2444
+ agentName: "cursor",
2445
+ ...payload.cursor_version === void 0 || payload.cursor_version.length === 0 ? {} : { agentVersion: payload.cursor_version },
2446
+ ...model === UNKNOWN_MODEL2 ? {} : { model },
2447
+ ...payload.composer_mode === void 0 ? {} : { extensions: { "cursor.composer_mode": payload.composer_mode } }
2448
+ });
2449
+ break;
2450
+ case "sessionEnd":
2451
+ factory.build({
2452
+ type: "session.end",
2453
+ reason: payload.reason === void 0 ? "unknown" : SESSION_END_REASONS[payload.reason] ?? "unknown",
2454
+ ...payload.duration_ms === void 0 ? {} : { durationMillis: payload.duration_ms },
2455
+ ...payload.final_status === void 0 ? {} : { extensions: { "cursor.final_status": payload.final_status } }
2456
+ });
2457
+ break;
2458
+ case "beforeSubmitPrompt": {
2459
+ factory.build({
2460
+ type: "prompt.submitted",
2461
+ // Cursor reports no prompt provenance. `user` would be a guess: this
2462
+ // hook also fires for an automation-driven or resumed turn.
2463
+ promptSource: "unknown",
2464
+ ...payload.prompt === void 0 ? {} : {
2465
+ content: context.privacy.describeContent({
2466
+ kind: "prompt",
2467
+ role: "user",
2468
+ text: payload.prompt
2469
+ })
2470
+ },
2471
+ ...payload.attachments === void 0 ? {} : { extensions: { "cursor.attachment_count": payload.attachments.length } }
2472
+ });
2473
+ if (payload.generation_id !== void 0 && payload.generation_id.length > 0) {
2474
+ factory.build({
2475
+ type: "generation.start",
2476
+ generationId: payload.generation_id,
2477
+ model
2478
+ });
2479
+ } else {
2480
+ warnings.push(
2481
+ "beforeSubmitPrompt carried no generation_id, so no generation.start was emitted"
2482
+ );
2483
+ }
2484
+ break;
2485
+ }
2486
+ case "preToolUse":
2487
+ factory.build({
2488
+ type: "tool.start",
2489
+ toolCallId: payload.tool_use_id ?? derivedToolCallId(context, sessionId, [
2490
+ "tool",
2491
+ payload.generation_id ?? "",
2492
+ payload.tool_name
2493
+ ]),
2494
+ toolName: payload.tool_name,
2495
+ // Cursor names its tools but does not classify them, and the names are
2496
+ // not a closed set. `unknown` says so; `other` would claim a lookup
2497
+ // happened and found nothing.
2498
+ toolKind: "unknown",
2499
+ ...payload.generation_id === void 0 || payload.generation_id.length === 0 ? {} : { generationId: payload.generation_id },
2500
+ ...payload.tool_input === void 0 ? {} : {
2501
+ input: context.privacy.describeStructured({
2502
+ kind: "tool-input",
2503
+ value: payload.tool_input,
2504
+ label: payload.tool_name
2505
+ })
2506
+ }
2507
+ });
2508
+ break;
2509
+ case "postToolUse":
2510
+ factory.build({
2511
+ type: "tool.end",
2512
+ toolCallId: payload.tool_use_id ?? derivedToolCallId(context, sessionId, [
2513
+ "tool",
2514
+ payload.generation_id ?? "",
2515
+ payload.tool_name
2516
+ ]),
2517
+ toolName: payload.tool_name,
2518
+ // Cursor routes failures to the separate postToolUseFailure callback,
2519
+ // so reaching this one *is* the success signal.
2520
+ outcome: "ok",
2521
+ ...payload.duration === void 0 ? {} : { durationMillis: payload.duration },
2522
+ ...payload.tool_output === void 0 ? {} : {
2523
+ output: context.privacy.describeStructured({
2524
+ kind: "tool-output",
2525
+ value: payload.tool_output,
2526
+ label: payload.tool_name
2527
+ })
2528
+ }
2529
+ });
2530
+ break;
2531
+ case "postToolUseFailure":
2532
+ factory.build({
2533
+ type: "tool.end",
2534
+ toolCallId: payload.tool_use_id ?? derivedToolCallId(context, sessionId, [
2535
+ "tool",
2536
+ payload.generation_id ?? "",
2537
+ payload.tool_name
2538
+ ]),
2539
+ toolName: payload.tool_name,
2540
+ outcome: payload.failure_type === "timeout" ? "timeout" : payload.failure_type === "permission_denied" ? "denied" : payload.is_interrupt === true ? "cancelled" : "error",
2541
+ ...payload.failure_type === "permission_denied" ? { permissionDecision: "denied" } : {},
2542
+ ...payload.duration === void 0 ? {} : { durationMillis: payload.duration },
2543
+ ...payload.error_message === void 0 ? {} : {
2544
+ output: context.privacy.describeContent({
2545
+ kind: "error-message",
2546
+ text: payload.error_message
2547
+ })
2548
+ }
2549
+ });
2550
+ break;
2551
+ case "beforeShellExecution":
2552
+ factory.build({
2553
+ type: "tool.start",
2554
+ toolCallId: derivedToolCallId(context, sessionId, [
2555
+ "shell",
2556
+ payload.generation_id ?? "",
2557
+ payload.command
2558
+ ]),
2559
+ toolName: "shell",
2560
+ toolKind: "execute",
2561
+ ...payload.generation_id === void 0 || payload.generation_id.length === 0 ? {} : { generationId: payload.generation_id },
2562
+ input: context.privacy.describeContent({
2563
+ kind: "tool-input",
2564
+ text: payload.command,
2565
+ label: "shell"
2566
+ }),
2567
+ ...payload.sandbox === void 0 ? {} : { extensions: { "cursor.sandbox": payload.sandbox } }
2568
+ });
2569
+ break;
2570
+ case "afterShellExecution":
2571
+ factory.build({
2572
+ type: "tool.end",
2573
+ toolCallId: derivedToolCallId(context, sessionId, [
2574
+ "shell",
2575
+ payload.generation_id ?? "",
2576
+ payload.command
2577
+ ]),
2578
+ toolName: "shell",
2579
+ // No exit code and no status field on this callback, in the reference
2580
+ // or in the captures. Reporting `ok` would assert a success Cursor
2581
+ // never claimed.
2582
+ outcome: "unknown",
2583
+ ...payload.duration === void 0 ? {} : { durationMillis: payload.duration },
2584
+ ...payload.output === void 0 ? {} : {
2585
+ output: context.privacy.describeContent({
2586
+ kind: "tool-output",
2587
+ text: payload.output,
2588
+ label: "shell"
2589
+ })
2590
+ },
2591
+ ...payload.sandbox === void 0 ? {} : { extensions: { "cursor.sandbox": payload.sandbox } }
2592
+ });
2593
+ break;
2594
+ case "beforeMCPExecution":
2595
+ factory.build({
2596
+ type: "tool.start",
2597
+ toolCallId: derivedToolCallId(context, sessionId, [
2598
+ "mcp",
2599
+ payload.generation_id ?? "",
2600
+ payload.tool_name
2601
+ ]),
2602
+ toolName: payload.tool_name,
2603
+ toolKind: "network",
2604
+ ...payload.generation_id === void 0 || payload.generation_id.length === 0 ? {} : { generationId: payload.generation_id },
2605
+ ...payload.tool_input === void 0 ? {} : {
2606
+ input: context.privacy.describeStructured({
2607
+ kind: "tool-input",
2608
+ value: payload.tool_input,
2609
+ label: payload.tool_name
2610
+ })
2611
+ }
2612
+ });
2613
+ break;
2614
+ case "afterMCPExecution":
2615
+ factory.build({
2616
+ type: "tool.end",
2617
+ toolCallId: derivedToolCallId(context, sessionId, [
2618
+ "mcp",
2619
+ payload.generation_id ?? "",
2620
+ payload.tool_name
2621
+ ]),
2622
+ toolName: payload.tool_name,
2623
+ // As with the shell pair: `result_json` is opaque and there is no
2624
+ // status field to read an outcome from.
2625
+ outcome: "unknown",
2626
+ ...payload.duration === void 0 ? {} : { durationMillis: payload.duration },
2627
+ ...payload.result_json === void 0 ? {} : {
2628
+ output: context.privacy.describeContent({
2629
+ kind: "tool-output",
2630
+ text: payload.result_json,
2631
+ label: payload.tool_name
2632
+ })
2633
+ }
2634
+ });
2635
+ break;
2636
+ case "afterFileEdit": {
2637
+ const toolCallId = derivedToolCallId(context, sessionId, [
2638
+ "file-edit",
2639
+ payload.generation_id ?? "",
2640
+ payload.file_path
2641
+ ]);
2642
+ factory.build({
2643
+ type: "tool.start",
2644
+ toolCallId,
2645
+ toolName: "edit_file",
2646
+ toolKind: "write",
2647
+ ...payload.generation_id === void 0 || payload.generation_id.length === 0 ? {} : { generationId: payload.generation_id },
2648
+ input: context.privacy.describeContent({
2649
+ kind: "tool-input",
2650
+ text: payload.file_path,
2651
+ label: "edit_file"
2652
+ })
2653
+ });
2654
+ factory.build({
2655
+ type: "tool.end",
2656
+ toolCallId,
2657
+ toolName: "edit_file",
2658
+ outcome: "ok",
2659
+ // `edits[].old_string`/`new_string` are file content and are never
2660
+ // exported, in described form or otherwise. Only how many edits landed.
2661
+ ...payload.edits === void 0 ? {} : { extensions: { "cursor.edit_count": payload.edits.length } }
2662
+ });
2663
+ break;
2664
+ }
2665
+ case "preCompact":
2666
+ factory.build({
2667
+ type: "compaction.performed",
2668
+ trigger: payload.trigger === void 0 ? "unknown" : COMPACT_TRIGGERS[payload.trigger] ?? "unknown",
2669
+ // Cursor exposes no post-compaction callback, so `contextTokensAfter`
2670
+ // is structurally unavailable and is never estimated.
2671
+ ...payload.context_tokens === void 0 ? {} : { contextTokensBefore: payload.context_tokens },
2672
+ ...payload.messages_to_compact === void 0 ? {} : { droppedMessageCount: payload.messages_to_compact },
2673
+ extensions: {
2674
+ ...payload.context_window_size === void 0 ? {} : { "cursor.context_window_size": payload.context_window_size },
2675
+ ...payload.message_count === void 0 ? {} : { "cursor.message_count": payload.message_count },
2676
+ ...payload.is_first_compaction === void 0 ? {} : { "cursor.is_first_compaction": payload.is_first_compaction }
2677
+ }
2678
+ });
2679
+ break;
2680
+ case "stop": {
2681
+ const usage = normalizeCursorUsage(payload);
2682
+ warnings.push(...usage.warnings);
2683
+ const generationId = payload.generation_id;
2684
+ if (generationId === void 0 || generationId.length === 0) {
2685
+ return {
2686
+ status: "ignored",
2687
+ reason: "stop carried no generation_id, so the generation it ends cannot be named; generation.end requires one and this adapter will not mint it"
2688
+ };
2689
+ }
2690
+ factory.build({
2691
+ type: "generation.end",
2692
+ generationId,
2693
+ model,
2694
+ outcome: payload.status === void 0 ? "unknown" : STOP_STATUS_TO_OUTCOME[payload.status] ?? "unknown",
2695
+ ...payload.status === void 0 ? {} : { stopReason: payload.status },
2696
+ ...usage.usage === void 0 ? {} : { usage: usage.usage },
2697
+ ...payload.loop_count === void 0 ? {} : { extensions: { "cursor.loop_count": payload.loop_count } }
2698
+ });
2699
+ break;
2700
+ }
2701
+ }
2702
+ return {
2703
+ status: "parsed",
2704
+ events: factory.events(),
2705
+ ...warnings.length === 0 ? {} : { warnings }
2706
+ };
2707
+ };
2708
+ const hookResponse2 = (input) => {
2709
+ const sourceEventName = input.detection?.sourceEventName;
2710
+ const decisionKey = sourceEventName === void 0 ? void 0 : CURSOR_DECISION_EVENTS[sourceEventName];
2711
+ if (decisionKey === void 0) {
2712
+ return SILENT_HOOK_RESPONSE;
2713
+ }
2714
+ return {
2715
+ exitCode: 0,
2716
+ contract: "provider-protocol",
2717
+ stdout: JSON.stringify(
2718
+ decisionKey === "continue" ? { continue: true } : { permission: "allow" }
2719
+ )
2720
+ };
2721
+ };
2722
+ return {
2723
+ id,
2724
+ version,
2725
+ capabilities,
2726
+ detect: detect2,
2727
+ identify: identify2,
2728
+ deliveryIdentity: cursorDeliveryIdentity,
2729
+ deliveryGaps: CURSOR_DELIVERY_GAPS,
2730
+ parse: parse2,
2731
+ hookResponse: hookResponse2
2732
+ };
2733
+ };
2734
+
2735
+ // src/providers/codex/payload.ts
2736
+ import { z as z13 } from "zod";
2737
+ var permissionModeSchema = z13.enum([
2738
+ "default",
2739
+ "acceptEdits",
2740
+ "plan",
2741
+ "dontAsk",
2742
+ "bypassPermissions"
2743
+ ]);
2744
+ var codexUsageSchema = z13.object({
2745
+ input_tokens: z13.number().int().min(0).optional(),
2746
+ cached_input_tokens: z13.number().int().min(0).optional(),
2747
+ output_tokens: z13.number().int().min(0).optional(),
2748
+ reasoning_output_tokens: z13.number().int().min(0).optional(),
2749
+ total_tokens: z13.number().int().min(0).optional()
2750
+ });
2751
+ var baseFields = {
2752
+ session_id: z13.string().min(1).max(256),
2753
+ cwd: z13.string().min(1).max(4096).optional(),
2754
+ model: z13.string().min(1).max(256).optional(),
2755
+ permission_mode: permissionModeSchema.optional(),
2756
+ transcript_path: z13.string().min(1).max(4096).optional(),
2757
+ codex_version: z13.string().min(1).max(64).optional(),
2758
+ /** Not part of the documented protocol; lets tests and replay stay deterministic. */
2759
+ occurred_at: z13.number().int().min(0).optional()
2760
+ };
2761
+ var codexSessionStartPayloadSchema = z13.object({
2762
+ ...baseFields,
2763
+ hook_event_name: z13.literal("SessionStart"),
2764
+ source: z13.enum(["startup", "resume", "clear", "compact"]).optional()
2765
+ });
2766
+ var codexUserPromptSubmitPayloadSchema = z13.object({
2767
+ ...baseFields,
2768
+ hook_event_name: z13.literal("UserPromptSubmit"),
2769
+ turn_id: z13.string().min(1).max(256).optional(),
2770
+ prompt: z13.string().max(1e6).optional()
2771
+ });
2772
+ var codexPreToolUsePayloadSchema = z13.object({
2773
+ ...baseFields,
2774
+ hook_event_name: z13.literal("PreToolUse"),
2775
+ turn_id: z13.string().min(1).max(256).optional(),
2776
+ tool_name: z13.string().min(1).max(256),
2777
+ tool_call_id: z13.string().min(1).max(256).optional(),
2778
+ tool_input: z13.unknown().optional()
2779
+ });
2780
+ var codexPermissionRequestPayloadSchema = z13.object({
2781
+ ...baseFields,
2782
+ hook_event_name: z13.literal("PermissionRequest"),
2783
+ turn_id: z13.string().min(1).max(256).optional(),
2784
+ tool_name: z13.string().min(1).max(256).optional(),
2785
+ tool_call_id: z13.string().min(1).max(256).optional(),
2786
+ tool_input: z13.unknown().optional()
2787
+ });
2788
+ var codexPostToolUsePayloadSchema = z13.object({
2789
+ ...baseFields,
2790
+ hook_event_name: z13.literal("PostToolUse"),
2791
+ turn_id: z13.string().min(1).max(256).optional(),
2792
+ tool_name: z13.string().min(1).max(256),
2793
+ tool_call_id: z13.string().min(1).max(256).optional(),
2794
+ tool_input: z13.unknown().optional(),
2795
+ tool_response: z13.unknown().optional(),
2796
+ permission_decision: z13.enum(["allowed", "denied", "deferred"]).optional(),
2797
+ duration_ms: z13.number().min(0).optional()
2798
+ });
2799
+ var codexPreCompactPayloadSchema = z13.object({
2800
+ ...baseFields,
2801
+ hook_event_name: z13.literal("PreCompact"),
2802
+ trigger: z13.enum(["auto", "manual"]).optional(),
2803
+ context_tokens_before: z13.number().int().min(0).optional()
2804
+ });
2805
+ var codexPostCompactPayloadSchema = z13.object({
2806
+ ...baseFields,
2807
+ hook_event_name: z13.literal("PostCompact"),
2808
+ trigger: z13.enum(["auto", "manual"]).optional(),
2809
+ context_tokens_after: z13.number().int().min(0).optional(),
2810
+ dropped_message_count: z13.number().int().min(0).optional(),
2811
+ usage: codexUsageSchema.optional()
2812
+ });
2813
+ var codexSubagentStartPayloadSchema = z13.object({
2814
+ ...baseFields,
2815
+ hook_event_name: z13.literal("SubagentStart"),
2816
+ turn_id: z13.string().min(1).max(256).optional(),
2817
+ subagent_id: z13.string().min(1).max(256),
2818
+ subagent_type: z13.string().min(1).max(256).optional()
2819
+ });
2820
+ var codexSubagentStopPayloadSchema = z13.object({
2821
+ ...baseFields,
2822
+ hook_event_name: z13.literal("SubagentStop"),
2823
+ turn_id: z13.string().min(1).max(256).optional(),
2824
+ subagent_id: z13.string().min(1).max(256),
2825
+ status: z13.enum(["completed", "failed", "cancelled"]).optional(),
2826
+ usage: codexUsageSchema.optional()
2827
+ });
2828
+ var codexStopPayloadSchema = z13.object({
2829
+ ...baseFields,
2830
+ hook_event_name: z13.literal("Stop"),
2831
+ turn_id: z13.string().min(1).max(256).optional(),
2832
+ stop_reason: z13.string().min(1).max(256).optional(),
2833
+ usage: codexUsageSchema.optional(),
2834
+ duration_ms: z13.number().min(0).optional()
2835
+ });
2836
+ var CODEX_HOOK_EVENT_NAMES = [
2837
+ "SessionStart",
2838
+ "UserPromptSubmit",
2839
+ "PreToolUse",
2840
+ "PermissionRequest",
2841
+ "PostToolUse",
2842
+ "PreCompact",
2843
+ "PostCompact",
2844
+ "SubagentStart",
2845
+ "SubagentStop",
2846
+ "Stop"
2847
+ ];
2848
+ var codexHookPayloadSchema = z13.discriminatedUnion("hook_event_name", [
2849
+ codexSessionStartPayloadSchema,
2850
+ codexUserPromptSubmitPayloadSchema,
2851
+ codexPreToolUsePayloadSchema,
2852
+ codexPermissionRequestPayloadSchema,
2853
+ codexPostToolUsePayloadSchema,
2854
+ codexPreCompactPayloadSchema,
2855
+ codexPostCompactPayloadSchema,
2856
+ codexSubagentStartPayloadSchema,
2857
+ codexSubagentStopPayloadSchema,
2858
+ codexStopPayloadSchema
2859
+ ]);
2860
+ var codexHookEnvelopeSchema = z13.object({
2861
+ session_id: z13.string().min(1),
2862
+ hook_event_name: z13.enum(CODEX_HOOK_EVENT_NAMES)
2863
+ });
2864
+
2865
+ // src/providers/codex/delivery.ts
2866
+ var deliveryComponents2 = (payload) => {
2867
+ switch (payload.hook_event_name) {
2868
+ case "PreToolUse":
2869
+ case "PermissionRequest":
2870
+ case "PostToolUse":
2871
+ return payload.tool_call_id === void 0 ? void 0 : {
2872
+ components: [payload.tool_call_id],
2873
+ evidence: ["payload.tool_call_id names one tool call and repeats on redelivery"]
2874
+ };
2875
+ case "SubagentStart":
2876
+ case "SubagentStop":
2877
+ return {
2878
+ components: [payload.subagent_id],
2879
+ evidence: ["payload.subagent_id names one subagent instance"]
2880
+ };
2881
+ case "UserPromptSubmit":
2882
+ case "Stop":
2883
+ return payload.turn_id === void 0 ? void 0 : {
2884
+ components: [payload.turn_id],
2885
+ evidence: [`payload.turn_id names one turn, which fires ${payload.hook_event_name} once`]
2886
+ };
2887
+ case "SessionStart":
2888
+ case "PreCompact":
2889
+ case "PostCompact":
2890
+ return void 0;
2891
+ }
2892
+ };
2893
+ var CODEX_DELIVERY_GAPS = Object.freeze({
2894
+ SessionStart: "no per-firing id; payload `source` (startup, resume, clear, compact) means SessionStart fires repeatedly under one session_id",
2895
+ PreCompact: "no compaction id; payload `trigger` does not separate two genuine compactions",
2896
+ PostCompact: "no compaction id; payload `trigger` does not separate two genuine compactions",
2897
+ PreToolUse: "payload.tool_call_id absent; tool_name is not a substitute because one turn can call the same tool twice",
2898
+ PostToolUse: "payload.tool_call_id absent; tool_name is not a substitute because one turn can call the same tool twice",
2899
+ PermissionRequest: "payload.tool_call_id absent; tool_name is not a substitute because one turn can prompt for the same tool twice",
2900
+ UserPromptSubmit: "payload.turn_id absent; nothing else in this callback names one turn",
2901
+ Stop: "payload.turn_id absent; nothing else in this callback names one turn",
2902
+ SubagentStart: "payload.subagent_id absent, so no subagent instance is named",
2903
+ SubagentStop: "payload.subagent_id absent, so no subagent instance is named"
2904
+ });
2905
+ var codexDeliveryIdentity = (input) => {
2906
+ const parsed = codexHookPayloadSchema.safeParse(input.payload);
2907
+ if (!parsed.success) {
2908
+ return void 0;
2909
+ }
2910
+ const payload = parsed.data;
2911
+ const identified = deliveryComponents2(payload);
2912
+ if (identified === void 0) {
2913
+ return void 0;
2914
+ }
2915
+ return {
2916
+ sessionId: payload.session_id,
2917
+ sourceEventName: payload.hook_event_name,
2918
+ components: identified.components,
2919
+ evidence: identified.evidence
2920
+ };
2921
+ };
2922
+
2923
+ // src/providers/codex/tool-kind.ts
2924
+ var PATTERNS = [
2925
+ [/^(apply[_-]?patch|patch)$/i, "write"],
2926
+ [/(write|edit|create[_-]?file|delete)/i, "write"],
2927
+ [/^(shell|bash|exec|local[_-]?shell|run[_-]?command|terminal)$/i, "execute"],
2928
+ [/(read|cat|view|get[_-]?file|open[_-]?file)/i, "read"],
2929
+ [/(web[_-]?search|browser|fetch|http)/i, "network"],
2930
+ [/(search|grep|find|glob)/i, "search"],
2931
+ [/(subagent|delegate|task)/i, "delegate"]
2932
+ ];
2933
+ var classifyCodexToolKind = (toolName) => {
2934
+ for (const [pattern, kind] of PATTERNS) {
2935
+ if (pattern.test(toolName)) {
2936
+ return kind;
2937
+ }
2938
+ }
2939
+ return "other";
2940
+ };
2941
+
2942
+ // src/providers/codex/usage.ts
2943
+ var codexUsageToReport = (usage, temporality) => ({
2944
+ temporality,
2945
+ ...usage.input_tokens === void 0 ? {} : { inputTokens: usage.input_tokens },
2946
+ ...usage.cached_input_tokens === void 0 ? {} : { cachedInputTokens: usage.cached_input_tokens },
2947
+ ...usage.output_tokens === void 0 ? {} : { outputTokens: usage.output_tokens },
2948
+ ...usage.reasoning_output_tokens === void 0 ? {} : { reasoningOutputTokens: usage.reasoning_output_tokens },
2949
+ ...usage.total_tokens === void 0 ? {} : { providerTotalTokens: usage.total_tokens }
2950
+ });
2951
+
2952
+ // src/providers/codex/version.ts
2953
+ var CODEX_PROVIDER_ID = providerIdSchema.parse("codex");
2954
+ var CODEX_ADAPTER_VERSION = "0.1.0";
2955
+
2956
+ // src/providers/codex/adapter.ts
2957
+ var CODEX_CAPABILITIES = Object.freeze({
2958
+ lifecycleEvents: Object.freeze([
2959
+ "session.start",
2960
+ "prompt.submitted",
2961
+ "generation.end",
2962
+ "tool.start",
2963
+ "tool.end",
2964
+ "subagent.start",
2965
+ "subagent.end",
2966
+ "compaction.performed"
2967
+ ]),
2968
+ usageTemporality: "cumulative",
2969
+ // Every usage-bearing Codex callback stamps the *session-wide* running total
2970
+ // (`total_token_usage`), not a per-turn figure, so all of them are points on
2971
+ // one series. Diffing per `turn_id` would re-count the whole session each
2972
+ // turn; see docs/usage-semantics.md.
2973
+ cumulativeUsageSeries: "session-lifetime",
2974
+ reportsCachedInput: true,
2975
+ reportsCacheCreation: false,
2976
+ cacheCreationAccounting: "not-reported",
2977
+ reportsReasoningOutput: true,
2978
+ reportsProviderTotal: true,
2979
+ reportsCost: false,
2980
+ emitsSubagentEvents: true,
2981
+ emitsCompactionEvents: true,
2982
+ requiresHookResponse: false,
2983
+ // Tool, subagent, and per-turn callbacks carry a replay-stable id; session and
2984
+ // compaction callbacks do not. See `./delivery.ts` for which and why.
2985
+ deliveryIdentifier: "partial"
2986
+ });
2987
+ var asRecord = (value) => value !== null && typeof value === "object" && !Array.isArray(value) ? value : void 0;
2988
+ var hasExactMarker = (payload) => {
2989
+ if (payload.codex_version !== void 0) {
2990
+ return true;
2991
+ }
2992
+ if (payload.permission_mode === "dontAsk") {
2993
+ return true;
2994
+ }
2995
+ return "tool_name" in payload && payload.tool_name === "apply_patch";
2996
+ };
2997
+ var detect = (input) => {
2998
+ const parsed = codexHookPayloadSchema.safeParse(input.payload);
2999
+ if (parsed.success) {
3000
+ const payload = parsed.data;
3001
+ const exact = hasExactMarker(payload);
3002
+ return providerDetectionSchema.parse({
3003
+ providerId: CODEX_PROVIDER_ID,
3004
+ confidence: exact ? "exact" : "strong",
3005
+ reasons: [
3006
+ "payload.hook_event_name matches the Codex hook protocol",
3007
+ ...exact ? ["payload carries a Codex-specific marker"] : []
3008
+ ],
3009
+ ...payload.codex_version === void 0 ? {} : { providerVersion: payload.codex_version },
3010
+ sourceEventName: payload.hook_event_name
3011
+ });
3012
+ }
3013
+ const envelope = codexHookEnvelopeSchema.safeParse(input.payload);
3014
+ if (envelope.success) {
3015
+ return providerDetectionSchema.parse({
3016
+ providerId: CODEX_PROVIDER_ID,
3017
+ confidence: "weak",
3018
+ reasons: [
3019
+ "payload.hook_event_name is a known Codex event but failed schema validation for it"
3020
+ ],
3021
+ sourceEventName: envelope.data.hook_event_name
3022
+ });
3023
+ }
3024
+ return unknownDetection(["payload does not match the Codex hook protocol"]);
3025
+ };
3026
+ var eventDiscriminator = (payload) => {
3027
+ switch (payload.hook_event_name) {
3028
+ case "PreToolUse":
3029
+ case "PermissionRequest":
3030
+ case "PostToolUse":
3031
+ return payload.tool_call_id ?? payload.tool_name;
3032
+ case "SubagentStart":
3033
+ case "SubagentStop":
3034
+ return payload.subagent_id;
3035
+ case "UserPromptSubmit":
3036
+ case "Stop":
3037
+ return payload.turn_id;
3038
+ case "SessionStart":
3039
+ case "PreCompact":
3040
+ case "PostCompact":
3041
+ return void 0;
3042
+ }
3043
+ };
3044
+ var identify = (input, context) => {
3045
+ const parsed = codexHookPayloadSchema.safeParse(input.payload);
3046
+ if (!parsed.success) {
3047
+ return [];
3048
+ }
3049
+ const payload = parsed.data;
3050
+ const occurredAt = payload.occurred_at ?? context.clock.now();
3051
+ const sessionId = sessionIdSchema.parse(payload.session_id);
3052
+ const discriminator = eventDiscriminator(payload);
3053
+ const invocationId = context.ids.newInvocationId({
3054
+ providerId: CODEX_PROVIDER_ID,
3055
+ sessionId,
3056
+ sourceEventName: payload.hook_event_name,
3057
+ occurredAt,
3058
+ ...discriminator === void 0 ? {} : { discriminator }
3059
+ });
3060
+ const workspace = payload.cwd === void 0 ? void 0 : deriveWorkspaceIdentity(context.privacy, { kind: "working-directory", absolutePath: payload.cwd });
3061
+ const claim = identityClaimSchema.parse({
3062
+ source: `adapter:${CODEX_PROVIDER_ID}`,
3063
+ confidence: input.detection.confidence,
3064
+ fields: {
3065
+ sessionId,
3066
+ invocationId,
3067
+ startedAt: occurredAt,
3068
+ ...workspace === void 0 ? {} : { workspace }
3069
+ }
3070
+ });
3071
+ return [claim];
3072
+ };
3073
+ var deriveSubagentInvocationId = (context, sessionId, subagentId) => invocationIdSchema.parse(
3074
+ `subinv_${context.ids.newOpaqueId(["codex", "subagent", sessionId, subagentId])}`
3075
+ );
3076
+ var outcomeFromToolResponse = (toolResponse) => {
3077
+ if (toolResponse === void 0) {
3078
+ return "unknown";
3079
+ }
3080
+ const record = asRecord(toolResponse);
3081
+ if (record === void 0) {
3082
+ return "ok";
3083
+ }
3084
+ if (typeof record.success === "boolean") {
3085
+ return record.success ? "ok" : "error";
3086
+ }
3087
+ if (typeof record.exit_code === "number" && record.exit_code !== 0) {
3088
+ return "error";
3089
+ }
3090
+ if (record.error !== void 0 && record.error !== null && record.error !== false) {
3091
+ return "error";
3092
+ }
3093
+ return "ok";
3094
+ };
3095
+ var mapTrigger = (trigger) => {
3096
+ if (trigger === "auto") {
3097
+ return "automatic";
3098
+ }
3099
+ if (trigger === "manual") {
3100
+ return "manual";
3101
+ }
3102
+ return "unknown";
3103
+ };
3104
+ var mapSubagentOutcome = (status) => {
3105
+ switch (status) {
3106
+ case "completed":
3107
+ return "ok";
3108
+ case "failed":
3109
+ return "error";
3110
+ case "cancelled":
3111
+ return "cancelled";
3112
+ default:
3113
+ return "unknown";
3114
+ }
3115
+ };
3116
+ var mapStopOutcome = (stopReason) => {
3117
+ if (stopReason === void 0) {
3118
+ return "ok";
3119
+ }
3120
+ const normalized = stopReason.toLowerCase();
3121
+ if (normalized.includes("cancel")) {
3122
+ return "cancelled";
3123
+ }
3124
+ if (normalized.includes("timeout")) {
3125
+ return "timeout";
3126
+ }
3127
+ if (normalized.includes("error") || normalized.includes("fail")) {
3128
+ return "error";
3129
+ }
3130
+ return "ok";
3131
+ };
3132
+ var parse = (input, context) => {
3133
+ const parsed = codexHookPayloadSchema.safeParse(input.payload);
3134
+ if (!parsed.success) {
3135
+ return {
3136
+ status: "failed",
3137
+ error: createErrorInfo({
3138
+ code: "invalid-input",
3139
+ phase: "parsing",
3140
+ detail: "payload does not match the Codex hook protocol"
3141
+ })
3142
+ };
3143
+ }
3144
+ const payload = parsed.data;
3145
+ const occurredAt = payload.occurred_at ?? context.clock.now();
3146
+ const factory = createEventFactory({
3147
+ identity: input.identity,
3148
+ sequenceBase: input.sequenceBase,
3149
+ context
3150
+ });
3151
+ const warnings = [];
3152
+ const buildUsage = (usage) => {
3153
+ if (usage === void 0) {
3154
+ return void 0;
3155
+ }
3156
+ const normalized = normalizeUsage(codexUsageToReport(usage, "cumulative"));
3157
+ if (normalized.status === "invalid") {
3158
+ warnings.push(...normalized.issues.map((issue) => issue.message));
3159
+ return void 0;
3160
+ }
3161
+ return normalized.usage;
3162
+ };
3163
+ switch (payload.hook_event_name) {
3164
+ case "SessionStart":
3165
+ factory.build({
3166
+ type: "session.start",
3167
+ sessionKind: "unknown",
3168
+ agentName: "codex",
3169
+ occurredAt,
3170
+ ...payload.codex_version === void 0 ? {} : { agentVersion: payload.codex_version },
3171
+ ...payload.model === void 0 ? {} : { model: { modelId: payload.model, vendor: "openai" } }
3172
+ });
3173
+ break;
3174
+ case "UserPromptSubmit":
3175
+ factory.build({
3176
+ type: "prompt.submitted",
3177
+ promptSource: "user",
3178
+ occurredAt,
3179
+ ...payload.prompt === void 0 ? {} : {
3180
+ content: context.privacy.describeContent({
3181
+ kind: "prompt",
3182
+ role: "user",
3183
+ text: payload.prompt
3184
+ })
3185
+ }
3186
+ });
3187
+ break;
3188
+ case "PreToolUse": {
3189
+ const toolCallId = payload.tool_call_id ?? context.ids.newOpaqueId([input.identity.sessionId, payload.turn_id ?? "", payload.tool_name]);
3190
+ factory.build({
3191
+ type: "tool.start",
3192
+ toolCallId,
3193
+ toolName: payload.tool_name,
3194
+ toolKind: classifyCodexToolKind(payload.tool_name),
3195
+ occurredAt,
3196
+ ...payload.tool_input === void 0 ? {} : {
3197
+ input: context.privacy.describeStructured({
3198
+ kind: "tool-input",
3199
+ value: payload.tool_input,
3200
+ label: payload.tool_name
3201
+ })
3202
+ }
3203
+ });
3204
+ break;
3205
+ }
3206
+ case "PermissionRequest":
3207
+ return {
3208
+ status: "ignored",
3209
+ reason: "permission requests carry no telemetry of their own; the decision surfaces on tool.end"
3210
+ };
3211
+ case "PostToolUse": {
3212
+ const toolCallId = payload.tool_call_id ?? context.ids.newOpaqueId([input.identity.sessionId, payload.turn_id ?? "", payload.tool_name]);
3213
+ const permissionDecision = payload.permission_decision ?? "not-required";
3214
+ const outcome = permissionDecision === "denied" ? "denied" : outcomeFromToolResponse(payload.tool_response);
3215
+ factory.build({
3216
+ type: "tool.end",
3217
+ toolCallId,
3218
+ toolName: payload.tool_name,
3219
+ outcome,
3220
+ permissionDecision,
3221
+ occurredAt,
3222
+ ...payload.duration_ms === void 0 ? {} : { durationMillis: payload.duration_ms },
3223
+ ...payload.tool_response === void 0 ? {} : {
3224
+ output: context.privacy.describeStructured({
3225
+ kind: "tool-output",
3226
+ value: payload.tool_response,
3227
+ label: payload.tool_name
3228
+ })
3229
+ }
3230
+ });
3231
+ break;
3232
+ }
3233
+ case "PreCompact":
3234
+ factory.build({
3235
+ type: "compaction.performed",
3236
+ trigger: mapTrigger(payload.trigger),
3237
+ occurredAt,
3238
+ ...payload.context_tokens_before === void 0 ? {} : { contextTokensBefore: payload.context_tokens_before }
3239
+ });
3240
+ break;
3241
+ case "PostCompact": {
3242
+ const usage = buildUsage(payload.usage);
3243
+ factory.build({
3244
+ type: "compaction.performed",
3245
+ trigger: mapTrigger(payload.trigger),
3246
+ occurredAt,
3247
+ ...payload.context_tokens_after === void 0 ? {} : { contextTokensAfter: payload.context_tokens_after },
3248
+ ...payload.dropped_message_count === void 0 ? {} : { droppedMessageCount: payload.dropped_message_count },
3249
+ ...usage === void 0 ? {} : { usage }
3250
+ });
3251
+ break;
3252
+ }
3253
+ case "SubagentStart": {
3254
+ const subagentInvocationId = deriveSubagentInvocationId(
3255
+ context,
3256
+ input.identity.sessionId,
3257
+ payload.subagent_id
3258
+ );
3259
+ factory.build({
3260
+ type: "subagent.start",
3261
+ subagentInvocationId,
3262
+ delegationDepth: 1,
3263
+ occurredAt,
3264
+ ...payload.subagent_type === void 0 ? {} : { subagentType: payload.subagent_type },
3265
+ ...payload.model === void 0 ? {} : { model: { modelId: payload.model, vendor: "openai" } }
3266
+ });
3267
+ break;
3268
+ }
3269
+ case "SubagentStop": {
3270
+ const subagentInvocationId = deriveSubagentInvocationId(
3271
+ context,
3272
+ input.identity.sessionId,
3273
+ payload.subagent_id
3274
+ );
3275
+ const usage = buildUsage(payload.usage);
3276
+ factory.build({
3277
+ type: "subagent.end",
3278
+ subagentInvocationId,
3279
+ outcome: mapSubagentOutcome(payload.status),
3280
+ occurredAt,
3281
+ ...usage === void 0 ? {} : { usage }
3282
+ });
3283
+ break;
3284
+ }
3285
+ case "Stop": {
3286
+ const generationId = payload.turn_id ?? context.ids.newOpaqueId([input.identity.sessionId, "stop", String(occurredAt)]);
3287
+ const usage = buildUsage(payload.usage);
3288
+ factory.build({
3289
+ type: "generation.end",
3290
+ generationId,
3291
+ model: {
3292
+ modelId: payload.model ?? "unknown",
3293
+ ...payload.model === void 0 ? {} : { vendor: "openai" }
3294
+ },
3295
+ outcome: mapStopOutcome(payload.stop_reason),
3296
+ occurredAt,
3297
+ ...payload.stop_reason === void 0 ? {} : { stopReason: payload.stop_reason },
3298
+ ...payload.duration_ms === void 0 ? {} : { durationMillis: payload.duration_ms },
3299
+ ...usage === void 0 ? {} : { usage }
3300
+ });
3301
+ break;
3302
+ }
3303
+ }
3304
+ return {
3305
+ status: "parsed",
3306
+ events: factory.events(),
3307
+ ...warnings.length === 0 ? {} : { warnings }
3308
+ };
3309
+ };
3310
+ var hookResponse = () => SILENT_HOOK_RESPONSE;
3311
+ var createCodexAdapter = () => ({
3312
+ id: CODEX_PROVIDER_ID,
3313
+ version: CODEX_ADAPTER_VERSION,
3314
+ capabilities: CODEX_CAPABILITIES,
3315
+ detect,
3316
+ identify,
3317
+ deliveryIdentity: codexDeliveryIdentity,
3318
+ deliveryGaps: CODEX_DELIVERY_GAPS,
3319
+ parse,
3320
+ hookResponse
3321
+ });
3322
+
3323
+ // src/providers/gemini/delivery.ts
3324
+ var GEMINI_UNIDENTIFIABLE_CALLBACKS = Object.freeze({
3325
+ SessionStart: "fires again within the same session_id on resume and clear (payload `source`), so session_id names a class of firings rather than one",
3326
+ SessionEnd: "the closing side of the same problem: a cleared session ends under the same session_id",
3327
+ BeforeTool: "ToolCallRequestInfo.callId exists but is not projected into the hook input; two calls to one tool can share a millisecond, so (timestamp, tool_name) would suppress a genuine second call",
3328
+ AfterTool: "ToolCallRequestInfo.callId exists but is not projected into the hook input; two calls to one tool can share a millisecond, so (timestamp, tool_name) would suppress a genuine second call",
3329
+ BeforeAgent: "no turn id; fires once per turn with only a millisecond separating turns",
3330
+ AfterAgent: "no turn id; fires once per turn with only a millisecond separating turns",
3331
+ PreCompress: "no compaction id; can fire repeatedly within one session",
3332
+ BeforeModel: "no request id",
3333
+ AfterModel: "fires per streaming chunk with the same llm_request each time, so several genuine firings share one request and often one millisecond",
3334
+ BeforeToolSelection: "no request id",
3335
+ Notification: "produces no canonical event"
3336
+ });
3337
+
3338
+ // src/providers/gemini/identity.ts
3339
+ var stableKey = (value) => {
3340
+ const seen = /* @__PURE__ */ new WeakSet();
3341
+ const walk = (input) => {
3342
+ if (input === null || input === void 0) {
3343
+ return "null";
3344
+ }
3345
+ if (typeof input === "string") {
3346
+ return JSON.stringify(input);
3347
+ }
3348
+ if (typeof input === "number") {
3349
+ return Number.isFinite(input) ? JSON.stringify(input) : "null";
3350
+ }
3351
+ if (typeof input === "boolean") {
3352
+ return input ? "true" : "false";
3353
+ }
3354
+ if (typeof input !== "object") {
3355
+ return "null";
3356
+ }
3357
+ if (seen.has(input)) {
3358
+ return '"<circular>"';
3359
+ }
3360
+ seen.add(input);
3361
+ if (Array.isArray(input)) {
3362
+ return `[${input.map((entry) => walk(entry)).join(",")}]`;
3363
+ }
3364
+ const record = input;
3365
+ const keys = Object.keys(record).sort();
3366
+ return `{${keys.map((key) => `${JSON.stringify(key)}:${walk(record[key])}`).join(",")}}`;
3367
+ };
3368
+ return walk(value);
3369
+ };
3370
+ var geminiSessionId = (input) => sessionIdSchema.parse(input.session_id);
3371
+ var parseGeminiTimestamp = (timestamp) => {
3372
+ if (timestamp === void 0) {
3373
+ return void 0;
3374
+ }
3375
+ const parsed = Date.parse(timestamp);
3376
+ return Number.isNaN(parsed) ? void 0 : parsed;
3377
+ };
3378
+ var geminiWorkspace = (context, input) => input.cwd === void 0 ? void 0 : deriveWorkspaceIdentity(context.privacy, { kind: "working-directory", absolutePath: input.cwd });
3379
+ var geminiToolCallKey = (input) => input.original_request_name === void 0 || input.original_request_name === input.tool_name ? input.tool_name : stableKey({ tail: input.tool_name, replacing: input.original_request_name });
3380
+ var geminiToolCallId = (context, sessionId, toolKey) => context.ids.newOpaqueId([sessionId, "gemini-cli", "tool", toolKey]);
3381
+ var geminiGenerationId = (context, sessionId, llmRequest) => context.ids.newOpaqueId([sessionId, "gemini-cli", "generation", stableKey(llmRequest)]);
3382
+ var geminiCorrelationSeed = (input) => {
3383
+ switch (input.hook_event_name) {
3384
+ case "SessionStart":
3385
+ return input.source ?? "session-start";
3386
+ case "SessionEnd":
3387
+ return input.reason ?? "session-end";
3388
+ case "BeforeAgent":
3389
+ return stableKey({ prompt: input.prompt });
3390
+ case "AfterAgent":
3391
+ return stableKey({ prompt: input.prompt, response: input.prompt_response });
3392
+ case "BeforeModel":
3393
+ return stableKey(input.llm_request);
3394
+ case "AfterModel":
3395
+ return stableKey({ request: input.llm_request, response: input.llm_response });
3396
+ case "BeforeToolSelection":
3397
+ return stableKey(input.llm_request);
3398
+ case "BeforeTool":
3399
+ return stableKey({ tool: geminiToolCallKey(input), input: input.tool_input });
3400
+ case "AfterTool":
3401
+ return stableKey({
3402
+ tool: geminiToolCallKey(input),
3403
+ input: input.tool_input,
3404
+ response: input.tool_response
3405
+ });
3406
+ case "PreCompress":
3407
+ return input.trigger ?? "compress";
3408
+ case "Notification":
3409
+ return stableKey({ type: input.notification_type, message: input.message });
3410
+ }
3411
+ };
3412
+
3413
+ // src/providers/gemini/schema.ts
3414
+ import { z as z14 } from "zod";
3415
+ var GEMINI_HOOK_EVENT_NAMES = [
3416
+ "SessionStart",
3417
+ "SessionEnd",
3418
+ "BeforeAgent",
3419
+ "AfterAgent",
3420
+ "BeforeModel",
3421
+ "AfterModel",
3422
+ "BeforeToolSelection",
3423
+ "BeforeTool",
3424
+ "AfterTool",
3425
+ "PreCompress",
3426
+ "Notification"
3427
+ ];
3428
+ var baseHookInputSchema = z14.object({
3429
+ session_id: z14.string().min(1),
3430
+ transcript_path: z14.string().optional(),
3431
+ cwd: z14.string().optional(),
3432
+ timestamp: z14.string().min(1).optional()
3433
+ });
3434
+ var llmMessageSchema = z14.object({
3435
+ role: z14.enum(["user", "model", "system"]).optional(),
3436
+ content: z14.union([z14.string(), z14.array(z14.unknown())]).optional()
3437
+ }).loose();
3438
+ var llmRequestConfigSchema = z14.object({
3439
+ temperature: z14.number().optional(),
3440
+ maxOutputTokens: z14.number().int().min(0).optional()
3441
+ }).loose();
3442
+ var geminiLlmRequestSchema = z14.object({
3443
+ model: z14.string().min(1).optional(),
3444
+ messages: z14.array(llmMessageSchema).optional(),
3445
+ config: llmRequestConfigSchema.optional(),
3446
+ toolConfig: z14.unknown().optional()
3447
+ }).loose();
3448
+ var geminiUsageMetadataSchema = z14.object({
3449
+ promptTokenCount: z14.number().int().min(0).optional(),
3450
+ cachedContentTokenCount: z14.number().int().min(0).optional(),
3451
+ candidatesTokenCount: z14.number().int().min(0).optional(),
3452
+ thoughtsTokenCount: z14.number().int().min(0).optional(),
3453
+ totalTokenCount: z14.number().int().min(0).optional()
3454
+ }).loose();
3455
+ var geminiCandidateSchema = z14.object({
3456
+ content: z14.object({
3457
+ role: z14.string().optional(),
3458
+ parts: z14.array(z14.unknown()).optional()
3459
+ }).loose().optional(),
3460
+ finishReason: z14.string().optional(),
3461
+ index: z14.number().int().min(0).optional()
3462
+ }).loose();
3463
+ var geminiLlmResponseSchema = z14.object({
3464
+ /** Whole-response text, set by the translator from `getResponseText`. */
3465
+ text: z14.string().optional(),
3466
+ candidates: z14.array(geminiCandidateSchema).optional(),
3467
+ usageMetadata: geminiUsageMetadataSchema.optional()
3468
+ }).loose();
3469
+ var geminiMcpContextSchema = z14.object({
3470
+ server_name: z14.string().optional(),
3471
+ tool_name: z14.string().optional()
3472
+ }).loose();
3473
+ var geminiToolResponseSchema = z14.object({
3474
+ llmContent: z14.unknown().optional(),
3475
+ returnDisplay: z14.unknown().optional(),
3476
+ error: z14.unknown().optional()
3477
+ }).loose();
3478
+ var sessionStartInputSchema = baseHookInputSchema.extend({
3479
+ hook_event_name: z14.literal("SessionStart"),
3480
+ source: z14.enum(["startup", "resume", "clear"]).optional()
3481
+ });
3482
+ var sessionEndInputSchema = baseHookInputSchema.extend({
3483
+ hook_event_name: z14.literal("SessionEnd"),
3484
+ reason: z14.enum(["exit", "clear", "logout", "prompt_input_exit", "other"]).optional()
3485
+ });
3486
+ var beforeAgentInputSchema = baseHookInputSchema.extend({
3487
+ hook_event_name: z14.literal("BeforeAgent"),
3488
+ prompt: z14.string().optional()
3489
+ });
3490
+ var afterAgentInputSchema = baseHookInputSchema.extend({
3491
+ hook_event_name: z14.literal("AfterAgent"),
3492
+ prompt: z14.string().optional(),
3493
+ prompt_response: z14.string().optional(),
3494
+ stop_hook_active: z14.boolean().optional()
3495
+ });
3496
+ var beforeModelInputSchema = baseHookInputSchema.extend({
3497
+ hook_event_name: z14.literal("BeforeModel"),
3498
+ llm_request: geminiLlmRequestSchema
3499
+ });
3500
+ var afterModelInputSchema = baseHookInputSchema.extend({
3501
+ hook_event_name: z14.literal("AfterModel"),
3502
+ llm_request: geminiLlmRequestSchema,
3503
+ llm_response: geminiLlmResponseSchema
3504
+ });
3505
+ var beforeToolSelectionInputSchema = baseHookInputSchema.extend({
3506
+ hook_event_name: z14.literal("BeforeToolSelection"),
3507
+ llm_request: geminiLlmRequestSchema
3508
+ });
3509
+ var beforeToolInputSchema = baseHookInputSchema.extend({
3510
+ hook_event_name: z14.literal("BeforeTool"),
3511
+ tool_name: z14.string().min(1),
3512
+ tool_input: z14.unknown().optional(),
3513
+ mcp_context: geminiMcpContextSchema.optional(),
3514
+ original_request_name: z14.string().min(1).optional()
3515
+ });
3516
+ var afterToolInputSchema = baseHookInputSchema.extend({
3517
+ hook_event_name: z14.literal("AfterTool"),
3518
+ tool_name: z14.string().min(1),
3519
+ tool_input: z14.unknown().optional(),
3520
+ tool_response: geminiToolResponseSchema.optional(),
3521
+ mcp_context: geminiMcpContextSchema.optional(),
3522
+ original_request_name: z14.string().min(1).optional()
3523
+ });
3524
+ var preCompressInputSchema = baseHookInputSchema.extend({
3525
+ hook_event_name: z14.literal("PreCompress"),
3526
+ trigger: z14.enum(["auto", "manual"]).optional()
3527
+ });
3528
+ var notificationInputSchema = baseHookInputSchema.extend({
3529
+ hook_event_name: z14.literal("Notification"),
3530
+ notification_type: z14.string().optional(),
3531
+ message: z14.string().optional(),
3532
+ details: z14.unknown().optional()
3533
+ });
3534
+ var geminiHookInputSchema = z14.discriminatedUnion("hook_event_name", [
3535
+ sessionStartInputSchema,
3536
+ sessionEndInputSchema,
3537
+ beforeAgentInputSchema,
3538
+ afterAgentInputSchema,
3539
+ beforeModelInputSchema,
3540
+ afterModelInputSchema,
3541
+ beforeToolSelectionInputSchema,
3542
+ beforeToolInputSchema,
3543
+ afterToolInputSchema,
3544
+ preCompressInputSchema,
3545
+ notificationInputSchema
3546
+ ]);
3547
+ var looksLikeGeminiHookPayload = (payload) => {
3548
+ if (typeof payload !== "object" || payload === null || Array.isArray(payload)) {
3549
+ return false;
3550
+ }
3551
+ const record = payload;
3552
+ return typeof record.session_id === "string" && typeof record.hook_event_name === "string" && GEMINI_HOOK_EVENT_NAMES.includes(record.hook_event_name);
3553
+ };
3554
+
3555
+ // src/providers/gemini/tool-kind.ts
3556
+ var BUILT_IN_TOOL_KIND2 = Object.freeze({
3557
+ read_file: "read",
3558
+ read_many_files: "read",
3559
+ list_directory: "read",
3560
+ get_internal_docs: "read",
3561
+ read_mcp_resource: "read",
3562
+ list_mcp_resources: "read",
3563
+ write_file: "write",
3564
+ replace: "write",
3565
+ run_shell_command: "execute",
3566
+ glob: "search",
3567
+ grep_search: "search",
3568
+ web_fetch: "network",
3569
+ google_web_search: "network",
3570
+ // Gemini's subagent entry point. The CLI has no subagent hook events, so a
3571
+ // delegated run is observable only as this tool's BeforeTool/AfterTool pair.
3572
+ invoke_agent: "delegate",
3573
+ activate_skill: "other",
3574
+ ask_user: "other",
3575
+ write_todos: "other",
3576
+ enter_plan_mode: "other",
3577
+ exit_plan_mode: "other",
3578
+ update_topic: "other",
3579
+ complete_task: "other",
3580
+ tracker_create_task: "other",
3581
+ tracker_update_task: "other",
3582
+ tracker_get_task: "other",
3583
+ tracker_list_tasks: "other",
3584
+ tracker_add_dependency: "other",
3585
+ tracker_visualize: "other"
3586
+ });
3587
+ var MCP_TOOL_PREFIX = "mcp_";
3588
+ var DISCOVERED_TOOL_PREFIX = "discovered_tool_";
3589
+ var classifyGeminiToolKind = (toolName) => {
3590
+ if (toolName.startsWith(MCP_TOOL_PREFIX) || toolName.startsWith(DISCOVERED_TOOL_PREFIX)) {
3591
+ return "unknown";
3592
+ }
3593
+ return BUILT_IN_TOOL_KIND2[toolName] ?? "unknown";
3594
+ };
3595
+
3596
+ // src/providers/gemini/usage.ts
3597
+ var mapGeminiUsage = (usage) => {
3598
+ if (usage === void 0) {
3599
+ return void 0;
3600
+ }
3601
+ const {
3602
+ promptTokenCount,
3603
+ cachedContentTokenCount,
3604
+ candidatesTokenCount,
3605
+ thoughtsTokenCount,
3606
+ totalTokenCount
3607
+ } = usage;
3608
+ const reportsNothing = promptTokenCount === void 0 && cachedContentTokenCount === void 0 && candidatesTokenCount === void 0 && thoughtsTokenCount === void 0 && totalTokenCount === void 0;
3609
+ if (reportsNothing) {
3610
+ return void 0;
3611
+ }
3612
+ const hasOutput = candidatesTokenCount !== void 0 || thoughtsTokenCount !== void 0;
3613
+ return usageReportSchema.parse({
3614
+ temporality: "cumulative",
3615
+ ...promptTokenCount === void 0 ? {} : { inputTokens: promptTokenCount },
3616
+ ...cachedContentTokenCount === void 0 ? {} : { cachedInputTokens: cachedContentTokenCount },
3617
+ ...hasOutput ? { outputTokens: (candidatesTokenCount ?? 0) + (thoughtsTokenCount ?? 0) } : {},
3618
+ ...thoughtsTokenCount === void 0 ? {} : { reasoningOutputTokens: thoughtsTokenCount },
3619
+ ...totalTokenCount === void 0 ? {} : { providerTotalTokens: totalTokenCount }
3620
+ });
3621
+ };
3622
+
3623
+ // src/providers/gemini/adapter.ts
3624
+ var GEMINI_PROVIDER_ID = "gemini-cli";
3625
+ var GEMINI_ADAPTER_VERSION = "0.1.0";
3626
+ var DEFAULT_GEMINI_CAPABILITIES = Object.freeze({
3627
+ lifecycleEvents: Object.freeze([
3628
+ "session.start",
3629
+ "session.end",
3630
+ "prompt.submitted",
3631
+ "generation.start",
3632
+ "generation.end",
3633
+ "tool.start",
3634
+ "tool.end",
3635
+ "compaction.performed"
3636
+ ]),
3637
+ // `AfterModel` fires per streaming chunk and a chunk's `usageMetadata` is a
3638
+ // snapshot of the response so far, not that chunk's increment. See
3639
+ // `./usage.ts` for the evidence; `delta` here would bill a multi-snapshot
3640
+ // stream several times over.
3641
+ usageTemporality: "cumulative",
3642
+ // Both false because the CLI's hook translator strips the counters before any
3643
+ // hook runs: `toHookLLMResponse` rebuilds `usageMetadata` as exactly
3644
+ // `{ promptTokenCount, candidatesTokenCount, totalTokenCount }`. The SDK
3645
+ // response it reads does carry `cachedContentTokenCount` and
3646
+ // `thoughtsTokenCount`, so this is a gap in the hook projection rather than in
3647
+ // the model — but a consumer must be able to tell "this provider reports no
3648
+ // cache reads" from "this session had none", and today it is the former.
3649
+ reportsCachedInput: false,
3650
+ reportsCacheCreation: false,
3651
+ cacheCreationAccounting: "not-reported",
3652
+ reportsReasoningOutput: false,
3653
+ reportsProviderTotal: true,
3654
+ reportsCost: false,
3655
+ // The Gemini CLI has no subagent hook events. Delegation happens through the
3656
+ // `invoke_agent` tool, so a subagent run is observable only as that tool's
3657
+ // BeforeTool/AfterTool pair — never as a distinct subagent lifecycle.
3658
+ emitsSubagentEvents: false,
3659
+ emitsCompactionEvents: true,
3660
+ requiresHookResponse: false,
3661
+ // Nothing in this protocol identifies a callback across a redelivery: there is
3662
+ // no request, turn, or tool-call id, and `session_id` repeats across resume and
3663
+ // clear. See `./delivery.ts` for the field-by-field reasoning.
3664
+ deliveryIdentifier: "none"
3665
+ });
3666
+ var SESSION_END_REASON_OUTCOME = Object.freeze({
3667
+ exit: "completed",
3668
+ clear: "completed",
3669
+ logout: "completed",
3670
+ prompt_input_exit: "completed",
3671
+ other: "unknown"
3672
+ });
3673
+ var FINISH_REASON_OUTCOME = Object.freeze({
3674
+ STOP: "ok",
3675
+ MAX_TOKENS: "ok",
3676
+ SAFETY: "denied",
3677
+ RECITATION: "denied",
3678
+ BLOCKLIST: "denied",
3679
+ PROHIBITED_CONTENT: "denied",
3680
+ SPII: "denied",
3681
+ LANGUAGE: "denied",
3682
+ MALFORMED_FUNCTION_CALL: "error",
3683
+ OTHER: "unknown"
3684
+ });
3685
+ var finishReasonOutcome = (finishReason) => finishReason === void 0 ? "unknown" : FINISH_REASON_OUTCOME[finishReason] ?? "unknown";
3686
+ var partText = (part) => {
3687
+ if (typeof part === "string") {
3688
+ return part;
3689
+ }
3690
+ if (typeof part === "object" && part !== null && "text" in part) {
3691
+ const { text } = part;
3692
+ return typeof text === "string" ? text : void 0;
3693
+ }
3694
+ return void 0;
3695
+ };
3696
+ var joinResponseText = (parts) => {
3697
+ if (parts === void 0 || parts.length === 0) {
3698
+ return void 0;
3699
+ }
3700
+ const texts = parts.map(partText).filter((text) => text !== void 0);
3701
+ const joined = texts.join("");
3702
+ return joined === "" ? void 0 : joined;
3703
+ };
3704
+ var nonEmpty = (text) => text === void 0 || text === "" ? void 0 : text;
3705
+ var messageText = (content) => {
3706
+ if (content === void 0) {
3707
+ return void 0;
3708
+ }
3709
+ if (typeof content === "string") {
3710
+ return content;
3711
+ }
3712
+ return joinResponseText(content);
3713
+ };
3714
+ var createGeminiCliAdapter = (options = {}) => {
3715
+ const id = providerIdSchema.parse(options.id ?? GEMINI_PROVIDER_ID);
3716
+ const version = options.version ?? GEMINI_ADAPTER_VERSION;
3717
+ const capabilities = {
3718
+ ...DEFAULT_GEMINI_CAPABILITIES,
3719
+ ...options.capabilities
3720
+ };
3721
+ const detect2 = (input) => {
3722
+ const parsed = geminiHookInputSchema.safeParse(input.payload);
3723
+ if (parsed.success) {
3724
+ return providerDetectionSchema.parse({
3725
+ providerId: id,
3726
+ confidence: "exact",
3727
+ reasons: [
3728
+ "payload matches the Gemini CLI command hook schema",
3729
+ `hook_event_name=${parsed.data.hook_event_name}`
3730
+ ],
3731
+ sourceEventName: parsed.data.hook_event_name
3732
+ });
3733
+ }
3734
+ if (looksLikeGeminiHookPayload(input.payload)) {
3735
+ const record = input.payload;
3736
+ return providerDetectionSchema.parse({
3737
+ providerId: id,
3738
+ confidence: "weak",
3739
+ reasons: [
3740
+ "payload has session_id and a recognized hook_event_name but failed event-specific validation"
3741
+ ],
3742
+ sourceEventName: record.hook_event_name
3743
+ });
3744
+ }
3745
+ return unknownDetection(["payload does not match the Gemini CLI command hook protocol"]);
3746
+ };
3747
+ const identify2 = (input, context) => {
3748
+ const parsed = geminiHookInputSchema.safeParse(input.payload);
3749
+ if (!parsed.success) {
3750
+ return [];
3751
+ }
3752
+ const payload = parsed.data;
3753
+ const sessionId = geminiSessionId(payload);
3754
+ const startedAt = parseGeminiTimestamp(payload.timestamp) ?? context.clock.now();
3755
+ const workspace = geminiWorkspace(context, payload);
3756
+ const invocationId = context.ids.newInvocationId({
3757
+ providerId: id,
3758
+ sessionId,
3759
+ sourceEventName: payload.hook_event_name,
3760
+ occurredAt: startedAt,
3761
+ discriminator: geminiCorrelationSeed(payload)
3762
+ });
3763
+ return [
3764
+ identityClaimSchema.parse({
3765
+ source: `adapter:${id}`,
3766
+ confidence: input.detection.confidence,
3767
+ fields: {
3768
+ sessionId,
3769
+ invocationId,
3770
+ startedAt,
3771
+ ...workspace === void 0 ? {} : { workspace }
3772
+ }
3773
+ })
3774
+ ];
3775
+ };
3776
+ const parse2 = (input, context) => {
3777
+ const parsed = geminiHookInputSchema.safeParse(input.payload);
3778
+ if (!parsed.success) {
3779
+ return {
3780
+ status: "failed",
3781
+ error: createErrorInfo({
3782
+ code: "invalid-input",
3783
+ phase: "parsing",
3784
+ detail: "payload does not match the Gemini CLI command hook protocol"
3785
+ })
3786
+ };
3787
+ }
3788
+ const payload = parsed.data;
3789
+ const sessionId = String(input.identity.sessionId);
3790
+ const occurredAt = input.identity.startedAt;
3791
+ const factory = createEventFactory({
3792
+ identity: input.identity,
3793
+ sequenceBase: input.sequenceBase,
3794
+ context
3795
+ });
3796
+ const warnings = [];
3797
+ switch (payload.hook_event_name) {
3798
+ case "SessionStart": {
3799
+ factory.build({
3800
+ type: "session.start",
3801
+ sessionKind: "unknown",
3802
+ agentName: "gemini-cli",
3803
+ occurredAt
3804
+ });
3805
+ break;
3806
+ }
3807
+ case "SessionEnd": {
3808
+ factory.build({
3809
+ type: "session.end",
3810
+ reason: SESSION_END_REASON_OUTCOME[payload.reason ?? "other"] ?? "unknown",
3811
+ occurredAt
3812
+ });
3813
+ break;
3814
+ }
3815
+ case "BeforeAgent": {
3816
+ factory.build({
3817
+ type: "prompt.submitted",
3818
+ promptSource: "user",
3819
+ occurredAt,
3820
+ ...payload.prompt === void 0 ? {} : {
3821
+ content: context.privacy.describeContent({
3822
+ kind: "prompt",
3823
+ role: "user",
3824
+ text: payload.prompt
3825
+ })
3826
+ }
3827
+ });
3828
+ break;
3829
+ }
3830
+ case "AfterAgent": {
3831
+ return {
3832
+ status: "ignored",
3833
+ reason: "AfterAgent marks turn completion; the canonical model has no turn-level event distinct from generation.end, so it carries no telemetry of its own"
3834
+ };
3835
+ }
3836
+ case "BeforeModel": {
3837
+ const generationId = geminiGenerationId(context, sessionId, payload.llm_request);
3838
+ const model = { modelId: payload.llm_request.model ?? "unknown", vendor: "google" };
3839
+ const inputContent = (payload.llm_request.messages ?? []).map((message) => {
3840
+ const text = messageText(message.content);
3841
+ return text === void 0 ? void 0 : context.privacy.describeContent({
3842
+ kind: "prompt",
3843
+ role: message.role === "model" ? "assistant" : message.role ?? "unknown",
3844
+ text
3845
+ });
3846
+ }).filter((fact) => fact !== void 0);
3847
+ factory.build({
3848
+ type: "generation.start",
3849
+ generationId,
3850
+ model,
3851
+ occurredAt,
3852
+ ...payload.llm_request.config?.maxOutputTokens === void 0 ? {} : { requestedMaxOutputTokens: payload.llm_request.config.maxOutputTokens },
3853
+ ...inputContent.length === 0 ? {} : { inputContent }
3854
+ });
3855
+ break;
3856
+ }
3857
+ case "AfterModel": {
3858
+ const usage = mapGeminiUsage(payload.llm_response.usageMetadata);
3859
+ if (usage === void 0) {
3860
+ return {
3861
+ status: "ignored",
3862
+ reason: "AfterModel fired for a streaming chunk carrying no usageMetadata snapshot"
3863
+ };
3864
+ }
3865
+ const generationId = geminiGenerationId(context, sessionId, payload.llm_request);
3866
+ const model = { modelId: payload.llm_request.model ?? "unknown", vendor: "google" };
3867
+ const candidate = payload.llm_response.candidates?.[0];
3868
+ const outputText = joinResponseText(candidate?.content?.parts) ?? nonEmpty(payload.llm_response.text);
3869
+ const usageResult = normalizeUsageOrWarn(usage, warnings);
3870
+ factory.build({
3871
+ type: "generation.end",
3872
+ generationId,
3873
+ model,
3874
+ outcome: finishReasonOutcome(candidate?.finishReason),
3875
+ occurredAt,
3876
+ ...candidate?.finishReason === void 0 ? {} : { stopReason: candidate.finishReason },
3877
+ ...usageResult === void 0 ? {} : { usage: usageResult },
3878
+ ...outputText === void 0 ? {} : {
3879
+ outputContent: [
3880
+ context.privacy.describeContent({ kind: "response", role: "assistant", text: outputText })
3881
+ ]
3882
+ }
3883
+ });
3884
+ break;
3885
+ }
3886
+ case "BeforeToolSelection": {
3887
+ return {
3888
+ status: "ignored",
3889
+ reason: "BeforeToolSelection carries tool-choice configuration only, not lifecycle telemetry"
3890
+ };
3891
+ }
3892
+ case "BeforeTool": {
3893
+ const toolCallId = geminiToolCallId(context, sessionId, geminiToolCallKey(payload));
3894
+ factory.build({
3895
+ type: "tool.start",
3896
+ toolCallId,
3897
+ toolName: payload.tool_name,
3898
+ toolKind: classifyGeminiToolKind(payload.tool_name),
3899
+ occurredAt,
3900
+ ...payload.tool_input === void 0 ? {} : {
3901
+ input: context.privacy.describeStructured({
3902
+ kind: "tool-input",
3903
+ value: payload.tool_input,
3904
+ label: payload.tool_name
3905
+ })
3906
+ }
3907
+ });
3908
+ break;
3909
+ }
3910
+ case "AfterTool": {
3911
+ const toolCallId = geminiToolCallId(context, sessionId, geminiToolCallKey(payload));
3912
+ const hasError = payload.tool_response?.error !== void 0;
3913
+ factory.build({
3914
+ type: "tool.end",
3915
+ toolCallId,
3916
+ toolName: payload.tool_name,
3917
+ outcome: hasError ? "error" : "ok",
3918
+ occurredAt,
3919
+ ...payload.tool_response === void 0 ? {} : {
3920
+ output: context.privacy.describeStructured({
3921
+ kind: "tool-output",
3922
+ value: payload.tool_response,
3923
+ label: payload.tool_name
3924
+ })
3925
+ }
3926
+ });
3927
+ break;
3928
+ }
3929
+ case "PreCompress": {
3930
+ factory.build({
3931
+ type: "compaction.performed",
3932
+ trigger: payload.trigger === "manual" ? "manual" : payload.trigger === "auto" ? "automatic" : "unknown",
3933
+ occurredAt
3934
+ });
3935
+ break;
3936
+ }
3937
+ case "Notification": {
3938
+ return {
3939
+ status: "ignored",
3940
+ reason: "Notification is observability-only in the Gemini CLI protocol and has no canonical event type"
3941
+ };
3942
+ }
3943
+ }
3944
+ return {
3945
+ status: "parsed",
3946
+ events: factory.events(),
3947
+ ...warnings.length === 0 ? {} : { warnings }
3948
+ };
3949
+ };
3950
+ const hookResponse2 = () => SILENT_HOOK_RESPONSE;
3951
+ return {
3952
+ id,
3953
+ version,
3954
+ capabilities,
3955
+ detect: detect2,
3956
+ identify: identify2,
3957
+ // No `deliveryIdentity`: the capability is `none`, and offering a resolver
3958
+ // that always declines would be a contradiction the runtime never consults.
3959
+ // The gap table is still worth carrying — "the protocol has no request id" is
3960
+ // the actionable half of that answer, and only this adapter can say it.
3961
+ deliveryGaps: GEMINI_UNIDENTIFIABLE_CALLBACKS,
3962
+ parse: parse2,
3963
+ hookResponse: hookResponse2
3964
+ };
3965
+ };
3966
+ var normalizeUsageOrWarn = (usage, warnings) => {
3967
+ if (usage === void 0) {
3968
+ return void 0;
3969
+ }
3970
+ const normalized = normalizeUsage(usage);
3971
+ if (normalized.status === "invalid") {
3972
+ warnings.push(...normalized.issues.map((issue) => issue.message));
3973
+ return void 0;
3974
+ }
3975
+ return normalized.usage;
3976
+ };
3977
+
3978
+ // src/providers/antigravity/payload.ts
3979
+ import { z as z15 } from "zod";
3980
+ var ANTIGRAVITY_HOOK_EVENT_NAMES = [
3981
+ "PreInvocation",
3982
+ "PostInvocation",
3983
+ "PreToolUse",
3984
+ "PostToolUse",
3985
+ "Stop"
3986
+ ];
3987
+ var hookEventNameSchema = z15.enum(ANTIGRAVITY_HOOK_EVENT_NAMES);
3988
+ var antigravityWeakShapeSchema = z15.object({ hookEventName: hookEventNameSchema }).passthrough();
3989
+ var commonFields2 = {
3990
+ conversationId: z15.string().min(1),
3991
+ workspacePaths: z15.array(z15.string().min(1)).max(64),
3992
+ invocationNum: z15.number().int().min(0),
3993
+ /** Never disclosed: a real filesystem path. Accepted, never propagated. */
3994
+ transcriptPath: z15.string().min(1).optional(),
3995
+ /** Never disclosed: a real filesystem path. Accepted, never propagated. */
3996
+ artifactDirectoryPath: z15.string().min(1).optional()
3997
+ };
3998
+ var preInvocationPayloadSchema = z15.object({
3999
+ hookEventName: z15.literal("PreInvocation"),
4000
+ ...commonFields2,
4001
+ agentVersion: z15.string().min(1).optional()
4002
+ });
4003
+ var postInvocationPayloadSchema = z15.object({
4004
+ hookEventName: z15.literal("PostInvocation"),
4005
+ ...commonFields2,
4006
+ agentVersion: z15.string().min(1).optional()
4007
+ });
4008
+ var preToolUsePayloadSchema3 = z15.object({
4009
+ hookEventName: z15.literal("PreToolUse"),
4010
+ ...commonFields2,
4011
+ stepIdx: z15.number().int().min(0),
4012
+ toolName: z15.string().min(1),
4013
+ toolInput: z15.unknown().optional()
4014
+ });
4015
+ var postToolUsePayloadSchema3 = z15.object({
4016
+ hookEventName: z15.literal("PostToolUse"),
4017
+ ...commonFields2,
4018
+ stepIdx: z15.number().int().min(0),
4019
+ toolName: z15.string().min(1),
4020
+ toolResponse: z15.unknown().optional(),
4021
+ isError: z15.boolean().optional()
4022
+ });
4023
+ var stopPayloadSchema3 = z15.object({
4024
+ hookEventName: z15.literal("Stop"),
4025
+ ...commonFields2,
4026
+ fullyIdle: z15.boolean()
4027
+ });
4028
+ var antigravityHookPayloadSchema = z15.discriminatedUnion("hookEventName", [
4029
+ preInvocationPayloadSchema,
4030
+ postInvocationPayloadSchema,
4031
+ preToolUsePayloadSchema3,
4032
+ postToolUsePayloadSchema3,
4033
+ stopPayloadSchema3
4034
+ ]);
4035
+ var ANTIGRAVITY_SUBAGENT_TOOL_NAME = "invoke_subagent";
4036
+
4037
+ // src/providers/antigravity/delivery.ts
4038
+ var INVOCATION_SCOPED_EVENTS = ["PreInvocation", "PostInvocation"];
4039
+ var antigravityDeliveryIdentity = (input) => {
4040
+ const parsed = antigravityHookPayloadSchema.safeParse(input.payload);
4041
+ if (!parsed.success) {
4042
+ return void 0;
4043
+ }
4044
+ const payload = parsed.data;
4045
+ if (payload.hookEventName === "PreToolUse" || payload.hookEventName === "PostToolUse") {
4046
+ return {
4047
+ sessionId: payload.conversationId,
4048
+ sourceEventName: payload.hookEventName,
4049
+ components: [String(payload.invocationNum), String(payload.stepIdx)],
4050
+ evidence: ["payload.invocationNum with payload.stepIdx names one step of one invocation"]
4051
+ };
4052
+ }
4053
+ if (INVOCATION_SCOPED_EVENTS.includes(payload.hookEventName)) {
4054
+ return {
4055
+ sessionId: payload.conversationId,
4056
+ sourceEventName: payload.hookEventName,
4057
+ components: [String(payload.invocationNum)],
4058
+ evidence: ["payload.invocationNum names one invocation, whose edges fire once each"]
4059
+ };
4060
+ }
4061
+ return void 0;
4062
+ };
4063
+ var ANTIGRAVITY_DELIVERY_GAPS = Object.freeze({
4064
+ Stop: "Stop can fire twice per invocation (idle, then fully idle) and payload `fullyIdle` \u2014 the only field separating them \u2014 is an unconfirmed reconstruction, so invocationNum alone would suppress the second real firing"
4065
+ });
4066
+
4067
+ // src/providers/antigravity/adapter.ts
4068
+ var ANTIGRAVITY_PROVIDER_ID = "antigravity";
4069
+ var ANTIGRAVITY_CAPABILITIES = Object.freeze({
4070
+ lifecycleEvents: Object.freeze(["tool.start", "tool.end"]),
4071
+ usageTemporality: "delta",
4072
+ reportsCachedInput: false,
4073
+ reportsCacheCreation: false,
4074
+ cacheCreationAccounting: "not-reported",
4075
+ reportsReasoningOutput: false,
4076
+ reportsProviderTotal: false,
4077
+ reportsCost: false,
4078
+ emitsSubagentEvents: false,
4079
+ emitsCompactionEvents: false,
4080
+ requiresHookResponse: false,
4081
+ // Only the tool pair carries a replay-stable id, and only from the two
4082
+ // verified counters. See `./delivery.ts` for which and why.
4083
+ deliveryIdentifier: "partial"
4084
+ });
4085
+ var createAntigravityAdapter = (options = {}) => {
4086
+ const id = providerIdSchema.parse(options.id ?? ANTIGRAVITY_PROVIDER_ID);
4087
+ const version = options.version ?? "0.1.0";
4088
+ const detect2 = (input) => {
4089
+ const full = antigravityHookPayloadSchema.safeParse(input.payload);
4090
+ if (full.success) {
4091
+ return providerDetectionSchema.parse({
4092
+ providerId: id,
4093
+ confidence: "exact",
4094
+ reasons: [`payload matches the documented antigravity ${full.data.hookEventName} hook shape`],
4095
+ sourceEventName: full.data.hookEventName
4096
+ });
4097
+ }
4098
+ const weak = antigravityWeakShapeSchema.safeParse(input.payload);
4099
+ if (weak.success) {
4100
+ return providerDetectionSchema.parse({
4101
+ providerId: id,
4102
+ confidence: "weak",
4103
+ reasons: [
4104
+ `payload.hookEventName=${weak.data.hookEventName} matches antigravity but required fields are missing or invalid`
4105
+ ],
4106
+ sourceEventName: weak.data.hookEventName
4107
+ });
4108
+ }
4109
+ return unknownDetection(["payload does not match any documented antigravity hook shape"]);
4110
+ };
4111
+ const identify2 = (input, context) => {
4112
+ const parsed = antigravityHookPayloadSchema.safeParse(input.payload);
4113
+ if (!parsed.success) {
4114
+ return [];
4115
+ }
4116
+ const payload = parsed.data;
4117
+ const sessionId = sessionIdSchema.parse(payload.conversationId);
4118
+ const invocationId = context.ids.newInvocationId({
4119
+ providerId: id,
4120
+ sessionId,
4121
+ occurredAt: 0,
4122
+ discriminator: String(payload.invocationNum)
4123
+ });
4124
+ const [firstWorkspacePath] = payload.workspacePaths;
4125
+ const workspace = firstWorkspacePath === void 0 ? unknownWorkspaceIdentity() : deriveWorkspaceIdentity(context.privacy, {
4126
+ kind: "working-directory",
4127
+ absolutePath: firstWorkspacePath
4128
+ });
4129
+ return [
4130
+ identityClaimSchema.parse({
4131
+ source: `adapter:${id}`,
4132
+ confidence: input.detection.confidence,
4133
+ fields: { sessionId, invocationId, workspace }
4134
+ })
4135
+ ];
4136
+ };
4137
+ const parse2 = (input, context) => {
4138
+ const parsed = antigravityHookPayloadSchema.safeParse(input.payload);
4139
+ if (!parsed.success) {
4140
+ return {
4141
+ status: "failed",
4142
+ error: createErrorInfo({
4143
+ code: "invalid-input",
4144
+ phase: "parsing",
4145
+ detail: "payload does not match the documented antigravity hook contract"
4146
+ })
4147
+ };
4148
+ }
4149
+ const payload = parsed.data;
4150
+ const factory = createEventFactory({
4151
+ identity: input.identity,
4152
+ sequenceBase: input.sequenceBase,
4153
+ context
4154
+ });
4155
+ switch (payload.hookEventName) {
4156
+ case "PreInvocation":
4157
+ return {
4158
+ status: "ignored",
4159
+ reason: "PreInvocation reports invocation bookkeeping only; it carries no modelId or usage, so it cannot become a generation fact, and it is not a genuine session-start signal Antigravity documents"
4160
+ };
4161
+ case "PostInvocation":
4162
+ return {
4163
+ status: "ignored",
4164
+ reason: "PostInvocation reports invocation bookkeeping only; it carries no modelId, usage, or outcome that the canonical model can represent without inventing a generation fact"
4165
+ };
4166
+ case "PreToolUse": {
4167
+ const toolCallId = context.ids.newOpaqueId([
4168
+ payload.conversationId,
4169
+ "step",
4170
+ String(payload.stepIdx)
4171
+ ]);
4172
+ const toolKind = payload.toolName === ANTIGRAVITY_SUBAGENT_TOOL_NAME ? "delegate" : "unknown";
4173
+ factory.build({
4174
+ type: "tool.start",
4175
+ toolCallId,
4176
+ toolName: payload.toolName,
4177
+ toolKind,
4178
+ ...payload.toolInput === void 0 ? {} : {
4179
+ input: context.privacy.describeStructured({
4180
+ kind: "tool-input",
4181
+ value: payload.toolInput,
4182
+ label: payload.toolName
4183
+ })
4184
+ }
4185
+ });
4186
+ break;
4187
+ }
4188
+ case "PostToolUse": {
4189
+ const toolCallId = context.ids.newOpaqueId([
4190
+ payload.conversationId,
4191
+ "step",
4192
+ String(payload.stepIdx)
4193
+ ]);
4194
+ const outcome = payload.isError === true ? "error" : payload.isError === false ? "ok" : "unknown";
4195
+ factory.build({
4196
+ type: "tool.end",
4197
+ toolCallId,
4198
+ toolName: payload.toolName,
4199
+ outcome,
4200
+ ...payload.toolResponse === void 0 ? {} : {
4201
+ output: context.privacy.describeStructured({
4202
+ kind: "tool-output",
4203
+ value: payload.toolResponse,
4204
+ label: payload.toolName
4205
+ })
4206
+ }
4207
+ });
4208
+ break;
4209
+ }
4210
+ case "Stop":
4211
+ return {
4212
+ status: "ignored",
4213
+ reason: payload.fullyIdle ? "Stop signals execution/turn completion (fullyIdle=true) but exposes no session or generation identity, so it cannot become session.end or generation.end without inventing one" : "Stop received while the agent is not fully idle; the conversation continues and the hook exposes no lifecycle fact the canonical model can represent"
4214
+ };
4215
+ }
4216
+ return { status: "parsed", events: factory.events() };
4217
+ };
4218
+ const hookResponse2 = () => SILENT_HOOK_RESPONSE;
4219
+ return {
4220
+ id,
4221
+ version,
4222
+ capabilities: ANTIGRAVITY_CAPABILITIES,
4223
+ detect: detect2,
4224
+ identify: identify2,
4225
+ deliveryIdentity: antigravityDeliveryIdentity,
4226
+ deliveryGaps: ANTIGRAVITY_DELIVERY_GAPS,
4227
+ parse: parse2,
4228
+ hookResponse: hookResponse2
4229
+ };
4230
+ };
4231
+
4232
+ // src/providers/antigravity/maturity.ts
4233
+ var ANTIGRAVITY_PROVIDER_MATURITY = "experimental";
4234
+ var ANTIGRAVITY_PROMOTION_GATES = Object.freeze([
4235
+ "confirm whether PreInvocation/PostInvocation ever expose modelId or usage",
4236
+ "confirm whether any hook documents a genuine session/conversation start or end",
4237
+ "confirm whether Stop or another hook can honestly close out a generation.end",
4238
+ "confirm whether Antigravity reports a native tool-call identifier",
4239
+ "confirm whether invoke_subagent should have a dedicated subagent lifecycle",
4240
+ "confirm PostToolUse.isError against real payloads",
4241
+ "replay a captured, redacted transcript with zero validation/privacy diagnostics"
4242
+ ]);
4243
+
4244
+ // src/providers/defaults.ts
4245
+ var PROVIDER_DESCRIPTORS = Object.freeze([
4246
+ Object.freeze({
4247
+ id: ANTIGRAVITY_PROVIDER_ID,
4248
+ maturity: ANTIGRAVITY_PROVIDER_MATURITY,
4249
+ title: "Google Antigravity (experimental)",
4250
+ createAdapter: () => createAntigravityAdapter(),
4251
+ promotionGates: ANTIGRAVITY_PROMOTION_GATES
4252
+ }),
4253
+ Object.freeze({
4254
+ id: CLAUDE_CODE_PROVIDER_ID,
4255
+ maturity: "stable",
4256
+ title: "Claude Code",
4257
+ createAdapter: () => createClaudeCodeAdapter(),
4258
+ promotionGates: Object.freeze([])
4259
+ }),
4260
+ Object.freeze({
4261
+ id: CODEX_PROVIDER_ID,
4262
+ maturity: "stable",
4263
+ title: "OpenAI Codex CLI",
4264
+ createAdapter: () => createCodexAdapter(),
4265
+ promotionGates: Object.freeze([])
4266
+ }),
4267
+ Object.freeze({
4268
+ id: CURSOR_PROVIDER_ID,
4269
+ maturity: "stable",
4270
+ title: "Cursor",
4271
+ createAdapter: () => createCursorAdapter(),
4272
+ promotionGates: Object.freeze([])
4273
+ }),
4274
+ Object.freeze({
4275
+ id: GEMINI_PROVIDER_ID,
4276
+ maturity: "stable",
4277
+ title: "Gemini CLI",
4278
+ createAdapter: () => createGeminiCliAdapter(),
4279
+ promotionGates: Object.freeze([])
4280
+ })
4281
+ ]);
4282
+ var EXPERIMENTAL_PROVIDER_IDS = Object.freeze(
4283
+ PROVIDER_DESCRIPTORS.filter((descriptor) => descriptor.maturity === "experimental").map(
4284
+ (descriptor) => descriptor.id
4285
+ )
4286
+ );
4287
+ var findProviderDescriptor = (id) => PROVIDER_DESCRIPTORS.find((descriptor) => descriptor.id === id);
4288
+ var isExperimentalProvider = (id) => findProviderDescriptor(id)?.maturity === "experimental";
4289
+ var createDefaultProviderRegistry = (options = {}) => {
4290
+ const includeExperimental = options.includeExperimental ?? true;
4291
+ const only = options.only ?? [];
4292
+ const selected = PROVIDER_DESCRIPTORS.filter((descriptor) => {
4293
+ if (only.length > 0 && !only.includes(descriptor.id)) {
4294
+ return false;
4295
+ }
4296
+ return includeExperimental || descriptor.maturity !== "experimental";
4297
+ });
4298
+ return createProviderRegistry([
4299
+ ...selected.map((descriptor) => descriptor.createAdapter()),
4300
+ ...options.additional ?? []
4301
+ ]);
4302
+ };
4303
+ var DELIVERY_IDENTIFIER_SUMMARY = Object.freeze({
4304
+ none: "no callback carries a replay-stable identifier",
4305
+ partial: "some callbacks carry a replay-stable identifier",
4306
+ all: "every recognized callback carries a replay-stable identifier"
4307
+ });
4308
+ var describeProviderCatalog = (options = {}) => {
4309
+ const includeExperimental = options.includeExperimental ?? true;
4310
+ const only = options.only ?? [];
4311
+ const entries = [];
4312
+ for (const descriptor of PROVIDER_DESCRIPTORS) {
4313
+ if (only.length > 0 && !only.includes(descriptor.id)) {
4314
+ continue;
4315
+ }
4316
+ if (!includeExperimental && descriptor.maturity === "experimental") {
4317
+ continue;
4318
+ }
4319
+ const adapter = descriptor.createAdapter();
4320
+ const { capabilities } = adapter;
4321
+ entries.push({
4322
+ ...describeAdapter(adapter),
4323
+ maturity: descriptor.maturity,
4324
+ title: descriptor.title,
4325
+ promotionGates: [...descriptor.promotionGates],
4326
+ requiresHookResponse: capabilities.requiresHookResponse,
4327
+ ...capabilities.cumulativeUsageSeries === void 0 ? {} : { cumulativeUsageSeries: capabilities.cumulativeUsageSeries },
4328
+ reportsCachedInput: capabilities.reportsCachedInput,
4329
+ reportsCacheCreation: capabilities.reportsCacheCreation,
4330
+ cacheCreationAccounting: capabilities.cacheCreationAccounting,
4331
+ reportsReasoningOutput: capabilities.reportsReasoningOutput,
4332
+ reportsProviderTotal: capabilities.reportsProviderTotal,
4333
+ reportsCost: capabilities.reportsCost,
4334
+ emitsSubagentEvents: capabilities.emitsSubagentEvents,
4335
+ emitsCompactionEvents: capabilities.emitsCompactionEvents
4336
+ });
4337
+ }
4338
+ return entries;
4339
+ };
4340
+ export {
4341
+ ANTIGRAVITY_CAPABILITIES,
4342
+ ANTIGRAVITY_HOOK_EVENT_NAMES,
4343
+ ANTIGRAVITY_PROMOTION_GATES,
4344
+ ANTIGRAVITY_PROVIDER_ID,
4345
+ ANTIGRAVITY_PROVIDER_MATURITY,
4346
+ BUILT_IN_PROVIDERS,
4347
+ CLAUDE_CODE_CAPABILITIES,
4348
+ CLAUDE_CODE_PROVIDER_ID,
4349
+ CLAUDE_HOOK_EVENT_NAMES,
4350
+ CODEX_ADAPTER_VERSION,
4351
+ CODEX_CAPABILITIES,
4352
+ CODEX_HOOK_EVENT_NAMES,
4353
+ CODEX_PROVIDER_ID,
4354
+ CURSOR_ADAPTER_VERSION,
4355
+ CURSOR_CAPABILITIES,
4356
+ CURSOR_DECISION_EVENTS,
4357
+ CURSOR_HOOK_EVENT_NAMES,
4358
+ CURSOR_PROVIDER_ID,
4359
+ CURSOR_UNMODELLED_HOOK_EVENT_NAMES,
4360
+ DEFAULT_GEMINI_CAPABILITIES,
4361
+ DELIVERY_COMPONENT_PATTERN,
4362
+ DELIVERY_GAP_REASON_PATTERN,
4363
+ DELIVERY_IDENTIFIER_SUMMARY,
4364
+ EXPERIMENTAL_PROVIDER_IDS,
4365
+ GEMINI_ADAPTER_VERSION,
4366
+ GEMINI_HOOK_EVENT_NAMES,
4367
+ GEMINI_PROVIDER_ID,
4368
+ MAX_DELIVERY_COMPONENTS,
4369
+ MAX_DELIVERY_GAPS,
4370
+ PROVIDER_DESCRIPTORS,
4371
+ SILENT_HOOK_RESPONSE,
4372
+ adapterSupports,
4373
+ asProviderId,
4374
+ createAntigravityAdapter,
4375
+ createClaudeCodeAdapter,
4376
+ createCodexAdapter,
4377
+ createCursorAdapter,
4378
+ createDefaultProviderRegistry,
4379
+ createEventFactory,
4380
+ createGeminiCliAdapter,
4381
+ createProviderRegistry,
4382
+ deliveryComponentSchema,
4383
+ deliveryGapReasonSchema,
4384
+ deliveryIdentifierSupportSchema,
4385
+ describeAdapter,
4386
+ describeProviderCatalog,
4387
+ findProviderDescriptor,
4388
+ isExperimentalProvider,
4389
+ providerCapabilitiesSchema,
4390
+ providerDeliveryClaimSchema,
4391
+ providerDeliveryGapsSchema,
4392
+ providerDetectionSchema,
4393
+ providerHookResponseSchema,
4394
+ readDeliveryClaim,
4395
+ readDeliveryGap,
4396
+ unknownDetection
4397
+ };
4398
+ //# sourceMappingURL=providers.js.map