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