@osfactory/otel-hook 0.5.0 → 0.7.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.
- package/README.md +72 -7
- package/dist/{adapter-BS7xHKGQ.d.ts → adapter-BJiz6lqM.d.ts} +2 -2
- package/dist/cli.js +207 -34
- package/dist/cli.js.map +1 -1
- package/dist/config.d.ts +85 -1
- package/dist/config.js +135 -1
- package/dist/config.js.map +1 -1
- package/dist/{events-CzZ5kukS.d.ts → events-B3MHoJTD.d.ts} +72 -1
- package/dist/{filesystem-store-BcOveJYY.d.ts → filesystem-store-r-nNA3BA.d.ts} +1 -1
- package/dist/{hook-DxTakjAD.d.ts → hook-Dh8OO4Wa.d.ts} +4 -4
- package/dist/index.d.ts +12 -12
- package/dist/index.js +197 -31
- package/dist/index.js.map +1 -1
- package/dist/install.d.ts +4 -4
- package/dist/install.js +8 -2
- package/dist/install.js.map +1 -1
- package/dist/integration.d.ts +13 -8
- package/dist/integration.js +2273 -2256
- package/dist/integration.js.map +1 -1
- package/dist/lifecycle.d.ts +3 -3
- package/dist/lifecycle.js +761 -212
- package/dist/lifecycle.js.map +1 -1
- package/dist/{memory-DkTohdIa.d.ts → memory-Bl9ANVff.d.ts} +2 -2
- package/dist/model.d.ts +1 -1
- package/dist/model.js +13 -2
- package/dist/model.js.map +1 -1
- package/dist/{otlp-log-sink-DaZDPKnR.d.ts → otlp-log-sink-eUEjaLhk.d.ts} +3 -3
- package/dist/{payload-2lnpKodw.d.ts → payload-Ci8_ERm6.d.ts} +1 -1
- package/dist/{ports-B0rC49b3.d.ts → ports-n7KFOpKo.d.ts} +1 -1
- package/dist/providers.d.ts +10 -10
- package/dist/providers.js +32 -13
- package/dist/providers.js.map +1 -1
- package/dist/{registry-DVnPA_b6.d.ts → registry-CIVvRlVK.d.ts} +1 -1
- package/dist/runtime.d.ts +8 -8
- package/dist/runtime.js +11 -6
- package/dist/runtime.js.map +1 -1
- package/dist/{semconv-CtnDdsPk.d.ts → semconv-fPRb-dpU.d.ts} +1 -1
- package/dist/state.d.ts +4 -4
- package/dist/telemetry.d.ts +6 -6
- package/dist/telemetry.js +956 -418
- package/dist/telemetry.js.map +1 -1
- package/dist/testing.d.ts +14 -8
- package/dist/testing.js +36 -18
- package/dist/testing.js.map +1 -1
- package/package.json +1 -1
package/dist/lifecycle.js
CHANGED
|
@@ -268,20 +268,746 @@ import {
|
|
|
268
268
|
} from "@opentelemetry/semantic-conventions/incubating";
|
|
269
269
|
|
|
270
270
|
// src/version.ts
|
|
271
|
-
var VERSION = "0.
|
|
271
|
+
var VERSION = "0.7.0";
|
|
272
272
|
|
|
273
273
|
// src/telemetry/export-identity.ts
|
|
274
274
|
import { ATTR_SESSION_ID } from "@opentelemetry/semantic-conventions/incubating";
|
|
275
|
+
|
|
276
|
+
// src/model/events.ts
|
|
277
|
+
import { z as z9 } from "zod";
|
|
278
|
+
|
|
279
|
+
// src/errors/taxonomy.ts
|
|
280
|
+
import { z as z2 } from "zod";
|
|
281
|
+
var otelHookErrorCodeSchema = z2.enum([
|
|
282
|
+
/** Input was not usable at all (empty stdin, unparsable JSON). */
|
|
283
|
+
"invalid-input",
|
|
284
|
+
/** Input parsed but failed canonical schema validation. */
|
|
285
|
+
"schema-validation-failed",
|
|
286
|
+
/** No adapter claimed the input with sufficient confidence. */
|
|
287
|
+
"provider-unknown",
|
|
288
|
+
/** Several adapters claimed the input at the same confidence. */
|
|
289
|
+
"provider-detection-ambiguous",
|
|
290
|
+
/** An adapter threw or returned a malformed result. */
|
|
291
|
+
"provider-adapter-failure",
|
|
292
|
+
/** Two identity claims disagreed at equal confidence. */
|
|
293
|
+
"identity-conflict",
|
|
294
|
+
/** Required identity fields were absent. */
|
|
295
|
+
"identity-incomplete",
|
|
296
|
+
/** A usage report violated the canonical usage invariants. */
|
|
297
|
+
"usage-invalid",
|
|
298
|
+
/** The state store could not be read or written. */
|
|
299
|
+
"state-store-failure",
|
|
300
|
+
/** The telemetry sink rejected or could not deliver a batch. */
|
|
301
|
+
"telemetry-export-failure",
|
|
302
|
+
/** Content reached the sink boundary in a state the policy forbids. */
|
|
303
|
+
"privacy-policy-violation",
|
|
304
|
+
/** Configuration could not be resolved. */
|
|
305
|
+
"configuration-invalid",
|
|
306
|
+
/** A configured bound (events, batch size) dropped data. */
|
|
307
|
+
"limit-exceeded",
|
|
308
|
+
/**
|
|
309
|
+
* No replay-stable delivery identifier was available for a callback while
|
|
310
|
+
* deduplication was required.
|
|
311
|
+
*/
|
|
312
|
+
"delivery-identifier-unavailable",
|
|
313
|
+
"delivery-claim-superseded",
|
|
314
|
+
/** Anything unanticipated. Always reported, never fatal to the host. */
|
|
315
|
+
"internal-error"
|
|
316
|
+
]);
|
|
317
|
+
var errorSeveritySchema = z2.enum(["warning", "error"]);
|
|
318
|
+
var errorPhaseSchema = z2.enum([
|
|
319
|
+
"configuration",
|
|
320
|
+
"detection",
|
|
321
|
+
"identity",
|
|
322
|
+
"parsing",
|
|
323
|
+
"normalization",
|
|
324
|
+
"privacy",
|
|
325
|
+
"state",
|
|
326
|
+
"export",
|
|
327
|
+
"shutdown"
|
|
328
|
+
]);
|
|
329
|
+
var failurePostureSchema = z2.enum(["fail-open", "fail-closed-attribution"]);
|
|
330
|
+
var ERROR_TAXONOMY = Object.freeze({
|
|
331
|
+
"invalid-input": {
|
|
332
|
+
code: "invalid-input",
|
|
333
|
+
severity: "warning",
|
|
334
|
+
posture: "fail-open",
|
|
335
|
+
retryable: false,
|
|
336
|
+
summary: "Input could not be read or decoded."
|
|
337
|
+
},
|
|
338
|
+
"schema-validation-failed": {
|
|
339
|
+
code: "schema-validation-failed",
|
|
340
|
+
severity: "error",
|
|
341
|
+
posture: "fail-closed-attribution",
|
|
342
|
+
retryable: false,
|
|
343
|
+
summary: "A canonical event failed schema validation and was dropped."
|
|
344
|
+
},
|
|
345
|
+
"provider-unknown": {
|
|
346
|
+
code: "provider-unknown",
|
|
347
|
+
severity: "warning",
|
|
348
|
+
posture: "fail-closed-attribution",
|
|
349
|
+
retryable: false,
|
|
350
|
+
summary: "No adapter recognized the source provider; the input stays unattributed."
|
|
351
|
+
},
|
|
352
|
+
"provider-detection-ambiguous": {
|
|
353
|
+
code: "provider-detection-ambiguous",
|
|
354
|
+
severity: "warning",
|
|
355
|
+
posture: "fail-closed-attribution",
|
|
356
|
+
retryable: false,
|
|
357
|
+
summary: "Multiple adapters claimed the input at equal confidence."
|
|
358
|
+
},
|
|
359
|
+
"provider-adapter-failure": {
|
|
360
|
+
code: "provider-adapter-failure",
|
|
361
|
+
severity: "error",
|
|
362
|
+
posture: "fail-open",
|
|
363
|
+
retryable: false,
|
|
364
|
+
summary: "A provider adapter failed while parsing."
|
|
365
|
+
},
|
|
366
|
+
"identity-conflict": {
|
|
367
|
+
code: "identity-conflict",
|
|
368
|
+
severity: "error",
|
|
369
|
+
posture: "fail-closed-attribution",
|
|
370
|
+
retryable: false,
|
|
371
|
+
summary: "Identity claims disagreed; attribution was declined."
|
|
372
|
+
},
|
|
373
|
+
"identity-incomplete": {
|
|
374
|
+
code: "identity-incomplete",
|
|
375
|
+
severity: "warning",
|
|
376
|
+
posture: "fail-closed-attribution",
|
|
377
|
+
retryable: false,
|
|
378
|
+
summary: "Required identity fields were missing; attribution was declined."
|
|
379
|
+
},
|
|
380
|
+
"usage-invalid": {
|
|
381
|
+
code: "usage-invalid",
|
|
382
|
+
severity: "error",
|
|
383
|
+
posture: "fail-open",
|
|
384
|
+
retryable: false,
|
|
385
|
+
summary: "A usage report violated the canonical usage invariants."
|
|
386
|
+
},
|
|
387
|
+
"state-store-failure": {
|
|
388
|
+
code: "state-store-failure",
|
|
389
|
+
severity: "warning",
|
|
390
|
+
posture: "fail-open",
|
|
391
|
+
retryable: true,
|
|
392
|
+
summary: "State could not be read or written; derived values may be incomplete."
|
|
393
|
+
},
|
|
394
|
+
"telemetry-export-failure": {
|
|
395
|
+
code: "telemetry-export-failure",
|
|
396
|
+
severity: "warning",
|
|
397
|
+
posture: "fail-open",
|
|
398
|
+
retryable: true,
|
|
399
|
+
summary: "The telemetry sink could not accept a batch."
|
|
400
|
+
},
|
|
401
|
+
"privacy-policy-violation": {
|
|
402
|
+
code: "privacy-policy-violation",
|
|
403
|
+
severity: "error",
|
|
404
|
+
posture: "fail-closed-attribution",
|
|
405
|
+
retryable: false,
|
|
406
|
+
summary: "Content violated the resolved privacy policy and was dropped."
|
|
407
|
+
},
|
|
408
|
+
"configuration-invalid": {
|
|
409
|
+
code: "configuration-invalid",
|
|
410
|
+
severity: "error",
|
|
411
|
+
posture: "fail-open",
|
|
412
|
+
retryable: false,
|
|
413
|
+
summary: "Configuration could not be resolved; defaults apply."
|
|
414
|
+
},
|
|
415
|
+
"limit-exceeded": {
|
|
416
|
+
code: "limit-exceeded",
|
|
417
|
+
severity: "warning",
|
|
418
|
+
posture: "fail-open",
|
|
419
|
+
retryable: false,
|
|
420
|
+
summary: "A configured bound was reached and data was dropped."
|
|
421
|
+
},
|
|
422
|
+
"delivery-identifier-unavailable": {
|
|
423
|
+
code: "delivery-identifier-unavailable",
|
|
424
|
+
severity: "warning",
|
|
425
|
+
// Fail-open: the observation is still attributed and exported. Only the
|
|
426
|
+
// at-most-once guarantee is missing, and refusing the telemetry to protect
|
|
427
|
+
// a duplicate count would trade a certain loss for a possible one.
|
|
428
|
+
posture: "fail-open",
|
|
429
|
+
retryable: false,
|
|
430
|
+
summary: "No replay-stable delivery identifier was available; this callback was exported without deduplication."
|
|
431
|
+
},
|
|
432
|
+
"delivery-claim-superseded": {
|
|
433
|
+
code: "delivery-claim-superseded",
|
|
434
|
+
severity: "warning",
|
|
435
|
+
// Fail-open, and specifically *not* silent. A peer reclaimed this callback's
|
|
436
|
+
// claim while this process was still working on it, which means the
|
|
437
|
+
// configured stale window is shorter than this installation's real worst
|
|
438
|
+
// case. Both processes may now have exported the callback, so the
|
|
439
|
+
// at-most-once guarantee did not hold for it — the only honest response is
|
|
440
|
+
// to say so and let the operator raise the window.
|
|
441
|
+
posture: "fail-open",
|
|
442
|
+
retryable: false,
|
|
443
|
+
summary: "A delivery claim was reclaimed by another process before this one committed; the callback may have been exported twice."
|
|
444
|
+
},
|
|
445
|
+
"internal-error": {
|
|
446
|
+
code: "internal-error",
|
|
447
|
+
severity: "error",
|
|
448
|
+
posture: "fail-open",
|
|
449
|
+
retryable: false,
|
|
450
|
+
summary: "An unexpected failure was contained."
|
|
451
|
+
}
|
|
452
|
+
});
|
|
453
|
+
var attributionOutcomeSchema = z2.enum([
|
|
454
|
+
/** Identity resolved; events carry provider and session identity. */
|
|
455
|
+
"attributed",
|
|
456
|
+
/** Identity could not be established safely; nothing was attributed. */
|
|
457
|
+
"declined",
|
|
458
|
+
/** Attribution was attempted and failed unexpectedly. */
|
|
459
|
+
"failed",
|
|
460
|
+
/** Input was recognized but intentionally carried no telemetry. */
|
|
461
|
+
"not-applicable"
|
|
462
|
+
]);
|
|
463
|
+
var attributionReasonSchema = z2.enum([
|
|
464
|
+
"provider-unknown",
|
|
465
|
+
"provider-detection-ambiguous",
|
|
466
|
+
"identity-conflict",
|
|
467
|
+
"identity-incomplete",
|
|
468
|
+
"adapter-ignored-input",
|
|
469
|
+
"adapter-failure",
|
|
470
|
+
"invalid-input",
|
|
471
|
+
"internal-error"
|
|
472
|
+
]);
|
|
473
|
+
|
|
474
|
+
// src/model/content.ts
|
|
475
|
+
import { z as z3 } from "zod";
|
|
476
|
+
var contentKindSchema = z3.enum([
|
|
477
|
+
"prompt",
|
|
478
|
+
"response",
|
|
479
|
+
"reasoning",
|
|
480
|
+
"tool-input",
|
|
481
|
+
"tool-output",
|
|
482
|
+
"error-message",
|
|
483
|
+
"system-instruction",
|
|
484
|
+
"attachment"
|
|
485
|
+
]);
|
|
486
|
+
var contentRoleSchema = z3.enum(["user", "assistant", "system", "tool", "unknown"]);
|
|
487
|
+
var contentDisclosureSchema = z3.enum(["omitted", "masked", "redacted", "raw"]);
|
|
488
|
+
var CONTENT_HASH_PATTERN = /^sha256:[0-9a-f]{64}$/;
|
|
489
|
+
var contentFactSchema = z3.strictObject({
|
|
490
|
+
kind: contentKindSchema,
|
|
491
|
+
role: contentRoleSchema.optional(),
|
|
492
|
+
/** Unicode code point count of the original content. */
|
|
493
|
+
characterLength: z3.number().int().min(0),
|
|
494
|
+
/** UTF-8 byte length of the original content. */
|
|
495
|
+
byteLength: z3.number().int().min(0),
|
|
496
|
+
/** Stable salted digest of the original content. */
|
|
497
|
+
contentHash: z3.string().regex(CONTENT_HASH_PATTERN),
|
|
498
|
+
disclosure: contentDisclosureSchema,
|
|
499
|
+
/** Disclosed text, bounded by the privacy policy. Absent when omitted. */
|
|
500
|
+
text: z3.string().optional(),
|
|
501
|
+
/** True when `text` was cut short by the configured string bound. */
|
|
502
|
+
truncated: z3.boolean(),
|
|
503
|
+
/** Number of secret-looking spans replaced while producing `text`. */
|
|
504
|
+
secretsRedacted: z3.number().int().min(0),
|
|
505
|
+
/** Optional non-sensitive label, e.g. a MIME type or tool name. */
|
|
506
|
+
label: nonEmptyStringSchema.optional()
|
|
507
|
+
});
|
|
508
|
+
var contentFactsSchema = z3.array(contentFactSchema).max(64);
|
|
509
|
+
|
|
510
|
+
// src/model/extensions.ts
|
|
511
|
+
import { z as z4 } from "zod";
|
|
512
|
+
var EXTENSION_KEY_PATTERN = /^[a-z][a-z0-9]*(?:[-_][a-z0-9]+)*(?:\.[a-z][a-z0-9]*(?:[-_][a-z0-9]+)*)+$/;
|
|
513
|
+
var RESERVED_EXTENSION_NAMESPACES = Object.freeze([
|
|
514
|
+
"otelhook",
|
|
515
|
+
"otel",
|
|
516
|
+
"telemetry"
|
|
517
|
+
]);
|
|
518
|
+
var MAX_EXTENSION_ENTRIES = 64;
|
|
519
|
+
var extensionKeyNamespace = (key) => key.slice(0, key.indexOf("."));
|
|
520
|
+
var isReservedExtensionNamespace = (key) => RESERVED_EXTENSION_NAMESPACES.includes(extensionKeyNamespace(key));
|
|
521
|
+
var extensionsSchema = z4.record(z4.string(), attributeValueSchema).check((ctx) => {
|
|
522
|
+
const keys = Object.keys(ctx.value);
|
|
523
|
+
if (keys.length > MAX_EXTENSION_ENTRIES) {
|
|
524
|
+
ctx.issues.push({
|
|
525
|
+
code: "custom",
|
|
526
|
+
input: ctx.value,
|
|
527
|
+
message: `extensions may contain at most ${MAX_EXTENSION_ENTRIES} entries`
|
|
528
|
+
});
|
|
529
|
+
}
|
|
530
|
+
for (const key of keys) {
|
|
531
|
+
if (!EXTENSION_KEY_PATTERN.test(key)) {
|
|
532
|
+
ctx.issues.push({
|
|
533
|
+
code: "custom",
|
|
534
|
+
input: ctx.value,
|
|
535
|
+
path: [key],
|
|
536
|
+
message: `extension key ${JSON.stringify(key)} must be namespaced, e.g. "acme.tier"`
|
|
537
|
+
});
|
|
538
|
+
continue;
|
|
539
|
+
}
|
|
540
|
+
if (isReservedExtensionNamespace(key)) {
|
|
541
|
+
ctx.issues.push({
|
|
542
|
+
code: "custom",
|
|
543
|
+
input: ctx.value,
|
|
544
|
+
path: [key],
|
|
545
|
+
message: `extension namespace ${JSON.stringify(extensionKeyNamespace(key))} is reserved`
|
|
546
|
+
});
|
|
547
|
+
}
|
|
548
|
+
}
|
|
549
|
+
});
|
|
550
|
+
var EMPTY_EXTENSIONS = Object.freeze({});
|
|
551
|
+
var emptyExtensions = () => ({});
|
|
552
|
+
|
|
553
|
+
// src/model/identity.ts
|
|
554
|
+
import { z as z5 } from "zod";
|
|
555
|
+
var workspaceKeySourceSchema = z5.enum([
|
|
556
|
+
"git-remote",
|
|
557
|
+
"git-root",
|
|
558
|
+
"working-directory",
|
|
559
|
+
"explicit",
|
|
560
|
+
"unknown"
|
|
561
|
+
]);
|
|
562
|
+
var workspaceIdentitySchema = z5.strictObject({
|
|
563
|
+
workspaceId: workspaceIdSchema,
|
|
564
|
+
keySource: workspaceKeySourceSchema,
|
|
565
|
+
/** Repository name only; never an owner path or URL with credentials. */
|
|
566
|
+
repositoryName: nonEmptyStringSchema.optional(),
|
|
567
|
+
vcsBranchName: nonEmptyStringSchema.optional(),
|
|
568
|
+
/** Opaque handle for the checked-out revision. */
|
|
569
|
+
vcsRevisionId: nonEmptyStringSchema.optional()
|
|
570
|
+
}).readonly();
|
|
571
|
+
var sourceProvenanceSchema = z5.strictObject({
|
|
572
|
+
providerId: resolvedProviderIdSchema,
|
|
573
|
+
providerVersion: nonEmptyStringSchema.optional(),
|
|
574
|
+
adapterId: nonEmptyStringSchema,
|
|
575
|
+
adapterVersion: nonEmptyStringSchema,
|
|
576
|
+
detectionConfidence: detectionConfidenceSchema,
|
|
577
|
+
/** The provider's own name for the source event, e.g. a hook event name. */
|
|
578
|
+
sourceEventName: nonEmptyStringSchema.optional(),
|
|
579
|
+
transport: sourceTransportSchema
|
|
580
|
+
}).readonly();
|
|
581
|
+
var consumerAttributesSchema = attributesSchema.readonly();
|
|
582
|
+
var invocationIdentitySchema = z5.strictObject({
|
|
583
|
+
invocationId: invocationIdSchema,
|
|
584
|
+
sessionId: sessionIdSchema,
|
|
585
|
+
/** Set when this invocation runs beneath another agent invocation. */
|
|
586
|
+
parentInvocationId: invocationIdSchema.optional(),
|
|
587
|
+
/** Root of the session tree when the provider exposes one. */
|
|
588
|
+
rootSessionId: sessionIdSchema.optional(),
|
|
589
|
+
/** Stable handle for the agent process/instance, when available. */
|
|
590
|
+
agentInstanceId: nonEmptyStringSchema.optional(),
|
|
591
|
+
provenance: sourceProvenanceSchema,
|
|
592
|
+
workspace: workspaceIdentitySchema,
|
|
593
|
+
startedAt: epochMillisSchema,
|
|
594
|
+
consumerAttributes: consumerAttributesSchema
|
|
595
|
+
}).readonly();
|
|
596
|
+
var identityClaimFieldsSchema = z5.strictObject({
|
|
597
|
+
invocationId: invocationIdSchema.optional(),
|
|
598
|
+
sessionId: sessionIdSchema.optional(),
|
|
599
|
+
parentInvocationId: invocationIdSchema.optional(),
|
|
600
|
+
rootSessionId: sessionIdSchema.optional(),
|
|
601
|
+
agentInstanceId: nonEmptyStringSchema.optional(),
|
|
602
|
+
workspace: workspaceIdentitySchema.optional(),
|
|
603
|
+
startedAt: epochMillisSchema.optional()
|
|
604
|
+
});
|
|
605
|
+
var identityClaimSchema = z5.strictObject({
|
|
606
|
+
/** Non-sensitive label, e.g. `adapter:acme-cli` or `env:OTEL_HOOK_SESSION_ID`. */
|
|
607
|
+
source: nonEmptyStringSchema,
|
|
608
|
+
confidence: detectionConfidenceSchema,
|
|
609
|
+
fields: identityClaimFieldsSchema
|
|
610
|
+
});
|
|
611
|
+
|
|
612
|
+
// src/model/target.ts
|
|
613
|
+
import { z as z6 } from "zod";
|
|
614
|
+
var targetSourceSchema = z6.enum(["tool-path", "shell-cwd", "session-cwd"]);
|
|
615
|
+
var MAX_TARGET_HINT_PATHS = 8;
|
|
616
|
+
var MAX_TARGET_PATH_LENGTH = 4096;
|
|
617
|
+
var localPathSchema = z6.string().min(1).max(MAX_TARGET_PATH_LENGTH).refine((value) => !value.includes("\0"), "path must not contain NUL");
|
|
618
|
+
var targetHintSchema = z6.strictObject({
|
|
619
|
+
source: targetSourceSchema,
|
|
620
|
+
paths: z6.array(localPathSchema).min(1).max(MAX_TARGET_HINT_PATHS).readonly(),
|
|
621
|
+
/** Absolute directory that relative `paths` resolve against. */
|
|
622
|
+
baseDirectory: localPathSchema.optional()
|
|
623
|
+
}).readonly();
|
|
624
|
+
var worktreeKindSchema = z6.enum(["main", "linked"]);
|
|
625
|
+
var workspaceTargetSchema = z6.strictObject({
|
|
626
|
+
workspaceId: workspaceIdSchema,
|
|
627
|
+
/** Branch checked out in that worktree; absent on a detached HEAD. */
|
|
628
|
+
vcsBranchName: nonEmptyStringSchema.optional(),
|
|
629
|
+
source: targetSourceSchema,
|
|
630
|
+
/** `git-root` handle of the repository's main worktree; absent when there is none to name. */
|
|
631
|
+
repositoryId: workspaceIdSchema.optional(),
|
|
632
|
+
worktreeKind: worktreeKindSchema.optional()
|
|
633
|
+
}).readonly();
|
|
634
|
+
var SUBAGENT_ID_PATTERN = /^[A-Za-z0-9_.:@+=-]{1,256}$/;
|
|
635
|
+
var subagentIdSchema = z6.string().regex(SUBAGENT_ID_PATTERN);
|
|
636
|
+
|
|
637
|
+
// src/model/usage.ts
|
|
638
|
+
import { z as z7 } from "zod";
|
|
639
|
+
var usageTemporalitySchema = z7.enum(["delta", "cumulative"]);
|
|
640
|
+
var cacheCreationAccountingSchema = z7.enum([
|
|
641
|
+
"included-in-input",
|
|
642
|
+
"disjoint-from-input",
|
|
643
|
+
"not-reported"
|
|
644
|
+
]);
|
|
645
|
+
var providerTotalAgreementSchema = z7.enum(["unreported", "agrees", "disagrees"]);
|
|
646
|
+
var usageReportSchema = z7.strictObject({
|
|
647
|
+
temporality: usageTemporalitySchema,
|
|
648
|
+
/** Inclusive input tokens. */
|
|
649
|
+
inputTokens: tokenCountSchema.optional(),
|
|
650
|
+
/** Subset of `inputTokens` served from a prompt cache. */
|
|
651
|
+
cachedInputTokens: tokenCountSchema.optional(),
|
|
652
|
+
/** Tokens written to a prompt cache. */
|
|
653
|
+
cacheCreationInputTokens: tokenCountSchema.optional(),
|
|
654
|
+
/** Required when `cacheCreationInputTokens` is present and non-zero. */
|
|
655
|
+
cacheCreationAccounting: cacheCreationAccountingSchema.optional(),
|
|
656
|
+
/** Inclusive output tokens. */
|
|
657
|
+
outputTokens: tokenCountSchema.optional(),
|
|
658
|
+
/** Subset of `outputTokens` spent on reasoning. */
|
|
659
|
+
reasoningOutputTokens: tokenCountSchema.optional(),
|
|
660
|
+
/** Total exactly as the provider reported it, if it reported one. */
|
|
661
|
+
providerTotalTokens: tokenCountSchema.optional()
|
|
662
|
+
});
|
|
663
|
+
var canonicalUsageSchema = z7.strictObject({
|
|
664
|
+
temporality: usageTemporalitySchema,
|
|
665
|
+
inputTokens: tokenCountSchema,
|
|
666
|
+
cachedInputTokens: tokenCountSchema,
|
|
667
|
+
cacheCreationInputTokens: tokenCountSchema,
|
|
668
|
+
cacheCreationAccounting: cacheCreationAccountingSchema,
|
|
669
|
+
outputTokens: tokenCountSchema,
|
|
670
|
+
reasoningOutputTokens: tokenCountSchema,
|
|
671
|
+
/** Derived: input tokens that were neither cache reads nor cache writes. */
|
|
672
|
+
uncachedInputTokens: tokenCountSchema,
|
|
673
|
+
/** Derived: canonical billable total. */
|
|
674
|
+
totalTokens: tokenCountSchema,
|
|
675
|
+
providerTotalTokens: tokenCountSchema.optional(),
|
|
676
|
+
providerTotalAgreement: providerTotalAgreementSchema
|
|
677
|
+
}).check((ctx) => {
|
|
678
|
+
const usage = ctx.value;
|
|
679
|
+
const push = (message) => {
|
|
680
|
+
ctx.issues.push({ code: "custom", input: usage, message });
|
|
681
|
+
};
|
|
682
|
+
if (usage.cachedInputTokens > usage.inputTokens) {
|
|
683
|
+
push("cachedInputTokens must not exceed inputTokens (it is a subset)");
|
|
684
|
+
}
|
|
685
|
+
if (usage.reasoningOutputTokens > usage.outputTokens) {
|
|
686
|
+
push("reasoningOutputTokens must not exceed outputTokens (it is a subset)");
|
|
687
|
+
}
|
|
688
|
+
if (usage.cacheCreationAccounting === "not-reported" && usage.cacheCreationInputTokens !== 0) {
|
|
689
|
+
push("cacheCreationInputTokens must be 0 when cacheCreationAccounting is not-reported");
|
|
690
|
+
}
|
|
691
|
+
const creationInsideInput = usage.cacheCreationAccounting === "included-in-input" ? usage.cacheCreationInputTokens : 0;
|
|
692
|
+
if (usage.cachedInputTokens + creationInsideInput > usage.inputTokens) {
|
|
693
|
+
push(
|
|
694
|
+
"cachedInputTokens + cacheCreationInputTokens must not exceed inputTokens when cache creation is included in input"
|
|
695
|
+
);
|
|
696
|
+
}
|
|
697
|
+
const expectedUncached = usage.inputTokens - usage.cachedInputTokens - creationInsideInput;
|
|
698
|
+
if (expectedUncached >= 0 && usage.uncachedInputTokens !== expectedUncached) {
|
|
699
|
+
push(`uncachedInputTokens must equal ${expectedUncached}`);
|
|
700
|
+
}
|
|
701
|
+
const creationOutsideInput = usage.cacheCreationAccounting === "disjoint-from-input" ? usage.cacheCreationInputTokens : 0;
|
|
702
|
+
const expectedTotal = usage.inputTokens + creationOutsideInput + usage.outputTokens;
|
|
703
|
+
if (usage.totalTokens !== expectedTotal) {
|
|
704
|
+
push(`totalTokens must equal ${expectedTotal}`);
|
|
705
|
+
}
|
|
706
|
+
const expectedAgreement = usage.providerTotalTokens === void 0 ? "unreported" : usage.providerTotalTokens === expectedTotal ? "agrees" : "disagrees";
|
|
707
|
+
if (usage.providerTotalAgreement !== expectedAgreement) {
|
|
708
|
+
push(`providerTotalAgreement must be ${expectedAgreement}`);
|
|
709
|
+
}
|
|
710
|
+
});
|
|
711
|
+
var normalizeUsage = (report) => {
|
|
712
|
+
const parsed = usageReportSchema.safeParse(report);
|
|
713
|
+
if (!parsed.success) {
|
|
714
|
+
return {
|
|
715
|
+
status: "invalid",
|
|
716
|
+
issues: parsed.error.issues.map((issue) => ({
|
|
717
|
+
code: "invalid-report",
|
|
718
|
+
message: `${issue.path.join(".") || "<root>"}: ${issue.message}`
|
|
719
|
+
}))
|
|
720
|
+
};
|
|
721
|
+
}
|
|
722
|
+
const input = parsed.data;
|
|
723
|
+
const issues = [];
|
|
724
|
+
const notes = [];
|
|
725
|
+
const inputTokens = input.inputTokens ?? 0;
|
|
726
|
+
const cachedInputTokens = input.cachedInputTokens ?? 0;
|
|
727
|
+
const cacheCreationInputTokens = input.cacheCreationInputTokens ?? 0;
|
|
728
|
+
const outputTokens = input.outputTokens ?? 0;
|
|
729
|
+
const reasoningOutputTokens = input.reasoningOutputTokens ?? 0;
|
|
730
|
+
let accounting;
|
|
731
|
+
if (cacheCreationInputTokens === 0) {
|
|
732
|
+
accounting = input.cacheCreationAccounting ?? "not-reported";
|
|
733
|
+
if (accounting !== "not-reported") {
|
|
734
|
+
notes.push(
|
|
735
|
+
`cacheCreationAccounting=${accounting} retained with zero cache-creation tokens`
|
|
736
|
+
);
|
|
737
|
+
}
|
|
738
|
+
} else if (input.cacheCreationAccounting === void 0) {
|
|
739
|
+
issues.push({
|
|
740
|
+
code: "cache-creation-accounting-missing",
|
|
741
|
+
message: "cacheCreationAccounting is required when cacheCreationInputTokens is non-zero; it cannot be inferred"
|
|
742
|
+
});
|
|
743
|
+
accounting = "not-reported";
|
|
744
|
+
} else if (input.cacheCreationAccounting === "not-reported") {
|
|
745
|
+
issues.push({
|
|
746
|
+
code: "cache-creation-accounting-missing",
|
|
747
|
+
message: "cacheCreationAccounting=not-reported conflicts with non-zero cacheCreationInputTokens"
|
|
748
|
+
});
|
|
749
|
+
accounting = "not-reported";
|
|
750
|
+
} else {
|
|
751
|
+
accounting = input.cacheCreationAccounting;
|
|
752
|
+
}
|
|
753
|
+
if (cachedInputTokens > inputTokens) {
|
|
754
|
+
issues.push({
|
|
755
|
+
code: "cached-exceeds-input",
|
|
756
|
+
message: `cachedInputTokens (${cachedInputTokens}) exceeds inclusive inputTokens (${inputTokens})`
|
|
757
|
+
});
|
|
758
|
+
}
|
|
759
|
+
if (reasoningOutputTokens > outputTokens) {
|
|
760
|
+
issues.push({
|
|
761
|
+
code: "reasoning-exceeds-output",
|
|
762
|
+
message: `reasoningOutputTokens (${reasoningOutputTokens}) exceeds inclusive outputTokens (${outputTokens})`
|
|
763
|
+
});
|
|
764
|
+
}
|
|
765
|
+
const creationInsideInput = accounting === "included-in-input" ? cacheCreationInputTokens : 0;
|
|
766
|
+
if (cachedInputTokens + creationInsideInput > inputTokens) {
|
|
767
|
+
issues.push({
|
|
768
|
+
code: "cache-creation-exceeds-input",
|
|
769
|
+
message: `cachedInputTokens + cacheCreationInputTokens (${cachedInputTokens + creationInsideInput}) exceeds inclusive inputTokens (${inputTokens})`
|
|
770
|
+
});
|
|
771
|
+
}
|
|
772
|
+
if (issues.length > 0) {
|
|
773
|
+
return { status: "invalid", issues };
|
|
774
|
+
}
|
|
775
|
+
const creationOutsideInput = accounting === "disjoint-from-input" ? cacheCreationInputTokens : 0;
|
|
776
|
+
const totalTokens = inputTokens + creationOutsideInput + outputTokens;
|
|
777
|
+
const providerTotalAgreement = input.providerTotalTokens === void 0 ? "unreported" : input.providerTotalTokens === totalTokens ? "agrees" : "disagrees";
|
|
778
|
+
if (providerTotalAgreement === "disagrees") {
|
|
779
|
+
notes.push(
|
|
780
|
+
`providerTotalTokens (${input.providerTotalTokens ?? 0}) disagrees with canonical total (${totalTokens}); both retained`
|
|
781
|
+
);
|
|
782
|
+
}
|
|
783
|
+
const usage = {
|
|
784
|
+
temporality: input.temporality,
|
|
785
|
+
inputTokens,
|
|
786
|
+
cachedInputTokens,
|
|
787
|
+
cacheCreationInputTokens,
|
|
788
|
+
cacheCreationAccounting: accounting,
|
|
789
|
+
outputTokens,
|
|
790
|
+
reasoningOutputTokens,
|
|
791
|
+
uncachedInputTokens: inputTokens - cachedInputTokens - creationInsideInput,
|
|
792
|
+
totalTokens,
|
|
793
|
+
...input.providerTotalTokens === void 0 ? {} : { providerTotalTokens: input.providerTotalTokens },
|
|
794
|
+
providerTotalAgreement
|
|
795
|
+
};
|
|
796
|
+
return { status: "ok", usage, notes };
|
|
797
|
+
};
|
|
798
|
+
var UsageNormalizationError = class extends Error {
|
|
799
|
+
issues;
|
|
800
|
+
constructor(issues) {
|
|
801
|
+
super(`invalid usage report: ${issues.map((issue) => issue.message).join("; ")}`);
|
|
802
|
+
this.name = "UsageNormalizationError";
|
|
803
|
+
this.issues = issues;
|
|
804
|
+
}
|
|
805
|
+
};
|
|
806
|
+
var normalizeUsageOrThrow = (report) => {
|
|
807
|
+
const result = normalizeUsage(report);
|
|
808
|
+
if (result.status === "invalid") {
|
|
809
|
+
throw new UsageNormalizationError(result.issues);
|
|
810
|
+
}
|
|
811
|
+
return result.usage;
|
|
812
|
+
};
|
|
813
|
+
var EMPTY_DELTA_USAGE = Object.freeze(
|
|
814
|
+
normalizeUsageOrThrow({ temporality: "delta" })
|
|
815
|
+
);
|
|
816
|
+
|
|
817
|
+
// src/model/version.ts
|
|
818
|
+
import { z as z8 } from "zod";
|
|
819
|
+
var CANONICAL_SCHEMA_VERSION = 1;
|
|
820
|
+
var canonicalSchemaVersionSchema = z8.literal(CANONICAL_SCHEMA_VERSION);
|
|
821
|
+
|
|
822
|
+
// src/model/events.ts
|
|
823
|
+
var modelDescriptorSchema = z9.strictObject({
|
|
824
|
+
modelId: nonEmptyStringSchema,
|
|
825
|
+
/** Vendor of the model, e.g. `anthropic`. Distinct from the agent provider. */
|
|
826
|
+
vendor: nonEmptyStringSchema.optional(),
|
|
827
|
+
family: nonEmptyStringSchema.optional()
|
|
828
|
+
});
|
|
829
|
+
var costFactsSchema = z9.strictObject({
|
|
830
|
+
/** ISO 4217 code. */
|
|
831
|
+
currency: z9.string().length(3),
|
|
832
|
+
amount: z9.number().min(0).finite(),
|
|
833
|
+
source: z9.enum(["provider-reported", "computed"])
|
|
834
|
+
});
|
|
835
|
+
var canonicalEventTypeSchema = z9.enum([
|
|
836
|
+
"session.start",
|
|
837
|
+
"session.end",
|
|
838
|
+
"prompt.submitted",
|
|
839
|
+
"generation.start",
|
|
840
|
+
"generation.end",
|
|
841
|
+
"tool.start",
|
|
842
|
+
"tool.end",
|
|
843
|
+
"subagent.start",
|
|
844
|
+
"subagent.end",
|
|
845
|
+
"compaction.performed",
|
|
846
|
+
"error.raised"
|
|
847
|
+
]);
|
|
848
|
+
var CANONICAL_EVENT_TYPES = canonicalEventTypeSchema.options;
|
|
849
|
+
var outcomeSchema = z9.enum(["ok", "error", "cancelled", "timeout", "denied", "unknown"]);
|
|
850
|
+
var baseEventFields = {
|
|
851
|
+
schemaVersion: canonicalSchemaVersionSchema,
|
|
852
|
+
eventId: eventIdSchema,
|
|
853
|
+
invocationId: invocationIdSchema,
|
|
854
|
+
sessionId: sessionIdSchema,
|
|
855
|
+
/** Per-invocation ordering key. Stable across replays of the same input. */
|
|
856
|
+
sequence: sequenceNumberSchema,
|
|
857
|
+
occurredAt: epochMillisSchema,
|
|
858
|
+
provenance: sourceProvenanceSchema,
|
|
859
|
+
workspace: workspaceIdentitySchema,
|
|
860
|
+
/**
|
|
861
|
+
* The provider's own id for the subagent this event was emitted inside (e.g.
|
|
862
|
+
* Claude Code's `agent_id`). Absent for the top-level agent. Set by the event
|
|
863
|
+
* factory, never by hand.
|
|
864
|
+
*/
|
|
865
|
+
subagentId: subagentIdSchema.optional(),
|
|
866
|
+
extensions: extensionsSchema.default(emptyExtensions)
|
|
867
|
+
};
|
|
868
|
+
var event = (shape) => z9.strictObject({ ...baseEventFields, ...shape });
|
|
869
|
+
var sessionStartEventSchema = event({
|
|
870
|
+
type: z9.literal("session.start"),
|
|
871
|
+
sessionKind: z9.enum(["interactive", "non-interactive", "unknown"]),
|
|
872
|
+
agentName: nonEmptyStringSchema.optional(),
|
|
873
|
+
agentVersion: nonEmptyStringSchema.optional(),
|
|
874
|
+
model: modelDescriptorSchema.optional(),
|
|
875
|
+
/** The git worktree the session runs in, resolved by the core (ADR 0008). */
|
|
876
|
+
target: workspaceTargetSchema.optional()
|
|
877
|
+
});
|
|
878
|
+
var sessionEndEventSchema = event({
|
|
879
|
+
type: z9.literal("session.end"),
|
|
880
|
+
reason: z9.enum(["completed", "aborted", "error", "timeout", "unknown"]),
|
|
881
|
+
durationMillis: durationMillisSchema.optional(),
|
|
882
|
+
/** Session totals, typically cumulative. */
|
|
883
|
+
usage: canonicalUsageSchema.optional(),
|
|
884
|
+
cost: costFactsSchema.optional()
|
|
885
|
+
});
|
|
886
|
+
var promptSubmittedEventSchema = event({
|
|
887
|
+
type: z9.literal("prompt.submitted"),
|
|
888
|
+
promptSource: z9.enum(["user", "automation", "resumed", "unknown"]),
|
|
889
|
+
content: contentFactSchema.optional(),
|
|
890
|
+
turnIndex: z9.number().int().min(0).optional(),
|
|
891
|
+
/** The git worktree the session runs in, resolved by the core (ADR 0008). */
|
|
892
|
+
target: workspaceTargetSchema.optional()
|
|
893
|
+
});
|
|
894
|
+
var generationStartEventSchema = event({
|
|
895
|
+
type: z9.literal("generation.start"),
|
|
896
|
+
generationId: nonEmptyStringSchema,
|
|
897
|
+
model: modelDescriptorSchema,
|
|
898
|
+
requestedMaxOutputTokens: tokenCountSchema.optional(),
|
|
899
|
+
inputContent: contentFactsSchema.optional()
|
|
900
|
+
});
|
|
901
|
+
var generationEndEventSchema = event({
|
|
902
|
+
type: z9.literal("generation.end"),
|
|
903
|
+
generationId: nonEmptyStringSchema,
|
|
904
|
+
model: modelDescriptorSchema,
|
|
905
|
+
outcome: outcomeSchema,
|
|
906
|
+
stopReason: nonEmptyStringSchema.optional(),
|
|
907
|
+
durationMillis: durationMillisSchema.optional(),
|
|
908
|
+
usage: canonicalUsageSchema.optional(),
|
|
909
|
+
cost: costFactsSchema.optional(),
|
|
910
|
+
outputContent: contentFactsSchema.optional()
|
|
911
|
+
});
|
|
912
|
+
var toolKindSchema = z9.enum([
|
|
913
|
+
"read",
|
|
914
|
+
"write",
|
|
915
|
+
"execute",
|
|
916
|
+
"search",
|
|
917
|
+
"network",
|
|
918
|
+
"delegate",
|
|
919
|
+
"other",
|
|
920
|
+
"unknown"
|
|
921
|
+
]);
|
|
922
|
+
var toolStartEventSchema = event({
|
|
923
|
+
type: z9.literal("tool.start"),
|
|
924
|
+
toolCallId: nonEmptyStringSchema,
|
|
925
|
+
toolName: nonEmptyStringSchema,
|
|
926
|
+
toolKind: toolKindSchema,
|
|
927
|
+
generationId: nonEmptyStringSchema.optional(),
|
|
928
|
+
input: contentFactSchema.optional(),
|
|
929
|
+
/** The git worktree this call targeted, resolved by the core (ADR 0008). */
|
|
930
|
+
target: workspaceTargetSchema.optional()
|
|
931
|
+
});
|
|
932
|
+
var toolEndEventSchema = event({
|
|
933
|
+
type: z9.literal("tool.end"),
|
|
934
|
+
toolCallId: nonEmptyStringSchema,
|
|
935
|
+
toolName: nonEmptyStringSchema,
|
|
936
|
+
outcome: outcomeSchema,
|
|
937
|
+
durationMillis: durationMillisSchema.optional(),
|
|
938
|
+
/** Present when the host asked for or recorded a permission decision. */
|
|
939
|
+
permissionDecision: z9.enum(["allowed", "denied", "deferred", "not-required"]).optional(),
|
|
940
|
+
output: contentFactSchema.optional(),
|
|
941
|
+
/** The git worktree this call targeted, resolved by the core (ADR 0008). */
|
|
942
|
+
target: workspaceTargetSchema.optional()
|
|
943
|
+
});
|
|
944
|
+
var subagentStartEventSchema = event({
|
|
945
|
+
type: z9.literal("subagent.start"),
|
|
946
|
+
subagentInvocationId: invocationIdSchema,
|
|
947
|
+
subagentType: nonEmptyStringSchema.optional(),
|
|
948
|
+
/** 0 for the top-level agent; 1 for its direct children. */
|
|
949
|
+
delegationDepth: z9.number().int().min(0).max(64),
|
|
950
|
+
model: modelDescriptorSchema.optional()
|
|
951
|
+
});
|
|
952
|
+
var subagentEndEventSchema = event({
|
|
953
|
+
type: z9.literal("subagent.end"),
|
|
954
|
+
subagentInvocationId: invocationIdSchema,
|
|
955
|
+
outcome: outcomeSchema,
|
|
956
|
+
durationMillis: durationMillisSchema.optional(),
|
|
957
|
+
usage: canonicalUsageSchema.optional()
|
|
958
|
+
});
|
|
959
|
+
var compactionPerformedEventSchema = event({
|
|
960
|
+
type: z9.literal("compaction.performed"),
|
|
961
|
+
trigger: z9.enum(["automatic", "manual", "unknown"]),
|
|
962
|
+
/** Provider-reported context size before and after compaction, if known. */
|
|
963
|
+
contextTokensBefore: tokenCountSchema.optional(),
|
|
964
|
+
contextTokensAfter: tokenCountSchema.optional(),
|
|
965
|
+
droppedMessageCount: z9.number().int().min(0).optional(),
|
|
966
|
+
usage: canonicalUsageSchema.optional()
|
|
967
|
+
});
|
|
968
|
+
var errorRaisedEventSchema = event({
|
|
969
|
+
type: z9.literal("error.raised"),
|
|
970
|
+
errorCode: otelHookErrorCodeSchema,
|
|
971
|
+
severity: errorSeveritySchema,
|
|
972
|
+
phase: errorPhaseSchema,
|
|
973
|
+
retryable: z9.boolean(),
|
|
974
|
+
/** Error text is content: it is described, never embedded verbatim by default. */
|
|
975
|
+
message: contentFactSchema.optional(),
|
|
976
|
+
/** Non-sensitive, provider-agnostic short label. */
|
|
977
|
+
detail: nonEmptyStringSchema.optional()
|
|
978
|
+
});
|
|
979
|
+
var canonicalEventSchema = z9.discriminatedUnion("type", [
|
|
980
|
+
sessionStartEventSchema,
|
|
981
|
+
sessionEndEventSchema,
|
|
982
|
+
promptSubmittedEventSchema,
|
|
983
|
+
generationStartEventSchema,
|
|
984
|
+
generationEndEventSchema,
|
|
985
|
+
toolStartEventSchema,
|
|
986
|
+
toolEndEventSchema,
|
|
987
|
+
subagentStartEventSchema,
|
|
988
|
+
subagentEndEventSchema,
|
|
989
|
+
compactionPerformedEventSchema,
|
|
990
|
+
errorRaisedEventSchema
|
|
991
|
+
]);
|
|
992
|
+
var TARGETED_EVENT_TYPES = ["session.start", "prompt.submitted", "tool.start", "tool.end"];
|
|
993
|
+
var TARGETED = new Set(TARGETED_EVENT_TYPES);
|
|
994
|
+
var isTargetedEvent = (event2) => TARGETED.has(event2.type);
|
|
995
|
+
|
|
996
|
+
// src/telemetry/export-identity.ts
|
|
997
|
+
var EXTERNAL_SESSION_KEY_ATTRIBUTES = Object.freeze([
|
|
998
|
+
ATTR_SESSION_ID,
|
|
999
|
+
"har.session_key"
|
|
1000
|
+
]);
|
|
275
1001
|
var ATTR_VCS_REF_HEAD_NAME = "vcs.ref.head.name";
|
|
276
1002
|
var ATTR_OTELHOOK_TARGET_WORKSPACE_ID = "otelhook.target.workspace.id";
|
|
277
1003
|
var ATTR_OTELHOOK_TARGET_SOURCE = "otelhook.target.source";
|
|
278
1004
|
var ATTR_OTELHOOK_TARGET_REPOSITORY_ID = "otelhook.target.repository.id";
|
|
279
1005
|
var ATTR_OTELHOOK_TARGET_WORKTREE_KIND = "otelhook.target.worktree.kind";
|
|
280
|
-
var targetAttributes = (
|
|
281
|
-
if (
|
|
1006
|
+
var targetAttributes = (event2) => {
|
|
1007
|
+
if (!isTargetedEvent(event2) || event2.target === void 0) {
|
|
282
1008
|
return {};
|
|
283
1009
|
}
|
|
284
|
-
const { target } =
|
|
1010
|
+
const { target } = event2;
|
|
285
1011
|
return {
|
|
286
1012
|
[ATTR_OTELHOOK_TARGET_WORKSPACE_ID]: target.workspaceId,
|
|
287
1013
|
[ATTR_OTELHOOK_TARGET_SOURCE]: target.source,
|
|
@@ -320,57 +1046,60 @@ var familyOf = (type) => {
|
|
|
320
1046
|
return void 0;
|
|
321
1047
|
}
|
|
322
1048
|
};
|
|
323
|
-
var spanScopeRefOf = (
|
|
324
|
-
const family = familyOf(
|
|
1049
|
+
var spanScopeRefOf = (event2) => {
|
|
1050
|
+
const family = familyOf(event2.type);
|
|
325
1051
|
if (family === void 0) {
|
|
326
1052
|
return void 0;
|
|
327
1053
|
}
|
|
328
|
-
switch (
|
|
1054
|
+
switch (event2.type) {
|
|
329
1055
|
case "session.start":
|
|
330
1056
|
case "session.end":
|
|
331
|
-
return { family, scopeKey:
|
|
1057
|
+
return { family, scopeKey: event2.sessionId };
|
|
332
1058
|
case "generation.start":
|
|
333
1059
|
case "generation.end":
|
|
334
|
-
return { family, scopeKey:
|
|
1060
|
+
return { family, scopeKey: event2.generationId };
|
|
335
1061
|
case "tool.start":
|
|
336
1062
|
case "tool.end":
|
|
337
|
-
return { family, scopeKey:
|
|
1063
|
+
return { family, scopeKey: event2.toolCallId };
|
|
338
1064
|
case "subagent.start":
|
|
339
1065
|
case "subagent.end":
|
|
340
|
-
return { family, scopeKey:
|
|
1066
|
+
return { family, scopeKey: event2.subagentInvocationId };
|
|
341
1067
|
default:
|
|
342
1068
|
return void 0;
|
|
343
1069
|
}
|
|
344
1070
|
};
|
|
345
|
-
var parentScopeRefOf = (
|
|
346
|
-
if (
|
|
1071
|
+
var parentScopeRefOf = (event2) => {
|
|
1072
|
+
if (event2.type === "session.start" || event2.type === "session.end") {
|
|
347
1073
|
return void 0;
|
|
348
1074
|
}
|
|
349
|
-
if (
|
|
350
|
-
return { family: "generation", scopeKey:
|
|
1075
|
+
if (event2.type === "tool.start" && event2.generationId !== void 0) {
|
|
1076
|
+
return { family: "generation", scopeKey: event2.generationId };
|
|
351
1077
|
}
|
|
352
|
-
return { family: "session", scopeKey:
|
|
1078
|
+
return { family: "session", scopeKey: event2.sessionId };
|
|
353
1079
|
};
|
|
354
|
-
var startOnlySpanAttributes = (
|
|
355
|
-
switch (
|
|
1080
|
+
var startOnlySpanAttributes = (event2) => {
|
|
1081
|
+
switch (event2.type) {
|
|
1082
|
+
// The session's own worktree is carried forward like a tool's target, so
|
|
1083
|
+
// the session span a later `session.end` process exports still names it.
|
|
356
1084
|
case "session.start":
|
|
357
1085
|
return {
|
|
358
|
-
...
|
|
359
|
-
...
|
|
1086
|
+
...event2.agentName === void 0 ? {} : { [ATTR_OTELHOOK_AGENT_NAME]: event2.agentName },
|
|
1087
|
+
...event2.agentVersion === void 0 ? {} : { [ATTR_OTELHOOK_AGENT_VERSION]: event2.agentVersion },
|
|
1088
|
+
...targetAttributes(event2)
|
|
360
1089
|
};
|
|
361
1090
|
case "generation.start":
|
|
362
1091
|
return {
|
|
363
|
-
[ATTR_GEN_AI_REQUEST_MODEL]:
|
|
364
|
-
...
|
|
1092
|
+
[ATTR_GEN_AI_REQUEST_MODEL]: event2.model.modelId,
|
|
1093
|
+
...event2.model.vendor === void 0 ? {} : { [ATTR_GEN_AI_SYSTEM]: event2.model.vendor }
|
|
365
1094
|
};
|
|
366
1095
|
// `toolName` and `toolCallId` are on both tool edges, so they are not
|
|
367
1096
|
// start-only and persisting them would just pad every record.
|
|
368
1097
|
// The target is carried forward too: an end-only process may see a payload
|
|
369
1098
|
// with less to go on (no tool input), and the start's evidence still holds.
|
|
370
1099
|
case "tool.start":
|
|
371
|
-
return { [ATTR_OTELHOOK_TOOL_KIND]:
|
|
1100
|
+
return { [ATTR_OTELHOOK_TOOL_KIND]: event2.toolKind, ...targetAttributes(event2) };
|
|
372
1101
|
case "subagent.start":
|
|
373
|
-
return { [ATTR_OTELHOOK_DELEGATION_DEPTH]:
|
|
1102
|
+
return { [ATTR_OTELHOOK_DELEGATION_DEPTH]: event2.delegationDepth };
|
|
374
1103
|
default:
|
|
375
1104
|
return {};
|
|
376
1105
|
}
|
|
@@ -700,22 +1429,22 @@ var createSpanCorrelator = (deps) => {
|
|
|
700
1429
|
};
|
|
701
1430
|
const correlateBatch = async (events) => {
|
|
702
1431
|
const groups = /* @__PURE__ */ new Map();
|
|
703
|
-
for (const
|
|
704
|
-
const ref = spanScopeRefOf(
|
|
1432
|
+
for (const event2 of events) {
|
|
1433
|
+
const ref = spanScopeRefOf(event2);
|
|
705
1434
|
if (ref === void 0) {
|
|
706
1435
|
continue;
|
|
707
1436
|
}
|
|
708
|
-
const providerId =
|
|
709
|
-
const groupKey = [providerId,
|
|
1437
|
+
const providerId = event2.provenance.providerId;
|
|
1438
|
+
const groupKey = [providerId, event2.sessionId, ref.family, ref.scopeKey].join("\0");
|
|
710
1439
|
const group = groups.get(groupKey) ?? {
|
|
711
1440
|
providerId,
|
|
712
|
-
sessionId:
|
|
1441
|
+
sessionId: event2.sessionId,
|
|
713
1442
|
ref
|
|
714
1443
|
};
|
|
715
|
-
if (
|
|
716
|
-
group.start =
|
|
1444
|
+
if (event2.type.endsWith(".start")) {
|
|
1445
|
+
group.start = event2;
|
|
717
1446
|
} else {
|
|
718
|
-
group.end =
|
|
1447
|
+
group.end = event2;
|
|
719
1448
|
}
|
|
720
1449
|
groups.set(groupKey, group);
|
|
721
1450
|
}
|
|
@@ -767,186 +1496,6 @@ var createSpanCorrelator = (deps) => {
|
|
|
767
1496
|
return { recordStart, recordEnd, correlateBatch, cleanup };
|
|
768
1497
|
};
|
|
769
1498
|
|
|
770
|
-
// src/model/usage.ts
|
|
771
|
-
import { z as z2 } from "zod";
|
|
772
|
-
var usageTemporalitySchema = z2.enum(["delta", "cumulative"]);
|
|
773
|
-
var cacheCreationAccountingSchema = z2.enum([
|
|
774
|
-
"included-in-input",
|
|
775
|
-
"disjoint-from-input",
|
|
776
|
-
"not-reported"
|
|
777
|
-
]);
|
|
778
|
-
var providerTotalAgreementSchema = z2.enum(["unreported", "agrees", "disagrees"]);
|
|
779
|
-
var usageReportSchema = z2.strictObject({
|
|
780
|
-
temporality: usageTemporalitySchema,
|
|
781
|
-
/** Inclusive input tokens. */
|
|
782
|
-
inputTokens: tokenCountSchema.optional(),
|
|
783
|
-
/** Subset of `inputTokens` served from a prompt cache. */
|
|
784
|
-
cachedInputTokens: tokenCountSchema.optional(),
|
|
785
|
-
/** Tokens written to a prompt cache. */
|
|
786
|
-
cacheCreationInputTokens: tokenCountSchema.optional(),
|
|
787
|
-
/** Required when `cacheCreationInputTokens` is present and non-zero. */
|
|
788
|
-
cacheCreationAccounting: cacheCreationAccountingSchema.optional(),
|
|
789
|
-
/** Inclusive output tokens. */
|
|
790
|
-
outputTokens: tokenCountSchema.optional(),
|
|
791
|
-
/** Subset of `outputTokens` spent on reasoning. */
|
|
792
|
-
reasoningOutputTokens: tokenCountSchema.optional(),
|
|
793
|
-
/** Total exactly as the provider reported it, if it reported one. */
|
|
794
|
-
providerTotalTokens: tokenCountSchema.optional()
|
|
795
|
-
});
|
|
796
|
-
var canonicalUsageSchema = z2.strictObject({
|
|
797
|
-
temporality: usageTemporalitySchema,
|
|
798
|
-
inputTokens: tokenCountSchema,
|
|
799
|
-
cachedInputTokens: tokenCountSchema,
|
|
800
|
-
cacheCreationInputTokens: tokenCountSchema,
|
|
801
|
-
cacheCreationAccounting: cacheCreationAccountingSchema,
|
|
802
|
-
outputTokens: tokenCountSchema,
|
|
803
|
-
reasoningOutputTokens: tokenCountSchema,
|
|
804
|
-
/** Derived: input tokens that were neither cache reads nor cache writes. */
|
|
805
|
-
uncachedInputTokens: tokenCountSchema,
|
|
806
|
-
/** Derived: canonical billable total. */
|
|
807
|
-
totalTokens: tokenCountSchema,
|
|
808
|
-
providerTotalTokens: tokenCountSchema.optional(),
|
|
809
|
-
providerTotalAgreement: providerTotalAgreementSchema
|
|
810
|
-
}).check((ctx) => {
|
|
811
|
-
const usage = ctx.value;
|
|
812
|
-
const push = (message) => {
|
|
813
|
-
ctx.issues.push({ code: "custom", input: usage, message });
|
|
814
|
-
};
|
|
815
|
-
if (usage.cachedInputTokens > usage.inputTokens) {
|
|
816
|
-
push("cachedInputTokens must not exceed inputTokens (it is a subset)");
|
|
817
|
-
}
|
|
818
|
-
if (usage.reasoningOutputTokens > usage.outputTokens) {
|
|
819
|
-
push("reasoningOutputTokens must not exceed outputTokens (it is a subset)");
|
|
820
|
-
}
|
|
821
|
-
if (usage.cacheCreationAccounting === "not-reported" && usage.cacheCreationInputTokens !== 0) {
|
|
822
|
-
push("cacheCreationInputTokens must be 0 when cacheCreationAccounting is not-reported");
|
|
823
|
-
}
|
|
824
|
-
const creationInsideInput = usage.cacheCreationAccounting === "included-in-input" ? usage.cacheCreationInputTokens : 0;
|
|
825
|
-
if (usage.cachedInputTokens + creationInsideInput > usage.inputTokens) {
|
|
826
|
-
push(
|
|
827
|
-
"cachedInputTokens + cacheCreationInputTokens must not exceed inputTokens when cache creation is included in input"
|
|
828
|
-
);
|
|
829
|
-
}
|
|
830
|
-
const expectedUncached = usage.inputTokens - usage.cachedInputTokens - creationInsideInput;
|
|
831
|
-
if (expectedUncached >= 0 && usage.uncachedInputTokens !== expectedUncached) {
|
|
832
|
-
push(`uncachedInputTokens must equal ${expectedUncached}`);
|
|
833
|
-
}
|
|
834
|
-
const creationOutsideInput = usage.cacheCreationAccounting === "disjoint-from-input" ? usage.cacheCreationInputTokens : 0;
|
|
835
|
-
const expectedTotal = usage.inputTokens + creationOutsideInput + usage.outputTokens;
|
|
836
|
-
if (usage.totalTokens !== expectedTotal) {
|
|
837
|
-
push(`totalTokens must equal ${expectedTotal}`);
|
|
838
|
-
}
|
|
839
|
-
const expectedAgreement = usage.providerTotalTokens === void 0 ? "unreported" : usage.providerTotalTokens === expectedTotal ? "agrees" : "disagrees";
|
|
840
|
-
if (usage.providerTotalAgreement !== expectedAgreement) {
|
|
841
|
-
push(`providerTotalAgreement must be ${expectedAgreement}`);
|
|
842
|
-
}
|
|
843
|
-
});
|
|
844
|
-
var normalizeUsage = (report) => {
|
|
845
|
-
const parsed = usageReportSchema.safeParse(report);
|
|
846
|
-
if (!parsed.success) {
|
|
847
|
-
return {
|
|
848
|
-
status: "invalid",
|
|
849
|
-
issues: parsed.error.issues.map((issue) => ({
|
|
850
|
-
code: "invalid-report",
|
|
851
|
-
message: `${issue.path.join(".") || "<root>"}: ${issue.message}`
|
|
852
|
-
}))
|
|
853
|
-
};
|
|
854
|
-
}
|
|
855
|
-
const input = parsed.data;
|
|
856
|
-
const issues = [];
|
|
857
|
-
const notes = [];
|
|
858
|
-
const inputTokens = input.inputTokens ?? 0;
|
|
859
|
-
const cachedInputTokens = input.cachedInputTokens ?? 0;
|
|
860
|
-
const cacheCreationInputTokens = input.cacheCreationInputTokens ?? 0;
|
|
861
|
-
const outputTokens = input.outputTokens ?? 0;
|
|
862
|
-
const reasoningOutputTokens = input.reasoningOutputTokens ?? 0;
|
|
863
|
-
let accounting;
|
|
864
|
-
if (cacheCreationInputTokens === 0) {
|
|
865
|
-
accounting = input.cacheCreationAccounting ?? "not-reported";
|
|
866
|
-
if (accounting !== "not-reported") {
|
|
867
|
-
notes.push(
|
|
868
|
-
`cacheCreationAccounting=${accounting} retained with zero cache-creation tokens`
|
|
869
|
-
);
|
|
870
|
-
}
|
|
871
|
-
} else if (input.cacheCreationAccounting === void 0) {
|
|
872
|
-
issues.push({
|
|
873
|
-
code: "cache-creation-accounting-missing",
|
|
874
|
-
message: "cacheCreationAccounting is required when cacheCreationInputTokens is non-zero; it cannot be inferred"
|
|
875
|
-
});
|
|
876
|
-
accounting = "not-reported";
|
|
877
|
-
} else if (input.cacheCreationAccounting === "not-reported") {
|
|
878
|
-
issues.push({
|
|
879
|
-
code: "cache-creation-accounting-missing",
|
|
880
|
-
message: "cacheCreationAccounting=not-reported conflicts with non-zero cacheCreationInputTokens"
|
|
881
|
-
});
|
|
882
|
-
accounting = "not-reported";
|
|
883
|
-
} else {
|
|
884
|
-
accounting = input.cacheCreationAccounting;
|
|
885
|
-
}
|
|
886
|
-
if (cachedInputTokens > inputTokens) {
|
|
887
|
-
issues.push({
|
|
888
|
-
code: "cached-exceeds-input",
|
|
889
|
-
message: `cachedInputTokens (${cachedInputTokens}) exceeds inclusive inputTokens (${inputTokens})`
|
|
890
|
-
});
|
|
891
|
-
}
|
|
892
|
-
if (reasoningOutputTokens > outputTokens) {
|
|
893
|
-
issues.push({
|
|
894
|
-
code: "reasoning-exceeds-output",
|
|
895
|
-
message: `reasoningOutputTokens (${reasoningOutputTokens}) exceeds inclusive outputTokens (${outputTokens})`
|
|
896
|
-
});
|
|
897
|
-
}
|
|
898
|
-
const creationInsideInput = accounting === "included-in-input" ? cacheCreationInputTokens : 0;
|
|
899
|
-
if (cachedInputTokens + creationInsideInput > inputTokens) {
|
|
900
|
-
issues.push({
|
|
901
|
-
code: "cache-creation-exceeds-input",
|
|
902
|
-
message: `cachedInputTokens + cacheCreationInputTokens (${cachedInputTokens + creationInsideInput}) exceeds inclusive inputTokens (${inputTokens})`
|
|
903
|
-
});
|
|
904
|
-
}
|
|
905
|
-
if (issues.length > 0) {
|
|
906
|
-
return { status: "invalid", issues };
|
|
907
|
-
}
|
|
908
|
-
const creationOutsideInput = accounting === "disjoint-from-input" ? cacheCreationInputTokens : 0;
|
|
909
|
-
const totalTokens = inputTokens + creationOutsideInput + outputTokens;
|
|
910
|
-
const providerTotalAgreement = input.providerTotalTokens === void 0 ? "unreported" : input.providerTotalTokens === totalTokens ? "agrees" : "disagrees";
|
|
911
|
-
if (providerTotalAgreement === "disagrees") {
|
|
912
|
-
notes.push(
|
|
913
|
-
`providerTotalTokens (${input.providerTotalTokens ?? 0}) disagrees with canonical total (${totalTokens}); both retained`
|
|
914
|
-
);
|
|
915
|
-
}
|
|
916
|
-
const usage = {
|
|
917
|
-
temporality: input.temporality,
|
|
918
|
-
inputTokens,
|
|
919
|
-
cachedInputTokens,
|
|
920
|
-
cacheCreationInputTokens,
|
|
921
|
-
cacheCreationAccounting: accounting,
|
|
922
|
-
outputTokens,
|
|
923
|
-
reasoningOutputTokens,
|
|
924
|
-
uncachedInputTokens: inputTokens - cachedInputTokens - creationInsideInput,
|
|
925
|
-
totalTokens,
|
|
926
|
-
...input.providerTotalTokens === void 0 ? {} : { providerTotalTokens: input.providerTotalTokens },
|
|
927
|
-
providerTotalAgreement
|
|
928
|
-
};
|
|
929
|
-
return { status: "ok", usage, notes };
|
|
930
|
-
};
|
|
931
|
-
var UsageNormalizationError = class extends Error {
|
|
932
|
-
issues;
|
|
933
|
-
constructor(issues) {
|
|
934
|
-
super(`invalid usage report: ${issues.map((issue) => issue.message).join("; ")}`);
|
|
935
|
-
this.name = "UsageNormalizationError";
|
|
936
|
-
this.issues = issues;
|
|
937
|
-
}
|
|
938
|
-
};
|
|
939
|
-
var normalizeUsageOrThrow = (report) => {
|
|
940
|
-
const result = normalizeUsage(report);
|
|
941
|
-
if (result.status === "invalid") {
|
|
942
|
-
throw new UsageNormalizationError(result.issues);
|
|
943
|
-
}
|
|
944
|
-
return result.usage;
|
|
945
|
-
};
|
|
946
|
-
var EMPTY_DELTA_USAGE = Object.freeze(
|
|
947
|
-
normalizeUsageOrThrow({ temporality: "delta" })
|
|
948
|
-
);
|
|
949
|
-
|
|
950
1499
|
// src/lifecycle/usage-accumulator.ts
|
|
951
1500
|
var EMPTY_CUMULATIVE_USAGE = normalizeUsageOrThrow({ temporality: "cumulative" });
|
|
952
1501
|
var combineCumulativeWithDelta = (total, delta) => {
|