@osfactory/otel-hook 0.9.0 → 0.11.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 +124 -4
- package/dist/{adapter-BJiz6lqM.d.ts → adapter-DiLknaTF.d.ts} +14 -2
- package/dist/cli.js +2272 -730
- package/dist/cli.js.map +1 -1
- package/dist/config.d.ts +13 -4
- package/dist/config.js +128 -23
- package/dist/config.js.map +1 -1
- package/dist/{destinations-C6Bm89W6.d.ts → destinations-BIl3gGzx.d.ts} +12 -2
- package/dist/diagnostics.d.ts +1 -1
- package/dist/diagnostics.js.map +1 -1
- package/dist/{events-B3MHoJTD.d.ts → events-CSD_YiJ2.d.ts} +2 -0
- package/dist/{export-destinations-d8tZV0G4.d.ts → export-destinations-QWKGGEjk.d.ts} +131 -6
- package/dist/{filesystem-store-r-nNA3BA.d.ts → filesystem-store-D3SCNmbX.d.ts} +1 -1
- package/dist/{hook-zA1b4cWd.d.ts → hook-BOecWGSz.d.ts} +10 -5
- package/dist/index.d.ts +16 -16
- package/dist/index.js +1808 -251
- package/dist/index.js.map +1 -1
- package/dist/install.d.ts +4 -4
- package/dist/install.js +31 -2
- package/dist/install.js.map +1 -1
- package/dist/integration.d.ts +37 -12
- package/dist/integration.js +3271 -1551
- package/dist/integration.js.map +1 -1
- package/dist/lifecycle.d.ts +55 -4
- package/dist/lifecycle.js +277 -4
- package/dist/lifecycle.js.map +1 -1
- package/dist/{memory-Bl9ANVff.d.ts → memory-Cs51jyRk.d.ts} +2 -2
- package/dist/{semconv-fPRb-dpU.d.ts → metric-model-DDnWxL9d.d.ts} +154 -2
- package/dist/model.d.ts +1 -1
- package/dist/model.js +7 -0
- package/dist/model.js.map +1 -1
- package/dist/{payload-Ci8_ERm6.d.ts → payload-ChtrEX6A.d.ts} +41 -2
- package/dist/{ports-n7KFOpKo.d.ts → ports-CeqLq31i.d.ts} +87 -2
- package/dist/providers.d.ts +146 -10
- package/dist/providers.js +397 -13
- package/dist/providers.js.map +1 -1
- package/dist/{registry-B8ZHc2bc.d.ts → registry-CcJNF3WY.d.ts} +2 -2
- package/dist/runtime.d.ts +8 -8
- package/dist/runtime.js +1404 -1219
- package/dist/runtime.js.map +1 -1
- package/dist/{schema-BxiVsU-d.d.ts → schema-DMnoU1V_.d.ts} +93 -1
- package/dist/state.d.ts +4 -4
- package/dist/state.js +630 -39
- package/dist/state.js.map +1 -1
- package/dist/telemetry.d.ts +6 -6
- package/dist/telemetry.js +872 -19
- package/dist/telemetry.js.map +1 -1
- package/dist/testing.d.ts +11 -9
- package/dist/testing.js +264 -34
- package/dist/testing.js.map +1 -1
- package/package.json +3 -1
package/dist/index.js
CHANGED
|
@@ -876,6 +876,13 @@ var generationEndEventSchema = event({
|
|
|
876
876
|
stopReason: nonEmptyStringSchema.optional(),
|
|
877
877
|
durationMillis: durationMillisSchema.optional(),
|
|
878
878
|
usage: canonicalUsageSchema.optional(),
|
|
879
|
+
/**
|
|
880
|
+
* True when `usage` is known to cover only part of the generation (for
|
|
881
|
+
* example the last model request of a multi-request turn); false when the
|
|
882
|
+
* provider or harness said it is the whole. Absent: not stated. Meaningless
|
|
883
|
+
* without `usage`.
|
|
884
|
+
*/
|
|
885
|
+
usagePartial: z9.boolean().optional(),
|
|
879
886
|
cost: costFactsSchema.optional(),
|
|
880
887
|
outputContent: contentFactsSchema.optional()
|
|
881
888
|
});
|
|
@@ -1345,11 +1352,11 @@ var createPrivacyService = (policyInput) => {
|
|
|
1345
1352
|
};
|
|
1346
1353
|
const flattenToAttributes = (value, prefix) => {
|
|
1347
1354
|
const attributes = {};
|
|
1348
|
-
const walk = (current,
|
|
1355
|
+
const walk = (current, path10) => {
|
|
1349
1356
|
if (typeof current === "string" || typeof current === "number" || typeof current === "boolean") {
|
|
1350
1357
|
const primitive = toAttributePrimitive(current);
|
|
1351
1358
|
if (primitive !== void 0) {
|
|
1352
|
-
attributes[
|
|
1359
|
+
attributes[path10] = primitive;
|
|
1353
1360
|
}
|
|
1354
1361
|
return;
|
|
1355
1362
|
}
|
|
@@ -1368,16 +1375,16 @@ var createPrivacyService = (policyInput) => {
|
|
|
1368
1375
|
primitives.push(entryPrimitive);
|
|
1369
1376
|
}
|
|
1370
1377
|
if (uniform) {
|
|
1371
|
-
attributes[
|
|
1378
|
+
attributes[path10] = primitives.slice(0, MAX_ATTRIBUTE_ARRAY_LENGTH);
|
|
1372
1379
|
return;
|
|
1373
1380
|
}
|
|
1374
1381
|
for (const [index, entry] of current.entries()) {
|
|
1375
|
-
walk(entry, `${
|
|
1382
|
+
walk(entry, `${path10}.${index}`);
|
|
1376
1383
|
}
|
|
1377
1384
|
return;
|
|
1378
1385
|
}
|
|
1379
1386
|
for (const [key, entry] of Object.entries(current)) {
|
|
1380
|
-
walk(entry,
|
|
1387
|
+
walk(entry, path10 === "" ? key : `${path10}.${key}`);
|
|
1381
1388
|
}
|
|
1382
1389
|
};
|
|
1383
1390
|
walk(value, prefix);
|
|
@@ -1813,7 +1820,7 @@ var HEADER_ENV_REFERENCE_PREFIX = "env:";
|
|
|
1813
1820
|
var HEADER_NAME_PATTERN2 = /^[A-Za-z0-9!#$%&'*+.^_`|~-]{1,128}$/;
|
|
1814
1821
|
var ENV_VARIABLE_NAME_PATTERN = /^[A-Za-z_][A-Za-z0-9_]{0,127}$/;
|
|
1815
1822
|
var MAX_HEADER_VALUE_LENGTH = 8192;
|
|
1816
|
-
var exportSignalSchema = z13.enum(["traces", "logs"]);
|
|
1823
|
+
var exportSignalSchema = z13.enum(["traces", "logs", "metrics"]);
|
|
1817
1824
|
var headerValueSchema = z13.string().min(1).max(MAX_HEADER_VALUE_LENGTH).refine(
|
|
1818
1825
|
(value) => !isUnsafeHeaderValue(value),
|
|
1819
1826
|
"header values may not contain line breaks, control characters, or characters beyond Latin-1"
|
|
@@ -1836,6 +1843,8 @@ var exportDestinationSchema = z13.strictObject({
|
|
|
1836
1843
|
tracesEndpoint: endpointSchema.optional(),
|
|
1837
1844
|
/** Per-signal override of the derived logs URL. */
|
|
1838
1845
|
logsEndpoint: endpointSchema.optional(),
|
|
1846
|
+
/** Per-signal override of the derived metrics URL (`/v1/traces` becomes `/v1/metrics`). */
|
|
1847
|
+
metricsEndpoint: endpointSchema.optional(),
|
|
1839
1848
|
/** Defaults to `exporter.protocol`. */
|
|
1840
1849
|
protocol: z13.enum(["http/protobuf", "http/json", "none"]).optional(),
|
|
1841
1850
|
/**
|
|
@@ -1848,15 +1857,17 @@ var exportDestinationSchema = z13.strictObject({
|
|
|
1848
1857
|
`at most ${String(MAX_DESTINATION_HEADERS)} headers per destination`
|
|
1849
1858
|
).optional(),
|
|
1850
1859
|
/**
|
|
1851
|
-
* Which signals this destination receives. Default:
|
|
1852
|
-
* still governed by `exporter.logs.enabled`, which stays the one
|
|
1853
|
-
*
|
|
1860
|
+
* Which signals this destination receives. Default: traces and logs. The logs
|
|
1861
|
+
* signal is still governed by `exporter.logs.enabled`, which stays the one
|
|
1862
|
+
* opt-in for content-bearing records leaving the host. `metrics` is never on by
|
|
1863
|
+
* default: a destination receives hook-derived metrics only when it lists them.
|
|
1854
1864
|
*/
|
|
1855
|
-
signals: z13.array(exportSignalSchema).min(1).max(
|
|
1865
|
+
signals: z13.array(exportSignalSchema).min(1).max(3).readonly().optional()
|
|
1856
1866
|
}).refine(
|
|
1857
|
-
(destination) => destination.endpoint !== void 0 || destination.tracesEndpoint !== void 0 || destination.logsEndpoint !== void 0,
|
|
1858
|
-
"a destination needs an endpoint, or a tracesEndpoint / logsEndpoint"
|
|
1867
|
+
(destination) => destination.endpoint !== void 0 || destination.tracesEndpoint !== void 0 || destination.logsEndpoint !== void 0 || destination.metricsEndpoint !== void 0,
|
|
1868
|
+
"a destination needs an endpoint, or a tracesEndpoint / logsEndpoint / metricsEndpoint"
|
|
1859
1869
|
);
|
|
1870
|
+
var DEFAULT_DESTINATION_SIGNALS = Object.freeze(["traces", "logs"]);
|
|
1860
1871
|
var exportDestinationsSchema = z13.array(exportDestinationSchema).max(MAX_EXPORT_DESTINATIONS).readonly().superRefine((destinations, context) => {
|
|
1861
1872
|
const seen = /* @__PURE__ */ new Set();
|
|
1862
1873
|
destinations.forEach((destination, index) => {
|
|
@@ -1901,7 +1912,8 @@ var legacyDestination = (exporter) => ({
|
|
|
1901
1912
|
protocol: exporter.protocol,
|
|
1902
1913
|
...exporter.endpoint === void 0 ? {} : { endpoint: exporter.endpoint },
|
|
1903
1914
|
...exporter.logs.endpoint === void 0 ? {} : { logsEndpoint: exporter.logs.endpoint },
|
|
1904
|
-
|
|
1915
|
+
...exporter.metrics?.endpoint === void 0 ? {} : { metricsEndpoint: exporter.metrics.endpoint },
|
|
1916
|
+
signals: { traces: true, logs: exporter.logs.enabled, metrics: exporter.metrics?.enabled === true },
|
|
1905
1917
|
headers: {}
|
|
1906
1918
|
});
|
|
1907
1919
|
var hasConfiguredDestinations = (exporter) => exporter.destinations !== void 0 && exporter.destinations.length > 0;
|
|
@@ -1910,14 +1922,14 @@ var resolveExportDestinations = (exporter) => {
|
|
|
1910
1922
|
return [legacyDestination(exporter)];
|
|
1911
1923
|
}
|
|
1912
1924
|
const resolved = [];
|
|
1913
|
-
if (exporter.endpoint !== void 0 || exporter.logs.endpoint !== void 0) {
|
|
1925
|
+
if (exporter.endpoint !== void 0 || exporter.logs.endpoint !== void 0 || exporter.metrics?.endpoint !== void 0) {
|
|
1914
1926
|
resolved.push(legacyDestination(exporter));
|
|
1915
1927
|
}
|
|
1916
1928
|
for (const destination of exporter.destinations ?? []) {
|
|
1917
1929
|
if (destination.enabled === false) {
|
|
1918
1930
|
continue;
|
|
1919
1931
|
}
|
|
1920
|
-
const signals = destination.signals ??
|
|
1932
|
+
const signals = destination.signals ?? DEFAULT_DESTINATION_SIGNALS;
|
|
1921
1933
|
resolved.push({
|
|
1922
1934
|
name: destination.name,
|
|
1923
1935
|
source: "destinations",
|
|
@@ -1925,9 +1937,11 @@ var resolveExportDestinations = (exporter) => {
|
|
|
1925
1937
|
...destination.endpoint === void 0 ? {} : { endpoint: destination.endpoint },
|
|
1926
1938
|
...destination.tracesEndpoint === void 0 ? {} : { tracesEndpoint: destination.tracesEndpoint },
|
|
1927
1939
|
...destination.logsEndpoint === void 0 ? {} : { logsEndpoint: destination.logsEndpoint },
|
|
1940
|
+
...destination.metricsEndpoint === void 0 ? {} : { metricsEndpoint: destination.metricsEndpoint },
|
|
1928
1941
|
signals: {
|
|
1929
1942
|
traces: signals.includes("traces"),
|
|
1930
|
-
logs: exporter.logs.enabled && signals.includes("logs")
|
|
1943
|
+
logs: exporter.logs.enabled && signals.includes("logs"),
|
|
1944
|
+
metrics: signals.includes("metrics")
|
|
1931
1945
|
},
|
|
1932
1946
|
headers: { ...destination.headers ?? {} }
|
|
1933
1947
|
});
|
|
@@ -1969,6 +1983,9 @@ var describeExportDestinations = (exporter) => {
|
|
|
1969
1983
|
const logsOrigin = endpointOrigin(
|
|
1970
1984
|
destination.logsEndpoint ?? destination.endpoint ?? destination.tracesEndpoint
|
|
1971
1985
|
);
|
|
1986
|
+
const metricsOrigin = endpointOrigin(
|
|
1987
|
+
destination.metricsEndpoint ?? destination.endpoint ?? destination.tracesEndpoint
|
|
1988
|
+
);
|
|
1972
1989
|
const variables = Object.values(destination.headers).map(parseHeaderValueReference).flatMap((reference) => reference.kind === "env" ? [reference.variable] : []);
|
|
1973
1990
|
return {
|
|
1974
1991
|
name: destination.name,
|
|
@@ -1977,6 +1994,7 @@ var describeExportDestinations = (exporter) => {
|
|
|
1977
1994
|
signals: exportSignalSchema.options.filter((signal) => destination.signals[signal]),
|
|
1978
1995
|
...tracesOrigin === void 0 || !destination.signals.traces ? {} : { tracesEndpointOrigin: tracesOrigin },
|
|
1979
1996
|
...logsOrigin === void 0 || !destination.signals.logs ? {} : { logsEndpointOrigin: logsOrigin },
|
|
1997
|
+
...metricsOrigin === void 0 || !destination.signals.metrics ? {} : { metricsEndpointOrigin: metricsOrigin },
|
|
1980
1998
|
headerNames: destination.source === "exporter" ? [...exporter.headerNames].sort() : Object.keys(destination.headers).sort(),
|
|
1981
1999
|
headerVariables: [...new Set(variables)].sort()
|
|
1982
2000
|
};
|
|
@@ -1991,7 +2009,7 @@ var describeExportDestinations = (exporter) => {
|
|
|
1991
2009
|
source: "destinations",
|
|
1992
2010
|
protocol: destination.protocol ?? exporter.protocol,
|
|
1993
2011
|
...destination.endpoint === void 0 ? {} : { endpoint: destination.endpoint },
|
|
1994
|
-
signals: { traces: false, logs: false },
|
|
2012
|
+
signals: { traces: false, logs: false, metrics: false },
|
|
1995
2013
|
headers: { ...destination.headers ?? {} }
|
|
1996
2014
|
},
|
|
1997
2015
|
false
|
|
@@ -2018,6 +2036,18 @@ var DEFAULT_LOGS_POLICY = Object.freeze({
|
|
|
2018
2036
|
includeContent: false,
|
|
2019
2037
|
maxBatchSize: 128
|
|
2020
2038
|
});
|
|
2039
|
+
var metricsPolicySchema = z14.strictObject({
|
|
2040
|
+
enabled: z14.boolean(),
|
|
2041
|
+
/** Full URL. Absent, derived from `endpoint` (`/v1/traces` becomes `/v1/metrics`). */
|
|
2042
|
+
endpoint: z14.string().url().max(2048).optional(),
|
|
2043
|
+
temporality: z14.enum(["cumulative", "delta"]),
|
|
2044
|
+
includeSessionId: z14.boolean()
|
|
2045
|
+
});
|
|
2046
|
+
var DEFAULT_METRICS_POLICY = Object.freeze({
|
|
2047
|
+
enabled: false,
|
|
2048
|
+
temporality: "cumulative",
|
|
2049
|
+
includeSessionId: true
|
|
2050
|
+
});
|
|
2021
2051
|
var exporterPolicySchema = z14.strictObject({
|
|
2022
2052
|
enabled: z14.boolean(),
|
|
2023
2053
|
protocol: z14.enum(["http/protobuf", "http/json", "none"]),
|
|
@@ -2048,6 +2078,11 @@ var exporterPolicySchema = z14.strictObject({
|
|
|
2048
2078
|
* a second top-level section would invite two of each to drift apart.
|
|
2049
2079
|
*/
|
|
2050
2080
|
logs: logsPolicySchema,
|
|
2081
|
+
/**
|
|
2082
|
+
* Hook-derived metrics. Optional so an `ExporterPolicy` built by hand before
|
|
2083
|
+
* metrics existed stays valid; absent reads as {@link DEFAULT_METRICS_POLICY}.
|
|
2084
|
+
*/
|
|
2085
|
+
metrics: metricsPolicySchema.optional(),
|
|
2051
2086
|
/**
|
|
2052
2087
|
* Additional OTLP destinations, each sent every batch in parallel.
|
|
2053
2088
|
*
|
|
@@ -2079,23 +2114,34 @@ var diagnosticsPolicySchema = z14.strictObject({
|
|
|
2079
2114
|
/** Emit `error.raised` events for contained failures. */
|
|
2080
2115
|
emitErrorEvents: z14.boolean()
|
|
2081
2116
|
});
|
|
2117
|
+
var providersPolicySchema = z14.strictObject({
|
|
2118
|
+
claudeCode: z14.strictObject({
|
|
2119
|
+
readTranscriptUsage: z14.boolean()
|
|
2120
|
+
}).optional()
|
|
2121
|
+
});
|
|
2082
2122
|
var otelHookConfigSchema = z14.strictObject({
|
|
2083
2123
|
exporter: exporterPolicySchema,
|
|
2084
2124
|
privacy: privacyPolicySchema,
|
|
2085
2125
|
detection: detectionPolicySchema,
|
|
2086
|
-
diagnostics: diagnosticsPolicySchema
|
|
2126
|
+
diagnostics: diagnosticsPolicySchema,
|
|
2127
|
+
/** Optional so a hand-built configuration from before it existed stays valid. */
|
|
2128
|
+
providers: providersPolicySchema.optional()
|
|
2087
2129
|
});
|
|
2088
2130
|
var otelHookConfigPatchSchema = z14.strictObject({
|
|
2089
2131
|
// `logs` is unwrapped and re-partialled for the same reason `privacy.limits` is:
|
|
2090
2132
|
// merging happens per leaf, so a layer must be able to set `logs.enabled` alone
|
|
2091
2133
|
// without also restating the endpoint and the batch size.
|
|
2092
|
-
exporter: exporterPolicySchema.omit({ logs: true, spool: true }).partial().extend({
|
|
2134
|
+
exporter: exporterPolicySchema.omit({ logs: true, metrics: true, spool: true }).partial().extend({
|
|
2093
2135
|
logs: logsPolicySchema.partial().optional(),
|
|
2136
|
+
metrics: metricsPolicySchema.partial().optional(),
|
|
2094
2137
|
spool: spoolPolicySchema.partial().optional()
|
|
2095
2138
|
}).optional(),
|
|
2096
2139
|
privacy: privacyPolicySchema.omit({ limits: true }).partial().extend({ limits: privacyPolicySchema.shape.limits.partial().optional() }).optional(),
|
|
2097
2140
|
detection: detectionPolicySchema.partial().optional(),
|
|
2098
|
-
diagnostics: diagnosticsPolicySchema.partial().optional()
|
|
2141
|
+
diagnostics: diagnosticsPolicySchema.partial().optional(),
|
|
2142
|
+
providers: z14.strictObject({
|
|
2143
|
+
claudeCode: z14.strictObject({ readTranscriptUsage: z14.boolean() }).partial().optional()
|
|
2144
|
+
}).partial().optional()
|
|
2099
2145
|
});
|
|
2100
2146
|
var DEFAULT_EXPORTER_POLICY = Object.freeze({
|
|
2101
2147
|
enabled: true,
|
|
@@ -2107,7 +2153,8 @@ var DEFAULT_EXPORTER_POLICY = Object.freeze({
|
|
|
2107
2153
|
maxRetryAttempts: 2,
|
|
2108
2154
|
serviceName: "coding-agent",
|
|
2109
2155
|
resourceAttributes: EMPTY_RESOURCE_ATTRIBUTES,
|
|
2110
|
-
logs: DEFAULT_LOGS_POLICY
|
|
2156
|
+
logs: DEFAULT_LOGS_POLICY,
|
|
2157
|
+
metrics: DEFAULT_METRICS_POLICY
|
|
2111
2158
|
});
|
|
2112
2159
|
var DEFAULT_DETECTION_POLICY = Object.freeze({
|
|
2113
2160
|
minimumConfidence: "strong",
|
|
@@ -2118,11 +2165,20 @@ var DEFAULT_DIAGNOSTICS_POLICY = Object.freeze({
|
|
|
2118
2165
|
logLevel: "warn",
|
|
2119
2166
|
emitErrorEvents: true
|
|
2120
2167
|
});
|
|
2168
|
+
var DEFAULT_PROVIDERS_POLICY = Object.freeze({
|
|
2169
|
+
claudeCode: Object.freeze({ readTranscriptUsage: false })
|
|
2170
|
+
});
|
|
2121
2171
|
var DEFAULT_CONFIG = Object.freeze({
|
|
2122
2172
|
exporter: DEFAULT_EXPORTER_POLICY,
|
|
2123
2173
|
privacy: DEFAULT_PRIVACY_POLICY,
|
|
2124
2174
|
detection: DEFAULT_DETECTION_POLICY,
|
|
2125
|
-
diagnostics: DEFAULT_DIAGNOSTICS_POLICY
|
|
2175
|
+
diagnostics: DEFAULT_DIAGNOSTICS_POLICY,
|
|
2176
|
+
providers: DEFAULT_PROVIDERS_POLICY
|
|
2177
|
+
});
|
|
2178
|
+
var readsClaudeTranscriptUsage = (config) => config.providers?.claudeCode?.readTranscriptUsage === true;
|
|
2179
|
+
var effectiveMetricsPolicy = (exporter) => ({
|
|
2180
|
+
...DEFAULT_METRICS_POLICY,
|
|
2181
|
+
...exporter.metrics ?? {}
|
|
2126
2182
|
});
|
|
2127
2183
|
|
|
2128
2184
|
// src/config/resolve.ts
|
|
@@ -2130,12 +2186,12 @@ import { z as z15 } from "zod";
|
|
|
2130
2186
|
var CONFIG_SOURCE_PRECEDENCE = ["defaults", "file", "environment", "inline-override"];
|
|
2131
2187
|
var configSourceSchema = z15.enum(CONFIG_SOURCE_PRECEDENCE);
|
|
2132
2188
|
var isPlainObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
2133
|
-
var mergeLeaf = (target, patch, source, provenance,
|
|
2189
|
+
var mergeLeaf = (target, patch, source, provenance, path10) => {
|
|
2134
2190
|
for (const [key, value] of Object.entries(patch)) {
|
|
2135
2191
|
if (value === void 0) {
|
|
2136
2192
|
continue;
|
|
2137
2193
|
}
|
|
2138
|
-
const childPath =
|
|
2194
|
+
const childPath = path10 === "" ? key : `${path10}.${key}`;
|
|
2139
2195
|
const existing = target[key];
|
|
2140
2196
|
if (isPlainObject(value) && (isPlainObject(existing) || existing === void 0)) {
|
|
2141
2197
|
const child = { ...existing ?? {} };
|
|
@@ -2149,14 +2205,14 @@ var mergeLeaf = (target, patch, source, provenance, path9) => {
|
|
|
2149
2205
|
};
|
|
2150
2206
|
var initialProvenance = (config) => {
|
|
2151
2207
|
const provenance = {};
|
|
2152
|
-
const walk = (value,
|
|
2208
|
+
const walk = (value, path10) => {
|
|
2153
2209
|
if (isPlainObject(value)) {
|
|
2154
2210
|
for (const [key, child] of Object.entries(value)) {
|
|
2155
|
-
walk(child,
|
|
2211
|
+
walk(child, path10 === "" ? key : `${path10}.${key}`);
|
|
2156
2212
|
}
|
|
2157
2213
|
return;
|
|
2158
2214
|
}
|
|
2159
|
-
provenance[
|
|
2215
|
+
provenance[path10] = "defaults";
|
|
2160
2216
|
};
|
|
2161
2217
|
walk(config, "");
|
|
2162
2218
|
return provenance;
|
|
@@ -2235,6 +2291,11 @@ var resolveConfig = (layers = []) => {
|
|
|
2235
2291
|
"exporter.logs.enabled is true but neither a logs endpoint nor a trace endpoint to derive one from is configured"
|
|
2236
2292
|
);
|
|
2237
2293
|
}
|
|
2294
|
+
if (!withDestinations && parsed.data.exporter.metrics?.enabled === true && parsed.data.exporter.metrics.endpoint === void 0 && parsed.data.exporter.endpoint === void 0) {
|
|
2295
|
+
notes.push(
|
|
2296
|
+
"exporter.metrics.enabled is true but neither a metrics endpoint nor a trace endpoint to derive one from is configured"
|
|
2297
|
+
);
|
|
2298
|
+
}
|
|
2238
2299
|
if (parsed.data.exporter.logs.includeContent && parsed.data.privacy.contentMode === "omit") {
|
|
2239
2300
|
notes.push(
|
|
2240
2301
|
"exporter.logs.includeContent is true but privacy.contentMode is omit, so no content is disclosed to describe"
|
|
@@ -2266,6 +2327,9 @@ var describeDestinationAttributes = (config) => {
|
|
|
2266
2327
|
if (destination.logsEndpointOrigin !== void 0) {
|
|
2267
2328
|
attributes[`${prefix}.logs_endpoint_origin`] = destination.logsEndpointOrigin;
|
|
2268
2329
|
}
|
|
2330
|
+
if (destination.metricsEndpointOrigin !== void 0) {
|
|
2331
|
+
attributes[`${prefix}.metrics_endpoint_origin`] = destination.metricsEndpointOrigin;
|
|
2332
|
+
}
|
|
2269
2333
|
attributes[`${prefix}.header_names`] = [...destination.headerNames];
|
|
2270
2334
|
attributes[`${prefix}.header_variables`] = [...destination.headerVariables];
|
|
2271
2335
|
}
|
|
@@ -2284,6 +2348,8 @@ var describeResolvedConfig = (config) => {
|
|
|
2284
2348
|
};
|
|
2285
2349
|
const endpointOrigin2 = originOf(config.exporter.endpoint);
|
|
2286
2350
|
const logsEndpointOrigin = originOf(config.exporter.logs.endpoint);
|
|
2351
|
+
const metrics = effectiveMetricsPolicy(config.exporter);
|
|
2352
|
+
const metricsEndpointOrigin = originOf(metrics.endpoint);
|
|
2287
2353
|
return {
|
|
2288
2354
|
"exporter.enabled": config.exporter.enabled,
|
|
2289
2355
|
"exporter.protocol": config.exporter.protocol,
|
|
@@ -2292,6 +2358,10 @@ var describeResolvedConfig = (config) => {
|
|
|
2292
2358
|
"exporter.logs_include_content": config.exporter.logs.includeContent,
|
|
2293
2359
|
"exporter.logs_max_batch_size": config.exporter.logs.maxBatchSize,
|
|
2294
2360
|
...logsEndpointOrigin === void 0 ? {} : { "exporter.logs_endpoint_origin": logsEndpointOrigin },
|
|
2361
|
+
"exporter.metrics_enabled": metrics.enabled,
|
|
2362
|
+
"exporter.metrics_temporality": metrics.temporality,
|
|
2363
|
+
"exporter.metrics_include_session_id": metrics.includeSessionId,
|
|
2364
|
+
...metricsEndpointOrigin === void 0 ? {} : { "exporter.metrics_endpoint_origin": metricsEndpointOrigin },
|
|
2295
2365
|
"exporter.header_names": [...config.exporter.headerNames],
|
|
2296
2366
|
// Names only. A resource attribute *name* is already on the wire in every
|
|
2297
2367
|
// exported resource, so disclosing it here adds nothing; a *value* may hold
|
|
@@ -2321,10 +2391,17 @@ var describeResolvedConfig = (config) => {
|
|
|
2321
2391
|
var OTLP_ENDPOINT_VARIABLES = Object.freeze({
|
|
2322
2392
|
generic: "OTEL_EXPORTER_OTLP_ENDPOINT",
|
|
2323
2393
|
traces: "OTEL_EXPORTER_OTLP_TRACES_ENDPOINT",
|
|
2324
|
-
logs: "OTEL_EXPORTER_OTLP_LOGS_ENDPOINT"
|
|
2394
|
+
logs: "OTEL_EXPORTER_OTLP_LOGS_ENDPOINT",
|
|
2395
|
+
metrics: "OTEL_EXPORTER_OTLP_METRICS_ENDPOINT"
|
|
2325
2396
|
});
|
|
2326
2397
|
var OTLP_TRACES_PATH = "/v1/traces";
|
|
2327
2398
|
var OTLP_LOGS_PATH = "/v1/logs";
|
|
2399
|
+
var OTLP_METRICS_PATH = "/v1/metrics";
|
|
2400
|
+
var SIGNAL_PATHS = Object.freeze({
|
|
2401
|
+
traces: OTLP_TRACES_PATH,
|
|
2402
|
+
logs: OTLP_LOGS_PATH,
|
|
2403
|
+
metrics: OTLP_METRICS_PATH
|
|
2404
|
+
});
|
|
2328
2405
|
var withoutTrailingSlashes = (value) => {
|
|
2329
2406
|
let end = value.length;
|
|
2330
2407
|
while (end > 0 && value.charCodeAt(end - 1) === 47) {
|
|
@@ -2335,9 +2412,20 @@ var withoutTrailingSlashes = (value) => {
|
|
|
2335
2412
|
var otlpSignalEndpointFromBase = (base, signal) => {
|
|
2336
2413
|
const trimmed = withoutTrailingSlashes(base);
|
|
2337
2414
|
if (trimmed.endsWith(OTLP_TRACES_PATH)) {
|
|
2338
|
-
return signal === "traces" ? trimmed : `${trimmed.slice(0, trimmed.length - OTLP_TRACES_PATH.length)}${
|
|
2415
|
+
return signal === "traces" ? trimmed : `${trimmed.slice(0, trimmed.length - OTLP_TRACES_PATH.length)}${SIGNAL_PATHS[signal]}`;
|
|
2416
|
+
}
|
|
2417
|
+
return `${trimmed}${SIGNAL_PATHS[signal]}`;
|
|
2418
|
+
};
|
|
2419
|
+
var siblingSignalEndpoint = (tracesEndpoint, signal) => {
|
|
2420
|
+
const trimmed = withoutTrailingSlashes(tracesEndpoint);
|
|
2421
|
+
const target = SIGNAL_PATHS[signal];
|
|
2422
|
+
if (trimmed.endsWith(target)) {
|
|
2423
|
+
return trimmed;
|
|
2424
|
+
}
|
|
2425
|
+
if (trimmed.endsWith(OTLP_TRACES_PATH)) {
|
|
2426
|
+
return `${trimmed.slice(0, trimmed.length - OTLP_TRACES_PATH.length)}${target}`;
|
|
2339
2427
|
}
|
|
2340
|
-
return `${trimmed}${
|
|
2428
|
+
return `${trimmed}${target}`;
|
|
2341
2429
|
};
|
|
2342
2430
|
|
|
2343
2431
|
// src/config/environment.ts
|
|
@@ -2358,6 +2446,12 @@ var ENVIRONMENT_VARIABLES = Object.freeze({
|
|
|
2358
2446
|
/** Standard per-signal endpoint; the weaker source of the two. */
|
|
2359
2447
|
otlpLogsEndpoint: "OTEL_EXPORTER_OTLP_LOGS_ENDPOINT",
|
|
2360
2448
|
logsIncludeContent: "OTEL_HOOK_LOGS_INCLUDE_CONTENT",
|
|
2449
|
+
metricsEnabled: "OTEL_HOOK_METRICS_ENABLED",
|
|
2450
|
+
metricsEndpoint: "OTEL_HOOK_METRICS_ENDPOINT",
|
|
2451
|
+
/** Standard per-signal endpoint; the weaker source of the two. */
|
|
2452
|
+
otlpMetricsEndpoint: "OTEL_EXPORTER_OTLP_METRICS_ENDPOINT",
|
|
2453
|
+
/** Standard: `cumulative`, `delta`, or `lowmemory` (read as `delta` here). */
|
|
2454
|
+
otlpMetricsTemporality: "OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE",
|
|
2361
2455
|
serviceName: "OTEL_HOOK_SERVICE_NAME",
|
|
2362
2456
|
otlpServiceName: "OTEL_SERVICE_NAME",
|
|
2363
2457
|
serviceNamespace: "OTEL_HOOK_SERVICE_NAMESPACE",
|
|
@@ -2371,7 +2465,9 @@ var ENVIRONMENT_VARIABLES = Object.freeze({
|
|
|
2371
2465
|
maxArrayLength: "OTEL_HOOK_MAX_ARRAY_LENGTH",
|
|
2372
2466
|
maxEventsPerInvocation: "OTEL_HOOK_MAX_EVENTS_PER_INVOCATION",
|
|
2373
2467
|
minimumConfidence: "OTEL_HOOK_MIN_DETECTION_CONFIDENCE",
|
|
2374
|
-
logLevel: "OTEL_HOOK_LOG_LEVEL"
|
|
2468
|
+
logLevel: "OTEL_HOOK_LOG_LEVEL",
|
|
2469
|
+
/** `providers.claudeCode.readTranscriptUsage`; see `providersPolicySchema`. */
|
|
2470
|
+
claudeTranscriptUsage: "OTEL_HOOK_CLAUDE_TRANSCRIPT_USAGE"
|
|
2375
2471
|
});
|
|
2376
2472
|
var BOOLEAN_TRUE = /* @__PURE__ */ new Set(["1", "true", "yes", "on"]);
|
|
2377
2473
|
var BOOLEAN_FALSE = /* @__PURE__ */ new Set(["0", "false", "no", "off"]);
|
|
@@ -2518,6 +2614,22 @@ var parseEnvironmentConfig = (env) => {
|
|
|
2518
2614
|
...logsEndpoint === void 0 ? {} : { endpoint: logsEndpoint },
|
|
2519
2615
|
...logsIncludeContent === void 0 ? {} : { includeContent: logsIncludeContent }
|
|
2520
2616
|
};
|
|
2617
|
+
const metricsEnabled = readBoolean(ENVIRONMENT_VARIABLES.metricsEnabled);
|
|
2618
|
+
const metricsEndpoint = readString(ENVIRONMENT_VARIABLES.metricsEndpoint) ?? readString(ENVIRONMENT_VARIABLES.otlpMetricsEndpoint) ?? (hookEndpoint === void 0 && otlpTracesEndpoint !== void 0 && otlpBaseEndpoint !== void 0 ? otlpSignalEndpointFromBase(otlpBaseEndpoint, "metrics") : void 0);
|
|
2619
|
+
const temporalityRaw = readString(ENVIRONMENT_VARIABLES.otlpMetricsTemporality)?.toLowerCase();
|
|
2620
|
+
let metricsTemporality;
|
|
2621
|
+
if (temporalityRaw === "cumulative") {
|
|
2622
|
+
metricsTemporality = "cumulative";
|
|
2623
|
+
} else if (temporalityRaw === "delta" || temporalityRaw === "lowmemory") {
|
|
2624
|
+
metricsTemporality = "delta";
|
|
2625
|
+
} else if (temporalityRaw !== void 0) {
|
|
2626
|
+
warn(ENVIRONMENT_VARIABLES.otlpMetricsTemporality, "expected cumulative, delta, or lowmemory");
|
|
2627
|
+
}
|
|
2628
|
+
const metrics = {
|
|
2629
|
+
...metricsEnabled === void 0 ? {} : { enabled: metricsEnabled },
|
|
2630
|
+
...metricsEndpoint === void 0 ? {} : { endpoint: metricsEndpoint },
|
|
2631
|
+
...metricsTemporality === void 0 ? {} : { temporality: metricsTemporality }
|
|
2632
|
+
};
|
|
2521
2633
|
const otlpHeaders = resolveOtlpHeaders(env);
|
|
2522
2634
|
for (const { variable, detail } of otlpHeaders.warnings) {
|
|
2523
2635
|
warn(variable, detail);
|
|
@@ -2532,7 +2644,8 @@ var parseEnvironmentConfig = (env) => {
|
|
|
2532
2644
|
...serviceName === void 0 ? {} : { serviceName },
|
|
2533
2645
|
...serviceNamespace === void 0 ? {} : { serviceNamespace },
|
|
2534
2646
|
...Object.keys(resourceAttributes).length === 0 ? {} : { resourceAttributes },
|
|
2535
|
-
...Object.keys(logs).length === 0 ? {} : { logs }
|
|
2647
|
+
...Object.keys(logs).length === 0 ? {} : { logs },
|
|
2648
|
+
...Object.keys(metrics).length === 0 ? {} : { metrics }
|
|
2536
2649
|
};
|
|
2537
2650
|
const limits = {
|
|
2538
2651
|
...maxStringLength === void 0 ? {} : { maxStringLength },
|
|
@@ -2548,11 +2661,14 @@ var parseEnvironmentConfig = (env) => {
|
|
|
2548
2661
|
};
|
|
2549
2662
|
const detection = confidenceParsed?.success === true ? { minimumConfidence: confidenceParsed.data } : {};
|
|
2550
2663
|
const diagnostics = logLevel === void 0 ? {} : { logLevel };
|
|
2664
|
+
const claudeTranscriptUsage = readBoolean(ENVIRONMENT_VARIABLES.claudeTranscriptUsage);
|
|
2665
|
+
const providers = claudeTranscriptUsage === void 0 ? {} : { claudeCode: { readTranscriptUsage: claudeTranscriptUsage } };
|
|
2551
2666
|
const patch = {
|
|
2552
2667
|
...Object.keys(exporter).length === 0 ? {} : { exporter },
|
|
2553
2668
|
...Object.keys(privacy).length === 0 ? {} : { privacy },
|
|
2554
2669
|
...Object.keys(detection).length === 0 ? {} : { detection },
|
|
2555
|
-
...Object.keys(diagnostics).length === 0 ? {} : { diagnostics }
|
|
2670
|
+
...Object.keys(diagnostics).length === 0 ? {} : { diagnostics },
|
|
2671
|
+
...Object.keys(providers).length === 0 ? {} : { providers }
|
|
2556
2672
|
};
|
|
2557
2673
|
return { patch, warnings };
|
|
2558
2674
|
};
|
|
@@ -3073,7 +3189,25 @@ var stopPayloadSchema = z17.object({
|
|
|
3073
3189
|
* the former without suppressing the latter.
|
|
3074
3190
|
*/
|
|
3075
3191
|
stop_hook_active: z17.boolean().optional(),
|
|
3076
|
-
usage: claudeUsageSchema.optional()
|
|
3192
|
+
usage: claudeUsageSchema.optional(),
|
|
3193
|
+
/**
|
|
3194
|
+
* The model that answered this turn — harness-supplied, never upstream.
|
|
3195
|
+
*
|
|
3196
|
+
* Claude Code's `Stop` carries no model id; the per-turn model sits only at
|
|
3197
|
+
* `message.model` in the transcript, beside `message.usage`. A wrapping harness
|
|
3198
|
+
* that read it (for instance with `readClaudeTranscriptTurn`) attaches it here
|
|
3199
|
+
* with `usage`, and it becomes the generation's response model. An unusable
|
|
3200
|
+
* value (empty, over 256 characters, not a string) is dropped rather than
|
|
3201
|
+
* failing the whole payload: the turn is still worth reporting without it.
|
|
3202
|
+
*/
|
|
3203
|
+
model: z17.string().min(1).max(256).optional().catch(void 0),
|
|
3204
|
+
/**
|
|
3205
|
+
* Harness-supplied, never upstream: whether `usage` covers only part of the
|
|
3206
|
+
* turn. `true` when it is the last model request alone (the tail fallback),
|
|
3207
|
+
* `false` when it sums every request since the previous stop. Exported as
|
|
3208
|
+
* `otelhook.usage.partial`; absent means the attacher did not say.
|
|
3209
|
+
*/
|
|
3210
|
+
usage_partial: z17.boolean().optional().catch(void 0)
|
|
3077
3211
|
});
|
|
3078
3212
|
var stopFailurePayloadSchema = z17.object({
|
|
3079
3213
|
...commonFields,
|
|
@@ -3085,7 +3219,11 @@ var stopFailurePayloadSchema = z17.object({
|
|
|
3085
3219
|
*/
|
|
3086
3220
|
error_type: z17.string().min(1),
|
|
3087
3221
|
error_message: z17.string().optional(),
|
|
3088
|
-
usage: claudeUsageSchema.optional()
|
|
3222
|
+
usage: claudeUsageSchema.optional(),
|
|
3223
|
+
/** Harness-supplied, never upstream: see `stopPayloadSchema.model`. */
|
|
3224
|
+
model: z17.string().min(1).max(256).optional().catch(void 0),
|
|
3225
|
+
/** Harness-supplied, never upstream: see `stopPayloadSchema.usage_partial`. */
|
|
3226
|
+
usage_partial: z17.boolean().optional().catch(void 0)
|
|
3089
3227
|
});
|
|
3090
3228
|
var claudeHookPayloadSchema = z17.discriminatedUnion("hook_event_name", [
|
|
3091
3229
|
sessionStartPayloadSchema,
|
|
@@ -3617,6 +3755,13 @@ var inferToolKind = (toolName) => {
|
|
|
3617
3755
|
|
|
3618
3756
|
// src/providers/claude/events.ts
|
|
3619
3757
|
var UNKNOWN_MODEL = { modelId: "unknown" };
|
|
3758
|
+
var generationModels = (attached, sessionModel) => {
|
|
3759
|
+
const turnModel = attached === void 0 ? void 0 : { modelId: attached };
|
|
3760
|
+
return {
|
|
3761
|
+
request: sessionModel ?? turnModel ?? UNKNOWN_MODEL,
|
|
3762
|
+
response: turnModel ?? sessionModel ?? UNKNOWN_MODEL
|
|
3763
|
+
};
|
|
3764
|
+
};
|
|
3620
3765
|
var SESSION_END_REASON = Object.freeze({
|
|
3621
3766
|
completed: "completed",
|
|
3622
3767
|
aborted: "aborted",
|
|
@@ -3683,6 +3828,10 @@ var parseClaudeCode = (input, context) => {
|
|
|
3683
3828
|
warnings.push(...normalized.warnings);
|
|
3684
3829
|
return applyUsage(normalized);
|
|
3685
3830
|
};
|
|
3831
|
+
const withPartialUsage = (usage, partial) => {
|
|
3832
|
+
const applied = withUsage(usage);
|
|
3833
|
+
return applied.usage === void 0 || partial === void 0 ? applied : { ...applied, usagePartial: partial };
|
|
3834
|
+
};
|
|
3686
3835
|
switch (payload.hook_event_name) {
|
|
3687
3836
|
case "SessionStart":
|
|
3688
3837
|
factory.build({
|
|
@@ -3795,11 +3944,12 @@ var parseClaudeCode = (input, context) => {
|
|
|
3795
3944
|
payload.prompt_id ?? String(input.sequenceBase)
|
|
3796
3945
|
]);
|
|
3797
3946
|
const assistantText = extractClaudeAssistantText(normalizedPayload);
|
|
3798
|
-
|
|
3947
|
+
const models = generationModels(payload.model, input.sessionModel);
|
|
3948
|
+
factory.build({ type: "generation.start", generationId, model: models.request });
|
|
3799
3949
|
factory.build({
|
|
3800
3950
|
type: "generation.end",
|
|
3801
3951
|
generationId,
|
|
3802
|
-
model:
|
|
3952
|
+
model: models.response,
|
|
3803
3953
|
outcome: "ok",
|
|
3804
3954
|
// Always a response fact: a body when Claude sent text, otherwise a
|
|
3805
3955
|
// zero-length omitted fact so the log mapping can emit metadata_only
|
|
@@ -3811,7 +3961,7 @@ var parseClaudeCode = (input, context) => {
|
|
|
3811
3961
|
text: assistantText
|
|
3812
3962
|
})
|
|
3813
3963
|
],
|
|
3814
|
-
...
|
|
3964
|
+
...withPartialUsage(extractedUsage ?? payload.usage, payload.usage_partial)
|
|
3815
3965
|
});
|
|
3816
3966
|
break;
|
|
3817
3967
|
}
|
|
@@ -3822,11 +3972,12 @@ var parseClaudeCode = (input, context) => {
|
|
|
3822
3972
|
payload.prompt_id ?? String(input.sequenceBase)
|
|
3823
3973
|
]);
|
|
3824
3974
|
const assistantText = extractClaudeAssistantText(normalizedPayload);
|
|
3825
|
-
|
|
3975
|
+
const models = generationModels(payload.model, input.sessionModel);
|
|
3976
|
+
factory.build({ type: "generation.start", generationId, model: models.request });
|
|
3826
3977
|
factory.build({
|
|
3827
3978
|
type: "generation.end",
|
|
3828
3979
|
generationId,
|
|
3829
|
-
model:
|
|
3980
|
+
model: models.response,
|
|
3830
3981
|
outcome: mapStopFailureOutcome(payload.error_type),
|
|
3831
3982
|
stopReason: payload.error_type,
|
|
3832
3983
|
...assistantText === void 0 ? {} : {
|
|
@@ -3838,7 +3989,7 @@ var parseClaudeCode = (input, context) => {
|
|
|
3838
3989
|
})
|
|
3839
3990
|
]
|
|
3840
3991
|
},
|
|
3841
|
-
...
|
|
3992
|
+
...withPartialUsage(extractedUsage ?? payload.usage, payload.usage_partial)
|
|
3842
3993
|
});
|
|
3843
3994
|
break;
|
|
3844
3995
|
}
|
|
@@ -3865,6 +4016,339 @@ var createClaudeCodeAdapter = (options = {}) => ({
|
|
|
3865
4016
|
hookResponse: () => SILENT_HOOK_RESPONSE
|
|
3866
4017
|
});
|
|
3867
4018
|
|
|
4019
|
+
// src/providers/claude/transcript.ts
|
|
4020
|
+
import { createHash as createHash2 } from "crypto";
|
|
4021
|
+
import { open, stat } from "fs/promises";
|
|
4022
|
+
import path from "path";
|
|
4023
|
+
var DEFAULT_CLAUDE_TRANSCRIPT_TAIL_BYTES = 1048576;
|
|
4024
|
+
var DEFAULT_CLAUDE_TRANSCRIPT_TIMEOUT_MILLIS = 250;
|
|
4025
|
+
var DEFAULT_CLAUDE_TRANSCRIPT_RANGE_BYTES = 8388608;
|
|
4026
|
+
var DEFAULT_CLAUDE_TRANSCRIPT_RANGE_TIMEOUT_MILLIS = 500;
|
|
4027
|
+
var MIN_TAIL_BYTES = 65536;
|
|
4028
|
+
var MAX_TAIL_BYTES = 16777216;
|
|
4029
|
+
var MAX_RANGE_BYTES = 67108864;
|
|
4030
|
+
var MIN_TIMEOUT_MILLIS = 10;
|
|
4031
|
+
var MAX_TIMEOUT_MILLIS = 5e3;
|
|
4032
|
+
var MAX_MODEL_ID_LENGTH = 256;
|
|
4033
|
+
var MAX_REQUESTS_PER_RANGE = 1e4;
|
|
4034
|
+
var SYNTHETIC_MODEL = "<synthetic>";
|
|
4035
|
+
var TIMED_OUT = /* @__PURE__ */ Symbol("timed-out");
|
|
4036
|
+
var clamp = (value, fallback, min, max) => {
|
|
4037
|
+
if (value === void 0 || !Number.isFinite(value)) {
|
|
4038
|
+
return fallback;
|
|
4039
|
+
}
|
|
4040
|
+
return Math.min(max, Math.max(min, Math.floor(value)));
|
|
4041
|
+
};
|
|
4042
|
+
var asRecord5 = (value) => typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
|
|
4043
|
+
var isTranscriptPath = (transcriptPath) => typeof transcriptPath === "string" && transcriptPath.length > 0 && !transcriptPath.includes("\0") && path.isAbsolute(transcriptPath) && path.extname(transcriptPath) === ".jsonl";
|
|
4044
|
+
var assistantRecordOf = (line) => {
|
|
4045
|
+
if (!line.includes('"assistant"')) {
|
|
4046
|
+
return void 0;
|
|
4047
|
+
}
|
|
4048
|
+
let parsed;
|
|
4049
|
+
try {
|
|
4050
|
+
parsed = JSON.parse(line);
|
|
4051
|
+
} catch {
|
|
4052
|
+
return void 0;
|
|
4053
|
+
}
|
|
4054
|
+
const record = asRecord5(parsed);
|
|
4055
|
+
if (record === void 0 || record.type !== "assistant" || record.isSidechain === true) {
|
|
4056
|
+
return void 0;
|
|
4057
|
+
}
|
|
4058
|
+
const message = asRecord5(record.message);
|
|
4059
|
+
if (message === void 0 || message.model === SYNTHETIC_MODEL) {
|
|
4060
|
+
return void 0;
|
|
4061
|
+
}
|
|
4062
|
+
const model = typeof message.model === "string" && message.model.length > 0 && message.model.length <= MAX_MODEL_ID_LENGTH ? message.model : void 0;
|
|
4063
|
+
const usage = coerceClaudeUsage(message.usage);
|
|
4064
|
+
if (model === void 0 && usage === void 0) {
|
|
4065
|
+
return void 0;
|
|
4066
|
+
}
|
|
4067
|
+
const id = typeof message.id === "string" && message.id.length > 0 && message.id.length <= 256 ? message.id : void 0;
|
|
4068
|
+
return {
|
|
4069
|
+
...id === void 0 ? {} : { id },
|
|
4070
|
+
...model === void 0 ? {} : { model },
|
|
4071
|
+
...usage === void 0 ? {} : { usage }
|
|
4072
|
+
};
|
|
4073
|
+
};
|
|
4074
|
+
var cacheCreationOf = (usage) => usage.cache_creation_input_tokens ?? (usage.cache_creation === void 0 ? 0 : (usage.cache_creation.ephemeral_5m_input_tokens ?? 0) + (usage.cache_creation.ephemeral_1h_input_tokens ?? 0));
|
|
4075
|
+
var sumUsage = (usages) => {
|
|
4076
|
+
let input = 0;
|
|
4077
|
+
let output = 0;
|
|
4078
|
+
let cacheRead = 0;
|
|
4079
|
+
let cacheCreation = 0;
|
|
4080
|
+
for (const usage of usages) {
|
|
4081
|
+
input += usage.input_tokens;
|
|
4082
|
+
output += usage.output_tokens;
|
|
4083
|
+
cacheRead += usage.cache_read_input_tokens ?? 0;
|
|
4084
|
+
cacheCreation += cacheCreationOf(usage);
|
|
4085
|
+
}
|
|
4086
|
+
return {
|
|
4087
|
+
input_tokens: input,
|
|
4088
|
+
output_tokens: output,
|
|
4089
|
+
cache_read_input_tokens: cacheRead,
|
|
4090
|
+
cache_creation_input_tokens: cacheCreation
|
|
4091
|
+
};
|
|
4092
|
+
};
|
|
4093
|
+
var withTimeout = async (work, timeoutMillis, onError) => {
|
|
4094
|
+
let timer;
|
|
4095
|
+
const timeout = new Promise((resolve5) => {
|
|
4096
|
+
timer = setTimeout(() => {
|
|
4097
|
+
resolve5(TIMED_OUT);
|
|
4098
|
+
}, timeoutMillis);
|
|
4099
|
+
timer.unref();
|
|
4100
|
+
});
|
|
4101
|
+
try {
|
|
4102
|
+
return await Promise.race([work.catch(() => onError), timeout]);
|
|
4103
|
+
} finally {
|
|
4104
|
+
clearTimeout(timer);
|
|
4105
|
+
}
|
|
4106
|
+
};
|
|
4107
|
+
var withRegularFile = async (transcriptPath, body) => {
|
|
4108
|
+
let info;
|
|
4109
|
+
try {
|
|
4110
|
+
info = await stat(transcriptPath);
|
|
4111
|
+
} catch {
|
|
4112
|
+
return { status: "unavailable", reason: "unreadable" };
|
|
4113
|
+
}
|
|
4114
|
+
if (!info.isFile()) {
|
|
4115
|
+
return { status: "unavailable", reason: "not-a-file" };
|
|
4116
|
+
}
|
|
4117
|
+
let handle;
|
|
4118
|
+
try {
|
|
4119
|
+
handle = await open(transcriptPath, "r");
|
|
4120
|
+
} catch {
|
|
4121
|
+
return { status: "unavailable", reason: "unreadable" };
|
|
4122
|
+
}
|
|
4123
|
+
try {
|
|
4124
|
+
const { size } = await handle.stat();
|
|
4125
|
+
return await body(handle, size);
|
|
4126
|
+
} catch {
|
|
4127
|
+
return { status: "unavailable", reason: "unreadable" };
|
|
4128
|
+
} finally {
|
|
4129
|
+
await handle.close().catch(() => void 0);
|
|
4130
|
+
}
|
|
4131
|
+
};
|
|
4132
|
+
var readBytes = async (handle, start, length) => {
|
|
4133
|
+
const buffer = Buffer.alloc(length);
|
|
4134
|
+
let filled = 0;
|
|
4135
|
+
while (filled < length) {
|
|
4136
|
+
const { bytesRead } = await handle.read(buffer, filled, length - filled, start + filled);
|
|
4137
|
+
if (bytesRead === 0) {
|
|
4138
|
+
break;
|
|
4139
|
+
}
|
|
4140
|
+
filled += bytesRead;
|
|
4141
|
+
}
|
|
4142
|
+
return buffer.subarray(0, filled);
|
|
4143
|
+
};
|
|
4144
|
+
var completeLinesEnd = (bytes, start) => {
|
|
4145
|
+
const lastNewline = bytes.lastIndexOf(10);
|
|
4146
|
+
return lastNewline < 0 ? start : start + lastNewline + 1;
|
|
4147
|
+
};
|
|
4148
|
+
var readTail = (transcriptPath, maxTailBytes) => withRegularFile(transcriptPath, async (handle, size) => {
|
|
4149
|
+
const length = Math.min(size, maxTailBytes);
|
|
4150
|
+
const start = size - length;
|
|
4151
|
+
const bytes = await readBytes(handle, start, length);
|
|
4152
|
+
const endOffset = completeLinesEnd(bytes, start);
|
|
4153
|
+
const lines = bytes.toString("utf8").split("\n");
|
|
4154
|
+
if (start > 0) {
|
|
4155
|
+
lines.shift();
|
|
4156
|
+
}
|
|
4157
|
+
for (let index = lines.length - 1; index >= 0; index -= 1) {
|
|
4158
|
+
const record = assistantRecordOf((lines[index] ?? "").trim());
|
|
4159
|
+
if (record !== void 0) {
|
|
4160
|
+
return {
|
|
4161
|
+
turn: {
|
|
4162
|
+
status: "found",
|
|
4163
|
+
...record.model === void 0 ? {} : { model: record.model },
|
|
4164
|
+
...record.usage === void 0 ? {} : { usage: record.usage }
|
|
4165
|
+
},
|
|
4166
|
+
endOffset
|
|
4167
|
+
};
|
|
4168
|
+
}
|
|
4169
|
+
}
|
|
4170
|
+
return { turn: { status: "unavailable", reason: "no-assistant-message" }, endOffset };
|
|
4171
|
+
});
|
|
4172
|
+
var boundedTail = async (transcriptPath, options) => withTimeout(
|
|
4173
|
+
readTail(
|
|
4174
|
+
transcriptPath,
|
|
4175
|
+
clamp(options.maxTailBytes, DEFAULT_CLAUDE_TRANSCRIPT_TAIL_BYTES, MIN_TAIL_BYTES, MAX_TAIL_BYTES)
|
|
4176
|
+
),
|
|
4177
|
+
clamp(options.timeoutMillis, DEFAULT_CLAUDE_TRANSCRIPT_TIMEOUT_MILLIS, MIN_TIMEOUT_MILLIS, MAX_TIMEOUT_MILLIS),
|
|
4178
|
+
{ status: "unavailable", reason: "unreadable" }
|
|
4179
|
+
);
|
|
4180
|
+
var readClaudeTranscriptTurn = async (transcriptPath, options = {}) => {
|
|
4181
|
+
if (!isTranscriptPath(transcriptPath)) {
|
|
4182
|
+
return { status: "unavailable", reason: "invalid-path" };
|
|
4183
|
+
}
|
|
4184
|
+
const read = await boundedTail(transcriptPath, options);
|
|
4185
|
+
if (read === TIMED_OUT) {
|
|
4186
|
+
return { status: "unavailable", reason: "timeout" };
|
|
4187
|
+
}
|
|
4188
|
+
return "turn" in read ? read.turn : read;
|
|
4189
|
+
};
|
|
4190
|
+
var readClaudeTranscriptRange = async (transcriptPath, fromOffset, options = {}) => {
|
|
4191
|
+
if (!isTranscriptPath(transcriptPath) || !Number.isSafeInteger(fromOffset) || fromOffset < 0) {
|
|
4192
|
+
return { status: "unavailable", reason: "invalid-path" };
|
|
4193
|
+
}
|
|
4194
|
+
const maxRangeBytes = clamp(options.maxRangeBytes, DEFAULT_CLAUDE_TRANSCRIPT_RANGE_BYTES, MIN_TAIL_BYTES, MAX_RANGE_BYTES);
|
|
4195
|
+
const timeoutMillis = clamp(
|
|
4196
|
+
options.rangeTimeoutMillis,
|
|
4197
|
+
DEFAULT_CLAUDE_TRANSCRIPT_RANGE_TIMEOUT_MILLIS,
|
|
4198
|
+
MIN_TIMEOUT_MILLIS,
|
|
4199
|
+
MAX_TIMEOUT_MILLIS
|
|
4200
|
+
);
|
|
4201
|
+
const work = withRegularFile(transcriptPath, async (handle, size) => {
|
|
4202
|
+
if (size < fromOffset) {
|
|
4203
|
+
return { status: "unavailable", reason: "truncated" };
|
|
4204
|
+
}
|
|
4205
|
+
if (size - fromOffset > maxRangeBytes) {
|
|
4206
|
+
return { status: "unavailable", reason: "over-cap" };
|
|
4207
|
+
}
|
|
4208
|
+
const bytes = await readBytes(handle, fromOffset, size - fromOffset);
|
|
4209
|
+
const endOffset = completeLinesEnd(bytes, fromOffset);
|
|
4210
|
+
const complete = bytes.subarray(0, endOffset - fromOffset).toString("utf8");
|
|
4211
|
+
const requests = /* @__PURE__ */ new Map();
|
|
4212
|
+
let anonymous = 0;
|
|
4213
|
+
let model;
|
|
4214
|
+
for (const line of complete.split("\n")) {
|
|
4215
|
+
const record = assistantRecordOf(line.trim());
|
|
4216
|
+
if (record === void 0) {
|
|
4217
|
+
continue;
|
|
4218
|
+
}
|
|
4219
|
+
if (record.model !== void 0) {
|
|
4220
|
+
model = record.model;
|
|
4221
|
+
}
|
|
4222
|
+
anonymous += record.id === void 0 ? 1 : 0;
|
|
4223
|
+
requests.set(record.id ?? `#${String(anonymous)}`, record);
|
|
4224
|
+
if (requests.size > MAX_REQUESTS_PER_RANGE) {
|
|
4225
|
+
return { status: "unavailable", reason: "over-cap" };
|
|
4226
|
+
}
|
|
4227
|
+
}
|
|
4228
|
+
const usages = [...requests.values()].flatMap((record) => record.usage === void 0 ? [] : [record.usage]);
|
|
4229
|
+
return {
|
|
4230
|
+
status: "found",
|
|
4231
|
+
...model === void 0 ? {} : { model },
|
|
4232
|
+
...usages.length === 0 ? {} : { usage: sumUsage(usages) },
|
|
4233
|
+
requestCount: requests.size,
|
|
4234
|
+
endOffset
|
|
4235
|
+
};
|
|
4236
|
+
});
|
|
4237
|
+
const result = await withTimeout(work, timeoutMillis, {
|
|
4238
|
+
status: "unavailable",
|
|
4239
|
+
reason: "unreadable"
|
|
4240
|
+
});
|
|
4241
|
+
return result === TIMED_OUT ? { status: "unavailable", reason: "timeout" } : result;
|
|
4242
|
+
};
|
|
4243
|
+
var STOP_EVENTS = /* @__PURE__ */ new Set(["Stop", "StopFailure"]);
|
|
4244
|
+
var hasUsage = (record) => record.usage !== void 0 || record.token_usage !== void 0 || record.tokenUsage !== void 0;
|
|
4245
|
+
var eventNameOf = (record) => record.hook_event_name ?? record.hookEventName;
|
|
4246
|
+
var transcriptPathOf = (record) => record.transcript_path ?? record.transcriptPath;
|
|
4247
|
+
var attachClaudeTranscriptTurn = async (payload, options = {}) => {
|
|
4248
|
+
const record = asRecord5(payload);
|
|
4249
|
+
if (record === void 0) {
|
|
4250
|
+
return payload;
|
|
4251
|
+
}
|
|
4252
|
+
const eventName = eventNameOf(record);
|
|
4253
|
+
if (typeof eventName !== "string" || !STOP_EVENTS.has(eventName)) {
|
|
4254
|
+
return payload;
|
|
4255
|
+
}
|
|
4256
|
+
const transcriptPath = transcriptPathOf(record);
|
|
4257
|
+
if (typeof transcriptPath !== "string") {
|
|
4258
|
+
return payload;
|
|
4259
|
+
}
|
|
4260
|
+
const needsModel = record.model === void 0;
|
|
4261
|
+
const needsUsage = !hasUsage(record);
|
|
4262
|
+
if (!needsModel && !needsUsage) {
|
|
4263
|
+
return payload;
|
|
4264
|
+
}
|
|
4265
|
+
const turn = await readClaudeTranscriptTurn(transcriptPath, options);
|
|
4266
|
+
if (turn.status !== "found") {
|
|
4267
|
+
return payload;
|
|
4268
|
+
}
|
|
4269
|
+
return {
|
|
4270
|
+
...record,
|
|
4271
|
+
...needsModel && turn.model !== void 0 ? { model: turn.model } : {},
|
|
4272
|
+
...needsUsage && turn.usage !== void 0 ? { usage: turn.usage, usage_partial: true } : {}
|
|
4273
|
+
};
|
|
4274
|
+
};
|
|
4275
|
+
var CLAUDE_TRANSCRIPT_USAGE_ENRICHER_ID = "claude-transcript-usage";
|
|
4276
|
+
var sourceDigest = (transcriptPath) => createHash2("sha256").update(transcriptPath, "utf8").digest("hex").slice(0, 32);
|
|
4277
|
+
var createClaudeTranscriptUsageEnricher = (options = {}) => {
|
|
4278
|
+
const fileSize = async (transcriptPath) => {
|
|
4279
|
+
try {
|
|
4280
|
+
const info = await stat(transcriptPath);
|
|
4281
|
+
return info.isFile() ? info.size : void 0;
|
|
4282
|
+
} catch (thrown) {
|
|
4283
|
+
return thrown?.code === "ENOENT" ? "absent" : void 0;
|
|
4284
|
+
}
|
|
4285
|
+
};
|
|
4286
|
+
const enrich = async (input) => {
|
|
4287
|
+
const unchanged = { payload: input.payload };
|
|
4288
|
+
const record = asRecord5(input.payload);
|
|
4289
|
+
if (record === void 0) {
|
|
4290
|
+
return unchanged;
|
|
4291
|
+
}
|
|
4292
|
+
const eventName = eventNameOf(record);
|
|
4293
|
+
const transcriptPath = transcriptPathOf(record);
|
|
4294
|
+
if (typeof eventName !== "string" || !isTranscriptPath(transcriptPath)) {
|
|
4295
|
+
return unchanged;
|
|
4296
|
+
}
|
|
4297
|
+
const source = sourceDigest(transcriptPath);
|
|
4298
|
+
const cursor = input.cursor?.source === source ? input.cursor : void 0;
|
|
4299
|
+
if (eventName === "SessionStart") {
|
|
4300
|
+
if (cursor !== void 0) {
|
|
4301
|
+
return unchanged;
|
|
4302
|
+
}
|
|
4303
|
+
const size = await fileSize(transcriptPath);
|
|
4304
|
+
if (size === void 0) {
|
|
4305
|
+
return { ...unchanged, notes: ["transcript is not a readable regular file; no cursor recorded"] };
|
|
4306
|
+
}
|
|
4307
|
+
return { payload: input.payload, cursor: { source, offset: size === "absent" ? 0 : size } };
|
|
4308
|
+
}
|
|
4309
|
+
if (!STOP_EVENTS.has(eventName)) {
|
|
4310
|
+
return unchanged;
|
|
4311
|
+
}
|
|
4312
|
+
if (hasUsage(record)) {
|
|
4313
|
+
const size = await fileSize(transcriptPath);
|
|
4314
|
+
return typeof size === "number" ? { payload: input.payload, cursor: { source, offset: size } } : unchanged;
|
|
4315
|
+
}
|
|
4316
|
+
const attach = (model, usage, partial) => ({
|
|
4317
|
+
...record,
|
|
4318
|
+
...record.model === void 0 && model !== void 0 ? { model } : {},
|
|
4319
|
+
...usage === void 0 ? {} : { usage, usage_partial: partial }
|
|
4320
|
+
});
|
|
4321
|
+
if (cursor !== void 0) {
|
|
4322
|
+
const range = await readClaudeTranscriptRange(transcriptPath, cursor.offset, options);
|
|
4323
|
+
if (range.status === "found") {
|
|
4324
|
+
return {
|
|
4325
|
+
payload: attach(range.model, range.usage, false),
|
|
4326
|
+
cursor: { source, offset: range.endOffset },
|
|
4327
|
+
notes: [`summed ${String(range.requestCount)} request(s) since the last stop`]
|
|
4328
|
+
};
|
|
4329
|
+
}
|
|
4330
|
+
if (range.reason !== "truncated" && range.reason !== "over-cap") {
|
|
4331
|
+
return { ...unchanged, notes: [`transcript range not read (${range.reason}); cursor kept`] };
|
|
4332
|
+
}
|
|
4333
|
+
}
|
|
4334
|
+
const tail = await boundedTail(transcriptPath, options);
|
|
4335
|
+
if (tail === TIMED_OUT || !("turn" in tail)) {
|
|
4336
|
+
return { ...unchanged, notes: [`transcript tail not read (${tail === TIMED_OUT ? "timeout" : tail.reason})`] };
|
|
4337
|
+
}
|
|
4338
|
+
const why = cursor === void 0 ? "no cursor for this transcript" : "range not summable within bounds";
|
|
4339
|
+
return {
|
|
4340
|
+
payload: tail.turn.status === "found" ? attach(tail.turn.model, tail.turn.usage, true) : input.payload,
|
|
4341
|
+
cursor: { source, offset: tail.endOffset },
|
|
4342
|
+
notes: [`${why}; attached the last request only (usage_partial)`]
|
|
4343
|
+
};
|
|
4344
|
+
};
|
|
4345
|
+
return Object.freeze({
|
|
4346
|
+
id: CLAUDE_TRANSCRIPT_USAGE_ENRICHER_ID,
|
|
4347
|
+
providerId: CLAUDE_CODE_PROVIDER_ID,
|
|
4348
|
+
enrich
|
|
4349
|
+
});
|
|
4350
|
+
};
|
|
4351
|
+
|
|
3868
4352
|
// src/providers/cursor/payload.ts
|
|
3869
4353
|
import { z as z18 } from "zod";
|
|
3870
4354
|
var CURSOR_PROVIDER_ID = "cursor";
|
|
@@ -5019,7 +5503,7 @@ var codexDeliveryIdentity = (input) => {
|
|
|
5019
5503
|
|
|
5020
5504
|
// src/providers/codex/target.ts
|
|
5021
5505
|
var PATCH_HEADER = /^\*\*\* (?:Add File|Update File|Delete File|Move to): (.+)$/;
|
|
5022
|
-
var
|
|
5506
|
+
var asRecord6 = (value) => value !== null && typeof value === "object" && !Array.isArray(value) ? value : void 0;
|
|
5023
5507
|
var nonEmptyString2 = (value) => typeof value === "string" && value.length > 0 ? value : void 0;
|
|
5024
5508
|
var commandText = (input) => {
|
|
5025
5509
|
const command = input?.command ?? input?.cmd;
|
|
@@ -5046,7 +5530,7 @@ var patchTextOf = (toolName, input) => {
|
|
|
5046
5530
|
if (typeof input === "string") {
|
|
5047
5531
|
return /^apply[_-]?patch$/i.test(toolName) ? input : void 0;
|
|
5048
5532
|
}
|
|
5049
|
-
const record =
|
|
5533
|
+
const record = asRecord6(input);
|
|
5050
5534
|
if (/^apply[_-]?patch$/i.test(toolName)) {
|
|
5051
5535
|
return nonEmptyString2(record?.patch) ?? nonEmptyString2(record?.input) ?? commandText(record);
|
|
5052
5536
|
}
|
|
@@ -5054,7 +5538,7 @@ var patchTextOf = (toolName, input) => {
|
|
|
5054
5538
|
return command !== void 0 && /^\s*apply_patch\b/.test(command) ? command : void 0;
|
|
5055
5539
|
};
|
|
5056
5540
|
var codexTargetHint = (toolName, toolInput, cwd) => {
|
|
5057
|
-
const record =
|
|
5541
|
+
const record = asRecord6(toolInput);
|
|
5058
5542
|
const workdir = nonEmptyString2(record?.workdir);
|
|
5059
5543
|
const base = workdir ?? cwd;
|
|
5060
5544
|
const patch = patchTextOf(toolName, toolInput);
|
|
@@ -5136,7 +5620,7 @@ var CODEX_CAPABILITIES = Object.freeze({
|
|
|
5136
5620
|
// compaction callbacks do not. See `./delivery.ts` for which and why.
|
|
5137
5621
|
deliveryIdentifier: "partial"
|
|
5138
5622
|
});
|
|
5139
|
-
var
|
|
5623
|
+
var asRecord7 = (value) => value !== null && typeof value === "object" && !Array.isArray(value) ? value : void 0;
|
|
5140
5624
|
var hasExactMarker = (payload) => {
|
|
5141
5625
|
if (payload.codex_version !== void 0) {
|
|
5142
5626
|
return true;
|
|
@@ -5229,7 +5713,7 @@ var outcomeFromToolResponse = (toolResponse) => {
|
|
|
5229
5713
|
if (toolResponse === void 0) {
|
|
5230
5714
|
return "unknown";
|
|
5231
5715
|
}
|
|
5232
|
-
const record =
|
|
5716
|
+
const record = asRecord7(toolResponse);
|
|
5233
5717
|
if (record === void 0) {
|
|
5234
5718
|
return "ok";
|
|
5235
5719
|
}
|
|
@@ -6527,6 +7011,49 @@ var stateValueSchema = z22.discriminatedUnion("kind", [
|
|
|
6527
7011
|
z22.strictObject({
|
|
6528
7012
|
kind: z22.literal("attributes"),
|
|
6529
7013
|
attributes: attributesSchema
|
|
7014
|
+
}),
|
|
7015
|
+
/**
|
|
7016
|
+
* The model a session last reported, so a later invocation whose payload names
|
|
7017
|
+
* none (Claude Code's `Stop`) can still say which model it was. A model id is
|
|
7018
|
+
* not sensitive (`modelDescriptorSchema`), and the descriptor is the strict,
|
|
7019
|
+
* bounded canonical shape, never a payload fragment.
|
|
7020
|
+
*/
|
|
7021
|
+
z22.strictObject({
|
|
7022
|
+
kind: z22.literal("session-model"),
|
|
7023
|
+
model: modelDescriptorSchema
|
|
7024
|
+
}),
|
|
7025
|
+
/**
|
|
7026
|
+
* How far a {@link PayloadEnricher} has read a session's append-only source
|
|
7027
|
+
* (Claude Code's transcript), so the next read starts where the last ended.
|
|
7028
|
+
* `source` is an opaque digest of what was read, never a path.
|
|
7029
|
+
*/
|
|
7030
|
+
/**
|
|
7031
|
+
* Running state of one metric series (issue #69), so a cumulative data point
|
|
7032
|
+
* exported by a later hook process continues the same total. Holds numbers and
|
|
7033
|
+
* a series digest only; the series' attributes are re-supplied by the caller
|
|
7034
|
+
* and never read back from disk.
|
|
7035
|
+
*/
|
|
7036
|
+
z22.strictObject({
|
|
7037
|
+
kind: z22.literal("metric-series"),
|
|
7038
|
+
/** Start of the cumulative interval. */
|
|
7039
|
+
startTimeMillis: epochMillisSchema,
|
|
7040
|
+
/** Counters: the running total. */
|
|
7041
|
+
value: z22.number().finite().min(0).optional(),
|
|
7042
|
+
/** Histograms: the running aggregation. */
|
|
7043
|
+
histogram: z22.strictObject({
|
|
7044
|
+
count: z22.number().int().min(0),
|
|
7045
|
+
sum: z22.number().finite().min(0),
|
|
7046
|
+
min: z22.number().finite(),
|
|
7047
|
+
max: z22.number().finite(),
|
|
7048
|
+
bucketCounts: z22.array(z22.number().int().min(0)).max(64)
|
|
7049
|
+
}).optional(),
|
|
7050
|
+
/** Opaque digest of the last delivery folded in; makes a replay a no-op. */
|
|
7051
|
+
appliedDelivery: z22.string().regex(/^[A-Za-z0-9_-]{1,128}$/).optional()
|
|
7052
|
+
}),
|
|
7053
|
+
z22.strictObject({
|
|
7054
|
+
kind: z22.literal("read-cursor"),
|
|
7055
|
+
source: z22.string().regex(/^[A-Za-z0-9_-]{1,128}$/),
|
|
7056
|
+
offset: z22.number().int().min(0).max(Number.MAX_SAFE_INTEGER)
|
|
6530
7057
|
})
|
|
6531
7058
|
]);
|
|
6532
7059
|
var stateRecordSchema = z22.strictObject({
|
|
@@ -6572,9 +7099,9 @@ var createFixedClock = (options = {}) => {
|
|
|
6572
7099
|
};
|
|
6573
7100
|
|
|
6574
7101
|
// src/runtime/ids.ts
|
|
6575
|
-
import { createHash as
|
|
7102
|
+
import { createHash as createHash3, randomUUID } from "crypto";
|
|
6576
7103
|
var digest = (namespace, parts) => {
|
|
6577
|
-
const hash =
|
|
7104
|
+
const hash = createHash3("sha256");
|
|
6578
7105
|
hash.update(namespace);
|
|
6579
7106
|
for (const part of parts) {
|
|
6580
7107
|
hash.update("\0");
|
|
@@ -6810,16 +7337,16 @@ var resolveDeliveryIdentity = (input) => {
|
|
|
6810
7337
|
import { z as z23 } from "zod";
|
|
6811
7338
|
|
|
6812
7339
|
// src/runtime/target-resolution.ts
|
|
6813
|
-
import * as
|
|
7340
|
+
import * as path2 from "path";
|
|
6814
7341
|
var DEFAULT_TARGET_RESOLUTION_BUDGET_MILLIS = 50;
|
|
6815
7342
|
var absolutePathsOf = (hint) => {
|
|
6816
|
-
const base = hint.baseDirectory !== void 0 &&
|
|
7343
|
+
const base = hint.baseDirectory !== void 0 && path2.isAbsolute(hint.baseDirectory) ? hint.baseDirectory : void 0;
|
|
6817
7344
|
const resolved = [];
|
|
6818
7345
|
for (const candidate of hint.paths) {
|
|
6819
|
-
if (
|
|
6820
|
-
resolved.push(
|
|
7346
|
+
if (path2.isAbsolute(candidate)) {
|
|
7347
|
+
resolved.push(path2.resolve(candidate));
|
|
6821
7348
|
} else if (base !== void 0) {
|
|
6822
|
-
resolved.push(
|
|
7349
|
+
resolved.push(path2.resolve(base, candidate));
|
|
6823
7350
|
} else {
|
|
6824
7351
|
return void 0;
|
|
6825
7352
|
}
|
|
@@ -7035,6 +7562,22 @@ var usageScopeOf = (event3) => {
|
|
|
7035
7562
|
}
|
|
7036
7563
|
};
|
|
7037
7564
|
var sequenceKey = (sessionId) => `sequence:${sessionId}`;
|
|
7565
|
+
var sessionModelKey = (sessionId) => `model:${sessionId}`;
|
|
7566
|
+
var readCursorKey = (enricherId, sessionId) => `cursor:${enricherId}:${sessionId}`;
|
|
7567
|
+
var UNKNOWN_MODEL_ID = "unknown";
|
|
7568
|
+
var latestSessionModel = (events) => {
|
|
7569
|
+
let latest;
|
|
7570
|
+
for (const event3 of events) {
|
|
7571
|
+
if (event3.subagentId !== void 0) {
|
|
7572
|
+
continue;
|
|
7573
|
+
}
|
|
7574
|
+
if ((event3.type === "session.start" || event3.type === "generation.start" || event3.type === "generation.end") && event3.model !== void 0 && event3.model.modelId !== UNKNOWN_MODEL_ID) {
|
|
7575
|
+
latest = event3.model;
|
|
7576
|
+
}
|
|
7577
|
+
}
|
|
7578
|
+
return latest;
|
|
7579
|
+
};
|
|
7580
|
+
var sameModel = (left, right) => left !== void 0 && left.modelId === right.modelId && left.vendor === right.vendor && left.family === right.family;
|
|
7038
7581
|
var usageKey = (sessionId, scope, scopeKey) => `usage:${sessionId}:${scope}:${scopeKey}`;
|
|
7039
7582
|
var baselineScopeOf = (scope, scopeKey, sessionId, series) => series === "session-lifetime" && scope === "generation" ? { scope: "session", scopeKey: sessionId } : { scope, scopeKey };
|
|
7040
7583
|
var createOtelHook = (deps) => {
|
|
@@ -7082,6 +7625,66 @@ var createOtelHook = (deps) => {
|
|
|
7082
7625
|
return 0;
|
|
7083
7626
|
}
|
|
7084
7627
|
};
|
|
7628
|
+
const enrichPayload = async (payload, providerId, sessionId, diagnostics) => {
|
|
7629
|
+
let current = payload;
|
|
7630
|
+
for (const enricher of deps.payloadEnrichers ?? []) {
|
|
7631
|
+
if (enricher.providerId !== providerId) {
|
|
7632
|
+
continue;
|
|
7633
|
+
}
|
|
7634
|
+
const key = readCursorKey(enricher.id, sessionId);
|
|
7635
|
+
let cursor;
|
|
7636
|
+
try {
|
|
7637
|
+
const record = await deps.stateStore.read(key);
|
|
7638
|
+
if (record?.value.kind === "read-cursor") {
|
|
7639
|
+
cursor = { source: record.value.source, offset: record.value.offset };
|
|
7640
|
+
}
|
|
7641
|
+
} catch (thrown) {
|
|
7642
|
+
diagnostics.push(
|
|
7643
|
+
errorInfoFromThrown(thrown, { code: "state-store-failure", phase: "state", occurredAt: clock.now() })
|
|
7644
|
+
);
|
|
7645
|
+
continue;
|
|
7646
|
+
}
|
|
7647
|
+
let result;
|
|
7648
|
+
try {
|
|
7649
|
+
result = await enricher.enrich({ payload: current, sessionId, ...cursor === void 0 ? {} : { cursor } });
|
|
7650
|
+
} catch (thrown) {
|
|
7651
|
+
logger.warn("payload enricher failed; parsing the payload as delivered", {
|
|
7652
|
+
"enricher.id": enricher.id,
|
|
7653
|
+
"error.name": thrown instanceof Error ? thrown.name : typeof thrown
|
|
7654
|
+
});
|
|
7655
|
+
continue;
|
|
7656
|
+
}
|
|
7657
|
+
current = result.payload;
|
|
7658
|
+
if (result.notes !== void 0 && result.notes.length > 0) {
|
|
7659
|
+
logger.debug("payload enricher notes", {
|
|
7660
|
+
"enricher.id": enricher.id,
|
|
7661
|
+
"enricher.notes": result.notes.slice(0, 8).map((note) => note.slice(0, 200))
|
|
7662
|
+
});
|
|
7663
|
+
}
|
|
7664
|
+
const next = result.cursor;
|
|
7665
|
+
if (next !== void 0 && (next.source !== cursor?.source || next.offset !== cursor.offset)) {
|
|
7666
|
+
try {
|
|
7667
|
+
await deps.stateStore.write(key, { kind: "read-cursor", source: next.source, offset: next.offset });
|
|
7668
|
+
} catch (thrown) {
|
|
7669
|
+
diagnostics.push(
|
|
7670
|
+
errorInfoFromThrown(thrown, { code: "state-store-failure", phase: "state", occurredAt: clock.now() })
|
|
7671
|
+
);
|
|
7672
|
+
}
|
|
7673
|
+
}
|
|
7674
|
+
}
|
|
7675
|
+
return current;
|
|
7676
|
+
};
|
|
7677
|
+
const readSessionModel = async (sessionId, diagnostics) => {
|
|
7678
|
+
try {
|
|
7679
|
+
const record = await deps.stateStore.read(sessionModelKey(sessionId));
|
|
7680
|
+
return record?.value.kind === "session-model" ? record.value.model : void 0;
|
|
7681
|
+
} catch (thrown) {
|
|
7682
|
+
diagnostics.push(
|
|
7683
|
+
errorInfoFromThrown(thrown, { code: "state-store-failure", phase: "state", occurredAt: clock.now() })
|
|
7684
|
+
);
|
|
7685
|
+
return void 0;
|
|
7686
|
+
}
|
|
7687
|
+
};
|
|
7085
7688
|
const deriveUsage = async (events, diagnostics, suppress, series) => {
|
|
7086
7689
|
const observations = [];
|
|
7087
7690
|
for (const event3 of events) {
|
|
@@ -7402,10 +8005,19 @@ var createOtelHook = (deps) => {
|
|
|
7402
8005
|
const identity = resolution.identity;
|
|
7403
8006
|
const prepare = async () => {
|
|
7404
8007
|
const sequenceBase = await readSequenceBase(identity.sessionId, diagnostics);
|
|
8008
|
+
const sessionModel = await readSessionModel(identity.sessionId, diagnostics);
|
|
8009
|
+
const payload = suppress ? detectionInput.payload : await enrichPayload(detectionInput.payload, detection.providerId, identity.sessionId, diagnostics);
|
|
7405
8010
|
let parsed;
|
|
7406
8011
|
try {
|
|
7407
8012
|
parsed = adapter.parse(
|
|
7408
|
-
{
|
|
8013
|
+
{
|
|
8014
|
+
...detectionInput,
|
|
8015
|
+
payload,
|
|
8016
|
+
detection,
|
|
8017
|
+
identity,
|
|
8018
|
+
sequenceBase,
|
|
8019
|
+
...sessionModel === void 0 ? {} : { sessionModel }
|
|
8020
|
+
},
|
|
7409
8021
|
providerContext
|
|
7410
8022
|
);
|
|
7411
8023
|
} catch (thrown) {
|
|
@@ -7515,6 +8127,23 @@ var createOtelHook = (deps) => {
|
|
|
7515
8127
|
})
|
|
7516
8128
|
);
|
|
7517
8129
|
}
|
|
8130
|
+
const reportedModel = latestSessionModel(screened.kept);
|
|
8131
|
+
if (reportedModel !== void 0 && !sameModel(sessionModel, reportedModel)) {
|
|
8132
|
+
try {
|
|
8133
|
+
await deps.stateStore.write(sessionModelKey(identity.sessionId), {
|
|
8134
|
+
kind: "session-model",
|
|
8135
|
+
model: reportedModel
|
|
8136
|
+
});
|
|
8137
|
+
} catch (thrown) {
|
|
8138
|
+
diagnostics.push(
|
|
8139
|
+
errorInfoFromThrown(thrown, {
|
|
8140
|
+
code: "state-store-failure",
|
|
8141
|
+
phase: "state",
|
|
8142
|
+
occurredAt: clock.now()
|
|
8143
|
+
})
|
|
8144
|
+
);
|
|
8145
|
+
}
|
|
8146
|
+
}
|
|
7518
8147
|
}
|
|
7519
8148
|
return {
|
|
7520
8149
|
kind: "ready",
|
|
@@ -7733,8 +8362,8 @@ var buildErrorEvents = (diagnostics, identity, sequenceBase, ids, privacy) => {
|
|
|
7733
8362
|
};
|
|
7734
8363
|
|
|
7735
8364
|
// src/runtime/git-worktree.ts
|
|
7736
|
-
import { lstat, open, stat } from "fs/promises";
|
|
7737
|
-
import * as
|
|
8365
|
+
import { lstat, open as open2, stat as stat2 } from "fs/promises";
|
|
8366
|
+
import * as path3 from "path";
|
|
7738
8367
|
var MAX_WORKTREE_WALK_DEPTH = 128;
|
|
7739
8368
|
var MAX_GIT_FILE_BYTES = 4096;
|
|
7740
8369
|
var MAX_CACHE_ENTRIES = 1024;
|
|
@@ -7745,7 +8374,7 @@ var INVALID = Object.freeze({ kind: "invalid" });
|
|
|
7745
8374
|
var readBounded = async (filePath) => {
|
|
7746
8375
|
let handle;
|
|
7747
8376
|
try {
|
|
7748
|
-
handle = await
|
|
8377
|
+
handle = await open2(filePath, "r");
|
|
7749
8378
|
const buffer = Buffer.alloc(MAX_GIT_FILE_BYTES);
|
|
7750
8379
|
const { bytesRead } = await handle.read(buffer, 0, MAX_GIT_FILE_BYTES, 0);
|
|
7751
8380
|
return buffer.subarray(0, bytesRead).toString("utf8");
|
|
@@ -7766,7 +8395,7 @@ var parseHeadBranch = (head) => {
|
|
|
7766
8395
|
return branch;
|
|
7767
8396
|
};
|
|
7768
8397
|
var firstLine = (content) => content.split(/\r?\n/, 1)[0]?.trim() ?? "";
|
|
7769
|
-
var resolveGitPath = (target, base) => target === void 0 || target.length === 0 || target.includes("\0") ? void 0 :
|
|
8398
|
+
var resolveGitPath = (target, base) => target === void 0 || target.length === 0 || target.includes("\0") ? void 0 : path3.resolve(base, target);
|
|
7770
8399
|
var parseGitDirFile = (content, worktreeRoot) => {
|
|
7771
8400
|
const line = firstLine(content);
|
|
7772
8401
|
return resolveGitPath(
|
|
@@ -7786,26 +8415,26 @@ var isMissing = async (filePath) => {
|
|
|
7786
8415
|
};
|
|
7787
8416
|
var isDirectory = async (directory) => {
|
|
7788
8417
|
try {
|
|
7789
|
-
return (await
|
|
8418
|
+
return (await stat2(directory)).isDirectory();
|
|
7790
8419
|
} catch {
|
|
7791
8420
|
return false;
|
|
7792
8421
|
}
|
|
7793
8422
|
};
|
|
7794
8423
|
var repositoryOf = async (worktreeRoot, gitDir) => {
|
|
7795
|
-
const commonDirFile =
|
|
8424
|
+
const commonDirFile = path3.join(gitDir, "commondir");
|
|
7796
8425
|
const content = await readBounded(commonDirFile);
|
|
7797
8426
|
if (content === void 0) {
|
|
7798
8427
|
return await isMissing(commonDirFile) ? { kind: "main", mainRoot: worktreeRoot } : { kind: "linked" };
|
|
7799
8428
|
}
|
|
7800
8429
|
const commonDir = parseCommonDirFile(content, gitDir);
|
|
7801
|
-
const mainRoot = commonDir !== void 0 &&
|
|
8430
|
+
const mainRoot = commonDir !== void 0 && path3.basename(commonDir) === ".git" && await isDirectory(commonDir) ? path3.dirname(commonDir) : void 0;
|
|
7802
8431
|
return { kind: "linked", ...mainRoot === void 0 ? {} : { mainRoot } };
|
|
7803
8432
|
};
|
|
7804
8433
|
var probeDirectory = async (directory) => {
|
|
7805
|
-
const dotGit =
|
|
8434
|
+
const dotGit = path3.join(directory, ".git");
|
|
7806
8435
|
let info;
|
|
7807
8436
|
try {
|
|
7808
|
-
info = await
|
|
8437
|
+
info = await stat2(dotGit);
|
|
7809
8438
|
} catch {
|
|
7810
8439
|
return ABSENT;
|
|
7811
8440
|
}
|
|
@@ -7819,7 +8448,7 @@ var probeDirectory = async (directory) => {
|
|
|
7819
8448
|
if (gitDir === void 0) {
|
|
7820
8449
|
return INVALID;
|
|
7821
8450
|
}
|
|
7822
|
-
const head = await readBounded(
|
|
8451
|
+
const head = await readBounded(path3.join(gitDir, "HEAD"));
|
|
7823
8452
|
if (head === void 0) {
|
|
7824
8453
|
return INVALID;
|
|
7825
8454
|
}
|
|
@@ -7849,10 +8478,10 @@ var createFilesystemWorktreeLocator = (options = {}) => {
|
|
|
7849
8478
|
};
|
|
7850
8479
|
const locate = async (absolutePath) => {
|
|
7851
8480
|
try {
|
|
7852
|
-
if (!
|
|
8481
|
+
if (!path3.isAbsolute(absolutePath) || absolutePath.includes("\0")) {
|
|
7853
8482
|
return void 0;
|
|
7854
8483
|
}
|
|
7855
|
-
let directory =
|
|
8484
|
+
let directory = path3.resolve(absolutePath);
|
|
7856
8485
|
for (let depth = 0; depth < MAX_WORKTREE_WALK_DEPTH; depth += 1) {
|
|
7857
8486
|
const probe = await cachedProbe(directory);
|
|
7858
8487
|
if (probe.kind === "worktree") {
|
|
@@ -7861,7 +8490,7 @@ var createFilesystemWorktreeLocator = (options = {}) => {
|
|
|
7861
8490
|
if (probe.kind === "invalid") {
|
|
7862
8491
|
return void 0;
|
|
7863
8492
|
}
|
|
7864
|
-
const parent =
|
|
8493
|
+
const parent = path3.dirname(directory);
|
|
7865
8494
|
if (parent === directory) {
|
|
7866
8495
|
return void 0;
|
|
7867
8496
|
}
|
|
@@ -7901,6 +8530,8 @@ var rollupUsageKey = (sessionId, scope, scopeKey) => `${rollupScanPrefix(session
|
|
|
7901
8530
|
var rollupEpochKey = (sessionId, scope, scopeKey) => `${rollupEpochScanPrefix(sessionId)}${encodeSegment(scope)}:${encodeSegment(scopeKey)}`;
|
|
7902
8531
|
var rollupScanPrefix = (sessionId) => sessionId === void 0 ? `${LIFECYCLE_PREFIX}:usage:` : `${LIFECYCLE_PREFIX}:usage:${encodeSegment(sessionId)}:`;
|
|
7903
8532
|
var rollupEpochScanPrefix = (sessionId) => sessionId === void 0 ? `${LIFECYCLE_PREFIX}:epoch:` : `${LIFECYCLE_PREFIX}:epoch:${encodeSegment(sessionId)}:`;
|
|
8533
|
+
var metricSeriesKey = (sessionScope2, seriesDigest) => `${metricSeriesScanPrefix(sessionScope2)}${encodeSegment(seriesDigest)}`;
|
|
8534
|
+
var metricSeriesScanPrefix = (sessionScope2) => sessionScope2 === void 0 ? `${LIFECYCLE_PREFIX}:metric:v1:` : `${LIFECYCLE_PREFIX}:metric:v1:${encodeSegment(sessionScope2)}:`;
|
|
7904
8535
|
|
|
7905
8536
|
// src/lifecycle/dedup.ts
|
|
7906
8537
|
var DEFAULT_STALE_CLAIM_MILLIS = 6e4;
|
|
@@ -8071,7 +8702,7 @@ var createCallbackDeduplicator = (deps) => {
|
|
|
8071
8702
|
};
|
|
8072
8703
|
|
|
8073
8704
|
// src/telemetry/semconv.ts
|
|
8074
|
-
import { createHash as
|
|
8705
|
+
import { createHash as createHash4 } from "crypto";
|
|
8075
8706
|
import { SpanKind, SpanStatusCode, TraceFlags } from "@opentelemetry/api";
|
|
8076
8707
|
import { millisToHrTime } from "@opentelemetry/core";
|
|
8077
8708
|
import {
|
|
@@ -8090,7 +8721,7 @@ import {
|
|
|
8090
8721
|
} from "@opentelemetry/semantic-conventions/incubating";
|
|
8091
8722
|
|
|
8092
8723
|
// src/version.ts
|
|
8093
|
-
var VERSION = "0.
|
|
8724
|
+
var VERSION = "0.11.0";
|
|
8094
8725
|
|
|
8095
8726
|
// src/telemetry/export-identity.ts
|
|
8096
8727
|
import { ATTR_SESSION_ID } from "@opentelemetry/semantic-conventions/incubating";
|
|
@@ -8187,6 +8818,7 @@ var ATTR_OTELHOOK_SPAN_PAIRING = "otelhook.span.pairing";
|
|
|
8187
8818
|
var ATTR_OTELHOOK_SPAN_ORPHAN = "otelhook.span.orphan";
|
|
8188
8819
|
var ATTR_OTELHOOK_OUTCOME = "otelhook.outcome";
|
|
8189
8820
|
var ATTR_OTELHOOK_RESET_DETECTED = "otelhook.usage.reset_detected";
|
|
8821
|
+
var ATTR_OTELHOOK_USAGE_PARTIAL = "otelhook.usage.partial";
|
|
8190
8822
|
var ATTR_OTELHOOK_TOOL_KIND = "otelhook.tool.kind";
|
|
8191
8823
|
var ATTR_OTELHOOK_DELEGATION_DEPTH = "otelhook.delegation_depth";
|
|
8192
8824
|
var ATTR_OTELHOOK_COMPACTION_TRIGGER = "otelhook.compaction.trigger";
|
|
@@ -8194,7 +8826,7 @@ var ATTR_OTELHOOK_AGENT_NAME = "otelhook.agent.name";
|
|
|
8194
8826
|
var ATTR_OTELHOOK_AGENT_VERSION = "otelhook.agent.version";
|
|
8195
8827
|
var ATTR_OTELHOOK_GENERATION_ID = "otelhook.generation.id";
|
|
8196
8828
|
var FIELD_SEPARATOR = "\0";
|
|
8197
|
-
var digestHex = (parts, length) =>
|
|
8829
|
+
var digestHex = (parts, length) => createHash4("sha256").update(parts.join(FIELD_SEPARATOR)).digest("hex").slice(0, length);
|
|
8198
8830
|
var MAX_RECOVERED_START_ATTRIBUTES = 16;
|
|
8199
8831
|
var familyOf = (type) => {
|
|
8200
8832
|
switch (type) {
|
|
@@ -8459,7 +9091,8 @@ var buildLifecycleSpan = (plan, resource, scope) => {
|
|
|
8459
9091
|
// Codex turn): the key a consumer stores a usage observation under.
|
|
8460
9092
|
[ATTR_OTELHOOK_GENERATION_ID]: group.ref.scopeKey,
|
|
8461
9093
|
...end?.outcome === void 0 ? {} : { [ATTR_OTELHOOK_OUTCOME]: end.outcome },
|
|
8462
|
-
...usageAttributes(end?.usage, false)
|
|
9094
|
+
...usageAttributes(end?.usage, false),
|
|
9095
|
+
...end?.usage === void 0 || end.usagePartial === void 0 ? {} : { [ATTR_OTELHOOK_USAGE_PARTIAL]: end.usagePartial }
|
|
8463
9096
|
};
|
|
8464
9097
|
status = outcomeStatus(end?.outcome);
|
|
8465
9098
|
break;
|
|
@@ -9210,65 +9843,483 @@ var createUsageAccumulator = (deps) => {
|
|
|
9210
9843
|
return { accumulateDelta, recordReset, read, cleanup };
|
|
9211
9844
|
};
|
|
9212
9845
|
|
|
9213
|
-
// src/lifecycle/
|
|
9214
|
-
|
|
9215
|
-
var DEFAULT_MAX_ENTRIES_PER_COMPONENT = 1e3;
|
|
9216
|
-
var createLifecycleJanitor = (options) => {
|
|
9217
|
-
const maxEntries = options.maxEntriesPerComponent ?? DEFAULT_MAX_ENTRIES_PER_COMPONENT;
|
|
9218
|
-
const spanMaxAge = options.spanMaxAgeMillis ?? DEFAULT_MAX_AGE_MILLIS;
|
|
9219
|
-
const dedupMaxAge = options.dedupMaxAgeMillis ?? DEFAULT_MAX_AGE_MILLIS;
|
|
9220
|
-
const usageMaxAge = options.usageMaxAgeMillis ?? DEFAULT_MAX_AGE_MILLIS;
|
|
9221
|
-
const runOnce = async (sessionId) => {
|
|
9222
|
-
const scope = { maxEntries, ...sessionId === void 0 ? {} : { sessionId } };
|
|
9223
|
-
const [span, dedup, usage] = await Promise.all([
|
|
9224
|
-
options.spanCorrelator?.cleanup(spanMaxAge, scope),
|
|
9225
|
-
// Deduplication is deliberately swept across every scope rather than the
|
|
9226
|
-
// ending session's: a delivery scope is a host-chosen namespace or a
|
|
9227
|
-
// digest of provider/installation/session, never a session id, so scoping
|
|
9228
|
-
// this sweep by `sessionId` would match nothing and let records accumulate
|
|
9229
|
-
// forever. The sweep is TTL-driven and still bounded by `maxEntries`.
|
|
9230
|
-
options.deduplicator?.cleanup(dedupMaxAge, {
|
|
9231
|
-
maxEntries,
|
|
9232
|
-
...options.dedupStaleClaimMillis === void 0 ? {} : { staleClaimMillis: options.dedupStaleClaimMillis }
|
|
9233
|
-
}),
|
|
9234
|
-
options.usageAccumulator?.cleanup(usageMaxAge, scope)
|
|
9235
|
-
]);
|
|
9236
|
-
return {
|
|
9237
|
-
...span === void 0 ? {} : { span },
|
|
9238
|
-
...dedup === void 0 ? {} : { dedup },
|
|
9239
|
-
...usage === void 0 ? {} : { usage }
|
|
9240
|
-
};
|
|
9241
|
-
};
|
|
9242
|
-
return { runOnce };
|
|
9243
|
-
};
|
|
9846
|
+
// src/lifecycle/metric-series.ts
|
|
9847
|
+
import { createHash as createHash5 } from "crypto";
|
|
9244
9848
|
|
|
9245
|
-
// src/
|
|
9246
|
-
var
|
|
9247
|
-
|
|
9248
|
-
|
|
9249
|
-
|
|
9250
|
-
|
|
9251
|
-
|
|
9252
|
-
|
|
9253
|
-
|
|
9254
|
-
|
|
9255
|
-
|
|
9256
|
-
|
|
9257
|
-
|
|
9258
|
-
|
|
9259
|
-
|
|
9260
|
-
|
|
9261
|
-
|
|
9262
|
-
|
|
9263
|
-
|
|
9264
|
-
|
|
9265
|
-
|
|
9266
|
-
|
|
9267
|
-
|
|
9268
|
-
|
|
9269
|
-
|
|
9270
|
-
|
|
9271
|
-
|
|
9849
|
+
// src/telemetry/metric-model.ts
|
|
9850
|
+
var TOKEN_USAGE_BUCKETS = Object.freeze([
|
|
9851
|
+
1,
|
|
9852
|
+
4,
|
|
9853
|
+
16,
|
|
9854
|
+
64,
|
|
9855
|
+
256,
|
|
9856
|
+
1024,
|
|
9857
|
+
4096,
|
|
9858
|
+
16384,
|
|
9859
|
+
65536,
|
|
9860
|
+
262144,
|
|
9861
|
+
1048576,
|
|
9862
|
+
4194304,
|
|
9863
|
+
16777216,
|
|
9864
|
+
67108864
|
|
9865
|
+
]);
|
|
9866
|
+
var OPERATION_DURATION_BUCKETS = Object.freeze([
|
|
9867
|
+
0.01,
|
|
9868
|
+
0.02,
|
|
9869
|
+
0.04,
|
|
9870
|
+
0.08,
|
|
9871
|
+
0.16,
|
|
9872
|
+
0.32,
|
|
9873
|
+
0.64,
|
|
9874
|
+
1.28,
|
|
9875
|
+
2.56,
|
|
9876
|
+
5.12,
|
|
9877
|
+
10.24,
|
|
9878
|
+
20.48,
|
|
9879
|
+
40.96,
|
|
9880
|
+
81.92
|
|
9881
|
+
]);
|
|
9882
|
+
var METRIC_TOKEN_USAGE = "gen_ai.client.token.usage";
|
|
9883
|
+
var METRIC_OPERATION_DURATION = "gen_ai.client.operation.duration";
|
|
9884
|
+
var METRIC_SESSIONS = "otelhook.sessions";
|
|
9885
|
+
var METRIC_TOOL_CALLS = "otelhook.tool.calls";
|
|
9886
|
+
var METRIC_COST_USAGE = "otelhook.cost.usage";
|
|
9887
|
+
var METRIC_INSTRUMENTS = Object.freeze({
|
|
9888
|
+
[METRIC_TOKEN_USAGE]: {
|
|
9889
|
+
name: METRIC_TOKEN_USAGE,
|
|
9890
|
+
kind: "histogram",
|
|
9891
|
+
unit: "{token}",
|
|
9892
|
+
description: "Tokens used per generation, by token type (hook-derived)",
|
|
9893
|
+
valueType: "int",
|
|
9894
|
+
boundaries: TOKEN_USAGE_BUCKETS
|
|
9895
|
+
},
|
|
9896
|
+
[METRIC_OPERATION_DURATION]: {
|
|
9897
|
+
name: METRIC_OPERATION_DURATION,
|
|
9898
|
+
kind: "histogram",
|
|
9899
|
+
unit: "s",
|
|
9900
|
+
description: "Generation duration, from its start hook to its end hook (hook-derived)",
|
|
9901
|
+
valueType: "double",
|
|
9902
|
+
boundaries: OPERATION_DURATION_BUCKETS
|
|
9903
|
+
},
|
|
9904
|
+
[METRIC_SESSIONS]: {
|
|
9905
|
+
name: METRIC_SESSIONS,
|
|
9906
|
+
kind: "counter",
|
|
9907
|
+
unit: "{session}",
|
|
9908
|
+
description: "Agent sessions started",
|
|
9909
|
+
valueType: "int"
|
|
9910
|
+
},
|
|
9911
|
+
[METRIC_TOOL_CALLS]: {
|
|
9912
|
+
name: METRIC_TOOL_CALLS,
|
|
9913
|
+
kind: "counter",
|
|
9914
|
+
unit: "{call}",
|
|
9915
|
+
description: "Completed tool calls, by tool name and outcome",
|
|
9916
|
+
valueType: "int"
|
|
9917
|
+
},
|
|
9918
|
+
[METRIC_COST_USAGE]: {
|
|
9919
|
+
name: METRIC_COST_USAGE,
|
|
9920
|
+
kind: "counter",
|
|
9921
|
+
unit: "USD",
|
|
9922
|
+
description: "Cost reported by the provider; never estimated",
|
|
9923
|
+
valueType: "double"
|
|
9924
|
+
}
|
|
9925
|
+
});
|
|
9926
|
+
var isMetricInstrumentName = (value) => typeof value === "string" && Object.hasOwn(METRIC_INSTRUMENTS, value);
|
|
9927
|
+
var ATTR_GEN_AI_TOKEN_TYPE = "gen_ai.token.type";
|
|
9928
|
+
var ATTR_GEN_AI_PROVIDER_NAME = "gen_ai.provider.name";
|
|
9929
|
+
var ATTR_GEN_AI_OPERATION_NAME2 = "gen_ai.operation.name";
|
|
9930
|
+
var ATTR_GEN_AI_REQUEST_MODEL2 = "gen_ai.request.model";
|
|
9931
|
+
var ATTR_GEN_AI_RESPONSE_MODEL2 = "gen_ai.response.model";
|
|
9932
|
+
var ATTR_GEN_AI_TOOL_NAME2 = "gen_ai.tool.name";
|
|
9933
|
+
var ATTR_ERROR_TYPE2 = "error.type";
|
|
9934
|
+
var ATTR_SESSION_ID2 = "session.id";
|
|
9935
|
+
var ATTR_OTELHOOK_PROVIDER_ID2 = "otelhook.provider.id";
|
|
9936
|
+
var ATTR_OTELHOOK_OUTCOME2 = "otelhook.outcome";
|
|
9937
|
+
var ATTR_OTELHOOK_SESSION_KIND = "otelhook.session.kind";
|
|
9938
|
+
var commonAttributes = (event3, resource, includeSessionId) => ({
|
|
9939
|
+
[ATTR_OTELHOOK_PROVIDER_ID2]: event3.provenance.providerId,
|
|
9940
|
+
...includeSessionId ? { [ATTR_SESSION_ID2]: resolveExportedSessionId(event3.sessionId, resource).sessionId } : {}
|
|
9941
|
+
});
|
|
9942
|
+
var generationAttributes = (end, requestModel) => ({
|
|
9943
|
+
[ATTR_GEN_AI_OPERATION_NAME2]: "chat",
|
|
9944
|
+
...end.model.vendor === void 0 ? {} : { [ATTR_GEN_AI_PROVIDER_NAME]: end.model.vendor },
|
|
9945
|
+
[ATTR_GEN_AI_REQUEST_MODEL2]: requestModel ?? end.model.modelId,
|
|
9946
|
+
[ATTR_GEN_AI_RESPONSE_MODEL2]: end.model.modelId
|
|
9947
|
+
});
|
|
9948
|
+
var TOKEN_FIELDS = [
|
|
9949
|
+
["input", (usage) => usage.inputTokens],
|
|
9950
|
+
["output", (usage) => usage.outputTokens],
|
|
9951
|
+
["cache_read", (usage) => usage.cachedInputTokens],
|
|
9952
|
+
["cache_creation", (usage) => usage.cacheCreationInputTokens]
|
|
9953
|
+
];
|
|
9954
|
+
var isFailedOutcome = (outcome) => outcome !== "ok" && outcome !== "unknown" && outcome !== "cancelled";
|
|
9955
|
+
var deriveMetricObservations = (input) => {
|
|
9956
|
+
const includeSessionId = input.includeSessionId ?? true;
|
|
9957
|
+
const observations = [];
|
|
9958
|
+
const byId = /* @__PURE__ */ new Map();
|
|
9959
|
+
const startsInBatch = /* @__PURE__ */ new Map();
|
|
9960
|
+
for (const event3 of input.events) {
|
|
9961
|
+
byId.set(event3.eventId, event3);
|
|
9962
|
+
if (event3.type === "generation.start") {
|
|
9963
|
+
startsInBatch.set(event3.generationId, {
|
|
9964
|
+
startMillis: event3.occurredAt,
|
|
9965
|
+
requestModel: event3.model.modelId
|
|
9966
|
+
});
|
|
9967
|
+
}
|
|
9968
|
+
}
|
|
9969
|
+
const requestModelOf = (generationId) => startsInBatch.get(generationId)?.requestModel ?? input.generationStarts?.(generationId)?.requestModel;
|
|
9970
|
+
let lastPromptInBatch;
|
|
9971
|
+
for (const event3 of input.events) {
|
|
9972
|
+
if (event3.type === "prompt.submitted") {
|
|
9973
|
+
lastPromptInBatch ??= /* @__PURE__ */ new Map();
|
|
9974
|
+
lastPromptInBatch.set(event3.sessionId, Math.max(lastPromptInBatch.get(event3.sessionId) ?? 0, event3.occurredAt));
|
|
9975
|
+
}
|
|
9976
|
+
}
|
|
9977
|
+
const measuredDurationOf = (end) => {
|
|
9978
|
+
if (end.durationMillis !== void 0) {
|
|
9979
|
+
return end.durationMillis;
|
|
9980
|
+
}
|
|
9981
|
+
const recovered = startsInBatch.has(end.generationId) ? void 0 : input.generationStarts?.(end.generationId);
|
|
9982
|
+
if (recovered !== void 0) {
|
|
9983
|
+
return end.occurredAt - recovered.startMillis;
|
|
9984
|
+
}
|
|
9985
|
+
const turn = lastPromptInBatch?.get(end.sessionId) ?? input.turnStart?.(end.sessionId);
|
|
9986
|
+
return turn === void 0 || turn > end.occurredAt ? void 0 : end.occurredAt - turn;
|
|
9987
|
+
};
|
|
9988
|
+
const push = (event3, instrument, value, attributes) => {
|
|
9989
|
+
if (!Number.isFinite(value) || value < 0) {
|
|
9990
|
+
return;
|
|
9991
|
+
}
|
|
9992
|
+
observations.push({
|
|
9993
|
+
instrument,
|
|
9994
|
+
value,
|
|
9995
|
+
attributes: { ...commonAttributes(event3, input.resource, includeSessionId), ...attributes },
|
|
9996
|
+
timeMillis: event3.occurredAt,
|
|
9997
|
+
sessionId: event3.sessionId
|
|
9998
|
+
});
|
|
9999
|
+
};
|
|
10000
|
+
for (const event3 of input.events) {
|
|
10001
|
+
switch (event3.type) {
|
|
10002
|
+
case "session.start":
|
|
10003
|
+
push(event3, METRIC_SESSIONS, 1, { [ATTR_OTELHOOK_SESSION_KIND]: event3.sessionKind });
|
|
10004
|
+
break;
|
|
10005
|
+
case "tool.end":
|
|
10006
|
+
push(event3, METRIC_TOOL_CALLS, 1, {
|
|
10007
|
+
[ATTR_GEN_AI_TOOL_NAME2]: event3.toolName,
|
|
10008
|
+
[ATTR_OTELHOOK_OUTCOME2]: event3.outcome
|
|
10009
|
+
});
|
|
10010
|
+
break;
|
|
10011
|
+
case "generation.end": {
|
|
10012
|
+
const attributes = generationAttributes(event3, requestModelOf(event3.generationId));
|
|
10013
|
+
const durationMillis = measuredDurationOf(event3);
|
|
10014
|
+
if (durationMillis !== void 0 && durationMillis >= 0) {
|
|
10015
|
+
push(event3, METRIC_OPERATION_DURATION, durationMillis / 1e3, {
|
|
10016
|
+
...attributes,
|
|
10017
|
+
...isFailedOutcome(event3.outcome) ? { [ATTR_ERROR_TYPE2]: event3.outcome } : {}
|
|
10018
|
+
});
|
|
10019
|
+
}
|
|
10020
|
+
if (event3.cost !== void 0 && event3.cost.source === "provider-reported" && event3.cost.currency === "USD") {
|
|
10021
|
+
push(event3, METRIC_COST_USAGE, event3.cost.amount, attributes);
|
|
10022
|
+
}
|
|
10023
|
+
break;
|
|
10024
|
+
}
|
|
10025
|
+
default:
|
|
10026
|
+
break;
|
|
10027
|
+
}
|
|
10028
|
+
}
|
|
10029
|
+
for (const observation of input.usage) {
|
|
10030
|
+
if (observation.scope !== "generation") {
|
|
10031
|
+
continue;
|
|
10032
|
+
}
|
|
10033
|
+
const event3 = byId.get(observation.eventId);
|
|
10034
|
+
if (event3?.type !== "generation.end") {
|
|
10035
|
+
continue;
|
|
10036
|
+
}
|
|
10037
|
+
const attributes = generationAttributes(event3, requestModelOf(event3.generationId));
|
|
10038
|
+
for (const [tokenType, read] of TOKEN_FIELDS) {
|
|
10039
|
+
const value = read(observation.delta);
|
|
10040
|
+
if (value === 0 && (tokenType === "cache_read" || tokenType === "cache_creation")) {
|
|
10041
|
+
continue;
|
|
10042
|
+
}
|
|
10043
|
+
push(event3, METRIC_TOKEN_USAGE, value, { ...attributes, [ATTR_GEN_AI_TOKEN_TYPE]: tokenType });
|
|
10044
|
+
}
|
|
10045
|
+
}
|
|
10046
|
+
return observations;
|
|
10047
|
+
};
|
|
10048
|
+
var emptyHistogram = (boundaries) => ({
|
|
10049
|
+
count: 0,
|
|
10050
|
+
sum: 0,
|
|
10051
|
+
min: Number.POSITIVE_INFINITY,
|
|
10052
|
+
max: Number.NEGATIVE_INFINITY,
|
|
10053
|
+
bucketCounts: new Array(boundaries.length + 1).fill(0)
|
|
10054
|
+
});
|
|
10055
|
+
var bucketIndex = (boundaries, value) => {
|
|
10056
|
+
for (let index = 0; index < boundaries.length; index += 1) {
|
|
10057
|
+
const bound = boundaries[index];
|
|
10058
|
+
if (bound !== void 0 && value <= bound) {
|
|
10059
|
+
return index;
|
|
10060
|
+
}
|
|
10061
|
+
}
|
|
10062
|
+
return boundaries.length;
|
|
10063
|
+
};
|
|
10064
|
+
var recordIntoHistogram = (state, boundaries, value) => {
|
|
10065
|
+
const bucketCounts = [...state.bucketCounts];
|
|
10066
|
+
const index = bucketIndex(boundaries, value);
|
|
10067
|
+
bucketCounts[index] = (bucketCounts[index] ?? 0) + 1;
|
|
10068
|
+
return {
|
|
10069
|
+
count: state.count + 1,
|
|
10070
|
+
sum: state.sum + value,
|
|
10071
|
+
min: Math.min(state.min, value),
|
|
10072
|
+
max: Math.max(state.max, value),
|
|
10073
|
+
bucketCounts
|
|
10074
|
+
};
|
|
10075
|
+
};
|
|
10076
|
+
var seriesIdentity = (instrument, attributes) => JSON.stringify([
|
|
10077
|
+
instrument,
|
|
10078
|
+
Object.entries(attributes).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0)
|
|
10079
|
+
]);
|
|
10080
|
+
var aggregateDeltaPoints = (observations, nowMillis) => {
|
|
10081
|
+
const series = /* @__PURE__ */ new Map();
|
|
10082
|
+
for (const observation of observations) {
|
|
10083
|
+
const instrument = METRIC_INSTRUMENTS[observation.instrument];
|
|
10084
|
+
const key = seriesIdentity(observation.instrument, observation.attributes);
|
|
10085
|
+
const existing = series.get(key) ?? {
|
|
10086
|
+
observation,
|
|
10087
|
+
start: observation.timeMillis,
|
|
10088
|
+
value: 0,
|
|
10089
|
+
...instrument.boundaries === void 0 ? {} : { histogram: emptyHistogram(instrument.boundaries) }
|
|
10090
|
+
};
|
|
10091
|
+
existing.start = Math.min(existing.start, observation.timeMillis);
|
|
10092
|
+
if (existing.histogram !== void 0 && instrument.boundaries !== void 0) {
|
|
10093
|
+
existing.histogram = recordIntoHistogram(existing.histogram, instrument.boundaries, observation.value);
|
|
10094
|
+
} else {
|
|
10095
|
+
existing.value += observation.value;
|
|
10096
|
+
}
|
|
10097
|
+
series.set(key, existing);
|
|
10098
|
+
}
|
|
10099
|
+
return [...series.values()].map((entry) => ({
|
|
10100
|
+
instrument: entry.observation.instrument,
|
|
10101
|
+
temporality: "delta",
|
|
10102
|
+
attributes: entry.observation.attributes,
|
|
10103
|
+
startTimeMillis: Math.min(entry.start, nowMillis),
|
|
10104
|
+
timeMillis: Math.max(nowMillis, entry.start),
|
|
10105
|
+
...entry.histogram === void 0 ? { value: entry.value } : { histogram: entry.histogram }
|
|
10106
|
+
}));
|
|
10107
|
+
};
|
|
10108
|
+
var FORBIDDEN_METRIC_ATTRIBUTE_PREFIXES = Object.freeze([
|
|
10109
|
+
"user.",
|
|
10110
|
+
"enduser.",
|
|
10111
|
+
"organization."
|
|
10112
|
+
]);
|
|
10113
|
+
var withoutAccountIdentity = (attributes) => Object.fromEntries(
|
|
10114
|
+
Object.entries(attributes).filter(
|
|
10115
|
+
([key]) => !FORBIDDEN_METRIC_ATTRIBUTE_PREFIXES.some((prefix) => key.startsWith(prefix))
|
|
10116
|
+
)
|
|
10117
|
+
);
|
|
10118
|
+
|
|
10119
|
+
// src/lifecycle/metric-series.ts
|
|
10120
|
+
var TURN_START_SEGMENT = "turn-start";
|
|
10121
|
+
var SHARED_SCOPE = "all";
|
|
10122
|
+
var SHARED_LOCK = "otelhook.metrics.shared";
|
|
10123
|
+
var sessionScope = (sessionId) => `s=${sessionId}`;
|
|
10124
|
+
var digest2 = (identity) => createHash5("sha256").update(identity).digest("base64url").slice(0, 43);
|
|
10125
|
+
var toStoredHistogram = (histogram) => ({
|
|
10126
|
+
count: histogram.count,
|
|
10127
|
+
sum: histogram.sum,
|
|
10128
|
+
// An empty histogram has infinite min/max, which JSON cannot hold. A stored
|
|
10129
|
+
// histogram always has at least one value, so these are finite in practice.
|
|
10130
|
+
min: Number.isFinite(histogram.min) ? histogram.min : 0,
|
|
10131
|
+
max: Number.isFinite(histogram.max) ? histogram.max : 0,
|
|
10132
|
+
bucketCounts: [...histogram.bucketCounts]
|
|
10133
|
+
});
|
|
10134
|
+
var createMetricSeriesStore = (deps) => {
|
|
10135
|
+
const { stateStore, clock } = deps;
|
|
10136
|
+
const readSeries = async (key) => {
|
|
10137
|
+
const record = await stateStore.read(key);
|
|
10138
|
+
if (record?.value.kind !== "metric-series") {
|
|
10139
|
+
return void 0;
|
|
10140
|
+
}
|
|
10141
|
+
return record.value;
|
|
10142
|
+
};
|
|
10143
|
+
const recordGroup = async (scope, observations, deliveryToken) => {
|
|
10144
|
+
const bySeries = /* @__PURE__ */ new Map();
|
|
10145
|
+
for (const observation of observations) {
|
|
10146
|
+
const identity = seriesIdentity(observation.instrument, observation.attributes);
|
|
10147
|
+
const group = bySeries.get(identity) ?? [];
|
|
10148
|
+
group.push(observation);
|
|
10149
|
+
bySeries.set(identity, group);
|
|
10150
|
+
}
|
|
10151
|
+
const now = clock.now();
|
|
10152
|
+
const points = [];
|
|
10153
|
+
for (const [identity, group] of bySeries) {
|
|
10154
|
+
const first = group[0];
|
|
10155
|
+
if (first === void 0) {
|
|
10156
|
+
continue;
|
|
10157
|
+
}
|
|
10158
|
+
const instrument = METRIC_INSTRUMENTS[first.instrument];
|
|
10159
|
+
const key = metricSeriesKey(scope, digest2(identity));
|
|
10160
|
+
const existing = await readSeries(key);
|
|
10161
|
+
const boundaries = instrument.boundaries;
|
|
10162
|
+
const compatible = existing !== void 0 && (boundaries === void 0 ? existing.value !== void 0 : existing.histogram?.bucketCounts.length === boundaries.length + 1);
|
|
10163
|
+
const base = compatible ? existing : void 0;
|
|
10164
|
+
const replay = deliveryToken !== void 0 && base?.appliedDelivery === deliveryToken;
|
|
10165
|
+
const earliest = Math.min(...group.map((observation) => observation.timeMillis));
|
|
10166
|
+
const startTimeMillis = base?.startTimeMillis ?? Math.min(earliest, now);
|
|
10167
|
+
let value = base?.value ?? 0;
|
|
10168
|
+
let histogram = boundaries === void 0 ? void 0 : base?.histogram === void 0 ? emptyHistogram(boundaries) : base.histogram;
|
|
10169
|
+
if (!replay) {
|
|
10170
|
+
for (const observation of group) {
|
|
10171
|
+
if (histogram !== void 0 && boundaries !== void 0) {
|
|
10172
|
+
histogram = recordIntoHistogram(histogram, boundaries, observation.value);
|
|
10173
|
+
} else {
|
|
10174
|
+
value += observation.value;
|
|
10175
|
+
}
|
|
10176
|
+
}
|
|
10177
|
+
await stateStore.write(key, {
|
|
10178
|
+
kind: "metric-series",
|
|
10179
|
+
startTimeMillis,
|
|
10180
|
+
...histogram === void 0 ? { value } : { histogram: toStoredHistogram(histogram) },
|
|
10181
|
+
...deliveryToken === void 0 ? {} : { appliedDelivery: deliveryToken }
|
|
10182
|
+
});
|
|
10183
|
+
}
|
|
10184
|
+
points.push({
|
|
10185
|
+
instrument: first.instrument,
|
|
10186
|
+
temporality: "cumulative",
|
|
10187
|
+
attributes: first.attributes,
|
|
10188
|
+
startTimeMillis,
|
|
10189
|
+
timeMillis: Math.max(now, startTimeMillis),
|
|
10190
|
+
...histogram === void 0 ? { value } : { histogram }
|
|
10191
|
+
});
|
|
10192
|
+
}
|
|
10193
|
+
return points;
|
|
10194
|
+
};
|
|
10195
|
+
const recordCumulative = async (observations, options) => {
|
|
10196
|
+
if (observations.length === 0) {
|
|
10197
|
+
return [];
|
|
10198
|
+
}
|
|
10199
|
+
if (options?.perSession === false) {
|
|
10200
|
+
return withOptionalSessionLock(
|
|
10201
|
+
stateStore,
|
|
10202
|
+
SHARED_LOCK,
|
|
10203
|
+
() => recordGroup(SHARED_SCOPE, observations, options.deliveryToken)
|
|
10204
|
+
);
|
|
10205
|
+
}
|
|
10206
|
+
const bySession = /* @__PURE__ */ new Map();
|
|
10207
|
+
for (const observation of observations) {
|
|
10208
|
+
const group = bySession.get(observation.sessionId) ?? [];
|
|
10209
|
+
group.push(observation);
|
|
10210
|
+
bySession.set(observation.sessionId, group);
|
|
10211
|
+
}
|
|
10212
|
+
const points = [];
|
|
10213
|
+
for (const [sessionId, group] of bySession) {
|
|
10214
|
+
points.push(
|
|
10215
|
+
...await withOptionalSessionLock(
|
|
10216
|
+
stateStore,
|
|
10217
|
+
sessionId,
|
|
10218
|
+
() => recordGroup(sessionScope(sessionId), group, options?.deliveryToken)
|
|
10219
|
+
)
|
|
10220
|
+
);
|
|
10221
|
+
}
|
|
10222
|
+
return points;
|
|
10223
|
+
};
|
|
10224
|
+
const cleanup = async (maxAgeMillis, options) => {
|
|
10225
|
+
const cap = options?.maxEntries ?? 1e3;
|
|
10226
|
+
const now = clock.now();
|
|
10227
|
+
let removed = 0;
|
|
10228
|
+
let scanned = 0;
|
|
10229
|
+
const prefix = metricSeriesScanPrefix(
|
|
10230
|
+
options?.sessionId === void 0 ? void 0 : sessionScope(options.sessionId)
|
|
10231
|
+
);
|
|
10232
|
+
for (const key of await stateStore.keys(prefix)) {
|
|
10233
|
+
if (scanned >= cap) {
|
|
10234
|
+
break;
|
|
10235
|
+
}
|
|
10236
|
+
scanned += 1;
|
|
10237
|
+
const record = await stateStore.read(key);
|
|
10238
|
+
if (record !== void 0 && now - record.updatedAt > maxAgeMillis) {
|
|
10239
|
+
await stateStore.delete(key);
|
|
10240
|
+
removed += 1;
|
|
10241
|
+
}
|
|
10242
|
+
}
|
|
10243
|
+
return { removed, scanned };
|
|
10244
|
+
};
|
|
10245
|
+
const turnKey = (sessionId) => metricSeriesKey(sessionScope(sessionId), TURN_START_SEGMENT);
|
|
10246
|
+
const recordTurnStart = (sessionId, startMillis) => withOptionalSessionLock(stateStore, sessionId, async () => {
|
|
10247
|
+
const existing = await stateStore.read(turnKey(sessionId));
|
|
10248
|
+
const previous = existing?.value.kind === "attributes" && typeof existing.value.attributes.startMillis === "number" ? existing.value.attributes.startMillis : void 0;
|
|
10249
|
+
if (previous !== void 0 && previous >= startMillis) {
|
|
10250
|
+
return;
|
|
10251
|
+
}
|
|
10252
|
+
await stateStore.write(turnKey(sessionId), { kind: "attributes", attributes: { startMillis } });
|
|
10253
|
+
});
|
|
10254
|
+
const readTurnStart = async (sessionId) => {
|
|
10255
|
+
const record = await stateStore.read(turnKey(sessionId));
|
|
10256
|
+
const value = record?.value.kind === "attributes" ? record.value.attributes.startMillis : void 0;
|
|
10257
|
+
return typeof value === "number" ? value : void 0;
|
|
10258
|
+
};
|
|
10259
|
+
return { recordCumulative, recordTurnStart, readTurnStart, cleanup };
|
|
10260
|
+
};
|
|
10261
|
+
|
|
10262
|
+
// src/lifecycle/janitor.ts
|
|
10263
|
+
var DEFAULT_MAX_AGE_MILLIS = 24 * 60 * 60 * 1e3;
|
|
10264
|
+
var DEFAULT_MAX_ENTRIES_PER_COMPONENT = 1e3;
|
|
10265
|
+
var createLifecycleJanitor = (options) => {
|
|
10266
|
+
const maxEntries = options.maxEntriesPerComponent ?? DEFAULT_MAX_ENTRIES_PER_COMPONENT;
|
|
10267
|
+
const spanMaxAge = options.spanMaxAgeMillis ?? DEFAULT_MAX_AGE_MILLIS;
|
|
10268
|
+
const dedupMaxAge = options.dedupMaxAgeMillis ?? DEFAULT_MAX_AGE_MILLIS;
|
|
10269
|
+
const usageMaxAge = options.usageMaxAgeMillis ?? DEFAULT_MAX_AGE_MILLIS;
|
|
10270
|
+
const runOnce = async (sessionId) => {
|
|
10271
|
+
const scope = { maxEntries, ...sessionId === void 0 ? {} : { sessionId } };
|
|
10272
|
+
const [span, dedup, usage, metrics] = await Promise.all([
|
|
10273
|
+
options.spanCorrelator?.cleanup(spanMaxAge, scope),
|
|
10274
|
+
// Deduplication is deliberately swept across every scope rather than the
|
|
10275
|
+
// ending session's: a delivery scope is a host-chosen namespace or a
|
|
10276
|
+
// digest of provider/installation/session, never a session id, so scoping
|
|
10277
|
+
// this sweep by `sessionId` would match nothing and let records accumulate
|
|
10278
|
+
// forever. The sweep is TTL-driven and still bounded by `maxEntries`.
|
|
10279
|
+
options.deduplicator?.cleanup(dedupMaxAge, {
|
|
10280
|
+
maxEntries,
|
|
10281
|
+
...options.dedupStaleClaimMillis === void 0 ? {} : { staleClaimMillis: options.dedupStaleClaimMillis }
|
|
10282
|
+
}),
|
|
10283
|
+
options.usageAccumulator?.cleanup(usageMaxAge, scope),
|
|
10284
|
+
options.metricSeries?.cleanup(usageMaxAge, scope)
|
|
10285
|
+
]);
|
|
10286
|
+
return {
|
|
10287
|
+
...span === void 0 ? {} : { span },
|
|
10288
|
+
...dedup === void 0 ? {} : { dedup },
|
|
10289
|
+
...usage === void 0 ? {} : { usage },
|
|
10290
|
+
...metrics === void 0 ? {} : { metrics }
|
|
10291
|
+
};
|
|
10292
|
+
};
|
|
10293
|
+
return { runOnce };
|
|
10294
|
+
};
|
|
10295
|
+
|
|
10296
|
+
// src/state/memory-store.ts
|
|
10297
|
+
var createBoundedMemoryStateStore = (options) => {
|
|
10298
|
+
const records = /* @__PURE__ */ new Map();
|
|
10299
|
+
const keyLock = createAsyncLock();
|
|
10300
|
+
const sessionLock = createAsyncLock();
|
|
10301
|
+
const maxEntries = options.maxEntries ?? 1e4;
|
|
10302
|
+
const lockTimeoutMillis = options.lockTimeoutMillis ?? 5e3;
|
|
10303
|
+
const isExpired = (record, now) => options.ttlMillis !== void 0 && now - record.updatedAt > options.ttlMillis;
|
|
10304
|
+
const evictOldestIfOverCapacity = () => {
|
|
10305
|
+
while (records.size > maxEntries) {
|
|
10306
|
+
let oldestKey;
|
|
10307
|
+
let oldestAt = Number.POSITIVE_INFINITY;
|
|
10308
|
+
for (const [key, record] of records) {
|
|
10309
|
+
if (record.updatedAt < oldestAt) {
|
|
10310
|
+
oldestAt = record.updatedAt;
|
|
10311
|
+
oldestKey = key;
|
|
10312
|
+
}
|
|
10313
|
+
}
|
|
10314
|
+
if (oldestKey === void 0) {
|
|
10315
|
+
break;
|
|
10316
|
+
}
|
|
10317
|
+
records.delete(oldestKey);
|
|
10318
|
+
}
|
|
10319
|
+
};
|
|
10320
|
+
return {
|
|
10321
|
+
read: (key) => keyLock.run(key, () => {
|
|
10322
|
+
const record = records.get(key);
|
|
9272
10323
|
if (record === void 0) {
|
|
9273
10324
|
return Promise.resolve(void 0);
|
|
9274
10325
|
}
|
|
@@ -9312,24 +10363,24 @@ var createBoundedMemoryStateStore = (options) => {
|
|
|
9312
10363
|
|
|
9313
10364
|
// src/state/filesystem-store.ts
|
|
9314
10365
|
import { randomBytes as randomBytes2 } from "crypto";
|
|
9315
|
-
import { mkdir, open as
|
|
9316
|
-
import * as
|
|
10366
|
+
import { mkdir, open as open3, readFile, readdir, rename, unlink, writeFile } from "fs/promises";
|
|
10367
|
+
import * as path4 from "path";
|
|
9317
10368
|
|
|
9318
10369
|
// src/state/keys.ts
|
|
9319
|
-
import { createHash as
|
|
10370
|
+
import { createHash as createHash6 } from "crypto";
|
|
9320
10371
|
var SAFE_SEGMENT_PATTERN = /^[A-Za-z0-9_-]{1,128}$/;
|
|
9321
10372
|
var isSafeSegment = (segment) => SAFE_SEGMENT_PATTERN.test(segment);
|
|
9322
10373
|
var sanitizeSegment = (segment) => {
|
|
9323
10374
|
if (isSafeSegment(segment)) {
|
|
9324
10375
|
return segment;
|
|
9325
10376
|
}
|
|
9326
|
-
return `h_${
|
|
10377
|
+
return `h_${createHash6("sha256").update(segment, "utf8").digest("hex").slice(0, 32)}`;
|
|
9327
10378
|
};
|
|
9328
10379
|
var namespaceSegments = (namespace) => [
|
|
9329
10380
|
sanitizeSegment(namespace.providerId),
|
|
9330
10381
|
sanitizeSegment(namespace.installationId)
|
|
9331
10382
|
];
|
|
9332
|
-
var keyDigest = (key) =>
|
|
10383
|
+
var keyDigest = (key) => createHash6("sha256").update(key, "utf8").digest("hex");
|
|
9333
10384
|
|
|
9334
10385
|
// src/state/filesystem-store.ts
|
|
9335
10386
|
var isErrnoException = (thrown, code) => thrown instanceof Error && thrown.code === code;
|
|
@@ -9345,10 +10396,10 @@ var wrapFsError = (thrown, operation) => {
|
|
|
9345
10396
|
};
|
|
9346
10397
|
var createFilesystemStateStore = (options) => {
|
|
9347
10398
|
const [providerSegment, installationSegment] = namespaceSegments(options);
|
|
9348
|
-
const baseDir =
|
|
9349
|
-
const recordsDir =
|
|
9350
|
-
const quarantineDir =
|
|
9351
|
-
const locksDir =
|
|
10399
|
+
const baseDir = path4.join(options.rootDir, providerSegment, installationSegment);
|
|
10400
|
+
const recordsDir = path4.join(baseDir, "records");
|
|
10401
|
+
const quarantineDir = path4.join(baseDir, "quarantine");
|
|
10402
|
+
const locksDir = path4.join(baseDir, "locks");
|
|
9352
10403
|
const lockTimeoutMillis = options.lockTimeoutMillis ?? 5e3;
|
|
9353
10404
|
const lockStaleMillis = options.lockStaleMillis ?? 3e4;
|
|
9354
10405
|
const lockPollIntervalMillis = options.lockPollIntervalMillis ?? 25;
|
|
@@ -9372,11 +10423,11 @@ var createFilesystemStateStore = (options) => {
|
|
|
9372
10423
|
throw wrapFsError(thrown, "ensure-dirs");
|
|
9373
10424
|
}
|
|
9374
10425
|
};
|
|
9375
|
-
const recordPath = (key) =>
|
|
9376
|
-
const tempPath = (key) =>
|
|
9377
|
-
const lockPath = (sessionId) =>
|
|
10426
|
+
const recordPath = (key) => path4.join(recordsDir, `${keyDigest(key)}.json`);
|
|
10427
|
+
const tempPath = (key) => path4.join(recordsDir, `.tmp-${keyDigest(key)}-${randomBytes2(6).toString("hex")}.json`);
|
|
10428
|
+
const lockPath = (sessionId) => path4.join(locksDir, `${sanitizeSegment(sessionId)}.lock`);
|
|
9378
10429
|
const quarantine = async (filePath, key, reason) => {
|
|
9379
|
-
const dest =
|
|
10430
|
+
const dest = path4.join(quarantineDir, `${options.clock.now()}-${keyDigest(key)}-${reason}.json`);
|
|
9380
10431
|
try {
|
|
9381
10432
|
await rename(filePath, dest);
|
|
9382
10433
|
} catch {
|
|
@@ -9440,7 +10491,7 @@ var createFilesystemStateStore = (options) => {
|
|
|
9440
10491
|
const startedAt = options.clock.monotonicMillis();
|
|
9441
10492
|
for (; ; ) {
|
|
9442
10493
|
try {
|
|
9443
|
-
const handle = await
|
|
10494
|
+
const handle = await open3(filePath, "wx");
|
|
9444
10495
|
try {
|
|
9445
10496
|
await handle.writeFile(JSON.stringify({ pid: process.pid, acquiredAt: options.clock.now() }));
|
|
9446
10497
|
} finally {
|
|
@@ -9508,7 +10559,7 @@ var createFilesystemStateStore = (options) => {
|
|
|
9508
10559
|
}
|
|
9509
10560
|
let raw;
|
|
9510
10561
|
try {
|
|
9511
|
-
raw = await readFile(
|
|
10562
|
+
raw = await readFile(path4.join(recordsDir, entry), "utf8");
|
|
9512
10563
|
} catch {
|
|
9513
10564
|
continue;
|
|
9514
10565
|
}
|
|
@@ -9561,7 +10612,7 @@ var createFilesystemStateStore = (options) => {
|
|
|
9561
10612
|
continue;
|
|
9562
10613
|
}
|
|
9563
10614
|
scanned += 1;
|
|
9564
|
-
const filePath =
|
|
10615
|
+
const filePath = path4.join(recordsDir, entry);
|
|
9565
10616
|
try {
|
|
9566
10617
|
const raw = await readFile(filePath, "utf8");
|
|
9567
10618
|
const envelope = JSON.parse(raw);
|
|
@@ -9581,7 +10632,7 @@ var createFilesystemStateStore = (options) => {
|
|
|
9581
10632
|
lockEntries = [];
|
|
9582
10633
|
}
|
|
9583
10634
|
for (const entry of lockEntries) {
|
|
9584
|
-
const filePath =
|
|
10635
|
+
const filePath = path4.join(locksDir, entry);
|
|
9585
10636
|
try {
|
|
9586
10637
|
const raw = await readFile(filePath, "utf8");
|
|
9587
10638
|
const parsed = JSON.parse(raw);
|
|
@@ -9599,8 +10650,8 @@ var createFilesystemStateStore = (options) => {
|
|
|
9599
10650
|
|
|
9600
10651
|
// src/telemetry/spool-queue.ts
|
|
9601
10652
|
import { randomBytes as randomBytes3 } from "crypto";
|
|
9602
|
-
import { mkdir as mkdir2, readFile as readFile2, readdir as readdir2, rename as rename2, stat as
|
|
9603
|
-
import * as
|
|
10653
|
+
import { mkdir as mkdir2, readFile as readFile2, readdir as readdir2, rename as rename2, stat as stat3, unlink as unlink2, writeFile as writeFile2 } from "fs/promises";
|
|
10654
|
+
import * as path5 from "path";
|
|
9604
10655
|
var EMPTY_SPOOL_DROP_COUNTS = Object.freeze({
|
|
9605
10656
|
total: 0,
|
|
9606
10657
|
age: 0,
|
|
@@ -9616,7 +10667,7 @@ var enqueuedAtOf = (fileName) => {
|
|
|
9616
10667
|
var isCount = (value) => typeof value === "number" && Number.isInteger(value) && value >= 0;
|
|
9617
10668
|
var readSpoolDropCounts = async (queueDir) => {
|
|
9618
10669
|
try {
|
|
9619
|
-
const parsed = JSON.parse(await readFile2(
|
|
10670
|
+
const parsed = JSON.parse(await readFile2(path5.join(queueDir, SPOOL_DROPS_FILE), "utf8"));
|
|
9620
10671
|
if (typeof parsed !== "object" || parsed === null) {
|
|
9621
10672
|
return EMPTY_SPOOL_DROP_COUNTS;
|
|
9622
10673
|
}
|
|
@@ -9645,7 +10696,7 @@ var readSpoolQueueStats = async (queueDir) => {
|
|
|
9645
10696
|
let bytes = 0;
|
|
9646
10697
|
for (const file of files) {
|
|
9647
10698
|
try {
|
|
9648
|
-
bytes += (await
|
|
10699
|
+
bytes += (await stat3(path5.join(queueDir, file))).size;
|
|
9649
10700
|
} catch {
|
|
9650
10701
|
}
|
|
9651
10702
|
}
|
|
@@ -9661,8 +10712,8 @@ var DEFAULT_DRAIN_MAX_BATCHES = 20;
|
|
|
9661
10712
|
var isErrnoException2 = (thrown, code) => thrown instanceof Error && thrown.code === code;
|
|
9662
10713
|
var createSpoolQueue = (options) => {
|
|
9663
10714
|
const [providerSegment, installationSegment] = namespaceSegments(options);
|
|
9664
|
-
const queueDir =
|
|
9665
|
-
const corruptDir =
|
|
10715
|
+
const queueDir = path5.join(options.rootDir, providerSegment, installationSegment, options.queueName);
|
|
10716
|
+
const corruptDir = path5.join(
|
|
9666
10717
|
options.rootDir,
|
|
9667
10718
|
providerSegment,
|
|
9668
10719
|
installationSegment,
|
|
@@ -9709,9 +10760,9 @@ var createSpoolQueue = (options) => {
|
|
|
9709
10760
|
[reason]: current[reason] + dropped,
|
|
9710
10761
|
lastDroppedAt: options.clock.now()
|
|
9711
10762
|
};
|
|
9712
|
-
const tmp =
|
|
10763
|
+
const tmp = path5.join(queueDir, `.tmp-${randomBytes3(6).toString("hex")}.drops`);
|
|
9713
10764
|
await writeFile2(tmp, JSON.stringify(next), "utf8");
|
|
9714
|
-
await rename2(tmp,
|
|
10765
|
+
await rename2(tmp, path5.join(queueDir, SPOOL_DROPS_FILE));
|
|
9715
10766
|
} catch {
|
|
9716
10767
|
}
|
|
9717
10768
|
options.logger?.warn("durable spool dropped batches", {
|
|
@@ -9727,7 +10778,7 @@ var createSpoolQueue = (options) => {
|
|
|
9727
10778
|
let bytes = 0;
|
|
9728
10779
|
if (options.maxBytes !== void 0) {
|
|
9729
10780
|
try {
|
|
9730
|
-
bytes = (await
|
|
10781
|
+
bytes = (await stat3(path5.join(queueDir, name))).size;
|
|
9731
10782
|
} catch {
|
|
9732
10783
|
continue;
|
|
9733
10784
|
}
|
|
@@ -9741,7 +10792,7 @@ var createSpoolQueue = (options) => {
|
|
|
9741
10792
|
let removed = 0;
|
|
9742
10793
|
for (const file of files) {
|
|
9743
10794
|
try {
|
|
9744
|
-
await unlink2(
|
|
10795
|
+
await unlink2(path5.join(queueDir, file.name));
|
|
9745
10796
|
removed += 1;
|
|
9746
10797
|
} catch {
|
|
9747
10798
|
}
|
|
@@ -9801,8 +10852,8 @@ var createSpoolQueue = (options) => {
|
|
|
9801
10852
|
}
|
|
9802
10853
|
}
|
|
9803
10854
|
const fileName = `${String(now).padStart(16, "0")}-${randomBytes3(6).toString("hex")}.json`;
|
|
9804
|
-
const target =
|
|
9805
|
-
const tmp =
|
|
10855
|
+
const target = path5.join(queueDir, fileName);
|
|
10856
|
+
const tmp = path5.join(queueDir, `.tmp-${randomBytes3(6).toString("hex")}.json`);
|
|
9806
10857
|
await writeFile2(tmp, serialized, "utf8");
|
|
9807
10858
|
await rename2(tmp, target);
|
|
9808
10859
|
return { spooled: true };
|
|
@@ -9832,7 +10883,7 @@ var createSpoolQueue = (options) => {
|
|
|
9832
10883
|
if (fileName === void 0) {
|
|
9833
10884
|
break;
|
|
9834
10885
|
}
|
|
9835
|
-
const filePath =
|
|
10886
|
+
const filePath = path5.join(queueDir, fileName);
|
|
9836
10887
|
const quarantine = async (rejection) => {
|
|
9837
10888
|
quarantined += 1;
|
|
9838
10889
|
options.logger?.error("durable spool quarantined an unusable batch", {
|
|
@@ -9841,7 +10892,7 @@ var createSpoolQueue = (options) => {
|
|
|
9841
10892
|
"spool.queue": options.queueName
|
|
9842
10893
|
});
|
|
9843
10894
|
try {
|
|
9844
|
-
await rename2(filePath,
|
|
10895
|
+
await rename2(filePath, path5.join(corruptDir, fileName));
|
|
9845
10896
|
} catch {
|
|
9846
10897
|
await unlink2(filePath).catch(() => void 0);
|
|
9847
10898
|
}
|
|
@@ -10288,13 +11339,13 @@ var createOtlpTraceSink = (options) => {
|
|
|
10288
11339
|
import { SeverityNumber, TraceFlags as TraceFlags2 } from "@opentelemetry/api";
|
|
10289
11340
|
import { millisToHrTime as millisToHrTime2 } from "@opentelemetry/core";
|
|
10290
11341
|
import {
|
|
10291
|
-
ATTR_ERROR_TYPE as
|
|
10292
|
-
ATTR_GEN_AI_OPERATION_NAME as
|
|
10293
|
-
ATTR_GEN_AI_REQUEST_MODEL as
|
|
10294
|
-
ATTR_GEN_AI_RESPONSE_MODEL as
|
|
11342
|
+
ATTR_ERROR_TYPE as ATTR_ERROR_TYPE3,
|
|
11343
|
+
ATTR_GEN_AI_OPERATION_NAME as ATTR_GEN_AI_OPERATION_NAME3,
|
|
11344
|
+
ATTR_GEN_AI_REQUEST_MODEL as ATTR_GEN_AI_REQUEST_MODEL3,
|
|
11345
|
+
ATTR_GEN_AI_RESPONSE_MODEL as ATTR_GEN_AI_RESPONSE_MODEL3,
|
|
10295
11346
|
ATTR_GEN_AI_SYSTEM as ATTR_GEN_AI_SYSTEM2,
|
|
10296
11347
|
ATTR_GEN_AI_TOOL_CALL_ID as ATTR_GEN_AI_TOOL_CALL_ID2,
|
|
10297
|
-
ATTR_GEN_AI_TOOL_NAME as
|
|
11348
|
+
ATTR_GEN_AI_TOOL_NAME as ATTR_GEN_AI_TOOL_NAME3,
|
|
10298
11349
|
ATTR_GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS as ATTR_GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS2,
|
|
10299
11350
|
ATTR_GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS as ATTR_GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS2,
|
|
10300
11351
|
ATTR_GEN_AI_USAGE_INPUT_TOKENS as ATTR_GEN_AI_USAGE_INPUT_TOKENS2,
|
|
@@ -10323,14 +11374,14 @@ var ATTR_OTELHOOK_EVENT_ID = "otelhook.event.id";
|
|
|
10323
11374
|
var ATTR_OTELHOOK_EVENT_SEQUENCE = "otelhook.event.sequence";
|
|
10324
11375
|
var ATTR_OTELHOOK_LOG_SIGNAL = "otelhook.log.signal";
|
|
10325
11376
|
var ATTR_OTELHOOK_LOG_MAPPING_VERSION = "otelhook.log.mapping_version";
|
|
10326
|
-
var
|
|
11377
|
+
var ATTR_OTELHOOK_OUTCOME3 = "otelhook.outcome";
|
|
10327
11378
|
var ATTR_OTELHOOK_TOOL_KIND2 = "otelhook.tool.kind";
|
|
10328
11379
|
var ATTR_OTELHOOK_TOOL_PERMISSION = "otelhook.tool.permission_decision";
|
|
10329
11380
|
var ATTR_OTELHOOK_DELEGATION_DEPTH2 = "otelhook.delegation_depth";
|
|
10330
11381
|
var ATTR_OTELHOOK_SUBAGENT_TYPE = "otelhook.subagent.type";
|
|
10331
11382
|
var ATTR_OTELHOOK_AGENT_NAME2 = "otelhook.agent.name";
|
|
10332
11383
|
var ATTR_OTELHOOK_AGENT_VERSION2 = "otelhook.agent.version";
|
|
10333
|
-
var
|
|
11384
|
+
var ATTR_OTELHOOK_SESSION_KIND2 = "otelhook.session.kind";
|
|
10334
11385
|
var ATTR_OTELHOOK_PROMPT_SOURCE = "otelhook.prompt.source";
|
|
10335
11386
|
var ATTR_OTELHOOK_PROMPT_TURN_INDEX = "otelhook.prompt.turn_index";
|
|
10336
11387
|
var ATTR_OTELHOOK_GENERATION_ID2 = "otelhook.generation.id";
|
|
@@ -10474,15 +11525,15 @@ var eventAttributes = (event3) => {
|
|
|
10474
11525
|
switch (event3.type) {
|
|
10475
11526
|
case "session.start":
|
|
10476
11527
|
return {
|
|
10477
|
-
[
|
|
11528
|
+
[ATTR_OTELHOOK_SESSION_KIND2]: event3.sessionKind,
|
|
10478
11529
|
...event3.agentName === void 0 ? {} : { [ATTR_OTELHOOK_AGENT_NAME2]: event3.agentName },
|
|
10479
11530
|
...event3.agentVersion === void 0 ? {} : { [ATTR_OTELHOOK_AGENT_VERSION2]: event3.agentVersion },
|
|
10480
|
-
...event3.model === void 0 ? {} : { [
|
|
11531
|
+
...event3.model === void 0 ? {} : { [ATTR_GEN_AI_REQUEST_MODEL3]: event3.model.modelId },
|
|
10481
11532
|
...targetAttributes(event3)
|
|
10482
11533
|
};
|
|
10483
11534
|
case "session.end":
|
|
10484
11535
|
return {
|
|
10485
|
-
[
|
|
11536
|
+
[ATTR_OTELHOOK_OUTCOME3]: event3.reason,
|
|
10486
11537
|
...usageAttributes2(event3.usage)
|
|
10487
11538
|
};
|
|
10488
11539
|
case "prompt.submitted":
|
|
@@ -10493,24 +11544,25 @@ var eventAttributes = (event3) => {
|
|
|
10493
11544
|
};
|
|
10494
11545
|
case "generation.start":
|
|
10495
11546
|
return {
|
|
10496
|
-
[
|
|
11547
|
+
[ATTR_GEN_AI_OPERATION_NAME3]: "chat",
|
|
10497
11548
|
[ATTR_OTELHOOK_GENERATION_ID2]: event3.generationId,
|
|
10498
|
-
[
|
|
11549
|
+
[ATTR_GEN_AI_REQUEST_MODEL3]: event3.model.modelId,
|
|
10499
11550
|
...event3.model.vendor === void 0 ? {} : { [ATTR_GEN_AI_SYSTEM2]: event3.model.vendor }
|
|
10500
11551
|
};
|
|
10501
11552
|
case "generation.end":
|
|
10502
11553
|
return {
|
|
10503
|
-
[
|
|
11554
|
+
[ATTR_GEN_AI_OPERATION_NAME3]: "chat",
|
|
10504
11555
|
[ATTR_OTELHOOK_GENERATION_ID2]: event3.generationId,
|
|
10505
|
-
[
|
|
11556
|
+
[ATTR_GEN_AI_RESPONSE_MODEL3]: event3.model.modelId,
|
|
10506
11557
|
...event3.model.vendor === void 0 ? {} : { [ATTR_GEN_AI_SYSTEM2]: event3.model.vendor },
|
|
10507
|
-
[
|
|
11558
|
+
[ATTR_OTELHOOK_OUTCOME3]: event3.outcome,
|
|
10508
11559
|
...event3.stopReason === void 0 ? {} : { [ATTR_OTELHOOK_STOP_REASON]: event3.stopReason },
|
|
10509
|
-
...usageAttributes2(event3.usage)
|
|
11560
|
+
...usageAttributes2(event3.usage),
|
|
11561
|
+
...event3.usage === void 0 || event3.usagePartial === void 0 ? {} : { [ATTR_OTELHOOK_USAGE_PARTIAL]: event3.usagePartial }
|
|
10510
11562
|
};
|
|
10511
11563
|
case "tool.start":
|
|
10512
11564
|
return {
|
|
10513
|
-
[
|
|
11565
|
+
[ATTR_GEN_AI_TOOL_NAME3]: event3.toolName,
|
|
10514
11566
|
[ATTR_GEN_AI_TOOL_CALL_ID2]: event3.toolCallId,
|
|
10515
11567
|
[ATTR_OTELHOOK_TOOL_KIND2]: event3.toolKind,
|
|
10516
11568
|
...event3.generationId === void 0 ? {} : { [ATTR_OTELHOOK_GENERATION_ID2]: event3.generationId },
|
|
@@ -10518,9 +11570,9 @@ var eventAttributes = (event3) => {
|
|
|
10518
11570
|
};
|
|
10519
11571
|
case "tool.end":
|
|
10520
11572
|
return {
|
|
10521
|
-
[
|
|
11573
|
+
[ATTR_GEN_AI_TOOL_NAME3]: event3.toolName,
|
|
10522
11574
|
[ATTR_GEN_AI_TOOL_CALL_ID2]: event3.toolCallId,
|
|
10523
|
-
[
|
|
11575
|
+
[ATTR_OTELHOOK_OUTCOME3]: event3.outcome,
|
|
10524
11576
|
...event3.permissionDecision === void 0 ? {} : { [ATTR_OTELHOOK_TOOL_PERMISSION]: event3.permissionDecision },
|
|
10525
11577
|
...targetAttributes(event3)
|
|
10526
11578
|
};
|
|
@@ -10528,11 +11580,11 @@ var eventAttributes = (event3) => {
|
|
|
10528
11580
|
return {
|
|
10529
11581
|
[ATTR_OTELHOOK_DELEGATION_DEPTH2]: event3.delegationDepth,
|
|
10530
11582
|
...event3.subagentType === void 0 ? {} : { [ATTR_OTELHOOK_SUBAGENT_TYPE]: event3.subagentType },
|
|
10531
|
-
...event3.model === void 0 ? {} : { [
|
|
11583
|
+
...event3.model === void 0 ? {} : { [ATTR_GEN_AI_REQUEST_MODEL3]: event3.model.modelId }
|
|
10532
11584
|
};
|
|
10533
11585
|
case "subagent.end":
|
|
10534
11586
|
return {
|
|
10535
|
-
[
|
|
11587
|
+
[ATTR_OTELHOOK_OUTCOME3]: event3.outcome,
|
|
10536
11588
|
...usageAttributes2(event3.usage)
|
|
10537
11589
|
};
|
|
10538
11590
|
case "compaction.performed":
|
|
@@ -10545,7 +11597,7 @@ var eventAttributes = (event3) => {
|
|
|
10545
11597
|
};
|
|
10546
11598
|
case "error.raised":
|
|
10547
11599
|
return {
|
|
10548
|
-
[
|
|
11600
|
+
[ATTR_ERROR_TYPE3]: event3.errorCode,
|
|
10549
11601
|
[ATTR_OTELHOOK_ERROR_PHASE]: event3.phase,
|
|
10550
11602
|
[ATTR_OTELHOOK_ERROR_RETRYABLE]: event3.retryable,
|
|
10551
11603
|
[ATTR_OTELHOOK_ERROR_SEVERITY]: event3.severity
|
|
@@ -11140,8 +12192,356 @@ var shareCorrelationPerBatch = (correlate) => {
|
|
|
11140
12192
|
};
|
|
11141
12193
|
};
|
|
11142
12194
|
|
|
12195
|
+
// src/telemetry/durable-metric-spool.ts
|
|
12196
|
+
var MAX_SPOOLED_METRIC_POINTS_PER_BATCH = 4096;
|
|
12197
|
+
var MAX_STRING_LENGTH = 8192;
|
|
12198
|
+
var MAX_ATTRIBUTES_PER_POINT = 64;
|
|
12199
|
+
var MAX_BUCKETS = 64;
|
|
12200
|
+
var isPlainObject5 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
12201
|
+
var isFiniteNonNegative3 = (value) => typeof value === "number" && Number.isFinite(value) && value >= 0;
|
|
12202
|
+
var isBoundedString3 = (value) => typeof value === "string" && value.length > 0 && value.length <= MAX_STRING_LENGTH;
|
|
12203
|
+
var isPrimitiveAttribute2 = (value) => typeof value === "string" && value.length <= MAX_STRING_LENGTH || typeof value === "number" && Number.isFinite(value) || typeof value === "boolean";
|
|
12204
|
+
var isReplayablePoint = (value) => {
|
|
12205
|
+
if (!isPlainObject5(value) || !isMetricInstrumentName(value.instrument)) {
|
|
12206
|
+
return false;
|
|
12207
|
+
}
|
|
12208
|
+
if (value.temporality !== "cumulative" && value.temporality !== "delta") {
|
|
12209
|
+
return false;
|
|
12210
|
+
}
|
|
12211
|
+
if (!isFiniteNonNegative3(value.startTimeMillis) || !isFiniteNonNegative3(value.timeMillis)) {
|
|
12212
|
+
return false;
|
|
12213
|
+
}
|
|
12214
|
+
if (!isPlainObject5(value.attributes)) {
|
|
12215
|
+
return false;
|
|
12216
|
+
}
|
|
12217
|
+
const entries = Object.entries(value.attributes);
|
|
12218
|
+
if (entries.length > MAX_ATTRIBUTES_PER_POINT || !entries.every(([, item]) => isPrimitiveAttribute2(item))) {
|
|
12219
|
+
return false;
|
|
12220
|
+
}
|
|
12221
|
+
const instrument = METRIC_INSTRUMENTS[value.instrument];
|
|
12222
|
+
if (instrument.kind === "counter") {
|
|
12223
|
+
return isFiniteNonNegative3(value.value) && value.histogram === void 0;
|
|
12224
|
+
}
|
|
12225
|
+
const histogram = value.histogram;
|
|
12226
|
+
if (!isPlainObject5(histogram) || value.value !== void 0) {
|
|
12227
|
+
return false;
|
|
12228
|
+
}
|
|
12229
|
+
const buckets = histogram.bucketCounts;
|
|
12230
|
+
return isFiniteNonNegative3(histogram.count) && Number.isInteger(histogram.count) && isFiniteNonNegative3(histogram.sum) && typeof histogram.min === "number" && typeof histogram.max === "number" && Array.isArray(buckets) && buckets.length <= MAX_BUCKETS && buckets.length === (instrument.boundaries?.length ?? 0) + 1 && buckets.every((count) => isFiniteNonNegative3(count) && Number.isInteger(count));
|
|
12231
|
+
};
|
|
12232
|
+
var validateMetricSpoolBatch = (value, identity) => {
|
|
12233
|
+
if (!isPlainObject5(value)) {
|
|
12234
|
+
return { rejection: "not-an-object" };
|
|
12235
|
+
}
|
|
12236
|
+
if (value.providerId !== identity.providerId || value.installationId !== identity.installationId) {
|
|
12237
|
+
return { rejection: "identity-mismatch" };
|
|
12238
|
+
}
|
|
12239
|
+
if (!isPlainObject5(value.resourceAttributes)) {
|
|
12240
|
+
return { rejection: "resource-attributes-invalid" };
|
|
12241
|
+
}
|
|
12242
|
+
if (!isPlainObject5(value.instrumentationScope) || !isBoundedString3(value.instrumentationScope.name)) {
|
|
12243
|
+
return { rejection: "instrumentation-scope-invalid" };
|
|
12244
|
+
}
|
|
12245
|
+
if (value.instrumentationScope.version !== void 0 && typeof value.instrumentationScope.version !== "string") {
|
|
12246
|
+
return { rejection: "instrumentation-scope-invalid" };
|
|
12247
|
+
}
|
|
12248
|
+
if (!Array.isArray(value.points) || value.points.length === 0 || value.points.length > MAX_SPOOLED_METRIC_POINTS_PER_BATCH) {
|
|
12249
|
+
return { rejection: "points-invalid" };
|
|
12250
|
+
}
|
|
12251
|
+
if (!value.points.every(isReplayablePoint)) {
|
|
12252
|
+
return { rejection: "point-field-invalid" };
|
|
12253
|
+
}
|
|
12254
|
+
if (!isFiniteNonNegative3(value.enqueuedAt)) {
|
|
12255
|
+
return { rejection: "not-an-object" };
|
|
12256
|
+
}
|
|
12257
|
+
return { batch: value };
|
|
12258
|
+
};
|
|
12259
|
+
var DEFAULT_MAX_METRIC_SPOOL_FILES = 500;
|
|
12260
|
+
var createFileDurableMetricSpool = (options) => createSpoolQueue({
|
|
12261
|
+
rootDir: options.rootDir,
|
|
12262
|
+
providerId: options.providerId,
|
|
12263
|
+
installationId: options.installationId,
|
|
12264
|
+
clock: options.clock,
|
|
12265
|
+
...options.logger === void 0 ? {} : { logger: options.logger },
|
|
12266
|
+
maxFiles: options.maxSpoolFiles ?? DEFAULT_MAX_METRIC_SPOOL_FILES,
|
|
12267
|
+
queueName: options.queueName ?? "spool-metrics",
|
|
12268
|
+
...options.maxBytes === void 0 ? {} : { maxBytes: options.maxBytes },
|
|
12269
|
+
...options.maxAgeMillis === void 0 ? {} : { maxAgeMillis: options.maxAgeMillis },
|
|
12270
|
+
...options.overflow === void 0 ? {} : { overflow: options.overflow },
|
|
12271
|
+
validate: validateMetricSpoolBatch
|
|
12272
|
+
});
|
|
12273
|
+
|
|
12274
|
+
// src/telemetry/otlp-metric-sink.ts
|
|
12275
|
+
import { ValueType } from "@opentelemetry/api";
|
|
12276
|
+
import { ExportResultCode as ExportResultCode3, millisToHrTime as millisToHrTime4 } from "@opentelemetry/core";
|
|
12277
|
+
import { OTLPMetricExporter } from "@opentelemetry/exporter-metrics-otlp-proto";
|
|
12278
|
+
import { resourceFromAttributes as resourceFromAttributes2 } from "@opentelemetry/resources";
|
|
12279
|
+
import {
|
|
12280
|
+
AggregationTemporality,
|
|
12281
|
+
DataPointType
|
|
12282
|
+
} from "@opentelemetry/sdk-metrics";
|
|
12283
|
+
var resolveMetricsEndpoint = (exporter) => {
|
|
12284
|
+
const stated = exporter.metrics?.endpoint;
|
|
12285
|
+
if (stated !== void 0) {
|
|
12286
|
+
return { endpoint: stated, derived: false };
|
|
12287
|
+
}
|
|
12288
|
+
if (exporter.endpoint === void 0) {
|
|
12289
|
+
return { unresolvable: "no-endpoint" };
|
|
12290
|
+
}
|
|
12291
|
+
return { endpoint: siblingSignalEndpoint(exporter.endpoint, "metrics"), derived: true };
|
|
12292
|
+
};
|
|
12293
|
+
var describeMetricsDeliverability = (exporter) => {
|
|
12294
|
+
if (exporter.metrics?.enabled !== true) {
|
|
12295
|
+
return { status: "disabled", reason: "metrics-disabled" };
|
|
12296
|
+
}
|
|
12297
|
+
if (!exporter.enabled) {
|
|
12298
|
+
return { status: "disabled", reason: "exporter-disabled" };
|
|
12299
|
+
}
|
|
12300
|
+
if (exporter.protocol === "none") {
|
|
12301
|
+
return { status: "disabled", reason: "protocol-none" };
|
|
12302
|
+
}
|
|
12303
|
+
if (exporter.protocol !== "http/protobuf") {
|
|
12304
|
+
return { status: "disabled", reason: "protocol-unsupported" };
|
|
12305
|
+
}
|
|
12306
|
+
const resolved = resolveMetricsEndpoint(exporter);
|
|
12307
|
+
if ("unresolvable" in resolved) {
|
|
12308
|
+
return { status: "disabled", reason: "no-endpoint" };
|
|
12309
|
+
}
|
|
12310
|
+
return { status: "configured", endpoint: resolved.endpoint, derivedEndpoint: resolved.derived };
|
|
12311
|
+
};
|
|
12312
|
+
var DISABLED_DETAIL2 = Object.freeze({
|
|
12313
|
+
"exporter-disabled": "otlp metric sink disabled: the exporter is disabled",
|
|
12314
|
+
"protocol-none": "otlp metric sink disabled: protocol is none",
|
|
12315
|
+
"protocol-unsupported": "otlp metric sink disabled: protocol not supported by this build",
|
|
12316
|
+
"no-endpoint": "otlp metric sink disabled: no metrics endpoint configured and none could be derived"
|
|
12317
|
+
});
|
|
12318
|
+
var createDisabledMetricSink = (destination) => {
|
|
12319
|
+
const health = createHealthTracker(
|
|
12320
|
+
"telemetry-metric-sink",
|
|
12321
|
+
destination === void 0 ? {} : { destination }
|
|
12322
|
+
);
|
|
12323
|
+
return {
|
|
12324
|
+
enabled: false,
|
|
12325
|
+
exportPoints: () => Promise.resolve({ accepted: 0, rejected: 0, errors: [] }),
|
|
12326
|
+
flush: () => Promise.resolve(),
|
|
12327
|
+
shutdown: () => Promise.resolve(),
|
|
12328
|
+
health: () => health.snapshot(),
|
|
12329
|
+
drainSpool: () => Promise.resolve({ drained: 0, remaining: 0, failed: 0 })
|
|
12330
|
+
};
|
|
12331
|
+
};
|
|
12332
|
+
var createDisabledOtlpMetricSink = createDisabledMetricSink;
|
|
12333
|
+
var toMetricData = (points) => {
|
|
12334
|
+
const byInstrument = /* @__PURE__ */ new Map();
|
|
12335
|
+
for (const point of points) {
|
|
12336
|
+
const key = `${point.instrument}|${point.temporality}`;
|
|
12337
|
+
const group = byInstrument.get(key) ?? [];
|
|
12338
|
+
group.push(point);
|
|
12339
|
+
byInstrument.set(key, group);
|
|
12340
|
+
}
|
|
12341
|
+
const metrics = [];
|
|
12342
|
+
for (const group of byInstrument.values()) {
|
|
12343
|
+
const first = group[0];
|
|
12344
|
+
if (first === void 0) {
|
|
12345
|
+
continue;
|
|
12346
|
+
}
|
|
12347
|
+
const instrument = METRIC_INSTRUMENTS[first.instrument];
|
|
12348
|
+
const descriptor = {
|
|
12349
|
+
name: instrument.name,
|
|
12350
|
+
description: instrument.description,
|
|
12351
|
+
unit: instrument.unit,
|
|
12352
|
+
valueType: instrument.valueType === "int" ? ValueType.INT : ValueType.DOUBLE
|
|
12353
|
+
};
|
|
12354
|
+
const aggregationTemporality = first.temporality === "cumulative" ? AggregationTemporality.CUMULATIVE : AggregationTemporality.DELTA;
|
|
12355
|
+
const times = (point) => ({
|
|
12356
|
+
startTime: millisToHrTime4(point.startTimeMillis),
|
|
12357
|
+
endTime: millisToHrTime4(point.timeMillis)
|
|
12358
|
+
});
|
|
12359
|
+
if (instrument.kind === "counter") {
|
|
12360
|
+
metrics.push({
|
|
12361
|
+
descriptor,
|
|
12362
|
+
aggregationTemporality,
|
|
12363
|
+
dataPointType: DataPointType.SUM,
|
|
12364
|
+
isMonotonic: true,
|
|
12365
|
+
dataPoints: group.map((point) => ({
|
|
12366
|
+
...times(point),
|
|
12367
|
+
attributes: { ...point.attributes },
|
|
12368
|
+
value: point.value ?? 0
|
|
12369
|
+
}))
|
|
12370
|
+
});
|
|
12371
|
+
continue;
|
|
12372
|
+
}
|
|
12373
|
+
metrics.push({
|
|
12374
|
+
descriptor,
|
|
12375
|
+
aggregationTemporality,
|
|
12376
|
+
dataPointType: DataPointType.HISTOGRAM,
|
|
12377
|
+
dataPoints: group.map((point) => {
|
|
12378
|
+
const histogram = point.histogram;
|
|
12379
|
+
return {
|
|
12380
|
+
...times(point),
|
|
12381
|
+
attributes: { ...point.attributes },
|
|
12382
|
+
value: {
|
|
12383
|
+
buckets: {
|
|
12384
|
+
boundaries: [...instrument.boundaries ?? []],
|
|
12385
|
+
counts: [...histogram?.bucketCounts ?? []]
|
|
12386
|
+
},
|
|
12387
|
+
count: histogram?.count ?? 0,
|
|
12388
|
+
sum: histogram?.sum ?? 0,
|
|
12389
|
+
...histogram === void 0 || histogram.count === 0 ? {} : { min: histogram.min, max: histogram.max }
|
|
12390
|
+
}
|
|
12391
|
+
};
|
|
12392
|
+
})
|
|
12393
|
+
});
|
|
12394
|
+
}
|
|
12395
|
+
return metrics;
|
|
12396
|
+
};
|
|
12397
|
+
var createOtlpMetricSink = (options) => {
|
|
12398
|
+
const destinationFields = options.destination === void 0 ? {} : { "export.destination": options.destination };
|
|
12399
|
+
const deliverability = describeMetricsDeliverability(options.exporter);
|
|
12400
|
+
if (deliverability.status === "disabled") {
|
|
12401
|
+
if (deliverability.reason !== "metrics-disabled") {
|
|
12402
|
+
options.logger?.warn(DISABLED_DETAIL2[deliverability.reason], {
|
|
12403
|
+
"exporter.protocol": options.exporter.protocol,
|
|
12404
|
+
...destinationFields
|
|
12405
|
+
});
|
|
12406
|
+
}
|
|
12407
|
+
return createDisabledMetricSink(options.destination);
|
|
12408
|
+
}
|
|
12409
|
+
const scope = options.instrumentationScope ?? DEFAULT_INSTRUMENTATION_SCOPE;
|
|
12410
|
+
const resource = resourceFromAttributes2(
|
|
12411
|
+
withoutAccountIdentity(resourceFromExporterPolicy(options.exporter).attributes)
|
|
12412
|
+
);
|
|
12413
|
+
const health = createHealthTracker(
|
|
12414
|
+
"telemetry-metric-sink",
|
|
12415
|
+
options.destination === void 0 ? {} : { destination: options.destination }
|
|
12416
|
+
);
|
|
12417
|
+
const exporter = new OTLPMetricExporter({
|
|
12418
|
+
url: deliverability.endpoint,
|
|
12419
|
+
headers: { ...options.headers },
|
|
12420
|
+
timeoutMillis: options.exporter.timeoutMillis
|
|
12421
|
+
});
|
|
12422
|
+
let shutdownCompleted = false;
|
|
12423
|
+
const exportResourceMetrics = (points, batchResource, batchScope) => new Promise((resolve5) => {
|
|
12424
|
+
const payload = {
|
|
12425
|
+
resource: batchResource,
|
|
12426
|
+
scopeMetrics: [{ scope: batchScope, metrics: toMetricData(points) }]
|
|
12427
|
+
};
|
|
12428
|
+
try {
|
|
12429
|
+
exporter.export(payload, (result) => resolve5(result));
|
|
12430
|
+
} catch (thrown) {
|
|
12431
|
+
resolve5({
|
|
12432
|
+
code: ExportResultCode3.FAILED,
|
|
12433
|
+
error: thrown instanceof Error ? thrown : new Error("export threw")
|
|
12434
|
+
});
|
|
12435
|
+
}
|
|
12436
|
+
});
|
|
12437
|
+
const toSpoolBatch = (points) => ({
|
|
12438
|
+
providerId: options.providerId,
|
|
12439
|
+
installationId: options.installationId,
|
|
12440
|
+
resourceAttributes: { ...resource.attributes },
|
|
12441
|
+
instrumentationScope: {
|
|
12442
|
+
name: scope.name,
|
|
12443
|
+
...scope.version === void 0 ? {} : { version: scope.version }
|
|
12444
|
+
},
|
|
12445
|
+
points: points.map((point) => ({ ...point })),
|
|
12446
|
+
enqueuedAt: options.clock.now()
|
|
12447
|
+
});
|
|
12448
|
+
const sendSerializedBatch = async (batch) => {
|
|
12449
|
+
const batchResource = resourceFromAttributes2(
|
|
12450
|
+
withoutAccountIdentity(replayResource(batch.resourceAttributes, options.exporter).attributes)
|
|
12451
|
+
);
|
|
12452
|
+
const result = await exportResourceMetrics(batch.points, batchResource, batch.instrumentationScope);
|
|
12453
|
+
if (result.code === ExportResultCode3.SUCCESS) {
|
|
12454
|
+
return true;
|
|
12455
|
+
}
|
|
12456
|
+
return isPermanentExportFailure(result) ? "discard" : false;
|
|
12457
|
+
};
|
|
12458
|
+
const exportPoints = async (points) => {
|
|
12459
|
+
if (points.length === 0) {
|
|
12460
|
+
return { accepted: 0, rejected: 0, errors: [] };
|
|
12461
|
+
}
|
|
12462
|
+
const result = await exportResourceMetrics(points, resource, scope);
|
|
12463
|
+
if (result.code === ExportResultCode3.SUCCESS) {
|
|
12464
|
+
health.recordSuccess(points.length, options.clock.now());
|
|
12465
|
+
return { accepted: points.length, rejected: 0, errors: [] };
|
|
12466
|
+
}
|
|
12467
|
+
health.recordFailure("telemetry-export-failure", points.length, options.clock.now());
|
|
12468
|
+
const permanent = isPermanentExportFailure(result);
|
|
12469
|
+
if (options.spool !== void 0 && !permanent) {
|
|
12470
|
+
const spooled = await options.spool.enqueue(toSpoolBatch(points)).catch(() => ({
|
|
12471
|
+
spooled: false,
|
|
12472
|
+
reason: "capacity-exceeded"
|
|
12473
|
+
}));
|
|
12474
|
+
if (spooled.spooled) {
|
|
12475
|
+
options.logger?.warn("metric batch not delivered; spooled for the next invocation", {
|
|
12476
|
+
"export.batch_size": points.length,
|
|
12477
|
+
...destinationFields
|
|
12478
|
+
});
|
|
12479
|
+
return { accepted: points.length, rejected: 0, errors: [] };
|
|
12480
|
+
}
|
|
12481
|
+
}
|
|
12482
|
+
return {
|
|
12483
|
+
accepted: 0,
|
|
12484
|
+
rejected: points.length,
|
|
12485
|
+
errors: [
|
|
12486
|
+
createErrorInfo({
|
|
12487
|
+
code: "telemetry-export-failure",
|
|
12488
|
+
phase: "export",
|
|
12489
|
+
detail: permanent ? "collector refused a metric batch with a non-retryable status" : "collector rejected or was unreachable for a metric batch",
|
|
12490
|
+
details: {
|
|
12491
|
+
"export.batch_size": points.length,
|
|
12492
|
+
"export.signal": "metrics",
|
|
12493
|
+
...destinationFields
|
|
12494
|
+
}
|
|
12495
|
+
})
|
|
12496
|
+
]
|
|
12497
|
+
};
|
|
12498
|
+
};
|
|
12499
|
+
const drainSpool = async (maxBatches) => {
|
|
12500
|
+
if (options.spool === void 0) {
|
|
12501
|
+
return { drained: 0, remaining: 0, failed: 0 };
|
|
12502
|
+
}
|
|
12503
|
+
const result = await options.spool.drain(sendSerializedBatch, {
|
|
12504
|
+
...maxBatches === void 0 ? {} : { maxBatches }
|
|
12505
|
+
});
|
|
12506
|
+
if (result.drained > 0) {
|
|
12507
|
+
health.recordSuccess(result.drained, options.clock.now());
|
|
12508
|
+
}
|
|
12509
|
+
return result;
|
|
12510
|
+
};
|
|
12511
|
+
const flush = async () => {
|
|
12512
|
+
try {
|
|
12513
|
+
await exporter.forceFlush();
|
|
12514
|
+
} catch {
|
|
12515
|
+
}
|
|
12516
|
+
await drainSpool().catch(() => void 0);
|
|
12517
|
+
};
|
|
12518
|
+
const shutdown = async () => {
|
|
12519
|
+
if (shutdownCompleted) {
|
|
12520
|
+
return;
|
|
12521
|
+
}
|
|
12522
|
+
shutdownCompleted = true;
|
|
12523
|
+
await flush();
|
|
12524
|
+
try {
|
|
12525
|
+
await exporter.shutdown();
|
|
12526
|
+
} catch {
|
|
12527
|
+
}
|
|
12528
|
+
};
|
|
12529
|
+
return {
|
|
12530
|
+
enabled: true,
|
|
12531
|
+
exportPoints,
|
|
12532
|
+
flush,
|
|
12533
|
+
shutdown,
|
|
12534
|
+
health: () => health.snapshot(),
|
|
12535
|
+
drainSpool
|
|
12536
|
+
};
|
|
12537
|
+
};
|
|
12538
|
+
|
|
11143
12539
|
// src/telemetry/export-destinations.ts
|
|
11144
|
-
var spoolQueueNamesFor = (destination) => destination === DEFAULT_DESTINATION_NAME ? { traces: "spool", logs: "spool-logs"
|
|
12540
|
+
var spoolQueueNamesFor = (destination) => destination === DEFAULT_DESTINATION_NAME ? { traces: "spool", logs: "spool-logs", metrics: "spool-metrics" } : {
|
|
12541
|
+
traces: `destinations/${destination}/spool`,
|
|
12542
|
+
logs: `destinations/${destination}/spool-logs`,
|
|
12543
|
+
metrics: `destinations/${destination}/spool-metrics`
|
|
12544
|
+
};
|
|
11145
12545
|
var exporterPolicyForDestination = (exporter, destination) => {
|
|
11146
12546
|
if (destination.source === "exporter") {
|
|
11147
12547
|
return exporter;
|
|
@@ -11158,8 +12558,10 @@ var exporterPolicyForDestination = (exporter, destination) => {
|
|
|
11158
12558
|
});
|
|
11159
12559
|
return "endpoint" in derived ? derived.endpoint : void 0;
|
|
11160
12560
|
})());
|
|
12561
|
+
const { metrics: sharedMetrics, ...rest } = shared;
|
|
12562
|
+
const derivedMetrics = destination.metricsEndpoint ?? (destination.endpoint === void 0 ? void 0 : siblingSignalEndpoint(destination.endpoint, "metrics"));
|
|
11161
12563
|
return {
|
|
11162
|
-
...
|
|
12564
|
+
...rest,
|
|
11163
12565
|
protocol: destination.protocol,
|
|
11164
12566
|
...tracesEndpoint === void 0 ? {} : { endpoint: tracesEndpoint },
|
|
11165
12567
|
headerNames: Object.keys(destination.headers).sort(),
|
|
@@ -11167,6 +12569,11 @@ var exporterPolicyForDestination = (exporter, destination) => {
|
|
|
11167
12569
|
...logs,
|
|
11168
12570
|
enabled: destination.signals.logs,
|
|
11169
12571
|
...derivedLogs === void 0 ? {} : { endpoint: derivedLogs }
|
|
12572
|
+
},
|
|
12573
|
+
metrics: {
|
|
12574
|
+
...effectiveMetricsPolicy({ ...exporter, metrics: sharedMetrics }),
|
|
12575
|
+
enabled: destination.signals.metrics,
|
|
12576
|
+
...derivedMetrics === void 0 ? {} : { endpoint: derivedMetrics }
|
|
11170
12577
|
}
|
|
11171
12578
|
};
|
|
11172
12579
|
};
|
|
@@ -11238,6 +12645,12 @@ var createExportDestinationSinks = (options) => {
|
|
|
11238
12645
|
...bounds,
|
|
11239
12646
|
queueName: queues.logs
|
|
11240
12647
|
});
|
|
12648
|
+
const metricSpool = options.spoolRootDir === void 0 || !destination.signals.metrics ? void 0 : createFileDurableMetricSpool({
|
|
12649
|
+
rootDir: options.spoolRootDir,
|
|
12650
|
+
...shared,
|
|
12651
|
+
...bounds,
|
|
12652
|
+
queueName: queues.metrics
|
|
12653
|
+
});
|
|
11241
12654
|
const sinkShared = {
|
|
11242
12655
|
exporter: policy,
|
|
11243
12656
|
...shared,
|
|
@@ -11255,12 +12668,21 @@ var createExportDestinationSinks = (options) => {
|
|
|
11255
12668
|
...logSpool === void 0 ? {} : { spool: logSpool },
|
|
11256
12669
|
content: options.logContent
|
|
11257
12670
|
});
|
|
12671
|
+
const metrics = destination.signals.metrics ? createOtlpMetricSink({
|
|
12672
|
+
exporter: policy,
|
|
12673
|
+
...shared,
|
|
12674
|
+
...label === void 0 ? {} : { destination: label },
|
|
12675
|
+
...headers === void 0 || Object.keys(headers).length === 0 ? {} : { headers },
|
|
12676
|
+
...metricSpool === void 0 ? {} : { spool: metricSpool }
|
|
12677
|
+
}) : createDisabledOtlpMetricSink(label);
|
|
11258
12678
|
destinations.push({
|
|
11259
12679
|
name: destination.name,
|
|
11260
12680
|
traces,
|
|
11261
12681
|
logs,
|
|
12682
|
+
metrics,
|
|
11262
12683
|
...spool === void 0 ? {} : { spool },
|
|
11263
|
-
...logSpool === void 0 ? {} : { logSpool }
|
|
12684
|
+
...logSpool === void 0 ? {} : { logSpool },
|
|
12685
|
+
...metricSpool === void 0 ? {} : { metricSpool }
|
|
11264
12686
|
});
|
|
11265
12687
|
}
|
|
11266
12688
|
return { destinations, skipped };
|
|
@@ -11418,6 +12840,7 @@ var createHookRuntime = (options) => {
|
|
|
11418
12840
|
privacy,
|
|
11419
12841
|
logger,
|
|
11420
12842
|
installationId: options.installationId,
|
|
12843
|
+
payloadEnrichers: options.payloadEnrichers ?? (readsClaudeTranscriptUsage(options.config) ? [createClaudeTranscriptUsageEnricher()] : []),
|
|
11421
12844
|
...options.worktreeLocator === null ? {} : {
|
|
11422
12845
|
worktreeLocator: options.worktreeLocator ?? createFilesystemWorktreeLocator({ monotonicMillis: () => clock.monotonicMillis() })
|
|
11423
12846
|
}
|
|
@@ -11425,6 +12848,12 @@ var createHookRuntime = (options) => {
|
|
|
11425
12848
|
const hook = createOtelHook({ ...hookDeps, sink });
|
|
11426
12849
|
const deduplicator = createCallbackDeduplicator({ stateStore, clock });
|
|
11427
12850
|
const usageAccumulator = createUsageAccumulator({ stateStore, clock });
|
|
12851
|
+
const metricSeries = createMetricSeriesStore({ stateStore, clock });
|
|
12852
|
+
const metricsPolicy = effectiveMetricsPolicy(options.config.exporter);
|
|
12853
|
+
const metricDestinations = exportDestinations.destinations.filter(
|
|
12854
|
+
(destination) => destination.metrics.enabled
|
|
12855
|
+
);
|
|
12856
|
+
const metricResource = resourceFromExporterPolicy(options.config.exporter);
|
|
11428
12857
|
const deliveryRetentionMillis = options.deliveryRetentionMillis ?? lifecycleMaxAge;
|
|
11429
12858
|
if (deliveryRetentionMillis < staleClaimMillis) {
|
|
11430
12859
|
logger.warn("delivery retention is shorter than the stale-claim window", {
|
|
@@ -11436,6 +12865,7 @@ var createHookRuntime = (options) => {
|
|
|
11436
12865
|
spanCorrelator,
|
|
11437
12866
|
deduplicator,
|
|
11438
12867
|
usageAccumulator,
|
|
12868
|
+
metricSeries,
|
|
11439
12869
|
spanMaxAgeMillis: lifecycleMaxAge,
|
|
11440
12870
|
dedupMaxAgeMillis: deliveryRetentionMillis,
|
|
11441
12871
|
// The *effective* window, not the requested one: a sweep that considered a
|
|
@@ -11446,6 +12876,86 @@ var createHookRuntime = (options) => {
|
|
|
11446
12876
|
});
|
|
11447
12877
|
const deliveryLock = createAsyncLock();
|
|
11448
12878
|
const stateDiagnostic = (thrown) => errorInfoFromThrown(thrown, { code: "state-store-failure", phase: "state", occurredAt: clock.now() });
|
|
12879
|
+
const generationStartsFor = async (events) => {
|
|
12880
|
+
const needed = events.some(
|
|
12881
|
+
(event3) => event3.type === "generation.end" && event3.durationMillis === void 0 && !events.some(
|
|
12882
|
+
(other) => other.type === "generation.start" && other.generationId === event3.generationId
|
|
12883
|
+
)
|
|
12884
|
+
);
|
|
12885
|
+
if (!needed) {
|
|
12886
|
+
return void 0;
|
|
12887
|
+
}
|
|
12888
|
+
try {
|
|
12889
|
+
const starts = /* @__PURE__ */ new Map();
|
|
12890
|
+
for (const correlation of await correlate(events)) {
|
|
12891
|
+
if (correlation.ref.family !== "generation" || correlation.startMillis === void 0) {
|
|
12892
|
+
continue;
|
|
12893
|
+
}
|
|
12894
|
+
const requestModel = correlation.attributes?.["gen_ai.request.model"];
|
|
12895
|
+
starts.set(correlation.ref.scopeKey, {
|
|
12896
|
+
startMillis: correlation.startMillis,
|
|
12897
|
+
...typeof requestModel === "string" ? { requestModel } : {}
|
|
12898
|
+
});
|
|
12899
|
+
}
|
|
12900
|
+
return (generationId) => starts.get(generationId);
|
|
12901
|
+
} catch {
|
|
12902
|
+
return void 0;
|
|
12903
|
+
}
|
|
12904
|
+
};
|
|
12905
|
+
const recordMetrics = async (ingest, deliveryToken, diagnostics) => {
|
|
12906
|
+
if (metricDestinations.length === 0 || ingest.events.length === 0) {
|
|
12907
|
+
return void 0;
|
|
12908
|
+
}
|
|
12909
|
+
try {
|
|
12910
|
+
for (const event3 of ingest.events) {
|
|
12911
|
+
if (event3.type === "prompt.submitted") {
|
|
12912
|
+
await metricSeries.recordTurnStart(event3.sessionId, event3.occurredAt);
|
|
12913
|
+
}
|
|
12914
|
+
}
|
|
12915
|
+
const generationStarts = await generationStartsFor(ingest.events);
|
|
12916
|
+
const turnStarts = /* @__PURE__ */ new Map();
|
|
12917
|
+
for (const event3 of ingest.events) {
|
|
12918
|
+
if (event3.type === "generation.end" && !turnStarts.has(event3.sessionId)) {
|
|
12919
|
+
turnStarts.set(event3.sessionId, await metricSeries.readTurnStart(event3.sessionId));
|
|
12920
|
+
}
|
|
12921
|
+
}
|
|
12922
|
+
const observations = deriveMetricObservations({
|
|
12923
|
+
events: ingest.events,
|
|
12924
|
+
usage: ingest.usageObservations,
|
|
12925
|
+
resource: metricResource,
|
|
12926
|
+
includeSessionId: metricsPolicy.includeSessionId,
|
|
12927
|
+
...generationStarts === void 0 ? {} : { generationStarts },
|
|
12928
|
+
turnStart: (sessionId) => turnStarts.get(sessionId)
|
|
12929
|
+
});
|
|
12930
|
+
if (observations.length === 0) {
|
|
12931
|
+
return void 0;
|
|
12932
|
+
}
|
|
12933
|
+
const points = metricsPolicy.temporality === "delta" ? aggregateDeltaPoints(observations, clock.now()) : await metricSeries.recordCumulative(observations, {
|
|
12934
|
+
perSession: metricsPolicy.includeSessionId,
|
|
12935
|
+
...deliveryToken === void 0 ? {} : { deliveryToken }
|
|
12936
|
+
});
|
|
12937
|
+
const results = await Promise.all(
|
|
12938
|
+
metricDestinations.map(async (destination) => {
|
|
12939
|
+
const result = await destination.metrics.exportPoints(points).catch(
|
|
12940
|
+
(thrown) => ({
|
|
12941
|
+
accepted: 0,
|
|
12942
|
+
rejected: points.length,
|
|
12943
|
+
errors: [
|
|
12944
|
+
errorInfoFromThrown(thrown, { code: "telemetry-export-failure", phase: "export" })
|
|
12945
|
+
]
|
|
12946
|
+
})
|
|
12947
|
+
);
|
|
12948
|
+
diagnostics.push(...result.errors);
|
|
12949
|
+
return { name: destination.name, accepted: result.accepted, rejected: result.rejected };
|
|
12950
|
+
})
|
|
12951
|
+
);
|
|
12952
|
+
return { points: points.length, destinations: results };
|
|
12953
|
+
} catch (thrown) {
|
|
12954
|
+
diagnostics.push(stateDiagnostic(thrown));
|
|
12955
|
+
logger.warn("hook-derived metrics could not be recorded for this callback", {});
|
|
12956
|
+
return void 0;
|
|
12957
|
+
}
|
|
12958
|
+
};
|
|
11449
12959
|
const rollupDeliveryToken = (identity) => {
|
|
11450
12960
|
const token = ids.newOpaqueId(["usage-delivery", identity.scope, identity.callbackId]).replace(/[^A-Za-z0-9_-]/g, "").slice(0, 128);
|
|
11451
12961
|
return token.length === 0 ? void 0 : token;
|
|
@@ -11566,6 +13076,11 @@ var createHookRuntime = (options) => {
|
|
|
11566
13076
|
identity === void 0 ? void 0 : rollupDeliveryToken(identity)
|
|
11567
13077
|
);
|
|
11568
13078
|
}
|
|
13079
|
+
const metrics = !duplicateDelivery && ingest.identity !== void 0 && isCommittable(ingest.durability) ? await recordMetrics(
|
|
13080
|
+
ingest,
|
|
13081
|
+
identity === void 0 ? void 0 : rollupDeliveryToken(identity),
|
|
13082
|
+
diagnostics
|
|
13083
|
+
) : void 0;
|
|
11569
13084
|
if (owned && identity !== void 0) {
|
|
11570
13085
|
try {
|
|
11571
13086
|
if (isCommittable(ingest.durability)) {
|
|
@@ -11632,6 +13147,7 @@ var createHookRuntime = (options) => {
|
|
|
11632
13147
|
duplicateDelivery,
|
|
11633
13148
|
delivery,
|
|
11634
13149
|
usageRollups,
|
|
13150
|
+
...metrics === void 0 ? {} : { metrics },
|
|
11635
13151
|
...cleanup === void 0 ? {} : { cleanup },
|
|
11636
13152
|
diagnostics
|
|
11637
13153
|
};
|
|
@@ -11648,12 +13164,20 @@ var createHookRuntime = (options) => {
|
|
|
11648
13164
|
() => runProcess(input, identified.identity, report, diagnostics)
|
|
11649
13165
|
);
|
|
11650
13166
|
};
|
|
11651
|
-
const snapshots = () =>
|
|
13167
|
+
const snapshots = () => [
|
|
13168
|
+
...sink.health(),
|
|
13169
|
+
...metricDestinations.map((destination) => destination.metrics.health())
|
|
13170
|
+
];
|
|
11652
13171
|
let shutdownReport;
|
|
11653
13172
|
const shutdown = () => {
|
|
11654
13173
|
shutdownReport ??= (async () => {
|
|
11655
13174
|
const raced = await Promise.race([
|
|
11656
|
-
|
|
13175
|
+
Promise.all([
|
|
13176
|
+
hook.shutdown(),
|
|
13177
|
+
// Metric sinks are not behind the hook's sink: they replay their own
|
|
13178
|
+
// spools here, inside the same bounded window.
|
|
13179
|
+
...metricDestinations.map((destination) => destination.metrics.shutdown().catch(() => void 0))
|
|
13180
|
+
]).then(() => "completed"),
|
|
11657
13181
|
delay(flushTimeoutMillis)
|
|
11658
13182
|
]);
|
|
11659
13183
|
if (raced === "timeout") {
|
|
@@ -11683,6 +13207,7 @@ var createHookRuntime = (options) => {
|
|
|
11683
13207
|
deduplicator,
|
|
11684
13208
|
usageAccumulator,
|
|
11685
13209
|
spanCorrelator,
|
|
13210
|
+
metricSeries,
|
|
11686
13211
|
janitor,
|
|
11687
13212
|
process: process_,
|
|
11688
13213
|
shutdown,
|
|
@@ -11691,12 +13216,12 @@ var createHookRuntime = (options) => {
|
|
|
11691
13216
|
};
|
|
11692
13217
|
|
|
11693
13218
|
// src/providers/antigravity/registration.ts
|
|
11694
|
-
var
|
|
13219
|
+
var isPlainObject6 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
11695
13220
|
var mergeAntigravityHookRegistration = (input) => {
|
|
11696
13221
|
const events = input.events ?? ANTIGRAVITY_HOOK_EVENT_NAMES;
|
|
11697
|
-
const base =
|
|
11698
|
-
const existingHooks =
|
|
11699
|
-
let changed = !
|
|
13222
|
+
const base = isPlainObject6(input.existing) ? input.existing : {};
|
|
13223
|
+
const existingHooks = isPlainObject6(base.hooks) ? base.hooks : {};
|
|
13224
|
+
let changed = !isPlainObject6(input.existing) || !isPlainObject6(base.hooks);
|
|
11700
13225
|
const nextHooks = { ...existingHooks };
|
|
11701
13226
|
const identifies = input.identifies ?? ((entry) => entry.command === input.command);
|
|
11702
13227
|
const desired = {
|
|
@@ -11705,7 +13230,7 @@ var mergeAntigravityHookRegistration = (input) => {
|
|
|
11705
13230
|
};
|
|
11706
13231
|
for (const event3 of events) {
|
|
11707
13232
|
const currentList = Array.isArray(existingHooks[event3]) ? [...existingHooks[event3]] : [];
|
|
11708
|
-
const managedIndex = currentList.findIndex((entry) =>
|
|
13233
|
+
const managedIndex = currentList.findIndex((entry) => isPlainObject6(entry) && identifies(entry));
|
|
11709
13234
|
if (managedIndex === -1) {
|
|
11710
13235
|
changed = true;
|
|
11711
13236
|
nextHooks[event3] = [...currentList, desired];
|
|
@@ -11714,7 +13239,7 @@ var mergeAntigravityHookRegistration = (input) => {
|
|
|
11714
13239
|
const managed = currentList[managedIndex];
|
|
11715
13240
|
const updated = { ...managed, ...desired };
|
|
11716
13241
|
const next = currentList.filter(
|
|
11717
|
-
(entry, index) => index === managedIndex || !(
|
|
13242
|
+
(entry, index) => index === managedIndex || !(isPlainObject6(entry) && identifies(entry))
|
|
11718
13243
|
);
|
|
11719
13244
|
next[next.indexOf(managed)] = updated;
|
|
11720
13245
|
const rewritten = Object.entries(desired).some(([key, value]) => managed[key] !== value);
|
|
@@ -11729,8 +13254,8 @@ var mergeAntigravityHookRegistration = (input) => {
|
|
|
11729
13254
|
};
|
|
11730
13255
|
};
|
|
11731
13256
|
var removeAntigravityHookRegistration = (input) => {
|
|
11732
|
-
const base =
|
|
11733
|
-
if (!
|
|
13257
|
+
const base = isPlainObject6(input.existing) ? { ...input.existing } : {};
|
|
13258
|
+
if (!isPlainObject6(base.hooks)) {
|
|
11734
13259
|
return { config: base, changed: false };
|
|
11735
13260
|
}
|
|
11736
13261
|
const nextHooks = { ...base.hooks };
|
|
@@ -11742,7 +13267,7 @@ var removeAntigravityHookRegistration = (input) => {
|
|
|
11742
13267
|
continue;
|
|
11743
13268
|
}
|
|
11744
13269
|
const kept = currentList.filter(
|
|
11745
|
-
(entry) => !(
|
|
13270
|
+
(entry) => !(isPlainObject6(entry) && input.identifies(entry))
|
|
11746
13271
|
);
|
|
11747
13272
|
if (kept.length === currentList.length) {
|
|
11748
13273
|
continue;
|
|
@@ -11767,7 +13292,7 @@ var removeAntigravityHookRegistration = (input) => {
|
|
|
11767
13292
|
};
|
|
11768
13293
|
var readAntigravityHookRegistrations = (existing, identifies) => {
|
|
11769
13294
|
const found = /* @__PURE__ */ new Map();
|
|
11770
|
-
if (!
|
|
13295
|
+
if (!isPlainObject6(existing) || !isPlainObject6(existing.hooks)) {
|
|
11771
13296
|
return found;
|
|
11772
13297
|
}
|
|
11773
13298
|
for (const [event3, list] of Object.entries(existing.hooks)) {
|
|
@@ -11775,7 +13300,7 @@ var readAntigravityHookRegistrations = (existing, identifies) => {
|
|
|
11775
13300
|
continue;
|
|
11776
13301
|
}
|
|
11777
13302
|
const commands = list.filter(
|
|
11778
|
-
(entry) =>
|
|
13303
|
+
(entry) => isPlainObject6(entry) && typeof entry.command === "string" && identifies(entry)
|
|
11779
13304
|
).map((entry) => entry.command);
|
|
11780
13305
|
if (commands.length > 0) {
|
|
11781
13306
|
found.set(event3, commands);
|
|
@@ -11785,10 +13310,10 @@ var readAntigravityHookRegistrations = (existing, identifies) => {
|
|
|
11785
13310
|
};
|
|
11786
13311
|
|
|
11787
13312
|
// src/providers/hook-document.ts
|
|
11788
|
-
var
|
|
13313
|
+
var isPlainObject7 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
11789
13314
|
var normalizeMatcher = (value) => typeof value === "string" && value !== "" && value !== "*" ? value : void 0;
|
|
11790
|
-
var isManaged = (value, identifies) =>
|
|
11791
|
-
var cloneGroup = (value) =>
|
|
13315
|
+
var isManaged = (value, identifies) => isPlainObject7(value) && identifies(value);
|
|
13316
|
+
var cloneGroup = (value) => isPlainObject7(value) && Array.isArray(value.hooks) ? { ...value, hooks: [...value.hooks] } : void 0;
|
|
11792
13317
|
var matchesDesired = (existing, desired) => {
|
|
11793
13318
|
for (const [key, value] of Object.entries(desired)) {
|
|
11794
13319
|
if (existing[key] !== value) {
|
|
@@ -11816,7 +13341,7 @@ var readHooksObject = (base, conflicts) => {
|
|
|
11816
13341
|
if (raw === void 0) {
|
|
11817
13342
|
return {};
|
|
11818
13343
|
}
|
|
11819
|
-
if (!
|
|
13344
|
+
if (!isPlainObject7(raw)) {
|
|
11820
13345
|
conflicts.push({
|
|
11821
13346
|
location: "hooks",
|
|
11822
13347
|
detail: `expected an object keyed by hook event name, found ${Array.isArray(raw) ? "an array" : raw === null ? "null" : typeof raw}`
|
|
@@ -11825,7 +13350,7 @@ var readHooksObject = (base, conflicts) => {
|
|
|
11825
13350
|
}
|
|
11826
13351
|
return { ...raw };
|
|
11827
13352
|
};
|
|
11828
|
-
var pruneEventList = (list) => list.filter((group) => !(
|
|
13353
|
+
var pruneEventList = (list) => list.filter((group) => !(isPlainObject7(group) && Array.isArray(group.hooks) && group.hooks.length === 0));
|
|
11829
13354
|
var finalize = (base, hooks) => {
|
|
11830
13355
|
const next = { ...base };
|
|
11831
13356
|
if (Object.keys(hooks).length === 0) {
|
|
@@ -11836,7 +13361,7 @@ var finalize = (base, hooks) => {
|
|
|
11836
13361
|
return next;
|
|
11837
13362
|
};
|
|
11838
13363
|
var mergeNestedHookRegistration = (input) => {
|
|
11839
|
-
const base =
|
|
13364
|
+
const base = isPlainObject7(input.existing) ? { ...input.existing } : {};
|
|
11840
13365
|
const conflicts = [];
|
|
11841
13366
|
const hooks = readHooksObject(base, conflicts);
|
|
11842
13367
|
if (hooks === void 0) {
|
|
@@ -11852,7 +13377,7 @@ var mergeNestedHookRegistration = (input) => {
|
|
|
11852
13377
|
}
|
|
11853
13378
|
const groups = list.map((group) => cloneGroup(group) ?? group);
|
|
11854
13379
|
const usableGroups = groups.filter(
|
|
11855
|
-
(group) =>
|
|
13380
|
+
(group) => isPlainObject7(group) && Array.isArray(group.hooks)
|
|
11856
13381
|
);
|
|
11857
13382
|
let ownHandler;
|
|
11858
13383
|
let ownGroup;
|
|
@@ -11917,7 +13442,7 @@ var mergeNestedHookRegistration = (input) => {
|
|
|
11917
13442
|
return { document: finalize(base, hooks), changed, changes, conflicts };
|
|
11918
13443
|
};
|
|
11919
13444
|
var removeNestedHookRegistrations = (input) => {
|
|
11920
|
-
const base =
|
|
13445
|
+
const base = isPlainObject7(input.existing) ? { ...input.existing } : {};
|
|
11921
13446
|
const conflicts = [];
|
|
11922
13447
|
const hooks = readHooksObject(base, conflicts);
|
|
11923
13448
|
if (hooks === void 0) {
|
|
@@ -11970,7 +13495,7 @@ var removeNestedHookRegistrations = (input) => {
|
|
|
11970
13495
|
};
|
|
11971
13496
|
var readNestedHookRegistrations = (existing, identifies) => {
|
|
11972
13497
|
const found = /* @__PURE__ */ new Map();
|
|
11973
|
-
if (!
|
|
13498
|
+
if (!isPlainObject7(existing) || !isPlainObject7(existing.hooks)) {
|
|
11974
13499
|
return found;
|
|
11975
13500
|
}
|
|
11976
13501
|
for (const [event3, list] of Object.entries(existing.hooks)) {
|
|
@@ -11979,7 +13504,7 @@ var readNestedHookRegistrations = (existing, identifies) => {
|
|
|
11979
13504
|
}
|
|
11980
13505
|
const commands = [];
|
|
11981
13506
|
for (const group of list) {
|
|
11982
|
-
if (!
|
|
13507
|
+
if (!isPlainObject7(group) || !Array.isArray(group.hooks)) {
|
|
11983
13508
|
continue;
|
|
11984
13509
|
}
|
|
11985
13510
|
for (const handler of group.hooks) {
|
|
@@ -12119,7 +13644,7 @@ var CURSOR_UNREGISTERED_HOOK_EVENTS = Object.freeze({
|
|
|
12119
13644
|
workspaceOpen: "an app-lifecycle hook that carries no conversation_id, so it has no session to attribute telemetry to"
|
|
12120
13645
|
});
|
|
12121
13646
|
var CURSOR_HOOKS_DOCUMENT_VERSION = 1;
|
|
12122
|
-
var
|
|
13647
|
+
var isPlainObject8 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
12123
13648
|
var buildEntry3 = (input) => ({
|
|
12124
13649
|
type: "command",
|
|
12125
13650
|
command: input.command,
|
|
@@ -12128,8 +13653,8 @@ var buildEntry3 = (input) => ({
|
|
|
12128
13653
|
});
|
|
12129
13654
|
var mergeCursorHookRegistration = (input) => {
|
|
12130
13655
|
const events = input.events ?? CURSOR_REGISTRABLE_HOOK_EVENTS;
|
|
12131
|
-
const base =
|
|
12132
|
-
const existingHooks =
|
|
13656
|
+
const base = isPlainObject8(input.existing) ? { ...input.existing } : {};
|
|
13657
|
+
const existingHooks = isPlainObject8(base.hooks) ? base.hooks : {};
|
|
12133
13658
|
const nextHooks = { ...existingHooks };
|
|
12134
13659
|
const desired = buildEntry3(input);
|
|
12135
13660
|
let changed = false;
|
|
@@ -12140,7 +13665,7 @@ var mergeCursorHookRegistration = (input) => {
|
|
|
12140
13665
|
for (const event3 of events) {
|
|
12141
13666
|
const currentList = Array.isArray(existingHooks[event3]) ? [...existingHooks[event3]] : [];
|
|
12142
13667
|
const managed = currentList.filter(
|
|
12143
|
-
(entry) =>
|
|
13668
|
+
(entry) => isPlainObject8(entry) && input.identifies(entry)
|
|
12144
13669
|
);
|
|
12145
13670
|
const [ours] = managed;
|
|
12146
13671
|
if (ours === void 0) {
|
|
@@ -12149,7 +13674,7 @@ var mergeCursorHookRegistration = (input) => {
|
|
|
12149
13674
|
continue;
|
|
12150
13675
|
}
|
|
12151
13676
|
const rewritten = { ...ours, ...desired };
|
|
12152
|
-
const next = currentList.filter((entry) => entry === ours || !(
|
|
13677
|
+
const next = currentList.filter((entry) => entry === ours || !(isPlainObject8(entry) && input.identifies(entry))).map((entry) => entry === ours ? rewritten : entry);
|
|
12153
13678
|
const entryChanged = Object.entries(desired).some(([key, value]) => ours[key] !== value);
|
|
12154
13679
|
if (entryChanged || managed.length > 1) {
|
|
12155
13680
|
changed = true;
|
|
@@ -12159,8 +13684,8 @@ var mergeCursorHookRegistration = (input) => {
|
|
|
12159
13684
|
return { config: { ...base, hooks: nextHooks }, changed };
|
|
12160
13685
|
};
|
|
12161
13686
|
var removeCursorHookRegistration = (input) => {
|
|
12162
|
-
const base =
|
|
12163
|
-
if (!
|
|
13687
|
+
const base = isPlainObject8(input.existing) ? { ...input.existing } : {};
|
|
13688
|
+
if (!isPlainObject8(base.hooks)) {
|
|
12164
13689
|
return { config: base, changed: false };
|
|
12165
13690
|
}
|
|
12166
13691
|
const nextHooks = { ...base.hooks };
|
|
@@ -12172,7 +13697,7 @@ var removeCursorHookRegistration = (input) => {
|
|
|
12172
13697
|
continue;
|
|
12173
13698
|
}
|
|
12174
13699
|
const kept = currentList.filter(
|
|
12175
|
-
(entry) => !(
|
|
13700
|
+
(entry) => !(isPlainObject8(entry) && input.identifies(entry))
|
|
12176
13701
|
);
|
|
12177
13702
|
if (kept.length === currentList.length) {
|
|
12178
13703
|
continue;
|
|
@@ -12200,7 +13725,7 @@ var removeCursorHookRegistration = (input) => {
|
|
|
12200
13725
|
};
|
|
12201
13726
|
var readCursorHookRegistrations = (existing, identifies) => {
|
|
12202
13727
|
const found = /* @__PURE__ */ new Map();
|
|
12203
|
-
if (!
|
|
13728
|
+
if (!isPlainObject8(existing) || !isPlainObject8(existing.hooks)) {
|
|
12204
13729
|
return found;
|
|
12205
13730
|
}
|
|
12206
13731
|
for (const [event3, list] of Object.entries(existing.hooks)) {
|
|
@@ -12208,7 +13733,7 @@ var readCursorHookRegistrations = (existing, identifies) => {
|
|
|
12208
13733
|
continue;
|
|
12209
13734
|
}
|
|
12210
13735
|
const commands = list.filter(
|
|
12211
|
-
(entry) =>
|
|
13736
|
+
(entry) => isPlainObject8(entry) && typeof entry.command === "string" && identifies(entry)
|
|
12212
13737
|
).map((entry) => entry.command);
|
|
12213
13738
|
if (commands.length > 0) {
|
|
12214
13739
|
found.set(event3, commands);
|
|
@@ -12308,7 +13833,7 @@ var managedHookPredicate = (marker) => {
|
|
|
12308
13833
|
}
|
|
12309
13834
|
return (handler) => handler.name === MANAGED_HOOK_NAME || typeof handler.command === "string" && handler.command.includes(marker);
|
|
12310
13835
|
};
|
|
12311
|
-
var
|
|
13836
|
+
var isPlainObject9 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
12312
13837
|
var adaptFlatResult = (read, existing, events, identifies, result, removal) => {
|
|
12313
13838
|
const before = read(existing, identifies);
|
|
12314
13839
|
const after = read(result.config, identifies);
|
|
@@ -12332,10 +13857,10 @@ var adaptFlatResult = (read, existing, events, identifies, result, removal) => {
|
|
|
12332
13857
|
return { document: result.config, changed: result.changed, changes, conflicts: [] };
|
|
12333
13858
|
};
|
|
12334
13859
|
var flatHookConflicts = (existing) => {
|
|
12335
|
-
if (!
|
|
13860
|
+
if (!isPlainObject9(existing) || existing.hooks === void 0) {
|
|
12336
13861
|
return [];
|
|
12337
13862
|
}
|
|
12338
|
-
if (!
|
|
13863
|
+
if (!isPlainObject9(existing.hooks)) {
|
|
12339
13864
|
return [
|
|
12340
13865
|
{
|
|
12341
13866
|
location: "hooks",
|
|
@@ -12355,7 +13880,7 @@ var flatHookConflicts = (existing) => {
|
|
|
12355
13880
|
return conflicts;
|
|
12356
13881
|
};
|
|
12357
13882
|
var asAntigravityEvents = (events) => events;
|
|
12358
|
-
var documentEventNames = (existing) =>
|
|
13883
|
+
var documentEventNames = (existing) => isPlainObject9(existing) && isPlainObject9(existing.hooks) ? Object.keys(existing.hooks) : [];
|
|
12359
13884
|
var PLANNERS = Object.freeze([
|
|
12360
13885
|
Object.freeze({
|
|
12361
13886
|
providerId: ANTIGRAVITY_PROVIDER_ID,
|
|
@@ -12364,7 +13889,7 @@ var PLANNERS = Object.freeze([
|
|
|
12364
13889
|
const conflicts = flatHookConflicts(input.existing);
|
|
12365
13890
|
if (conflicts.length > 0) {
|
|
12366
13891
|
return {
|
|
12367
|
-
document:
|
|
13892
|
+
document: isPlainObject9(input.existing) ? input.existing : {},
|
|
12368
13893
|
changed: false,
|
|
12369
13894
|
changes: [],
|
|
12370
13895
|
conflicts
|
|
@@ -12390,7 +13915,7 @@ var PLANNERS = Object.freeze([
|
|
|
12390
13915
|
const conflicts = flatHookConflicts(input.existing);
|
|
12391
13916
|
if (conflicts.length > 0) {
|
|
12392
13917
|
return {
|
|
12393
|
-
document:
|
|
13918
|
+
document: isPlainObject9(input.existing) ? input.existing : {},
|
|
12394
13919
|
changed: false,
|
|
12395
13920
|
changes: [],
|
|
12396
13921
|
conflicts
|
|
@@ -12433,7 +13958,7 @@ var PLANNERS = Object.freeze([
|
|
|
12433
13958
|
const conflicts = flatHookConflicts(input.existing);
|
|
12434
13959
|
if (conflicts.length > 0) {
|
|
12435
13960
|
return {
|
|
12436
|
-
document:
|
|
13961
|
+
document: isPlainObject9(input.existing) ? input.existing : {},
|
|
12437
13962
|
changed: false,
|
|
12438
13963
|
changes: [],
|
|
12439
13964
|
conflicts
|
|
@@ -12460,7 +13985,7 @@ var PLANNERS = Object.freeze([
|
|
|
12460
13985
|
const conflicts = flatHookConflicts(input.existing);
|
|
12461
13986
|
if (conflicts.length > 0) {
|
|
12462
13987
|
return {
|
|
12463
|
-
document:
|
|
13988
|
+
document: isPlainObject9(input.existing) ? input.existing : {},
|
|
12464
13989
|
changed: false,
|
|
12465
13990
|
changes: [],
|
|
12466
13991
|
conflicts
|
|
@@ -12551,7 +14076,7 @@ var SUPPORTED_REGISTRATION_PROVIDER_IDS = Object.freeze(
|
|
|
12551
14076
|
);
|
|
12552
14077
|
|
|
12553
14078
|
// src/install/scopes.ts
|
|
12554
|
-
import * as
|
|
14079
|
+
import * as path6 from "path";
|
|
12555
14080
|
var REGISTRATION_SCOPES = Object.freeze([
|
|
12556
14081
|
"global",
|
|
12557
14082
|
"project"
|
|
@@ -12619,15 +14144,15 @@ var PROVIDERS_WITH_VERIFIED_LOCATION = Object.freeze([
|
|
|
12619
14144
|
var findInstallLocation = (providerId, scope) => PROVIDER_INSTALL_LOCATIONS.find(
|
|
12620
14145
|
(entry) => entry.providerId === providerId && entry.scope === scope
|
|
12621
14146
|
);
|
|
12622
|
-
var resolveInstallPath = (location, roots) =>
|
|
14147
|
+
var resolveInstallPath = (location, roots) => path6.resolve(
|
|
12623
14148
|
location.scope === "global" ? roots.homeDir : roots.projectDir,
|
|
12624
14149
|
...location.segments
|
|
12625
14150
|
);
|
|
12626
14151
|
|
|
12627
14152
|
// src/install/document.ts
|
|
12628
14153
|
import { randomBytes as randomBytes4 } from "crypto";
|
|
12629
|
-
import { chmod, mkdir as mkdir3, open as
|
|
12630
|
-
import * as
|
|
14154
|
+
import { chmod, mkdir as mkdir3, open as open4, readFile as readFile3, rename as rename3, stat as stat4, unlink as unlink3 } from "fs/promises";
|
|
14155
|
+
import * as path7 from "path";
|
|
12631
14156
|
var DEFAULT_DOCUMENT_FORMAT = Object.freeze({
|
|
12632
14157
|
indent: " ",
|
|
12633
14158
|
eol: "\n",
|
|
@@ -12698,15 +14223,15 @@ var renameWithRetry = async (from, to) => {
|
|
|
12698
14223
|
var NEW_DOCUMENT_MODE = 384;
|
|
12699
14224
|
var TEMPORARY_DOCUMENT_MODE = 384;
|
|
12700
14225
|
var writeDocumentAtomically = async (filePath, contents) => {
|
|
12701
|
-
const directory =
|
|
14226
|
+
const directory = path7.dirname(filePath);
|
|
12702
14227
|
await mkdir3(directory, { recursive: true });
|
|
12703
|
-
const temporary =
|
|
14228
|
+
const temporary = path7.join(
|
|
12704
14229
|
directory,
|
|
12705
|
-
`.${
|
|
14230
|
+
`.${path7.basename(filePath)}.${randomBytes4(6).toString("hex")}.tmp`
|
|
12706
14231
|
);
|
|
12707
14232
|
let existingMode;
|
|
12708
14233
|
try {
|
|
12709
|
-
existingMode = (await
|
|
14234
|
+
existingMode = (await stat4(filePath)).mode & 4095;
|
|
12710
14235
|
} catch (thrown) {
|
|
12711
14236
|
if (!isErrnoException3(thrown, "ENOENT")) {
|
|
12712
14237
|
throw thrown;
|
|
@@ -12714,7 +14239,7 @@ var writeDocumentAtomically = async (filePath, contents) => {
|
|
|
12714
14239
|
}
|
|
12715
14240
|
const targetMode = existingMode ?? NEW_DOCUMENT_MODE;
|
|
12716
14241
|
try {
|
|
12717
|
-
const handle = await
|
|
14242
|
+
const handle = await open4(temporary, "wx", TEMPORARY_DOCUMENT_MODE);
|
|
12718
14243
|
try {
|
|
12719
14244
|
await handle.writeFile(contents, "utf8");
|
|
12720
14245
|
await handle.sync();
|
|
@@ -12731,12 +14256,12 @@ var writeDocumentAtomically = async (filePath, contents) => {
|
|
|
12731
14256
|
|
|
12732
14257
|
// src/install/file-lock.ts
|
|
12733
14258
|
import { randomBytes as randomBytes5 } from "crypto";
|
|
12734
|
-
import { mkdir as mkdir4, open as
|
|
12735
|
-
import * as
|
|
14259
|
+
import { mkdir as mkdir4, open as open5, readFile as readFile4, rename as rename4, stat as stat5, unlink as unlink4 } from "fs/promises";
|
|
14260
|
+
import * as path8 from "path";
|
|
12736
14261
|
var FileLockTimeoutError = class extends Error {
|
|
12737
14262
|
constructor(lockPath, timeoutMillis) {
|
|
12738
14263
|
super(
|
|
12739
|
-
`timed out after ${String(timeoutMillis)}ms waiting for the lock on ${
|
|
14264
|
+
`timed out after ${String(timeoutMillis)}ms waiting for the lock on ${path8.basename(lockPath)}`
|
|
12740
14265
|
);
|
|
12741
14266
|
this.name = "FileLockTimeoutError";
|
|
12742
14267
|
}
|
|
@@ -12796,7 +14321,7 @@ var isStale = async (lockPath, clock, staleMillis) => {
|
|
|
12796
14321
|
} catch {
|
|
12797
14322
|
}
|
|
12798
14323
|
try {
|
|
12799
|
-
const stats = await
|
|
14324
|
+
const stats = await stat5(lockPath);
|
|
12800
14325
|
return { stale: clock.now() - stats.mtimeMs > staleMillis };
|
|
12801
14326
|
} catch (thrown) {
|
|
12802
14327
|
return { stale: !isErrnoException4(thrown, "ENOENT") };
|
|
@@ -12808,12 +14333,12 @@ var withFileLock = async (filePath, options, fn) => {
|
|
|
12808
14333
|
const pollIntervalMillis = options.pollIntervalMillis ?? 25;
|
|
12809
14334
|
const lockPath = lockPathFor(filePath);
|
|
12810
14335
|
const startedAt = options.clock.monotonicMillis();
|
|
12811
|
-
await mkdir4(
|
|
14336
|
+
await mkdir4(path8.dirname(filePath), { recursive: true });
|
|
12812
14337
|
for (; ; ) {
|
|
12813
14338
|
const token = randomBytes5(16).toString("hex");
|
|
12814
14339
|
let acquired = false;
|
|
12815
14340
|
try {
|
|
12816
|
-
const handle = await
|
|
14341
|
+
const handle = await open5(lockPath, "wx", 384);
|
|
12817
14342
|
try {
|
|
12818
14343
|
const contents = {
|
|
12819
14344
|
token,
|
|
@@ -12856,7 +14381,7 @@ var withFileLock = async (filePath, options, fn) => {
|
|
|
12856
14381
|
|
|
12857
14382
|
// src/install/lifecycle.ts
|
|
12858
14383
|
import { readFile as readFile5 } from "fs/promises";
|
|
12859
|
-
import * as
|
|
14384
|
+
import * as path9 from "path";
|
|
12860
14385
|
var defaultHookCommand = (providerId) => `otel-hook run --provider ${providerId}`;
|
|
12861
14386
|
var unsupportedOutcome = (providerId, scope, reason) => ({
|
|
12862
14387
|
providerId,
|
|
@@ -12873,7 +14398,7 @@ var unsupportedOutcome = (providerId, scope, reason) => ({
|
|
|
12873
14398
|
var resolveTarget = (providerId, scope, request) => {
|
|
12874
14399
|
if (request.configFile !== void 0) {
|
|
12875
14400
|
return {
|
|
12876
|
-
configPath:
|
|
14401
|
+
configPath: path9.resolve(request.configFile),
|
|
12877
14402
|
evidence: "path supplied by the caller with --settings-file"
|
|
12878
14403
|
};
|
|
12879
14404
|
}
|
|
@@ -12890,14 +14415,14 @@ var resolveTarget = (providerId, scope, request) => {
|
|
|
12890
14415
|
};
|
|
12891
14416
|
};
|
|
12892
14417
|
var codexFeatureNote = async (configPath) => {
|
|
12893
|
-
const tomlPath =
|
|
14418
|
+
const tomlPath = path9.join(path9.dirname(configPath), "config.toml");
|
|
12894
14419
|
let raw;
|
|
12895
14420
|
try {
|
|
12896
14421
|
raw = await readFile5(tomlPath, "utf8");
|
|
12897
14422
|
} catch {
|
|
12898
14423
|
return void 0;
|
|
12899
14424
|
}
|
|
12900
|
-
return readCodexHooksFeatureFlag(raw) === "disabled" ? `${
|
|
14425
|
+
return readCodexHooksFeatureFlag(raw) === "disabled" ? `${path9.basename(tomlPath)} sets [features] hooks = false; registered hooks will not fire until that is removed` : void 0;
|
|
12901
14426
|
};
|
|
12902
14427
|
var readState = async (configPath) => {
|
|
12903
14428
|
const read = await readJsonDocument(configPath);
|
|
@@ -12909,12 +14434,12 @@ var readState = async (configPath) => {
|
|
|
12909
14434
|
case "unparseable":
|
|
12910
14435
|
return {
|
|
12911
14436
|
status: "blocked",
|
|
12912
|
-
problem: `${
|
|
14437
|
+
problem: `${path9.basename(configPath)} is not well-formed JSON (${read.detail}); it was left untouched`
|
|
12913
14438
|
};
|
|
12914
14439
|
case "unreadable":
|
|
12915
14440
|
return {
|
|
12916
14441
|
status: "failed",
|
|
12917
|
-
problem: `${
|
|
14442
|
+
problem: `${path9.basename(configPath)} could not be read (${read.detail})`
|
|
12918
14443
|
};
|
|
12919
14444
|
}
|
|
12920
14445
|
};
|
|
@@ -13026,7 +14551,7 @@ var runOneTarget = async (providerId, scope, request, command) => {
|
|
|
13026
14551
|
missingEvents: [],
|
|
13027
14552
|
notes,
|
|
13028
14553
|
problems: planned.conflicts.map(
|
|
13029
|
-
(conflict) => `${
|
|
14554
|
+
(conflict) => `${path9.basename(configPath)} has an unexpected shape at ${conflict.location}: ${conflict.detail}; it was left untouched`
|
|
13030
14555
|
)
|
|
13031
14556
|
};
|
|
13032
14557
|
}
|
|
@@ -13037,7 +14562,7 @@ var runOneTarget = async (providerId, scope, request, command) => {
|
|
|
13037
14562
|
changed: false,
|
|
13038
14563
|
registeredEvents: [],
|
|
13039
14564
|
missingEvents: [],
|
|
13040
|
-
notes: [...notes, `${
|
|
14565
|
+
notes: [...notes, `${path9.basename(configPath)} does not exist; nothing to remove`],
|
|
13041
14566
|
problems: []
|
|
13042
14567
|
};
|
|
13043
14568
|
}
|
|
@@ -13080,7 +14605,7 @@ var runOneTarget = async (providerId, scope, request, command) => {
|
|
|
13080
14605
|
missingEvents: [],
|
|
13081
14606
|
notes,
|
|
13082
14607
|
problems: [
|
|
13083
|
-
`could not write ${
|
|
14608
|
+
`could not write ${path9.basename(configPath)} (${thrown instanceof Error ? thrown.name : typeof thrown})`
|
|
13084
14609
|
]
|
|
13085
14610
|
};
|
|
13086
14611
|
}
|
|
@@ -13107,7 +14632,7 @@ var runOneTarget = async (providerId, scope, request, command) => {
|
|
|
13107
14632
|
missingEvents: [],
|
|
13108
14633
|
notes,
|
|
13109
14634
|
problems: [
|
|
13110
|
-
thrown instanceof Error ? `${
|
|
14635
|
+
thrown instanceof Error ? `${path9.basename(configPath)}: ${thrown.message}` : `${path9.basename(configPath)}: the configuration file could not be locked`
|
|
13111
14636
|
]
|
|
13112
14637
|
};
|
|
13113
14638
|
}
|
|
@@ -13200,6 +14725,7 @@ export {
|
|
|
13200
14725
|
CLAUDE_HOOK_EVENTS_MODELLED,
|
|
13201
14726
|
CLAUDE_HOOK_EVENT_NAMES,
|
|
13202
14727
|
CLAUDE_REGISTRABLE_HOOK_EVENTS,
|
|
14728
|
+
CLAUDE_TRANSCRIPT_USAGE_ENRICHER_ID,
|
|
13203
14729
|
CLAUDE_UNREGISTERED_HOOK_EVENTS,
|
|
13204
14730
|
CODEX_ADAPTER_VERSION,
|
|
13205
14731
|
CODEX_CAPABILITIES,
|
|
@@ -13221,8 +14747,13 @@ export {
|
|
|
13221
14747
|
CURSOR_REGISTRABLE_HOOK_EVENTS,
|
|
13222
14748
|
CURSOR_UNMODELLED_HOOK_EVENT_NAMES,
|
|
13223
14749
|
CURSOR_UNREGISTERED_HOOK_EVENTS,
|
|
14750
|
+
DEFAULT_CLAUDE_TRANSCRIPT_RANGE_BYTES,
|
|
14751
|
+
DEFAULT_CLAUDE_TRANSCRIPT_RANGE_TIMEOUT_MILLIS,
|
|
14752
|
+
DEFAULT_CLAUDE_TRANSCRIPT_TAIL_BYTES,
|
|
14753
|
+
DEFAULT_CLAUDE_TRANSCRIPT_TIMEOUT_MILLIS,
|
|
13224
14754
|
DEFAULT_CONFIG,
|
|
13225
14755
|
DEFAULT_DESTINATION_NAME,
|
|
14756
|
+
DEFAULT_DESTINATION_SIGNALS,
|
|
13226
14757
|
DEFAULT_DETECTION_POLICY,
|
|
13227
14758
|
DEFAULT_DIAGNOSTICS_POLICY,
|
|
13228
14759
|
DEFAULT_DOCUMENT_FORMAT,
|
|
@@ -13231,8 +14762,10 @@ export {
|
|
|
13231
14762
|
DEFAULT_INSTRUMENTATION_SCOPE,
|
|
13232
14763
|
DEFAULT_LOGS_POLICY,
|
|
13233
14764
|
DEFAULT_MANAGED_COMMAND_MARKER,
|
|
14765
|
+
DEFAULT_METRICS_POLICY,
|
|
13234
14766
|
DEFAULT_PRIVACY_LIMITS,
|
|
13235
14767
|
DEFAULT_PRIVACY_POLICY,
|
|
14768
|
+
DEFAULT_PROVIDERS_POLICY,
|
|
13236
14769
|
DEFAULT_SECRET_KEY_PATTERNS,
|
|
13237
14770
|
DEFAULT_SECRET_VALUE_PATTERNS,
|
|
13238
14771
|
DEFAULT_SPOOL_POLICY,
|
|
@@ -13281,7 +14814,14 @@ export {
|
|
|
13281
14814
|
MAX_TARGET_PATH_LENGTH,
|
|
13282
14815
|
MAX_WORKTREE_WALK_DEPTH,
|
|
13283
14816
|
MCP_TOOL_NAME_PATTERN,
|
|
14817
|
+
METRIC_COST_USAGE,
|
|
14818
|
+
METRIC_INSTRUMENTS,
|
|
14819
|
+
METRIC_OPERATION_DURATION,
|
|
14820
|
+
METRIC_SESSIONS,
|
|
14821
|
+
METRIC_TOKEN_USAGE,
|
|
14822
|
+
METRIC_TOOL_CALLS,
|
|
13284
14823
|
NO_LOG_CONTENT,
|
|
14824
|
+
OPERATION_DURATION_BUCKETS,
|
|
13285
14825
|
OTLP_ENDPOINT_VARIABLES,
|
|
13286
14826
|
OTLP_HEADER_VARIABLES,
|
|
13287
14827
|
OtelHookError,
|
|
@@ -13302,6 +14842,7 @@ export {
|
|
|
13302
14842
|
SUBAGENT_ID_PATTERN,
|
|
13303
14843
|
SUPPORTED_REGISTRATION_PROVIDER_IDS,
|
|
13304
14844
|
TARGETED_EVENT_TYPES,
|
|
14845
|
+
TOKEN_USAGE_BUCKETS,
|
|
13305
14846
|
UNKNOWN_PROVIDER_ID,
|
|
13306
14847
|
UNKNOWN_WORKSPACE_ID,
|
|
13307
14848
|
UsageNormalizationError,
|
|
@@ -13309,8 +14850,10 @@ export {
|
|
|
13309
14850
|
WORKSPACE_ID_PATTERN,
|
|
13310
14851
|
adapterSupports,
|
|
13311
14852
|
addUsage,
|
|
14853
|
+
aggregateDeltaPoints,
|
|
13312
14854
|
appliedDeliverySchema,
|
|
13313
14855
|
asProviderId,
|
|
14856
|
+
attachClaudeTranscriptTurn,
|
|
13314
14857
|
attributePrimitiveSchema,
|
|
13315
14858
|
attributeValueSchema,
|
|
13316
14859
|
attributesSchema,
|
|
@@ -13344,6 +14887,7 @@ export {
|
|
|
13344
14887
|
createBoundedMemoryStateStore,
|
|
13345
14888
|
createCallbackDeduplicator,
|
|
13346
14889
|
createClaudeCodeAdapter,
|
|
14890
|
+
createClaudeTranscriptUsageEnricher,
|
|
13347
14891
|
createCodexAdapter,
|
|
13348
14892
|
createCursorAdapter,
|
|
13349
14893
|
createDefaultProviderRegistry,
|
|
@@ -13353,6 +14897,7 @@ export {
|
|
|
13353
14897
|
createEventFactory,
|
|
13354
14898
|
createExportDestinationSinks,
|
|
13355
14899
|
createFileDurableLogSpool,
|
|
14900
|
+
createFileDurableMetricSpool,
|
|
13356
14901
|
createFileDurableSpool,
|
|
13357
14902
|
createFilesystemStateStore,
|
|
13358
14903
|
createFilesystemWorktreeLocator,
|
|
@@ -13362,10 +14907,12 @@ export {
|
|
|
13362
14907
|
createHookRuntime,
|
|
13363
14908
|
createInMemoryStateStore,
|
|
13364
14909
|
createLifecycleJanitor,
|
|
14910
|
+
createMetricSeriesStore,
|
|
13365
14911
|
createNullLogger,
|
|
13366
14912
|
createNullTelemetrySink,
|
|
13367
14913
|
createOtelHook,
|
|
13368
14914
|
createOtlpLogSink,
|
|
14915
|
+
createOtlpMetricSink,
|
|
13369
14916
|
createOtlpTraceSink,
|
|
13370
14917
|
createPrivacyService,
|
|
13371
14918
|
createProviderRegistry,
|
|
@@ -13382,11 +14929,13 @@ export {
|
|
|
13382
14929
|
deliveryComponentSchema,
|
|
13383
14930
|
deliveryGapReasonSchema,
|
|
13384
14931
|
deliveryIdentifierSupportSchema,
|
|
14932
|
+
deriveMetricObservations,
|
|
13385
14933
|
deriveWorkspaceIdentity,
|
|
13386
14934
|
describeAdapter,
|
|
13387
14935
|
describeErrorCode,
|
|
13388
14936
|
describeExportDestinations,
|
|
13389
14937
|
describeLogsDeliverability,
|
|
14938
|
+
describeMetricsDeliverability,
|
|
13390
14939
|
describeOtlpHeaderNames,
|
|
13391
14940
|
describeProviderCatalog,
|
|
13392
14941
|
describeResolvedConfig,
|
|
@@ -13397,6 +14946,7 @@ export {
|
|
|
13397
14946
|
detectionPolicySchema,
|
|
13398
14947
|
diagnosticsPolicySchema,
|
|
13399
14948
|
durationMillisSchema,
|
|
14949
|
+
effectiveMetricsPolicy,
|
|
13400
14950
|
effectiveSpoolPolicy,
|
|
13401
14951
|
emptyExtensions,
|
|
13402
14952
|
endpointOrigin,
|
|
@@ -13453,6 +15003,7 @@ export {
|
|
|
13453
15003
|
mergeGeminiHookRegistration,
|
|
13454
15004
|
mergeNestedHookRegistration,
|
|
13455
15005
|
mergeOtlpHeaders,
|
|
15006
|
+
metricsPolicySchema,
|
|
13456
15007
|
minimumStaleClaimMillis,
|
|
13457
15008
|
modelDescriptorSchema,
|
|
13458
15009
|
nonEmptyStringSchema,
|
|
@@ -13483,8 +15034,11 @@ export {
|
|
|
13483
15034
|
providerHookResponseSchema,
|
|
13484
15035
|
providerIdSchema,
|
|
13485
15036
|
providerTotalAgreementSchema,
|
|
15037
|
+
providersPolicySchema,
|
|
13486
15038
|
readAntigravityHookRegistrations,
|
|
13487
15039
|
readClaudeHookRegistrations,
|
|
15040
|
+
readClaudeTranscriptRange,
|
|
15041
|
+
readClaudeTranscriptTurn,
|
|
13488
15042
|
readCodexHookRegistrations,
|
|
13489
15043
|
readCodexHooksFeatureFlag,
|
|
13490
15044
|
readCursorHookRegistrations,
|
|
@@ -13493,6 +15047,7 @@ export {
|
|
|
13493
15047
|
readGeminiHookRegistrations,
|
|
13494
15048
|
readJsonDocument,
|
|
13495
15049
|
readNestedHookRegistrations,
|
|
15050
|
+
readsClaudeTranscriptUsage,
|
|
13496
15051
|
removeAntigravityHookRegistration,
|
|
13497
15052
|
removeClaudeHookRegistration,
|
|
13498
15053
|
removeCodexHookRegistration,
|
|
@@ -13508,6 +15063,7 @@ export {
|
|
|
13508
15063
|
resolveInstallPath,
|
|
13509
15064
|
resolveInvocationIdentity,
|
|
13510
15065
|
resolveLogsEndpoint,
|
|
15066
|
+
resolveMetricsEndpoint,
|
|
13511
15067
|
resolveOtlpHeaders,
|
|
13512
15068
|
resolvePrivacyPolicy,
|
|
13513
15069
|
resolvedProviderIdSchema,
|
|
@@ -13547,6 +15103,7 @@ export {
|
|
|
13547
15103
|
usageScopeSchema,
|
|
13548
15104
|
usageTemporalitySchema,
|
|
13549
15105
|
validateCanonicalEvent,
|
|
15106
|
+
validateMetricSpoolBatch,
|
|
13550
15107
|
withFileLock,
|
|
13551
15108
|
withOptionalSessionLock,
|
|
13552
15109
|
workspaceIdSchema,
|