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