@osfactory/otel-hook 0.5.0 → 0.6.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 (41) hide show
  1. package/dist/{adapter-BS7xHKGQ.d.ts → adapter-BJiz6lqM.d.ts} +2 -2
  2. package/dist/cli.js +47 -24
  3. package/dist/cli.js.map +1 -1
  4. package/dist/{events-CzZ5kukS.d.ts → events-B3MHoJTD.d.ts} +72 -1
  5. package/dist/{filesystem-store-BcOveJYY.d.ts → filesystem-store-r-nNA3BA.d.ts} +1 -1
  6. package/dist/{hook-DxTakjAD.d.ts → hook-Dh8OO4Wa.d.ts} +4 -4
  7. package/dist/index.d.ts +11 -11
  8. package/dist/index.js +50 -24
  9. package/dist/index.js.map +1 -1
  10. package/dist/install.d.ts +4 -4
  11. package/dist/install.js +8 -2
  12. package/dist/install.js.map +1 -1
  13. package/dist/integration.d.ts +8 -8
  14. package/dist/integration.js +2264 -2253
  15. package/dist/integration.js.map +1 -1
  16. package/dist/lifecycle.d.ts +3 -3
  17. package/dist/lifecycle.js +757 -212
  18. package/dist/lifecycle.js.map +1 -1
  19. package/dist/{memory-DkTohdIa.d.ts → memory-Bl9ANVff.d.ts} +2 -2
  20. package/dist/model.d.ts +1 -1
  21. package/dist/model.js +13 -2
  22. package/dist/model.js.map +1 -1
  23. package/dist/{otlp-log-sink-DaZDPKnR.d.ts → otlp-log-sink-eUEjaLhk.d.ts} +3 -3
  24. package/dist/{payload-2lnpKodw.d.ts → payload-Ci8_ERm6.d.ts} +1 -1
  25. package/dist/{ports-B0rC49b3.d.ts → ports-n7KFOpKo.d.ts} +1 -1
  26. package/dist/providers.d.ts +10 -10
  27. package/dist/providers.js +32 -13
  28. package/dist/providers.js.map +1 -1
  29. package/dist/{registry-DVnPA_b6.d.ts → registry-CIVvRlVK.d.ts} +1 -1
  30. package/dist/runtime.d.ts +8 -8
  31. package/dist/runtime.js +11 -6
  32. package/dist/runtime.js.map +1 -1
  33. package/dist/{semconv-CtnDdsPk.d.ts → semconv-fPRb-dpU.d.ts} +1 -1
  34. package/dist/state.d.ts +4 -4
  35. package/dist/telemetry.d.ts +6 -6
  36. package/dist/telemetry.js +945 -412
  37. package/dist/telemetry.js.map +1 -1
  38. package/dist/testing.d.ts +14 -8
  39. package/dist/testing.js +36 -18
  40. package/dist/testing.js.map +1 -1
  41. package/package.json +1 -1
@@ -692,2437 +692,2448 @@ import {
692
692
  } from "@opentelemetry/semantic-conventions/incubating";
693
693
 
694
694
  // src/version.ts
695
- var VERSION = "0.5.0";
695
+ var VERSION = "0.6.0";
696
696
 
697
697
  // src/telemetry/export-identity.ts
698
698
  import { ATTR_SESSION_ID } from "@opentelemetry/semantic-conventions/incubating";
699
- var ATTR_TRACE_ID = "trace_id";
700
- var ATTR_SPAN_ID = "span_id";
701
- var ATTR_PARENT_SPAN_ID = "parent_span_id";
702
- var ATTR_OTELHOOK_SESSION_ID = "otelhook.session.id";
703
- var ATTR_GEN_AI_CONVERSATION_ID = "gen_ai.conversation.id";
704
- var TRACE_ID_HEX_PATTERN = /^[0-9a-f]{32}$/;
705
- var SPAN_ID_HEX_PATTERN = /^[0-9a-f]{16}$/;
706
- var ATTR_OTELHOOK_INVOCATION_ID = "otelhook.invocation.id";
707
- var ATTR_OTELHOOK_PROVIDER_ID = "otelhook.provider.id";
708
- var ATTR_OTELHOOK_PROVIDER_VERSION = "otelhook.provider.version";
709
- var ATTR_OTELHOOK_WORKSPACE_ID = "otelhook.workspace.id";
710
- var HAR_SESSION_KEY = "har.session_key";
711
- var ATTR_OTELHOOK_SUBAGENT_ID = "otelhook.subagent.id";
712
- var ATTR_VCS_REF_HEAD_NAME = "vcs.ref.head.name";
713
- var ATTR_OTELHOOK_TARGET_WORKSPACE_ID = "otelhook.target.workspace.id";
714
- var ATTR_OTELHOOK_TARGET_SOURCE = "otelhook.target.source";
715
- var ATTR_OTELHOOK_TARGET_REPOSITORY_ID = "otelhook.target.repository.id";
716
- var ATTR_OTELHOOK_TARGET_WORKTREE_KIND = "otelhook.target.worktree.kind";
717
- var ATTR_OTELHOOK_USAGE_TEMPORALITY = "otelhook.usage.temporality";
718
- var targetAttributes = (event2) => {
719
- if (event2.type !== "tool.start" && event2.type !== "tool.end" || event2.target === void 0) {
720
- return {};
699
+
700
+ // src/model/events.ts
701
+ import { z as z10 } from "zod";
702
+
703
+ // src/model/content.ts
704
+ import { z as z4 } from "zod";
705
+ var contentKindSchema = z4.enum([
706
+ "prompt",
707
+ "response",
708
+ "reasoning",
709
+ "tool-input",
710
+ "tool-output",
711
+ "error-message",
712
+ "system-instruction",
713
+ "attachment"
714
+ ]);
715
+ var contentRoleSchema = z4.enum(["user", "assistant", "system", "tool", "unknown"]);
716
+ var contentDisclosureSchema = z4.enum(["omitted", "masked", "redacted", "raw"]);
717
+ var CONTENT_HASH_PATTERN = /^sha256:[0-9a-f]{64}$/;
718
+ var contentFactSchema = z4.strictObject({
719
+ kind: contentKindSchema,
720
+ role: contentRoleSchema.optional(),
721
+ /** Unicode code point count of the original content. */
722
+ characterLength: z4.number().int().min(0),
723
+ /** UTF-8 byte length of the original content. */
724
+ byteLength: z4.number().int().min(0),
725
+ /** Stable salted digest of the original content. */
726
+ contentHash: z4.string().regex(CONTENT_HASH_PATTERN),
727
+ disclosure: contentDisclosureSchema,
728
+ /** Disclosed text, bounded by the privacy policy. Absent when omitted. */
729
+ text: z4.string().optional(),
730
+ /** True when `text` was cut short by the configured string bound. */
731
+ truncated: z4.boolean(),
732
+ /** Number of secret-looking spans replaced while producing `text`. */
733
+ secretsRedacted: z4.number().int().min(0),
734
+ /** Optional non-sensitive label, e.g. a MIME type or tool name. */
735
+ label: nonEmptyStringSchema.optional()
736
+ });
737
+ var contentFactsSchema = z4.array(contentFactSchema).max(64);
738
+ var isContentFactConsistent = (fact) => fact.disclosure === "omitted" ? fact.text === void 0 : fact.text !== void 0;
739
+ var isUnavailableContentFact = (fact) => fact.disclosure === "omitted" && fact.text === void 0 && fact.characterLength === 0 && fact.byteLength === 0;
740
+
741
+ // src/model/extensions.ts
742
+ import { z as z5 } from "zod";
743
+ var EXTENSION_KEY_PATTERN = /^[a-z][a-z0-9]*(?:[-_][a-z0-9]+)*(?:\.[a-z][a-z0-9]*(?:[-_][a-z0-9]+)*)+$/;
744
+ var RESERVED_EXTENSION_NAMESPACES = Object.freeze([
745
+ "otelhook",
746
+ "otel",
747
+ "telemetry"
748
+ ]);
749
+ var MAX_EXTENSION_ENTRIES = 64;
750
+ var extensionKeyNamespace = (key) => key.slice(0, key.indexOf("."));
751
+ var isReservedExtensionNamespace = (key) => RESERVED_EXTENSION_NAMESPACES.includes(extensionKeyNamespace(key));
752
+ var isValidExtensionKey = (key) => EXTENSION_KEY_PATTERN.test(key) && !isReservedExtensionNamespace(key);
753
+ var extensionsSchema = z5.record(z5.string(), attributeValueSchema).check((ctx) => {
754
+ const keys = Object.keys(ctx.value);
755
+ if (keys.length > MAX_EXTENSION_ENTRIES) {
756
+ ctx.issues.push({
757
+ code: "custom",
758
+ input: ctx.value,
759
+ message: `extensions may contain at most ${MAX_EXTENSION_ENTRIES} entries`
760
+ });
721
761
  }
722
- const { target } = event2;
723
- return {
724
- [ATTR_OTELHOOK_TARGET_WORKSPACE_ID]: target.workspaceId,
725
- [ATTR_OTELHOOK_TARGET_SOURCE]: target.source,
726
- ...target.vcsBranchName === void 0 ? {} : { [ATTR_VCS_REF_HEAD_NAME]: target.vcsBranchName },
727
- ...target.repositoryId === void 0 ? {} : { [ATTR_OTELHOOK_TARGET_REPOSITORY_ID]: target.repositoryId },
728
- ...target.worktreeKind === void 0 ? {} : { [ATTR_OTELHOOK_TARGET_WORKTREE_KIND]: target.worktreeKind }
729
- };
730
- };
731
- var usageTemporalityAttributes = (usage) => usage === void 0 ? {} : { [ATTR_OTELHOOK_USAGE_TEMPORALITY]: usage.temporality };
732
- var isPrimitiveAttribute = (value) => typeof value === "string" || typeof value === "number" || typeof value === "boolean";
733
- var passthroughHarAttributes = (resource) => {
734
- const attributes = {};
735
- for (const [key, value] of Object.entries(resource.attributes)) {
736
- if (key.startsWith("har.") && isPrimitiveAttribute(value)) {
737
- attributes[key] = value;
762
+ for (const key of keys) {
763
+ if (!EXTENSION_KEY_PATTERN.test(key)) {
764
+ ctx.issues.push({
765
+ code: "custom",
766
+ input: ctx.value,
767
+ path: [key],
768
+ message: `extension key ${JSON.stringify(key)} must be namespaced, e.g. "acme.tier"`
769
+ });
770
+ continue;
738
771
  }
739
- }
740
- return attributes;
741
- };
742
- var resolveExportedSessionId = (eventSessionId, resource) => {
743
- const har = resource.attributes[HAR_SESSION_KEY];
744
- if (typeof har === "string") {
745
- const trimmed = har.trim();
746
- if (trimmed.length > 0) {
747
- return { sessionId: trimmed, providerSessionId: eventSessionId };
772
+ if (isReservedExtensionNamespace(key)) {
773
+ ctx.issues.push({
774
+ code: "custom",
775
+ input: ctx.value,
776
+ path: [key],
777
+ message: `extension namespace ${JSON.stringify(extensionKeyNamespace(key))} is reserved`
778
+ });
748
779
  }
749
780
  }
750
- return { sessionId: eventSessionId, providerSessionId: eventSessionId };
751
- };
752
- var hexTraceAttributes = (ids) => ({
753
- ...TRACE_ID_HEX_PATTERN.test(ids.traceId) ? { [ATTR_TRACE_ID]: ids.traceId } : {},
754
- ...SPAN_ID_HEX_PATTERN.test(ids.spanId) ? { [ATTR_SPAN_ID]: ids.spanId } : {},
755
- ...ids.parentSpanId !== void 0 && SPAN_ID_HEX_PATTERN.test(ids.parentSpanId) ? { [ATTR_PARENT_SPAN_ID]: ids.parentSpanId } : {}
756
781
  });
757
- var exportIdentityAttributes = (event2, resource, ids) => {
758
- const { sessionId, providerSessionId } = resolveExportedSessionId(event2.sessionId, resource);
759
- return {
760
- [ATTR_SESSION_ID]: sessionId,
761
- [ATTR_OTELHOOK_SESSION_ID]: providerSessionId,
762
- [ATTR_GEN_AI_CONVERSATION_ID]: providerSessionId,
763
- [ATTR_OTELHOOK_INVOCATION_ID]: event2.invocationId,
764
- [ATTR_OTELHOOK_PROVIDER_ID]: event2.provenance.providerId,
765
- ...event2.provenance.providerVersion === void 0 ? {} : { [ATTR_OTELHOOK_PROVIDER_VERSION]: event2.provenance.providerVersion },
766
- [ATTR_OTELHOOK_WORKSPACE_ID]: event2.workspace.workspaceId,
767
- ...event2.subagentId === void 0 ? {} : { [ATTR_OTELHOOK_SUBAGENT_ID]: event2.subagentId },
768
- ...passthroughHarAttributes(resource),
769
- ...hexTraceAttributes(ids)
770
- };
771
- };
782
+ var EMPTY_EXTENSIONS = Object.freeze({});
783
+ var emptyExtensions = () => ({});
772
784
 
773
- // src/telemetry/semconv.ts
774
- var SCOPE_NAME = "@osfactory/otel-hook";
775
- var DEFAULT_INSTRUMENTATION_SCOPE = Object.freeze({
776
- name: SCOPE_NAME,
777
- version: VERSION
785
+ // src/model/identity.ts
786
+ import { z as z6 } from "zod";
787
+ var workspaceKeySourceSchema = z6.enum([
788
+ "git-remote",
789
+ "git-root",
790
+ "working-directory",
791
+ "explicit",
792
+ "unknown"
793
+ ]);
794
+ var workspaceIdentitySchema = z6.strictObject({
795
+ workspaceId: workspaceIdSchema,
796
+ keySource: workspaceKeySourceSchema,
797
+ /** Repository name only; never an owner path or URL with credentials. */
798
+ repositoryName: nonEmptyStringSchema.optional(),
799
+ vcsBranchName: nonEmptyStringSchema.optional(),
800
+ /** Opaque handle for the checked-out revision. */
801
+ vcsRevisionId: nonEmptyStringSchema.optional()
802
+ }).readonly();
803
+ var UNKNOWN_WORKSPACE_ID = "unknown:0000000000000000";
804
+ var unknownWorkspaceIdentity = () => workspaceIdentitySchema.parse({
805
+ workspaceId: UNKNOWN_WORKSPACE_ID,
806
+ keySource: "unknown"
778
807
  });
779
- var ATTR_OTELHOOK_SPAN_PAIRED = "otelhook.span.paired";
780
- var ATTR_OTELHOOK_SPAN_PAIRING = "otelhook.span.pairing";
781
- var ATTR_OTELHOOK_SPAN_ORPHAN = "otelhook.span.orphan";
782
- var ATTR_OTELHOOK_OUTCOME = "otelhook.outcome";
783
- var ATTR_OTELHOOK_RESET_DETECTED = "otelhook.usage.reset_detected";
784
- var ATTR_OTELHOOK_TOOL_KIND = "otelhook.tool.kind";
785
- var ATTR_OTELHOOK_DELEGATION_DEPTH = "otelhook.delegation_depth";
786
- var ATTR_OTELHOOK_COMPACTION_TRIGGER = "otelhook.compaction.trigger";
787
- var ATTR_OTELHOOK_AGENT_NAME = "otelhook.agent.name";
788
- var ATTR_OTELHOOK_AGENT_VERSION = "otelhook.agent.version";
789
- var ATTR_OTELHOOK_GENERATION_ID = "otelhook.generation.id";
790
- var FIELD_SEPARATOR = "\0";
791
- var digestHex = (parts, length) => createHash("sha256").update(parts.join(FIELD_SEPARATOR)).digest("hex").slice(0, length);
792
- var MAX_RECOVERED_START_ATTRIBUTES = 16;
793
- var familyOf = (type) => {
794
- switch (type) {
795
- case "session.start":
796
- case "session.end":
797
- return "session";
798
- case "generation.start":
799
- case "generation.end":
800
- return "generation";
801
- case "tool.start":
802
- case "tool.end":
803
- return "tool";
804
- case "subagent.start":
805
- case "subagent.end":
806
- return "subagent";
807
- default:
808
- return void 0;
808
+ var sourceProvenanceSchema = z6.strictObject({
809
+ providerId: resolvedProviderIdSchema,
810
+ providerVersion: nonEmptyStringSchema.optional(),
811
+ adapterId: nonEmptyStringSchema,
812
+ adapterVersion: nonEmptyStringSchema,
813
+ detectionConfidence: detectionConfidenceSchema,
814
+ /** The provider's own name for the source event, e.g. a hook event name. */
815
+ sourceEventName: nonEmptyStringSchema.optional(),
816
+ transport: sourceTransportSchema
817
+ }).readonly();
818
+ var consumerAttributesSchema = attributesSchema.readonly();
819
+ var invocationIdentitySchema = z6.strictObject({
820
+ invocationId: invocationIdSchema,
821
+ sessionId: sessionIdSchema,
822
+ /** Set when this invocation runs beneath another agent invocation. */
823
+ parentInvocationId: invocationIdSchema.optional(),
824
+ /** Root of the session tree when the provider exposes one. */
825
+ rootSessionId: sessionIdSchema.optional(),
826
+ /** Stable handle for the agent process/instance, when available. */
827
+ agentInstanceId: nonEmptyStringSchema.optional(),
828
+ provenance: sourceProvenanceSchema,
829
+ workspace: workspaceIdentitySchema,
830
+ startedAt: epochMillisSchema,
831
+ consumerAttributes: consumerAttributesSchema
832
+ }).readonly();
833
+ var identityClaimFieldsSchema = z6.strictObject({
834
+ invocationId: invocationIdSchema.optional(),
835
+ sessionId: sessionIdSchema.optional(),
836
+ parentInvocationId: invocationIdSchema.optional(),
837
+ rootSessionId: sessionIdSchema.optional(),
838
+ agentInstanceId: nonEmptyStringSchema.optional(),
839
+ workspace: workspaceIdentitySchema.optional(),
840
+ startedAt: epochMillisSchema.optional()
841
+ });
842
+ var identityClaimSchema = z6.strictObject({
843
+ /** Non-sensitive label, e.g. `adapter:acme-cli` or `env:OTEL_HOOK_SESSION_ID`. */
844
+ source: nonEmptyStringSchema,
845
+ confidence: detectionConfidenceSchema,
846
+ fields: identityClaimFieldsSchema
847
+ });
848
+ var CLAIM_FIELDS = [
849
+ "invocationId",
850
+ "sessionId",
851
+ "parentInvocationId",
852
+ "rootSessionId",
853
+ "agentInstanceId",
854
+ "workspace",
855
+ "startedAt"
856
+ ];
857
+ var renderClaimValue = (value) => {
858
+ if (typeof value === "string") {
859
+ return value;
809
860
  }
810
- };
811
- var spanScopeRefOf = (event2) => {
812
- const family = familyOf(event2.type);
813
- if (family === void 0) {
814
- return void 0;
861
+ if (typeof value === "number" || typeof value === "boolean") {
862
+ return String(value);
815
863
  }
816
- switch (event2.type) {
817
- case "session.start":
818
- case "session.end":
819
- return { family, scopeKey: event2.sessionId };
820
- case "generation.start":
821
- case "generation.end":
822
- return { family, scopeKey: event2.generationId };
823
- case "tool.start":
824
- case "tool.end":
825
- return { family, scopeKey: event2.toolCallId };
826
- case "subagent.start":
827
- case "subagent.end":
828
- return { family, scopeKey: event2.subagentInvocationId };
829
- default:
830
- return void 0;
864
+ if (value !== null && typeof value === "object" && "workspaceId" in value) {
865
+ const { workspaceId } = value;
866
+ return typeof workspaceId === "string" ? workspaceId : "<workspace>";
831
867
  }
868
+ return "<opaque>";
832
869
  };
833
- var parentScopeRefOf = (event2) => {
834
- if (event2.type === "session.start" || event2.type === "session.end") {
835
- return void 0;
836
- }
837
- if (event2.type === "tool.start" && event2.generationId !== void 0) {
838
- return { family: "generation", scopeKey: event2.generationId };
870
+ var resolveInvocationIdentity = (input) => {
871
+ const parsedClaims = [];
872
+ const issues = [];
873
+ for (const [index, claim] of input.claims.entries()) {
874
+ const parsed2 = identityClaimSchema.safeParse(claim);
875
+ if (parsed2.success) {
876
+ parsedClaims.push(parsed2.data);
877
+ } else {
878
+ issues.push(
879
+ `claim[${index}]: ${parsed2.error.issues.map((issue) => `${issue.path.join(".") || "<root>"} ${issue.message}`).join(", ")}`
880
+ );
881
+ }
839
882
  }
840
- return { family: "session", scopeKey: event2.sessionId };
841
- };
842
- var startOnlySpanAttributes = (event2) => {
843
- switch (event2.type) {
844
- case "session.start":
845
- return {
846
- ...event2.agentName === void 0 ? {} : { [ATTR_OTELHOOK_AGENT_NAME]: event2.agentName },
847
- ...event2.agentVersion === void 0 ? {} : { [ATTR_OTELHOOK_AGENT_VERSION]: event2.agentVersion }
848
- };
849
- case "generation.start":
850
- return {
851
- [ATTR_GEN_AI_REQUEST_MODEL]: event2.model.modelId,
852
- ...event2.model.vendor === void 0 ? {} : { [ATTR_GEN_AI_SYSTEM]: event2.model.vendor }
853
- };
854
- // `toolName` and `toolCallId` are on both tool edges, so they are not
855
- // start-only and persisting them would just pad every record.
856
- // The target is carried forward too: an end-only process may see a payload
857
- // with less to go on (no tool input), and the start's evidence still holds.
858
- case "tool.start":
859
- return { [ATTR_OTELHOOK_TOOL_KIND]: event2.toolKind, ...targetAttributes(event2) };
860
- case "subagent.start":
861
- return { [ATTR_OTELHOOK_DELEGATION_DEPTH]: event2.delegationDepth };
862
- default:
863
- return {};
883
+ if (issues.length > 0) {
884
+ return { status: "invalid", issues };
864
885
  }
865
- };
866
- var deriveTraceId = (providerId, sessionId) => digestHex(["otelhook/trace", providerId, sessionId], 32);
867
- var deriveSpanId = (providerId, sessionId, ref) => digestHex(["otelhook/span", providerId, sessionId, ref.family, ref.scopeKey], 16);
868
- var deriveStandaloneSpanId = (providerId, sessionId, eventType, eventId) => digestHex(["otelhook/span", providerId, sessionId, "event", eventType, eventId], 16);
869
- var correlationKey = (providerId, sessionId, ref) => [providerId, sessionId, ref.family, ref.scopeKey].join(FIELD_SEPARATOR);
870
- var outcomeStatus = (outcome) => {
871
- if (outcome === void 0 || outcome === "ok" || outcome === "unknown") {
872
- return { code: SpanStatusCode.UNSET };
886
+ const conflicts = [];
887
+ const selected = {};
888
+ for (const field of CLAIM_FIELDS) {
889
+ const contributors = parsedClaims.filter((claim) => claim.fields[field] !== void 0);
890
+ if (contributors.length === 0) {
891
+ continue;
892
+ }
893
+ const bestRank = Math.max(
894
+ ...contributors.map((claim) => DETECTION_CONFIDENCE_RANK[claim.confidence])
895
+ );
896
+ const best = contributors.filter(
897
+ (claim) => DETECTION_CONFIDENCE_RANK[claim.confidence] === bestRank
898
+ );
899
+ const rendered = /* @__PURE__ */ new Map();
900
+ for (const claim of best) {
901
+ const key = JSON.stringify(claim.fields[field]);
902
+ const sources = rendered.get(key) ?? [];
903
+ sources.push(claim.source);
904
+ rendered.set(key, sources);
905
+ }
906
+ if (rendered.size > 1) {
907
+ const [firstBest] = best;
908
+ conflicts.push({
909
+ field,
910
+ confidence: firstBest?.confidence ?? "none",
911
+ values: best.map((claim) => renderClaimValue(claim.fields[field])),
912
+ sources: best.map((claim) => claim.source)
913
+ });
914
+ continue;
915
+ }
916
+ const [winner] = best;
917
+ if (winner !== void 0) {
918
+ selected[field] = winner.fields[field];
919
+ }
873
920
  }
874
- if (outcome === "cancelled") {
875
- return { code: SpanStatusCode.UNSET };
921
+ if (conflicts.length > 0) {
922
+ return { status: "conflict", conflicts };
876
923
  }
877
- return { code: SpanStatusCode.ERROR, message: outcome };
878
- };
879
- var identityAttributes = (event2, resource, ids) => exportIdentityAttributes(event2, resource, ids);
880
- var usageAttributes = (usage, resetDetected) => {
881
- if (usage === void 0) {
882
- return {};
924
+ const missing = [];
925
+ if (selected.invocationId === void 0) {
926
+ missing.push("invocationId");
883
927
  }
884
- return {
885
- [ATTR_GEN_AI_USAGE_INPUT_TOKENS]: usage.inputTokens,
886
- [ATTR_GEN_AI_USAGE_OUTPUT_TOKENS]: usage.outputTokens,
887
- [ATTR_GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS]: usage.cachedInputTokens,
888
- [ATTR_GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS]: usage.cacheCreationInputTokens,
889
- [ATTR_GEN_AI_USAGE_REASONING_OUTPUT_TOKENS]: usage.reasoningOutputTokens,
890
- ...usageTemporalityAttributes(usage),
891
- ...resetDetected ? { [ATTR_OTELHOOK_RESET_DETECTED]: true } : {}
892
- };
893
- };
894
- var TARGET_SOURCE_RANK = Object.freeze({
895
- "tool-path": 3,
896
- "shell-cwd": 2,
897
- "session-cwd": 1
898
- });
899
- var TARGET_KEYS = [
900
- ATTR_OTELHOOK_TARGET_WORKSPACE_ID,
901
- ATTR_OTELHOOK_TARGET_SOURCE,
902
- ATTR_VCS_REF_HEAD_NAME,
903
- ATTR_OTELHOOK_TARGET_REPOSITORY_ID,
904
- ATTR_OTELHOOK_TARGET_WORKTREE_KIND
905
- ];
906
- var pickTarget = (attributes) => {
907
- const picked = {};
908
- for (const key of TARGET_KEYS) {
909
- if (attributes[key] !== void 0) {
910
- picked[key] = attributes[key];
911
- }
928
+ if (selected.sessionId === void 0) {
929
+ missing.push("sessionId");
912
930
  }
913
- return picked;
914
- };
915
- var withoutTarget = (attributes) => {
916
- const rest = { ...attributes };
917
- for (const key of TARGET_KEYS) {
918
- delete rest[key];
931
+ if (missing.length > 0) {
932
+ return { status: "incomplete", missing };
919
933
  }
920
- return rest;
921
- };
922
- var rankOf = (candidate) => {
923
- const source = candidate[ATTR_OTELHOOK_TARGET_SOURCE];
924
- return typeof source === "string" && Object.hasOwn(TARGET_SOURCE_RANK, source) ? TARGET_SOURCE_RANK[source] ?? 0 : 0;
925
- };
926
- var strongestTarget = (candidates) => {
927
- let best = {};
928
- let bestRank = 0;
929
- for (const candidate of candidates) {
930
- const rank = rankOf(candidate);
931
- if (rank > 0 && rank >= bestRank) {
932
- best = candidate;
933
- bestRank = rank;
934
- }
934
+ const startedAt = selected.startedAt ?? input.fallback?.startedAt;
935
+ if (startedAt === void 0) {
936
+ return { status: "incomplete", missing: ["startedAt"] };
935
937
  }
936
- return best;
937
- };
938
- var buildSpanContext = (traceId, spanId) => ({
939
- traceId,
940
- spanId,
941
- traceFlags: TraceFlags.SAMPLED,
942
- isRemote: false
943
- });
944
- var assembleReadableSpan = (input) => toReadableSpan(input);
945
- var toReadableSpan = (input) => {
946
- const startTime = millisToHrTime(input.startMillis);
947
- const endTime = millisToHrTime(Math.max(input.startMillis, input.endMillis));
948
- const duration = millisToHrTime(Math.max(0, input.endMillis - input.startMillis));
949
- return {
950
- name: input.name,
951
- kind: input.kind,
952
- spanContext: () => buildSpanContext(input.traceId, input.spanId),
953
- ...input.parentSpanId === void 0 ? {} : { parentSpanContext: buildSpanContext(input.traceId, input.parentSpanId) },
954
- startTime,
955
- endTime,
956
- status: input.status,
957
- attributes: input.attributes,
958
- links: [],
959
- events: [],
960
- duration,
961
- ended: true,
962
- resource: input.resource,
963
- instrumentationScope: input.instrumentationScope,
964
- droppedAttributesCount: 0,
965
- droppedEventsCount: 0,
966
- droppedLinksCount: 0
938
+ const workspace = selected.workspace ?? input.fallback?.workspace ?? unknownWorkspaceIdentity();
939
+ const candidate = {
940
+ invocationId: selected.invocationId,
941
+ sessionId: selected.sessionId,
942
+ ...selected.parentInvocationId === void 0 ? {} : { parentInvocationId: selected.parentInvocationId },
943
+ ...selected.rootSessionId === void 0 ? {} : { rootSessionId: selected.rootSessionId },
944
+ ...selected.agentInstanceId === void 0 ? {} : { agentInstanceId: selected.agentInstanceId },
945
+ provenance: input.provenance,
946
+ workspace,
947
+ startedAt,
948
+ consumerAttributes: input.consumerAttributes ?? {}
967
949
  };
968
- };
969
- var resolvePairing = (group, anchor, correlation) => {
970
- const inBatch = group.start !== void 0 && group.end !== void 0;
971
- const batchStart = group.start?.occurredAt ?? anchor.occurredAt;
972
- const batchEnd = group.end?.occurredAt ?? anchor.occurredAt;
973
- if (correlation === void 0) {
950
+ const parsed = invocationIdentitySchema.safeParse(candidate);
951
+ if (!parsed.success) {
974
952
  return {
975
- pairing: inBatch ? "in-batch" : "unpaired",
976
- orphan: inBatch ? "none" : group.start === void 0 ? "missing-start" : "missing-end",
977
- startMillis: batchStart,
978
- endMillis: inBatch ? batchEnd : batchStart,
979
- parent: parentScopeRefOf(anchor),
980
- recovered: {}
953
+ status: "invalid",
954
+ issues: parsed.error.issues.map(
955
+ (issue) => `${issue.path.join(".") || "<root>"}: ${issue.message}`
956
+ )
981
957
  };
982
958
  }
983
- const startMillis = correlation.startMillis ?? (inBatch ? batchStart : batchEnd);
984
- const endMillis = correlation.endMillis ?? (group.end === void 0 ? startMillis : batchEnd);
985
- return {
986
- pairing: correlation.pairing,
987
- orphan: correlation.orphan,
988
- startMillis,
989
- endMillis,
990
- parent: correlation.parent ?? parentScopeRefOf(anchor),
991
- recovered: correlation.attributes ?? {}
992
- };
959
+ return { status: "resolved", identity: parsed.data };
993
960
  };
994
- var buildLifecycleSpan = (plan, resource, scope) => {
995
- const group = plan.group;
996
- const anchor = plan.anchor;
997
- const correlation = plan.correlation;
998
- const providerId = anchor.provenance.providerId;
999
- const sessionId = anchor.sessionId;
1000
- const resolved = resolvePairing(group, anchor, correlation);
1001
- const traceId = plan.traceId;
1002
- const spanId = plan.spanId;
1003
- const parentSpanId = resolved.parent === void 0 ? void 0 : deriveSpanId(providerId, sessionId, resolved.parent);
1004
- let name = group.ref.family;
1005
- let kind = SpanKind.INTERNAL;
1006
- let status = { code: SpanStatusCode.UNSET };
1007
- let attributes = {
1008
- ...identityAttributes(anchor, resource, {
1009
- traceId,
1010
- spanId,
1011
- ...parentSpanId === void 0 ? {} : { parentSpanId }
1012
- }),
1013
- ...resolved.recovered,
1014
- [ATTR_OTELHOOK_SPAN_PAIRED]: resolved.pairing !== "unpaired",
1015
- [ATTR_OTELHOOK_SPAN_PAIRING]: resolved.pairing,
1016
- [ATTR_OTELHOOK_SPAN_ORPHAN]: resolved.orphan
1017
- };
1018
- switch (group.ref.family) {
1019
- case "session": {
1020
- const end = group.end?.type === "session.end" ? group.end : void 0;
1021
- const start = group.start?.type === "session.start" ? group.start : void 0;
1022
- name = "session";
1023
- kind = SpanKind.INTERNAL;
1024
- attributes = {
1025
- ...attributes,
1026
- ...start?.agentName === void 0 ? {} : { [ATTR_OTELHOOK_AGENT_NAME]: start.agentName },
1027
- ...start?.agentVersion === void 0 ? {} : { [ATTR_OTELHOOK_AGENT_VERSION]: start.agentVersion },
1028
- ...end === void 0 ? {} : { [ATTR_OTELHOOK_OUTCOME]: end.reason },
1029
- ...usageAttributes(end?.usage, false)
1030
- };
1031
- if (end?.reason === "error" || end?.reason === "timeout") {
1032
- status = { code: SpanStatusCode.ERROR, message: end.reason };
1033
- }
1034
- break;
1035
- }
1036
- case "generation": {
1037
- const start = group.start?.type === "generation.start" ? group.start : void 0;
1038
- const end = group.end?.type === "generation.end" ? group.end : void 0;
1039
- const model = end?.model ?? start?.model;
1040
- name = model === void 0 ? "generation" : `generation ${model.modelId}`;
1041
- kind = SpanKind.CLIENT;
1042
- attributes = {
1043
- ...attributes,
1044
- [ATTR_GEN_AI_OPERATION_NAME]: "chat",
1045
- ...model?.vendor === void 0 ? {} : { [ATTR_GEN_AI_SYSTEM]: model.vendor },
1046
- ...start?.model?.modelId === void 0 ? {} : { [ATTR_GEN_AI_REQUEST_MODEL]: start.model.modelId },
1047
- ...end?.model?.modelId === void 0 ? {} : { [ATTR_GEN_AI_RESPONSE_MODEL]: end.model.modelId },
1048
- // The provider's own id for this unit of work (Cursor generation,
1049
- // Codex turn): the key a consumer stores a usage observation under.
1050
- [ATTR_OTELHOOK_GENERATION_ID]: group.ref.scopeKey,
1051
- ...end?.outcome === void 0 ? {} : { [ATTR_OTELHOOK_OUTCOME]: end.outcome },
1052
- ...usageAttributes(end?.usage, false)
1053
- };
1054
- status = outcomeStatus(end?.outcome);
1055
- break;
1056
- }
1057
- case "tool": {
1058
- const start = group.start?.type === "tool.start" ? group.start : void 0;
1059
- const end = group.end?.type === "tool.end" ? group.end : void 0;
1060
- const toolName = start?.toolName ?? end?.toolName ?? "unknown";
1061
- name = `tool ${toolName}`;
1062
- kind = SpanKind.CLIENT;
1063
- attributes = {
1064
- // Target keys are re-chosen below as one unit, never mixed across edges.
1065
- ...withoutTarget(attributes),
1066
- [ATTR_GEN_AI_TOOL_NAME]: toolName,
1067
- [ATTR_GEN_AI_TOOL_CALL_ID]: start?.toolCallId ?? end?.toolCallId ?? group.ref.scopeKey,
1068
- ...start?.toolKind === void 0 ? {} : { [ATTR_OTELHOOK_TOOL_KIND]: start.toolKind },
1069
- ...end?.outcome === void 0 ? {} : { [ATTR_OTELHOOK_OUTCOME]: end.outcome },
1070
- ...strongestTarget([
1071
- pickTarget(resolved.recovered),
1072
- start === void 0 ? {} : targetAttributes(start),
1073
- end === void 0 ? {} : targetAttributes(end)
1074
- ])
1075
- };
1076
- status = outcomeStatus(end?.outcome);
1077
- break;
1078
- }
1079
- case "subagent": {
1080
- const start = group.start?.type === "subagent.start" ? group.start : void 0;
1081
- const end = group.end?.type === "subagent.end" ? group.end : void 0;
1082
- name = "subagent";
1083
- kind = SpanKind.INTERNAL;
1084
- attributes = {
1085
- ...attributes,
1086
- ...start?.delegationDepth === void 0 ? {} : { [ATTR_OTELHOOK_DELEGATION_DEPTH]: start.delegationDepth },
1087
- ...end?.outcome === void 0 ? {} : { [ATTR_OTELHOOK_OUTCOME]: end.outcome },
1088
- ...usageAttributes(end?.usage, false)
1089
- };
1090
- status = outcomeStatus(end?.outcome);
1091
- break;
1092
- }
1093
- }
1094
- if (status.code === SpanStatusCode.ERROR) {
1095
- attributes = { ...attributes, [ATTR_ERROR_TYPE]: status.message ?? "error" };
1096
- }
1097
- return toReadableSpan({
1098
- name,
1099
- kind,
1100
- startMillis: resolved.startMillis,
1101
- endMillis: resolved.endMillis,
1102
- attributes,
1103
- status,
1104
- traceId,
1105
- spanId,
1106
- ...parentSpanId === void 0 ? {} : { parentSpanId },
1107
- resource,
1108
- instrumentationScope: scope
1109
- });
1110
- };
1111
- var buildStandaloneSpan = (event2, resource, scope) => {
1112
- const providerId = event2.provenance.providerId;
1113
- const traceId = deriveTraceId(providerId, event2.sessionId);
1114
- const spanId = deriveStandaloneSpanId(providerId, event2.sessionId, event2.type, event2.eventId);
1115
- const parent = parentScopeRefOf(event2);
1116
- const parentSpanId = parent === void 0 ? void 0 : deriveSpanId(providerId, event2.sessionId, parent);
1117
- let attributes = {
1118
- ...identityAttributes(event2, resource, {
1119
- traceId,
1120
- spanId,
1121
- ...parentSpanId === void 0 ? {} : { parentSpanId }
1122
- }),
1123
- [ATTR_OTELHOOK_SPAN_PAIRED]: true
961
+
962
+ // src/model/target.ts
963
+ import { z as z7 } from "zod";
964
+ var targetSourceSchema = z7.enum(["tool-path", "shell-cwd", "session-cwd"]);
965
+ var MAX_TARGET_HINT_PATHS = 8;
966
+ var MAX_TARGET_PATH_LENGTH = 4096;
967
+ var localPathSchema = z7.string().min(1).max(MAX_TARGET_PATH_LENGTH).refine((value) => !value.includes("\0"), "path must not contain NUL");
968
+ var targetHintSchema = z7.strictObject({
969
+ source: targetSourceSchema,
970
+ paths: z7.array(localPathSchema).min(1).max(MAX_TARGET_HINT_PATHS).readonly(),
971
+ /** Absolute directory that relative `paths` resolve against. */
972
+ baseDirectory: localPathSchema.optional()
973
+ }).readonly();
974
+ var worktreeKindSchema = z7.enum(["main", "linked"]);
975
+ var workspaceTargetSchema = z7.strictObject({
976
+ workspaceId: workspaceIdSchema,
977
+ /** Branch checked out in that worktree; absent on a detached HEAD. */
978
+ vcsBranchName: nonEmptyStringSchema.optional(),
979
+ source: targetSourceSchema,
980
+ /** `git-root` handle of the repository's main worktree; absent when there is none to name. */
981
+ repositoryId: workspaceIdSchema.optional(),
982
+ worktreeKind: worktreeKindSchema.optional()
983
+ }).readonly();
984
+ var SUBAGENT_ID_PATTERN = /^[A-Za-z0-9_.:@+=-]{1,256}$/;
985
+ var subagentIdSchema = z7.string().regex(SUBAGENT_ID_PATTERN);
986
+
987
+ // src/model/usage.ts
988
+ import { z as z8 } from "zod";
989
+ var usageTemporalitySchema = z8.enum(["delta", "cumulative"]);
990
+ var cacheCreationAccountingSchema = z8.enum([
991
+ "included-in-input",
992
+ "disjoint-from-input",
993
+ "not-reported"
994
+ ]);
995
+ var providerTotalAgreementSchema = z8.enum(["unreported", "agrees", "disagrees"]);
996
+ var usageReportSchema = z8.strictObject({
997
+ temporality: usageTemporalitySchema,
998
+ /** Inclusive input tokens. */
999
+ inputTokens: tokenCountSchema.optional(),
1000
+ /** Subset of `inputTokens` served from a prompt cache. */
1001
+ cachedInputTokens: tokenCountSchema.optional(),
1002
+ /** Tokens written to a prompt cache. */
1003
+ cacheCreationInputTokens: tokenCountSchema.optional(),
1004
+ /** Required when `cacheCreationInputTokens` is present and non-zero. */
1005
+ cacheCreationAccounting: cacheCreationAccountingSchema.optional(),
1006
+ /** Inclusive output tokens. */
1007
+ outputTokens: tokenCountSchema.optional(),
1008
+ /** Subset of `outputTokens` spent on reasoning. */
1009
+ reasoningOutputTokens: tokenCountSchema.optional(),
1010
+ /** Total exactly as the provider reported it, if it reported one. */
1011
+ providerTotalTokens: tokenCountSchema.optional()
1012
+ });
1013
+ var canonicalUsageSchema = z8.strictObject({
1014
+ temporality: usageTemporalitySchema,
1015
+ inputTokens: tokenCountSchema,
1016
+ cachedInputTokens: tokenCountSchema,
1017
+ cacheCreationInputTokens: tokenCountSchema,
1018
+ cacheCreationAccounting: cacheCreationAccountingSchema,
1019
+ outputTokens: tokenCountSchema,
1020
+ reasoningOutputTokens: tokenCountSchema,
1021
+ /** Derived: input tokens that were neither cache reads nor cache writes. */
1022
+ uncachedInputTokens: tokenCountSchema,
1023
+ /** Derived: canonical billable total. */
1024
+ totalTokens: tokenCountSchema,
1025
+ providerTotalTokens: tokenCountSchema.optional(),
1026
+ providerTotalAgreement: providerTotalAgreementSchema
1027
+ }).check((ctx) => {
1028
+ const usage = ctx.value;
1029
+ const push = (message) => {
1030
+ ctx.issues.push({ code: "custom", input: usage, message });
1124
1031
  };
1125
- let status = { code: SpanStatusCode.UNSET };
1126
- let name = event2.type;
1127
- switch (event2.type) {
1128
- case "prompt.submitted":
1129
- name = "prompt";
1130
- attributes = { ...attributes, "otelhook.prompt.source": event2.promptSource };
1131
- break;
1132
- case "compaction.performed":
1133
- name = "compaction";
1134
- attributes = {
1135
- ...attributes,
1136
- [ATTR_OTELHOOK_COMPACTION_TRIGGER]: event2.trigger,
1137
- ...usageAttributes(event2.usage, false)
1138
- };
1139
- break;
1140
- case "error.raised":
1141
- name = "error";
1142
- status = { code: SpanStatusCode.ERROR, message: event2.errorCode };
1143
- attributes = {
1144
- ...attributes,
1145
- [ATTR_ERROR_TYPE]: event2.errorCode,
1146
- "otelhook.error.phase": event2.phase,
1147
- "otelhook.error.retryable": event2.retryable
1148
- };
1149
- break;
1150
- default:
1151
- break;
1032
+ if (usage.cachedInputTokens > usage.inputTokens) {
1033
+ push("cachedInputTokens must not exceed inputTokens (it is a subset)");
1152
1034
  }
1153
- return toReadableSpan({
1154
- name,
1155
- kind: SpanKind.INTERNAL,
1156
- startMillis: event2.occurredAt,
1157
- endMillis: event2.occurredAt,
1158
- attributes,
1159
- status,
1160
- traceId,
1161
- spanId,
1162
- ...parentSpanId === void 0 ? {} : { parentSpanId },
1163
- resource,
1164
- instrumentationScope: scope
1165
- });
1166
- };
1167
- var effectiveCorrelation = (group, correlation) => {
1168
- if (correlation !== void 0 || group.end !== void 0 || group.start === void 0) {
1169
- return correlation;
1035
+ if (usage.reasoningOutputTokens > usage.outputTokens) {
1036
+ push("reasoningOutputTokens must not exceed outputTokens (it is a subset)");
1170
1037
  }
1171
- return {
1172
- providerId: group.start.provenance.providerId,
1173
- sessionId: group.start.sessionId,
1174
- ref: group.ref,
1175
- pairing: "unpaired",
1176
- orphan: "state-unavailable",
1177
- disposition: "emit",
1178
- spanIdDiscriminator: group.start.eventId
1179
- };
1180
- };
1181
- var layoutBatch = (events) => {
1182
- const groups = /* @__PURE__ */ new Map();
1183
- const standalone = [];
1184
- const groupOf = /* @__PURE__ */ new Map();
1185
- for (const event2 of events) {
1186
- const ref = spanScopeRefOf(event2);
1187
- if (ref === void 0) {
1188
- standalone.push(event2);
1189
- continue;
1190
- }
1191
- const groupKey = correlationKey(event2.provenance.providerId, event2.sessionId, ref);
1192
- const group = groups.get(groupKey) ?? { ref };
1193
- if (event2.type.endsWith(".start")) {
1194
- group.start = event2;
1195
- } else {
1196
- group.end = event2;
1197
- }
1198
- groups.set(groupKey, group);
1199
- groupOf.set(event2.eventId, groupKey);
1038
+ if (usage.cacheCreationAccounting === "not-reported" && usage.cacheCreationInputTokens !== 0) {
1039
+ push("cacheCreationInputTokens must be 0 when cacheCreationAccounting is not-reported");
1200
1040
  }
1201
- return { groups, standalone, groupOf };
1202
- };
1203
- var indexCorrelations = (correlations) => {
1204
- const indexed = /* @__PURE__ */ new Map();
1205
- for (const correlation of correlations ?? []) {
1206
- indexed.set(
1207
- correlationKey(correlation.providerId, correlation.sessionId, correlation.ref),
1208
- correlation
1041
+ const creationInsideInput = usage.cacheCreationAccounting === "included-in-input" ? usage.cacheCreationInputTokens : 0;
1042
+ if (usage.cachedInputTokens + creationInsideInput > usage.inputTokens) {
1043
+ push(
1044
+ "cachedInputTokens + cacheCreationInputTokens must not exceed inputTokens when cache creation is included in input"
1209
1045
  );
1210
1046
  }
1211
- return indexed;
1212
- };
1213
- var planGroup = (group, correlation, correlationAvailable) => {
1214
- const anchor = group.start ?? group.end;
1215
- if (anchor === void 0) {
1216
- return void 0;
1047
+ const expectedUncached = usage.inputTokens - usage.cachedInputTokens - creationInsideInput;
1048
+ if (expectedUncached >= 0 && usage.uncachedInputTokens !== expectedUncached) {
1049
+ push(`uncachedInputTokens must equal ${expectedUncached}`);
1217
1050
  }
1218
- const providerId = anchor.provenance.providerId;
1219
- const sessionId = anchor.sessionId;
1220
- const durablyRecorded = group.end === void 0 && (correlation?.disposition === "defer" || // No correlator wired at all: cross-process pairing was never on offer, so
1221
- // this is the documented no-state-root degradation rather than a failure to
1222
- // persist something that should have been persisted.
1223
- correlation === void 0 && correlationAvailable === void 0);
1224
- const effective = durablyRecorded ? correlation : effectiveCorrelation(group, correlation);
1225
- const discriminator = durablyRecorded ? void 0 : effective?.spanIdDiscriminator;
1226
- return {
1227
- group,
1228
- anchor,
1229
- emits: !durablyRecorded,
1230
- correlation: effective,
1231
- traceId: deriveTraceId(providerId, sessionId),
1232
- spanId: discriminator === void 0 ? deriveSpanId(providerId, sessionId, group.ref) : digestHex(
1233
- [
1234
- "otelhook/span",
1235
- providerId,
1236
- sessionId,
1237
- group.ref.family,
1238
- group.ref.scopeKey,
1239
- discriminator
1240
- ],
1241
- 16
1242
- )
1243
- };
1244
- };
1245
- var canonicalEventTraceIdentities = (events, options = {}) => {
1246
- const layout = layoutBatch(events);
1247
- const correlations = indexCorrelations(options.correlations);
1248
- const plans = /* @__PURE__ */ new Map();
1249
- for (const [groupKey, group] of layout.groups) {
1250
- const plan = planGroup(group, correlations.get(groupKey), options.correlationAvailable);
1251
- if (plan !== void 0) {
1252
- plans.set(groupKey, plan);
1253
- }
1051
+ const creationOutsideInput = usage.cacheCreationAccounting === "disjoint-from-input" ? usage.cacheCreationInputTokens : 0;
1052
+ const expectedTotal = usage.inputTokens + creationOutsideInput + usage.outputTokens;
1053
+ if (usage.totalTokens !== expectedTotal) {
1054
+ push(`totalTokens must equal ${expectedTotal}`);
1254
1055
  }
1255
- const identities = /* @__PURE__ */ new Map();
1256
- for (const event2 of events) {
1257
- const providerId = event2.provenance.providerId;
1258
- const groupKey = layout.groupOf.get(event2.eventId);
1259
- const plan = groupKey === void 0 ? void 0 : plans.get(groupKey);
1260
- if (plan === void 0) {
1261
- const parent2 = parentScopeRefOf(event2);
1262
- identities.set(event2.eventId, {
1263
- traceId: deriveTraceId(providerId, event2.sessionId),
1264
- spanId: deriveStandaloneSpanId(providerId, event2.sessionId, event2.type, event2.eventId),
1265
- ...parent2 === void 0 ? {} : { parentSpanId: deriveSpanId(providerId, event2.sessionId, parent2) }
1266
- });
1267
- continue;
1056
+ const expectedAgreement = usage.providerTotalTokens === void 0 ? "unreported" : usage.providerTotalTokens === expectedTotal ? "agrees" : "disagrees";
1057
+ if (usage.providerTotalAgreement !== expectedAgreement) {
1058
+ push(`providerTotalAgreement must be ${expectedAgreement}`);
1059
+ }
1060
+ });
1061
+ var normalizeUsage = (report) => {
1062
+ const parsed = usageReportSchema.safeParse(report);
1063
+ if (!parsed.success) {
1064
+ return {
1065
+ status: "invalid",
1066
+ issues: parsed.error.issues.map((issue) => ({
1067
+ code: "invalid-report",
1068
+ message: `${issue.path.join(".") || "<root>"}: ${issue.message}`
1069
+ }))
1070
+ };
1071
+ }
1072
+ const input = parsed.data;
1073
+ const issues = [];
1074
+ const notes = [];
1075
+ const inputTokens = input.inputTokens ?? 0;
1076
+ const cachedInputTokens = input.cachedInputTokens ?? 0;
1077
+ const cacheCreationInputTokens = input.cacheCreationInputTokens ?? 0;
1078
+ const outputTokens = input.outputTokens ?? 0;
1079
+ const reasoningOutputTokens = input.reasoningOutputTokens ?? 0;
1080
+ let accounting;
1081
+ if (cacheCreationInputTokens === 0) {
1082
+ accounting = input.cacheCreationAccounting ?? "not-reported";
1083
+ if (accounting !== "not-reported") {
1084
+ notes.push(
1085
+ `cacheCreationAccounting=${accounting} retained with zero cache-creation tokens`
1086
+ );
1268
1087
  }
1269
- const parent = plan.correlation?.parent ?? parentScopeRefOf(event2);
1270
- identities.set(event2.eventId, {
1271
- traceId: plan.traceId,
1272
- spanId: plan.spanId,
1273
- ...parent === void 0 ? {} : { parentSpanId: deriveSpanId(providerId, event2.sessionId, parent) }
1088
+ } else if (input.cacheCreationAccounting === void 0) {
1089
+ issues.push({
1090
+ code: "cache-creation-accounting-missing",
1091
+ message: "cacheCreationAccounting is required when cacheCreationInputTokens is non-zero; it cannot be inferred"
1092
+ });
1093
+ accounting = "not-reported";
1094
+ } else if (input.cacheCreationAccounting === "not-reported") {
1095
+ issues.push({
1096
+ code: "cache-creation-accounting-missing",
1097
+ message: "cacheCreationAccounting=not-reported conflicts with non-zero cacheCreationInputTokens"
1274
1098
  });
1099
+ accounting = "not-reported";
1100
+ } else {
1101
+ accounting = input.cacheCreationAccounting;
1275
1102
  }
1276
- return identities;
1277
- };
1278
- var canonicalEventsToReadableSpans = (events, options) => {
1279
- const scope = options.instrumentationScope ?? DEFAULT_INSTRUMENTATION_SCOPE;
1280
- const layout = layoutBatch(events);
1281
- const correlations = indexCorrelations(options.correlations);
1282
- const spans = [];
1283
- for (const [groupKey, group] of layout.groups) {
1284
- const plan = planGroup(group, correlations.get(groupKey), options.correlationAvailable);
1285
- if (plan === void 0 || !plan.emits) {
1286
- continue;
1287
- }
1288
- spans.push(buildLifecycleSpan(plan, options.resource, scope));
1103
+ if (cachedInputTokens > inputTokens) {
1104
+ issues.push({
1105
+ code: "cached-exceeds-input",
1106
+ message: `cachedInputTokens (${cachedInputTokens}) exceeds inclusive inputTokens (${inputTokens})`
1107
+ });
1289
1108
  }
1290
- for (const event2 of layout.standalone) {
1291
- spans.push(buildStandaloneSpan(event2, options.resource, scope));
1109
+ if (reasoningOutputTokens > outputTokens) {
1110
+ issues.push({
1111
+ code: "reasoning-exceeds-output",
1112
+ message: `reasoningOutputTokens (${reasoningOutputTokens}) exceeds inclusive outputTokens (${outputTokens})`
1113
+ });
1292
1114
  }
1293
- return spans;
1294
- };
1295
-
1296
- // src/lifecycle/span-correlator.ts
1297
- var SPAN_RECORD_VERSION = 2;
1298
- var DEFAULT_MAX_START_AGE_MILLIS = 24 * 60 * 60 * 1e3;
1299
- var ATTRIBUTE_PREFIX = "a:";
1300
- var SPAN_FAMILIES = ["session", "generation", "tool", "subagent"];
1301
- var isSpanFamily = (value) => typeof value === "string" && SPAN_FAMILIES.includes(value);
1302
- var optionalNumber = (value) => typeof value === "number" && Number.isFinite(value) ? value : void 0;
1303
- var optionalString = (value) => typeof value === "string" && value.length > 0 ? value : void 0;
1304
- var encodeAttributes = (attributes) => {
1305
- const encoded = {};
1306
- let count = 0;
1307
- for (const [key, value] of Object.entries(attributes ?? {})) {
1308
- if (count >= MAX_RECOVERED_START_ATTRIBUTES) {
1309
- break;
1310
- }
1311
- const encodedKey = `${ATTRIBUTE_PREFIX}${key}`;
1312
- if (encodedKey.length > MAX_IDENTIFIER_LENGTH) {
1313
- continue;
1314
- }
1315
- if (typeof value === "string") {
1316
- encoded[encodedKey] = value.slice(0, MAX_ATTRIBUTE_STRING_LENGTH);
1317
- } else if (typeof value === "number" && Number.isFinite(value)) {
1318
- encoded[encodedKey] = value;
1319
- } else if (typeof value === "boolean") {
1320
- encoded[encodedKey] = value;
1321
- } else {
1322
- continue;
1323
- }
1324
- count += 1;
1115
+ const creationInsideInput = accounting === "included-in-input" ? cacheCreationInputTokens : 0;
1116
+ if (cachedInputTokens + creationInsideInput > inputTokens) {
1117
+ issues.push({
1118
+ code: "cache-creation-exceeds-input",
1119
+ message: `cachedInputTokens + cacheCreationInputTokens (${cachedInputTokens + creationInsideInput}) exceeds inclusive inputTokens (${inputTokens})`
1120
+ });
1325
1121
  }
1326
- return encoded;
1327
- };
1328
- var decodeAttributes = (attributes) => {
1329
- const decoded = {};
1330
- let count = 0;
1331
- for (const [key, value] of Object.entries(attributes)) {
1332
- if (!key.startsWith(ATTRIBUTE_PREFIX) || count >= MAX_RECOVERED_START_ATTRIBUTES) {
1333
- continue;
1334
- }
1335
- if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
1336
- decoded[key.slice(ATTRIBUTE_PREFIX.length)] = value;
1337
- count += 1;
1338
- }
1122
+ if (issues.length > 0) {
1123
+ return { status: "invalid", issues };
1339
1124
  }
1340
- return count === 0 ? void 0 : decoded;
1125
+ const creationOutsideInput = accounting === "disjoint-from-input" ? cacheCreationInputTokens : 0;
1126
+ const totalTokens = inputTokens + creationOutsideInput + outputTokens;
1127
+ const providerTotalAgreement = input.providerTotalTokens === void 0 ? "unreported" : input.providerTotalTokens === totalTokens ? "agrees" : "disagrees";
1128
+ if (providerTotalAgreement === "disagrees") {
1129
+ notes.push(
1130
+ `providerTotalTokens (${input.providerTotalTokens ?? 0}) disagrees with canonical total (${totalTokens}); both retained`
1131
+ );
1132
+ }
1133
+ const usage = {
1134
+ temporality: input.temporality,
1135
+ inputTokens,
1136
+ cachedInputTokens,
1137
+ cacheCreationInputTokens,
1138
+ cacheCreationAccounting: accounting,
1139
+ outputTokens,
1140
+ reasoningOutputTokens,
1141
+ uncachedInputTokens: inputTokens - cachedInputTokens - creationInsideInput,
1142
+ totalTokens,
1143
+ ...input.providerTotalTokens === void 0 ? {} : { providerTotalTokens: input.providerTotalTokens },
1144
+ providerTotalAgreement
1145
+ };
1146
+ return { status: "ok", usage, notes };
1341
1147
  };
1342
- var encodeRecord = (record) => ({
1343
- kind: "attributes",
1344
- attributes: {
1345
- v: SPAN_RECORD_VERSION,
1346
- providerId: record.providerId,
1347
- ...record.startEventId === void 0 ? {} : { startEventId: record.startEventId },
1348
- ...record.startedAt === void 0 ? {} : { startedAt: record.startedAt },
1349
- ...record.endEventId === void 0 ? {} : { endEventId: record.endEventId },
1350
- ...record.endedAt === void 0 ? {} : { endedAt: record.endedAt },
1351
- ...record.exported === true ? { exported: true } : {},
1352
- ...record.parent === void 0 ? {} : { parentFamily: record.parent.family, parentScopeKey: record.parent.scopeKey },
1353
- ...encodeAttributes(record.attributes)
1148
+ var UsageNormalizationError = class extends Error {
1149
+ issues;
1150
+ constructor(issues) {
1151
+ super(`invalid usage report: ${issues.map((issue) => issue.message).join("; ")}`);
1152
+ this.name = "UsageNormalizationError";
1153
+ this.issues = issues;
1354
1154
  }
1355
- });
1356
- var decodeRecord = (attributes) => {
1357
- if (attributes["v"] !== SPAN_RECORD_VERSION) {
1358
- return { kind: "incompatible" };
1155
+ };
1156
+ var normalizeUsageOrThrow = (report) => {
1157
+ const result = normalizeUsage(report);
1158
+ if (result.status === "invalid") {
1159
+ throw new UsageNormalizationError(result.issues);
1359
1160
  }
1360
- const providerId = optionalString(attributes["providerId"]);
1361
- if (providerId === void 0) {
1362
- return { kind: "corrupt" };
1161
+ return result.usage;
1162
+ };
1163
+ var EMPTY_DELTA_USAGE = Object.freeze(
1164
+ normalizeUsageOrThrow({ temporality: "delta" })
1165
+ );
1166
+ var requireCumulative = (usage, label) => {
1167
+ if (usage.temporality !== "cumulative") {
1168
+ throw new UsageNormalizationError([
1169
+ { code: "invalid-report", message: `${label} must have cumulative temporality` }
1170
+ ]);
1363
1171
  }
1364
- const startedAt = optionalNumber(attributes["startedAt"]);
1365
- const startEventId = optionalString(attributes["startEventId"]);
1366
- if (startedAt === void 0 !== (startEventId === void 0)) {
1367
- return { kind: "corrupt" };
1172
+ };
1173
+ var cumulativeToDelta = (previous, current) => {
1174
+ requireCumulative(previous, "previous usage");
1175
+ requireCumulative(current, "current usage");
1176
+ if (previous.cacheCreationAccounting !== current.cacheCreationAccounting && previous.cacheCreationInputTokens !== 0 && current.cacheCreationInputTokens !== 0) {
1177
+ throw new UsageNormalizationError([
1178
+ {
1179
+ code: "cache-creation-accounting-missing",
1180
+ message: "cannot diff cumulative usage across differing cacheCreationAccounting modes"
1181
+ }
1182
+ ]);
1368
1183
  }
1369
- const endedAt = optionalNumber(attributes["endedAt"]);
1370
- const endEventId = optionalString(attributes["endEventId"]);
1371
- if (endedAt === void 0 !== (endEventId === void 0)) {
1372
- return { kind: "corrupt" };
1184
+ const resetDetected = current.inputTokens < previous.inputTokens || current.cachedInputTokens < previous.cachedInputTokens || current.cacheCreationInputTokens < previous.cacheCreationInputTokens || current.outputTokens < previous.outputTokens || current.reasoningOutputTokens < previous.reasoningOutputTokens;
1185
+ if (resetDetected) {
1186
+ return {
1187
+ usage: normalizeUsageOrThrow({ ...toReport(current), temporality: "delta" }),
1188
+ resetDetected: true
1189
+ };
1373
1190
  }
1374
- const exported = attributes["exported"] === true;
1375
- const parentFamily = attributes["parentFamily"];
1376
- const parentScopeKey = optionalString(attributes["parentScopeKey"]);
1377
- const parent = isSpanFamily(parentFamily) && parentScopeKey !== void 0 ? { family: parentFamily, scopeKey: parentScopeKey } : void 0;
1378
- const decodedAttributes = decodeAttributes(attributes);
1379
- return {
1380
- kind: "present",
1381
- record: {
1382
- providerId,
1383
- ...startEventId === void 0 ? {} : { startEventId },
1384
- ...startedAt === void 0 ? {} : { startedAt },
1385
- ...endEventId === void 0 ? {} : { endEventId },
1386
- ...endedAt === void 0 ? {} : { endedAt },
1387
- ...parent === void 0 ? {} : { parent },
1388
- ...exported ? { exported: true } : {},
1389
- ...decodedAttributes === void 0 ? {} : { attributes: decodedAttributes }
1390
- }
1391
- };
1191
+ const usage = normalizeUsageOrThrow({
1192
+ temporality: "delta",
1193
+ inputTokens: current.inputTokens - previous.inputTokens,
1194
+ cachedInputTokens: current.cachedInputTokens - previous.cachedInputTokens,
1195
+ cacheCreationInputTokens: current.cacheCreationInputTokens - previous.cacheCreationInputTokens,
1196
+ cacheCreationAccounting: current.cacheCreationAccounting,
1197
+ outputTokens: current.outputTokens - previous.outputTokens,
1198
+ reasoningOutputTokens: current.reasoningOutputTokens - previous.reasoningOutputTokens
1199
+ });
1200
+ return { usage, resetDetected: false };
1392
1201
  };
1393
- var factsOf = (record) => ({
1394
- ...record.startedAt === void 0 ? {} : { startedAt: record.startedAt },
1395
- ...record.endedAt === void 0 ? {} : { endedAt: record.endedAt },
1396
- ...record.parent === void 0 ? {} : { parent: record.parent },
1397
- ...record.attributes === void 0 ? {} : { attributes: record.attributes }
1202
+ var toReport = (usage) => ({
1203
+ temporality: usage.temporality,
1204
+ inputTokens: usage.inputTokens,
1205
+ cachedInputTokens: usage.cachedInputTokens,
1206
+ cacheCreationInputTokens: usage.cacheCreationInputTokens,
1207
+ cacheCreationAccounting: usage.cacheCreationAccounting,
1208
+ outputTokens: usage.outputTokens,
1209
+ reasoningOutputTokens: usage.reasoningOutputTokens,
1210
+ ...usage.providerTotalTokens === void 0 ? {} : { providerTotalTokens: usage.providerTotalTokens }
1398
1211
  });
1399
- var correlationTimesOf = (facts, options = { withStart: true }) => ({
1400
- ...facts.startedAt === void 0 || !options.withStart ? {} : { startMillis: facts.startedAt },
1401
- ...facts.endedAt === void 0 ? {} : { endMillis: facts.endedAt },
1402
- ...facts.parent === void 0 ? {} : { parent: facts.parent },
1403
- ...facts.attributes === void 0 ? {} : { attributes: facts.attributes }
1212
+
1213
+ // src/model/version.ts
1214
+ import { z as z9 } from "zod";
1215
+ var CANONICAL_SCHEMA_VERSION = 1;
1216
+ var canonicalSchemaVersionSchema = z9.literal(CANONICAL_SCHEMA_VERSION);
1217
+
1218
+ // src/model/events.ts
1219
+ var modelDescriptorSchema = z10.strictObject({
1220
+ modelId: nonEmptyStringSchema,
1221
+ /** Vendor of the model, e.g. `anthropic`. Distinct from the agent provider. */
1222
+ vendor: nonEmptyStringSchema.optional(),
1223
+ family: nonEmptyStringSchema.optional()
1404
1224
  });
1405
- var orphanClassificationOf = (reason) => {
1406
- switch (reason) {
1407
- case "no-start-recorded":
1408
- return "missing-start";
1409
- case "start-expired":
1410
- return "expired-start";
1411
- case "already-closed":
1412
- return "already-closed";
1413
- case "provider-mismatch":
1414
- return "provider-mismatch";
1415
- case "state-incompatible":
1416
- return "state-incompatible";
1417
- case "state-corrupt":
1418
- return "state-corrupt";
1419
- }
1225
+ var costFactsSchema = z10.strictObject({
1226
+ /** ISO 4217 code. */
1227
+ currency: z10.string().length(3),
1228
+ amount: z10.number().min(0).finite(),
1229
+ source: z10.enum(["provider-reported", "computed"])
1230
+ });
1231
+ var canonicalEventTypeSchema = z10.enum([
1232
+ "session.start",
1233
+ "session.end",
1234
+ "prompt.submitted",
1235
+ "generation.start",
1236
+ "generation.end",
1237
+ "tool.start",
1238
+ "tool.end",
1239
+ "subagent.start",
1240
+ "subagent.end",
1241
+ "compaction.performed",
1242
+ "error.raised"
1243
+ ]);
1244
+ var CANONICAL_EVENT_TYPES = canonicalEventTypeSchema.options;
1245
+ var outcomeSchema = z10.enum(["ok", "error", "cancelled", "timeout", "denied", "unknown"]);
1246
+ var baseEventFields = {
1247
+ schemaVersion: canonicalSchemaVersionSchema,
1248
+ eventId: eventIdSchema,
1249
+ invocationId: invocationIdSchema,
1250
+ sessionId: sessionIdSchema,
1251
+ /** Per-invocation ordering key. Stable across replays of the same input. */
1252
+ sequence: sequenceNumberSchema,
1253
+ occurredAt: epochMillisSchema,
1254
+ provenance: sourceProvenanceSchema,
1255
+ workspace: workspaceIdentitySchema,
1256
+ /**
1257
+ * The provider's own id for the subagent this event was emitted inside (e.g.
1258
+ * Claude Code's `agent_id`). Absent for the top-level agent. Set by the event
1259
+ * factory, never by hand.
1260
+ */
1261
+ subagentId: subagentIdSchema.optional(),
1262
+ extensions: extensionsSchema.default(emptyExtensions)
1420
1263
  };
1421
- var createSpanCorrelator = (deps) => {
1422
- const { stateStore, clock } = deps;
1423
- const maxStartAgeMillis = deps.maxStartAgeMillis ?? DEFAULT_MAX_START_AGE_MILLIS;
1424
- const keyFor = (input) => spanKey(input.sessionId, input.providerId, input.scope, input.scopeKey);
1425
- const readRecord = async (key) => {
1426
- const existing = await stateStore.read(key);
1427
- if (existing === void 0) {
1428
- return { kind: "absent" };
1429
- }
1430
- if (existing.value.kind !== "attributes") {
1431
- await stateStore.delete(key);
1432
- return { kind: "corrupt" };
1433
- }
1434
- const decoded = decodeRecord(existing.value.attributes);
1435
- if (decoded.kind === "corrupt" || decoded.kind === "incompatible") {
1436
- await stateStore.delete(key);
1437
- }
1438
- return decoded;
1439
- };
1440
- const recordStart = (input) => withOptionalSessionLock(stateStore, input.sessionId, async () => {
1441
- const key = keyFor(input);
1442
- const decoded = await readRecord(key);
1443
- if (decoded.kind === "present") {
1444
- const existing = decoded.record;
1445
- if (existing.providerId !== input.providerId) {
1446
- return { status: "conflict", reason: "provider-mismatch" };
1447
- }
1448
- if (existing.startEventId === input.eventId) {
1449
- return { status: "duplicate", facts: factsOf(existing) };
1450
- }
1451
- if (existing.startEventId === void 0 && existing.endEventId !== void 0) {
1452
- const completed = {
1453
- ...existing,
1454
- startEventId: input.eventId,
1455
- startedAt: input.occurredAt,
1456
- ...input.parent === void 0 ? {} : { parent: input.parent },
1457
- ...input.attributes === void 0 ? {} : { attributes: input.attributes }
1458
- };
1459
- await stateStore.write(key, encodeRecord(completed));
1460
- return existing.exported === true ? { status: "published", facts: factsOf(completed) } : { status: "recorded", facts: factsOf(completed) };
1461
- }
1462
- }
1463
- const fresh = {
1464
- providerId: input.providerId,
1465
- startEventId: input.eventId,
1466
- startedAt: input.occurredAt,
1467
- ...input.parent === void 0 ? {} : { parent: input.parent },
1468
- ...input.attributes === void 0 ? {} : { attributes: input.attributes }
1469
- };
1470
- await stateStore.write(key, encodeRecord(fresh));
1471
- return { status: "recorded", facts: factsOf(fresh) };
1472
- });
1473
- const recordEnd = (input) => withOptionalSessionLock(stateStore, input.sessionId, async () => {
1474
- const key = keyFor(input);
1475
- const decoded = await readRecord(key);
1476
- if (decoded.kind === "incompatible" || decoded.kind === "corrupt") {
1477
- const reason = decoded.kind === "incompatible" ? "state-incompatible" : "state-corrupt";
1478
- return { status: "orphaned", reason, facts: { endedAt: input.occurredAt } };
1479
- }
1480
- if (decoded.kind === "absent") {
1481
- const endOnly = {
1482
- providerId: input.providerId,
1483
- endEventId: input.eventId,
1484
- endedAt: input.occurredAt,
1485
- // This end is about to be exported as an orphan under the scope's
1486
- // canonical span id, so a start arriving later must not reuse it.
1487
- exported: true
1488
- };
1489
- await stateStore.write(key, encodeRecord(endOnly));
1490
- return { status: "orphaned", reason: "no-start-recorded", facts: factsOf(endOnly) };
1491
- }
1492
- const existing = decoded.record;
1493
- if (existing.providerId !== input.providerId) {
1494
- return {
1495
- status: "orphaned",
1496
- reason: "provider-mismatch",
1497
- facts: { endedAt: input.occurredAt }
1498
- };
1499
- }
1500
- if (existing.endEventId === input.eventId) {
1501
- return { status: "duplicate", facts: factsOf(existing) };
1502
- }
1503
- if (existing.endEventId !== void 0) {
1504
- return {
1505
- status: "orphaned",
1506
- reason: "already-closed",
1507
- facts: { endedAt: input.occurredAt }
1508
- };
1509
- }
1510
- if (existing.startedAt === void 0) {
1511
- const replaced = {
1512
- ...existing,
1513
- endEventId: input.eventId,
1514
- endedAt: input.occurredAt,
1515
- exported: true
1516
- };
1517
- await stateStore.write(key, encodeRecord(replaced));
1518
- return { status: "orphaned", reason: "no-start-recorded", facts: factsOf(replaced) };
1519
- }
1520
- if (input.occurredAt - existing.startedAt > maxStartAgeMillis) {
1521
- await stateStore.delete(key);
1522
- return { status: "orphaned", reason: "start-expired", facts: { endedAt: input.occurredAt } };
1523
- }
1524
- const closed = {
1525
- ...existing,
1526
- endEventId: input.eventId,
1527
- endedAt: input.occurredAt,
1528
- exported: true
1529
- };
1530
- await stateStore.write(key, encodeRecord(closed));
1531
- return {
1532
- status: "matched",
1533
- startedAt: existing.startedAt,
1534
- durationMillis: Math.max(0, input.occurredAt - existing.startedAt),
1535
- facts: factsOf(closed)
1536
- };
1537
- });
1538
- const correlateGroup = async (group) => {
1539
- const base = {
1540
- providerId: group.providerId,
1541
- sessionId: group.sessionId,
1542
- ref: group.ref
1543
- };
1544
- const unpaired = (orphan, facts) => ({
1545
- ...base,
1546
- pairing: "unpaired",
1547
- orphan,
1548
- // An unpaired span has no trustworthy start, so a start time is the one
1549
- // fact it must not carry; everything else recovered is still true.
1550
- ...correlationTimesOf(facts, { withStart: false })
1551
- });
1552
- let startFacts;
1553
- if (group.start !== void 0) {
1554
- const parent = parentScopeRefOf(group.start);
1555
- const result2 = await recordStart({
1556
- sessionId: group.sessionId,
1557
- providerId: group.providerId,
1558
- scope: group.ref.family,
1559
- scopeKey: group.ref.scopeKey,
1560
- eventId: group.start.eventId,
1561
- occurredAt: group.start.occurredAt,
1562
- ...parent === void 0 ? {} : { parent },
1563
- attributes: startOnlySpanAttributes(group.start)
1564
- });
1565
- if (result2.status === "conflict") {
1566
- return unpaired("provider-mismatch", {});
1567
- }
1568
- if (result2.status === "published" && group.end === void 0) {
1569
- return { ...unpaired("already-closed", result2.facts), disposition: "defer" };
1570
- }
1571
- startFacts = result2.facts;
1572
- }
1573
- if (group.end === void 0) {
1574
- const facts = startFacts ?? {};
1575
- if (facts.endedAt !== void 0) {
1576
- return {
1577
- ...base,
1578
- pairing: "cross-process",
1579
- orphan: "none",
1580
- disposition: "emit",
1581
- ...correlationTimesOf(facts)
1582
- };
1583
- }
1584
- return { ...unpaired("missing-end", facts), disposition: "defer" };
1585
- }
1586
- const result = await recordEnd({
1587
- sessionId: group.sessionId,
1588
- providerId: group.providerId,
1589
- scope: group.ref.family,
1590
- scopeKey: group.ref.scopeKey,
1591
- eventId: group.end.eventId,
1592
- occurredAt: group.end.occurredAt
1593
- });
1594
- if (result.status === "orphaned") {
1595
- const orphan = orphanClassificationOf(result.reason);
1596
- return orphan === "already-closed" ? {
1597
- ...unpaired(orphan, result.facts),
1598
- disposition: "emit",
1599
- spanIdDiscriminator: group.end.eventId
1600
- } : { ...unpaired(orphan, result.facts), disposition: "emit" };
1601
- }
1602
- if (result.status === "duplicate" && result.facts.startedAt === void 0) {
1603
- return { ...unpaired("missing-start", result.facts), disposition: "emit" };
1604
- }
1605
- return {
1606
- ...base,
1607
- pairing: group.start === void 0 ? "cross-process" : "in-batch",
1608
- orphan: "none",
1609
- disposition: "emit",
1610
- ...correlationTimesOf(result.facts)
1611
- };
1612
- };
1613
- const correlateBatch = async (events) => {
1614
- const groups = /* @__PURE__ */ new Map();
1615
- for (const event2 of events) {
1616
- const ref = spanScopeRefOf(event2);
1617
- if (ref === void 0) {
1618
- continue;
1619
- }
1620
- const providerId = event2.provenance.providerId;
1621
- const groupKey = [providerId, event2.sessionId, ref.family, ref.scopeKey].join("\0");
1622
- const group = groups.get(groupKey) ?? {
1623
- providerId,
1624
- sessionId: event2.sessionId,
1625
- ref
1626
- };
1627
- if (event2.type.endsWith(".start")) {
1628
- group.start = event2;
1629
- } else {
1630
- group.end = event2;
1631
- }
1632
- groups.set(groupKey, group);
1633
- }
1634
- const correlations = [];
1635
- for (const group of groups.values()) {
1636
- try {
1637
- correlations.push(await correlateGroup(group));
1638
- } catch {
1639
- const unrecordedStart = group.start !== void 0 && group.end === void 0;
1640
- correlations.push({
1641
- providerId: group.providerId,
1642
- sessionId: group.sessionId,
1643
- ref: group.ref,
1644
- pairing: "unpaired",
1645
- orphan: "state-unavailable",
1646
- disposition: "emit",
1647
- ...unrecordedStart && group.start !== void 0 ? { spanIdDiscriminator: group.start.eventId } : {}
1648
- });
1649
- }
1650
- }
1651
- return correlations;
1264
+ var event = (shape) => z10.strictObject({ ...baseEventFields, ...shape });
1265
+ var sessionStartEventSchema = event({
1266
+ type: z10.literal("session.start"),
1267
+ sessionKind: z10.enum(["interactive", "non-interactive", "unknown"]),
1268
+ agentName: nonEmptyStringSchema.optional(),
1269
+ agentVersion: nonEmptyStringSchema.optional(),
1270
+ model: modelDescriptorSchema.optional(),
1271
+ /** The git worktree the session runs in, resolved by the core (ADR 0008). */
1272
+ target: workspaceTargetSchema.optional()
1273
+ });
1274
+ var sessionEndEventSchema = event({
1275
+ type: z10.literal("session.end"),
1276
+ reason: z10.enum(["completed", "aborted", "error", "timeout", "unknown"]),
1277
+ durationMillis: durationMillisSchema.optional(),
1278
+ /** Session totals, typically cumulative. */
1279
+ usage: canonicalUsageSchema.optional(),
1280
+ cost: costFactsSchema.optional()
1281
+ });
1282
+ var promptSubmittedEventSchema = event({
1283
+ type: z10.literal("prompt.submitted"),
1284
+ promptSource: z10.enum(["user", "automation", "resumed", "unknown"]),
1285
+ content: contentFactSchema.optional(),
1286
+ turnIndex: z10.number().int().min(0).optional(),
1287
+ /** The git worktree the session runs in, resolved by the core (ADR 0008). */
1288
+ target: workspaceTargetSchema.optional()
1289
+ });
1290
+ var generationStartEventSchema = event({
1291
+ type: z10.literal("generation.start"),
1292
+ generationId: nonEmptyStringSchema,
1293
+ model: modelDescriptorSchema,
1294
+ requestedMaxOutputTokens: tokenCountSchema.optional(),
1295
+ inputContent: contentFactsSchema.optional()
1296
+ });
1297
+ var generationEndEventSchema = event({
1298
+ type: z10.literal("generation.end"),
1299
+ generationId: nonEmptyStringSchema,
1300
+ model: modelDescriptorSchema,
1301
+ outcome: outcomeSchema,
1302
+ stopReason: nonEmptyStringSchema.optional(),
1303
+ durationMillis: durationMillisSchema.optional(),
1304
+ usage: canonicalUsageSchema.optional(),
1305
+ cost: costFactsSchema.optional(),
1306
+ outputContent: contentFactsSchema.optional()
1307
+ });
1308
+ var toolKindSchema = z10.enum([
1309
+ "read",
1310
+ "write",
1311
+ "execute",
1312
+ "search",
1313
+ "network",
1314
+ "delegate",
1315
+ "other",
1316
+ "unknown"
1317
+ ]);
1318
+ var toolStartEventSchema = event({
1319
+ type: z10.literal("tool.start"),
1320
+ toolCallId: nonEmptyStringSchema,
1321
+ toolName: nonEmptyStringSchema,
1322
+ toolKind: toolKindSchema,
1323
+ generationId: nonEmptyStringSchema.optional(),
1324
+ input: contentFactSchema.optional(),
1325
+ /** The git worktree this call targeted, resolved by the core (ADR 0008). */
1326
+ target: workspaceTargetSchema.optional()
1327
+ });
1328
+ var toolEndEventSchema = event({
1329
+ type: z10.literal("tool.end"),
1330
+ toolCallId: nonEmptyStringSchema,
1331
+ toolName: nonEmptyStringSchema,
1332
+ outcome: outcomeSchema,
1333
+ durationMillis: durationMillisSchema.optional(),
1334
+ /** Present when the host asked for or recorded a permission decision. */
1335
+ permissionDecision: z10.enum(["allowed", "denied", "deferred", "not-required"]).optional(),
1336
+ output: contentFactSchema.optional(),
1337
+ /** The git worktree this call targeted, resolved by the core (ADR 0008). */
1338
+ target: workspaceTargetSchema.optional()
1339
+ });
1340
+ var subagentStartEventSchema = event({
1341
+ type: z10.literal("subagent.start"),
1342
+ subagentInvocationId: invocationIdSchema,
1343
+ subagentType: nonEmptyStringSchema.optional(),
1344
+ /** 0 for the top-level agent; 1 for its direct children. */
1345
+ delegationDepth: z10.number().int().min(0).max(64),
1346
+ model: modelDescriptorSchema.optional()
1347
+ });
1348
+ var subagentEndEventSchema = event({
1349
+ type: z10.literal("subagent.end"),
1350
+ subagentInvocationId: invocationIdSchema,
1351
+ outcome: outcomeSchema,
1352
+ durationMillis: durationMillisSchema.optional(),
1353
+ usage: canonicalUsageSchema.optional()
1354
+ });
1355
+ var compactionPerformedEventSchema = event({
1356
+ type: z10.literal("compaction.performed"),
1357
+ trigger: z10.enum(["automatic", "manual", "unknown"]),
1358
+ /** Provider-reported context size before and after compaction, if known. */
1359
+ contextTokensBefore: tokenCountSchema.optional(),
1360
+ contextTokensAfter: tokenCountSchema.optional(),
1361
+ droppedMessageCount: z10.number().int().min(0).optional(),
1362
+ usage: canonicalUsageSchema.optional()
1363
+ });
1364
+ var errorRaisedEventSchema = event({
1365
+ type: z10.literal("error.raised"),
1366
+ errorCode: otelHookErrorCodeSchema,
1367
+ severity: errorSeveritySchema,
1368
+ phase: errorPhaseSchema,
1369
+ retryable: z10.boolean(),
1370
+ /** Error text is content: it is described, never embedded verbatim by default. */
1371
+ message: contentFactSchema.optional(),
1372
+ /** Non-sensitive, provider-agnostic short label. */
1373
+ detail: nonEmptyStringSchema.optional()
1374
+ });
1375
+ var canonicalEventSchema = z10.discriminatedUnion("type", [
1376
+ sessionStartEventSchema,
1377
+ sessionEndEventSchema,
1378
+ promptSubmittedEventSchema,
1379
+ generationStartEventSchema,
1380
+ generationEndEventSchema,
1381
+ toolStartEventSchema,
1382
+ toolEndEventSchema,
1383
+ subagentStartEventSchema,
1384
+ subagentEndEventSchema,
1385
+ compactionPerformedEventSchema,
1386
+ errorRaisedEventSchema
1387
+ ]);
1388
+ var TARGETED_EVENT_TYPES = ["session.start", "prompt.submitted", "tool.start", "tool.end"];
1389
+ var TARGETED = new Set(TARGETED_EVENT_TYPES);
1390
+ var isTargetedEvent = (event2) => TARGETED.has(event2.type);
1391
+
1392
+ // src/telemetry/export-identity.ts
1393
+ var ATTR_TRACE_ID = "trace_id";
1394
+ var ATTR_SPAN_ID = "span_id";
1395
+ var ATTR_PARENT_SPAN_ID = "parent_span_id";
1396
+ var ATTR_OTELHOOK_SESSION_ID = "otelhook.session.id";
1397
+ var ATTR_GEN_AI_CONVERSATION_ID = "gen_ai.conversation.id";
1398
+ var TRACE_ID_HEX_PATTERN = /^[0-9a-f]{32}$/;
1399
+ var SPAN_ID_HEX_PATTERN = /^[0-9a-f]{16}$/;
1400
+ var ATTR_OTELHOOK_INVOCATION_ID = "otelhook.invocation.id";
1401
+ var ATTR_OTELHOOK_PROVIDER_ID = "otelhook.provider.id";
1402
+ var ATTR_OTELHOOK_PROVIDER_VERSION = "otelhook.provider.version";
1403
+ var ATTR_OTELHOOK_WORKSPACE_ID = "otelhook.workspace.id";
1404
+ var HAR_SESSION_KEY = "har.session_key";
1405
+ var ATTR_OTELHOOK_SUBAGENT_ID = "otelhook.subagent.id";
1406
+ var ATTR_VCS_REF_HEAD_NAME = "vcs.ref.head.name";
1407
+ var ATTR_OTELHOOK_TARGET_WORKSPACE_ID = "otelhook.target.workspace.id";
1408
+ var ATTR_OTELHOOK_TARGET_SOURCE = "otelhook.target.source";
1409
+ var ATTR_OTELHOOK_TARGET_REPOSITORY_ID = "otelhook.target.repository.id";
1410
+ var ATTR_OTELHOOK_TARGET_WORKTREE_KIND = "otelhook.target.worktree.kind";
1411
+ var ATTR_OTELHOOK_USAGE_TEMPORALITY = "otelhook.usage.temporality";
1412
+ var targetAttributes = (event2) => {
1413
+ if (!isTargetedEvent(event2) || event2.target === void 0) {
1414
+ return {};
1415
+ }
1416
+ const { target } = event2;
1417
+ return {
1418
+ [ATTR_OTELHOOK_TARGET_WORKSPACE_ID]: target.workspaceId,
1419
+ [ATTR_OTELHOOK_TARGET_SOURCE]: target.source,
1420
+ ...target.vcsBranchName === void 0 ? {} : { [ATTR_VCS_REF_HEAD_NAME]: target.vcsBranchName },
1421
+ ...target.repositoryId === void 0 ? {} : { [ATTR_OTELHOOK_TARGET_REPOSITORY_ID]: target.repositoryId },
1422
+ ...target.worktreeKind === void 0 ? {} : { [ATTR_OTELHOOK_TARGET_WORKTREE_KIND]: target.worktreeKind }
1652
1423
  };
1653
- const cleanup = async (maxAgeMillis, options) => {
1654
- const keys = await stateStore.keys(spanScanPrefix(options?.sessionId));
1655
- const cap = options?.maxEntries ?? 1e3;
1656
- const now = clock.now();
1657
- let removed = 0;
1658
- let scanned = 0;
1659
- let expiredOpen = 0;
1660
- for (const key of keys) {
1661
- if (scanned >= cap) {
1662
- break;
1663
- }
1664
- scanned += 1;
1665
- const record = await stateStore.read(key);
1666
- if (record !== void 0 && now - record.updatedAt > maxAgeMillis) {
1667
- if (record.value.kind === "attributes") {
1668
- const decoded = decodeRecord(record.value.attributes);
1669
- if (decoded.kind === "present" && decoded.record.startedAt !== void 0 && decoded.record.endedAt === void 0) {
1670
- expiredOpen += 1;
1671
- }
1672
- }
1673
- await stateStore.delete(key);
1674
- removed += 1;
1675
- }
1424
+ };
1425
+ var usageTemporalityAttributes = (usage) => usage === void 0 ? {} : { [ATTR_OTELHOOK_USAGE_TEMPORALITY]: usage.temporality };
1426
+ var isPrimitiveAttribute = (value) => typeof value === "string" || typeof value === "number" || typeof value === "boolean";
1427
+ var passthroughHarAttributes = (resource) => {
1428
+ const attributes = {};
1429
+ for (const [key, value] of Object.entries(resource.attributes)) {
1430
+ if (key.startsWith("har.") && isPrimitiveAttribute(value)) {
1431
+ attributes[key] = value;
1676
1432
  }
1677
- return { removed, scanned, expiredOpen };
1433
+ }
1434
+ return attributes;
1435
+ };
1436
+ var resolveExportedSessionId = (eventSessionId, resource) => {
1437
+ const har = resource.attributes[HAR_SESSION_KEY];
1438
+ if (typeof har === "string") {
1439
+ const trimmed = har.trim();
1440
+ if (trimmed.length > 0) {
1441
+ return { sessionId: trimmed, providerSessionId: eventSessionId };
1442
+ }
1443
+ }
1444
+ return { sessionId: eventSessionId, providerSessionId: eventSessionId };
1445
+ };
1446
+ var hexTraceAttributes = (ids) => ({
1447
+ ...TRACE_ID_HEX_PATTERN.test(ids.traceId) ? { [ATTR_TRACE_ID]: ids.traceId } : {},
1448
+ ...SPAN_ID_HEX_PATTERN.test(ids.spanId) ? { [ATTR_SPAN_ID]: ids.spanId } : {},
1449
+ ...ids.parentSpanId !== void 0 && SPAN_ID_HEX_PATTERN.test(ids.parentSpanId) ? { [ATTR_PARENT_SPAN_ID]: ids.parentSpanId } : {}
1450
+ });
1451
+ var exportIdentityAttributes = (event2, resource, ids) => {
1452
+ const { sessionId, providerSessionId } = resolveExportedSessionId(event2.sessionId, resource);
1453
+ return {
1454
+ [ATTR_SESSION_ID]: sessionId,
1455
+ [ATTR_OTELHOOK_SESSION_ID]: providerSessionId,
1456
+ [ATTR_GEN_AI_CONVERSATION_ID]: providerSessionId,
1457
+ [ATTR_OTELHOOK_INVOCATION_ID]: event2.invocationId,
1458
+ [ATTR_OTELHOOK_PROVIDER_ID]: event2.provenance.providerId,
1459
+ ...event2.provenance.providerVersion === void 0 ? {} : { [ATTR_OTELHOOK_PROVIDER_VERSION]: event2.provenance.providerVersion },
1460
+ [ATTR_OTELHOOK_WORKSPACE_ID]: event2.workspace.workspaceId,
1461
+ ...event2.subagentId === void 0 ? {} : { [ATTR_OTELHOOK_SUBAGENT_ID]: event2.subagentId },
1462
+ ...passthroughHarAttributes(resource),
1463
+ ...hexTraceAttributes(ids)
1678
1464
  };
1679
- return { recordStart, recordEnd, correlateBatch, cleanup };
1680
1465
  };
1681
1466
 
1682
- // src/model/usage.ts
1683
- import { z as z4 } from "zod";
1684
- var usageTemporalitySchema = z4.enum(["delta", "cumulative"]);
1685
- var cacheCreationAccountingSchema = z4.enum([
1686
- "included-in-input",
1687
- "disjoint-from-input",
1688
- "not-reported"
1689
- ]);
1690
- var providerTotalAgreementSchema = z4.enum(["unreported", "agrees", "disagrees"]);
1691
- var usageReportSchema = z4.strictObject({
1692
- temporality: usageTemporalitySchema,
1693
- /** Inclusive input tokens. */
1694
- inputTokens: tokenCountSchema.optional(),
1695
- /** Subset of `inputTokens` served from a prompt cache. */
1696
- cachedInputTokens: tokenCountSchema.optional(),
1697
- /** Tokens written to a prompt cache. */
1698
- cacheCreationInputTokens: tokenCountSchema.optional(),
1699
- /** Required when `cacheCreationInputTokens` is present and non-zero. */
1700
- cacheCreationAccounting: cacheCreationAccountingSchema.optional(),
1701
- /** Inclusive output tokens. */
1702
- outputTokens: tokenCountSchema.optional(),
1703
- /** Subset of `outputTokens` spent on reasoning. */
1704
- reasoningOutputTokens: tokenCountSchema.optional(),
1705
- /** Total exactly as the provider reported it, if it reported one. */
1706
- providerTotalTokens: tokenCountSchema.optional()
1467
+ // src/telemetry/semconv.ts
1468
+ var SCOPE_NAME = "@osfactory/otel-hook";
1469
+ var DEFAULT_INSTRUMENTATION_SCOPE = Object.freeze({
1470
+ name: SCOPE_NAME,
1471
+ version: VERSION
1707
1472
  });
1708
- var canonicalUsageSchema = z4.strictObject({
1709
- temporality: usageTemporalitySchema,
1710
- inputTokens: tokenCountSchema,
1711
- cachedInputTokens: tokenCountSchema,
1712
- cacheCreationInputTokens: tokenCountSchema,
1713
- cacheCreationAccounting: cacheCreationAccountingSchema,
1714
- outputTokens: tokenCountSchema,
1715
- reasoningOutputTokens: tokenCountSchema,
1716
- /** Derived: input tokens that were neither cache reads nor cache writes. */
1717
- uncachedInputTokens: tokenCountSchema,
1718
- /** Derived: canonical billable total. */
1719
- totalTokens: tokenCountSchema,
1720
- providerTotalTokens: tokenCountSchema.optional(),
1721
- providerTotalAgreement: providerTotalAgreementSchema
1722
- }).check((ctx) => {
1723
- const usage = ctx.value;
1724
- const push = (message) => {
1725
- ctx.issues.push({ code: "custom", input: usage, message });
1726
- };
1727
- if (usage.cachedInputTokens > usage.inputTokens) {
1728
- push("cachedInputTokens must not exceed inputTokens (it is a subset)");
1729
- }
1730
- if (usage.reasoningOutputTokens > usage.outputTokens) {
1731
- push("reasoningOutputTokens must not exceed outputTokens (it is a subset)");
1732
- }
1733
- if (usage.cacheCreationAccounting === "not-reported" && usage.cacheCreationInputTokens !== 0) {
1734
- push("cacheCreationInputTokens must be 0 when cacheCreationAccounting is not-reported");
1735
- }
1736
- const creationInsideInput = usage.cacheCreationAccounting === "included-in-input" ? usage.cacheCreationInputTokens : 0;
1737
- if (usage.cachedInputTokens + creationInsideInput > usage.inputTokens) {
1738
- push(
1739
- "cachedInputTokens + cacheCreationInputTokens must not exceed inputTokens when cache creation is included in input"
1740
- );
1741
- }
1742
- const expectedUncached = usage.inputTokens - usage.cachedInputTokens - creationInsideInput;
1743
- if (expectedUncached >= 0 && usage.uncachedInputTokens !== expectedUncached) {
1744
- push(`uncachedInputTokens must equal ${expectedUncached}`);
1745
- }
1746
- const creationOutsideInput = usage.cacheCreationAccounting === "disjoint-from-input" ? usage.cacheCreationInputTokens : 0;
1747
- const expectedTotal = usage.inputTokens + creationOutsideInput + usage.outputTokens;
1748
- if (usage.totalTokens !== expectedTotal) {
1749
- push(`totalTokens must equal ${expectedTotal}`);
1750
- }
1751
- const expectedAgreement = usage.providerTotalTokens === void 0 ? "unreported" : usage.providerTotalTokens === expectedTotal ? "agrees" : "disagrees";
1752
- if (usage.providerTotalAgreement !== expectedAgreement) {
1753
- push(`providerTotalAgreement must be ${expectedAgreement}`);
1473
+ var ATTR_OTELHOOK_SPAN_PAIRED = "otelhook.span.paired";
1474
+ var ATTR_OTELHOOK_SPAN_PAIRING = "otelhook.span.pairing";
1475
+ var ATTR_OTELHOOK_SPAN_ORPHAN = "otelhook.span.orphan";
1476
+ var ATTR_OTELHOOK_OUTCOME = "otelhook.outcome";
1477
+ var ATTR_OTELHOOK_RESET_DETECTED = "otelhook.usage.reset_detected";
1478
+ var ATTR_OTELHOOK_TOOL_KIND = "otelhook.tool.kind";
1479
+ var ATTR_OTELHOOK_DELEGATION_DEPTH = "otelhook.delegation_depth";
1480
+ var ATTR_OTELHOOK_COMPACTION_TRIGGER = "otelhook.compaction.trigger";
1481
+ var ATTR_OTELHOOK_AGENT_NAME = "otelhook.agent.name";
1482
+ var ATTR_OTELHOOK_AGENT_VERSION = "otelhook.agent.version";
1483
+ var ATTR_OTELHOOK_GENERATION_ID = "otelhook.generation.id";
1484
+ var FIELD_SEPARATOR = "\0";
1485
+ var digestHex = (parts, length) => createHash("sha256").update(parts.join(FIELD_SEPARATOR)).digest("hex").slice(0, length);
1486
+ var MAX_RECOVERED_START_ATTRIBUTES = 16;
1487
+ var familyOf = (type) => {
1488
+ switch (type) {
1489
+ case "session.start":
1490
+ case "session.end":
1491
+ return "session";
1492
+ case "generation.start":
1493
+ case "generation.end":
1494
+ return "generation";
1495
+ case "tool.start":
1496
+ case "tool.end":
1497
+ return "tool";
1498
+ case "subagent.start":
1499
+ case "subagent.end":
1500
+ return "subagent";
1501
+ default:
1502
+ return void 0;
1754
1503
  }
1755
- });
1756
- var normalizeUsage = (report) => {
1757
- const parsed = usageReportSchema.safeParse(report);
1758
- if (!parsed.success) {
1759
- return {
1760
- status: "invalid",
1761
- issues: parsed.error.issues.map((issue) => ({
1762
- code: "invalid-report",
1763
- message: `${issue.path.join(".") || "<root>"}: ${issue.message}`
1764
- }))
1765
- };
1504
+ };
1505
+ var spanScopeRefOf = (event2) => {
1506
+ const family = familyOf(event2.type);
1507
+ if (family === void 0) {
1508
+ return void 0;
1766
1509
  }
1767
- const input = parsed.data;
1768
- const issues = [];
1769
- const notes = [];
1770
- const inputTokens = input.inputTokens ?? 0;
1771
- const cachedInputTokens = input.cachedInputTokens ?? 0;
1772
- const cacheCreationInputTokens = input.cacheCreationInputTokens ?? 0;
1773
- const outputTokens = input.outputTokens ?? 0;
1774
- const reasoningOutputTokens = input.reasoningOutputTokens ?? 0;
1775
- let accounting;
1776
- if (cacheCreationInputTokens === 0) {
1777
- accounting = input.cacheCreationAccounting ?? "not-reported";
1778
- if (accounting !== "not-reported") {
1779
- notes.push(
1780
- `cacheCreationAccounting=${accounting} retained with zero cache-creation tokens`
1781
- );
1782
- }
1783
- } else if (input.cacheCreationAccounting === void 0) {
1784
- issues.push({
1785
- code: "cache-creation-accounting-missing",
1786
- message: "cacheCreationAccounting is required when cacheCreationInputTokens is non-zero; it cannot be inferred"
1787
- });
1788
- accounting = "not-reported";
1789
- } else if (input.cacheCreationAccounting === "not-reported") {
1790
- issues.push({
1791
- code: "cache-creation-accounting-missing",
1792
- message: "cacheCreationAccounting=not-reported conflicts with non-zero cacheCreationInputTokens"
1793
- });
1794
- accounting = "not-reported";
1795
- } else {
1796
- accounting = input.cacheCreationAccounting;
1510
+ switch (event2.type) {
1511
+ case "session.start":
1512
+ case "session.end":
1513
+ return { family, scopeKey: event2.sessionId };
1514
+ case "generation.start":
1515
+ case "generation.end":
1516
+ return { family, scopeKey: event2.generationId };
1517
+ case "tool.start":
1518
+ case "tool.end":
1519
+ return { family, scopeKey: event2.toolCallId };
1520
+ case "subagent.start":
1521
+ case "subagent.end":
1522
+ return { family, scopeKey: event2.subagentInvocationId };
1523
+ default:
1524
+ return void 0;
1797
1525
  }
1798
- if (cachedInputTokens > inputTokens) {
1799
- issues.push({
1800
- code: "cached-exceeds-input",
1801
- message: `cachedInputTokens (${cachedInputTokens}) exceeds inclusive inputTokens (${inputTokens})`
1802
- });
1526
+ };
1527
+ var parentScopeRefOf = (event2) => {
1528
+ if (event2.type === "session.start" || event2.type === "session.end") {
1529
+ return void 0;
1803
1530
  }
1804
- if (reasoningOutputTokens > outputTokens) {
1805
- issues.push({
1806
- code: "reasoning-exceeds-output",
1807
- message: `reasoningOutputTokens (${reasoningOutputTokens}) exceeds inclusive outputTokens (${outputTokens})`
1808
- });
1531
+ if (event2.type === "tool.start" && event2.generationId !== void 0) {
1532
+ return { family: "generation", scopeKey: event2.generationId };
1809
1533
  }
1810
- const creationInsideInput = accounting === "included-in-input" ? cacheCreationInputTokens : 0;
1811
- if (cachedInputTokens + creationInsideInput > inputTokens) {
1812
- issues.push({
1813
- code: "cache-creation-exceeds-input",
1814
- message: `cachedInputTokens + cacheCreationInputTokens (${cachedInputTokens + creationInsideInput}) exceeds inclusive inputTokens (${inputTokens})`
1815
- });
1534
+ return { family: "session", scopeKey: event2.sessionId };
1535
+ };
1536
+ var startOnlySpanAttributes = (event2) => {
1537
+ switch (event2.type) {
1538
+ // The session's own worktree is carried forward like a tool's target, so
1539
+ // the session span a later `session.end` process exports still names it.
1540
+ case "session.start":
1541
+ return {
1542
+ ...event2.agentName === void 0 ? {} : { [ATTR_OTELHOOK_AGENT_NAME]: event2.agentName },
1543
+ ...event2.agentVersion === void 0 ? {} : { [ATTR_OTELHOOK_AGENT_VERSION]: event2.agentVersion },
1544
+ ...targetAttributes(event2)
1545
+ };
1546
+ case "generation.start":
1547
+ return {
1548
+ [ATTR_GEN_AI_REQUEST_MODEL]: event2.model.modelId,
1549
+ ...event2.model.vendor === void 0 ? {} : { [ATTR_GEN_AI_SYSTEM]: event2.model.vendor }
1550
+ };
1551
+ // `toolName` and `toolCallId` are on both tool edges, so they are not
1552
+ // start-only and persisting them would just pad every record.
1553
+ // The target is carried forward too: an end-only process may see a payload
1554
+ // with less to go on (no tool input), and the start's evidence still holds.
1555
+ case "tool.start":
1556
+ return { [ATTR_OTELHOOK_TOOL_KIND]: event2.toolKind, ...targetAttributes(event2) };
1557
+ case "subagent.start":
1558
+ return { [ATTR_OTELHOOK_DELEGATION_DEPTH]: event2.delegationDepth };
1559
+ default:
1560
+ return {};
1816
1561
  }
1817
- if (issues.length > 0) {
1818
- return { status: "invalid", issues };
1562
+ };
1563
+ var deriveTraceId = (providerId, sessionId) => digestHex(["otelhook/trace", providerId, sessionId], 32);
1564
+ var deriveSpanId = (providerId, sessionId, ref) => digestHex(["otelhook/span", providerId, sessionId, ref.family, ref.scopeKey], 16);
1565
+ var deriveStandaloneSpanId = (providerId, sessionId, eventType, eventId) => digestHex(["otelhook/span", providerId, sessionId, "event", eventType, eventId], 16);
1566
+ var correlationKey = (providerId, sessionId, ref) => [providerId, sessionId, ref.family, ref.scopeKey].join(FIELD_SEPARATOR);
1567
+ var outcomeStatus = (outcome) => {
1568
+ if (outcome === void 0 || outcome === "ok" || outcome === "unknown") {
1569
+ return { code: SpanStatusCode.UNSET };
1819
1570
  }
1820
- const creationOutsideInput = accounting === "disjoint-from-input" ? cacheCreationInputTokens : 0;
1821
- const totalTokens = inputTokens + creationOutsideInput + outputTokens;
1822
- const providerTotalAgreement = input.providerTotalTokens === void 0 ? "unreported" : input.providerTotalTokens === totalTokens ? "agrees" : "disagrees";
1823
- if (providerTotalAgreement === "disagrees") {
1824
- notes.push(
1825
- `providerTotalTokens (${input.providerTotalTokens ?? 0}) disagrees with canonical total (${totalTokens}); both retained`
1826
- );
1571
+ if (outcome === "cancelled") {
1572
+ return { code: SpanStatusCode.UNSET };
1827
1573
  }
1828
- const usage = {
1829
- temporality: input.temporality,
1830
- inputTokens,
1831
- cachedInputTokens,
1832
- cacheCreationInputTokens,
1833
- cacheCreationAccounting: accounting,
1834
- outputTokens,
1835
- reasoningOutputTokens,
1836
- uncachedInputTokens: inputTokens - cachedInputTokens - creationInsideInput,
1837
- totalTokens,
1838
- ...input.providerTotalTokens === void 0 ? {} : { providerTotalTokens: input.providerTotalTokens },
1839
- providerTotalAgreement
1840
- };
1841
- return { status: "ok", usage, notes };
1574
+ return { code: SpanStatusCode.ERROR, message: outcome };
1842
1575
  };
1843
- var UsageNormalizationError = class extends Error {
1844
- issues;
1845
- constructor(issues) {
1846
- super(`invalid usage report: ${issues.map((issue) => issue.message).join("; ")}`);
1847
- this.name = "UsageNormalizationError";
1848
- this.issues = issues;
1576
+ var identityAttributes = (event2, resource, ids) => exportIdentityAttributes(event2, resource, ids);
1577
+ var usageAttributes = (usage, resetDetected) => {
1578
+ if (usage === void 0) {
1579
+ return {};
1849
1580
  }
1581
+ return {
1582
+ [ATTR_GEN_AI_USAGE_INPUT_TOKENS]: usage.inputTokens,
1583
+ [ATTR_GEN_AI_USAGE_OUTPUT_TOKENS]: usage.outputTokens,
1584
+ [ATTR_GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS]: usage.cachedInputTokens,
1585
+ [ATTR_GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS]: usage.cacheCreationInputTokens,
1586
+ [ATTR_GEN_AI_USAGE_REASONING_OUTPUT_TOKENS]: usage.reasoningOutputTokens,
1587
+ ...usageTemporalityAttributes(usage),
1588
+ ...resetDetected ? { [ATTR_OTELHOOK_RESET_DETECTED]: true } : {}
1589
+ };
1850
1590
  };
1851
- var normalizeUsageOrThrow = (report) => {
1852
- const result = normalizeUsage(report);
1853
- if (result.status === "invalid") {
1854
- throw new UsageNormalizationError(result.issues);
1591
+ var TARGET_SOURCE_RANK = Object.freeze({
1592
+ "tool-path": 3,
1593
+ "shell-cwd": 2,
1594
+ "session-cwd": 1
1595
+ });
1596
+ var TARGET_KEYS = [
1597
+ ATTR_OTELHOOK_TARGET_WORKSPACE_ID,
1598
+ ATTR_OTELHOOK_TARGET_SOURCE,
1599
+ ATTR_VCS_REF_HEAD_NAME,
1600
+ ATTR_OTELHOOK_TARGET_REPOSITORY_ID,
1601
+ ATTR_OTELHOOK_TARGET_WORKTREE_KIND
1602
+ ];
1603
+ var pickTarget = (attributes) => {
1604
+ const picked = {};
1605
+ for (const key of TARGET_KEYS) {
1606
+ if (attributes[key] !== void 0) {
1607
+ picked[key] = attributes[key];
1608
+ }
1855
1609
  }
1856
- return result.usage;
1610
+ return picked;
1857
1611
  };
1858
- var EMPTY_DELTA_USAGE = Object.freeze(
1859
- normalizeUsageOrThrow({ temporality: "delta" })
1860
- );
1861
- var requireCumulative = (usage, label) => {
1862
- if (usage.temporality !== "cumulative") {
1863
- throw new UsageNormalizationError([
1864
- { code: "invalid-report", message: `${label} must have cumulative temporality` }
1865
- ]);
1612
+ var withoutTarget = (attributes) => {
1613
+ const rest = { ...attributes };
1614
+ for (const key of TARGET_KEYS) {
1615
+ delete rest[key];
1866
1616
  }
1617
+ return rest;
1867
1618
  };
1868
- var cumulativeToDelta = (previous, current) => {
1869
- requireCumulative(previous, "previous usage");
1870
- requireCumulative(current, "current usage");
1871
- if (previous.cacheCreationAccounting !== current.cacheCreationAccounting && previous.cacheCreationInputTokens !== 0 && current.cacheCreationInputTokens !== 0) {
1872
- throw new UsageNormalizationError([
1873
- {
1874
- code: "cache-creation-accounting-missing",
1875
- message: "cannot diff cumulative usage across differing cacheCreationAccounting modes"
1876
- }
1877
- ]);
1878
- }
1879
- const resetDetected = current.inputTokens < previous.inputTokens || current.cachedInputTokens < previous.cachedInputTokens || current.cacheCreationInputTokens < previous.cacheCreationInputTokens || current.outputTokens < previous.outputTokens || current.reasoningOutputTokens < previous.reasoningOutputTokens;
1880
- if (resetDetected) {
1881
- return {
1882
- usage: normalizeUsageOrThrow({ ...toReport(current), temporality: "delta" }),
1883
- resetDetected: true
1884
- };
1619
+ var rankOf = (candidate) => {
1620
+ const source = candidate[ATTR_OTELHOOK_TARGET_SOURCE];
1621
+ return typeof source === "string" && Object.hasOwn(TARGET_SOURCE_RANK, source) ? TARGET_SOURCE_RANK[source] ?? 0 : 0;
1622
+ };
1623
+ var strongestTarget = (candidates) => {
1624
+ let best = {};
1625
+ let bestRank = 0;
1626
+ for (const candidate of candidates) {
1627
+ const rank = rankOf(candidate);
1628
+ if (rank > 0 && rank >= bestRank) {
1629
+ best = candidate;
1630
+ bestRank = rank;
1631
+ }
1885
1632
  }
1886
- const usage = normalizeUsageOrThrow({
1887
- temporality: "delta",
1888
- inputTokens: current.inputTokens - previous.inputTokens,
1889
- cachedInputTokens: current.cachedInputTokens - previous.cachedInputTokens,
1890
- cacheCreationInputTokens: current.cacheCreationInputTokens - previous.cacheCreationInputTokens,
1891
- cacheCreationAccounting: current.cacheCreationAccounting,
1892
- outputTokens: current.outputTokens - previous.outputTokens,
1893
- reasoningOutputTokens: current.reasoningOutputTokens - previous.reasoningOutputTokens
1894
- });
1895
- return { usage, resetDetected: false };
1633
+ return best;
1896
1634
  };
1897
- var toReport = (usage) => ({
1898
- temporality: usage.temporality,
1899
- inputTokens: usage.inputTokens,
1900
- cachedInputTokens: usage.cachedInputTokens,
1901
- cacheCreationInputTokens: usage.cacheCreationInputTokens,
1902
- cacheCreationAccounting: usage.cacheCreationAccounting,
1903
- outputTokens: usage.outputTokens,
1904
- reasoningOutputTokens: usage.reasoningOutputTokens,
1905
- ...usage.providerTotalTokens === void 0 ? {} : { providerTotalTokens: usage.providerTotalTokens }
1635
+ var buildSpanContext = (traceId, spanId) => ({
1636
+ traceId,
1637
+ spanId,
1638
+ traceFlags: TraceFlags.SAMPLED,
1639
+ isRemote: false
1906
1640
  });
1907
-
1908
- // src/lifecycle/usage-accumulator.ts
1909
- var EMPTY_CUMULATIVE_USAGE = normalizeUsageOrThrow({ temporality: "cumulative" });
1910
- var combineCumulativeWithDelta = (total, delta) => {
1911
- if (total.temporality !== "cumulative") {
1912
- throw new UsageNormalizationError([
1913
- { code: "invalid-report", message: "usage rollup total must have cumulative temporality" }
1914
- ]);
1915
- }
1916
- if (delta.temporality !== "delta") {
1917
- throw new UsageNormalizationError([
1918
- { code: "invalid-report", message: "usage accumulator only accepts delta observations" }
1919
- ]);
1920
- }
1921
- const accounting = total.cacheCreationInputTokens === 0 && total.cacheCreationAccounting === "not-reported" ? delta.cacheCreationAccounting : delta.cacheCreationInputTokens === 0 && delta.cacheCreationAccounting === "not-reported" ? total.cacheCreationAccounting : total.cacheCreationAccounting;
1922
- if (total.cacheCreationInputTokens !== 0 && delta.cacheCreationInputTokens !== 0 && total.cacheCreationAccounting !== delta.cacheCreationAccounting) {
1923
- throw new UsageNormalizationError([
1924
- {
1925
- code: "cache-creation-accounting-missing",
1926
- message: "cannot roll up usage across differing cacheCreationAccounting modes"
1927
- }
1928
- ]);
1641
+ var assembleReadableSpan = (input) => toReadableSpan(input);
1642
+ var toReadableSpan = (input) => {
1643
+ const startTime = millisToHrTime(input.startMillis);
1644
+ const endTime = millisToHrTime(Math.max(input.startMillis, input.endMillis));
1645
+ const duration = millisToHrTime(Math.max(0, input.endMillis - input.startMillis));
1646
+ return {
1647
+ name: input.name,
1648
+ kind: input.kind,
1649
+ spanContext: () => buildSpanContext(input.traceId, input.spanId),
1650
+ ...input.parentSpanId === void 0 ? {} : { parentSpanContext: buildSpanContext(input.traceId, input.parentSpanId) },
1651
+ startTime,
1652
+ endTime,
1653
+ status: input.status,
1654
+ attributes: input.attributes,
1655
+ links: [],
1656
+ events: [],
1657
+ duration,
1658
+ ended: true,
1659
+ resource: input.resource,
1660
+ instrumentationScope: input.instrumentationScope,
1661
+ droppedAttributesCount: 0,
1662
+ droppedEventsCount: 0,
1663
+ droppedLinksCount: 0
1664
+ };
1665
+ };
1666
+ var resolvePairing = (group, anchor, correlation) => {
1667
+ const inBatch = group.start !== void 0 && group.end !== void 0;
1668
+ const batchStart = group.start?.occurredAt ?? anchor.occurredAt;
1669
+ const batchEnd = group.end?.occurredAt ?? anchor.occurredAt;
1670
+ if (correlation === void 0) {
1671
+ return {
1672
+ pairing: inBatch ? "in-batch" : "unpaired",
1673
+ orphan: inBatch ? "none" : group.start === void 0 ? "missing-start" : "missing-end",
1674
+ startMillis: batchStart,
1675
+ endMillis: inBatch ? batchEnd : batchStart,
1676
+ parent: parentScopeRefOf(anchor),
1677
+ recovered: {}
1678
+ };
1929
1679
  }
1930
- const providerTotal = total.providerTotalTokens === void 0 && delta.providerTotalTokens === void 0 ? void 0 : (total.providerTotalTokens ?? 0) + (delta.providerTotalTokens ?? 0);
1931
- return normalizeUsageOrThrow({
1932
- temporality: "cumulative",
1933
- inputTokens: total.inputTokens + delta.inputTokens,
1934
- cachedInputTokens: total.cachedInputTokens + delta.cachedInputTokens,
1935
- cacheCreationInputTokens: total.cacheCreationInputTokens + delta.cacheCreationInputTokens,
1936
- cacheCreationAccounting: accounting,
1937
- outputTokens: total.outputTokens + delta.outputTokens,
1938
- reasoningOutputTokens: total.reasoningOutputTokens + delta.reasoningOutputTokens,
1939
- ...providerTotal === void 0 ? {} : { providerTotalTokens: providerTotal }
1940
- });
1680
+ const startMillis = correlation.startMillis ?? (inBatch ? batchStart : batchEnd);
1681
+ const endMillis = correlation.endMillis ?? (group.end === void 0 ? startMillis : batchEnd);
1682
+ return {
1683
+ pairing: correlation.pairing,
1684
+ orphan: correlation.orphan,
1685
+ startMillis,
1686
+ endMillis,
1687
+ parent: correlation.parent ?? parentScopeRefOf(anchor),
1688
+ recovered: correlation.attributes ?? {}
1689
+ };
1941
1690
  };
1942
- var createUsageAccumulator = (deps) => {
1943
- const { stateStore, clock } = deps;
1944
- const readEpochMarker = (attributes) => {
1945
- const callbackId = attributes.resetDelivery;
1946
- const applications = attributes.resetApplications;
1947
- if (typeof callbackId !== "string" || callbackId.length === 0 || typeof applications !== "number" || !Number.isInteger(applications) || applications < 1) {
1948
- return void 0;
1949
- }
1950
- return { callbackId, applications };
1691
+ var buildLifecycleSpan = (plan, resource, scope) => {
1692
+ const group = plan.group;
1693
+ const anchor = plan.anchor;
1694
+ const correlation = plan.correlation;
1695
+ const providerId = anchor.provenance.providerId;
1696
+ const sessionId = anchor.sessionId;
1697
+ const resolved = resolvePairing(group, anchor, correlation);
1698
+ const traceId = plan.traceId;
1699
+ const spanId = plan.spanId;
1700
+ const parentSpanId = resolved.parent === void 0 ? void 0 : deriveSpanId(providerId, sessionId, resolved.parent);
1701
+ let name = group.ref.family;
1702
+ let kind = SpanKind.INTERNAL;
1703
+ let status = { code: SpanStatusCode.UNSET };
1704
+ let attributes = {
1705
+ ...identityAttributes(anchor, resource, {
1706
+ traceId,
1707
+ spanId,
1708
+ ...parentSpanId === void 0 ? {} : { parentSpanId }
1709
+ }),
1710
+ ...resolved.recovered,
1711
+ [ATTR_OTELHOOK_SPAN_PAIRED]: resolved.pairing !== "unpaired",
1712
+ [ATTR_OTELHOOK_SPAN_PAIRING]: resolved.pairing,
1713
+ [ATTR_OTELHOOK_SPAN_ORPHAN]: resolved.orphan
1951
1714
  };
1952
- const readEpoch = async (key) => {
1953
- const record = await stateStore.read(rollupEpochKey(key.sessionId, key.scope, key.scopeKey));
1954
- if (record?.value.kind === "attributes" && typeof record.value.attributes.epoch === "number") {
1955
- return record.value.attributes.epoch;
1715
+ switch (group.ref.family) {
1716
+ case "session": {
1717
+ const end = group.end?.type === "session.end" ? group.end : void 0;
1718
+ const start = group.start?.type === "session.start" ? group.start : void 0;
1719
+ name = "session";
1720
+ kind = SpanKind.INTERNAL;
1721
+ attributes = {
1722
+ ...withoutTarget(attributes),
1723
+ ...strongestTarget([pickTarget(resolved.recovered), start === void 0 ? {} : targetAttributes(start)]),
1724
+ ...start?.agentName === void 0 ? {} : { [ATTR_OTELHOOK_AGENT_NAME]: start.agentName },
1725
+ ...start?.agentVersion === void 0 ? {} : { [ATTR_OTELHOOK_AGENT_VERSION]: start.agentVersion },
1726
+ ...end === void 0 ? {} : { [ATTR_OTELHOOK_OUTCOME]: end.reason },
1727
+ ...usageAttributes(end?.usage, false)
1728
+ };
1729
+ if (end?.reason === "error" || end?.reason === "timeout") {
1730
+ status = { code: SpanStatusCode.ERROR, message: end.reason };
1731
+ }
1732
+ break;
1956
1733
  }
1957
- return 0;
1958
- };
1959
- const alreadyApplied = (marker, delivery) => delivery !== void 0 && marker !== void 0 && marker.callbackId === delivery.callbackId && delivery.ordinal < marker.applications;
1960
- const markerFor = (delivery) => delivery === void 0 ? {} : {
1961
- appliedDelivery: { callbackId: delivery.callbackId, applications: delivery.ordinal + 1 }
1962
- };
1963
- const accumulateDelta = (key, delta, options) => withOptionalSessionLock(stateStore, key.sessionId, async () => {
1964
- const usageKey2 = rollupUsageKey(key.sessionId, key.scope, key.scopeKey);
1965
- const existing = await stateStore.read(usageKey2);
1966
- const previousTotal = existing?.value.kind === "usage-cumulative" ? existing.value.usage : EMPTY_CUMULATIVE_USAGE;
1967
- if (existing?.value.kind === "usage-cumulative" && alreadyApplied(existing.value.appliedDelivery, options?.delivery)) {
1968
- return { total: previousTotal, epoch: await readEpoch(key) };
1734
+ case "generation": {
1735
+ const start = group.start?.type === "generation.start" ? group.start : void 0;
1736
+ const end = group.end?.type === "generation.end" ? group.end : void 0;
1737
+ const model = end?.model ?? start?.model;
1738
+ name = model === void 0 ? "generation" : `generation ${model.modelId}`;
1739
+ kind = SpanKind.CLIENT;
1740
+ attributes = {
1741
+ ...attributes,
1742
+ [ATTR_GEN_AI_OPERATION_NAME]: "chat",
1743
+ ...model?.vendor === void 0 ? {} : { [ATTR_GEN_AI_SYSTEM]: model.vendor },
1744
+ ...start?.model?.modelId === void 0 ? {} : { [ATTR_GEN_AI_REQUEST_MODEL]: start.model.modelId },
1745
+ ...end?.model?.modelId === void 0 ? {} : { [ATTR_GEN_AI_RESPONSE_MODEL]: end.model.modelId },
1746
+ // The provider's own id for this unit of work (Cursor generation,
1747
+ // Codex turn): the key a consumer stores a usage observation under.
1748
+ [ATTR_OTELHOOK_GENERATION_ID]: group.ref.scopeKey,
1749
+ ...end?.outcome === void 0 ? {} : { [ATTR_OTELHOOK_OUTCOME]: end.outcome },
1750
+ ...usageAttributes(end?.usage, false)
1751
+ };
1752
+ status = outcomeStatus(end?.outcome);
1753
+ break;
1969
1754
  }
1970
- const total = combineCumulativeWithDelta(previousTotal, delta);
1971
- await stateStore.write(usageKey2, {
1972
- kind: "usage-cumulative",
1973
- usage: total,
1974
- ...markerFor(options?.delivery)
1975
- });
1976
- return { total, epoch: await readEpoch(key) };
1977
- });
1978
- const recordReset = (key, options) => withOptionalSessionLock(stateStore, key.sessionId, async () => {
1979
- const epochKey = rollupEpochKey(key.sessionId, key.scope, key.scopeKey);
1980
- const existingEpoch = await stateStore.read(epochKey);
1981
- const marker = existingEpoch?.value.kind === "attributes" ? readEpochMarker(existingEpoch.value.attributes) : void 0;
1982
- if (alreadyApplied(marker, options?.delivery)) {
1983
- return { epoch: await readEpoch(key) };
1755
+ case "tool": {
1756
+ const start = group.start?.type === "tool.start" ? group.start : void 0;
1757
+ const end = group.end?.type === "tool.end" ? group.end : void 0;
1758
+ const toolName = start?.toolName ?? end?.toolName ?? "unknown";
1759
+ name = `tool ${toolName}`;
1760
+ kind = SpanKind.CLIENT;
1761
+ attributes = {
1762
+ // Target keys are re-chosen below as one unit, never mixed across edges.
1763
+ ...withoutTarget(attributes),
1764
+ [ATTR_GEN_AI_TOOL_NAME]: toolName,
1765
+ [ATTR_GEN_AI_TOOL_CALL_ID]: start?.toolCallId ?? end?.toolCallId ?? group.ref.scopeKey,
1766
+ ...start?.toolKind === void 0 ? {} : { [ATTR_OTELHOOK_TOOL_KIND]: start.toolKind },
1767
+ ...end?.outcome === void 0 ? {} : { [ATTR_OTELHOOK_OUTCOME]: end.outcome },
1768
+ ...strongestTarget([
1769
+ pickTarget(resolved.recovered),
1770
+ start === void 0 ? {} : targetAttributes(start),
1771
+ end === void 0 ? {} : targetAttributes(end)
1772
+ ])
1773
+ };
1774
+ status = outcomeStatus(end?.outcome);
1775
+ break;
1984
1776
  }
1985
- const epoch = await readEpoch(key) + 1;
1986
- const applied = markerFor(options?.delivery).appliedDelivery;
1987
- await stateStore.write(epochKey, {
1988
- kind: "attributes",
1989
- attributes: {
1990
- epoch,
1991
- ...applied === void 0 ? {} : { resetDelivery: applied.callbackId, resetApplications: applied.applications }
1992
- }
1993
- });
1994
- await stateStore.delete(rollupUsageKey(key.sessionId, key.scope, key.scopeKey));
1995
- return { epoch };
1996
- });
1997
- const read = async (key) => {
1998
- const record = await stateStore.read(rollupUsageKey(key.sessionId, key.scope, key.scopeKey));
1999
- if (record?.value.kind !== "usage-cumulative") {
2000
- return void 0;
1777
+ case "subagent": {
1778
+ const start = group.start?.type === "subagent.start" ? group.start : void 0;
1779
+ const end = group.end?.type === "subagent.end" ? group.end : void 0;
1780
+ name = "subagent";
1781
+ kind = SpanKind.INTERNAL;
1782
+ attributes = {
1783
+ ...attributes,
1784
+ ...start?.delegationDepth === void 0 ? {} : { [ATTR_OTELHOOK_DELEGATION_DEPTH]: start.delegationDepth },
1785
+ ...end?.outcome === void 0 ? {} : { [ATTR_OTELHOOK_OUTCOME]: end.outcome },
1786
+ ...usageAttributes(end?.usage, false)
1787
+ };
1788
+ status = outcomeStatus(end?.outcome);
1789
+ break;
2001
1790
  }
2002
- return { total: record.value.usage, epoch: await readEpoch(key) };
2003
- };
2004
- const cleanup = async (maxAgeMillis, options) => {
2005
- const cap = options?.maxEntries ?? 1e3;
2006
- const now = clock.now();
2007
- let removed = 0;
2008
- let scanned = 0;
2009
- const sweep = async (keys) => {
2010
- for (const key of keys) {
2011
- if (scanned >= cap) {
2012
- return;
2013
- }
2014
- scanned += 1;
2015
- const record = await stateStore.read(key);
2016
- if (record !== void 0 && now - record.updatedAt > maxAgeMillis) {
2017
- await stateStore.delete(key);
2018
- removed += 1;
2019
- }
2020
- }
2021
- };
2022
- await sweep(await stateStore.keys(rollupScanPrefix(options?.sessionId)));
2023
- await sweep(await stateStore.keys(rollupEpochScanPrefix(options?.sessionId)));
2024
- return { removed, scanned };
1791
+ }
1792
+ if (status.code === SpanStatusCode.ERROR) {
1793
+ attributes = { ...attributes, [ATTR_ERROR_TYPE]: status.message ?? "error" };
1794
+ }
1795
+ return toReadableSpan({
1796
+ name,
1797
+ kind,
1798
+ startMillis: resolved.startMillis,
1799
+ endMillis: resolved.endMillis,
1800
+ attributes,
1801
+ status,
1802
+ traceId,
1803
+ spanId,
1804
+ ...parentSpanId === void 0 ? {} : { parentSpanId },
1805
+ resource,
1806
+ instrumentationScope: scope
1807
+ });
1808
+ };
1809
+ var buildStandaloneSpan = (event2, resource, scope) => {
1810
+ const providerId = event2.provenance.providerId;
1811
+ const traceId = deriveTraceId(providerId, event2.sessionId);
1812
+ const spanId = deriveStandaloneSpanId(providerId, event2.sessionId, event2.type, event2.eventId);
1813
+ const parent = parentScopeRefOf(event2);
1814
+ const parentSpanId = parent === void 0 ? void 0 : deriveSpanId(providerId, event2.sessionId, parent);
1815
+ let attributes = {
1816
+ ...identityAttributes(event2, resource, {
1817
+ traceId,
1818
+ spanId,
1819
+ ...parentSpanId === void 0 ? {} : { parentSpanId }
1820
+ }),
1821
+ [ATTR_OTELHOOK_SPAN_PAIRED]: true
2025
1822
  };
2026
- return { accumulateDelta, recordReset, read, cleanup };
1823
+ let status = { code: SpanStatusCode.UNSET };
1824
+ let name = event2.type;
1825
+ switch (event2.type) {
1826
+ case "prompt.submitted":
1827
+ name = "prompt";
1828
+ attributes = { ...attributes, "otelhook.prompt.source": event2.promptSource, ...targetAttributes(event2) };
1829
+ break;
1830
+ case "compaction.performed":
1831
+ name = "compaction";
1832
+ attributes = {
1833
+ ...attributes,
1834
+ [ATTR_OTELHOOK_COMPACTION_TRIGGER]: event2.trigger,
1835
+ ...usageAttributes(event2.usage, false)
1836
+ };
1837
+ break;
1838
+ case "error.raised":
1839
+ name = "error";
1840
+ status = { code: SpanStatusCode.ERROR, message: event2.errorCode };
1841
+ attributes = {
1842
+ ...attributes,
1843
+ [ATTR_ERROR_TYPE]: event2.errorCode,
1844
+ "otelhook.error.phase": event2.phase,
1845
+ "otelhook.error.retryable": event2.retryable
1846
+ };
1847
+ break;
1848
+ default:
1849
+ break;
1850
+ }
1851
+ return toReadableSpan({
1852
+ name,
1853
+ kind: SpanKind.INTERNAL,
1854
+ startMillis: event2.occurredAt,
1855
+ endMillis: event2.occurredAt,
1856
+ attributes,
1857
+ status,
1858
+ traceId,
1859
+ spanId,
1860
+ ...parentSpanId === void 0 ? {} : { parentSpanId },
1861
+ resource,
1862
+ instrumentationScope: scope
1863
+ });
2027
1864
  };
2028
-
2029
- // src/privacy/service.ts
2030
- import { createHash as createHash2 } from "crypto";
2031
-
2032
- // src/model/extensions.ts
2033
- import { z as z5 } from "zod";
2034
- var EXTENSION_KEY_PATTERN = /^[a-z][a-z0-9]*(?:[-_][a-z0-9]+)*(?:\.[a-z][a-z0-9]*(?:[-_][a-z0-9]+)*)+$/;
2035
- var RESERVED_EXTENSION_NAMESPACES = Object.freeze([
2036
- "otelhook",
2037
- "otel",
2038
- "telemetry"
2039
- ]);
2040
- var MAX_EXTENSION_ENTRIES = 64;
2041
- var extensionKeyNamespace = (key) => key.slice(0, key.indexOf("."));
2042
- var isReservedExtensionNamespace = (key) => RESERVED_EXTENSION_NAMESPACES.includes(extensionKeyNamespace(key));
2043
- var isValidExtensionKey = (key) => EXTENSION_KEY_PATTERN.test(key) && !isReservedExtensionNamespace(key);
2044
- var extensionsSchema = z5.record(z5.string(), attributeValueSchema).check((ctx) => {
2045
- const keys = Object.keys(ctx.value);
2046
- if (keys.length > MAX_EXTENSION_ENTRIES) {
2047
- ctx.issues.push({
2048
- code: "custom",
2049
- input: ctx.value,
2050
- message: `extensions may contain at most ${MAX_EXTENSION_ENTRIES} entries`
2051
- });
1865
+ var effectiveCorrelation = (group, correlation) => {
1866
+ if (correlation !== void 0 || group.end !== void 0 || group.start === void 0) {
1867
+ return correlation;
2052
1868
  }
2053
- for (const key of keys) {
2054
- if (!EXTENSION_KEY_PATTERN.test(key)) {
2055
- ctx.issues.push({
2056
- code: "custom",
2057
- input: ctx.value,
2058
- path: [key],
2059
- message: `extension key ${JSON.stringify(key)} must be namespaced, e.g. "acme.tier"`
2060
- });
1869
+ return {
1870
+ providerId: group.start.provenance.providerId,
1871
+ sessionId: group.start.sessionId,
1872
+ ref: group.ref,
1873
+ pairing: "unpaired",
1874
+ orphan: "state-unavailable",
1875
+ disposition: "emit",
1876
+ spanIdDiscriminator: group.start.eventId
1877
+ };
1878
+ };
1879
+ var layoutBatch = (events) => {
1880
+ const groups = /* @__PURE__ */ new Map();
1881
+ const standalone = [];
1882
+ const groupOf = /* @__PURE__ */ new Map();
1883
+ for (const event2 of events) {
1884
+ const ref = spanScopeRefOf(event2);
1885
+ if (ref === void 0) {
1886
+ standalone.push(event2);
2061
1887
  continue;
2062
1888
  }
2063
- if (isReservedExtensionNamespace(key)) {
2064
- ctx.issues.push({
2065
- code: "custom",
2066
- input: ctx.value,
2067
- path: [key],
2068
- message: `extension namespace ${JSON.stringify(extensionKeyNamespace(key))} is reserved`
2069
- });
1889
+ const groupKey = correlationKey(event2.provenance.providerId, event2.sessionId, ref);
1890
+ const group = groups.get(groupKey) ?? { ref };
1891
+ if (event2.type.endsWith(".start")) {
1892
+ group.start = event2;
1893
+ } else {
1894
+ group.end = event2;
2070
1895
  }
1896
+ groups.set(groupKey, group);
1897
+ groupOf.set(event2.eventId, groupKey);
2071
1898
  }
2072
- });
2073
- var EMPTY_EXTENSIONS = Object.freeze({});
2074
- var emptyExtensions = () => ({});
2075
-
2076
- // src/privacy/policy.ts
2077
- import { z as z6 } from "zod";
2078
- var contentModeSchema = z6.enum(["omit", "mask", "redact", "raw"]);
2079
- var CONTENT_MODE_DISCLOSURE = Object.freeze({
2080
- omit: "omitted",
2081
- mask: "masked",
2082
- redact: "redacted",
2083
- raw: "raw"
2084
- });
2085
- var DEFAULT_SECRET_KEY_PATTERNS = Object.freeze([
2086
- "(^|[._-])(secret|secrets)([._-]|$)",
2087
- "(^|[._-])(token|tokens)([._-]|$)",
2088
- "(^|[._-])(password|passwd|pwd)([._-]|$)",
2089
- "(^|[._-])(credential|credentials)([._-]|$)",
2090
- "(^|[._-])(api[._-]?key|apikey|access[._-]?key|secret[._-]?key|private[._-]?key)([._-]|$)",
2091
- "(^|[._-])(authorization|auth[._-]?header|bearer)([._-]|$)",
2092
- "(^|[._-])(cookie|set[._-]?cookie)([._-]|$)",
2093
- "(^|[._-])(signature|sig)([._-]|$)"
2094
- ]);
2095
- var DEFAULT_SECRET_VALUE_PATTERNS = Object.freeze([
2096
- "AKIA[0-9A-Z]{16}",
2097
- "sk-[A-Za-z0-9_-]{16,}",
2098
- "gh[pousr]_[A-Za-z0-9]{16,}",
2099
- "xox[abprs]-[A-Za-z0-9-]{10,}",
2100
- "-----BEGIN[A-Z ]*PRIVATE KEY-----",
2101
- "eyJ[A-Za-z0-9_-]{10,}\\.[A-Za-z0-9_-]{10,}\\.[A-Za-z0-9_-]{10,}",
2102
- "(?:Bearer|Basic)\\s+[A-Za-z0-9._~+/=-]{12,}"
2103
- ]);
2104
- var privacyLimitsSchema = z6.strictObject({
2105
- /** Maximum characters of disclosed text per content fact or string value. */
2106
- maxStringLength: z6.number().int().min(0).max(65536),
2107
- /** Maximum nesting depth walked when sanitizing structured values. */
2108
- maxDepth: z6.number().int().min(1).max(32),
2109
- /** Maximum array entries retained when sanitizing structured values. */
2110
- maxArrayLength: z6.number().int().min(1).max(4096),
2111
- /** Maximum canonical events emitted per invocation. */
2112
- maxEventsPerInvocation: z6.number().int().min(1).max(1e4),
2113
- /** Maximum object keys retained per level when sanitizing. */
2114
- maxObjectKeys: z6.number().int().min(1).max(1024)
2115
- });
2116
- var privacyPolicySchema = z6.strictObject({
2117
- contentMode: contentModeSchema,
2118
- /**
2119
- * `raw` mode is refused unless this is also true, so a single mistyped
2120
- * environment variable cannot start exporting prompts.
2121
- */
2122
- allowRawContent: z6.boolean(),
2123
- /**
2124
- * Salt mixed into every hash. A per-deployment salt makes hashes
2125
- * non-correlatable across deployments; an empty salt makes them globally
2126
- * comparable. Both are legitimate; the choice is explicit.
2127
- */
2128
- hashSalt: z6.string().max(256),
2129
- maskCharacter: z6.string().length(1),
2130
- redactionPlaceholder: z6.string().min(1).max(64),
2131
- secretKeyPatterns: z6.array(z6.string().min(1)).max(128).readonly(),
2132
- secretValuePatterns: z6.array(z6.string().min(1)).max(128).readonly(),
2133
- limits: privacyLimitsSchema
2134
- });
2135
- var DEFAULT_PRIVACY_LIMITS = Object.freeze({
2136
- maxStringLength: 1024,
2137
- maxDepth: 6,
2138
- maxArrayLength: 64,
2139
- maxEventsPerInvocation: 512,
2140
- maxObjectKeys: 128
2141
- });
2142
- var DEFAULT_PRIVACY_POLICY = Object.freeze({
2143
- contentMode: "omit",
2144
- allowRawContent: false,
2145
- hashSalt: "",
2146
- maskCharacter: "*",
2147
- redactionPlaceholder: "[redacted]",
2148
- secretKeyPatterns: DEFAULT_SECRET_KEY_PATTERNS,
2149
- secretValuePatterns: DEFAULT_SECRET_VALUE_PATTERNS,
2150
- limits: DEFAULT_PRIVACY_LIMITS
2151
- });
2152
- var resolvePrivacyPolicy = (policy) => {
2153
- const parsed = privacyPolicySchema.parse(policy);
2154
- if (parsed.contentMode === "raw" && !parsed.allowRawContent) {
2155
- return {
2156
- policy: { ...parsed, contentMode: "omit" },
2157
- notes: ["contentMode=raw downgraded to omit because allowRawContent is false"]
2158
- };
1899
+ return { groups, standalone, groupOf };
1900
+ };
1901
+ var indexCorrelations = (correlations) => {
1902
+ const indexed = /* @__PURE__ */ new Map();
1903
+ for (const correlation of correlations ?? []) {
1904
+ indexed.set(
1905
+ correlationKey(correlation.providerId, correlation.sessionId, correlation.ref),
1906
+ correlation
1907
+ );
2159
1908
  }
2160
- return { policy: parsed, notes: [] };
1909
+ return indexed;
2161
1910
  };
2162
-
2163
- // src/privacy/service.ts
2164
- var compilePatterns = (sources, flags) => {
2165
- const compiled = [];
2166
- for (const source of sources) {
2167
- try {
2168
- compiled.push(new RegExp(source, flags));
2169
- } catch {
1911
+ var planGroup = (group, correlation, correlationAvailable) => {
1912
+ const anchor = group.start ?? group.end;
1913
+ if (anchor === void 0) {
1914
+ return void 0;
1915
+ }
1916
+ const providerId = anchor.provenance.providerId;
1917
+ const sessionId = anchor.sessionId;
1918
+ const durablyRecorded = group.end === void 0 && (correlation?.disposition === "defer" || // No correlator wired at all: cross-process pairing was never on offer, so
1919
+ // this is the documented no-state-root degradation rather than a failure to
1920
+ // persist something that should have been persisted.
1921
+ correlation === void 0 && correlationAvailable === void 0);
1922
+ const effective = durablyRecorded ? correlation : effectiveCorrelation(group, correlation);
1923
+ const discriminator = durablyRecorded ? void 0 : effective?.spanIdDiscriminator;
1924
+ return {
1925
+ group,
1926
+ anchor,
1927
+ emits: !durablyRecorded,
1928
+ correlation: effective,
1929
+ traceId: deriveTraceId(providerId, sessionId),
1930
+ spanId: discriminator === void 0 ? deriveSpanId(providerId, sessionId, group.ref) : digestHex(
1931
+ [
1932
+ "otelhook/span",
1933
+ providerId,
1934
+ sessionId,
1935
+ group.ref.family,
1936
+ group.ref.scopeKey,
1937
+ discriminator
1938
+ ],
1939
+ 16
1940
+ )
1941
+ };
1942
+ };
1943
+ var canonicalEventTraceIdentities = (events, options = {}) => {
1944
+ const layout = layoutBatch(events);
1945
+ const correlations = indexCorrelations(options.correlations);
1946
+ const plans = /* @__PURE__ */ new Map();
1947
+ for (const [groupKey, group] of layout.groups) {
1948
+ const plan = planGroup(group, correlations.get(groupKey), options.correlationAvailable);
1949
+ if (plan !== void 0) {
1950
+ plans.set(groupKey, plan);
1951
+ }
1952
+ }
1953
+ const identities = /* @__PURE__ */ new Map();
1954
+ for (const event2 of events) {
1955
+ const providerId = event2.provenance.providerId;
1956
+ const groupKey = layout.groupOf.get(event2.eventId);
1957
+ const plan = groupKey === void 0 ? void 0 : plans.get(groupKey);
1958
+ if (plan === void 0) {
1959
+ const parent2 = parentScopeRefOf(event2);
1960
+ identities.set(event2.eventId, {
1961
+ traceId: deriveTraceId(providerId, event2.sessionId),
1962
+ spanId: deriveStandaloneSpanId(providerId, event2.sessionId, event2.type, event2.eventId),
1963
+ ...parent2 === void 0 ? {} : { parentSpanId: deriveSpanId(providerId, event2.sessionId, parent2) }
1964
+ });
2170
1965
  continue;
2171
1966
  }
1967
+ const parent = plan.correlation?.parent ?? parentScopeRefOf(event2);
1968
+ identities.set(event2.eventId, {
1969
+ traceId: plan.traceId,
1970
+ spanId: plan.spanId,
1971
+ ...parent === void 0 ? {} : { parentSpanId: deriveSpanId(providerId, event2.sessionId, parent) }
1972
+ });
2172
1973
  }
2173
- return compiled;
1974
+ return identities;
2174
1975
  };
2175
- var codePointLength = (value) => [...value].length;
2176
- var isSanitizedArray = (value) => Array.isArray(value);
2177
- var sliceCodePoints = (value, max) => {
2178
- if (max <= 0) {
2179
- return "";
1976
+ var canonicalEventsToReadableSpans = (events, options) => {
1977
+ const scope = options.instrumentationScope ?? DEFAULT_INSTRUMENTATION_SCOPE;
1978
+ const layout = layoutBatch(events);
1979
+ const correlations = indexCorrelations(options.correlations);
1980
+ const spans = [];
1981
+ for (const [groupKey, group] of layout.groups) {
1982
+ const plan = planGroup(group, correlations.get(groupKey), options.correlationAvailable);
1983
+ if (plan === void 0 || !plan.emits) {
1984
+ continue;
1985
+ }
1986
+ spans.push(buildLifecycleSpan(plan, options.resource, scope));
2180
1987
  }
2181
- let result = "";
1988
+ for (const event2 of layout.standalone) {
1989
+ spans.push(buildStandaloneSpan(event2, options.resource, scope));
1990
+ }
1991
+ return spans;
1992
+ };
1993
+
1994
+ // src/lifecycle/span-correlator.ts
1995
+ var SPAN_RECORD_VERSION = 2;
1996
+ var DEFAULT_MAX_START_AGE_MILLIS = 24 * 60 * 60 * 1e3;
1997
+ var ATTRIBUTE_PREFIX = "a:";
1998
+ var SPAN_FAMILIES = ["session", "generation", "tool", "subagent"];
1999
+ var isSpanFamily = (value) => typeof value === "string" && SPAN_FAMILIES.includes(value);
2000
+ var optionalNumber = (value) => typeof value === "number" && Number.isFinite(value) ? value : void 0;
2001
+ var optionalString = (value) => typeof value === "string" && value.length > 0 ? value : void 0;
2002
+ var encodeAttributes = (attributes) => {
2003
+ const encoded = {};
2182
2004
  let count = 0;
2183
- for (const char of value) {
2184
- if (count >= max) {
2005
+ for (const [key, value] of Object.entries(attributes ?? {})) {
2006
+ if (count >= MAX_RECOVERED_START_ATTRIBUTES) {
2185
2007
  break;
2186
2008
  }
2187
- result += char;
2009
+ const encodedKey = `${ATTRIBUTE_PREFIX}${key}`;
2010
+ if (encodedKey.length > MAX_IDENTIFIER_LENGTH) {
2011
+ continue;
2012
+ }
2013
+ if (typeof value === "string") {
2014
+ encoded[encodedKey] = value.slice(0, MAX_ATTRIBUTE_STRING_LENGTH);
2015
+ } else if (typeof value === "number" && Number.isFinite(value)) {
2016
+ encoded[encodedKey] = value;
2017
+ } else if (typeof value === "boolean") {
2018
+ encoded[encodedKey] = value;
2019
+ } else {
2020
+ continue;
2021
+ }
2188
2022
  count += 1;
2189
2023
  }
2190
- return result;
2024
+ return encoded;
2191
2025
  };
2192
- var stableStringify = (value) => {
2193
- const seen = /* @__PURE__ */ new WeakSet();
2194
- const walk = (input) => {
2195
- if (input === null) {
2196
- return "null";
2197
- }
2198
- if (typeof input === "string") {
2199
- return JSON.stringify(input);
2200
- }
2201
- if (typeof input === "number") {
2202
- return Number.isFinite(input) ? JSON.stringify(input) : "null";
2203
- }
2204
- if (typeof input === "boolean") {
2205
- return input ? "true" : "false";
2206
- }
2207
- if (typeof input === "bigint") {
2208
- return JSON.stringify(input.toString());
2209
- }
2210
- if (typeof input !== "object") {
2211
- return "null";
2212
- }
2213
- if (seen.has(input)) {
2214
- return '"<circular>"';
2026
+ var decodeAttributes = (attributes) => {
2027
+ const decoded = {};
2028
+ let count = 0;
2029
+ for (const [key, value] of Object.entries(attributes)) {
2030
+ if (!key.startsWith(ATTRIBUTE_PREFIX) || count >= MAX_RECOVERED_START_ATTRIBUTES) {
2031
+ continue;
2215
2032
  }
2216
- seen.add(input);
2217
- if (Array.isArray(input)) {
2218
- return `[${input.map((entry) => walk(entry)).join(",")}]`;
2033
+ if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
2034
+ decoded[key.slice(ATTRIBUTE_PREFIX.length)] = value;
2035
+ count += 1;
2219
2036
  }
2220
- const record = input;
2221
- const keys = Object.keys(record).sort();
2222
- return `{${keys.map((key) => `${JSON.stringify(key)}:${walk(record[key])}`).join(",")}}`;
2223
- };
2224
- return walk(value);
2037
+ }
2038
+ return count === 0 ? void 0 : decoded;
2225
2039
  };
2226
- var emptyStats = () => ({
2227
- truncatedStrings: 0,
2228
- truncatedArrays: 0,
2229
- truncatedObjects: 0,
2230
- redactedKeys: 0,
2231
- depthExceeded: 0,
2232
- droppedValues: 0,
2233
- circularReferences: 0
2040
+ var encodeRecord = (record) => ({
2041
+ kind: "attributes",
2042
+ attributes: {
2043
+ v: SPAN_RECORD_VERSION,
2044
+ providerId: record.providerId,
2045
+ ...record.startEventId === void 0 ? {} : { startEventId: record.startEventId },
2046
+ ...record.startedAt === void 0 ? {} : { startedAt: record.startedAt },
2047
+ ...record.endEventId === void 0 ? {} : { endEventId: record.endEventId },
2048
+ ...record.endedAt === void 0 ? {} : { endedAt: record.endedAt },
2049
+ ...record.exported === true ? { exported: true } : {},
2050
+ ...record.parent === void 0 ? {} : { parentFamily: record.parent.family, parentScopeKey: record.parent.scopeKey },
2051
+ ...encodeAttributes(record.attributes)
2052
+ }
2234
2053
  });
2235
- var createPrivacyService = (policyInput) => {
2236
- const { policy, notes } = resolvePrivacyPolicy(policyInput);
2237
- const limits = policy.limits;
2238
- const secretKeyPatterns = compilePatterns(policy.secretKeyPatterns, "i");
2239
- const secretValuePatterns = compilePatterns(policy.secretValuePatterns, "g");
2240
- const hash = (value) => `sha256:${createHash2("sha256").update(policy.hashSalt).update("\0").update(value, "utf8").digest("hex")}`;
2241
- const isSecretKey = (key) => secretKeyPatterns.some((pattern) => pattern.test(key));
2242
- const boundString = (value) => {
2243
- const length = codePointLength(value);
2244
- if (length <= limits.maxStringLength) {
2245
- return { text: value, truncated: false };
2246
- }
2247
- return { text: sliceCodePoints(value, limits.maxStringLength), truncated: true };
2248
- };
2249
- const redactSecretSpans = (value) => {
2250
- let count = 0;
2251
- let text = value;
2252
- for (const pattern of secretValuePatterns) {
2253
- text = text.replace(new RegExp(pattern.source, pattern.flags), () => {
2254
- count += 1;
2255
- return policy.redactionPlaceholder;
2256
- });
2257
- }
2258
- return { text, count };
2259
- };
2260
- const maskText = (value) => Array.from(value, (char) => /\s/.test(char) ? char : policy.maskCharacter).join("");
2261
- const disclose = (original) => {
2262
- switch (policy.contentMode) {
2263
- case "omit":
2264
- return { text: void 0, truncated: false, secretsRedacted: 0 };
2265
- case "mask": {
2266
- const bounded = boundString(original);
2267
- return { text: maskText(bounded.text), truncated: bounded.truncated, secretsRedacted: 0 };
2268
- }
2269
- case "redact": {
2270
- const redacted = redactSecretSpans(original);
2271
- const bounded = boundString(redacted.text);
2272
- return {
2273
- text: bounded.text,
2274
- truncated: bounded.truncated,
2275
- secretsRedacted: redacted.count
2276
- };
2277
- }
2278
- case "raw": {
2279
- const bounded = boundString(original);
2280
- return { text: bounded.text, truncated: bounded.truncated, secretsRedacted: 0 };
2281
- }
2054
+ var decodeRecord = (attributes) => {
2055
+ if (attributes["v"] !== SPAN_RECORD_VERSION) {
2056
+ return { kind: "incompatible" };
2057
+ }
2058
+ const providerId = optionalString(attributes["providerId"]);
2059
+ if (providerId === void 0) {
2060
+ return { kind: "corrupt" };
2061
+ }
2062
+ const startedAt = optionalNumber(attributes["startedAt"]);
2063
+ const startEventId = optionalString(attributes["startEventId"]);
2064
+ if (startedAt === void 0 !== (startEventId === void 0)) {
2065
+ return { kind: "corrupt" };
2066
+ }
2067
+ const endedAt = optionalNumber(attributes["endedAt"]);
2068
+ const endEventId = optionalString(attributes["endEventId"]);
2069
+ if (endedAt === void 0 !== (endEventId === void 0)) {
2070
+ return { kind: "corrupt" };
2071
+ }
2072
+ const exported = attributes["exported"] === true;
2073
+ const parentFamily = attributes["parentFamily"];
2074
+ const parentScopeKey = optionalString(attributes["parentScopeKey"]);
2075
+ const parent = isSpanFamily(parentFamily) && parentScopeKey !== void 0 ? { family: parentFamily, scopeKey: parentScopeKey } : void 0;
2076
+ const decodedAttributes = decodeAttributes(attributes);
2077
+ return {
2078
+ kind: "present",
2079
+ record: {
2080
+ providerId,
2081
+ ...startEventId === void 0 ? {} : { startEventId },
2082
+ ...startedAt === void 0 ? {} : { startedAt },
2083
+ ...endEventId === void 0 ? {} : { endEventId },
2084
+ ...endedAt === void 0 ? {} : { endedAt },
2085
+ ...parent === void 0 ? {} : { parent },
2086
+ ...exported ? { exported: true } : {},
2087
+ ...decodedAttributes === void 0 ? {} : { attributes: decodedAttributes }
2282
2088
  }
2283
2089
  };
2284
- const describeText = (input) => {
2285
- const disclosed = disclose(input.text);
2286
- return {
2287
- kind: input.kind,
2288
- ...input.role === void 0 ? {} : { role: input.role },
2289
- characterLength: codePointLength(input.text),
2290
- byteLength: Buffer.byteLength(input.text, "utf8"),
2291
- contentHash: hash(input.text),
2292
- disclosure: CONTENT_MODE_DISCLOSURE[policy.contentMode],
2293
- ...disclosed.text === void 0 ? {} : { text: disclosed.text },
2294
- truncated: disclosed.truncated,
2295
- secretsRedacted: disclosed.secretsRedacted,
2296
- ...input.label === void 0 ? {} : { label: input.label }
2297
- };
2298
- };
2299
- const sanitizeValue = (value, depth, stats, seen) => {
2300
- if (value === null) {
2301
- return null;
2302
- }
2303
- switch (typeof value) {
2304
- case "string": {
2305
- const bounded = boundString(value);
2306
- if (bounded.truncated) {
2307
- stats.truncatedStrings += 1;
2308
- }
2309
- return bounded.text;
2310
- }
2311
- case "number":
2312
- if (!Number.isFinite(value)) {
2313
- stats.droppedValues += 1;
2314
- return null;
2315
- }
2316
- return value;
2317
- case "boolean":
2318
- return value;
2319
- case "bigint":
2320
- return value.toString();
2321
- case "undefined":
2322
- case "function":
2323
- case "symbol":
2324
- stats.droppedValues += 1;
2325
- return null;
2326
- default:
2327
- break;
2090
+ };
2091
+ var factsOf = (record) => ({
2092
+ ...record.startedAt === void 0 ? {} : { startedAt: record.startedAt },
2093
+ ...record.endedAt === void 0 ? {} : { endedAt: record.endedAt },
2094
+ ...record.parent === void 0 ? {} : { parent: record.parent },
2095
+ ...record.attributes === void 0 ? {} : { attributes: record.attributes }
2096
+ });
2097
+ var correlationTimesOf = (facts, options = { withStart: true }) => ({
2098
+ ...facts.startedAt === void 0 || !options.withStart ? {} : { startMillis: facts.startedAt },
2099
+ ...facts.endedAt === void 0 ? {} : { endMillis: facts.endedAt },
2100
+ ...facts.parent === void 0 ? {} : { parent: facts.parent },
2101
+ ...facts.attributes === void 0 ? {} : { attributes: facts.attributes }
2102
+ });
2103
+ var orphanClassificationOf = (reason) => {
2104
+ switch (reason) {
2105
+ case "no-start-recorded":
2106
+ return "missing-start";
2107
+ case "start-expired":
2108
+ return "expired-start";
2109
+ case "already-closed":
2110
+ return "already-closed";
2111
+ case "provider-mismatch":
2112
+ return "provider-mismatch";
2113
+ case "state-incompatible":
2114
+ return "state-incompatible";
2115
+ case "state-corrupt":
2116
+ return "state-corrupt";
2117
+ }
2118
+ };
2119
+ var createSpanCorrelator = (deps) => {
2120
+ const { stateStore, clock } = deps;
2121
+ const maxStartAgeMillis = deps.maxStartAgeMillis ?? DEFAULT_MAX_START_AGE_MILLIS;
2122
+ const keyFor = (input) => spanKey(input.sessionId, input.providerId, input.scope, input.scopeKey);
2123
+ const readRecord = async (key) => {
2124
+ const existing = await stateStore.read(key);
2125
+ if (existing === void 0) {
2126
+ return { kind: "absent" };
2328
2127
  }
2329
- if (depth >= limits.maxDepth) {
2330
- stats.depthExceeded += 1;
2331
- return "<depth-exceeded>";
2128
+ if (existing.value.kind !== "attributes") {
2129
+ await stateStore.delete(key);
2130
+ return { kind: "corrupt" };
2332
2131
  }
2333
- if (seen.has(value)) {
2334
- stats.circularReferences += 1;
2335
- return "<circular>";
2132
+ const decoded = decodeRecord(existing.value.attributes);
2133
+ if (decoded.kind === "corrupt" || decoded.kind === "incompatible") {
2134
+ await stateStore.delete(key);
2336
2135
  }
2337
- seen.add(value);
2338
- if (Array.isArray(value)) {
2339
- const entries = value.slice(0, limits.maxArrayLength);
2340
- if (value.length > limits.maxArrayLength) {
2341
- stats.truncatedArrays += 1;
2136
+ return decoded;
2137
+ };
2138
+ const recordStart = (input) => withOptionalSessionLock(stateStore, input.sessionId, async () => {
2139
+ const key = keyFor(input);
2140
+ const decoded = await readRecord(key);
2141
+ if (decoded.kind === "present") {
2142
+ const existing = decoded.record;
2143
+ if (existing.providerId !== input.providerId) {
2144
+ return { status: "conflict", reason: "provider-mismatch" };
2145
+ }
2146
+ if (existing.startEventId === input.eventId) {
2147
+ return { status: "duplicate", facts: factsOf(existing) };
2148
+ }
2149
+ if (existing.startEventId === void 0 && existing.endEventId !== void 0) {
2150
+ const completed = {
2151
+ ...existing,
2152
+ startEventId: input.eventId,
2153
+ startedAt: input.occurredAt,
2154
+ ...input.parent === void 0 ? {} : { parent: input.parent },
2155
+ ...input.attributes === void 0 ? {} : { attributes: input.attributes }
2156
+ };
2157
+ await stateStore.write(key, encodeRecord(completed));
2158
+ return existing.exported === true ? { status: "published", facts: factsOf(completed) } : { status: "recorded", facts: factsOf(completed) };
2342
2159
  }
2343
- return entries.map((entry) => sanitizeValue(entry, depth + 1, stats, seen));
2344
2160
  }
2345
- if (value instanceof Date) {
2346
- return value.toISOString();
2161
+ const fresh = {
2162
+ providerId: input.providerId,
2163
+ startEventId: input.eventId,
2164
+ startedAt: input.occurredAt,
2165
+ ...input.parent === void 0 ? {} : { parent: input.parent },
2166
+ ...input.attributes === void 0 ? {} : { attributes: input.attributes }
2167
+ };
2168
+ await stateStore.write(key, encodeRecord(fresh));
2169
+ return { status: "recorded", facts: factsOf(fresh) };
2170
+ });
2171
+ const recordEnd = (input) => withOptionalSessionLock(stateStore, input.sessionId, async () => {
2172
+ const key = keyFor(input);
2173
+ const decoded = await readRecord(key);
2174
+ if (decoded.kind === "incompatible" || decoded.kind === "corrupt") {
2175
+ const reason = decoded.kind === "incompatible" ? "state-incompatible" : "state-corrupt";
2176
+ return { status: "orphaned", reason, facts: { endedAt: input.occurredAt } };
2347
2177
  }
2348
- const record = value;
2349
- const keys = Object.keys(record);
2350
- const retained = keys.slice(0, limits.maxObjectKeys);
2351
- if (keys.length > limits.maxObjectKeys) {
2352
- stats.truncatedObjects += 1;
2178
+ if (decoded.kind === "absent") {
2179
+ const endOnly = {
2180
+ providerId: input.providerId,
2181
+ endEventId: input.eventId,
2182
+ endedAt: input.occurredAt,
2183
+ // This end is about to be exported as an orphan under the scope's
2184
+ // canonical span id, so a start arriving later must not reuse it.
2185
+ exported: true
2186
+ };
2187
+ await stateStore.write(key, encodeRecord(endOnly));
2188
+ return { status: "orphaned", reason: "no-start-recorded", facts: factsOf(endOnly) };
2353
2189
  }
2354
- const result = {};
2355
- for (const key of retained) {
2356
- if (isSecretKey(key)) {
2357
- stats.redactedKeys += 1;
2358
- result[key] = policy.redactionPlaceholder;
2359
- continue;
2360
- }
2361
- result[key] = sanitizeValue(record[key], depth + 1, stats, seen);
2190
+ const existing = decoded.record;
2191
+ if (existing.providerId !== input.providerId) {
2192
+ return {
2193
+ status: "orphaned",
2194
+ reason: "provider-mismatch",
2195
+ facts: { endedAt: input.occurredAt }
2196
+ };
2362
2197
  }
2363
- return result;
2364
- };
2365
- const sanitizeStructured = (value) => {
2366
- const stats = emptyStats();
2367
- const sanitized = sanitizeValue(value, 0, stats, /* @__PURE__ */ new WeakSet());
2368
- return { value: sanitized, stats };
2369
- };
2370
- const toAttributePrimitive = (value) => {
2371
- if (typeof value === "string") {
2372
- return value.slice(0, MAX_ATTRIBUTE_STRING_LENGTH);
2198
+ if (existing.endEventId === input.eventId) {
2199
+ return { status: "duplicate", facts: factsOf(existing) };
2373
2200
  }
2374
- if (typeof value === "number" || typeof value === "boolean") {
2375
- return value;
2201
+ if (existing.endEventId !== void 0) {
2202
+ return {
2203
+ status: "orphaned",
2204
+ reason: "already-closed",
2205
+ facts: { endedAt: input.occurredAt }
2206
+ };
2376
2207
  }
2377
- return void 0;
2378
- };
2379
- const flattenToAttributes = (value, prefix) => {
2380
- const attributes = {};
2381
- const walk = (current, path5) => {
2382
- if (typeof current === "string" || typeof current === "number" || typeof current === "boolean") {
2383
- const primitive = toAttributePrimitive(current);
2384
- if (primitive !== void 0) {
2385
- attributes[path5] = primitive;
2386
- }
2387
- return;
2388
- }
2389
- if (current === null) {
2390
- return;
2391
- }
2392
- if (isSanitizedArray(current)) {
2393
- const primitives = [];
2394
- let uniform = true;
2395
- for (const entry of current) {
2396
- const entryPrimitive = toAttributePrimitive(entry);
2397
- if (entryPrimitive === void 0) {
2398
- uniform = false;
2399
- break;
2400
- }
2401
- primitives.push(entryPrimitive);
2402
- }
2403
- if (uniform) {
2404
- attributes[path5] = primitives.slice(0, MAX_ATTRIBUTE_ARRAY_LENGTH);
2405
- return;
2406
- }
2407
- for (const [index, entry] of current.entries()) {
2408
- walk(entry, `${path5}.${index}`);
2409
- }
2410
- return;
2411
- }
2412
- for (const [key, entry] of Object.entries(current)) {
2413
- walk(entry, path5 === "" ? key : `${path5}.${key}`);
2414
- }
2208
+ if (existing.startedAt === void 0) {
2209
+ const replaced = {
2210
+ ...existing,
2211
+ endEventId: input.eventId,
2212
+ endedAt: input.occurredAt,
2213
+ exported: true
2214
+ };
2215
+ await stateStore.write(key, encodeRecord(replaced));
2216
+ return { status: "orphaned", reason: "no-start-recorded", facts: factsOf(replaced) };
2217
+ }
2218
+ if (input.occurredAt - existing.startedAt > maxStartAgeMillis) {
2219
+ await stateStore.delete(key);
2220
+ return { status: "orphaned", reason: "start-expired", facts: { endedAt: input.occurredAt } };
2221
+ }
2222
+ const closed = {
2223
+ ...existing,
2224
+ endEventId: input.eventId,
2225
+ endedAt: input.occurredAt,
2226
+ exported: true
2415
2227
  };
2416
- walk(value, prefix);
2417
- return attributes;
2418
- };
2419
- const sanitizeAttributes = (value) => {
2420
- const attributes = {};
2421
- for (const [key, entry] of Object.entries(value)) {
2422
- if (isSecretKey(key)) {
2423
- attributes[key] = policy.redactionPlaceholder;
2424
- continue;
2228
+ await stateStore.write(key, encodeRecord(closed));
2229
+ return {
2230
+ status: "matched",
2231
+ startedAt: existing.startedAt,
2232
+ durationMillis: Math.max(0, input.occurredAt - existing.startedAt),
2233
+ facts: factsOf(closed)
2234
+ };
2235
+ });
2236
+ const correlateGroup = async (group) => {
2237
+ const base = {
2238
+ providerId: group.providerId,
2239
+ sessionId: group.sessionId,
2240
+ ref: group.ref
2241
+ };
2242
+ const unpaired = (orphan, facts) => ({
2243
+ ...base,
2244
+ pairing: "unpaired",
2245
+ orphan,
2246
+ // An unpaired span has no trustworthy start, so a start time is the one
2247
+ // fact it must not carry; everything else recovered is still true.
2248
+ ...correlationTimesOf(facts, { withStart: false })
2249
+ });
2250
+ let startFacts;
2251
+ if (group.start !== void 0) {
2252
+ const parent = parentScopeRefOf(group.start);
2253
+ const result2 = await recordStart({
2254
+ sessionId: group.sessionId,
2255
+ providerId: group.providerId,
2256
+ scope: group.ref.family,
2257
+ scopeKey: group.ref.scopeKey,
2258
+ eventId: group.start.eventId,
2259
+ occurredAt: group.start.occurredAt,
2260
+ ...parent === void 0 ? {} : { parent },
2261
+ attributes: startOnlySpanAttributes(group.start)
2262
+ });
2263
+ if (result2.status === "conflict") {
2264
+ return unpaired("provider-mismatch", {});
2425
2265
  }
2426
- const sanitized = sanitizeStructured(entry).value;
2427
- const primitive = toAttributePrimitive(sanitized);
2428
- if (primitive !== void 0) {
2429
- attributes[key] = primitive;
2430
- continue;
2266
+ if (result2.status === "published" && group.end === void 0) {
2267
+ return { ...unpaired("already-closed", result2.facts), disposition: "defer" };
2431
2268
  }
2432
- const flattened = flattenToAttributes(sanitized, key);
2433
- Object.assign(attributes, flattened);
2269
+ startFacts = result2.facts;
2434
2270
  }
2435
- return attributes;
2271
+ if (group.end === void 0) {
2272
+ const facts = startFacts ?? {};
2273
+ if (facts.endedAt !== void 0) {
2274
+ return {
2275
+ ...base,
2276
+ pairing: "cross-process",
2277
+ orphan: "none",
2278
+ disposition: "emit",
2279
+ ...correlationTimesOf(facts)
2280
+ };
2281
+ }
2282
+ return { ...unpaired("missing-end", facts), disposition: "defer" };
2283
+ }
2284
+ const result = await recordEnd({
2285
+ sessionId: group.sessionId,
2286
+ providerId: group.providerId,
2287
+ scope: group.ref.family,
2288
+ scopeKey: group.ref.scopeKey,
2289
+ eventId: group.end.eventId,
2290
+ occurredAt: group.end.occurredAt
2291
+ });
2292
+ if (result.status === "orphaned") {
2293
+ const orphan = orphanClassificationOf(result.reason);
2294
+ return orphan === "already-closed" ? {
2295
+ ...unpaired(orphan, result.facts),
2296
+ disposition: "emit",
2297
+ spanIdDiscriminator: group.end.eventId
2298
+ } : { ...unpaired(orphan, result.facts), disposition: "emit" };
2299
+ }
2300
+ if (result.status === "duplicate" && result.facts.startedAt === void 0) {
2301
+ return { ...unpaired("missing-start", result.facts), disposition: "emit" };
2302
+ }
2303
+ return {
2304
+ ...base,
2305
+ pairing: group.start === void 0 ? "cross-process" : "in-batch",
2306
+ orphan: "none",
2307
+ disposition: "emit",
2308
+ ...correlationTimesOf(result.facts)
2309
+ };
2436
2310
  };
2437
- const sanitizeExtensions = (value) => {
2438
- const extensions = {};
2439
- const droppedKeys = [];
2440
- for (const [key, entry] of Object.entries(value)) {
2441
- if (!isValidExtensionKey(key)) {
2442
- droppedKeys.push(key);
2443
- continue;
2444
- }
2445
- if (isSecretKey(key)) {
2446
- extensions[key] = policy.redactionPlaceholder;
2311
+ const correlateBatch = async (events) => {
2312
+ const groups = /* @__PURE__ */ new Map();
2313
+ for (const event2 of events) {
2314
+ const ref = spanScopeRefOf(event2);
2315
+ if (ref === void 0) {
2447
2316
  continue;
2448
2317
  }
2449
- const sanitized = sanitizeStructured(entry).value;
2450
- const candidate = attributeValueSchema.safeParse(sanitized);
2451
- if (candidate.success) {
2452
- extensions[key] = candidate.data;
2318
+ const providerId = event2.provenance.providerId;
2319
+ const groupKey = [providerId, event2.sessionId, ref.family, ref.scopeKey].join("\0");
2320
+ const group = groups.get(groupKey) ?? {
2321
+ providerId,
2322
+ sessionId: event2.sessionId,
2323
+ ref
2324
+ };
2325
+ if (event2.type.endsWith(".start")) {
2326
+ group.start = event2;
2453
2327
  } else {
2454
- droppedKeys.push(key);
2328
+ group.end = event2;
2455
2329
  }
2330
+ groups.set(groupKey, group);
2456
2331
  }
2457
- return { extensions, droppedKeys };
2332
+ const correlations = [];
2333
+ for (const group of groups.values()) {
2334
+ try {
2335
+ correlations.push(await correlateGroup(group));
2336
+ } catch {
2337
+ const unrecordedStart = group.start !== void 0 && group.end === void 0;
2338
+ correlations.push({
2339
+ providerId: group.providerId,
2340
+ sessionId: group.sessionId,
2341
+ ref: group.ref,
2342
+ pairing: "unpaired",
2343
+ orphan: "state-unavailable",
2344
+ disposition: "emit",
2345
+ ...unrecordedStart && group.start !== void 0 ? { spanIdDiscriminator: group.start.eventId } : {}
2346
+ });
2347
+ }
2348
+ }
2349
+ return correlations;
2458
2350
  };
2459
- return {
2460
- policy,
2461
- policyNotes: notes,
2462
- hash,
2463
- deriveOpaqueId: (namespace, value) => hash(`${namespace}\0${value}`),
2464
- describeContent: describeText,
2465
- describeUnavailableContent: (input) => ({
2466
- kind: input.kind,
2467
- ...input.role === void 0 ? {} : { role: input.role },
2468
- characterLength: 0,
2469
- byteLength: 0,
2470
- contentHash: hash(""),
2471
- disclosure: "omitted",
2472
- truncated: false,
2473
- secretsRedacted: 0,
2474
- ...input.label === void 0 ? {} : { label: input.label }
2475
- }),
2476
- describeStructured: (input) => {
2477
- const serialized = stableStringify(input.value);
2478
- const sanitized = sanitizeStructured(input.value);
2479
- const base = describeText({
2480
- kind: input.kind,
2481
- text: serialized,
2482
- ...input.role === void 0 ? {} : { role: input.role },
2483
- ...input.label === void 0 ? {} : { label: input.label }
2484
- });
2485
- if (base.text === void 0) {
2486
- return base;
2351
+ const cleanup = async (maxAgeMillis, options) => {
2352
+ const keys = await stateStore.keys(spanScanPrefix(options?.sessionId));
2353
+ const cap = options?.maxEntries ?? 1e3;
2354
+ const now = clock.now();
2355
+ let removed = 0;
2356
+ let scanned = 0;
2357
+ let expiredOpen = 0;
2358
+ for (const key of keys) {
2359
+ if (scanned >= cap) {
2360
+ break;
2487
2361
  }
2488
- const disclosed = disclose(stableStringify(sanitized.value));
2489
- return {
2490
- ...base,
2491
- ...disclosed.text === void 0 ? {} : { text: disclosed.text },
2492
- truncated: base.truncated || disclosed.truncated,
2493
- secretsRedacted: disclosed.secretsRedacted + sanitized.stats.redactedKeys
2494
- };
2495
- },
2496
- isSecretKey,
2497
- sanitizeStructured,
2498
- flattenToAttributes,
2499
- sanitizeAttributes,
2500
- sanitizeExtensions,
2501
- boundString
2362
+ scanned += 1;
2363
+ const record = await stateStore.read(key);
2364
+ if (record !== void 0 && now - record.updatedAt > maxAgeMillis) {
2365
+ if (record.value.kind === "attributes") {
2366
+ const decoded = decodeRecord(record.value.attributes);
2367
+ if (decoded.kind === "present" && decoded.record.startedAt !== void 0 && decoded.record.endedAt === void 0) {
2368
+ expiredOpen += 1;
2369
+ }
2370
+ }
2371
+ await stateStore.delete(key);
2372
+ removed += 1;
2373
+ }
2374
+ }
2375
+ return { removed, scanned, expiredOpen };
2502
2376
  };
2377
+ return { recordStart, recordEnd, correlateBatch, cleanup };
2503
2378
  };
2504
2379
 
2505
- // src/runtime/clock.ts
2506
- var createSystemClock = () => ({
2507
- now: () => epochMillisSchema.parse(Date.now()),
2508
- monotonicMillis: () => Number(process.hrtime.bigint() / 1000000n)
2509
- });
2510
-
2511
- // src/runtime/hook.ts
2512
- import { z as z16 } from "zod";
2513
-
2514
- // src/config/schema.ts
2515
- import { z as z8 } from "zod";
2516
-
2517
- // src/config/resource-attributes.ts
2518
- import { z as z7 } from "zod";
2519
- var MAX_RESOURCE_ATTRIBUTES = 64;
2520
- var MAX_RESOURCE_ATTRIBUTE_KEY_LENGTH = 255;
2521
- var MAX_RESOURCE_ATTRIBUTE_VALUE_LENGTH = 2048;
2522
- var RESOURCE_ATTRIBUTE_KEY_PATTERN = /^[A-Za-z][A-Za-z0-9_./-]*$/;
2523
- var RESERVED_RESOURCE_ATTRIBUTE_KEYS = Object.freeze([
2524
- "service.name",
2525
- "service.namespace"
2526
- ]);
2527
- var isReservedResourceAttributeKey = (key) => RESERVED_RESOURCE_ATTRIBUTE_KEYS.includes(key.toLowerCase());
2528
- var SECRET_KEY_MATCHERS = Object.freeze(
2529
- DEFAULT_SECRET_KEY_PATTERNS.flatMap((source) => {
2530
- try {
2531
- return [new RegExp(source, "i")];
2532
- } catch {
2533
- return [];
2534
- }
2535
- })
2536
- );
2537
- var isSecretResourceAttributeKey = (key) => SECRET_KEY_MATCHERS.some((pattern) => pattern.test(key));
2538
- var RESOURCE_ATTRIBUTE_KEY_REJECTION_DETAIL = Object.freeze({
2539
- empty: "resource attribute key is empty",
2540
- "too-long": `resource attribute key exceeds ${String(MAX_RESOURCE_ATTRIBUTE_KEY_LENGTH)} characters`,
2541
- malformed: "resource attribute key must start with a letter and use only letters, digits, and `_`, `.`, `-`, `/`",
2542
- reserved: "service.name and service.namespace are exporter policy (--service-name / OTEL_HOOK_SERVICE_NAME), not resource attributes",
2543
- "secret-like": "resource attribute key matches a secret-name pattern, so it is never exported"
2544
- });
2545
- var checkResourceAttributeKey = (key) => {
2546
- if (key.length === 0) {
2547
- return "empty";
2548
- }
2549
- if (key.length > MAX_RESOURCE_ATTRIBUTE_KEY_LENGTH) {
2550
- return "too-long";
2551
- }
2552
- if (!RESOURCE_ATTRIBUTE_KEY_PATTERN.test(key)) {
2553
- return "malformed";
2380
+ // src/lifecycle/usage-accumulator.ts
2381
+ var EMPTY_CUMULATIVE_USAGE = normalizeUsageOrThrow({ temporality: "cumulative" });
2382
+ var combineCumulativeWithDelta = (total, delta) => {
2383
+ if (total.temporality !== "cumulative") {
2384
+ throw new UsageNormalizationError([
2385
+ { code: "invalid-report", message: "usage rollup total must have cumulative temporality" }
2386
+ ]);
2554
2387
  }
2555
- if (isReservedResourceAttributeKey(key)) {
2556
- return "reserved";
2388
+ if (delta.temporality !== "delta") {
2389
+ throw new UsageNormalizationError([
2390
+ { code: "invalid-report", message: "usage accumulator only accepts delta observations" }
2391
+ ]);
2557
2392
  }
2558
- if (isSecretResourceAttributeKey(key)) {
2559
- return "secret-like";
2393
+ const accounting = total.cacheCreationInputTokens === 0 && total.cacheCreationAccounting === "not-reported" ? delta.cacheCreationAccounting : delta.cacheCreationInputTokens === 0 && delta.cacheCreationAccounting === "not-reported" ? total.cacheCreationAccounting : total.cacheCreationAccounting;
2394
+ if (total.cacheCreationInputTokens !== 0 && delta.cacheCreationInputTokens !== 0 && total.cacheCreationAccounting !== delta.cacheCreationAccounting) {
2395
+ throw new UsageNormalizationError([
2396
+ {
2397
+ code: "cache-creation-accounting-missing",
2398
+ message: "cannot roll up usage across differing cacheCreationAccounting modes"
2399
+ }
2400
+ ]);
2560
2401
  }
2561
- return void 0;
2402
+ const providerTotal = total.providerTotalTokens === void 0 && delta.providerTotalTokens === void 0 ? void 0 : (total.providerTotalTokens ?? 0) + (delta.providerTotalTokens ?? 0);
2403
+ return normalizeUsageOrThrow({
2404
+ temporality: "cumulative",
2405
+ inputTokens: total.inputTokens + delta.inputTokens,
2406
+ cachedInputTokens: total.cachedInputTokens + delta.cachedInputTokens,
2407
+ cacheCreationInputTokens: total.cacheCreationInputTokens + delta.cacheCreationInputTokens,
2408
+ cacheCreationAccounting: accounting,
2409
+ outputTokens: total.outputTokens + delta.outputTokens,
2410
+ reasoningOutputTokens: total.reasoningOutputTokens + delta.reasoningOutputTokens,
2411
+ ...providerTotal === void 0 ? {} : { providerTotalTokens: providerTotal }
2412
+ });
2562
2413
  };
2563
- var resourceAttributeValueSchema = z7.union([
2564
- z7.string().max(MAX_RESOURCE_ATTRIBUTE_VALUE_LENGTH),
2565
- z7.number().finite(),
2566
- z7.boolean()
2567
- ]);
2568
- var resourceAttributesSchema = z7.record(z7.string(), resourceAttributeValueSchema).superRefine((value, ctx) => {
2569
- const keys = Object.keys(value);
2570
- if (keys.length > MAX_RESOURCE_ATTRIBUTES) {
2571
- ctx.addIssue({
2572
- code: "custom",
2573
- message: `at most ${String(MAX_RESOURCE_ATTRIBUTES)} resource attributes are accepted`
2574
- });
2575
- }
2576
- for (const key of keys) {
2577
- const rejection = checkResourceAttributeKey(key);
2578
- if (rejection !== void 0) {
2579
- ctx.addIssue({
2580
- code: "custom",
2581
- path: [key],
2582
- message: RESOURCE_ATTRIBUTE_KEY_REJECTION_DETAIL[rejection]
2583
- });
2414
+ var createUsageAccumulator = (deps) => {
2415
+ const { stateStore, clock } = deps;
2416
+ const readEpochMarker = (attributes) => {
2417
+ const callbackId = attributes.resetDelivery;
2418
+ const applications = attributes.resetApplications;
2419
+ if (typeof callbackId !== "string" || callbackId.length === 0 || typeof applications !== "number" || !Number.isInteger(applications) || applications < 1) {
2420
+ return void 0;
2584
2421
  }
2585
- }
2586
- }).readonly();
2587
- var EMPTY_RESOURCE_ATTRIBUTES = Object.freeze({});
2588
- var sanitizeResourceAttributes = (attributes) => {
2589
- const safe = {};
2590
- for (const [key, value] of Object.entries(attributes)) {
2591
- if (checkResourceAttributeKey(key) !== void 0) {
2592
- continue;
2422
+ return { callbackId, applications };
2423
+ };
2424
+ const readEpoch = async (key) => {
2425
+ const record = await stateStore.read(rollupEpochKey(key.sessionId, key.scope, key.scopeKey));
2426
+ if (record?.value.kind === "attributes" && typeof record.value.attributes.epoch === "number") {
2427
+ return record.value.attributes.epoch;
2428
+ }
2429
+ return 0;
2430
+ };
2431
+ const alreadyApplied = (marker, delivery) => delivery !== void 0 && marker !== void 0 && marker.callbackId === delivery.callbackId && delivery.ordinal < marker.applications;
2432
+ const markerFor = (delivery) => delivery === void 0 ? {} : {
2433
+ appliedDelivery: { callbackId: delivery.callbackId, applications: delivery.ordinal + 1 }
2434
+ };
2435
+ const accumulateDelta = (key, delta, options) => withOptionalSessionLock(stateStore, key.sessionId, async () => {
2436
+ const usageKey2 = rollupUsageKey(key.sessionId, key.scope, key.scopeKey);
2437
+ const existing = await stateStore.read(usageKey2);
2438
+ const previousTotal = existing?.value.kind === "usage-cumulative" ? existing.value.usage : EMPTY_CUMULATIVE_USAGE;
2439
+ if (existing?.value.kind === "usage-cumulative" && alreadyApplied(existing.value.appliedDelivery, options?.delivery)) {
2440
+ return { total: previousTotal, epoch: await readEpoch(key) };
2441
+ }
2442
+ const total = combineCumulativeWithDelta(previousTotal, delta);
2443
+ await stateStore.write(usageKey2, {
2444
+ kind: "usage-cumulative",
2445
+ usage: total,
2446
+ ...markerFor(options?.delivery)
2447
+ });
2448
+ return { total, epoch: await readEpoch(key) };
2449
+ });
2450
+ const recordReset = (key, options) => withOptionalSessionLock(stateStore, key.sessionId, async () => {
2451
+ const epochKey = rollupEpochKey(key.sessionId, key.scope, key.scopeKey);
2452
+ const existingEpoch = await stateStore.read(epochKey);
2453
+ const marker = existingEpoch?.value.kind === "attributes" ? readEpochMarker(existingEpoch.value.attributes) : void 0;
2454
+ if (alreadyApplied(marker, options?.delivery)) {
2455
+ return { epoch: await readEpoch(key) };
2593
2456
  }
2594
- if (Object.keys(safe).length >= MAX_RESOURCE_ATTRIBUTES) {
2595
- break;
2457
+ const epoch = await readEpoch(key) + 1;
2458
+ const applied = markerFor(options?.delivery).appliedDelivery;
2459
+ await stateStore.write(epochKey, {
2460
+ kind: "attributes",
2461
+ attributes: {
2462
+ epoch,
2463
+ ...applied === void 0 ? {} : { resetDelivery: applied.callbackId, resetApplications: applied.applications }
2464
+ }
2465
+ });
2466
+ await stateStore.delete(rollupUsageKey(key.sessionId, key.scope, key.scopeKey));
2467
+ return { epoch };
2468
+ });
2469
+ const read = async (key) => {
2470
+ const record = await stateStore.read(rollupUsageKey(key.sessionId, key.scope, key.scopeKey));
2471
+ if (record?.value.kind !== "usage-cumulative") {
2472
+ return void 0;
2596
2473
  }
2597
- safe[key] = value;
2598
- }
2599
- return safe;
2474
+ return { total: record.value.usage, epoch: await readEpoch(key) };
2475
+ };
2476
+ const cleanup = async (maxAgeMillis, options) => {
2477
+ const cap = options?.maxEntries ?? 1e3;
2478
+ const now = clock.now();
2479
+ let removed = 0;
2480
+ let scanned = 0;
2481
+ const sweep = async (keys) => {
2482
+ for (const key of keys) {
2483
+ if (scanned >= cap) {
2484
+ return;
2485
+ }
2486
+ scanned += 1;
2487
+ const record = await stateStore.read(key);
2488
+ if (record !== void 0 && now - record.updatedAt > maxAgeMillis) {
2489
+ await stateStore.delete(key);
2490
+ removed += 1;
2491
+ }
2492
+ }
2493
+ };
2494
+ await sweep(await stateStore.keys(rollupScanPrefix(options?.sessionId)));
2495
+ await sweep(await stateStore.keys(rollupEpochScanPrefix(options?.sessionId)));
2496
+ return { removed, scanned };
2497
+ };
2498
+ return { accumulateDelta, recordReset, read, cleanup };
2600
2499
  };
2601
2500
 
2602
- // src/config/schema.ts
2603
- var logsPolicySchema = z8.strictObject({
2604
- enabled: z8.boolean(),
2605
- /**
2606
- * Full URL for the logs signal.
2607
- *
2608
- * Absent, it is derived from `endpoint`: a trailing `/v1/traces` becomes
2609
- * `/v1/logs`, and an endpoint with no signal path has `/v1/logs` appended.
2610
- */
2611
- endpoint: z8.string().url().max(2048).optional(),
2612
- includeContent: z8.boolean(),
2613
- maxBatchSize: z8.number().int().min(1).max(4096)
2501
+ // src/privacy/service.ts
2502
+ import { createHash as createHash2 } from "crypto";
2503
+
2504
+ // src/privacy/policy.ts
2505
+ import { z as z11 } from "zod";
2506
+ var contentModeSchema = z11.enum(["omit", "mask", "redact", "raw"]);
2507
+ var CONTENT_MODE_DISCLOSURE = Object.freeze({
2508
+ omit: "omitted",
2509
+ mask: "masked",
2510
+ redact: "redacted",
2511
+ raw: "raw"
2614
2512
  });
2615
- var DEFAULT_LOGS_POLICY = Object.freeze({
2616
- enabled: false,
2617
- includeContent: false,
2618
- maxBatchSize: 128
2513
+ var DEFAULT_SECRET_KEY_PATTERNS = Object.freeze([
2514
+ "(^|[._-])(secret|secrets)([._-]|$)",
2515
+ "(^|[._-])(token|tokens)([._-]|$)",
2516
+ "(^|[._-])(password|passwd|pwd)([._-]|$)",
2517
+ "(^|[._-])(credential|credentials)([._-]|$)",
2518
+ "(^|[._-])(api[._-]?key|apikey|access[._-]?key|secret[._-]?key|private[._-]?key)([._-]|$)",
2519
+ "(^|[._-])(authorization|auth[._-]?header|bearer)([._-]|$)",
2520
+ "(^|[._-])(cookie|set[._-]?cookie)([._-]|$)",
2521
+ "(^|[._-])(signature|sig)([._-]|$)"
2522
+ ]);
2523
+ var DEFAULT_SECRET_VALUE_PATTERNS = Object.freeze([
2524
+ "AKIA[0-9A-Z]{16}",
2525
+ "sk-[A-Za-z0-9_-]{16,}",
2526
+ "gh[pousr]_[A-Za-z0-9]{16,}",
2527
+ "xox[abprs]-[A-Za-z0-9-]{10,}",
2528
+ "-----BEGIN[A-Z ]*PRIVATE KEY-----",
2529
+ "eyJ[A-Za-z0-9_-]{10,}\\.[A-Za-z0-9_-]{10,}\\.[A-Za-z0-9_-]{10,}",
2530
+ "(?:Bearer|Basic)\\s+[A-Za-z0-9._~+/=-]{12,}"
2531
+ ]);
2532
+ var privacyLimitsSchema = z11.strictObject({
2533
+ /** Maximum characters of disclosed text per content fact or string value. */
2534
+ maxStringLength: z11.number().int().min(0).max(65536),
2535
+ /** Maximum nesting depth walked when sanitizing structured values. */
2536
+ maxDepth: z11.number().int().min(1).max(32),
2537
+ /** Maximum array entries retained when sanitizing structured values. */
2538
+ maxArrayLength: z11.number().int().min(1).max(4096),
2539
+ /** Maximum canonical events emitted per invocation. */
2540
+ maxEventsPerInvocation: z11.number().int().min(1).max(1e4),
2541
+ /** Maximum object keys retained per level when sanitizing. */
2542
+ maxObjectKeys: z11.number().int().min(1).max(1024)
2619
2543
  });
2620
- var exporterPolicySchema = z8.strictObject({
2621
- enabled: z8.boolean(),
2622
- protocol: z8.enum(["http/protobuf", "http/json", "none"]),
2623
- endpoint: z8.string().url().max(2048).optional(),
2624
- /**
2625
- * Header names only. Values are supplied separately at construction time and
2626
- * are never part of a resolved-config snapshot, which is logged and exported.
2627
- */
2628
- headerNames: z8.array(nonEmptyStringSchema).max(32).readonly(),
2629
- timeoutMillis: z8.number().int().min(1).max(6e5),
2630
- maxBatchSize: z8.number().int().min(1).max(4096),
2631
- maxQueueSize: z8.number().int().min(1).max(65536),
2632
- maxRetryAttempts: z8.number().int().min(0).max(10),
2633
- serviceName: nonEmptyStringSchema,
2634
- serviceNamespace: nonEmptyStringSchema.optional(),
2544
+ var privacyPolicySchema = z11.strictObject({
2545
+ contentMode: contentModeSchema,
2635
2546
  /**
2636
- * Custom attributes merged into the exported OTLP Resource.
2637
- *
2638
- * Bounded and validated, and refusing `service.name`/`service.namespace`,
2639
- * which are the two fields above. Distinct from an invocation's
2640
- * `consumerAttributes`: this describes the emitting deployment, carries no
2641
- * identity, and is the same for every span this process exports.
2547
+ * `raw` mode is refused unless this is also true, so a single mistyped
2548
+ * environment variable cannot start exporting prompts.
2642
2549
  */
2643
- resourceAttributes: resourceAttributesSchema,
2550
+ allowRawContent: z11.boolean(),
2644
2551
  /**
2645
- * The logs signal. Nested under the exporter because it shares the endpoint,
2646
- * headers, timeout, protocol, service identity, and resource attributes above —
2647
- * a second top-level section would invite two of each to drift apart.
2552
+ * Salt mixed into every hash. A per-deployment salt makes hashes
2553
+ * non-correlatable across deployments; an empty salt makes them globally
2554
+ * comparable. Both are legitimate; the choice is explicit.
2648
2555
  */
2649
- logs: logsPolicySchema
2650
- });
2651
- var detectionPolicySchema = z8.strictObject({
2652
- /** Detections below this confidence resolve to the unknown provider. */
2653
- minimumConfidence: detectionConfidenceSchema,
2654
- /** When false, an ambiguous detection is an error rather than unknown. */
2655
- allowAmbiguousFallback: z8.boolean(),
2656
- /** Optional allow-list of provider ids; empty means "any registered". */
2657
- allowedProviderIds: z8.array(nonEmptyStringSchema).max(32).readonly()
2658
- });
2659
- var diagnosticsPolicySchema = z8.strictObject({
2660
- logLevel: z8.enum(["silent", "error", "warn", "info", "debug"]),
2661
- /** Emit `error.raised` events for contained failures. */
2662
- emitErrorEvents: z8.boolean()
2663
- });
2664
- var otelHookConfigSchema = z8.strictObject({
2665
- exporter: exporterPolicySchema,
2666
- privacy: privacyPolicySchema,
2667
- detection: detectionPolicySchema,
2668
- diagnostics: diagnosticsPolicySchema
2669
- });
2670
- var otelHookConfigPatchSchema = z8.strictObject({
2671
- // `logs` is unwrapped and re-partialled for the same reason `privacy.limits` is:
2672
- // merging happens per leaf, so a layer must be able to set `logs.enabled` alone
2673
- // without also restating the endpoint and the batch size.
2674
- exporter: exporterPolicySchema.omit({ logs: true }).partial().extend({ logs: logsPolicySchema.partial().optional() }).optional(),
2675
- privacy: privacyPolicySchema.omit({ limits: true }).partial().extend({ limits: privacyPolicySchema.shape.limits.partial().optional() }).optional(),
2676
- detection: detectionPolicySchema.partial().optional(),
2677
- diagnostics: diagnosticsPolicySchema.partial().optional()
2678
- });
2679
- var DEFAULT_EXPORTER_POLICY = Object.freeze({
2680
- enabled: true,
2681
- protocol: "http/protobuf",
2682
- headerNames: Object.freeze([]),
2683
- timeoutMillis: 1e4,
2684
- maxBatchSize: 128,
2685
- maxQueueSize: 2048,
2686
- maxRetryAttempts: 2,
2687
- serviceName: "coding-agent",
2688
- resourceAttributes: EMPTY_RESOURCE_ATTRIBUTES,
2689
- logs: DEFAULT_LOGS_POLICY
2690
- });
2691
- var DEFAULT_DETECTION_POLICY = Object.freeze({
2692
- minimumConfidence: "strong",
2693
- allowAmbiguousFallback: true,
2694
- allowedProviderIds: Object.freeze([])
2695
- });
2696
- var DEFAULT_DIAGNOSTICS_POLICY = Object.freeze({
2697
- logLevel: "warn",
2698
- emitErrorEvents: true
2699
- });
2700
- var DEFAULT_CONFIG = Object.freeze({
2701
- exporter: DEFAULT_EXPORTER_POLICY,
2702
- privacy: DEFAULT_PRIVACY_POLICY,
2703
- detection: DEFAULT_DETECTION_POLICY,
2704
- diagnostics: DEFAULT_DIAGNOSTICS_POLICY
2705
- });
2706
-
2707
- // src/model/content.ts
2708
- import { z as z9 } from "zod";
2709
- var contentKindSchema = z9.enum([
2710
- "prompt",
2711
- "response",
2712
- "reasoning",
2713
- "tool-input",
2714
- "tool-output",
2715
- "error-message",
2716
- "system-instruction",
2717
- "attachment"
2718
- ]);
2719
- var contentRoleSchema = z9.enum(["user", "assistant", "system", "tool", "unknown"]);
2720
- var contentDisclosureSchema = z9.enum(["omitted", "masked", "redacted", "raw"]);
2721
- var CONTENT_HASH_PATTERN = /^sha256:[0-9a-f]{64}$/;
2722
- var contentFactSchema = z9.strictObject({
2723
- kind: contentKindSchema,
2724
- role: contentRoleSchema.optional(),
2725
- /** Unicode code point count of the original content. */
2726
- characterLength: z9.number().int().min(0),
2727
- /** UTF-8 byte length of the original content. */
2728
- byteLength: z9.number().int().min(0),
2729
- /** Stable salted digest of the original content. */
2730
- contentHash: z9.string().regex(CONTENT_HASH_PATTERN),
2731
- disclosure: contentDisclosureSchema,
2732
- /** Disclosed text, bounded by the privacy policy. Absent when omitted. */
2733
- text: z9.string().optional(),
2734
- /** True when `text` was cut short by the configured string bound. */
2735
- truncated: z9.boolean(),
2736
- /** Number of secret-looking spans replaced while producing `text`. */
2737
- secretsRedacted: z9.number().int().min(0),
2738
- /** Optional non-sensitive label, e.g. a MIME type or tool name. */
2739
- label: nonEmptyStringSchema.optional()
2740
- });
2741
- var contentFactsSchema = z9.array(contentFactSchema).max(64);
2742
- var isContentFactConsistent = (fact) => fact.disclosure === "omitted" ? fact.text === void 0 : fact.text !== void 0;
2743
- var isUnavailableContentFact = (fact) => fact.disclosure === "omitted" && fact.text === void 0 && fact.characterLength === 0 && fact.byteLength === 0;
2744
-
2745
- // src/model/identity.ts
2746
- import { z as z10 } from "zod";
2747
- var workspaceKeySourceSchema = z10.enum([
2748
- "git-remote",
2749
- "git-root",
2750
- "working-directory",
2751
- "explicit",
2752
- "unknown"
2753
- ]);
2754
- var workspaceIdentitySchema = z10.strictObject({
2755
- workspaceId: workspaceIdSchema,
2756
- keySource: workspaceKeySourceSchema,
2757
- /** Repository name only; never an owner path or URL with credentials. */
2758
- repositoryName: nonEmptyStringSchema.optional(),
2759
- vcsBranchName: nonEmptyStringSchema.optional(),
2760
- /** Opaque handle for the checked-out revision. */
2761
- vcsRevisionId: nonEmptyStringSchema.optional()
2762
- }).readonly();
2763
- var UNKNOWN_WORKSPACE_ID = "unknown:0000000000000000";
2764
- var unknownWorkspaceIdentity = () => workspaceIdentitySchema.parse({
2765
- workspaceId: UNKNOWN_WORKSPACE_ID,
2766
- keySource: "unknown"
2556
+ hashSalt: z11.string().max(256),
2557
+ maskCharacter: z11.string().length(1),
2558
+ redactionPlaceholder: z11.string().min(1).max(64),
2559
+ secretKeyPatterns: z11.array(z11.string().min(1)).max(128).readonly(),
2560
+ secretValuePatterns: z11.array(z11.string().min(1)).max(128).readonly(),
2561
+ limits: privacyLimitsSchema
2767
2562
  });
2768
- var sourceProvenanceSchema = z10.strictObject({
2769
- providerId: resolvedProviderIdSchema,
2770
- providerVersion: nonEmptyStringSchema.optional(),
2771
- adapterId: nonEmptyStringSchema,
2772
- adapterVersion: nonEmptyStringSchema,
2773
- detectionConfidence: detectionConfidenceSchema,
2774
- /** The provider's own name for the source event, e.g. a hook event name. */
2775
- sourceEventName: nonEmptyStringSchema.optional(),
2776
- transport: sourceTransportSchema
2777
- }).readonly();
2778
- var consumerAttributesSchema = attributesSchema.readonly();
2779
- var invocationIdentitySchema = z10.strictObject({
2780
- invocationId: invocationIdSchema,
2781
- sessionId: sessionIdSchema,
2782
- /** Set when this invocation runs beneath another agent invocation. */
2783
- parentInvocationId: invocationIdSchema.optional(),
2784
- /** Root of the session tree when the provider exposes one. */
2785
- rootSessionId: sessionIdSchema.optional(),
2786
- /** Stable handle for the agent process/instance, when available. */
2787
- agentInstanceId: nonEmptyStringSchema.optional(),
2788
- provenance: sourceProvenanceSchema,
2789
- workspace: workspaceIdentitySchema,
2790
- startedAt: epochMillisSchema,
2791
- consumerAttributes: consumerAttributesSchema
2792
- }).readonly();
2793
- var identityClaimFieldsSchema = z10.strictObject({
2794
- invocationId: invocationIdSchema.optional(),
2795
- sessionId: sessionIdSchema.optional(),
2796
- parentInvocationId: invocationIdSchema.optional(),
2797
- rootSessionId: sessionIdSchema.optional(),
2798
- agentInstanceId: nonEmptyStringSchema.optional(),
2799
- workspace: workspaceIdentitySchema.optional(),
2800
- startedAt: epochMillisSchema.optional()
2563
+ var DEFAULT_PRIVACY_LIMITS = Object.freeze({
2564
+ maxStringLength: 1024,
2565
+ maxDepth: 6,
2566
+ maxArrayLength: 64,
2567
+ maxEventsPerInvocation: 512,
2568
+ maxObjectKeys: 128
2801
2569
  });
2802
- var identityClaimSchema = z10.strictObject({
2803
- /** Non-sensitive label, e.g. `adapter:acme-cli` or `env:OTEL_HOOK_SESSION_ID`. */
2804
- source: nonEmptyStringSchema,
2805
- confidence: detectionConfidenceSchema,
2806
- fields: identityClaimFieldsSchema
2570
+ var DEFAULT_PRIVACY_POLICY = Object.freeze({
2571
+ contentMode: "omit",
2572
+ allowRawContent: false,
2573
+ hashSalt: "",
2574
+ maskCharacter: "*",
2575
+ redactionPlaceholder: "[redacted]",
2576
+ secretKeyPatterns: DEFAULT_SECRET_KEY_PATTERNS,
2577
+ secretValuePatterns: DEFAULT_SECRET_VALUE_PATTERNS,
2578
+ limits: DEFAULT_PRIVACY_LIMITS
2807
2579
  });
2808
- var CLAIM_FIELDS = [
2809
- "invocationId",
2810
- "sessionId",
2811
- "parentInvocationId",
2812
- "rootSessionId",
2813
- "agentInstanceId",
2814
- "workspace",
2815
- "startedAt"
2816
- ];
2817
- var renderClaimValue = (value) => {
2818
- if (typeof value === "string") {
2819
- return value;
2580
+ var resolvePrivacyPolicy = (policy) => {
2581
+ const parsed = privacyPolicySchema.parse(policy);
2582
+ if (parsed.contentMode === "raw" && !parsed.allowRawContent) {
2583
+ return {
2584
+ policy: { ...parsed, contentMode: "omit" },
2585
+ notes: ["contentMode=raw downgraded to omit because allowRawContent is false"]
2586
+ };
2820
2587
  }
2821
- if (typeof value === "number" || typeof value === "boolean") {
2822
- return String(value);
2588
+ return { policy: parsed, notes: [] };
2589
+ };
2590
+
2591
+ // src/privacy/service.ts
2592
+ var compilePatterns = (sources, flags) => {
2593
+ const compiled = [];
2594
+ for (const source of sources) {
2595
+ try {
2596
+ compiled.push(new RegExp(source, flags));
2597
+ } catch {
2598
+ continue;
2599
+ }
2823
2600
  }
2824
- if (value !== null && typeof value === "object" && "workspaceId" in value) {
2825
- const { workspaceId } = value;
2826
- return typeof workspaceId === "string" ? workspaceId : "<workspace>";
2601
+ return compiled;
2602
+ };
2603
+ var codePointLength = (value) => [...value].length;
2604
+ var isSanitizedArray = (value) => Array.isArray(value);
2605
+ var sliceCodePoints = (value, max) => {
2606
+ if (max <= 0) {
2607
+ return "";
2827
2608
  }
2828
- return "<opaque>";
2609
+ let result = "";
2610
+ let count = 0;
2611
+ for (const char of value) {
2612
+ if (count >= max) {
2613
+ break;
2614
+ }
2615
+ result += char;
2616
+ count += 1;
2617
+ }
2618
+ return result;
2829
2619
  };
2830
- var resolveInvocationIdentity = (input) => {
2831
- const parsedClaims = [];
2832
- const issues = [];
2833
- for (const [index, claim] of input.claims.entries()) {
2834
- const parsed2 = identityClaimSchema.safeParse(claim);
2835
- if (parsed2.success) {
2836
- parsedClaims.push(parsed2.data);
2837
- } else {
2838
- issues.push(
2839
- `claim[${index}]: ${parsed2.error.issues.map((issue) => `${issue.path.join(".") || "<root>"} ${issue.message}`).join(", ")}`
2840
- );
2620
+ var stableStringify = (value) => {
2621
+ const seen = /* @__PURE__ */ new WeakSet();
2622
+ const walk = (input) => {
2623
+ if (input === null) {
2624
+ return "null";
2625
+ }
2626
+ if (typeof input === "string") {
2627
+ return JSON.stringify(input);
2628
+ }
2629
+ if (typeof input === "number") {
2630
+ return Number.isFinite(input) ? JSON.stringify(input) : "null";
2631
+ }
2632
+ if (typeof input === "boolean") {
2633
+ return input ? "true" : "false";
2634
+ }
2635
+ if (typeof input === "bigint") {
2636
+ return JSON.stringify(input.toString());
2637
+ }
2638
+ if (typeof input !== "object") {
2639
+ return "null";
2640
+ }
2641
+ if (seen.has(input)) {
2642
+ return '"<circular>"';
2643
+ }
2644
+ seen.add(input);
2645
+ if (Array.isArray(input)) {
2646
+ return `[${input.map((entry) => walk(entry)).join(",")}]`;
2647
+ }
2648
+ const record = input;
2649
+ const keys = Object.keys(record).sort();
2650
+ return `{${keys.map((key) => `${JSON.stringify(key)}:${walk(record[key])}`).join(",")}}`;
2651
+ };
2652
+ return walk(value);
2653
+ };
2654
+ var emptyStats = () => ({
2655
+ truncatedStrings: 0,
2656
+ truncatedArrays: 0,
2657
+ truncatedObjects: 0,
2658
+ redactedKeys: 0,
2659
+ depthExceeded: 0,
2660
+ droppedValues: 0,
2661
+ circularReferences: 0
2662
+ });
2663
+ var createPrivacyService = (policyInput) => {
2664
+ const { policy, notes } = resolvePrivacyPolicy(policyInput);
2665
+ const limits = policy.limits;
2666
+ const secretKeyPatterns = compilePatterns(policy.secretKeyPatterns, "i");
2667
+ const secretValuePatterns = compilePatterns(policy.secretValuePatterns, "g");
2668
+ const hash = (value) => `sha256:${createHash2("sha256").update(policy.hashSalt).update("\0").update(value, "utf8").digest("hex")}`;
2669
+ const isSecretKey = (key) => secretKeyPatterns.some((pattern) => pattern.test(key));
2670
+ const boundString = (value) => {
2671
+ const length = codePointLength(value);
2672
+ if (length <= limits.maxStringLength) {
2673
+ return { text: value, truncated: false };
2674
+ }
2675
+ return { text: sliceCodePoints(value, limits.maxStringLength), truncated: true };
2676
+ };
2677
+ const redactSecretSpans = (value) => {
2678
+ let count = 0;
2679
+ let text = value;
2680
+ for (const pattern of secretValuePatterns) {
2681
+ text = text.replace(new RegExp(pattern.source, pattern.flags), () => {
2682
+ count += 1;
2683
+ return policy.redactionPlaceholder;
2684
+ });
2685
+ }
2686
+ return { text, count };
2687
+ };
2688
+ const maskText = (value) => Array.from(value, (char) => /\s/.test(char) ? char : policy.maskCharacter).join("");
2689
+ const disclose = (original) => {
2690
+ switch (policy.contentMode) {
2691
+ case "omit":
2692
+ return { text: void 0, truncated: false, secretsRedacted: 0 };
2693
+ case "mask": {
2694
+ const bounded = boundString(original);
2695
+ return { text: maskText(bounded.text), truncated: bounded.truncated, secretsRedacted: 0 };
2696
+ }
2697
+ case "redact": {
2698
+ const redacted = redactSecretSpans(original);
2699
+ const bounded = boundString(redacted.text);
2700
+ return {
2701
+ text: bounded.text,
2702
+ truncated: bounded.truncated,
2703
+ secretsRedacted: redacted.count
2704
+ };
2705
+ }
2706
+ case "raw": {
2707
+ const bounded = boundString(original);
2708
+ return { text: bounded.text, truncated: bounded.truncated, secretsRedacted: 0 };
2709
+ }
2710
+ }
2711
+ };
2712
+ const describeText = (input) => {
2713
+ const disclosed = disclose(input.text);
2714
+ return {
2715
+ kind: input.kind,
2716
+ ...input.role === void 0 ? {} : { role: input.role },
2717
+ characterLength: codePointLength(input.text),
2718
+ byteLength: Buffer.byteLength(input.text, "utf8"),
2719
+ contentHash: hash(input.text),
2720
+ disclosure: CONTENT_MODE_DISCLOSURE[policy.contentMode],
2721
+ ...disclosed.text === void 0 ? {} : { text: disclosed.text },
2722
+ truncated: disclosed.truncated,
2723
+ secretsRedacted: disclosed.secretsRedacted,
2724
+ ...input.label === void 0 ? {} : { label: input.label }
2725
+ };
2726
+ };
2727
+ const sanitizeValue = (value, depth, stats, seen) => {
2728
+ if (value === null) {
2729
+ return null;
2730
+ }
2731
+ switch (typeof value) {
2732
+ case "string": {
2733
+ const bounded = boundString(value);
2734
+ if (bounded.truncated) {
2735
+ stats.truncatedStrings += 1;
2736
+ }
2737
+ return bounded.text;
2738
+ }
2739
+ case "number":
2740
+ if (!Number.isFinite(value)) {
2741
+ stats.droppedValues += 1;
2742
+ return null;
2743
+ }
2744
+ return value;
2745
+ case "boolean":
2746
+ return value;
2747
+ case "bigint":
2748
+ return value.toString();
2749
+ case "undefined":
2750
+ case "function":
2751
+ case "symbol":
2752
+ stats.droppedValues += 1;
2753
+ return null;
2754
+ default:
2755
+ break;
2756
+ }
2757
+ if (depth >= limits.maxDepth) {
2758
+ stats.depthExceeded += 1;
2759
+ return "<depth-exceeded>";
2760
+ }
2761
+ if (seen.has(value)) {
2762
+ stats.circularReferences += 1;
2763
+ return "<circular>";
2764
+ }
2765
+ seen.add(value);
2766
+ if (Array.isArray(value)) {
2767
+ const entries = value.slice(0, limits.maxArrayLength);
2768
+ if (value.length > limits.maxArrayLength) {
2769
+ stats.truncatedArrays += 1;
2770
+ }
2771
+ return entries.map((entry) => sanitizeValue(entry, depth + 1, stats, seen));
2772
+ }
2773
+ if (value instanceof Date) {
2774
+ return value.toISOString();
2775
+ }
2776
+ const record = value;
2777
+ const keys = Object.keys(record);
2778
+ const retained = keys.slice(0, limits.maxObjectKeys);
2779
+ if (keys.length > limits.maxObjectKeys) {
2780
+ stats.truncatedObjects += 1;
2781
+ }
2782
+ const result = {};
2783
+ for (const key of retained) {
2784
+ if (isSecretKey(key)) {
2785
+ stats.redactedKeys += 1;
2786
+ result[key] = policy.redactionPlaceholder;
2787
+ continue;
2788
+ }
2789
+ result[key] = sanitizeValue(record[key], depth + 1, stats, seen);
2790
+ }
2791
+ return result;
2792
+ };
2793
+ const sanitizeStructured = (value) => {
2794
+ const stats = emptyStats();
2795
+ const sanitized = sanitizeValue(value, 0, stats, /* @__PURE__ */ new WeakSet());
2796
+ return { value: sanitized, stats };
2797
+ };
2798
+ const toAttributePrimitive = (value) => {
2799
+ if (typeof value === "string") {
2800
+ return value.slice(0, MAX_ATTRIBUTE_STRING_LENGTH);
2841
2801
  }
2842
- }
2843
- if (issues.length > 0) {
2844
- return { status: "invalid", issues };
2845
- }
2846
- const conflicts = [];
2847
- const selected = {};
2848
- for (const field of CLAIM_FIELDS) {
2849
- const contributors = parsedClaims.filter((claim) => claim.fields[field] !== void 0);
2850
- if (contributors.length === 0) {
2851
- continue;
2802
+ if (typeof value === "number" || typeof value === "boolean") {
2803
+ return value;
2852
2804
  }
2853
- const bestRank = Math.max(
2854
- ...contributors.map((claim) => DETECTION_CONFIDENCE_RANK[claim.confidence])
2855
- );
2856
- const best = contributors.filter(
2857
- (claim) => DETECTION_CONFIDENCE_RANK[claim.confidence] === bestRank
2858
- );
2859
- const rendered = /* @__PURE__ */ new Map();
2860
- for (const claim of best) {
2861
- const key = JSON.stringify(claim.fields[field]);
2862
- const sources = rendered.get(key) ?? [];
2863
- sources.push(claim.source);
2864
- rendered.set(key, sources);
2805
+ return void 0;
2806
+ };
2807
+ const flattenToAttributes = (value, prefix) => {
2808
+ const attributes = {};
2809
+ const walk = (current, path5) => {
2810
+ if (typeof current === "string" || typeof current === "number" || typeof current === "boolean") {
2811
+ const primitive = toAttributePrimitive(current);
2812
+ if (primitive !== void 0) {
2813
+ attributes[path5] = primitive;
2814
+ }
2815
+ return;
2816
+ }
2817
+ if (current === null) {
2818
+ return;
2819
+ }
2820
+ if (isSanitizedArray(current)) {
2821
+ const primitives = [];
2822
+ let uniform = true;
2823
+ for (const entry of current) {
2824
+ const entryPrimitive = toAttributePrimitive(entry);
2825
+ if (entryPrimitive === void 0) {
2826
+ uniform = false;
2827
+ break;
2828
+ }
2829
+ primitives.push(entryPrimitive);
2830
+ }
2831
+ if (uniform) {
2832
+ attributes[path5] = primitives.slice(0, MAX_ATTRIBUTE_ARRAY_LENGTH);
2833
+ return;
2834
+ }
2835
+ for (const [index, entry] of current.entries()) {
2836
+ walk(entry, `${path5}.${index}`);
2837
+ }
2838
+ return;
2839
+ }
2840
+ for (const [key, entry] of Object.entries(current)) {
2841
+ walk(entry, path5 === "" ? key : `${path5}.${key}`);
2842
+ }
2843
+ };
2844
+ walk(value, prefix);
2845
+ return attributes;
2846
+ };
2847
+ const sanitizeAttributes = (value) => {
2848
+ const attributes = {};
2849
+ for (const [key, entry] of Object.entries(value)) {
2850
+ if (isSecretKey(key)) {
2851
+ attributes[key] = policy.redactionPlaceholder;
2852
+ continue;
2853
+ }
2854
+ const sanitized = sanitizeStructured(entry).value;
2855
+ const primitive = toAttributePrimitive(sanitized);
2856
+ if (primitive !== void 0) {
2857
+ attributes[key] = primitive;
2858
+ continue;
2859
+ }
2860
+ const flattened = flattenToAttributes(sanitized, key);
2861
+ Object.assign(attributes, flattened);
2865
2862
  }
2866
- if (rendered.size > 1) {
2867
- const [firstBest] = best;
2868
- conflicts.push({
2869
- field,
2870
- confidence: firstBest?.confidence ?? "none",
2871
- values: best.map((claim) => renderClaimValue(claim.fields[field])),
2872
- sources: best.map((claim) => claim.source)
2873
- });
2874
- continue;
2863
+ return attributes;
2864
+ };
2865
+ const sanitizeExtensions = (value) => {
2866
+ const extensions = {};
2867
+ const droppedKeys = [];
2868
+ for (const [key, entry] of Object.entries(value)) {
2869
+ if (!isValidExtensionKey(key)) {
2870
+ droppedKeys.push(key);
2871
+ continue;
2872
+ }
2873
+ if (isSecretKey(key)) {
2874
+ extensions[key] = policy.redactionPlaceholder;
2875
+ continue;
2876
+ }
2877
+ const sanitized = sanitizeStructured(entry).value;
2878
+ const candidate = attributeValueSchema.safeParse(sanitized);
2879
+ if (candidate.success) {
2880
+ extensions[key] = candidate.data;
2881
+ } else {
2882
+ droppedKeys.push(key);
2883
+ }
2875
2884
  }
2876
- const [winner] = best;
2877
- if (winner !== void 0) {
2878
- selected[field] = winner.fields[field];
2885
+ return { extensions, droppedKeys };
2886
+ };
2887
+ return {
2888
+ policy,
2889
+ policyNotes: notes,
2890
+ hash,
2891
+ deriveOpaqueId: (namespace, value) => hash(`${namespace}\0${value}`),
2892
+ describeContent: describeText,
2893
+ describeUnavailableContent: (input) => ({
2894
+ kind: input.kind,
2895
+ ...input.role === void 0 ? {} : { role: input.role },
2896
+ characterLength: 0,
2897
+ byteLength: 0,
2898
+ contentHash: hash(""),
2899
+ disclosure: "omitted",
2900
+ truncated: false,
2901
+ secretsRedacted: 0,
2902
+ ...input.label === void 0 ? {} : { label: input.label }
2903
+ }),
2904
+ describeStructured: (input) => {
2905
+ const serialized = stableStringify(input.value);
2906
+ const sanitized = sanitizeStructured(input.value);
2907
+ const base = describeText({
2908
+ kind: input.kind,
2909
+ text: serialized,
2910
+ ...input.role === void 0 ? {} : { role: input.role },
2911
+ ...input.label === void 0 ? {} : { label: input.label }
2912
+ });
2913
+ if (base.text === void 0) {
2914
+ return base;
2915
+ }
2916
+ const disclosed = disclose(stableStringify(sanitized.value));
2917
+ return {
2918
+ ...base,
2919
+ ...disclosed.text === void 0 ? {} : { text: disclosed.text },
2920
+ truncated: base.truncated || disclosed.truncated,
2921
+ secretsRedacted: disclosed.secretsRedacted + sanitized.stats.redactedKeys
2922
+ };
2923
+ },
2924
+ isSecretKey,
2925
+ sanitizeStructured,
2926
+ flattenToAttributes,
2927
+ sanitizeAttributes,
2928
+ sanitizeExtensions,
2929
+ boundString
2930
+ };
2931
+ };
2932
+
2933
+ // src/runtime/clock.ts
2934
+ var createSystemClock = () => ({
2935
+ now: () => epochMillisSchema.parse(Date.now()),
2936
+ monotonicMillis: () => Number(process.hrtime.bigint() / 1000000n)
2937
+ });
2938
+
2939
+ // src/runtime/hook.ts
2940
+ import { z as z16 } from "zod";
2941
+
2942
+ // src/config/schema.ts
2943
+ import { z as z13 } from "zod";
2944
+
2945
+ // src/config/resource-attributes.ts
2946
+ import { z as z12 } from "zod";
2947
+ var MAX_RESOURCE_ATTRIBUTES = 64;
2948
+ var MAX_RESOURCE_ATTRIBUTE_KEY_LENGTH = 255;
2949
+ var MAX_RESOURCE_ATTRIBUTE_VALUE_LENGTH = 2048;
2950
+ var RESOURCE_ATTRIBUTE_KEY_PATTERN = /^[A-Za-z][A-Za-z0-9_./-]*$/;
2951
+ var RESERVED_RESOURCE_ATTRIBUTE_KEYS = Object.freeze([
2952
+ "service.name",
2953
+ "service.namespace"
2954
+ ]);
2955
+ var isReservedResourceAttributeKey = (key) => RESERVED_RESOURCE_ATTRIBUTE_KEYS.includes(key.toLowerCase());
2956
+ var SECRET_KEY_MATCHERS = Object.freeze(
2957
+ DEFAULT_SECRET_KEY_PATTERNS.flatMap((source) => {
2958
+ try {
2959
+ return [new RegExp(source, "i")];
2960
+ } catch {
2961
+ return [];
2879
2962
  }
2963
+ })
2964
+ );
2965
+ var isSecretResourceAttributeKey = (key) => SECRET_KEY_MATCHERS.some((pattern) => pattern.test(key));
2966
+ var RESOURCE_ATTRIBUTE_KEY_REJECTION_DETAIL = Object.freeze({
2967
+ empty: "resource attribute key is empty",
2968
+ "too-long": `resource attribute key exceeds ${String(MAX_RESOURCE_ATTRIBUTE_KEY_LENGTH)} characters`,
2969
+ malformed: "resource attribute key must start with a letter and use only letters, digits, and `_`, `.`, `-`, `/`",
2970
+ reserved: "service.name and service.namespace are exporter policy (--service-name / OTEL_HOOK_SERVICE_NAME), not resource attributes",
2971
+ "secret-like": "resource attribute key matches a secret-name pattern, so it is never exported"
2972
+ });
2973
+ var checkResourceAttributeKey = (key) => {
2974
+ if (key.length === 0) {
2975
+ return "empty";
2880
2976
  }
2881
- if (conflicts.length > 0) {
2882
- return { status: "conflict", conflicts };
2883
- }
2884
- const missing = [];
2885
- if (selected.invocationId === void 0) {
2886
- missing.push("invocationId");
2887
- }
2888
- if (selected.sessionId === void 0) {
2889
- missing.push("sessionId");
2977
+ if (key.length > MAX_RESOURCE_ATTRIBUTE_KEY_LENGTH) {
2978
+ return "too-long";
2890
2979
  }
2891
- if (missing.length > 0) {
2892
- return { status: "incomplete", missing };
2980
+ if (!RESOURCE_ATTRIBUTE_KEY_PATTERN.test(key)) {
2981
+ return "malformed";
2893
2982
  }
2894
- const startedAt = selected.startedAt ?? input.fallback?.startedAt;
2895
- if (startedAt === void 0) {
2896
- return { status: "incomplete", missing: ["startedAt"] };
2983
+ if (isReservedResourceAttributeKey(key)) {
2984
+ return "reserved";
2897
2985
  }
2898
- const workspace = selected.workspace ?? input.fallback?.workspace ?? unknownWorkspaceIdentity();
2899
- const candidate = {
2900
- invocationId: selected.invocationId,
2901
- sessionId: selected.sessionId,
2902
- ...selected.parentInvocationId === void 0 ? {} : { parentInvocationId: selected.parentInvocationId },
2903
- ...selected.rootSessionId === void 0 ? {} : { rootSessionId: selected.rootSessionId },
2904
- ...selected.agentInstanceId === void 0 ? {} : { agentInstanceId: selected.agentInstanceId },
2905
- provenance: input.provenance,
2906
- workspace,
2907
- startedAt,
2908
- consumerAttributes: input.consumerAttributes ?? {}
2909
- };
2910
- const parsed = invocationIdentitySchema.safeParse(candidate);
2911
- if (!parsed.success) {
2912
- return {
2913
- status: "invalid",
2914
- issues: parsed.error.issues.map(
2915
- (issue) => `${issue.path.join(".") || "<root>"}: ${issue.message}`
2916
- )
2917
- };
2986
+ if (isSecretResourceAttributeKey(key)) {
2987
+ return "secret-like";
2918
2988
  }
2919
- return { status: "resolved", identity: parsed.data };
2989
+ return void 0;
2920
2990
  };
2921
-
2922
- // src/model/version.ts
2923
- import { z as z11 } from "zod";
2924
- var CANONICAL_SCHEMA_VERSION = 1;
2925
- var canonicalSchemaVersionSchema = z11.literal(CANONICAL_SCHEMA_VERSION);
2926
-
2927
- // src/providers/adapter.ts
2928
- import { z as z14 } from "zod";
2929
-
2930
- // src/model/events.ts
2931
- import { z as z13 } from "zod";
2932
-
2933
- // src/model/target.ts
2934
- import { z as z12 } from "zod";
2935
- var targetSourceSchema = z12.enum(["tool-path", "shell-cwd", "session-cwd"]);
2936
- var MAX_TARGET_HINT_PATHS = 8;
2937
- var MAX_TARGET_PATH_LENGTH = 4096;
2938
- var localPathSchema = z12.string().min(1).max(MAX_TARGET_PATH_LENGTH).refine((value) => !value.includes("\0"), "path must not contain NUL");
2939
- var targetHintSchema = z12.strictObject({
2940
- source: targetSourceSchema,
2941
- paths: z12.array(localPathSchema).min(1).max(MAX_TARGET_HINT_PATHS).readonly(),
2942
- /** Absolute directory that relative `paths` resolve against. */
2943
- baseDirectory: localPathSchema.optional()
2944
- }).readonly();
2945
- var worktreeKindSchema = z12.enum(["main", "linked"]);
2946
- var workspaceTargetSchema = z12.strictObject({
2947
- workspaceId: workspaceIdSchema,
2948
- /** Branch checked out in that worktree; absent on a detached HEAD. */
2949
- vcsBranchName: nonEmptyStringSchema.optional(),
2950
- source: targetSourceSchema,
2951
- /** `git-root` handle of the repository's main worktree; absent when there is none to name. */
2952
- repositoryId: workspaceIdSchema.optional(),
2953
- worktreeKind: worktreeKindSchema.optional()
2991
+ var resourceAttributeValueSchema = z12.union([
2992
+ z12.string().max(MAX_RESOURCE_ATTRIBUTE_VALUE_LENGTH),
2993
+ z12.number().finite(),
2994
+ z12.boolean()
2995
+ ]);
2996
+ var resourceAttributesSchema = z12.record(z12.string(), resourceAttributeValueSchema).superRefine((value, ctx) => {
2997
+ const keys = Object.keys(value);
2998
+ if (keys.length > MAX_RESOURCE_ATTRIBUTES) {
2999
+ ctx.addIssue({
3000
+ code: "custom",
3001
+ message: `at most ${String(MAX_RESOURCE_ATTRIBUTES)} resource attributes are accepted`
3002
+ });
3003
+ }
3004
+ for (const key of keys) {
3005
+ const rejection = checkResourceAttributeKey(key);
3006
+ if (rejection !== void 0) {
3007
+ ctx.addIssue({
3008
+ code: "custom",
3009
+ path: [key],
3010
+ message: RESOURCE_ATTRIBUTE_KEY_REJECTION_DETAIL[rejection]
3011
+ });
3012
+ }
3013
+ }
2954
3014
  }).readonly();
2955
- var SUBAGENT_ID_PATTERN = /^[A-Za-z0-9_.:@+=-]{1,256}$/;
2956
- var subagentIdSchema = z12.string().regex(SUBAGENT_ID_PATTERN);
3015
+ var EMPTY_RESOURCE_ATTRIBUTES = Object.freeze({});
3016
+ var sanitizeResourceAttributes = (attributes) => {
3017
+ const safe = {};
3018
+ for (const [key, value] of Object.entries(attributes)) {
3019
+ if (checkResourceAttributeKey(key) !== void 0) {
3020
+ continue;
3021
+ }
3022
+ if (Object.keys(safe).length >= MAX_RESOURCE_ATTRIBUTES) {
3023
+ break;
3024
+ }
3025
+ safe[key] = value;
3026
+ }
3027
+ return safe;
3028
+ };
2957
3029
 
2958
- // src/model/events.ts
2959
- var modelDescriptorSchema = z13.strictObject({
2960
- modelId: nonEmptyStringSchema,
2961
- /** Vendor of the model, e.g. `anthropic`. Distinct from the agent provider. */
2962
- vendor: nonEmptyStringSchema.optional(),
2963
- family: nonEmptyStringSchema.optional()
2964
- });
2965
- var costFactsSchema = z13.strictObject({
2966
- /** ISO 4217 code. */
2967
- currency: z13.string().length(3),
2968
- amount: z13.number().min(0).finite(),
2969
- source: z13.enum(["provider-reported", "computed"])
2970
- });
2971
- var canonicalEventTypeSchema = z13.enum([
2972
- "session.start",
2973
- "session.end",
2974
- "prompt.submitted",
2975
- "generation.start",
2976
- "generation.end",
2977
- "tool.start",
2978
- "tool.end",
2979
- "subagent.start",
2980
- "subagent.end",
2981
- "compaction.performed",
2982
- "error.raised"
2983
- ]);
2984
- var CANONICAL_EVENT_TYPES = canonicalEventTypeSchema.options;
2985
- var outcomeSchema = z13.enum(["ok", "error", "cancelled", "timeout", "denied", "unknown"]);
2986
- var baseEventFields = {
2987
- schemaVersion: canonicalSchemaVersionSchema,
2988
- eventId: eventIdSchema,
2989
- invocationId: invocationIdSchema,
2990
- sessionId: sessionIdSchema,
2991
- /** Per-invocation ordering key. Stable across replays of the same input. */
2992
- sequence: sequenceNumberSchema,
2993
- occurredAt: epochMillisSchema,
2994
- provenance: sourceProvenanceSchema,
2995
- workspace: workspaceIdentitySchema,
3030
+ // src/config/schema.ts
3031
+ var logsPolicySchema = z13.strictObject({
3032
+ enabled: z13.boolean(),
2996
3033
  /**
2997
- * The provider's own id for the subagent this event was emitted inside (e.g.
2998
- * Claude Code's `agent_id`). Absent for the top-level agent. Set by the event
2999
- * factory, never by hand.
3034
+ * Full URL for the logs signal.
3035
+ *
3036
+ * Absent, it is derived from `endpoint`: a trailing `/v1/traces` becomes
3037
+ * `/v1/logs`, and an endpoint with no signal path has `/v1/logs` appended.
3000
3038
  */
3001
- subagentId: subagentIdSchema.optional(),
3002
- extensions: extensionsSchema.default(emptyExtensions)
3003
- };
3004
- var event = (shape) => z13.strictObject({ ...baseEventFields, ...shape });
3005
- var sessionStartEventSchema = event({
3006
- type: z13.literal("session.start"),
3007
- sessionKind: z13.enum(["interactive", "non-interactive", "unknown"]),
3008
- agentName: nonEmptyStringSchema.optional(),
3009
- agentVersion: nonEmptyStringSchema.optional(),
3010
- model: modelDescriptorSchema.optional()
3039
+ endpoint: z13.string().url().max(2048).optional(),
3040
+ includeContent: z13.boolean(),
3041
+ maxBatchSize: z13.number().int().min(1).max(4096)
3011
3042
  });
3012
- var sessionEndEventSchema = event({
3013
- type: z13.literal("session.end"),
3014
- reason: z13.enum(["completed", "aborted", "error", "timeout", "unknown"]),
3015
- durationMillis: durationMillisSchema.optional(),
3016
- /** Session totals, typically cumulative. */
3017
- usage: canonicalUsageSchema.optional(),
3018
- cost: costFactsSchema.optional()
3043
+ var DEFAULT_LOGS_POLICY = Object.freeze({
3044
+ enabled: false,
3045
+ includeContent: false,
3046
+ maxBatchSize: 128
3019
3047
  });
3020
- var promptSubmittedEventSchema = event({
3021
- type: z13.literal("prompt.submitted"),
3022
- promptSource: z13.enum(["user", "automation", "resumed", "unknown"]),
3023
- content: contentFactSchema.optional(),
3024
- turnIndex: z13.number().int().min(0).optional()
3048
+ var exporterPolicySchema = z13.strictObject({
3049
+ enabled: z13.boolean(),
3050
+ protocol: z13.enum(["http/protobuf", "http/json", "none"]),
3051
+ endpoint: z13.string().url().max(2048).optional(),
3052
+ /**
3053
+ * Header names only. Values are supplied separately at construction time and
3054
+ * are never part of a resolved-config snapshot, which is logged and exported.
3055
+ */
3056
+ headerNames: z13.array(nonEmptyStringSchema).max(32).readonly(),
3057
+ timeoutMillis: z13.number().int().min(1).max(6e5),
3058
+ maxBatchSize: z13.number().int().min(1).max(4096),
3059
+ maxQueueSize: z13.number().int().min(1).max(65536),
3060
+ maxRetryAttempts: z13.number().int().min(0).max(10),
3061
+ serviceName: nonEmptyStringSchema,
3062
+ serviceNamespace: nonEmptyStringSchema.optional(),
3063
+ /**
3064
+ * Custom attributes merged into the exported OTLP Resource.
3065
+ *
3066
+ * Bounded and validated, and refusing `service.name`/`service.namespace`,
3067
+ * which are the two fields above. Distinct from an invocation's
3068
+ * `consumerAttributes`: this describes the emitting deployment, carries no
3069
+ * identity, and is the same for every span this process exports.
3070
+ */
3071
+ resourceAttributes: resourceAttributesSchema,
3072
+ /**
3073
+ * The logs signal. Nested under the exporter because it shares the endpoint,
3074
+ * headers, timeout, protocol, service identity, and resource attributes above —
3075
+ * a second top-level section would invite two of each to drift apart.
3076
+ */
3077
+ logs: logsPolicySchema
3025
3078
  });
3026
- var generationStartEventSchema = event({
3027
- type: z13.literal("generation.start"),
3028
- generationId: nonEmptyStringSchema,
3029
- model: modelDescriptorSchema,
3030
- requestedMaxOutputTokens: tokenCountSchema.optional(),
3031
- inputContent: contentFactsSchema.optional()
3079
+ var detectionPolicySchema = z13.strictObject({
3080
+ /** Detections below this confidence resolve to the unknown provider. */
3081
+ minimumConfidence: detectionConfidenceSchema,
3082
+ /** When false, an ambiguous detection is an error rather than unknown. */
3083
+ allowAmbiguousFallback: z13.boolean(),
3084
+ /** Optional allow-list of provider ids; empty means "any registered". */
3085
+ allowedProviderIds: z13.array(nonEmptyStringSchema).max(32).readonly()
3032
3086
  });
3033
- var generationEndEventSchema = event({
3034
- type: z13.literal("generation.end"),
3035
- generationId: nonEmptyStringSchema,
3036
- model: modelDescriptorSchema,
3037
- outcome: outcomeSchema,
3038
- stopReason: nonEmptyStringSchema.optional(),
3039
- durationMillis: durationMillisSchema.optional(),
3040
- usage: canonicalUsageSchema.optional(),
3041
- cost: costFactsSchema.optional(),
3042
- outputContent: contentFactsSchema.optional()
3087
+ var diagnosticsPolicySchema = z13.strictObject({
3088
+ logLevel: z13.enum(["silent", "error", "warn", "info", "debug"]),
3089
+ /** Emit `error.raised` events for contained failures. */
3090
+ emitErrorEvents: z13.boolean()
3043
3091
  });
3044
- var toolKindSchema = z13.enum([
3045
- "read",
3046
- "write",
3047
- "execute",
3048
- "search",
3049
- "network",
3050
- "delegate",
3051
- "other",
3052
- "unknown"
3053
- ]);
3054
- var toolStartEventSchema = event({
3055
- type: z13.literal("tool.start"),
3056
- toolCallId: nonEmptyStringSchema,
3057
- toolName: nonEmptyStringSchema,
3058
- toolKind: toolKindSchema,
3059
- generationId: nonEmptyStringSchema.optional(),
3060
- input: contentFactSchema.optional(),
3061
- /** The git worktree this call targeted, resolved by the core (ADR 0008). */
3062
- target: workspaceTargetSchema.optional()
3092
+ var otelHookConfigSchema = z13.strictObject({
3093
+ exporter: exporterPolicySchema,
3094
+ privacy: privacyPolicySchema,
3095
+ detection: detectionPolicySchema,
3096
+ diagnostics: diagnosticsPolicySchema
3063
3097
  });
3064
- var toolEndEventSchema = event({
3065
- type: z13.literal("tool.end"),
3066
- toolCallId: nonEmptyStringSchema,
3067
- toolName: nonEmptyStringSchema,
3068
- outcome: outcomeSchema,
3069
- durationMillis: durationMillisSchema.optional(),
3070
- /** Present when the host asked for or recorded a permission decision. */
3071
- permissionDecision: z13.enum(["allowed", "denied", "deferred", "not-required"]).optional(),
3072
- output: contentFactSchema.optional(),
3073
- /** The git worktree this call targeted, resolved by the core (ADR 0008). */
3074
- target: workspaceTargetSchema.optional()
3098
+ var otelHookConfigPatchSchema = z13.strictObject({
3099
+ // `logs` is unwrapped and re-partialled for the same reason `privacy.limits` is:
3100
+ // merging happens per leaf, so a layer must be able to set `logs.enabled` alone
3101
+ // without also restating the endpoint and the batch size.
3102
+ exporter: exporterPolicySchema.omit({ logs: true }).partial().extend({ logs: logsPolicySchema.partial().optional() }).optional(),
3103
+ privacy: privacyPolicySchema.omit({ limits: true }).partial().extend({ limits: privacyPolicySchema.shape.limits.partial().optional() }).optional(),
3104
+ detection: detectionPolicySchema.partial().optional(),
3105
+ diagnostics: diagnosticsPolicySchema.partial().optional()
3075
3106
  });
3076
- var subagentStartEventSchema = event({
3077
- type: z13.literal("subagent.start"),
3078
- subagentInvocationId: invocationIdSchema,
3079
- subagentType: nonEmptyStringSchema.optional(),
3080
- /** 0 for the top-level agent; 1 for its direct children. */
3081
- delegationDepth: z13.number().int().min(0).max(64),
3082
- model: modelDescriptorSchema.optional()
3107
+ var DEFAULT_EXPORTER_POLICY = Object.freeze({
3108
+ enabled: true,
3109
+ protocol: "http/protobuf",
3110
+ headerNames: Object.freeze([]),
3111
+ timeoutMillis: 1e4,
3112
+ maxBatchSize: 128,
3113
+ maxQueueSize: 2048,
3114
+ maxRetryAttempts: 2,
3115
+ serviceName: "coding-agent",
3116
+ resourceAttributes: EMPTY_RESOURCE_ATTRIBUTES,
3117
+ logs: DEFAULT_LOGS_POLICY
3083
3118
  });
3084
- var subagentEndEventSchema = event({
3085
- type: z13.literal("subagent.end"),
3086
- subagentInvocationId: invocationIdSchema,
3087
- outcome: outcomeSchema,
3088
- durationMillis: durationMillisSchema.optional(),
3089
- usage: canonicalUsageSchema.optional()
3119
+ var DEFAULT_DETECTION_POLICY = Object.freeze({
3120
+ minimumConfidence: "strong",
3121
+ allowAmbiguousFallback: true,
3122
+ allowedProviderIds: Object.freeze([])
3090
3123
  });
3091
- var compactionPerformedEventSchema = event({
3092
- type: z13.literal("compaction.performed"),
3093
- trigger: z13.enum(["automatic", "manual", "unknown"]),
3094
- /** Provider-reported context size before and after compaction, if known. */
3095
- contextTokensBefore: tokenCountSchema.optional(),
3096
- contextTokensAfter: tokenCountSchema.optional(),
3097
- droppedMessageCount: z13.number().int().min(0).optional(),
3098
- usage: canonicalUsageSchema.optional()
3124
+ var DEFAULT_DIAGNOSTICS_POLICY = Object.freeze({
3125
+ logLevel: "warn",
3126
+ emitErrorEvents: true
3099
3127
  });
3100
- var errorRaisedEventSchema = event({
3101
- type: z13.literal("error.raised"),
3102
- errorCode: otelHookErrorCodeSchema,
3103
- severity: errorSeveritySchema,
3104
- phase: errorPhaseSchema,
3105
- retryable: z13.boolean(),
3106
- /** Error text is content: it is described, never embedded verbatim by default. */
3107
- message: contentFactSchema.optional(),
3108
- /** Non-sensitive, provider-agnostic short label. */
3109
- detail: nonEmptyStringSchema.optional()
3128
+ var DEFAULT_CONFIG = Object.freeze({
3129
+ exporter: DEFAULT_EXPORTER_POLICY,
3130
+ privacy: DEFAULT_PRIVACY_POLICY,
3131
+ detection: DEFAULT_DETECTION_POLICY,
3132
+ diagnostics: DEFAULT_DIAGNOSTICS_POLICY
3110
3133
  });
3111
- var canonicalEventSchema = z13.discriminatedUnion("type", [
3112
- sessionStartEventSchema,
3113
- sessionEndEventSchema,
3114
- promptSubmittedEventSchema,
3115
- generationStartEventSchema,
3116
- generationEndEventSchema,
3117
- toolStartEventSchema,
3118
- toolEndEventSchema,
3119
- subagentStartEventSchema,
3120
- subagentEndEventSchema,
3121
- compactionPerformedEventSchema,
3122
- errorRaisedEventSchema
3123
- ]);
3124
3134
 
3125
3135
  // src/providers/adapter.ts
3136
+ import { z as z14 } from "zod";
3126
3137
  var providerDetectionSchema = z14.strictObject({
3127
3138
  providerId: resolvedProviderIdSchema,
3128
3139
  confidence: detectionConfidenceSchema,
@@ -3600,9 +3611,7 @@ var resolveHint = async (hint, locator, privacy) => {
3600
3611
  return parsed.success ? parsed.data : void 0;
3601
3612
  };
3602
3613
  var resolveEventTargets = async (input) => {
3603
- const pending = input.events.filter(
3604
- (event2) => (event2.type === "tool.start" || event2.type === "tool.end") && input.hints.has(event2.eventId)
3605
- );
3614
+ const pending = input.events.filter((event2) => isTargetedEvent(event2) && input.hints.has(event2.eventId));
3606
3615
  if (pending.length === 0) {
3607
3616
  return { events: input.events, resolved: 0, timedOut: false };
3608
3617
  }
@@ -3634,7 +3643,7 @@ var resolveEventTargets = async (input) => {
3634
3643
  const settled = new Map(targets);
3635
3644
  const events = input.events.map((event2) => {
3636
3645
  const target = settled.get(event2.eventId);
3637
- if (target === void 0 || event2.type !== "tool.start" && event2.type !== "tool.end") {
3646
+ if (target === void 0 || !isTargetedEvent(event2)) {
3638
3647
  return event2;
3639
3648
  }
3640
3649
  return { ...event2, target };
@@ -5328,7 +5337,8 @@ var eventAttributes = (event2) => {
5328
5337
  [ATTR_OTELHOOK_SESSION_KIND]: event2.sessionKind,
5329
5338
  ...event2.agentName === void 0 ? {} : { [ATTR_OTELHOOK_AGENT_NAME2]: event2.agentName },
5330
5339
  ...event2.agentVersion === void 0 ? {} : { [ATTR_OTELHOOK_AGENT_VERSION2]: event2.agentVersion },
5331
- ...event2.model === void 0 ? {} : { [ATTR_GEN_AI_REQUEST_MODEL2]: event2.model.modelId }
5340
+ ...event2.model === void 0 ? {} : { [ATTR_GEN_AI_REQUEST_MODEL2]: event2.model.modelId },
5341
+ ...targetAttributes(event2)
5332
5342
  };
5333
5343
  case "session.end":
5334
5344
  return {
@@ -5338,7 +5348,8 @@ var eventAttributes = (event2) => {
5338
5348
  case "prompt.submitted":
5339
5349
  return {
5340
5350
  [ATTR_OTELHOOK_PROMPT_SOURCE]: event2.promptSource,
5341
- ...event2.turnIndex === void 0 ? {} : { [ATTR_OTELHOOK_PROMPT_TURN_INDEX]: event2.turnIndex }
5351
+ ...event2.turnIndex === void 0 ? {} : { [ATTR_OTELHOOK_PROMPT_TURN_INDEX]: event2.turnIndex },
5352
+ ...targetAttributes(event2)
5342
5353
  };
5343
5354
  case "generation.start":
5344
5355
  return {