@osfactory/otel-hook 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +1020 -0
- package/dist/adapter-DIgRACtL.d.ts +303 -0
- package/dist/cli.js +12607 -0
- package/dist/cli.js.map +1 -0
- package/dist/config.d.ts +233 -0
- package/dist/config.js +996 -0
- package/dist/config.js.map +1 -0
- package/dist/content-CoB7aNP1.d.ts +118 -0
- package/dist/diagnostics.d.ts +58 -0
- package/dist/diagnostics.js +46 -0
- package/dist/diagnostics.js.map +1 -0
- package/dist/errors.d.ts +91 -0
- package/dist/errors.js +322 -0
- package/dist/errors.js.map +1 -0
- package/dist/events-VxBnDFaO.d.ts +2044 -0
- package/dist/filesystem-store-J8jjDMTh.d.ts +65 -0
- package/dist/hook-CGpo-vks.d.ts +292 -0
- package/dist/identity-BrVBs901.d.ts +227 -0
- package/dist/index.d.ts +44 -0
- package/dist/index.js +11798 -0
- package/dist/index.js.map +1 -0
- package/dist/install.d.ts +1021 -0
- package/dist/install.js +3271 -0
- package/dist/install.js.map +1 -0
- package/dist/integration.d.ts +303 -0
- package/dist/integration.js +5942 -0
- package/dist/integration.js.map +1 -0
- package/dist/keys-Dej5bN3L.d.ts +7 -0
- package/dist/lifecycle.d.ts +428 -0
- package/dist/lifecycle.js +1077 -0
- package/dist/lifecycle.js.map +1 -0
- package/dist/memory-DXVBc8V9.d.ts +94 -0
- package/dist/model.d.ts +45 -0
- package/dist/model.js +1023 -0
- package/dist/model.js.map +1 -0
- package/dist/otlp-log-sink-CeIFDDpn.d.ts +457 -0
- package/dist/payload-CHr53E_v.d.ts +201 -0
- package/dist/policy-D1CrlYn3.d.ts +73 -0
- package/dist/ports-Q8x0ODhs.d.ts +200 -0
- package/dist/primitives-CJ8-rn-f.d.ts +75 -0
- package/dist/privacy.d.ts +51 -0
- package/dist/privacy.js +633 -0
- package/dist/privacy.js.map +1 -0
- package/dist/providers.d.ts +257 -0
- package/dist/providers.js +4398 -0
- package/dist/providers.js.map +1 -0
- package/dist/registry-BzYmC9OC.d.ts +49 -0
- package/dist/runtime.d.ts +32 -0
- package/dist/runtime.js +2907 -0
- package/dist/runtime.js.map +1 -0
- package/dist/schema-Cn0-xz8L.d.ts +224 -0
- package/dist/semconv-Baoz-0OI.d.ts +188 -0
- package/dist/service-j4jEO6cZ.d.ts +68 -0
- package/dist/state.d.ts +36 -0
- package/dist/state.js +710 -0
- package/dist/state.js.map +1 -0
- package/dist/taxonomy-DwhTtuWd.d.ts +87 -0
- package/dist/telemetry.d.ts +77 -0
- package/dist/telemetry.js +2294 -0
- package/dist/telemetry.js.map +1 -0
- package/dist/testing.d.ts +155 -0
- package/dist/testing.js +6513 -0
- package/dist/testing.js.map +1 -0
- package/package.json +124 -0
|
@@ -0,0 +1,1077 @@
|
|
|
1
|
+
// src/lifecycle/dedup.ts
|
|
2
|
+
import { randomBytes } from "crypto";
|
|
3
|
+
|
|
4
|
+
// src/state/store.ts
|
|
5
|
+
var isLockingStateStore = (store) => typeof store.withSessionLock === "function";
|
|
6
|
+
var withOptionalSessionLock = async (store, sessionId, fn, options) => {
|
|
7
|
+
if (isLockingStateStore(store)) {
|
|
8
|
+
return store.withSessionLock(sessionId, fn, options);
|
|
9
|
+
}
|
|
10
|
+
return fn();
|
|
11
|
+
};
|
|
12
|
+
|
|
13
|
+
// src/lifecycle/keys.ts
|
|
14
|
+
var LIFECYCLE_PREFIX = "lifecycle";
|
|
15
|
+
var SPAN_KEY_VERSION = 2;
|
|
16
|
+
var DEDUP_KEY_VERSION = 2;
|
|
17
|
+
var encodeSegment = (segment) => segment.replaceAll("%", "%25").replaceAll(":", "%3A");
|
|
18
|
+
var spanKey = (sessionId, providerId, scope, scopeKey) => `${spanScanPrefix(sessionId)}${encodeSegment(providerId)}:${encodeSegment(scope)}:${encodeSegment(scopeKey)}`;
|
|
19
|
+
var spanScanPrefix = (sessionId) => sessionId === void 0 ? `${LIFECYCLE_PREFIX}:span:` : `${LIFECYCLE_PREFIX}:span:v${String(SPAN_KEY_VERSION)}:${encodeSegment(sessionId)}:`;
|
|
20
|
+
var dedupKey = (scope, callbackId) => `${dedupScanPrefix(scope)}${encodeSegment(callbackId)}`;
|
|
21
|
+
var dedupScanPrefix = (scope) => scope === void 0 ? `${LIFECYCLE_PREFIX}:dedup:` : `${LIFECYCLE_PREFIX}:dedup:v${String(DEDUP_KEY_VERSION)}:${encodeSegment(scope)}:`;
|
|
22
|
+
var decodeSegment = (segment) => segment.replaceAll("%3A", ":").replaceAll("%25", "%");
|
|
23
|
+
var dedupScopeOf = (key) => {
|
|
24
|
+
const prefix = `${LIFECYCLE_PREFIX}:dedup:v${String(DEDUP_KEY_VERSION)}:`;
|
|
25
|
+
if (!key.startsWith(prefix)) {
|
|
26
|
+
return void 0;
|
|
27
|
+
}
|
|
28
|
+
const rest = key.slice(prefix.length);
|
|
29
|
+
const boundary = rest.indexOf(":");
|
|
30
|
+
return boundary <= 0 ? void 0 : decodeSegment(rest.slice(0, boundary));
|
|
31
|
+
};
|
|
32
|
+
var rollupUsageKey = (sessionId, scope, scopeKey) => `${rollupScanPrefix(sessionId)}${encodeSegment(scope)}:${encodeSegment(scopeKey)}`;
|
|
33
|
+
var rollupEpochKey = (sessionId, scope, scopeKey) => `${rollupEpochScanPrefix(sessionId)}${encodeSegment(scope)}:${encodeSegment(scopeKey)}`;
|
|
34
|
+
var rollupScanPrefix = (sessionId) => sessionId === void 0 ? `${LIFECYCLE_PREFIX}:usage:` : `${LIFECYCLE_PREFIX}:usage:${encodeSegment(sessionId)}:`;
|
|
35
|
+
var rollupEpochScanPrefix = (sessionId) => sessionId === void 0 ? `${LIFECYCLE_PREFIX}:epoch:` : `${LIFECYCLE_PREFIX}:epoch:${encodeSegment(sessionId)}:`;
|
|
36
|
+
|
|
37
|
+
// src/lifecycle/dedup.ts
|
|
38
|
+
var DEFAULT_STALE_CLAIM_MILLIS = 6e4;
|
|
39
|
+
var stateOf = (record) => {
|
|
40
|
+
if (record?.value.kind !== "attributes") {
|
|
41
|
+
return void 0;
|
|
42
|
+
}
|
|
43
|
+
const declared = record.value.attributes.state;
|
|
44
|
+
if (declared === "claimed" || declared === "completed") {
|
|
45
|
+
return declared;
|
|
46
|
+
}
|
|
47
|
+
return "completed";
|
|
48
|
+
};
|
|
49
|
+
var attemptOf = (record) => {
|
|
50
|
+
if (record?.value.kind !== "attributes") {
|
|
51
|
+
return 0;
|
|
52
|
+
}
|
|
53
|
+
const attempt = record.value.attributes.attempt;
|
|
54
|
+
return typeof attempt === "number" && Number.isInteger(attempt) && attempt > 0 ? attempt : 1;
|
|
55
|
+
};
|
|
56
|
+
var ownerOf = (record) => {
|
|
57
|
+
if (record?.value.kind !== "attributes") {
|
|
58
|
+
return void 0;
|
|
59
|
+
}
|
|
60
|
+
const owner = record.value.attributes.owner;
|
|
61
|
+
return typeof owner === "string" && owner.length > 0 ? owner : void 0;
|
|
62
|
+
};
|
|
63
|
+
var newOwnerToken = () => randomBytes(12).toString("hex");
|
|
64
|
+
var claimedAtOf = (record) => {
|
|
65
|
+
if (record?.value.kind !== "attributes") {
|
|
66
|
+
return void 0;
|
|
67
|
+
}
|
|
68
|
+
const claimedAt = record.value.attributes.claimedAt;
|
|
69
|
+
return typeof claimedAt === "number" ? claimedAt : record.updatedAt;
|
|
70
|
+
};
|
|
71
|
+
var createCallbackDeduplicator = (deps) => {
|
|
72
|
+
const { stateStore, clock } = deps;
|
|
73
|
+
const write = (key, attributes) => stateStore.write(key, { kind: "attributes", attributes });
|
|
74
|
+
const checkAndMark = (scope, callbackId) => withOptionalSessionLock(stateStore, scope, async () => {
|
|
75
|
+
const key = dedupKey(scope, callbackId);
|
|
76
|
+
const existing = await stateStore.read(key);
|
|
77
|
+
if (existing?.value.kind === "attributes") {
|
|
78
|
+
return { duplicate: true };
|
|
79
|
+
}
|
|
80
|
+
const now = clock.now();
|
|
81
|
+
await write(key, {
|
|
82
|
+
state: "completed",
|
|
83
|
+
attempt: 1,
|
|
84
|
+
claimedAt: now,
|
|
85
|
+
seenAt: now,
|
|
86
|
+
owner: newOwnerToken()
|
|
87
|
+
});
|
|
88
|
+
return { duplicate: false };
|
|
89
|
+
});
|
|
90
|
+
const claim = (scope, callbackId, options) => withOptionalSessionLock(stateStore, scope, async () => {
|
|
91
|
+
const staleClaimMillis = options?.staleClaimMillis ?? DEFAULT_STALE_CLAIM_MILLIS;
|
|
92
|
+
const key = dedupKey(scope, callbackId);
|
|
93
|
+
const existing = await stateStore.read(key);
|
|
94
|
+
const state = stateOf(existing);
|
|
95
|
+
const now = clock.now();
|
|
96
|
+
if (state === "completed") {
|
|
97
|
+
return { outcome: "duplicate", duplicate: true, owned: false, attempt: attemptOf(existing) };
|
|
98
|
+
}
|
|
99
|
+
if (state === "claimed") {
|
|
100
|
+
const claimedAt = claimedAtOf(existing) ?? now;
|
|
101
|
+
const age = now - claimedAt;
|
|
102
|
+
if (age <= staleClaimMillis) {
|
|
103
|
+
return {
|
|
104
|
+
outcome: "in-flight",
|
|
105
|
+
duplicate: true,
|
|
106
|
+
owned: false,
|
|
107
|
+
attempt: attemptOf(existing)
|
|
108
|
+
};
|
|
109
|
+
}
|
|
110
|
+
const attempt = attemptOf(existing) + 1;
|
|
111
|
+
const owner2 = newOwnerToken();
|
|
112
|
+
await write(key, { state: "claimed", attempt, claimedAt: now, owner: owner2 });
|
|
113
|
+
return {
|
|
114
|
+
outcome: "reclaimed",
|
|
115
|
+
duplicate: false,
|
|
116
|
+
owned: true,
|
|
117
|
+
attempt,
|
|
118
|
+
abandonedForMillis: age,
|
|
119
|
+
owner: owner2
|
|
120
|
+
};
|
|
121
|
+
}
|
|
122
|
+
const owner = newOwnerToken();
|
|
123
|
+
await write(key, { state: "claimed", attempt: 1, claimedAt: now, owner });
|
|
124
|
+
return { outcome: "fresh", duplicate: false, owned: true, attempt: 1, owner };
|
|
125
|
+
});
|
|
126
|
+
const commit = (scope, callbackId, owner) => withOptionalSessionLock(stateStore, scope, async () => {
|
|
127
|
+
const key = dedupKey(scope, callbackId);
|
|
128
|
+
const existing = await stateStore.read(key);
|
|
129
|
+
const now = clock.now();
|
|
130
|
+
const attempt = Math.max(attemptOf(existing), 1);
|
|
131
|
+
const recordedOwner = ownerOf(existing);
|
|
132
|
+
if (owner !== void 0 && recordedOwner !== void 0 && recordedOwner !== owner) {
|
|
133
|
+
return { status: "superseded", attempt };
|
|
134
|
+
}
|
|
135
|
+
await write(key, {
|
|
136
|
+
state: "completed",
|
|
137
|
+
attempt,
|
|
138
|
+
claimedAt: claimedAtOf(existing) ?? now,
|
|
139
|
+
completedAt: now,
|
|
140
|
+
seenAt: now,
|
|
141
|
+
...recordedOwner === void 0 ? {} : { owner: recordedOwner }
|
|
142
|
+
});
|
|
143
|
+
return { status: "committed", attempt };
|
|
144
|
+
});
|
|
145
|
+
const release = (scope, callbackId) => withOptionalSessionLock(stateStore, scope, async () => {
|
|
146
|
+
const key = dedupKey(scope, callbackId);
|
|
147
|
+
if (stateOf(await stateStore.read(key)) === "claimed") {
|
|
148
|
+
await stateStore.delete(key);
|
|
149
|
+
}
|
|
150
|
+
});
|
|
151
|
+
const cleanup = async (maxAgeMillis, options) => {
|
|
152
|
+
const keys = await stateStore.keys(dedupScanPrefix(options?.sessionId));
|
|
153
|
+
const cap = options?.maxEntries ?? 1e3;
|
|
154
|
+
const staleClaimMillis = options?.staleClaimMillis ?? DEFAULT_STALE_CLAIM_MILLIS;
|
|
155
|
+
const now = clock.now();
|
|
156
|
+
let removed = 0;
|
|
157
|
+
let scanned = 0;
|
|
158
|
+
let retainedInFlight = 0;
|
|
159
|
+
const isDroppable = (record, count) => {
|
|
160
|
+
if (record === void 0 || now - record.updatedAt <= maxAgeMillis) {
|
|
161
|
+
return false;
|
|
162
|
+
}
|
|
163
|
+
if (stateOf(record) === "claimed") {
|
|
164
|
+
const age = now - (claimedAtOf(record) ?? record.updatedAt);
|
|
165
|
+
if (age <= staleClaimMillis) {
|
|
166
|
+
if (count) {
|
|
167
|
+
retainedInFlight += 1;
|
|
168
|
+
}
|
|
169
|
+
return false;
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
return true;
|
|
173
|
+
};
|
|
174
|
+
for (const key of keys) {
|
|
175
|
+
if (scanned >= cap) {
|
|
176
|
+
break;
|
|
177
|
+
}
|
|
178
|
+
scanned += 1;
|
|
179
|
+
if (!isDroppable(await stateStore.read(key), true)) {
|
|
180
|
+
continue;
|
|
181
|
+
}
|
|
182
|
+
const scope = dedupScopeOf(key);
|
|
183
|
+
if (scope === void 0) {
|
|
184
|
+
await stateStore.delete(key);
|
|
185
|
+
removed += 1;
|
|
186
|
+
continue;
|
|
187
|
+
}
|
|
188
|
+
await withOptionalSessionLock(stateStore, scope, async () => {
|
|
189
|
+
if (!isDroppable(await stateStore.read(key), false)) {
|
|
190
|
+
return;
|
|
191
|
+
}
|
|
192
|
+
await stateStore.delete(key);
|
|
193
|
+
removed += 1;
|
|
194
|
+
});
|
|
195
|
+
}
|
|
196
|
+
return {
|
|
197
|
+
removed,
|
|
198
|
+
scanned,
|
|
199
|
+
...retainedInFlight === 0 ? {} : { retainedInFlight }
|
|
200
|
+
};
|
|
201
|
+
};
|
|
202
|
+
return { checkAndMark, claim, commit, release, cleanup };
|
|
203
|
+
};
|
|
204
|
+
|
|
205
|
+
// src/model/primitives.ts
|
|
206
|
+
import { z } from "zod";
|
|
207
|
+
var MAX_IDENTIFIER_LENGTH = 256;
|
|
208
|
+
var MAX_ATTRIBUTE_STRING_LENGTH = 4096;
|
|
209
|
+
var MAX_ATTRIBUTE_ARRAY_LENGTH = 128;
|
|
210
|
+
var nonEmptyStringSchema = z.string().min(1).max(MAX_IDENTIFIER_LENGTH);
|
|
211
|
+
var epochMillisSchema = z.number().int().min(0).max(864e13);
|
|
212
|
+
var durationMillisSchema = z.number().min(0).finite();
|
|
213
|
+
var tokenCountSchema = z.number().int().min(0);
|
|
214
|
+
var sequenceNumberSchema = z.number().int().min(0);
|
|
215
|
+
var brandedIdSchema = () => z.string().min(1).max(MAX_IDENTIFIER_LENGTH);
|
|
216
|
+
var invocationIdSchema = brandedIdSchema().brand();
|
|
217
|
+
var sessionIdSchema = brandedIdSchema().brand();
|
|
218
|
+
var eventIdSchema = brandedIdSchema().brand();
|
|
219
|
+
var WORKSPACE_ID_PATTERN = /^[a-z][a-z0-9]{0,15}:[A-Za-z0-9_-]{8,128}$/;
|
|
220
|
+
var workspaceIdSchema = z.string().regex(WORKSPACE_ID_PATTERN, "workspace id must be an opaque `<scheme>:<token>` handle").brand();
|
|
221
|
+
var PROVIDER_ID_PATTERN = /^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/;
|
|
222
|
+
var providerIdSchema = z.string().min(1).max(64).regex(PROVIDER_ID_PATTERN, "provider id must be lowercase and hyphenated").brand();
|
|
223
|
+
var UNKNOWN_PROVIDER_ID = "unknown";
|
|
224
|
+
var resolvedProviderIdSchema = z.union([
|
|
225
|
+
providerIdSchema,
|
|
226
|
+
z.literal(UNKNOWN_PROVIDER_ID)
|
|
227
|
+
]);
|
|
228
|
+
var attributePrimitiveSchema = z.union([
|
|
229
|
+
z.string().max(MAX_ATTRIBUTE_STRING_LENGTH),
|
|
230
|
+
z.number().finite(),
|
|
231
|
+
z.boolean()
|
|
232
|
+
]);
|
|
233
|
+
var attributeValueSchema = z.union([
|
|
234
|
+
attributePrimitiveSchema,
|
|
235
|
+
z.array(attributePrimitiveSchema).max(MAX_ATTRIBUTE_ARRAY_LENGTH)
|
|
236
|
+
]);
|
|
237
|
+
var attributesSchema = z.record(z.string().min(1).max(MAX_IDENTIFIER_LENGTH), attributeValueSchema);
|
|
238
|
+
var detectionConfidenceSchema = z.enum(["none", "weak", "strong", "exact"]);
|
|
239
|
+
var DETECTION_CONFIDENCE_RANK = Object.freeze({
|
|
240
|
+
none: 0,
|
|
241
|
+
weak: 1,
|
|
242
|
+
strong: 2,
|
|
243
|
+
exact: 3
|
|
244
|
+
});
|
|
245
|
+
var sourceTransportSchema = z.enum([
|
|
246
|
+
"hook-stdin",
|
|
247
|
+
"cli-argument",
|
|
248
|
+
"library-call",
|
|
249
|
+
"test-fixture"
|
|
250
|
+
]);
|
|
251
|
+
|
|
252
|
+
// src/telemetry/semconv.ts
|
|
253
|
+
import { createHash } from "crypto";
|
|
254
|
+
import { SpanKind, SpanStatusCode, TraceFlags } from "@opentelemetry/api";
|
|
255
|
+
import {
|
|
256
|
+
ATTR_ERROR_TYPE,
|
|
257
|
+
ATTR_GEN_AI_OPERATION_NAME,
|
|
258
|
+
ATTR_GEN_AI_REQUEST_MODEL,
|
|
259
|
+
ATTR_GEN_AI_RESPONSE_MODEL,
|
|
260
|
+
ATTR_GEN_AI_SYSTEM,
|
|
261
|
+
ATTR_GEN_AI_TOOL_CALL_ID,
|
|
262
|
+
ATTR_GEN_AI_TOOL_NAME,
|
|
263
|
+
ATTR_GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS,
|
|
264
|
+
ATTR_GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS,
|
|
265
|
+
ATTR_GEN_AI_USAGE_INPUT_TOKENS,
|
|
266
|
+
ATTR_GEN_AI_USAGE_OUTPUT_TOKENS,
|
|
267
|
+
ATTR_GEN_AI_USAGE_REASONING_OUTPUT_TOKENS,
|
|
268
|
+
ATTR_SESSION_ID
|
|
269
|
+
} from "@opentelemetry/semantic-conventions/incubating";
|
|
270
|
+
var SCOPE_NAME = "@osfactory/otel-hook";
|
|
271
|
+
var DEFAULT_INSTRUMENTATION_SCOPE = Object.freeze({
|
|
272
|
+
name: SCOPE_NAME,
|
|
273
|
+
version: "0.1.0"
|
|
274
|
+
});
|
|
275
|
+
var ATTR_OTELHOOK_TOOL_KIND = "otelhook.tool.kind";
|
|
276
|
+
var ATTR_OTELHOOK_DELEGATION_DEPTH = "otelhook.delegation_depth";
|
|
277
|
+
var ATTR_OTELHOOK_AGENT_NAME = "otelhook.agent.name";
|
|
278
|
+
var ATTR_OTELHOOK_AGENT_VERSION = "otelhook.agent.version";
|
|
279
|
+
var MAX_RECOVERED_START_ATTRIBUTES = 16;
|
|
280
|
+
var familyOf = (type) => {
|
|
281
|
+
switch (type) {
|
|
282
|
+
case "session.start":
|
|
283
|
+
case "session.end":
|
|
284
|
+
return "session";
|
|
285
|
+
case "generation.start":
|
|
286
|
+
case "generation.end":
|
|
287
|
+
return "generation";
|
|
288
|
+
case "tool.start":
|
|
289
|
+
case "tool.end":
|
|
290
|
+
return "tool";
|
|
291
|
+
case "subagent.start":
|
|
292
|
+
case "subagent.end":
|
|
293
|
+
return "subagent";
|
|
294
|
+
default:
|
|
295
|
+
return void 0;
|
|
296
|
+
}
|
|
297
|
+
};
|
|
298
|
+
var spanScopeRefOf = (event) => {
|
|
299
|
+
const family = familyOf(event.type);
|
|
300
|
+
if (family === void 0) {
|
|
301
|
+
return void 0;
|
|
302
|
+
}
|
|
303
|
+
switch (event.type) {
|
|
304
|
+
case "session.start":
|
|
305
|
+
case "session.end":
|
|
306
|
+
return { family, scopeKey: event.sessionId };
|
|
307
|
+
case "generation.start":
|
|
308
|
+
case "generation.end":
|
|
309
|
+
return { family, scopeKey: event.generationId };
|
|
310
|
+
case "tool.start":
|
|
311
|
+
case "tool.end":
|
|
312
|
+
return { family, scopeKey: event.toolCallId };
|
|
313
|
+
case "subagent.start":
|
|
314
|
+
case "subagent.end":
|
|
315
|
+
return { family, scopeKey: event.subagentInvocationId };
|
|
316
|
+
default:
|
|
317
|
+
return void 0;
|
|
318
|
+
}
|
|
319
|
+
};
|
|
320
|
+
var parentScopeRefOf = (event) => {
|
|
321
|
+
if (event.type === "session.start" || event.type === "session.end") {
|
|
322
|
+
return void 0;
|
|
323
|
+
}
|
|
324
|
+
if (event.type === "tool.start" && event.generationId !== void 0) {
|
|
325
|
+
return { family: "generation", scopeKey: event.generationId };
|
|
326
|
+
}
|
|
327
|
+
return { family: "session", scopeKey: event.sessionId };
|
|
328
|
+
};
|
|
329
|
+
var startOnlySpanAttributes = (event) => {
|
|
330
|
+
switch (event.type) {
|
|
331
|
+
case "session.start":
|
|
332
|
+
return {
|
|
333
|
+
...event.agentName === void 0 ? {} : { [ATTR_OTELHOOK_AGENT_NAME]: event.agentName },
|
|
334
|
+
...event.agentVersion === void 0 ? {} : { [ATTR_OTELHOOK_AGENT_VERSION]: event.agentVersion }
|
|
335
|
+
};
|
|
336
|
+
case "generation.start":
|
|
337
|
+
return {
|
|
338
|
+
[ATTR_GEN_AI_REQUEST_MODEL]: event.model.modelId,
|
|
339
|
+
...event.model.vendor === void 0 ? {} : { [ATTR_GEN_AI_SYSTEM]: event.model.vendor }
|
|
340
|
+
};
|
|
341
|
+
// `toolName` and `toolCallId` are on both tool edges, so they are not
|
|
342
|
+
// start-only and persisting them would just pad every record.
|
|
343
|
+
case "tool.start":
|
|
344
|
+
return { [ATTR_OTELHOOK_TOOL_KIND]: event.toolKind };
|
|
345
|
+
case "subagent.start":
|
|
346
|
+
return { [ATTR_OTELHOOK_DELEGATION_DEPTH]: event.delegationDepth };
|
|
347
|
+
default:
|
|
348
|
+
return {};
|
|
349
|
+
}
|
|
350
|
+
};
|
|
351
|
+
|
|
352
|
+
// src/lifecycle/span-correlator.ts
|
|
353
|
+
var SPAN_RECORD_VERSION = 2;
|
|
354
|
+
var DEFAULT_MAX_START_AGE_MILLIS = 24 * 60 * 60 * 1e3;
|
|
355
|
+
var ATTRIBUTE_PREFIX = "a:";
|
|
356
|
+
var SPAN_FAMILIES = ["session", "generation", "tool", "subagent"];
|
|
357
|
+
var isSpanFamily = (value) => typeof value === "string" && SPAN_FAMILIES.includes(value);
|
|
358
|
+
var optionalNumber = (value) => typeof value === "number" && Number.isFinite(value) ? value : void 0;
|
|
359
|
+
var optionalString = (value) => typeof value === "string" && value.length > 0 ? value : void 0;
|
|
360
|
+
var encodeAttributes = (attributes) => {
|
|
361
|
+
const encoded = {};
|
|
362
|
+
let count = 0;
|
|
363
|
+
for (const [key, value] of Object.entries(attributes ?? {})) {
|
|
364
|
+
if (count >= MAX_RECOVERED_START_ATTRIBUTES) {
|
|
365
|
+
break;
|
|
366
|
+
}
|
|
367
|
+
const encodedKey = `${ATTRIBUTE_PREFIX}${key}`;
|
|
368
|
+
if (encodedKey.length > MAX_IDENTIFIER_LENGTH) {
|
|
369
|
+
continue;
|
|
370
|
+
}
|
|
371
|
+
if (typeof value === "string") {
|
|
372
|
+
encoded[encodedKey] = value.slice(0, MAX_ATTRIBUTE_STRING_LENGTH);
|
|
373
|
+
} else if (typeof value === "number" && Number.isFinite(value)) {
|
|
374
|
+
encoded[encodedKey] = value;
|
|
375
|
+
} else if (typeof value === "boolean") {
|
|
376
|
+
encoded[encodedKey] = value;
|
|
377
|
+
} else {
|
|
378
|
+
continue;
|
|
379
|
+
}
|
|
380
|
+
count += 1;
|
|
381
|
+
}
|
|
382
|
+
return encoded;
|
|
383
|
+
};
|
|
384
|
+
var decodeAttributes = (attributes) => {
|
|
385
|
+
const decoded = {};
|
|
386
|
+
let count = 0;
|
|
387
|
+
for (const [key, value] of Object.entries(attributes)) {
|
|
388
|
+
if (!key.startsWith(ATTRIBUTE_PREFIX) || count >= MAX_RECOVERED_START_ATTRIBUTES) {
|
|
389
|
+
continue;
|
|
390
|
+
}
|
|
391
|
+
if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
|
|
392
|
+
decoded[key.slice(ATTRIBUTE_PREFIX.length)] = value;
|
|
393
|
+
count += 1;
|
|
394
|
+
}
|
|
395
|
+
}
|
|
396
|
+
return count === 0 ? void 0 : decoded;
|
|
397
|
+
};
|
|
398
|
+
var encodeRecord = (record) => ({
|
|
399
|
+
kind: "attributes",
|
|
400
|
+
attributes: {
|
|
401
|
+
v: SPAN_RECORD_VERSION,
|
|
402
|
+
providerId: record.providerId,
|
|
403
|
+
...record.startEventId === void 0 ? {} : { startEventId: record.startEventId },
|
|
404
|
+
...record.startedAt === void 0 ? {} : { startedAt: record.startedAt },
|
|
405
|
+
...record.endEventId === void 0 ? {} : { endEventId: record.endEventId },
|
|
406
|
+
...record.endedAt === void 0 ? {} : { endedAt: record.endedAt },
|
|
407
|
+
...record.exported === true ? { exported: true } : {},
|
|
408
|
+
...record.parent === void 0 ? {} : { parentFamily: record.parent.family, parentScopeKey: record.parent.scopeKey },
|
|
409
|
+
...encodeAttributes(record.attributes)
|
|
410
|
+
}
|
|
411
|
+
});
|
|
412
|
+
var decodeRecord = (attributes) => {
|
|
413
|
+
if (attributes["v"] !== SPAN_RECORD_VERSION) {
|
|
414
|
+
return { kind: "incompatible" };
|
|
415
|
+
}
|
|
416
|
+
const providerId = optionalString(attributes["providerId"]);
|
|
417
|
+
if (providerId === void 0) {
|
|
418
|
+
return { kind: "corrupt" };
|
|
419
|
+
}
|
|
420
|
+
const startedAt = optionalNumber(attributes["startedAt"]);
|
|
421
|
+
const startEventId = optionalString(attributes["startEventId"]);
|
|
422
|
+
if (startedAt === void 0 !== (startEventId === void 0)) {
|
|
423
|
+
return { kind: "corrupt" };
|
|
424
|
+
}
|
|
425
|
+
const endedAt = optionalNumber(attributes["endedAt"]);
|
|
426
|
+
const endEventId = optionalString(attributes["endEventId"]);
|
|
427
|
+
if (endedAt === void 0 !== (endEventId === void 0)) {
|
|
428
|
+
return { kind: "corrupt" };
|
|
429
|
+
}
|
|
430
|
+
const exported = attributes["exported"] === true;
|
|
431
|
+
const parentFamily = attributes["parentFamily"];
|
|
432
|
+
const parentScopeKey = optionalString(attributes["parentScopeKey"]);
|
|
433
|
+
const parent = isSpanFamily(parentFamily) && parentScopeKey !== void 0 ? { family: parentFamily, scopeKey: parentScopeKey } : void 0;
|
|
434
|
+
const decodedAttributes = decodeAttributes(attributes);
|
|
435
|
+
return {
|
|
436
|
+
kind: "present",
|
|
437
|
+
record: {
|
|
438
|
+
providerId,
|
|
439
|
+
...startEventId === void 0 ? {} : { startEventId },
|
|
440
|
+
...startedAt === void 0 ? {} : { startedAt },
|
|
441
|
+
...endEventId === void 0 ? {} : { endEventId },
|
|
442
|
+
...endedAt === void 0 ? {} : { endedAt },
|
|
443
|
+
...parent === void 0 ? {} : { parent },
|
|
444
|
+
...exported ? { exported: true } : {},
|
|
445
|
+
...decodedAttributes === void 0 ? {} : { attributes: decodedAttributes }
|
|
446
|
+
}
|
|
447
|
+
};
|
|
448
|
+
};
|
|
449
|
+
var factsOf = (record) => ({
|
|
450
|
+
...record.startedAt === void 0 ? {} : { startedAt: record.startedAt },
|
|
451
|
+
...record.endedAt === void 0 ? {} : { endedAt: record.endedAt },
|
|
452
|
+
...record.parent === void 0 ? {} : { parent: record.parent },
|
|
453
|
+
...record.attributes === void 0 ? {} : { attributes: record.attributes }
|
|
454
|
+
});
|
|
455
|
+
var correlationTimesOf = (facts, options = { withStart: true }) => ({
|
|
456
|
+
...facts.startedAt === void 0 || !options.withStart ? {} : { startMillis: facts.startedAt },
|
|
457
|
+
...facts.endedAt === void 0 ? {} : { endMillis: facts.endedAt },
|
|
458
|
+
...facts.parent === void 0 ? {} : { parent: facts.parent },
|
|
459
|
+
...facts.attributes === void 0 ? {} : { attributes: facts.attributes }
|
|
460
|
+
});
|
|
461
|
+
var orphanClassificationOf = (reason) => {
|
|
462
|
+
switch (reason) {
|
|
463
|
+
case "no-start-recorded":
|
|
464
|
+
return "missing-start";
|
|
465
|
+
case "start-expired":
|
|
466
|
+
return "expired-start";
|
|
467
|
+
case "already-closed":
|
|
468
|
+
return "already-closed";
|
|
469
|
+
case "provider-mismatch":
|
|
470
|
+
return "provider-mismatch";
|
|
471
|
+
case "state-incompatible":
|
|
472
|
+
return "state-incompatible";
|
|
473
|
+
case "state-corrupt":
|
|
474
|
+
return "state-corrupt";
|
|
475
|
+
}
|
|
476
|
+
};
|
|
477
|
+
var createSpanCorrelator = (deps) => {
|
|
478
|
+
const { stateStore, clock } = deps;
|
|
479
|
+
const maxStartAgeMillis = deps.maxStartAgeMillis ?? DEFAULT_MAX_START_AGE_MILLIS;
|
|
480
|
+
const keyFor = (input) => spanKey(input.sessionId, input.providerId, input.scope, input.scopeKey);
|
|
481
|
+
const readRecord = async (key) => {
|
|
482
|
+
const existing = await stateStore.read(key);
|
|
483
|
+
if (existing === void 0) {
|
|
484
|
+
return { kind: "absent" };
|
|
485
|
+
}
|
|
486
|
+
if (existing.value.kind !== "attributes") {
|
|
487
|
+
await stateStore.delete(key);
|
|
488
|
+
return { kind: "corrupt" };
|
|
489
|
+
}
|
|
490
|
+
const decoded = decodeRecord(existing.value.attributes);
|
|
491
|
+
if (decoded.kind === "corrupt" || decoded.kind === "incompatible") {
|
|
492
|
+
await stateStore.delete(key);
|
|
493
|
+
}
|
|
494
|
+
return decoded;
|
|
495
|
+
};
|
|
496
|
+
const recordStart = (input) => withOptionalSessionLock(stateStore, input.sessionId, async () => {
|
|
497
|
+
const key = keyFor(input);
|
|
498
|
+
const decoded = await readRecord(key);
|
|
499
|
+
if (decoded.kind === "present") {
|
|
500
|
+
const existing = decoded.record;
|
|
501
|
+
if (existing.providerId !== input.providerId) {
|
|
502
|
+
return { status: "conflict", reason: "provider-mismatch" };
|
|
503
|
+
}
|
|
504
|
+
if (existing.startEventId === input.eventId) {
|
|
505
|
+
return { status: "duplicate", facts: factsOf(existing) };
|
|
506
|
+
}
|
|
507
|
+
if (existing.startEventId === void 0 && existing.endEventId !== void 0) {
|
|
508
|
+
const completed = {
|
|
509
|
+
...existing,
|
|
510
|
+
startEventId: input.eventId,
|
|
511
|
+
startedAt: input.occurredAt,
|
|
512
|
+
...input.parent === void 0 ? {} : { parent: input.parent },
|
|
513
|
+
...input.attributes === void 0 ? {} : { attributes: input.attributes }
|
|
514
|
+
};
|
|
515
|
+
await stateStore.write(key, encodeRecord(completed));
|
|
516
|
+
return existing.exported === true ? { status: "published", facts: factsOf(completed) } : { status: "recorded", facts: factsOf(completed) };
|
|
517
|
+
}
|
|
518
|
+
}
|
|
519
|
+
const fresh = {
|
|
520
|
+
providerId: input.providerId,
|
|
521
|
+
startEventId: input.eventId,
|
|
522
|
+
startedAt: input.occurredAt,
|
|
523
|
+
...input.parent === void 0 ? {} : { parent: input.parent },
|
|
524
|
+
...input.attributes === void 0 ? {} : { attributes: input.attributes }
|
|
525
|
+
};
|
|
526
|
+
await stateStore.write(key, encodeRecord(fresh));
|
|
527
|
+
return { status: "recorded", facts: factsOf(fresh) };
|
|
528
|
+
});
|
|
529
|
+
const recordEnd = (input) => withOptionalSessionLock(stateStore, input.sessionId, async () => {
|
|
530
|
+
const key = keyFor(input);
|
|
531
|
+
const decoded = await readRecord(key);
|
|
532
|
+
if (decoded.kind === "incompatible" || decoded.kind === "corrupt") {
|
|
533
|
+
const reason = decoded.kind === "incompatible" ? "state-incompatible" : "state-corrupt";
|
|
534
|
+
return { status: "orphaned", reason, facts: { endedAt: input.occurredAt } };
|
|
535
|
+
}
|
|
536
|
+
if (decoded.kind === "absent") {
|
|
537
|
+
const endOnly = {
|
|
538
|
+
providerId: input.providerId,
|
|
539
|
+
endEventId: input.eventId,
|
|
540
|
+
endedAt: input.occurredAt,
|
|
541
|
+
// This end is about to be exported as an orphan under the scope's
|
|
542
|
+
// canonical span id, so a start arriving later must not reuse it.
|
|
543
|
+
exported: true
|
|
544
|
+
};
|
|
545
|
+
await stateStore.write(key, encodeRecord(endOnly));
|
|
546
|
+
return { status: "orphaned", reason: "no-start-recorded", facts: factsOf(endOnly) };
|
|
547
|
+
}
|
|
548
|
+
const existing = decoded.record;
|
|
549
|
+
if (existing.providerId !== input.providerId) {
|
|
550
|
+
return {
|
|
551
|
+
status: "orphaned",
|
|
552
|
+
reason: "provider-mismatch",
|
|
553
|
+
facts: { endedAt: input.occurredAt }
|
|
554
|
+
};
|
|
555
|
+
}
|
|
556
|
+
if (existing.endEventId === input.eventId) {
|
|
557
|
+
return { status: "duplicate", facts: factsOf(existing) };
|
|
558
|
+
}
|
|
559
|
+
if (existing.endEventId !== void 0) {
|
|
560
|
+
return {
|
|
561
|
+
status: "orphaned",
|
|
562
|
+
reason: "already-closed",
|
|
563
|
+
facts: { endedAt: input.occurredAt }
|
|
564
|
+
};
|
|
565
|
+
}
|
|
566
|
+
if (existing.startedAt === void 0) {
|
|
567
|
+
const replaced = {
|
|
568
|
+
...existing,
|
|
569
|
+
endEventId: input.eventId,
|
|
570
|
+
endedAt: input.occurredAt,
|
|
571
|
+
exported: true
|
|
572
|
+
};
|
|
573
|
+
await stateStore.write(key, encodeRecord(replaced));
|
|
574
|
+
return { status: "orphaned", reason: "no-start-recorded", facts: factsOf(replaced) };
|
|
575
|
+
}
|
|
576
|
+
if (input.occurredAt - existing.startedAt > maxStartAgeMillis) {
|
|
577
|
+
await stateStore.delete(key);
|
|
578
|
+
return { status: "orphaned", reason: "start-expired", facts: { endedAt: input.occurredAt } };
|
|
579
|
+
}
|
|
580
|
+
const closed = {
|
|
581
|
+
...existing,
|
|
582
|
+
endEventId: input.eventId,
|
|
583
|
+
endedAt: input.occurredAt,
|
|
584
|
+
exported: true
|
|
585
|
+
};
|
|
586
|
+
await stateStore.write(key, encodeRecord(closed));
|
|
587
|
+
return {
|
|
588
|
+
status: "matched",
|
|
589
|
+
startedAt: existing.startedAt,
|
|
590
|
+
durationMillis: Math.max(0, input.occurredAt - existing.startedAt),
|
|
591
|
+
facts: factsOf(closed)
|
|
592
|
+
};
|
|
593
|
+
});
|
|
594
|
+
const correlateGroup = async (group) => {
|
|
595
|
+
const base = {
|
|
596
|
+
providerId: group.providerId,
|
|
597
|
+
sessionId: group.sessionId,
|
|
598
|
+
ref: group.ref
|
|
599
|
+
};
|
|
600
|
+
const unpaired = (orphan, facts) => ({
|
|
601
|
+
...base,
|
|
602
|
+
pairing: "unpaired",
|
|
603
|
+
orphan,
|
|
604
|
+
// An unpaired span has no trustworthy start, so a start time is the one
|
|
605
|
+
// fact it must not carry; everything else recovered is still true.
|
|
606
|
+
...correlationTimesOf(facts, { withStart: false })
|
|
607
|
+
});
|
|
608
|
+
let startFacts;
|
|
609
|
+
if (group.start !== void 0) {
|
|
610
|
+
const parent = parentScopeRefOf(group.start);
|
|
611
|
+
const result2 = await recordStart({
|
|
612
|
+
sessionId: group.sessionId,
|
|
613
|
+
providerId: group.providerId,
|
|
614
|
+
scope: group.ref.family,
|
|
615
|
+
scopeKey: group.ref.scopeKey,
|
|
616
|
+
eventId: group.start.eventId,
|
|
617
|
+
occurredAt: group.start.occurredAt,
|
|
618
|
+
...parent === void 0 ? {} : { parent },
|
|
619
|
+
attributes: startOnlySpanAttributes(group.start)
|
|
620
|
+
});
|
|
621
|
+
if (result2.status === "conflict") {
|
|
622
|
+
return unpaired("provider-mismatch", {});
|
|
623
|
+
}
|
|
624
|
+
if (result2.status === "published" && group.end === void 0) {
|
|
625
|
+
return { ...unpaired("already-closed", result2.facts), disposition: "defer" };
|
|
626
|
+
}
|
|
627
|
+
startFacts = result2.facts;
|
|
628
|
+
}
|
|
629
|
+
if (group.end === void 0) {
|
|
630
|
+
const facts = startFacts ?? {};
|
|
631
|
+
if (facts.endedAt !== void 0) {
|
|
632
|
+
return {
|
|
633
|
+
...base,
|
|
634
|
+
pairing: "cross-process",
|
|
635
|
+
orphan: "none",
|
|
636
|
+
disposition: "emit",
|
|
637
|
+
...correlationTimesOf(facts)
|
|
638
|
+
};
|
|
639
|
+
}
|
|
640
|
+
return { ...unpaired("missing-end", facts), disposition: "defer" };
|
|
641
|
+
}
|
|
642
|
+
const result = await recordEnd({
|
|
643
|
+
sessionId: group.sessionId,
|
|
644
|
+
providerId: group.providerId,
|
|
645
|
+
scope: group.ref.family,
|
|
646
|
+
scopeKey: group.ref.scopeKey,
|
|
647
|
+
eventId: group.end.eventId,
|
|
648
|
+
occurredAt: group.end.occurredAt
|
|
649
|
+
});
|
|
650
|
+
if (result.status === "orphaned") {
|
|
651
|
+
const orphan = orphanClassificationOf(result.reason);
|
|
652
|
+
return orphan === "already-closed" ? {
|
|
653
|
+
...unpaired(orphan, result.facts),
|
|
654
|
+
disposition: "emit",
|
|
655
|
+
spanIdDiscriminator: group.end.eventId
|
|
656
|
+
} : { ...unpaired(orphan, result.facts), disposition: "emit" };
|
|
657
|
+
}
|
|
658
|
+
if (result.status === "duplicate" && result.facts.startedAt === void 0) {
|
|
659
|
+
return { ...unpaired("missing-start", result.facts), disposition: "emit" };
|
|
660
|
+
}
|
|
661
|
+
return {
|
|
662
|
+
...base,
|
|
663
|
+
pairing: group.start === void 0 ? "cross-process" : "in-batch",
|
|
664
|
+
orphan: "none",
|
|
665
|
+
disposition: "emit",
|
|
666
|
+
...correlationTimesOf(result.facts)
|
|
667
|
+
};
|
|
668
|
+
};
|
|
669
|
+
const correlateBatch = async (events) => {
|
|
670
|
+
const groups = /* @__PURE__ */ new Map();
|
|
671
|
+
for (const event of events) {
|
|
672
|
+
const ref = spanScopeRefOf(event);
|
|
673
|
+
if (ref === void 0) {
|
|
674
|
+
continue;
|
|
675
|
+
}
|
|
676
|
+
const providerId = event.provenance.providerId;
|
|
677
|
+
const groupKey = [providerId, event.sessionId, ref.family, ref.scopeKey].join("\0");
|
|
678
|
+
const group = groups.get(groupKey) ?? {
|
|
679
|
+
providerId,
|
|
680
|
+
sessionId: event.sessionId,
|
|
681
|
+
ref
|
|
682
|
+
};
|
|
683
|
+
if (event.type.endsWith(".start")) {
|
|
684
|
+
group.start = event;
|
|
685
|
+
} else {
|
|
686
|
+
group.end = event;
|
|
687
|
+
}
|
|
688
|
+
groups.set(groupKey, group);
|
|
689
|
+
}
|
|
690
|
+
const correlations = [];
|
|
691
|
+
for (const group of groups.values()) {
|
|
692
|
+
try {
|
|
693
|
+
correlations.push(await correlateGroup(group));
|
|
694
|
+
} catch {
|
|
695
|
+
const unrecordedStart = group.start !== void 0 && group.end === void 0;
|
|
696
|
+
correlations.push({
|
|
697
|
+
providerId: group.providerId,
|
|
698
|
+
sessionId: group.sessionId,
|
|
699
|
+
ref: group.ref,
|
|
700
|
+
pairing: "unpaired",
|
|
701
|
+
orphan: "state-unavailable",
|
|
702
|
+
disposition: "emit",
|
|
703
|
+
...unrecordedStart && group.start !== void 0 ? { spanIdDiscriminator: group.start.eventId } : {}
|
|
704
|
+
});
|
|
705
|
+
}
|
|
706
|
+
}
|
|
707
|
+
return correlations;
|
|
708
|
+
};
|
|
709
|
+
const cleanup = async (maxAgeMillis, options) => {
|
|
710
|
+
const keys = await stateStore.keys(spanScanPrefix(options?.sessionId));
|
|
711
|
+
const cap = options?.maxEntries ?? 1e3;
|
|
712
|
+
const now = clock.now();
|
|
713
|
+
let removed = 0;
|
|
714
|
+
let scanned = 0;
|
|
715
|
+
let expiredOpen = 0;
|
|
716
|
+
for (const key of keys) {
|
|
717
|
+
if (scanned >= cap) {
|
|
718
|
+
break;
|
|
719
|
+
}
|
|
720
|
+
scanned += 1;
|
|
721
|
+
const record = await stateStore.read(key);
|
|
722
|
+
if (record !== void 0 && now - record.updatedAt > maxAgeMillis) {
|
|
723
|
+
if (record.value.kind === "attributes") {
|
|
724
|
+
const decoded = decodeRecord(record.value.attributes);
|
|
725
|
+
if (decoded.kind === "present" && decoded.record.startedAt !== void 0 && decoded.record.endedAt === void 0) {
|
|
726
|
+
expiredOpen += 1;
|
|
727
|
+
}
|
|
728
|
+
}
|
|
729
|
+
await stateStore.delete(key);
|
|
730
|
+
removed += 1;
|
|
731
|
+
}
|
|
732
|
+
}
|
|
733
|
+
return { removed, scanned, expiredOpen };
|
|
734
|
+
};
|
|
735
|
+
return { recordStart, recordEnd, correlateBatch, cleanup };
|
|
736
|
+
};
|
|
737
|
+
|
|
738
|
+
// src/model/usage.ts
|
|
739
|
+
import { z as z2 } from "zod";
|
|
740
|
+
var usageTemporalitySchema = z2.enum(["delta", "cumulative"]);
|
|
741
|
+
var cacheCreationAccountingSchema = z2.enum([
|
|
742
|
+
"included-in-input",
|
|
743
|
+
"disjoint-from-input",
|
|
744
|
+
"not-reported"
|
|
745
|
+
]);
|
|
746
|
+
var providerTotalAgreementSchema = z2.enum(["unreported", "agrees", "disagrees"]);
|
|
747
|
+
var usageReportSchema = z2.strictObject({
|
|
748
|
+
temporality: usageTemporalitySchema,
|
|
749
|
+
/** Inclusive input tokens. */
|
|
750
|
+
inputTokens: tokenCountSchema.optional(),
|
|
751
|
+
/** Subset of `inputTokens` served from a prompt cache. */
|
|
752
|
+
cachedInputTokens: tokenCountSchema.optional(),
|
|
753
|
+
/** Tokens written to a prompt cache. */
|
|
754
|
+
cacheCreationInputTokens: tokenCountSchema.optional(),
|
|
755
|
+
/** Required when `cacheCreationInputTokens` is present and non-zero. */
|
|
756
|
+
cacheCreationAccounting: cacheCreationAccountingSchema.optional(),
|
|
757
|
+
/** Inclusive output tokens. */
|
|
758
|
+
outputTokens: tokenCountSchema.optional(),
|
|
759
|
+
/** Subset of `outputTokens` spent on reasoning. */
|
|
760
|
+
reasoningOutputTokens: tokenCountSchema.optional(),
|
|
761
|
+
/** Total exactly as the provider reported it, if it reported one. */
|
|
762
|
+
providerTotalTokens: tokenCountSchema.optional()
|
|
763
|
+
});
|
|
764
|
+
var canonicalUsageSchema = z2.strictObject({
|
|
765
|
+
temporality: usageTemporalitySchema,
|
|
766
|
+
inputTokens: tokenCountSchema,
|
|
767
|
+
cachedInputTokens: tokenCountSchema,
|
|
768
|
+
cacheCreationInputTokens: tokenCountSchema,
|
|
769
|
+
cacheCreationAccounting: cacheCreationAccountingSchema,
|
|
770
|
+
outputTokens: tokenCountSchema,
|
|
771
|
+
reasoningOutputTokens: tokenCountSchema,
|
|
772
|
+
/** Derived: input tokens that were neither cache reads nor cache writes. */
|
|
773
|
+
uncachedInputTokens: tokenCountSchema,
|
|
774
|
+
/** Derived: canonical billable total. */
|
|
775
|
+
totalTokens: tokenCountSchema,
|
|
776
|
+
providerTotalTokens: tokenCountSchema.optional(),
|
|
777
|
+
providerTotalAgreement: providerTotalAgreementSchema
|
|
778
|
+
}).check((ctx) => {
|
|
779
|
+
const usage = ctx.value;
|
|
780
|
+
const push = (message) => {
|
|
781
|
+
ctx.issues.push({ code: "custom", input: usage, message });
|
|
782
|
+
};
|
|
783
|
+
if (usage.cachedInputTokens > usage.inputTokens) {
|
|
784
|
+
push("cachedInputTokens must not exceed inputTokens (it is a subset)");
|
|
785
|
+
}
|
|
786
|
+
if (usage.reasoningOutputTokens > usage.outputTokens) {
|
|
787
|
+
push("reasoningOutputTokens must not exceed outputTokens (it is a subset)");
|
|
788
|
+
}
|
|
789
|
+
if (usage.cacheCreationAccounting === "not-reported" && usage.cacheCreationInputTokens !== 0) {
|
|
790
|
+
push("cacheCreationInputTokens must be 0 when cacheCreationAccounting is not-reported");
|
|
791
|
+
}
|
|
792
|
+
const creationInsideInput = usage.cacheCreationAccounting === "included-in-input" ? usage.cacheCreationInputTokens : 0;
|
|
793
|
+
if (usage.cachedInputTokens + creationInsideInput > usage.inputTokens) {
|
|
794
|
+
push(
|
|
795
|
+
"cachedInputTokens + cacheCreationInputTokens must not exceed inputTokens when cache creation is included in input"
|
|
796
|
+
);
|
|
797
|
+
}
|
|
798
|
+
const expectedUncached = usage.inputTokens - usage.cachedInputTokens - creationInsideInput;
|
|
799
|
+
if (expectedUncached >= 0 && usage.uncachedInputTokens !== expectedUncached) {
|
|
800
|
+
push(`uncachedInputTokens must equal ${expectedUncached}`);
|
|
801
|
+
}
|
|
802
|
+
const creationOutsideInput = usage.cacheCreationAccounting === "disjoint-from-input" ? usage.cacheCreationInputTokens : 0;
|
|
803
|
+
const expectedTotal = usage.inputTokens + creationOutsideInput + usage.outputTokens;
|
|
804
|
+
if (usage.totalTokens !== expectedTotal) {
|
|
805
|
+
push(`totalTokens must equal ${expectedTotal}`);
|
|
806
|
+
}
|
|
807
|
+
const expectedAgreement = usage.providerTotalTokens === void 0 ? "unreported" : usage.providerTotalTokens === expectedTotal ? "agrees" : "disagrees";
|
|
808
|
+
if (usage.providerTotalAgreement !== expectedAgreement) {
|
|
809
|
+
push(`providerTotalAgreement must be ${expectedAgreement}`);
|
|
810
|
+
}
|
|
811
|
+
});
|
|
812
|
+
var normalizeUsage = (report) => {
|
|
813
|
+
const parsed = usageReportSchema.safeParse(report);
|
|
814
|
+
if (!parsed.success) {
|
|
815
|
+
return {
|
|
816
|
+
status: "invalid",
|
|
817
|
+
issues: parsed.error.issues.map((issue) => ({
|
|
818
|
+
code: "invalid-report",
|
|
819
|
+
message: `${issue.path.join(".") || "<root>"}: ${issue.message}`
|
|
820
|
+
}))
|
|
821
|
+
};
|
|
822
|
+
}
|
|
823
|
+
const input = parsed.data;
|
|
824
|
+
const issues = [];
|
|
825
|
+
const notes = [];
|
|
826
|
+
const inputTokens = input.inputTokens ?? 0;
|
|
827
|
+
const cachedInputTokens = input.cachedInputTokens ?? 0;
|
|
828
|
+
const cacheCreationInputTokens = input.cacheCreationInputTokens ?? 0;
|
|
829
|
+
const outputTokens = input.outputTokens ?? 0;
|
|
830
|
+
const reasoningOutputTokens = input.reasoningOutputTokens ?? 0;
|
|
831
|
+
let accounting;
|
|
832
|
+
if (cacheCreationInputTokens === 0) {
|
|
833
|
+
accounting = input.cacheCreationAccounting ?? "not-reported";
|
|
834
|
+
if (accounting !== "not-reported") {
|
|
835
|
+
notes.push(
|
|
836
|
+
`cacheCreationAccounting=${accounting} retained with zero cache-creation tokens`
|
|
837
|
+
);
|
|
838
|
+
}
|
|
839
|
+
} else if (input.cacheCreationAccounting === void 0) {
|
|
840
|
+
issues.push({
|
|
841
|
+
code: "cache-creation-accounting-missing",
|
|
842
|
+
message: "cacheCreationAccounting is required when cacheCreationInputTokens is non-zero; it cannot be inferred"
|
|
843
|
+
});
|
|
844
|
+
accounting = "not-reported";
|
|
845
|
+
} else if (input.cacheCreationAccounting === "not-reported") {
|
|
846
|
+
issues.push({
|
|
847
|
+
code: "cache-creation-accounting-missing",
|
|
848
|
+
message: "cacheCreationAccounting=not-reported conflicts with non-zero cacheCreationInputTokens"
|
|
849
|
+
});
|
|
850
|
+
accounting = "not-reported";
|
|
851
|
+
} else {
|
|
852
|
+
accounting = input.cacheCreationAccounting;
|
|
853
|
+
}
|
|
854
|
+
if (cachedInputTokens > inputTokens) {
|
|
855
|
+
issues.push({
|
|
856
|
+
code: "cached-exceeds-input",
|
|
857
|
+
message: `cachedInputTokens (${cachedInputTokens}) exceeds inclusive inputTokens (${inputTokens})`
|
|
858
|
+
});
|
|
859
|
+
}
|
|
860
|
+
if (reasoningOutputTokens > outputTokens) {
|
|
861
|
+
issues.push({
|
|
862
|
+
code: "reasoning-exceeds-output",
|
|
863
|
+
message: `reasoningOutputTokens (${reasoningOutputTokens}) exceeds inclusive outputTokens (${outputTokens})`
|
|
864
|
+
});
|
|
865
|
+
}
|
|
866
|
+
const creationInsideInput = accounting === "included-in-input" ? cacheCreationInputTokens : 0;
|
|
867
|
+
if (cachedInputTokens + creationInsideInput > inputTokens) {
|
|
868
|
+
issues.push({
|
|
869
|
+
code: "cache-creation-exceeds-input",
|
|
870
|
+
message: `cachedInputTokens + cacheCreationInputTokens (${cachedInputTokens + creationInsideInput}) exceeds inclusive inputTokens (${inputTokens})`
|
|
871
|
+
});
|
|
872
|
+
}
|
|
873
|
+
if (issues.length > 0) {
|
|
874
|
+
return { status: "invalid", issues };
|
|
875
|
+
}
|
|
876
|
+
const creationOutsideInput = accounting === "disjoint-from-input" ? cacheCreationInputTokens : 0;
|
|
877
|
+
const totalTokens = inputTokens + creationOutsideInput + outputTokens;
|
|
878
|
+
const providerTotalAgreement = input.providerTotalTokens === void 0 ? "unreported" : input.providerTotalTokens === totalTokens ? "agrees" : "disagrees";
|
|
879
|
+
if (providerTotalAgreement === "disagrees") {
|
|
880
|
+
notes.push(
|
|
881
|
+
`providerTotalTokens (${input.providerTotalTokens ?? 0}) disagrees with canonical total (${totalTokens}); both retained`
|
|
882
|
+
);
|
|
883
|
+
}
|
|
884
|
+
const usage = {
|
|
885
|
+
temporality: input.temporality,
|
|
886
|
+
inputTokens,
|
|
887
|
+
cachedInputTokens,
|
|
888
|
+
cacheCreationInputTokens,
|
|
889
|
+
cacheCreationAccounting: accounting,
|
|
890
|
+
outputTokens,
|
|
891
|
+
reasoningOutputTokens,
|
|
892
|
+
uncachedInputTokens: inputTokens - cachedInputTokens - creationInsideInput,
|
|
893
|
+
totalTokens,
|
|
894
|
+
...input.providerTotalTokens === void 0 ? {} : { providerTotalTokens: input.providerTotalTokens },
|
|
895
|
+
providerTotalAgreement
|
|
896
|
+
};
|
|
897
|
+
return { status: "ok", usage, notes };
|
|
898
|
+
};
|
|
899
|
+
var UsageNormalizationError = class extends Error {
|
|
900
|
+
issues;
|
|
901
|
+
constructor(issues) {
|
|
902
|
+
super(`invalid usage report: ${issues.map((issue) => issue.message).join("; ")}`);
|
|
903
|
+
this.name = "UsageNormalizationError";
|
|
904
|
+
this.issues = issues;
|
|
905
|
+
}
|
|
906
|
+
};
|
|
907
|
+
var normalizeUsageOrThrow = (report) => {
|
|
908
|
+
const result = normalizeUsage(report);
|
|
909
|
+
if (result.status === "invalid") {
|
|
910
|
+
throw new UsageNormalizationError(result.issues);
|
|
911
|
+
}
|
|
912
|
+
return result.usage;
|
|
913
|
+
};
|
|
914
|
+
var EMPTY_DELTA_USAGE = Object.freeze(
|
|
915
|
+
normalizeUsageOrThrow({ temporality: "delta" })
|
|
916
|
+
);
|
|
917
|
+
|
|
918
|
+
// src/lifecycle/usage-accumulator.ts
|
|
919
|
+
var EMPTY_CUMULATIVE_USAGE = normalizeUsageOrThrow({ temporality: "cumulative" });
|
|
920
|
+
var combineCumulativeWithDelta = (total, delta) => {
|
|
921
|
+
if (total.temporality !== "cumulative") {
|
|
922
|
+
throw new UsageNormalizationError([
|
|
923
|
+
{ code: "invalid-report", message: "usage rollup total must have cumulative temporality" }
|
|
924
|
+
]);
|
|
925
|
+
}
|
|
926
|
+
if (delta.temporality !== "delta") {
|
|
927
|
+
throw new UsageNormalizationError([
|
|
928
|
+
{ code: "invalid-report", message: "usage accumulator only accepts delta observations" }
|
|
929
|
+
]);
|
|
930
|
+
}
|
|
931
|
+
const accounting = total.cacheCreationInputTokens === 0 && total.cacheCreationAccounting === "not-reported" ? delta.cacheCreationAccounting : delta.cacheCreationInputTokens === 0 && delta.cacheCreationAccounting === "not-reported" ? total.cacheCreationAccounting : total.cacheCreationAccounting;
|
|
932
|
+
if (total.cacheCreationInputTokens !== 0 && delta.cacheCreationInputTokens !== 0 && total.cacheCreationAccounting !== delta.cacheCreationAccounting) {
|
|
933
|
+
throw new UsageNormalizationError([
|
|
934
|
+
{
|
|
935
|
+
code: "cache-creation-accounting-missing",
|
|
936
|
+
message: "cannot roll up usage across differing cacheCreationAccounting modes"
|
|
937
|
+
}
|
|
938
|
+
]);
|
|
939
|
+
}
|
|
940
|
+
const providerTotal = total.providerTotalTokens === void 0 && delta.providerTotalTokens === void 0 ? void 0 : (total.providerTotalTokens ?? 0) + (delta.providerTotalTokens ?? 0);
|
|
941
|
+
return normalizeUsageOrThrow({
|
|
942
|
+
temporality: "cumulative",
|
|
943
|
+
inputTokens: total.inputTokens + delta.inputTokens,
|
|
944
|
+
cachedInputTokens: total.cachedInputTokens + delta.cachedInputTokens,
|
|
945
|
+
cacheCreationInputTokens: total.cacheCreationInputTokens + delta.cacheCreationInputTokens,
|
|
946
|
+
cacheCreationAccounting: accounting,
|
|
947
|
+
outputTokens: total.outputTokens + delta.outputTokens,
|
|
948
|
+
reasoningOutputTokens: total.reasoningOutputTokens + delta.reasoningOutputTokens,
|
|
949
|
+
...providerTotal === void 0 ? {} : { providerTotalTokens: providerTotal }
|
|
950
|
+
});
|
|
951
|
+
};
|
|
952
|
+
var createUsageAccumulator = (deps) => {
|
|
953
|
+
const { stateStore, clock } = deps;
|
|
954
|
+
const readEpochMarker = (attributes) => {
|
|
955
|
+
const callbackId = attributes.resetDelivery;
|
|
956
|
+
const applications = attributes.resetApplications;
|
|
957
|
+
if (typeof callbackId !== "string" || callbackId.length === 0 || typeof applications !== "number" || !Number.isInteger(applications) || applications < 1) {
|
|
958
|
+
return void 0;
|
|
959
|
+
}
|
|
960
|
+
return { callbackId, applications };
|
|
961
|
+
};
|
|
962
|
+
const readEpoch = async (key) => {
|
|
963
|
+
const record = await stateStore.read(rollupEpochKey(key.sessionId, key.scope, key.scopeKey));
|
|
964
|
+
if (record?.value.kind === "attributes" && typeof record.value.attributes.epoch === "number") {
|
|
965
|
+
return record.value.attributes.epoch;
|
|
966
|
+
}
|
|
967
|
+
return 0;
|
|
968
|
+
};
|
|
969
|
+
const alreadyApplied = (marker, delivery) => delivery !== void 0 && marker !== void 0 && marker.callbackId === delivery.callbackId && delivery.ordinal < marker.applications;
|
|
970
|
+
const markerFor = (delivery) => delivery === void 0 ? {} : {
|
|
971
|
+
appliedDelivery: { callbackId: delivery.callbackId, applications: delivery.ordinal + 1 }
|
|
972
|
+
};
|
|
973
|
+
const accumulateDelta = (key, delta, options) => withOptionalSessionLock(stateStore, key.sessionId, async () => {
|
|
974
|
+
const usageKey = rollupUsageKey(key.sessionId, key.scope, key.scopeKey);
|
|
975
|
+
const existing = await stateStore.read(usageKey);
|
|
976
|
+
const previousTotal = existing?.value.kind === "usage-cumulative" ? existing.value.usage : EMPTY_CUMULATIVE_USAGE;
|
|
977
|
+
if (existing?.value.kind === "usage-cumulative" && alreadyApplied(existing.value.appliedDelivery, options?.delivery)) {
|
|
978
|
+
return { total: previousTotal, epoch: await readEpoch(key) };
|
|
979
|
+
}
|
|
980
|
+
const total = combineCumulativeWithDelta(previousTotal, delta);
|
|
981
|
+
await stateStore.write(usageKey, {
|
|
982
|
+
kind: "usage-cumulative",
|
|
983
|
+
usage: total,
|
|
984
|
+
...markerFor(options?.delivery)
|
|
985
|
+
});
|
|
986
|
+
return { total, epoch: await readEpoch(key) };
|
|
987
|
+
});
|
|
988
|
+
const recordReset = (key, options) => withOptionalSessionLock(stateStore, key.sessionId, async () => {
|
|
989
|
+
const epochKey = rollupEpochKey(key.sessionId, key.scope, key.scopeKey);
|
|
990
|
+
const existingEpoch = await stateStore.read(epochKey);
|
|
991
|
+
const marker = existingEpoch?.value.kind === "attributes" ? readEpochMarker(existingEpoch.value.attributes) : void 0;
|
|
992
|
+
if (alreadyApplied(marker, options?.delivery)) {
|
|
993
|
+
return { epoch: await readEpoch(key) };
|
|
994
|
+
}
|
|
995
|
+
const epoch = await readEpoch(key) + 1;
|
|
996
|
+
const applied = markerFor(options?.delivery).appliedDelivery;
|
|
997
|
+
await stateStore.write(epochKey, {
|
|
998
|
+
kind: "attributes",
|
|
999
|
+
attributes: {
|
|
1000
|
+
epoch,
|
|
1001
|
+
...applied === void 0 ? {} : { resetDelivery: applied.callbackId, resetApplications: applied.applications }
|
|
1002
|
+
}
|
|
1003
|
+
});
|
|
1004
|
+
await stateStore.delete(rollupUsageKey(key.sessionId, key.scope, key.scopeKey));
|
|
1005
|
+
return { epoch };
|
|
1006
|
+
});
|
|
1007
|
+
const read = async (key) => {
|
|
1008
|
+
const record = await stateStore.read(rollupUsageKey(key.sessionId, key.scope, key.scopeKey));
|
|
1009
|
+
if (record?.value.kind !== "usage-cumulative") {
|
|
1010
|
+
return void 0;
|
|
1011
|
+
}
|
|
1012
|
+
return { total: record.value.usage, epoch: await readEpoch(key) };
|
|
1013
|
+
};
|
|
1014
|
+
const cleanup = async (maxAgeMillis, options) => {
|
|
1015
|
+
const cap = options?.maxEntries ?? 1e3;
|
|
1016
|
+
const now = clock.now();
|
|
1017
|
+
let removed = 0;
|
|
1018
|
+
let scanned = 0;
|
|
1019
|
+
const sweep = async (keys) => {
|
|
1020
|
+
for (const key of keys) {
|
|
1021
|
+
if (scanned >= cap) {
|
|
1022
|
+
return;
|
|
1023
|
+
}
|
|
1024
|
+
scanned += 1;
|
|
1025
|
+
const record = await stateStore.read(key);
|
|
1026
|
+
if (record !== void 0 && now - record.updatedAt > maxAgeMillis) {
|
|
1027
|
+
await stateStore.delete(key);
|
|
1028
|
+
removed += 1;
|
|
1029
|
+
}
|
|
1030
|
+
}
|
|
1031
|
+
};
|
|
1032
|
+
await sweep(await stateStore.keys(rollupScanPrefix(options?.sessionId)));
|
|
1033
|
+
await sweep(await stateStore.keys(rollupEpochScanPrefix(options?.sessionId)));
|
|
1034
|
+
return { removed, scanned };
|
|
1035
|
+
};
|
|
1036
|
+
return { accumulateDelta, recordReset, read, cleanup };
|
|
1037
|
+
};
|
|
1038
|
+
|
|
1039
|
+
// src/lifecycle/janitor.ts
|
|
1040
|
+
var DEFAULT_MAX_AGE_MILLIS = 24 * 60 * 60 * 1e3;
|
|
1041
|
+
var DEFAULT_MAX_ENTRIES_PER_COMPONENT = 1e3;
|
|
1042
|
+
var createLifecycleJanitor = (options) => {
|
|
1043
|
+
const maxEntries = options.maxEntriesPerComponent ?? DEFAULT_MAX_ENTRIES_PER_COMPONENT;
|
|
1044
|
+
const spanMaxAge = options.spanMaxAgeMillis ?? DEFAULT_MAX_AGE_MILLIS;
|
|
1045
|
+
const dedupMaxAge = options.dedupMaxAgeMillis ?? DEFAULT_MAX_AGE_MILLIS;
|
|
1046
|
+
const usageMaxAge = options.usageMaxAgeMillis ?? DEFAULT_MAX_AGE_MILLIS;
|
|
1047
|
+
const runOnce = async (sessionId) => {
|
|
1048
|
+
const scope = { maxEntries, ...sessionId === void 0 ? {} : { sessionId } };
|
|
1049
|
+
const [span, dedup, usage] = await Promise.all([
|
|
1050
|
+
options.spanCorrelator?.cleanup(spanMaxAge, scope),
|
|
1051
|
+
// Deduplication is deliberately swept across every scope rather than the
|
|
1052
|
+
// ending session's: a delivery scope is a host-chosen namespace or a
|
|
1053
|
+
// digest of provider/installation/session, never a session id, so scoping
|
|
1054
|
+
// this sweep by `sessionId` would match nothing and let records accumulate
|
|
1055
|
+
// forever. The sweep is TTL-driven and still bounded by `maxEntries`.
|
|
1056
|
+
options.deduplicator?.cleanup(dedupMaxAge, {
|
|
1057
|
+
maxEntries,
|
|
1058
|
+
...options.dedupStaleClaimMillis === void 0 ? {} : { staleClaimMillis: options.dedupStaleClaimMillis }
|
|
1059
|
+
}),
|
|
1060
|
+
options.usageAccumulator?.cleanup(usageMaxAge, scope)
|
|
1061
|
+
]);
|
|
1062
|
+
return {
|
|
1063
|
+
...span === void 0 ? {} : { span },
|
|
1064
|
+
...dedup === void 0 ? {} : { dedup },
|
|
1065
|
+
...usage === void 0 ? {} : { usage }
|
|
1066
|
+
};
|
|
1067
|
+
};
|
|
1068
|
+
return { runOnce };
|
|
1069
|
+
};
|
|
1070
|
+
export {
|
|
1071
|
+
SPAN_RECORD_VERSION,
|
|
1072
|
+
createCallbackDeduplicator,
|
|
1073
|
+
createLifecycleJanitor,
|
|
1074
|
+
createSpanCorrelator,
|
|
1075
|
+
createUsageAccumulator
|
|
1076
|
+
};
|
|
1077
|
+
//# sourceMappingURL=lifecycle.js.map
|