@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/cli.js
CHANGED
|
@@ -332,6 +332,8 @@ var VALUE_FLAGS = /* @__PURE__ */ new Set([
|
|
|
332
332
|
"--installation-id",
|
|
333
333
|
"--flush-timeout-ms",
|
|
334
334
|
"--logs-endpoint",
|
|
335
|
+
"--metrics-endpoint",
|
|
336
|
+
"--metrics-temporality",
|
|
335
337
|
"--max-input-bytes",
|
|
336
338
|
"--scope",
|
|
337
339
|
"--project-dir",
|
|
@@ -350,6 +352,10 @@ var BOOLEAN_FLAGS = /* @__PURE__ */ new Set([
|
|
|
350
352
|
"--logs",
|
|
351
353
|
"--no-logs",
|
|
352
354
|
"--logs-content",
|
|
355
|
+
"--metrics",
|
|
356
|
+
"--no-metrics",
|
|
357
|
+
"--no-metrics-session-id",
|
|
358
|
+
"--claude-transcript-usage",
|
|
353
359
|
"--include-experimental",
|
|
354
360
|
"--no-experimental",
|
|
355
361
|
"--dry-run",
|
|
@@ -514,6 +520,20 @@ var parsePolicy = (tokens, errors) => {
|
|
|
514
520
|
if (tokens.booleans.has("--logs") && tokens.booleans.has("--no-logs")) {
|
|
515
521
|
errors.push("flags --logs and --no-logs cannot both be given");
|
|
516
522
|
}
|
|
523
|
+
const metricsEndpoint = single(tokens, "--metrics-endpoint", errors);
|
|
524
|
+
const metricsEnabled = tokens.booleans.has("--metrics") ? true : tokens.booleans.has("--no-metrics") ? false : void 0;
|
|
525
|
+
if (tokens.booleans.has("--metrics") && tokens.booleans.has("--no-metrics")) {
|
|
526
|
+
errors.push("flags --metrics and --no-metrics cannot both be given");
|
|
527
|
+
}
|
|
528
|
+
const metricsTemporalityRaw = single(tokens, "--metrics-temporality", errors);
|
|
529
|
+
let metricsTemporality;
|
|
530
|
+
if (metricsTemporalityRaw !== void 0) {
|
|
531
|
+
if (metricsTemporalityRaw === "cumulative" || metricsTemporalityRaw === "delta") {
|
|
532
|
+
metricsTemporality = metricsTemporalityRaw;
|
|
533
|
+
} else {
|
|
534
|
+
errors.push("flag --metrics-temporality must be cumulative or delta");
|
|
535
|
+
}
|
|
536
|
+
}
|
|
517
537
|
return {
|
|
518
538
|
...configFile === void 0 ? {} : { configFile },
|
|
519
539
|
...endpoint === void 0 ? {} : { endpoint },
|
|
@@ -533,7 +553,12 @@ var parsePolicy = (tokens, errors) => {
|
|
|
533
553
|
...includeExperimental === void 0 ? {} : { includeExperimental },
|
|
534
554
|
...logsEnabled === void 0 ? {} : { logsEnabled },
|
|
535
555
|
...logsEndpoint === void 0 ? {} : { logsEndpoint },
|
|
536
|
-
...tokens.booleans.has("--logs-content") ? { logsIncludeContent: true } : {}
|
|
556
|
+
...tokens.booleans.has("--logs-content") ? { logsIncludeContent: true } : {},
|
|
557
|
+
...metricsEnabled === void 0 ? {} : { metricsEnabled },
|
|
558
|
+
...metricsEndpoint === void 0 ? {} : { metricsEndpoint },
|
|
559
|
+
...metricsTemporality === void 0 ? {} : { metricsTemporality },
|
|
560
|
+
...tokens.booleans.has("--no-metrics-session-id") ? { metricsIncludeSessionId: false } : {},
|
|
561
|
+
...tokens.booleans.has("--claude-transcript-usage") ? { claudeTranscriptUsage: true } : {}
|
|
537
562
|
};
|
|
538
563
|
};
|
|
539
564
|
var parseIdentity = (tokens, errors) => {
|
|
@@ -588,6 +613,12 @@ var RUN_FLAGS = /* @__PURE__ */ new Set([
|
|
|
588
613
|
"--no-logs",
|
|
589
614
|
"--logs-endpoint",
|
|
590
615
|
"--logs-content",
|
|
616
|
+
"--metrics",
|
|
617
|
+
"--no-metrics",
|
|
618
|
+
"--metrics-endpoint",
|
|
619
|
+
"--metrics-temporality",
|
|
620
|
+
"--no-metrics-session-id",
|
|
621
|
+
"--claude-transcript-usage",
|
|
591
622
|
"--max-input-bytes",
|
|
592
623
|
"--no-export",
|
|
593
624
|
"--no-spool",
|
|
@@ -617,6 +648,12 @@ var DOCTOR_FLAGS = /* @__PURE__ */ new Set([
|
|
|
617
648
|
"--no-logs",
|
|
618
649
|
"--logs-endpoint",
|
|
619
650
|
"--logs-content",
|
|
651
|
+
"--metrics",
|
|
652
|
+
"--no-metrics",
|
|
653
|
+
"--metrics-endpoint",
|
|
654
|
+
"--metrics-temporality",
|
|
655
|
+
"--no-metrics-session-id",
|
|
656
|
+
"--claude-transcript-usage",
|
|
620
657
|
"--include-experimental",
|
|
621
658
|
"--no-experimental"
|
|
622
659
|
]);
|
|
@@ -861,6 +898,18 @@ Exporter and runtime policy (never identity):
|
|
|
861
898
|
--logs-content permit disclosed content text in a log body. Needs
|
|
862
899
|
--content-mode too: this decides whether the logs
|
|
863
900
|
pipeline may carry what that one discloses
|
|
901
|
+
--metrics also export hook-derived OTLP metrics (off by
|
|
902
|
+
default): token usage, generation duration,
|
|
903
|
+
sessions, tool calls, provider-reported cost
|
|
904
|
+
--metrics-endpoint <url> OTLP HTTP/protobuf metrics endpoint; derived from
|
|
905
|
+
--endpoint when omitted (/v1/traces -> /v1/metrics)
|
|
906
|
+
--metrics-temporality <t> cumulative (default; running totals kept in the
|
|
907
|
+
state dir) | delta
|
|
908
|
+
--no-metrics-session-id leave session.id off metric points (fewer series)
|
|
909
|
+
--claude-transcript-usage Claude Code only: at Stop, read the transcript the
|
|
910
|
+
payload names (bounded) for the turn's model and
|
|
911
|
+
summed token usage. Off by default; also
|
|
912
|
+
OTEL_HOOK_CLAUDE_TRANSCRIPT_USAGE=1
|
|
864
913
|
--max-input-bytes <n> stdin bound (default 1048576)
|
|
865
914
|
--attr <key=value> opaque consumer attribute for this invocation,
|
|
866
915
|
carried unchanged (not a resource attribute)
|
|
@@ -1162,10 +1211,17 @@ var errorInfoFromThrown = (thrown, input) => {
|
|
|
1162
1211
|
var OTLP_ENDPOINT_VARIABLES = Object.freeze({
|
|
1163
1212
|
generic: "OTEL_EXPORTER_OTLP_ENDPOINT",
|
|
1164
1213
|
traces: "OTEL_EXPORTER_OTLP_TRACES_ENDPOINT",
|
|
1165
|
-
logs: "OTEL_EXPORTER_OTLP_LOGS_ENDPOINT"
|
|
1214
|
+
logs: "OTEL_EXPORTER_OTLP_LOGS_ENDPOINT",
|
|
1215
|
+
metrics: "OTEL_EXPORTER_OTLP_METRICS_ENDPOINT"
|
|
1166
1216
|
});
|
|
1167
1217
|
var OTLP_TRACES_PATH = "/v1/traces";
|
|
1168
1218
|
var OTLP_LOGS_PATH = "/v1/logs";
|
|
1219
|
+
var OTLP_METRICS_PATH = "/v1/metrics";
|
|
1220
|
+
var SIGNAL_PATHS = Object.freeze({
|
|
1221
|
+
traces: OTLP_TRACES_PATH,
|
|
1222
|
+
logs: OTLP_LOGS_PATH,
|
|
1223
|
+
metrics: OTLP_METRICS_PATH
|
|
1224
|
+
});
|
|
1169
1225
|
var withoutTrailingSlashes = (value) => {
|
|
1170
1226
|
let end = value.length;
|
|
1171
1227
|
while (end > 0 && value.charCodeAt(end - 1) === 47) {
|
|
@@ -1176,9 +1232,20 @@ var withoutTrailingSlashes = (value) => {
|
|
|
1176
1232
|
var otlpSignalEndpointFromBase = (base, signal) => {
|
|
1177
1233
|
const trimmed = withoutTrailingSlashes(base);
|
|
1178
1234
|
if (trimmed.endsWith(OTLP_TRACES_PATH)) {
|
|
1179
|
-
return signal === "traces" ? trimmed : `${trimmed.slice(0, trimmed.length - OTLP_TRACES_PATH.length)}${
|
|
1235
|
+
return signal === "traces" ? trimmed : `${trimmed.slice(0, trimmed.length - OTLP_TRACES_PATH.length)}${SIGNAL_PATHS[signal]}`;
|
|
1236
|
+
}
|
|
1237
|
+
return `${trimmed}${SIGNAL_PATHS[signal]}`;
|
|
1238
|
+
};
|
|
1239
|
+
var siblingSignalEndpoint = (tracesEndpoint, signal) => {
|
|
1240
|
+
const trimmed = withoutTrailingSlashes(tracesEndpoint);
|
|
1241
|
+
const target = SIGNAL_PATHS[signal];
|
|
1242
|
+
if (trimmed.endsWith(target)) {
|
|
1243
|
+
return trimmed;
|
|
1244
|
+
}
|
|
1245
|
+
if (trimmed.endsWith(OTLP_TRACES_PATH)) {
|
|
1246
|
+
return `${trimmed.slice(0, trimmed.length - OTLP_TRACES_PATH.length)}${target}`;
|
|
1180
1247
|
}
|
|
1181
|
-
return `${trimmed}${
|
|
1248
|
+
return `${trimmed}${target}`;
|
|
1182
1249
|
};
|
|
1183
1250
|
|
|
1184
1251
|
// src/config/header-value.ts
|
|
@@ -1322,6 +1389,12 @@ var ENVIRONMENT_VARIABLES = Object.freeze({
|
|
|
1322
1389
|
/** Standard per-signal endpoint; the weaker source of the two. */
|
|
1323
1390
|
otlpLogsEndpoint: "OTEL_EXPORTER_OTLP_LOGS_ENDPOINT",
|
|
1324
1391
|
logsIncludeContent: "OTEL_HOOK_LOGS_INCLUDE_CONTENT",
|
|
1392
|
+
metricsEnabled: "OTEL_HOOK_METRICS_ENABLED",
|
|
1393
|
+
metricsEndpoint: "OTEL_HOOK_METRICS_ENDPOINT",
|
|
1394
|
+
/** Standard per-signal endpoint; the weaker source of the two. */
|
|
1395
|
+
otlpMetricsEndpoint: "OTEL_EXPORTER_OTLP_METRICS_ENDPOINT",
|
|
1396
|
+
/** Standard: `cumulative`, `delta`, or `lowmemory` (read as `delta` here). */
|
|
1397
|
+
otlpMetricsTemporality: "OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE",
|
|
1325
1398
|
serviceName: "OTEL_HOOK_SERVICE_NAME",
|
|
1326
1399
|
otlpServiceName: "OTEL_SERVICE_NAME",
|
|
1327
1400
|
serviceNamespace: "OTEL_HOOK_SERVICE_NAMESPACE",
|
|
@@ -1335,7 +1408,9 @@ var ENVIRONMENT_VARIABLES = Object.freeze({
|
|
|
1335
1408
|
maxArrayLength: "OTEL_HOOK_MAX_ARRAY_LENGTH",
|
|
1336
1409
|
maxEventsPerInvocation: "OTEL_HOOK_MAX_EVENTS_PER_INVOCATION",
|
|
1337
1410
|
minimumConfidence: "OTEL_HOOK_MIN_DETECTION_CONFIDENCE",
|
|
1338
|
-
logLevel: "OTEL_HOOK_LOG_LEVEL"
|
|
1411
|
+
logLevel: "OTEL_HOOK_LOG_LEVEL",
|
|
1412
|
+
/** `providers.claudeCode.readTranscriptUsage`; see `providersPolicySchema`. */
|
|
1413
|
+
claudeTranscriptUsage: "OTEL_HOOK_CLAUDE_TRANSCRIPT_USAGE"
|
|
1339
1414
|
});
|
|
1340
1415
|
var BOOLEAN_TRUE = /* @__PURE__ */ new Set(["1", "true", "yes", "on"]);
|
|
1341
1416
|
var BOOLEAN_FALSE = /* @__PURE__ */ new Set(["0", "false", "no", "off"]);
|
|
@@ -1482,6 +1557,22 @@ var parseEnvironmentConfig = (env) => {
|
|
|
1482
1557
|
...logsEndpoint === void 0 ? {} : { endpoint: logsEndpoint },
|
|
1483
1558
|
...logsIncludeContent === void 0 ? {} : { includeContent: logsIncludeContent }
|
|
1484
1559
|
};
|
|
1560
|
+
const metricsEnabled = readBoolean(ENVIRONMENT_VARIABLES.metricsEnabled);
|
|
1561
|
+
const metricsEndpoint = readString(ENVIRONMENT_VARIABLES.metricsEndpoint) ?? readString(ENVIRONMENT_VARIABLES.otlpMetricsEndpoint) ?? (hookEndpoint === void 0 && otlpTracesEndpoint !== void 0 && otlpBaseEndpoint !== void 0 ? otlpSignalEndpointFromBase(otlpBaseEndpoint, "metrics") : void 0);
|
|
1562
|
+
const temporalityRaw = readString(ENVIRONMENT_VARIABLES.otlpMetricsTemporality)?.toLowerCase();
|
|
1563
|
+
let metricsTemporality;
|
|
1564
|
+
if (temporalityRaw === "cumulative") {
|
|
1565
|
+
metricsTemporality = "cumulative";
|
|
1566
|
+
} else if (temporalityRaw === "delta" || temporalityRaw === "lowmemory") {
|
|
1567
|
+
metricsTemporality = "delta";
|
|
1568
|
+
} else if (temporalityRaw !== void 0) {
|
|
1569
|
+
warn(ENVIRONMENT_VARIABLES.otlpMetricsTemporality, "expected cumulative, delta, or lowmemory");
|
|
1570
|
+
}
|
|
1571
|
+
const metrics = {
|
|
1572
|
+
...metricsEnabled === void 0 ? {} : { enabled: metricsEnabled },
|
|
1573
|
+
...metricsEndpoint === void 0 ? {} : { endpoint: metricsEndpoint },
|
|
1574
|
+
...metricsTemporality === void 0 ? {} : { temporality: metricsTemporality }
|
|
1575
|
+
};
|
|
1485
1576
|
const otlpHeaders = resolveOtlpHeaders(env);
|
|
1486
1577
|
for (const { variable, detail } of otlpHeaders.warnings) {
|
|
1487
1578
|
warn(variable, detail);
|
|
@@ -1496,7 +1587,8 @@ var parseEnvironmentConfig = (env) => {
|
|
|
1496
1587
|
...serviceName === void 0 ? {} : { serviceName },
|
|
1497
1588
|
...serviceNamespace === void 0 ? {} : { serviceNamespace },
|
|
1498
1589
|
...Object.keys(resourceAttributes).length === 0 ? {} : { resourceAttributes },
|
|
1499
|
-
...Object.keys(logs).length === 0 ? {} : { logs }
|
|
1590
|
+
...Object.keys(logs).length === 0 ? {} : { logs },
|
|
1591
|
+
...Object.keys(metrics).length === 0 ? {} : { metrics }
|
|
1500
1592
|
};
|
|
1501
1593
|
const limits = {
|
|
1502
1594
|
...maxStringLength === void 0 ? {} : { maxStringLength },
|
|
@@ -1512,11 +1604,14 @@ var parseEnvironmentConfig = (env) => {
|
|
|
1512
1604
|
};
|
|
1513
1605
|
const detection = confidenceParsed?.success === true ? { minimumConfidence: confidenceParsed.data } : {};
|
|
1514
1606
|
const diagnostics = logLevel === void 0 ? {} : { logLevel };
|
|
1607
|
+
const claudeTranscriptUsage = readBoolean(ENVIRONMENT_VARIABLES.claudeTranscriptUsage);
|
|
1608
|
+
const providers = claudeTranscriptUsage === void 0 ? {} : { claudeCode: { readTranscriptUsage: claudeTranscriptUsage } };
|
|
1515
1609
|
const patch = {
|
|
1516
1610
|
...Object.keys(exporter).length === 0 ? {} : { exporter },
|
|
1517
1611
|
...Object.keys(privacy).length === 0 ? {} : { privacy },
|
|
1518
1612
|
...Object.keys(detection).length === 0 ? {} : { detection },
|
|
1519
|
-
...Object.keys(diagnostics).length === 0 ? {} : { diagnostics }
|
|
1613
|
+
...Object.keys(diagnostics).length === 0 ? {} : { diagnostics },
|
|
1614
|
+
...Object.keys(providers).length === 0 ? {} : { providers }
|
|
1520
1615
|
};
|
|
1521
1616
|
return { patch, warnings };
|
|
1522
1617
|
};
|
|
@@ -1534,7 +1629,7 @@ var HEADER_ENV_REFERENCE_PREFIX = "env:";
|
|
|
1534
1629
|
var HEADER_NAME_PATTERN2 = /^[A-Za-z0-9!#$%&'*+.^_`|~-]{1,128}$/;
|
|
1535
1630
|
var ENV_VARIABLE_NAME_PATTERN = /^[A-Za-z_][A-Za-z0-9_]{0,127}$/;
|
|
1536
1631
|
var MAX_HEADER_VALUE_LENGTH = 8192;
|
|
1537
|
-
var exportSignalSchema = z6.enum(["traces", "logs"]);
|
|
1632
|
+
var exportSignalSchema = z6.enum(["traces", "logs", "metrics"]);
|
|
1538
1633
|
var headerValueSchema = z6.string().min(1).max(MAX_HEADER_VALUE_LENGTH).refine(
|
|
1539
1634
|
(value) => !isUnsafeHeaderValue(value),
|
|
1540
1635
|
"header values may not contain line breaks, control characters, or characters beyond Latin-1"
|
|
@@ -1557,6 +1652,8 @@ var exportDestinationSchema = z6.strictObject({
|
|
|
1557
1652
|
tracesEndpoint: endpointSchema.optional(),
|
|
1558
1653
|
/** Per-signal override of the derived logs URL. */
|
|
1559
1654
|
logsEndpoint: endpointSchema.optional(),
|
|
1655
|
+
/** Per-signal override of the derived metrics URL (`/v1/traces` becomes `/v1/metrics`). */
|
|
1656
|
+
metricsEndpoint: endpointSchema.optional(),
|
|
1560
1657
|
/** Defaults to `exporter.protocol`. */
|
|
1561
1658
|
protocol: z6.enum(["http/protobuf", "http/json", "none"]).optional(),
|
|
1562
1659
|
/**
|
|
@@ -1569,15 +1666,17 @@ var exportDestinationSchema = z6.strictObject({
|
|
|
1569
1666
|
`at most ${String(MAX_DESTINATION_HEADERS)} headers per destination`
|
|
1570
1667
|
).optional(),
|
|
1571
1668
|
/**
|
|
1572
|
-
* Which signals this destination receives. Default:
|
|
1573
|
-
* still governed by `exporter.logs.enabled`, which stays the one
|
|
1574
|
-
*
|
|
1669
|
+
* Which signals this destination receives. Default: traces and logs. The logs
|
|
1670
|
+
* signal is still governed by `exporter.logs.enabled`, which stays the one
|
|
1671
|
+
* opt-in for content-bearing records leaving the host. `metrics` is never on by
|
|
1672
|
+
* default: a destination receives hook-derived metrics only when it lists them.
|
|
1575
1673
|
*/
|
|
1576
|
-
signals: z6.array(exportSignalSchema).min(1).max(
|
|
1674
|
+
signals: z6.array(exportSignalSchema).min(1).max(3).readonly().optional()
|
|
1577
1675
|
}).refine(
|
|
1578
|
-
(destination) => destination.endpoint !== void 0 || destination.tracesEndpoint !== void 0 || destination.logsEndpoint !== void 0,
|
|
1579
|
-
"a destination needs an endpoint, or a tracesEndpoint / logsEndpoint"
|
|
1676
|
+
(destination) => destination.endpoint !== void 0 || destination.tracesEndpoint !== void 0 || destination.logsEndpoint !== void 0 || destination.metricsEndpoint !== void 0,
|
|
1677
|
+
"a destination needs an endpoint, or a tracesEndpoint / logsEndpoint / metricsEndpoint"
|
|
1580
1678
|
);
|
|
1679
|
+
var DEFAULT_DESTINATION_SIGNALS = Object.freeze(["traces", "logs"]);
|
|
1581
1680
|
var exportDestinationsSchema = z6.array(exportDestinationSchema).max(MAX_EXPORT_DESTINATIONS).readonly().superRefine((destinations, context) => {
|
|
1582
1681
|
const seen = /* @__PURE__ */ new Set();
|
|
1583
1682
|
destinations.forEach((destination, index) => {
|
|
@@ -1622,7 +1721,8 @@ var legacyDestination = (exporter) => ({
|
|
|
1622
1721
|
protocol: exporter.protocol,
|
|
1623
1722
|
...exporter.endpoint === void 0 ? {} : { endpoint: exporter.endpoint },
|
|
1624
1723
|
...exporter.logs.endpoint === void 0 ? {} : { logsEndpoint: exporter.logs.endpoint },
|
|
1625
|
-
|
|
1724
|
+
...exporter.metrics?.endpoint === void 0 ? {} : { metricsEndpoint: exporter.metrics.endpoint },
|
|
1725
|
+
signals: { traces: true, logs: exporter.logs.enabled, metrics: exporter.metrics?.enabled === true },
|
|
1626
1726
|
headers: {}
|
|
1627
1727
|
});
|
|
1628
1728
|
var hasConfiguredDestinations = (exporter) => exporter.destinations !== void 0 && exporter.destinations.length > 0;
|
|
@@ -1631,14 +1731,14 @@ var resolveExportDestinations = (exporter) => {
|
|
|
1631
1731
|
return [legacyDestination(exporter)];
|
|
1632
1732
|
}
|
|
1633
1733
|
const resolved = [];
|
|
1634
|
-
if (exporter.endpoint !== void 0 || exporter.logs.endpoint !== void 0) {
|
|
1734
|
+
if (exporter.endpoint !== void 0 || exporter.logs.endpoint !== void 0 || exporter.metrics?.endpoint !== void 0) {
|
|
1635
1735
|
resolved.push(legacyDestination(exporter));
|
|
1636
1736
|
}
|
|
1637
1737
|
for (const destination of exporter.destinations ?? []) {
|
|
1638
1738
|
if (destination.enabled === false) {
|
|
1639
1739
|
continue;
|
|
1640
1740
|
}
|
|
1641
|
-
const signals = destination.signals ??
|
|
1741
|
+
const signals = destination.signals ?? DEFAULT_DESTINATION_SIGNALS;
|
|
1642
1742
|
resolved.push({
|
|
1643
1743
|
name: destination.name,
|
|
1644
1744
|
source: "destinations",
|
|
@@ -1646,9 +1746,11 @@ var resolveExportDestinations = (exporter) => {
|
|
|
1646
1746
|
...destination.endpoint === void 0 ? {} : { endpoint: destination.endpoint },
|
|
1647
1747
|
...destination.tracesEndpoint === void 0 ? {} : { tracesEndpoint: destination.tracesEndpoint },
|
|
1648
1748
|
...destination.logsEndpoint === void 0 ? {} : { logsEndpoint: destination.logsEndpoint },
|
|
1749
|
+
...destination.metricsEndpoint === void 0 ? {} : { metricsEndpoint: destination.metricsEndpoint },
|
|
1649
1750
|
signals: {
|
|
1650
1751
|
traces: signals.includes("traces"),
|
|
1651
|
-
logs: exporter.logs.enabled && signals.includes("logs")
|
|
1752
|
+
logs: exporter.logs.enabled && signals.includes("logs"),
|
|
1753
|
+
metrics: signals.includes("metrics")
|
|
1652
1754
|
},
|
|
1653
1755
|
headers: { ...destination.headers ?? {} }
|
|
1654
1756
|
});
|
|
@@ -1690,6 +1792,9 @@ var describeExportDestinations = (exporter) => {
|
|
|
1690
1792
|
const logsOrigin = endpointOrigin(
|
|
1691
1793
|
destination.logsEndpoint ?? destination.endpoint ?? destination.tracesEndpoint
|
|
1692
1794
|
);
|
|
1795
|
+
const metricsOrigin = endpointOrigin(
|
|
1796
|
+
destination.metricsEndpoint ?? destination.endpoint ?? destination.tracesEndpoint
|
|
1797
|
+
);
|
|
1693
1798
|
const variables = Object.values(destination.headers).map(parseHeaderValueReference).flatMap((reference) => reference.kind === "env" ? [reference.variable] : []);
|
|
1694
1799
|
return {
|
|
1695
1800
|
name: destination.name,
|
|
@@ -1698,6 +1803,7 @@ var describeExportDestinations = (exporter) => {
|
|
|
1698
1803
|
signals: exportSignalSchema.options.filter((signal) => destination.signals[signal]),
|
|
1699
1804
|
...tracesOrigin === void 0 || !destination.signals.traces ? {} : { tracesEndpointOrigin: tracesOrigin },
|
|
1700
1805
|
...logsOrigin === void 0 || !destination.signals.logs ? {} : { logsEndpointOrigin: logsOrigin },
|
|
1806
|
+
...metricsOrigin === void 0 || !destination.signals.metrics ? {} : { metricsEndpointOrigin: metricsOrigin },
|
|
1701
1807
|
headerNames: destination.source === "exporter" ? [...exporter.headerNames].sort() : Object.keys(destination.headers).sort(),
|
|
1702
1808
|
headerVariables: [...new Set(variables)].sort()
|
|
1703
1809
|
};
|
|
@@ -1712,7 +1818,7 @@ var describeExportDestinations = (exporter) => {
|
|
|
1712
1818
|
source: "destinations",
|
|
1713
1819
|
protocol: destination.protocol ?? exporter.protocol,
|
|
1714
1820
|
...destination.endpoint === void 0 ? {} : { endpoint: destination.endpoint },
|
|
1715
|
-
signals: { traces: false, logs: false },
|
|
1821
|
+
signals: { traces: false, logs: false, metrics: false },
|
|
1716
1822
|
headers: { ...destination.headers ?? {} }
|
|
1717
1823
|
},
|
|
1718
1824
|
false
|
|
@@ -1740,6 +1846,18 @@ var DEFAULT_LOGS_POLICY = Object.freeze({
|
|
|
1740
1846
|
includeContent: false,
|
|
1741
1847
|
maxBatchSize: 128
|
|
1742
1848
|
});
|
|
1849
|
+
var metricsPolicySchema = z7.strictObject({
|
|
1850
|
+
enabled: z7.boolean(),
|
|
1851
|
+
/** Full URL. Absent, derived from `endpoint` (`/v1/traces` becomes `/v1/metrics`). */
|
|
1852
|
+
endpoint: z7.string().url().max(2048).optional(),
|
|
1853
|
+
temporality: z7.enum(["cumulative", "delta"]),
|
|
1854
|
+
includeSessionId: z7.boolean()
|
|
1855
|
+
});
|
|
1856
|
+
var DEFAULT_METRICS_POLICY = Object.freeze({
|
|
1857
|
+
enabled: false,
|
|
1858
|
+
temporality: "cumulative",
|
|
1859
|
+
includeSessionId: true
|
|
1860
|
+
});
|
|
1743
1861
|
var exporterPolicySchema = z7.strictObject({
|
|
1744
1862
|
enabled: z7.boolean(),
|
|
1745
1863
|
protocol: z7.enum(["http/protobuf", "http/json", "none"]),
|
|
@@ -1770,6 +1888,11 @@ var exporterPolicySchema = z7.strictObject({
|
|
|
1770
1888
|
* a second top-level section would invite two of each to drift apart.
|
|
1771
1889
|
*/
|
|
1772
1890
|
logs: logsPolicySchema,
|
|
1891
|
+
/**
|
|
1892
|
+
* Hook-derived metrics. Optional so an `ExporterPolicy` built by hand before
|
|
1893
|
+
* metrics existed stays valid; absent reads as {@link DEFAULT_METRICS_POLICY}.
|
|
1894
|
+
*/
|
|
1895
|
+
metrics: metricsPolicySchema.optional(),
|
|
1773
1896
|
/**
|
|
1774
1897
|
* Additional OTLP destinations, each sent every batch in parallel.
|
|
1775
1898
|
*
|
|
@@ -1801,23 +1924,34 @@ var diagnosticsPolicySchema = z7.strictObject({
|
|
|
1801
1924
|
/** Emit `error.raised` events for contained failures. */
|
|
1802
1925
|
emitErrorEvents: z7.boolean()
|
|
1803
1926
|
});
|
|
1927
|
+
var providersPolicySchema = z7.strictObject({
|
|
1928
|
+
claudeCode: z7.strictObject({
|
|
1929
|
+
readTranscriptUsage: z7.boolean()
|
|
1930
|
+
}).optional()
|
|
1931
|
+
});
|
|
1804
1932
|
var otelHookConfigSchema = z7.strictObject({
|
|
1805
1933
|
exporter: exporterPolicySchema,
|
|
1806
1934
|
privacy: privacyPolicySchema,
|
|
1807
1935
|
detection: detectionPolicySchema,
|
|
1808
|
-
diagnostics: diagnosticsPolicySchema
|
|
1936
|
+
diagnostics: diagnosticsPolicySchema,
|
|
1937
|
+
/** Optional so a hand-built configuration from before it existed stays valid. */
|
|
1938
|
+
providers: providersPolicySchema.optional()
|
|
1809
1939
|
});
|
|
1810
1940
|
var otelHookConfigPatchSchema = z7.strictObject({
|
|
1811
1941
|
// `logs` is unwrapped and re-partialled for the same reason `privacy.limits` is:
|
|
1812
1942
|
// merging happens per leaf, so a layer must be able to set `logs.enabled` alone
|
|
1813
1943
|
// without also restating the endpoint and the batch size.
|
|
1814
|
-
exporter: exporterPolicySchema.omit({ logs: true, spool: true }).partial().extend({
|
|
1944
|
+
exporter: exporterPolicySchema.omit({ logs: true, metrics: true, spool: true }).partial().extend({
|
|
1815
1945
|
logs: logsPolicySchema.partial().optional(),
|
|
1946
|
+
metrics: metricsPolicySchema.partial().optional(),
|
|
1816
1947
|
spool: spoolPolicySchema.partial().optional()
|
|
1817
1948
|
}).optional(),
|
|
1818
1949
|
privacy: privacyPolicySchema.omit({ limits: true }).partial().extend({ limits: privacyPolicySchema.shape.limits.partial().optional() }).optional(),
|
|
1819
1950
|
detection: detectionPolicySchema.partial().optional(),
|
|
1820
|
-
diagnostics: diagnosticsPolicySchema.partial().optional()
|
|
1951
|
+
diagnostics: diagnosticsPolicySchema.partial().optional(),
|
|
1952
|
+
providers: z7.strictObject({
|
|
1953
|
+
claudeCode: z7.strictObject({ readTranscriptUsage: z7.boolean() }).partial().optional()
|
|
1954
|
+
}).partial().optional()
|
|
1821
1955
|
});
|
|
1822
1956
|
var DEFAULT_EXPORTER_POLICY = Object.freeze({
|
|
1823
1957
|
enabled: true,
|
|
@@ -1829,7 +1963,8 @@ var DEFAULT_EXPORTER_POLICY = Object.freeze({
|
|
|
1829
1963
|
maxRetryAttempts: 2,
|
|
1830
1964
|
serviceName: "coding-agent",
|
|
1831
1965
|
resourceAttributes: EMPTY_RESOURCE_ATTRIBUTES,
|
|
1832
|
-
logs: DEFAULT_LOGS_POLICY
|
|
1966
|
+
logs: DEFAULT_LOGS_POLICY,
|
|
1967
|
+
metrics: DEFAULT_METRICS_POLICY
|
|
1833
1968
|
});
|
|
1834
1969
|
var DEFAULT_DETECTION_POLICY = Object.freeze({
|
|
1835
1970
|
minimumConfidence: "strong",
|
|
@@ -1840,23 +1975,32 @@ var DEFAULT_DIAGNOSTICS_POLICY = Object.freeze({
|
|
|
1840
1975
|
logLevel: "warn",
|
|
1841
1976
|
emitErrorEvents: true
|
|
1842
1977
|
});
|
|
1978
|
+
var DEFAULT_PROVIDERS_POLICY = Object.freeze({
|
|
1979
|
+
claudeCode: Object.freeze({ readTranscriptUsage: false })
|
|
1980
|
+
});
|
|
1843
1981
|
var DEFAULT_CONFIG = Object.freeze({
|
|
1844
1982
|
exporter: DEFAULT_EXPORTER_POLICY,
|
|
1845
1983
|
privacy: DEFAULT_PRIVACY_POLICY,
|
|
1846
1984
|
detection: DEFAULT_DETECTION_POLICY,
|
|
1847
|
-
diagnostics: DEFAULT_DIAGNOSTICS_POLICY
|
|
1985
|
+
diagnostics: DEFAULT_DIAGNOSTICS_POLICY,
|
|
1986
|
+
providers: DEFAULT_PROVIDERS_POLICY
|
|
1987
|
+
});
|
|
1988
|
+
var readsClaudeTranscriptUsage = (config) => config.providers?.claudeCode?.readTranscriptUsage === true;
|
|
1989
|
+
var effectiveMetricsPolicy = (exporter) => ({
|
|
1990
|
+
...DEFAULT_METRICS_POLICY,
|
|
1991
|
+
...exporter.metrics ?? {}
|
|
1848
1992
|
});
|
|
1849
1993
|
|
|
1850
1994
|
// src/config/resolve.ts
|
|
1851
1995
|
var CONFIG_SOURCE_PRECEDENCE = ["defaults", "file", "environment", "inline-override"];
|
|
1852
1996
|
var configSourceSchema = z8.enum(CONFIG_SOURCE_PRECEDENCE);
|
|
1853
1997
|
var isPlainObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
1854
|
-
var mergeLeaf = (target, patch, source, provenance,
|
|
1998
|
+
var mergeLeaf = (target, patch, source, provenance, path14) => {
|
|
1855
1999
|
for (const [key, value] of Object.entries(patch)) {
|
|
1856
2000
|
if (value === void 0) {
|
|
1857
2001
|
continue;
|
|
1858
2002
|
}
|
|
1859
|
-
const childPath =
|
|
2003
|
+
const childPath = path14 === "" ? key : `${path14}.${key}`;
|
|
1860
2004
|
const existing = target[key];
|
|
1861
2005
|
if (isPlainObject(value) && (isPlainObject(existing) || existing === void 0)) {
|
|
1862
2006
|
const child = { ...existing ?? {} };
|
|
@@ -1870,14 +2014,14 @@ var mergeLeaf = (target, patch, source, provenance, path13) => {
|
|
|
1870
2014
|
};
|
|
1871
2015
|
var initialProvenance = (config) => {
|
|
1872
2016
|
const provenance = {};
|
|
1873
|
-
const walk = (value,
|
|
2017
|
+
const walk = (value, path14) => {
|
|
1874
2018
|
if (isPlainObject(value)) {
|
|
1875
2019
|
for (const [key, child] of Object.entries(value)) {
|
|
1876
|
-
walk(child,
|
|
2020
|
+
walk(child, path14 === "" ? key : `${path14}.${key}`);
|
|
1877
2021
|
}
|
|
1878
2022
|
return;
|
|
1879
2023
|
}
|
|
1880
|
-
provenance[
|
|
2024
|
+
provenance[path14] = "defaults";
|
|
1881
2025
|
};
|
|
1882
2026
|
walk(config, "");
|
|
1883
2027
|
return provenance;
|
|
@@ -1956,6 +2100,11 @@ var resolveConfig = (layers = []) => {
|
|
|
1956
2100
|
"exporter.logs.enabled is true but neither a logs endpoint nor a trace endpoint to derive one from is configured"
|
|
1957
2101
|
);
|
|
1958
2102
|
}
|
|
2103
|
+
if (!withDestinations && parsed.data.exporter.metrics?.enabled === true && parsed.data.exporter.metrics.endpoint === void 0 && parsed.data.exporter.endpoint === void 0) {
|
|
2104
|
+
notes.push(
|
|
2105
|
+
"exporter.metrics.enabled is true but neither a metrics endpoint nor a trace endpoint to derive one from is configured"
|
|
2106
|
+
);
|
|
2107
|
+
}
|
|
1959
2108
|
if (parsed.data.exporter.logs.includeContent && parsed.data.privacy.contentMode === "omit") {
|
|
1960
2109
|
notes.push(
|
|
1961
2110
|
"exporter.logs.includeContent is true but privacy.contentMode is omit, so no content is disclosed to describe"
|
|
@@ -1987,6 +2136,9 @@ var describeDestinationAttributes = (config) => {
|
|
|
1987
2136
|
if (destination.logsEndpointOrigin !== void 0) {
|
|
1988
2137
|
attributes[`${prefix}.logs_endpoint_origin`] = destination.logsEndpointOrigin;
|
|
1989
2138
|
}
|
|
2139
|
+
if (destination.metricsEndpointOrigin !== void 0) {
|
|
2140
|
+
attributes[`${prefix}.metrics_endpoint_origin`] = destination.metricsEndpointOrigin;
|
|
2141
|
+
}
|
|
1990
2142
|
attributes[`${prefix}.header_names`] = [...destination.headerNames];
|
|
1991
2143
|
attributes[`${prefix}.header_variables`] = [...destination.headerVariables];
|
|
1992
2144
|
}
|
|
@@ -2005,6 +2157,8 @@ var describeResolvedConfig = (config) => {
|
|
|
2005
2157
|
};
|
|
2006
2158
|
const endpointOrigin2 = originOf(config.exporter.endpoint);
|
|
2007
2159
|
const logsEndpointOrigin = originOf(config.exporter.logs.endpoint);
|
|
2160
|
+
const metrics = effectiveMetricsPolicy(config.exporter);
|
|
2161
|
+
const metricsEndpointOrigin = originOf(metrics.endpoint);
|
|
2008
2162
|
return {
|
|
2009
2163
|
"exporter.enabled": config.exporter.enabled,
|
|
2010
2164
|
"exporter.protocol": config.exporter.protocol,
|
|
@@ -2013,6 +2167,10 @@ var describeResolvedConfig = (config) => {
|
|
|
2013
2167
|
"exporter.logs_include_content": config.exporter.logs.includeContent,
|
|
2014
2168
|
"exporter.logs_max_batch_size": config.exporter.logs.maxBatchSize,
|
|
2015
2169
|
...logsEndpointOrigin === void 0 ? {} : { "exporter.logs_endpoint_origin": logsEndpointOrigin },
|
|
2170
|
+
"exporter.metrics_enabled": metrics.enabled,
|
|
2171
|
+
"exporter.metrics_temporality": metrics.temporality,
|
|
2172
|
+
"exporter.metrics_include_session_id": metrics.includeSessionId,
|
|
2173
|
+
...metricsEndpointOrigin === void 0 ? {} : { "exporter.metrics_endpoint_origin": metricsEndpointOrigin },
|
|
2016
2174
|
"exporter.header_names": [...config.exporter.headerNames],
|
|
2017
2175
|
// Names only. A resource attribute *name* is already on the wire in every
|
|
2018
2176
|
// exported resource, so disclosing it here adds nothing; a *value* may hold
|
|
@@ -2039,92 +2197,380 @@ var describeResolvedConfig = (config) => {
|
|
|
2039
2197
|
};
|
|
2040
2198
|
|
|
2041
2199
|
// src/runtime/ports.ts
|
|
2042
|
-
import { z as
|
|
2200
|
+
import { z as z16 } from "zod";
|
|
2043
2201
|
|
|
2044
|
-
// src/model/
|
|
2202
|
+
// src/model/events.ts
|
|
2203
|
+
import { z as z15 } from "zod";
|
|
2204
|
+
|
|
2205
|
+
// src/model/content.ts
|
|
2045
2206
|
import { z as z9 } from "zod";
|
|
2046
|
-
var
|
|
2047
|
-
|
|
2048
|
-
"
|
|
2049
|
-
"
|
|
2050
|
-
"
|
|
2207
|
+
var contentKindSchema = z9.enum([
|
|
2208
|
+
"prompt",
|
|
2209
|
+
"response",
|
|
2210
|
+
"reasoning",
|
|
2211
|
+
"tool-input",
|
|
2212
|
+
"tool-output",
|
|
2213
|
+
"error-message",
|
|
2214
|
+
"system-instruction",
|
|
2215
|
+
"attachment"
|
|
2051
2216
|
]);
|
|
2052
|
-
var
|
|
2053
|
-
var
|
|
2054
|
-
|
|
2055
|
-
|
|
2056
|
-
|
|
2057
|
-
|
|
2058
|
-
|
|
2059
|
-
|
|
2060
|
-
|
|
2061
|
-
|
|
2062
|
-
|
|
2063
|
-
|
|
2064
|
-
|
|
2065
|
-
/**
|
|
2066
|
-
|
|
2067
|
-
/**
|
|
2068
|
-
|
|
2217
|
+
var contentRoleSchema = z9.enum(["user", "assistant", "system", "tool", "unknown"]);
|
|
2218
|
+
var contentDisclosureSchema = z9.enum(["omitted", "masked", "redacted", "raw"]);
|
|
2219
|
+
var CONTENT_HASH_PATTERN = /^sha256:[0-9a-f]{64}$/;
|
|
2220
|
+
var contentFactSchema = z9.strictObject({
|
|
2221
|
+
kind: contentKindSchema,
|
|
2222
|
+
role: contentRoleSchema.optional(),
|
|
2223
|
+
/** Unicode code point count of the original content. */
|
|
2224
|
+
characterLength: z9.number().int().min(0),
|
|
2225
|
+
/** UTF-8 byte length of the original content. */
|
|
2226
|
+
byteLength: z9.number().int().min(0),
|
|
2227
|
+
/** Stable salted digest of the original content. */
|
|
2228
|
+
contentHash: z9.string().regex(CONTENT_HASH_PATTERN),
|
|
2229
|
+
disclosure: contentDisclosureSchema,
|
|
2230
|
+
/** Disclosed text, bounded by the privacy policy. Absent when omitted. */
|
|
2231
|
+
text: z9.string().optional(),
|
|
2232
|
+
/** True when `text` was cut short by the configured string bound. */
|
|
2233
|
+
truncated: z9.boolean(),
|
|
2234
|
+
/** Number of secret-looking spans replaced while producing `text`. */
|
|
2235
|
+
secretsRedacted: z9.number().int().min(0),
|
|
2236
|
+
/** Optional non-sensitive label, e.g. a MIME type or tool name. */
|
|
2237
|
+
label: nonEmptyStringSchema.optional()
|
|
2069
2238
|
});
|
|
2070
|
-
var
|
|
2071
|
-
|
|
2072
|
-
|
|
2073
|
-
|
|
2074
|
-
|
|
2075
|
-
|
|
2076
|
-
|
|
2077
|
-
|
|
2078
|
-
|
|
2079
|
-
|
|
2080
|
-
|
|
2081
|
-
|
|
2082
|
-
|
|
2083
|
-
|
|
2084
|
-
|
|
2085
|
-
|
|
2086
|
-
|
|
2087
|
-
|
|
2088
|
-
|
|
2089
|
-
|
|
2090
|
-
|
|
2091
|
-
|
|
2092
|
-
|
|
2093
|
-
|
|
2239
|
+
var contentFactsSchema = z9.array(contentFactSchema).max(64);
|
|
2240
|
+
var isContentFactConsistent = (fact) => fact.disclosure === "omitted" ? fact.text === void 0 : fact.text !== void 0;
|
|
2241
|
+
var isUnavailableContentFact = (fact) => fact.disclosure === "omitted" && fact.text === void 0 && fact.characterLength === 0 && fact.byteLength === 0;
|
|
2242
|
+
|
|
2243
|
+
// src/model/extensions.ts
|
|
2244
|
+
import { z as z10 } from "zod";
|
|
2245
|
+
var EXTENSION_KEY_PATTERN = /^[a-z][a-z0-9]*(?:[-_][a-z0-9]+)*(?:\.[a-z][a-z0-9]*(?:[-_][a-z0-9]+)*)+$/;
|
|
2246
|
+
var RESERVED_EXTENSION_NAMESPACES = Object.freeze([
|
|
2247
|
+
"otelhook",
|
|
2248
|
+
"otel",
|
|
2249
|
+
"telemetry"
|
|
2250
|
+
]);
|
|
2251
|
+
var MAX_EXTENSION_ENTRIES = 64;
|
|
2252
|
+
var extensionKeyNamespace = (key) => key.slice(0, key.indexOf("."));
|
|
2253
|
+
var isReservedExtensionNamespace = (key) => RESERVED_EXTENSION_NAMESPACES.includes(extensionKeyNamespace(key));
|
|
2254
|
+
var isValidExtensionKey = (key) => EXTENSION_KEY_PATTERN.test(key) && !isReservedExtensionNamespace(key);
|
|
2255
|
+
var extensionsSchema = z10.record(z10.string(), attributeValueSchema).check((ctx) => {
|
|
2256
|
+
const keys = Object.keys(ctx.value);
|
|
2257
|
+
if (keys.length > MAX_EXTENSION_ENTRIES) {
|
|
2258
|
+
ctx.issues.push({
|
|
2259
|
+
code: "custom",
|
|
2260
|
+
input: ctx.value,
|
|
2261
|
+
message: `extensions may contain at most ${MAX_EXTENSION_ENTRIES} entries`
|
|
2262
|
+
});
|
|
2094
2263
|
}
|
|
2095
|
-
|
|
2096
|
-
|
|
2264
|
+
for (const key of keys) {
|
|
2265
|
+
if (!EXTENSION_KEY_PATTERN.test(key)) {
|
|
2266
|
+
ctx.issues.push({
|
|
2267
|
+
code: "custom",
|
|
2268
|
+
input: ctx.value,
|
|
2269
|
+
path: [key],
|
|
2270
|
+
message: `extension key ${JSON.stringify(key)} must be namespaced, e.g. "acme.tier"`
|
|
2271
|
+
});
|
|
2272
|
+
continue;
|
|
2273
|
+
}
|
|
2274
|
+
if (isReservedExtensionNamespace(key)) {
|
|
2275
|
+
ctx.issues.push({
|
|
2276
|
+
code: "custom",
|
|
2277
|
+
input: ctx.value,
|
|
2278
|
+
path: [key],
|
|
2279
|
+
message: `extension namespace ${JSON.stringify(extensionKeyNamespace(key))} is reserved`
|
|
2280
|
+
});
|
|
2281
|
+
}
|
|
2097
2282
|
}
|
|
2098
|
-
|
|
2099
|
-
|
|
2100
|
-
|
|
2101
|
-
|
|
2102
|
-
|
|
2283
|
+
});
|
|
2284
|
+
var EMPTY_EXTENSIONS = Object.freeze({});
|
|
2285
|
+
var emptyExtensions = () => ({});
|
|
2286
|
+
|
|
2287
|
+
// src/model/identity.ts
|
|
2288
|
+
import { z as z11 } from "zod";
|
|
2289
|
+
var workspaceKeySourceSchema = z11.enum([
|
|
2290
|
+
"git-remote",
|
|
2291
|
+
"git-root",
|
|
2292
|
+
"working-directory",
|
|
2293
|
+
"explicit",
|
|
2294
|
+
"unknown"
|
|
2295
|
+
]);
|
|
2296
|
+
var workspaceIdentitySchema = z11.strictObject({
|
|
2297
|
+
workspaceId: workspaceIdSchema,
|
|
2298
|
+
keySource: workspaceKeySourceSchema,
|
|
2299
|
+
/** Repository name only; never an owner path or URL with credentials. */
|
|
2300
|
+
repositoryName: nonEmptyStringSchema.optional(),
|
|
2301
|
+
vcsBranchName: nonEmptyStringSchema.optional(),
|
|
2302
|
+
/** Opaque handle for the checked-out revision. */
|
|
2303
|
+
vcsRevisionId: nonEmptyStringSchema.optional()
|
|
2304
|
+
}).readonly();
|
|
2305
|
+
var UNKNOWN_WORKSPACE_ID = "unknown:0000000000000000";
|
|
2306
|
+
var unknownWorkspaceIdentity = () => workspaceIdentitySchema.parse({
|
|
2307
|
+
workspaceId: UNKNOWN_WORKSPACE_ID,
|
|
2308
|
+
keySource: "unknown"
|
|
2309
|
+
});
|
|
2310
|
+
var sourceProvenanceSchema = z11.strictObject({
|
|
2311
|
+
providerId: resolvedProviderIdSchema,
|
|
2312
|
+
providerVersion: nonEmptyStringSchema.optional(),
|
|
2313
|
+
adapterId: nonEmptyStringSchema,
|
|
2314
|
+
adapterVersion: nonEmptyStringSchema,
|
|
2315
|
+
detectionConfidence: detectionConfidenceSchema,
|
|
2316
|
+
/** The provider's own name for the source event, e.g. a hook event name. */
|
|
2317
|
+
sourceEventName: nonEmptyStringSchema.optional(),
|
|
2318
|
+
transport: sourceTransportSchema
|
|
2319
|
+
}).readonly();
|
|
2320
|
+
var consumerAttributesSchema = attributesSchema.readonly();
|
|
2321
|
+
var invocationIdentitySchema = z11.strictObject({
|
|
2322
|
+
invocationId: invocationIdSchema,
|
|
2323
|
+
sessionId: sessionIdSchema,
|
|
2324
|
+
/** Set when this invocation runs beneath another agent invocation. */
|
|
2325
|
+
parentInvocationId: invocationIdSchema.optional(),
|
|
2326
|
+
/** Root of the session tree when the provider exposes one. */
|
|
2327
|
+
rootSessionId: sessionIdSchema.optional(),
|
|
2328
|
+
/** Stable handle for the agent process/instance, when available. */
|
|
2329
|
+
agentInstanceId: nonEmptyStringSchema.optional(),
|
|
2330
|
+
provenance: sourceProvenanceSchema,
|
|
2331
|
+
workspace: workspaceIdentitySchema,
|
|
2332
|
+
startedAt: epochMillisSchema,
|
|
2333
|
+
consumerAttributes: consumerAttributesSchema
|
|
2334
|
+
}).readonly();
|
|
2335
|
+
var identityClaimFieldsSchema = z11.strictObject({
|
|
2336
|
+
invocationId: invocationIdSchema.optional(),
|
|
2337
|
+
sessionId: sessionIdSchema.optional(),
|
|
2338
|
+
parentInvocationId: invocationIdSchema.optional(),
|
|
2339
|
+
rootSessionId: sessionIdSchema.optional(),
|
|
2340
|
+
agentInstanceId: nonEmptyStringSchema.optional(),
|
|
2341
|
+
workspace: workspaceIdentitySchema.optional(),
|
|
2342
|
+
startedAt: epochMillisSchema.optional()
|
|
2343
|
+
});
|
|
2344
|
+
var identityClaimSchema = z11.strictObject({
|
|
2345
|
+
/** Non-sensitive label, e.g. `adapter:acme-cli` or `env:OTEL_HOOK_SESSION_ID`. */
|
|
2346
|
+
source: nonEmptyStringSchema,
|
|
2347
|
+
confidence: detectionConfidenceSchema,
|
|
2348
|
+
fields: identityClaimFieldsSchema
|
|
2349
|
+
});
|
|
2350
|
+
var CLAIM_FIELDS = [
|
|
2351
|
+
"invocationId",
|
|
2352
|
+
"sessionId",
|
|
2353
|
+
"parentInvocationId",
|
|
2354
|
+
"rootSessionId",
|
|
2355
|
+
"agentInstanceId",
|
|
2356
|
+
"workspace",
|
|
2357
|
+
"startedAt"
|
|
2358
|
+
];
|
|
2359
|
+
var renderClaimValue = (value) => {
|
|
2360
|
+
if (typeof value === "string") {
|
|
2361
|
+
return value;
|
|
2103
2362
|
}
|
|
2104
|
-
|
|
2105
|
-
|
|
2106
|
-
push(`uncachedInputTokens must equal ${expectedUncached}`);
|
|
2363
|
+
if (typeof value === "number" || typeof value === "boolean") {
|
|
2364
|
+
return String(value);
|
|
2107
2365
|
}
|
|
2108
|
-
|
|
2109
|
-
|
|
2110
|
-
|
|
2111
|
-
push(`totalTokens must equal ${expectedTotal}`);
|
|
2366
|
+
if (value !== null && typeof value === "object" && "workspaceId" in value) {
|
|
2367
|
+
const { workspaceId } = value;
|
|
2368
|
+
return typeof workspaceId === "string" ? workspaceId : "<workspace>";
|
|
2112
2369
|
}
|
|
2113
|
-
|
|
2114
|
-
|
|
2115
|
-
|
|
2370
|
+
return "<opaque>";
|
|
2371
|
+
};
|
|
2372
|
+
var resolveInvocationIdentity = (input) => {
|
|
2373
|
+
const parsedClaims = [];
|
|
2374
|
+
const issues = [];
|
|
2375
|
+
for (const [index, claim] of input.claims.entries()) {
|
|
2376
|
+
const parsed2 = identityClaimSchema.safeParse(claim);
|
|
2377
|
+
if (parsed2.success) {
|
|
2378
|
+
parsedClaims.push(parsed2.data);
|
|
2379
|
+
} else {
|
|
2380
|
+
issues.push(
|
|
2381
|
+
`claim[${index}]: ${parsed2.error.issues.map((issue) => `${issue.path.join(".") || "<root>"} ${issue.message}`).join(", ")}`
|
|
2382
|
+
);
|
|
2383
|
+
}
|
|
2116
2384
|
}
|
|
2117
|
-
|
|
2118
|
-
|
|
2119
|
-
|
|
2120
|
-
|
|
2121
|
-
|
|
2122
|
-
|
|
2123
|
-
|
|
2124
|
-
|
|
2125
|
-
|
|
2126
|
-
|
|
2127
|
-
|
|
2385
|
+
if (issues.length > 0) {
|
|
2386
|
+
return { status: "invalid", issues };
|
|
2387
|
+
}
|
|
2388
|
+
const conflicts = [];
|
|
2389
|
+
const selected = {};
|
|
2390
|
+
for (const field of CLAIM_FIELDS) {
|
|
2391
|
+
const contributors = parsedClaims.filter((claim) => claim.fields[field] !== void 0);
|
|
2392
|
+
if (contributors.length === 0) {
|
|
2393
|
+
continue;
|
|
2394
|
+
}
|
|
2395
|
+
const bestRank = Math.max(
|
|
2396
|
+
...contributors.map((claim) => DETECTION_CONFIDENCE_RANK[claim.confidence])
|
|
2397
|
+
);
|
|
2398
|
+
const best = contributors.filter(
|
|
2399
|
+
(claim) => DETECTION_CONFIDENCE_RANK[claim.confidence] === bestRank
|
|
2400
|
+
);
|
|
2401
|
+
const rendered = /* @__PURE__ */ new Map();
|
|
2402
|
+
for (const claim of best) {
|
|
2403
|
+
const key = JSON.stringify(claim.fields[field]);
|
|
2404
|
+
const sources = rendered.get(key) ?? [];
|
|
2405
|
+
sources.push(claim.source);
|
|
2406
|
+
rendered.set(key, sources);
|
|
2407
|
+
}
|
|
2408
|
+
if (rendered.size > 1) {
|
|
2409
|
+
const [firstBest] = best;
|
|
2410
|
+
conflicts.push({
|
|
2411
|
+
field,
|
|
2412
|
+
confidence: firstBest?.confidence ?? "none",
|
|
2413
|
+
values: best.map((claim) => renderClaimValue(claim.fields[field])),
|
|
2414
|
+
sources: best.map((claim) => claim.source)
|
|
2415
|
+
});
|
|
2416
|
+
continue;
|
|
2417
|
+
}
|
|
2418
|
+
const [winner] = best;
|
|
2419
|
+
if (winner !== void 0) {
|
|
2420
|
+
selected[field] = winner.fields[field];
|
|
2421
|
+
}
|
|
2422
|
+
}
|
|
2423
|
+
if (conflicts.length > 0) {
|
|
2424
|
+
return { status: "conflict", conflicts };
|
|
2425
|
+
}
|
|
2426
|
+
const missing = [];
|
|
2427
|
+
if (selected.invocationId === void 0) {
|
|
2428
|
+
missing.push("invocationId");
|
|
2429
|
+
}
|
|
2430
|
+
if (selected.sessionId === void 0) {
|
|
2431
|
+
missing.push("sessionId");
|
|
2432
|
+
}
|
|
2433
|
+
if (missing.length > 0) {
|
|
2434
|
+
return { status: "incomplete", missing };
|
|
2435
|
+
}
|
|
2436
|
+
const startedAt = selected.startedAt ?? input.fallback?.startedAt;
|
|
2437
|
+
if (startedAt === void 0) {
|
|
2438
|
+
return { status: "incomplete", missing: ["startedAt"] };
|
|
2439
|
+
}
|
|
2440
|
+
const workspace = selected.workspace ?? input.fallback?.workspace ?? unknownWorkspaceIdentity();
|
|
2441
|
+
const candidate = {
|
|
2442
|
+
invocationId: selected.invocationId,
|
|
2443
|
+
sessionId: selected.sessionId,
|
|
2444
|
+
...selected.parentInvocationId === void 0 ? {} : { parentInvocationId: selected.parentInvocationId },
|
|
2445
|
+
...selected.rootSessionId === void 0 ? {} : { rootSessionId: selected.rootSessionId },
|
|
2446
|
+
...selected.agentInstanceId === void 0 ? {} : { agentInstanceId: selected.agentInstanceId },
|
|
2447
|
+
provenance: input.provenance,
|
|
2448
|
+
workspace,
|
|
2449
|
+
startedAt,
|
|
2450
|
+
consumerAttributes: input.consumerAttributes ?? {}
|
|
2451
|
+
};
|
|
2452
|
+
const parsed = invocationIdentitySchema.safeParse(candidate);
|
|
2453
|
+
if (!parsed.success) {
|
|
2454
|
+
return {
|
|
2455
|
+
status: "invalid",
|
|
2456
|
+
issues: parsed.error.issues.map(
|
|
2457
|
+
(issue) => `${issue.path.join(".") || "<root>"}: ${issue.message}`
|
|
2458
|
+
)
|
|
2459
|
+
};
|
|
2460
|
+
}
|
|
2461
|
+
return { status: "resolved", identity: parsed.data };
|
|
2462
|
+
};
|
|
2463
|
+
|
|
2464
|
+
// src/model/target.ts
|
|
2465
|
+
import { z as z12 } from "zod";
|
|
2466
|
+
var targetSourceSchema = z12.enum(["tool-path", "shell-cwd", "session-cwd"]);
|
|
2467
|
+
var MAX_TARGET_HINT_PATHS = 8;
|
|
2468
|
+
var MAX_TARGET_PATH_LENGTH = 4096;
|
|
2469
|
+
var localPathSchema = z12.string().min(1).max(MAX_TARGET_PATH_LENGTH).refine((value) => !value.includes("\0"), "path must not contain NUL");
|
|
2470
|
+
var targetHintSchema = z12.strictObject({
|
|
2471
|
+
source: targetSourceSchema,
|
|
2472
|
+
paths: z12.array(localPathSchema).min(1).max(MAX_TARGET_HINT_PATHS).readonly(),
|
|
2473
|
+
/** Absolute directory that relative `paths` resolve against. */
|
|
2474
|
+
baseDirectory: localPathSchema.optional()
|
|
2475
|
+
}).readonly();
|
|
2476
|
+
var sessionCwdHint = (cwd) => cwd === void 0 || cwd.length === 0 ? void 0 : { source: "session-cwd", paths: [cwd] };
|
|
2477
|
+
var worktreeKindSchema = z12.enum(["main", "linked"]);
|
|
2478
|
+
var workspaceTargetSchema = z12.strictObject({
|
|
2479
|
+
workspaceId: workspaceIdSchema,
|
|
2480
|
+
/** Branch checked out in that worktree; absent on a detached HEAD. */
|
|
2481
|
+
vcsBranchName: nonEmptyStringSchema.optional(),
|
|
2482
|
+
source: targetSourceSchema,
|
|
2483
|
+
/** `git-root` handle of the repository's main worktree; absent when there is none to name. */
|
|
2484
|
+
repositoryId: workspaceIdSchema.optional(),
|
|
2485
|
+
worktreeKind: worktreeKindSchema.optional()
|
|
2486
|
+
}).readonly();
|
|
2487
|
+
var SUBAGENT_ID_PATTERN = /^[A-Za-z0-9_.:@+=-]{1,256}$/;
|
|
2488
|
+
var subagentIdSchema = z12.string().regex(SUBAGENT_ID_PATTERN);
|
|
2489
|
+
|
|
2490
|
+
// src/model/usage.ts
|
|
2491
|
+
import { z as z13 } from "zod";
|
|
2492
|
+
var usageTemporalitySchema = z13.enum(["delta", "cumulative"]);
|
|
2493
|
+
var cacheCreationAccountingSchema = z13.enum([
|
|
2494
|
+
"included-in-input",
|
|
2495
|
+
"disjoint-from-input",
|
|
2496
|
+
"not-reported"
|
|
2497
|
+
]);
|
|
2498
|
+
var providerTotalAgreementSchema = z13.enum(["unreported", "agrees", "disagrees"]);
|
|
2499
|
+
var usageReportSchema = z13.strictObject({
|
|
2500
|
+
temporality: usageTemporalitySchema,
|
|
2501
|
+
/** Inclusive input tokens. */
|
|
2502
|
+
inputTokens: tokenCountSchema.optional(),
|
|
2503
|
+
/** Subset of `inputTokens` served from a prompt cache. */
|
|
2504
|
+
cachedInputTokens: tokenCountSchema.optional(),
|
|
2505
|
+
/** Tokens written to a prompt cache. */
|
|
2506
|
+
cacheCreationInputTokens: tokenCountSchema.optional(),
|
|
2507
|
+
/** Required when `cacheCreationInputTokens` is present and non-zero. */
|
|
2508
|
+
cacheCreationAccounting: cacheCreationAccountingSchema.optional(),
|
|
2509
|
+
/** Inclusive output tokens. */
|
|
2510
|
+
outputTokens: tokenCountSchema.optional(),
|
|
2511
|
+
/** Subset of `outputTokens` spent on reasoning. */
|
|
2512
|
+
reasoningOutputTokens: tokenCountSchema.optional(),
|
|
2513
|
+
/** Total exactly as the provider reported it, if it reported one. */
|
|
2514
|
+
providerTotalTokens: tokenCountSchema.optional()
|
|
2515
|
+
});
|
|
2516
|
+
var canonicalUsageSchema = z13.strictObject({
|
|
2517
|
+
temporality: usageTemporalitySchema,
|
|
2518
|
+
inputTokens: tokenCountSchema,
|
|
2519
|
+
cachedInputTokens: tokenCountSchema,
|
|
2520
|
+
cacheCreationInputTokens: tokenCountSchema,
|
|
2521
|
+
cacheCreationAccounting: cacheCreationAccountingSchema,
|
|
2522
|
+
outputTokens: tokenCountSchema,
|
|
2523
|
+
reasoningOutputTokens: tokenCountSchema,
|
|
2524
|
+
/** Derived: input tokens that were neither cache reads nor cache writes. */
|
|
2525
|
+
uncachedInputTokens: tokenCountSchema,
|
|
2526
|
+
/** Derived: canonical billable total. */
|
|
2527
|
+
totalTokens: tokenCountSchema,
|
|
2528
|
+
providerTotalTokens: tokenCountSchema.optional(),
|
|
2529
|
+
providerTotalAgreement: providerTotalAgreementSchema
|
|
2530
|
+
}).check((ctx) => {
|
|
2531
|
+
const usage = ctx.value;
|
|
2532
|
+
const push = (message) => {
|
|
2533
|
+
ctx.issues.push({ code: "custom", input: usage, message });
|
|
2534
|
+
};
|
|
2535
|
+
if (usage.cachedInputTokens > usage.inputTokens) {
|
|
2536
|
+
push("cachedInputTokens must not exceed inputTokens (it is a subset)");
|
|
2537
|
+
}
|
|
2538
|
+
if (usage.reasoningOutputTokens > usage.outputTokens) {
|
|
2539
|
+
push("reasoningOutputTokens must not exceed outputTokens (it is a subset)");
|
|
2540
|
+
}
|
|
2541
|
+
if (usage.cacheCreationAccounting === "not-reported" && usage.cacheCreationInputTokens !== 0) {
|
|
2542
|
+
push("cacheCreationInputTokens must be 0 when cacheCreationAccounting is not-reported");
|
|
2543
|
+
}
|
|
2544
|
+
const creationInsideInput = usage.cacheCreationAccounting === "included-in-input" ? usage.cacheCreationInputTokens : 0;
|
|
2545
|
+
if (usage.cachedInputTokens + creationInsideInput > usage.inputTokens) {
|
|
2546
|
+
push(
|
|
2547
|
+
"cachedInputTokens + cacheCreationInputTokens must not exceed inputTokens when cache creation is included in input"
|
|
2548
|
+
);
|
|
2549
|
+
}
|
|
2550
|
+
const expectedUncached = usage.inputTokens - usage.cachedInputTokens - creationInsideInput;
|
|
2551
|
+
if (expectedUncached >= 0 && usage.uncachedInputTokens !== expectedUncached) {
|
|
2552
|
+
push(`uncachedInputTokens must equal ${expectedUncached}`);
|
|
2553
|
+
}
|
|
2554
|
+
const creationOutsideInput = usage.cacheCreationAccounting === "disjoint-from-input" ? usage.cacheCreationInputTokens : 0;
|
|
2555
|
+
const expectedTotal = usage.inputTokens + creationOutsideInput + usage.outputTokens;
|
|
2556
|
+
if (usage.totalTokens !== expectedTotal) {
|
|
2557
|
+
push(`totalTokens must equal ${expectedTotal}`);
|
|
2558
|
+
}
|
|
2559
|
+
const expectedAgreement = usage.providerTotalTokens === void 0 ? "unreported" : usage.providerTotalTokens === expectedTotal ? "agrees" : "disagrees";
|
|
2560
|
+
if (usage.providerTotalAgreement !== expectedAgreement) {
|
|
2561
|
+
push(`providerTotalAgreement must be ${expectedAgreement}`);
|
|
2562
|
+
}
|
|
2563
|
+
});
|
|
2564
|
+
var normalizeUsage = (report) => {
|
|
2565
|
+
const parsed = usageReportSchema.safeParse(report);
|
|
2566
|
+
if (!parsed.success) {
|
|
2567
|
+
return {
|
|
2568
|
+
status: "invalid",
|
|
2569
|
+
issues: parsed.error.issues.map((issue) => ({
|
|
2570
|
+
code: "invalid-report",
|
|
2571
|
+
message: `${issue.path.join(".") || "<root>"}: ${issue.message}`
|
|
2572
|
+
}))
|
|
2573
|
+
};
|
|
2128
2574
|
}
|
|
2129
2575
|
const input = parsed.data;
|
|
2130
2576
|
const issues = [];
|
|
@@ -2267,15 +2713,201 @@ var toReport = (usage) => ({
|
|
|
2267
2713
|
...usage.providerTotalTokens === void 0 ? {} : { providerTotalTokens: usage.providerTotalTokens }
|
|
2268
2714
|
});
|
|
2269
2715
|
|
|
2716
|
+
// src/model/version.ts
|
|
2717
|
+
import { z as z14 } from "zod";
|
|
2718
|
+
var CANONICAL_SCHEMA_VERSION = 1;
|
|
2719
|
+
var canonicalSchemaVersionSchema = z14.literal(CANONICAL_SCHEMA_VERSION);
|
|
2720
|
+
|
|
2721
|
+
// src/model/events.ts
|
|
2722
|
+
var modelDescriptorSchema = z15.strictObject({
|
|
2723
|
+
modelId: nonEmptyStringSchema,
|
|
2724
|
+
/** Vendor of the model, e.g. `anthropic`. Distinct from the agent provider. */
|
|
2725
|
+
vendor: nonEmptyStringSchema.optional(),
|
|
2726
|
+
family: nonEmptyStringSchema.optional()
|
|
2727
|
+
});
|
|
2728
|
+
var costFactsSchema = z15.strictObject({
|
|
2729
|
+
/** ISO 4217 code. */
|
|
2730
|
+
currency: z15.string().length(3),
|
|
2731
|
+
amount: z15.number().min(0).finite(),
|
|
2732
|
+
source: z15.enum(["provider-reported", "computed"])
|
|
2733
|
+
});
|
|
2734
|
+
var canonicalEventTypeSchema = z15.enum([
|
|
2735
|
+
"session.start",
|
|
2736
|
+
"session.end",
|
|
2737
|
+
"prompt.submitted",
|
|
2738
|
+
"generation.start",
|
|
2739
|
+
"generation.end",
|
|
2740
|
+
"tool.start",
|
|
2741
|
+
"tool.end",
|
|
2742
|
+
"subagent.start",
|
|
2743
|
+
"subagent.end",
|
|
2744
|
+
"compaction.performed",
|
|
2745
|
+
"error.raised"
|
|
2746
|
+
]);
|
|
2747
|
+
var CANONICAL_EVENT_TYPES = canonicalEventTypeSchema.options;
|
|
2748
|
+
var outcomeSchema = z15.enum(["ok", "error", "cancelled", "timeout", "denied", "unknown"]);
|
|
2749
|
+
var baseEventFields = {
|
|
2750
|
+
schemaVersion: canonicalSchemaVersionSchema,
|
|
2751
|
+
eventId: eventIdSchema,
|
|
2752
|
+
invocationId: invocationIdSchema,
|
|
2753
|
+
sessionId: sessionIdSchema,
|
|
2754
|
+
/** Per-invocation ordering key. Stable across replays of the same input. */
|
|
2755
|
+
sequence: sequenceNumberSchema,
|
|
2756
|
+
occurredAt: epochMillisSchema,
|
|
2757
|
+
provenance: sourceProvenanceSchema,
|
|
2758
|
+
workspace: workspaceIdentitySchema,
|
|
2759
|
+
/**
|
|
2760
|
+
* The provider's own id for the subagent this event was emitted inside (e.g.
|
|
2761
|
+
* Claude Code's `agent_id`). Absent for the top-level agent. Set by the event
|
|
2762
|
+
* factory, never by hand.
|
|
2763
|
+
*/
|
|
2764
|
+
subagentId: subagentIdSchema.optional(),
|
|
2765
|
+
extensions: extensionsSchema.default(emptyExtensions)
|
|
2766
|
+
};
|
|
2767
|
+
var event = (shape) => z15.strictObject({ ...baseEventFields, ...shape });
|
|
2768
|
+
var sessionStartEventSchema = event({
|
|
2769
|
+
type: z15.literal("session.start"),
|
|
2770
|
+
sessionKind: z15.enum(["interactive", "non-interactive", "unknown"]),
|
|
2771
|
+
agentName: nonEmptyStringSchema.optional(),
|
|
2772
|
+
agentVersion: nonEmptyStringSchema.optional(),
|
|
2773
|
+
model: modelDescriptorSchema.optional(),
|
|
2774
|
+
/** The git worktree the session runs in, resolved by the core (ADR 0008). */
|
|
2775
|
+
target: workspaceTargetSchema.optional()
|
|
2776
|
+
});
|
|
2777
|
+
var sessionEndEventSchema = event({
|
|
2778
|
+
type: z15.literal("session.end"),
|
|
2779
|
+
reason: z15.enum(["completed", "aborted", "error", "timeout", "unknown"]),
|
|
2780
|
+
durationMillis: durationMillisSchema.optional(),
|
|
2781
|
+
/** Session totals, typically cumulative. */
|
|
2782
|
+
usage: canonicalUsageSchema.optional(),
|
|
2783
|
+
cost: costFactsSchema.optional()
|
|
2784
|
+
});
|
|
2785
|
+
var promptSubmittedEventSchema = event({
|
|
2786
|
+
type: z15.literal("prompt.submitted"),
|
|
2787
|
+
promptSource: z15.enum(["user", "automation", "resumed", "unknown"]),
|
|
2788
|
+
content: contentFactSchema.optional(),
|
|
2789
|
+
turnIndex: z15.number().int().min(0).optional(),
|
|
2790
|
+
/** The git worktree the session runs in, resolved by the core (ADR 0008). */
|
|
2791
|
+
target: workspaceTargetSchema.optional()
|
|
2792
|
+
});
|
|
2793
|
+
var generationStartEventSchema = event({
|
|
2794
|
+
type: z15.literal("generation.start"),
|
|
2795
|
+
generationId: nonEmptyStringSchema,
|
|
2796
|
+
model: modelDescriptorSchema,
|
|
2797
|
+
requestedMaxOutputTokens: tokenCountSchema.optional(),
|
|
2798
|
+
inputContent: contentFactsSchema.optional()
|
|
2799
|
+
});
|
|
2800
|
+
var generationEndEventSchema = event({
|
|
2801
|
+
type: z15.literal("generation.end"),
|
|
2802
|
+
generationId: nonEmptyStringSchema,
|
|
2803
|
+
model: modelDescriptorSchema,
|
|
2804
|
+
outcome: outcomeSchema,
|
|
2805
|
+
stopReason: nonEmptyStringSchema.optional(),
|
|
2806
|
+
durationMillis: durationMillisSchema.optional(),
|
|
2807
|
+
usage: canonicalUsageSchema.optional(),
|
|
2808
|
+
/**
|
|
2809
|
+
* True when `usage` is known to cover only part of the generation (for
|
|
2810
|
+
* example the last model request of a multi-request turn); false when the
|
|
2811
|
+
* provider or harness said it is the whole. Absent: not stated. Meaningless
|
|
2812
|
+
* without `usage`.
|
|
2813
|
+
*/
|
|
2814
|
+
usagePartial: z15.boolean().optional(),
|
|
2815
|
+
cost: costFactsSchema.optional(),
|
|
2816
|
+
outputContent: contentFactsSchema.optional()
|
|
2817
|
+
});
|
|
2818
|
+
var toolKindSchema = z15.enum([
|
|
2819
|
+
"read",
|
|
2820
|
+
"write",
|
|
2821
|
+
"execute",
|
|
2822
|
+
"search",
|
|
2823
|
+
"network",
|
|
2824
|
+
"delegate",
|
|
2825
|
+
"other",
|
|
2826
|
+
"unknown"
|
|
2827
|
+
]);
|
|
2828
|
+
var toolStartEventSchema = event({
|
|
2829
|
+
type: z15.literal("tool.start"),
|
|
2830
|
+
toolCallId: nonEmptyStringSchema,
|
|
2831
|
+
toolName: nonEmptyStringSchema,
|
|
2832
|
+
toolKind: toolKindSchema,
|
|
2833
|
+
generationId: nonEmptyStringSchema.optional(),
|
|
2834
|
+
input: contentFactSchema.optional(),
|
|
2835
|
+
/** The git worktree this call targeted, resolved by the core (ADR 0008). */
|
|
2836
|
+
target: workspaceTargetSchema.optional()
|
|
2837
|
+
});
|
|
2838
|
+
var toolEndEventSchema = event({
|
|
2839
|
+
type: z15.literal("tool.end"),
|
|
2840
|
+
toolCallId: nonEmptyStringSchema,
|
|
2841
|
+
toolName: nonEmptyStringSchema,
|
|
2842
|
+
outcome: outcomeSchema,
|
|
2843
|
+
durationMillis: durationMillisSchema.optional(),
|
|
2844
|
+
/** Present when the host asked for or recorded a permission decision. */
|
|
2845
|
+
permissionDecision: z15.enum(["allowed", "denied", "deferred", "not-required"]).optional(),
|
|
2846
|
+
output: contentFactSchema.optional(),
|
|
2847
|
+
/** The git worktree this call targeted, resolved by the core (ADR 0008). */
|
|
2848
|
+
target: workspaceTargetSchema.optional()
|
|
2849
|
+
});
|
|
2850
|
+
var subagentStartEventSchema = event({
|
|
2851
|
+
type: z15.literal("subagent.start"),
|
|
2852
|
+
subagentInvocationId: invocationIdSchema,
|
|
2853
|
+
subagentType: nonEmptyStringSchema.optional(),
|
|
2854
|
+
/** 0 for the top-level agent; 1 for its direct children. */
|
|
2855
|
+
delegationDepth: z15.number().int().min(0).max(64),
|
|
2856
|
+
model: modelDescriptorSchema.optional()
|
|
2857
|
+
});
|
|
2858
|
+
var subagentEndEventSchema = event({
|
|
2859
|
+
type: z15.literal("subagent.end"),
|
|
2860
|
+
subagentInvocationId: invocationIdSchema,
|
|
2861
|
+
outcome: outcomeSchema,
|
|
2862
|
+
durationMillis: durationMillisSchema.optional(),
|
|
2863
|
+
usage: canonicalUsageSchema.optional()
|
|
2864
|
+
});
|
|
2865
|
+
var compactionPerformedEventSchema = event({
|
|
2866
|
+
type: z15.literal("compaction.performed"),
|
|
2867
|
+
trigger: z15.enum(["automatic", "manual", "unknown"]),
|
|
2868
|
+
/** Provider-reported context size before and after compaction, if known. */
|
|
2869
|
+
contextTokensBefore: tokenCountSchema.optional(),
|
|
2870
|
+
contextTokensAfter: tokenCountSchema.optional(),
|
|
2871
|
+
droppedMessageCount: z15.number().int().min(0).optional(),
|
|
2872
|
+
usage: canonicalUsageSchema.optional()
|
|
2873
|
+
});
|
|
2874
|
+
var errorRaisedEventSchema = event({
|
|
2875
|
+
type: z15.literal("error.raised"),
|
|
2876
|
+
errorCode: otelHookErrorCodeSchema,
|
|
2877
|
+
severity: errorSeveritySchema,
|
|
2878
|
+
phase: errorPhaseSchema,
|
|
2879
|
+
retryable: z15.boolean(),
|
|
2880
|
+
/** Error text is content: it is described, never embedded verbatim by default. */
|
|
2881
|
+
message: contentFactSchema.optional(),
|
|
2882
|
+
/** Non-sensitive, provider-agnostic short label. */
|
|
2883
|
+
detail: nonEmptyStringSchema.optional()
|
|
2884
|
+
});
|
|
2885
|
+
var canonicalEventSchema = z15.discriminatedUnion("type", [
|
|
2886
|
+
sessionStartEventSchema,
|
|
2887
|
+
sessionEndEventSchema,
|
|
2888
|
+
promptSubmittedEventSchema,
|
|
2889
|
+
generationStartEventSchema,
|
|
2890
|
+
generationEndEventSchema,
|
|
2891
|
+
toolStartEventSchema,
|
|
2892
|
+
toolEndEventSchema,
|
|
2893
|
+
subagentStartEventSchema,
|
|
2894
|
+
subagentEndEventSchema,
|
|
2895
|
+
compactionPerformedEventSchema,
|
|
2896
|
+
errorRaisedEventSchema
|
|
2897
|
+
]);
|
|
2898
|
+
var TARGETED_EVENT_TYPES = ["session.start", "prompt.submitted", "tool.start", "tool.end"];
|
|
2899
|
+
var TARGETED = new Set(TARGETED_EVENT_TYPES);
|
|
2900
|
+
var isTargetedEvent = (event3) => TARGETED.has(event3.type);
|
|
2901
|
+
|
|
2270
2902
|
// src/runtime/ports.ts
|
|
2271
|
-
var appliedDeliverySchema =
|
|
2272
|
-
callbackId:
|
|
2903
|
+
var appliedDeliverySchema = z16.strictObject({
|
|
2904
|
+
callbackId: z16.string().regex(/^[A-Za-z0-9_-]{1,128}$/),
|
|
2273
2905
|
/** How many of that delivery's observations are folded in, counted from one. */
|
|
2274
|
-
applications:
|
|
2906
|
+
applications: z16.number().int().min(1).max(4096)
|
|
2275
2907
|
});
|
|
2276
|
-
var stateValueSchema =
|
|
2277
|
-
|
|
2278
|
-
kind:
|
|
2908
|
+
var stateValueSchema = z16.discriminatedUnion("kind", [
|
|
2909
|
+
z16.strictObject({
|
|
2910
|
+
kind: z16.literal("usage-cumulative"),
|
|
2279
2911
|
usage: canonicalUsageSchema,
|
|
2280
2912
|
/**
|
|
2281
2913
|
* Optional: absent on every record written before this field existed, which
|
|
@@ -2284,22 +2916,65 @@ var stateValueSchema = z10.discriminatedUnion("kind", [
|
|
|
2284
2916
|
*/
|
|
2285
2917
|
appliedDelivery: appliedDeliverySchema.optional()
|
|
2286
2918
|
}),
|
|
2287
|
-
|
|
2288
|
-
kind:
|
|
2919
|
+
z16.strictObject({
|
|
2920
|
+
kind: z16.literal("sequence"),
|
|
2289
2921
|
next: sequenceNumberSchema
|
|
2290
2922
|
}),
|
|
2291
|
-
|
|
2292
|
-
kind:
|
|
2923
|
+
z16.strictObject({
|
|
2924
|
+
kind: z16.literal("attributes"),
|
|
2293
2925
|
attributes: attributesSchema
|
|
2926
|
+
}),
|
|
2927
|
+
/**
|
|
2928
|
+
* The model a session last reported, so a later invocation whose payload names
|
|
2929
|
+
* none (Claude Code's `Stop`) can still say which model it was. A model id is
|
|
2930
|
+
* not sensitive (`modelDescriptorSchema`), and the descriptor is the strict,
|
|
2931
|
+
* bounded canonical shape, never a payload fragment.
|
|
2932
|
+
*/
|
|
2933
|
+
z16.strictObject({
|
|
2934
|
+
kind: z16.literal("session-model"),
|
|
2935
|
+
model: modelDescriptorSchema
|
|
2936
|
+
}),
|
|
2937
|
+
/**
|
|
2938
|
+
* How far a {@link PayloadEnricher} has read a session's append-only source
|
|
2939
|
+
* (Claude Code's transcript), so the next read starts where the last ended.
|
|
2940
|
+
* `source` is an opaque digest of what was read, never a path.
|
|
2941
|
+
*/
|
|
2942
|
+
/**
|
|
2943
|
+
* Running state of one metric series (issue #69), so a cumulative data point
|
|
2944
|
+
* exported by a later hook process continues the same total. Holds numbers and
|
|
2945
|
+
* a series digest only; the series' attributes are re-supplied by the caller
|
|
2946
|
+
* and never read back from disk.
|
|
2947
|
+
*/
|
|
2948
|
+
z16.strictObject({
|
|
2949
|
+
kind: z16.literal("metric-series"),
|
|
2950
|
+
/** Start of the cumulative interval. */
|
|
2951
|
+
startTimeMillis: epochMillisSchema,
|
|
2952
|
+
/** Counters: the running total. */
|
|
2953
|
+
value: z16.number().finite().min(0).optional(),
|
|
2954
|
+
/** Histograms: the running aggregation. */
|
|
2955
|
+
histogram: z16.strictObject({
|
|
2956
|
+
count: z16.number().int().min(0),
|
|
2957
|
+
sum: z16.number().finite().min(0),
|
|
2958
|
+
min: z16.number().finite(),
|
|
2959
|
+
max: z16.number().finite(),
|
|
2960
|
+
bucketCounts: z16.array(z16.number().int().min(0)).max(64)
|
|
2961
|
+
}).optional(),
|
|
2962
|
+
/** Opaque digest of the last delivery folded in; makes a replay a no-op. */
|
|
2963
|
+
appliedDelivery: z16.string().regex(/^[A-Za-z0-9_-]{1,128}$/).optional()
|
|
2964
|
+
}),
|
|
2965
|
+
z16.strictObject({
|
|
2966
|
+
kind: z16.literal("read-cursor"),
|
|
2967
|
+
source: z16.string().regex(/^[A-Za-z0-9_-]{1,128}$/),
|
|
2968
|
+
offset: z16.number().int().min(0).max(Number.MAX_SAFE_INTEGER)
|
|
2294
2969
|
})
|
|
2295
2970
|
]);
|
|
2296
|
-
var stateRecordSchema =
|
|
2971
|
+
var stateRecordSchema = z16.strictObject({
|
|
2297
2972
|
/** Incremented on each write; lets callers detect lost updates. */
|
|
2298
|
-
revision:
|
|
2973
|
+
revision: z16.number().int().min(0),
|
|
2299
2974
|
updatedAt: epochMillisSchema,
|
|
2300
2975
|
value: stateValueSchema
|
|
2301
2976
|
});
|
|
2302
|
-
var logLevelSchema =
|
|
2977
|
+
var logLevelSchema = z16.enum(["silent", "error", "warn", "info", "debug"]);
|
|
2303
2978
|
var LOG_LEVEL_RANK = Object.freeze({
|
|
2304
2979
|
silent: 0,
|
|
2305
2980
|
error: 1,
|
|
@@ -2386,6 +3061,12 @@ var policyFlagsToPatch = (policy) => {
|
|
|
2386
3061
|
...policy.logsEndpoint === void 0 ? {} : { endpoint: policy.logsEndpoint },
|
|
2387
3062
|
...policy.logsIncludeContent === void 0 ? {} : { includeContent: policy.logsIncludeContent }
|
|
2388
3063
|
};
|
|
3064
|
+
const metrics = {
|
|
3065
|
+
...policy.metricsEnabled === void 0 ? {} : { enabled: policy.metricsEnabled },
|
|
3066
|
+
...policy.metricsEndpoint === void 0 ? {} : { endpoint: policy.metricsEndpoint },
|
|
3067
|
+
...policy.metricsTemporality === void 0 ? {} : { temporality: policy.metricsTemporality },
|
|
3068
|
+
...policy.metricsIncludeSessionId === void 0 ? {} : { includeSessionId: policy.metricsIncludeSessionId }
|
|
3069
|
+
};
|
|
2389
3070
|
const exporter = {
|
|
2390
3071
|
...policy.exportDisabled === true ? { enabled: false } : {},
|
|
2391
3072
|
...policy.endpoint === void 0 ? {} : { endpoint: policy.endpoint },
|
|
@@ -2401,14 +3082,16 @@ var policyFlagsToPatch = (policy) => {
|
|
|
2401
3082
|
// value they are exported on every span by design, so there is nothing to
|
|
2402
3083
|
// keep out of the snapshot. The snapshot still reports names only.
|
|
2403
3084
|
...Object.keys(policy.resourceAttributes).length === 0 ? {} : { resourceAttributes: policy.resourceAttributes },
|
|
2404
|
-
...Object.keys(logs).length === 0 ? {} : { logs }
|
|
3085
|
+
...Object.keys(logs).length === 0 ? {} : { logs },
|
|
3086
|
+
...Object.keys(metrics).length === 0 ? {} : { metrics }
|
|
2405
3087
|
};
|
|
2406
3088
|
const privacy = policy.contentMode === void 0 ? {} : { contentMode: policy.contentMode };
|
|
2407
3089
|
const diagnostics = policy.logLevel === void 0 ? {} : { logLevel: policy.logLevel };
|
|
2408
3090
|
return {
|
|
2409
3091
|
...Object.keys(exporter).length === 0 ? {} : { exporter },
|
|
2410
3092
|
...Object.keys(privacy).length === 0 ? {} : { privacy },
|
|
2411
|
-
...Object.keys(diagnostics).length === 0 ? {} : { diagnostics }
|
|
3093
|
+
...Object.keys(diagnostics).length === 0 ? {} : { diagnostics },
|
|
3094
|
+
...policy.claudeTranscriptUsage === true ? { providers: { claudeCode: { readTranscriptUsage: true } } } : {}
|
|
2412
3095
|
};
|
|
2413
3096
|
};
|
|
2414
3097
|
var resolveCliExporterHeaders = (policy, io) => {
|
|
@@ -2543,59 +3226,8 @@ var summarizeHealth = (snapshots) => ({
|
|
|
2543
3226
|
subsystems: [...snapshots]
|
|
2544
3227
|
});
|
|
2545
3228
|
|
|
2546
|
-
// src/model/version.ts
|
|
2547
|
-
import { z as z11 } from "zod";
|
|
2548
|
-
var CANONICAL_SCHEMA_VERSION = 1;
|
|
2549
|
-
var canonicalSchemaVersionSchema = z11.literal(CANONICAL_SCHEMA_VERSION);
|
|
2550
|
-
|
|
2551
3229
|
// src/privacy/service.ts
|
|
2552
3230
|
import { createHash } from "crypto";
|
|
2553
|
-
|
|
2554
|
-
// src/model/extensions.ts
|
|
2555
|
-
import { z as z12 } from "zod";
|
|
2556
|
-
var EXTENSION_KEY_PATTERN = /^[a-z][a-z0-9]*(?:[-_][a-z0-9]+)*(?:\.[a-z][a-z0-9]*(?:[-_][a-z0-9]+)*)+$/;
|
|
2557
|
-
var RESERVED_EXTENSION_NAMESPACES = Object.freeze([
|
|
2558
|
-
"otelhook",
|
|
2559
|
-
"otel",
|
|
2560
|
-
"telemetry"
|
|
2561
|
-
]);
|
|
2562
|
-
var MAX_EXTENSION_ENTRIES = 64;
|
|
2563
|
-
var extensionKeyNamespace = (key) => key.slice(0, key.indexOf("."));
|
|
2564
|
-
var isReservedExtensionNamespace = (key) => RESERVED_EXTENSION_NAMESPACES.includes(extensionKeyNamespace(key));
|
|
2565
|
-
var isValidExtensionKey = (key) => EXTENSION_KEY_PATTERN.test(key) && !isReservedExtensionNamespace(key);
|
|
2566
|
-
var extensionsSchema = z12.record(z12.string(), attributeValueSchema).check((ctx) => {
|
|
2567
|
-
const keys = Object.keys(ctx.value);
|
|
2568
|
-
if (keys.length > MAX_EXTENSION_ENTRIES) {
|
|
2569
|
-
ctx.issues.push({
|
|
2570
|
-
code: "custom",
|
|
2571
|
-
input: ctx.value,
|
|
2572
|
-
message: `extensions may contain at most ${MAX_EXTENSION_ENTRIES} entries`
|
|
2573
|
-
});
|
|
2574
|
-
}
|
|
2575
|
-
for (const key of keys) {
|
|
2576
|
-
if (!EXTENSION_KEY_PATTERN.test(key)) {
|
|
2577
|
-
ctx.issues.push({
|
|
2578
|
-
code: "custom",
|
|
2579
|
-
input: ctx.value,
|
|
2580
|
-
path: [key],
|
|
2581
|
-
message: `extension key ${JSON.stringify(key)} must be namespaced, e.g. "acme.tier"`
|
|
2582
|
-
});
|
|
2583
|
-
continue;
|
|
2584
|
-
}
|
|
2585
|
-
if (isReservedExtensionNamespace(key)) {
|
|
2586
|
-
ctx.issues.push({
|
|
2587
|
-
code: "custom",
|
|
2588
|
-
input: ctx.value,
|
|
2589
|
-
path: [key],
|
|
2590
|
-
message: `extension namespace ${JSON.stringify(extensionKeyNamespace(key))} is reserved`
|
|
2591
|
-
});
|
|
2592
|
-
}
|
|
2593
|
-
}
|
|
2594
|
-
});
|
|
2595
|
-
var EMPTY_EXTENSIONS = Object.freeze({});
|
|
2596
|
-
var emptyExtensions = () => ({});
|
|
2597
|
-
|
|
2598
|
-
// src/privacy/service.ts
|
|
2599
3231
|
var compilePatterns = (sources, flags) => {
|
|
2600
3232
|
const compiled = [];
|
|
2601
3233
|
for (const source of sources) {
|
|
@@ -2813,11 +3445,11 @@ var createPrivacyService = (policyInput) => {
|
|
|
2813
3445
|
};
|
|
2814
3446
|
const flattenToAttributes = (value, prefix) => {
|
|
2815
3447
|
const attributes = {};
|
|
2816
|
-
const walk = (current,
|
|
3448
|
+
const walk = (current, path14) => {
|
|
2817
3449
|
if (typeof current === "string" || typeof current === "number" || typeof current === "boolean") {
|
|
2818
3450
|
const primitive = toAttributePrimitive(current);
|
|
2819
3451
|
if (primitive !== void 0) {
|
|
2820
|
-
attributes[
|
|
3452
|
+
attributes[path14] = primitive;
|
|
2821
3453
|
}
|
|
2822
3454
|
return;
|
|
2823
3455
|
}
|
|
@@ -2836,16 +3468,16 @@ var createPrivacyService = (policyInput) => {
|
|
|
2836
3468
|
primitives.push(entryPrimitive);
|
|
2837
3469
|
}
|
|
2838
3470
|
if (uniform) {
|
|
2839
|
-
attributes[
|
|
3471
|
+
attributes[path14] = primitives.slice(0, MAX_ATTRIBUTE_ARRAY_LENGTH);
|
|
2840
3472
|
return;
|
|
2841
3473
|
}
|
|
2842
3474
|
for (const [index, entry] of current.entries()) {
|
|
2843
|
-
walk(entry, `${
|
|
3475
|
+
walk(entry, `${path14}.${index}`);
|
|
2844
3476
|
}
|
|
2845
3477
|
return;
|
|
2846
3478
|
}
|
|
2847
3479
|
for (const [key, entry] of Object.entries(current)) {
|
|
2848
|
-
walk(entry,
|
|
3480
|
+
walk(entry, path14 === "" ? key : `${path14}.${key}`);
|
|
2849
3481
|
}
|
|
2850
3482
|
};
|
|
2851
3483
|
walk(value, prefix);
|
|
@@ -2889,229 +3521,52 @@ var createPrivacyService = (policyInput) => {
|
|
|
2889
3521
|
droppedKeys.push(key);
|
|
2890
3522
|
}
|
|
2891
3523
|
}
|
|
2892
|
-
return { extensions, droppedKeys };
|
|
2893
|
-
};
|
|
2894
|
-
return {
|
|
2895
|
-
policy,
|
|
2896
|
-
policyNotes: notes,
|
|
2897
|
-
hash,
|
|
2898
|
-
deriveOpaqueId: (namespace, value) => hash(`${namespace}\0${value}`),
|
|
2899
|
-
describeContent: describeText,
|
|
2900
|
-
describeUnavailableContent: (input) => ({
|
|
2901
|
-
kind: input.kind,
|
|
2902
|
-
...input.role === void 0 ? {} : { role: input.role },
|
|
2903
|
-
characterLength: 0,
|
|
2904
|
-
byteLength: 0,
|
|
2905
|
-
contentHash: hash(""),
|
|
2906
|
-
disclosure: "omitted",
|
|
2907
|
-
truncated: false,
|
|
2908
|
-
secretsRedacted: 0,
|
|
2909
|
-
...input.label === void 0 ? {} : { label: input.label }
|
|
2910
|
-
}),
|
|
2911
|
-
describeStructured: (input) => {
|
|
2912
|
-
const serialized = stableStringify(input.value);
|
|
2913
|
-
const sanitized = sanitizeStructured(input.value);
|
|
2914
|
-
const base = describeText({
|
|
2915
|
-
kind: input.kind,
|
|
2916
|
-
text: serialized,
|
|
2917
|
-
...input.role === void 0 ? {} : { role: input.role },
|
|
2918
|
-
...input.label === void 0 ? {} : { label: input.label }
|
|
2919
|
-
});
|
|
2920
|
-
if (base.text === void 0) {
|
|
2921
|
-
return base;
|
|
2922
|
-
}
|
|
2923
|
-
const disclosed = disclose(stableStringify(sanitized.value));
|
|
2924
|
-
return {
|
|
2925
|
-
...base,
|
|
2926
|
-
...disclosed.text === void 0 ? {} : { text: disclosed.text },
|
|
2927
|
-
truncated: base.truncated || disclosed.truncated,
|
|
2928
|
-
secretsRedacted: disclosed.secretsRedacted + sanitized.stats.redactedKeys
|
|
2929
|
-
};
|
|
2930
|
-
},
|
|
2931
|
-
isSecretKey,
|
|
2932
|
-
sanitizeStructured,
|
|
2933
|
-
flattenToAttributes,
|
|
2934
|
-
sanitizeAttributes,
|
|
2935
|
-
sanitizeExtensions,
|
|
2936
|
-
boundString
|
|
2937
|
-
};
|
|
2938
|
-
};
|
|
2939
|
-
|
|
2940
|
-
// src/model/identity.ts
|
|
2941
|
-
import { z as z13 } from "zod";
|
|
2942
|
-
var workspaceKeySourceSchema = z13.enum([
|
|
2943
|
-
"git-remote",
|
|
2944
|
-
"git-root",
|
|
2945
|
-
"working-directory",
|
|
2946
|
-
"explicit",
|
|
2947
|
-
"unknown"
|
|
2948
|
-
]);
|
|
2949
|
-
var workspaceIdentitySchema = z13.strictObject({
|
|
2950
|
-
workspaceId: workspaceIdSchema,
|
|
2951
|
-
keySource: workspaceKeySourceSchema,
|
|
2952
|
-
/** Repository name only; never an owner path or URL with credentials. */
|
|
2953
|
-
repositoryName: nonEmptyStringSchema.optional(),
|
|
2954
|
-
vcsBranchName: nonEmptyStringSchema.optional(),
|
|
2955
|
-
/** Opaque handle for the checked-out revision. */
|
|
2956
|
-
vcsRevisionId: nonEmptyStringSchema.optional()
|
|
2957
|
-
}).readonly();
|
|
2958
|
-
var UNKNOWN_WORKSPACE_ID = "unknown:0000000000000000";
|
|
2959
|
-
var unknownWorkspaceIdentity = () => workspaceIdentitySchema.parse({
|
|
2960
|
-
workspaceId: UNKNOWN_WORKSPACE_ID,
|
|
2961
|
-
keySource: "unknown"
|
|
2962
|
-
});
|
|
2963
|
-
var sourceProvenanceSchema = z13.strictObject({
|
|
2964
|
-
providerId: resolvedProviderIdSchema,
|
|
2965
|
-
providerVersion: nonEmptyStringSchema.optional(),
|
|
2966
|
-
adapterId: nonEmptyStringSchema,
|
|
2967
|
-
adapterVersion: nonEmptyStringSchema,
|
|
2968
|
-
detectionConfidence: detectionConfidenceSchema,
|
|
2969
|
-
/** The provider's own name for the source event, e.g. a hook event name. */
|
|
2970
|
-
sourceEventName: nonEmptyStringSchema.optional(),
|
|
2971
|
-
transport: sourceTransportSchema
|
|
2972
|
-
}).readonly();
|
|
2973
|
-
var consumerAttributesSchema = attributesSchema.readonly();
|
|
2974
|
-
var invocationIdentitySchema = z13.strictObject({
|
|
2975
|
-
invocationId: invocationIdSchema,
|
|
2976
|
-
sessionId: sessionIdSchema,
|
|
2977
|
-
/** Set when this invocation runs beneath another agent invocation. */
|
|
2978
|
-
parentInvocationId: invocationIdSchema.optional(),
|
|
2979
|
-
/** Root of the session tree when the provider exposes one. */
|
|
2980
|
-
rootSessionId: sessionIdSchema.optional(),
|
|
2981
|
-
/** Stable handle for the agent process/instance, when available. */
|
|
2982
|
-
agentInstanceId: nonEmptyStringSchema.optional(),
|
|
2983
|
-
provenance: sourceProvenanceSchema,
|
|
2984
|
-
workspace: workspaceIdentitySchema,
|
|
2985
|
-
startedAt: epochMillisSchema,
|
|
2986
|
-
consumerAttributes: consumerAttributesSchema
|
|
2987
|
-
}).readonly();
|
|
2988
|
-
var identityClaimFieldsSchema = z13.strictObject({
|
|
2989
|
-
invocationId: invocationIdSchema.optional(),
|
|
2990
|
-
sessionId: sessionIdSchema.optional(),
|
|
2991
|
-
parentInvocationId: invocationIdSchema.optional(),
|
|
2992
|
-
rootSessionId: sessionIdSchema.optional(),
|
|
2993
|
-
agentInstanceId: nonEmptyStringSchema.optional(),
|
|
2994
|
-
workspace: workspaceIdentitySchema.optional(),
|
|
2995
|
-
startedAt: epochMillisSchema.optional()
|
|
2996
|
-
});
|
|
2997
|
-
var identityClaimSchema = z13.strictObject({
|
|
2998
|
-
/** Non-sensitive label, e.g. `adapter:acme-cli` or `env:OTEL_HOOK_SESSION_ID`. */
|
|
2999
|
-
source: nonEmptyStringSchema,
|
|
3000
|
-
confidence: detectionConfidenceSchema,
|
|
3001
|
-
fields: identityClaimFieldsSchema
|
|
3002
|
-
});
|
|
3003
|
-
var CLAIM_FIELDS = [
|
|
3004
|
-
"invocationId",
|
|
3005
|
-
"sessionId",
|
|
3006
|
-
"parentInvocationId",
|
|
3007
|
-
"rootSessionId",
|
|
3008
|
-
"agentInstanceId",
|
|
3009
|
-
"workspace",
|
|
3010
|
-
"startedAt"
|
|
3011
|
-
];
|
|
3012
|
-
var renderClaimValue = (value) => {
|
|
3013
|
-
if (typeof value === "string") {
|
|
3014
|
-
return value;
|
|
3015
|
-
}
|
|
3016
|
-
if (typeof value === "number" || typeof value === "boolean") {
|
|
3017
|
-
return String(value);
|
|
3018
|
-
}
|
|
3019
|
-
if (value !== null && typeof value === "object" && "workspaceId" in value) {
|
|
3020
|
-
const { workspaceId } = value;
|
|
3021
|
-
return typeof workspaceId === "string" ? workspaceId : "<workspace>";
|
|
3022
|
-
}
|
|
3023
|
-
return "<opaque>";
|
|
3024
|
-
};
|
|
3025
|
-
var resolveInvocationIdentity = (input) => {
|
|
3026
|
-
const parsedClaims = [];
|
|
3027
|
-
const issues = [];
|
|
3028
|
-
for (const [index, claim] of input.claims.entries()) {
|
|
3029
|
-
const parsed2 = identityClaimSchema.safeParse(claim);
|
|
3030
|
-
if (parsed2.success) {
|
|
3031
|
-
parsedClaims.push(parsed2.data);
|
|
3032
|
-
} else {
|
|
3033
|
-
issues.push(
|
|
3034
|
-
`claim[${index}]: ${parsed2.error.issues.map((issue) => `${issue.path.join(".") || "<root>"} ${issue.message}`).join(", ")}`
|
|
3035
|
-
);
|
|
3036
|
-
}
|
|
3037
|
-
}
|
|
3038
|
-
if (issues.length > 0) {
|
|
3039
|
-
return { status: "invalid", issues };
|
|
3040
|
-
}
|
|
3041
|
-
const conflicts = [];
|
|
3042
|
-
const selected = {};
|
|
3043
|
-
for (const field of CLAIM_FIELDS) {
|
|
3044
|
-
const contributors = parsedClaims.filter((claim) => claim.fields[field] !== void 0);
|
|
3045
|
-
if (contributors.length === 0) {
|
|
3046
|
-
continue;
|
|
3047
|
-
}
|
|
3048
|
-
const bestRank = Math.max(
|
|
3049
|
-
...contributors.map((claim) => DETECTION_CONFIDENCE_RANK[claim.confidence])
|
|
3050
|
-
);
|
|
3051
|
-
const best = contributors.filter(
|
|
3052
|
-
(claim) => DETECTION_CONFIDENCE_RANK[claim.confidence] === bestRank
|
|
3053
|
-
);
|
|
3054
|
-
const rendered = /* @__PURE__ */ new Map();
|
|
3055
|
-
for (const claim of best) {
|
|
3056
|
-
const key = JSON.stringify(claim.fields[field]);
|
|
3057
|
-
const sources = rendered.get(key) ?? [];
|
|
3058
|
-
sources.push(claim.source);
|
|
3059
|
-
rendered.set(key, sources);
|
|
3060
|
-
}
|
|
3061
|
-
if (rendered.size > 1) {
|
|
3062
|
-
const [firstBest] = best;
|
|
3063
|
-
conflicts.push({
|
|
3064
|
-
field,
|
|
3065
|
-
confidence: firstBest?.confidence ?? "none",
|
|
3066
|
-
values: best.map((claim) => renderClaimValue(claim.fields[field])),
|
|
3067
|
-
sources: best.map((claim) => claim.source)
|
|
3068
|
-
});
|
|
3069
|
-
continue;
|
|
3070
|
-
}
|
|
3071
|
-
const [winner] = best;
|
|
3072
|
-
if (winner !== void 0) {
|
|
3073
|
-
selected[field] = winner.fields[field];
|
|
3074
|
-
}
|
|
3075
|
-
}
|
|
3076
|
-
if (conflicts.length > 0) {
|
|
3077
|
-
return { status: "conflict", conflicts };
|
|
3078
|
-
}
|
|
3079
|
-
const missing = [];
|
|
3080
|
-
if (selected.invocationId === void 0) {
|
|
3081
|
-
missing.push("invocationId");
|
|
3082
|
-
}
|
|
3083
|
-
if (selected.sessionId === void 0) {
|
|
3084
|
-
missing.push("sessionId");
|
|
3085
|
-
}
|
|
3086
|
-
if (missing.length > 0) {
|
|
3087
|
-
return { status: "incomplete", missing };
|
|
3088
|
-
}
|
|
3089
|
-
const startedAt = selected.startedAt ?? input.fallback?.startedAt;
|
|
3090
|
-
if (startedAt === void 0) {
|
|
3091
|
-
return { status: "incomplete", missing: ["startedAt"] };
|
|
3092
|
-
}
|
|
3093
|
-
const workspace = selected.workspace ?? input.fallback?.workspace ?? unknownWorkspaceIdentity();
|
|
3094
|
-
const candidate = {
|
|
3095
|
-
invocationId: selected.invocationId,
|
|
3096
|
-
sessionId: selected.sessionId,
|
|
3097
|
-
...selected.parentInvocationId === void 0 ? {} : { parentInvocationId: selected.parentInvocationId },
|
|
3098
|
-
...selected.rootSessionId === void 0 ? {} : { rootSessionId: selected.rootSessionId },
|
|
3099
|
-
...selected.agentInstanceId === void 0 ? {} : { agentInstanceId: selected.agentInstanceId },
|
|
3100
|
-
provenance: input.provenance,
|
|
3101
|
-
workspace,
|
|
3102
|
-
startedAt,
|
|
3103
|
-
consumerAttributes: input.consumerAttributes ?? {}
|
|
3524
|
+
return { extensions, droppedKeys };
|
|
3525
|
+
};
|
|
3526
|
+
return {
|
|
3527
|
+
policy,
|
|
3528
|
+
policyNotes: notes,
|
|
3529
|
+
hash,
|
|
3530
|
+
deriveOpaqueId: (namespace, value) => hash(`${namespace}\0${value}`),
|
|
3531
|
+
describeContent: describeText,
|
|
3532
|
+
describeUnavailableContent: (input) => ({
|
|
3533
|
+
kind: input.kind,
|
|
3534
|
+
...input.role === void 0 ? {} : { role: input.role },
|
|
3535
|
+
characterLength: 0,
|
|
3536
|
+
byteLength: 0,
|
|
3537
|
+
contentHash: hash(""),
|
|
3538
|
+
disclosure: "omitted",
|
|
3539
|
+
truncated: false,
|
|
3540
|
+
secretsRedacted: 0,
|
|
3541
|
+
...input.label === void 0 ? {} : { label: input.label }
|
|
3542
|
+
}),
|
|
3543
|
+
describeStructured: (input) => {
|
|
3544
|
+
const serialized = stableStringify(input.value);
|
|
3545
|
+
const sanitized = sanitizeStructured(input.value);
|
|
3546
|
+
const base = describeText({
|
|
3547
|
+
kind: input.kind,
|
|
3548
|
+
text: serialized,
|
|
3549
|
+
...input.role === void 0 ? {} : { role: input.role },
|
|
3550
|
+
...input.label === void 0 ? {} : { label: input.label }
|
|
3551
|
+
});
|
|
3552
|
+
if (base.text === void 0) {
|
|
3553
|
+
return base;
|
|
3554
|
+
}
|
|
3555
|
+
const disclosed = disclose(stableStringify(sanitized.value));
|
|
3556
|
+
return {
|
|
3557
|
+
...base,
|
|
3558
|
+
...disclosed.text === void 0 ? {} : { text: disclosed.text },
|
|
3559
|
+
truncated: base.truncated || disclosed.truncated,
|
|
3560
|
+
secretsRedacted: disclosed.secretsRedacted + sanitized.stats.redactedKeys
|
|
3561
|
+
};
|
|
3562
|
+
},
|
|
3563
|
+
isSecretKey,
|
|
3564
|
+
sanitizeStructured,
|
|
3565
|
+
flattenToAttributes,
|
|
3566
|
+
sanitizeAttributes,
|
|
3567
|
+
sanitizeExtensions,
|
|
3568
|
+
boundString
|
|
3104
3569
|
};
|
|
3105
|
-
const parsed = invocationIdentitySchema.safeParse(candidate);
|
|
3106
|
-
if (!parsed.success) {
|
|
3107
|
-
return {
|
|
3108
|
-
status: "invalid",
|
|
3109
|
-
issues: parsed.error.issues.map(
|
|
3110
|
-
(issue) => `${issue.path.join(".") || "<root>"}: ${issue.message}`
|
|
3111
|
-
)
|
|
3112
|
-
};
|
|
3113
|
-
}
|
|
3114
|
-
return { status: "resolved", identity: parsed.data };
|
|
3115
3570
|
};
|
|
3116
3571
|
|
|
3117
3572
|
// src/privacy/workspace.ts
|
|
@@ -3163,249 +3618,6 @@ var deriveWorkspaceIdentity = (privacy, input, labels = {}) => {
|
|
|
3163
3618
|
|
|
3164
3619
|
// src/providers/adapter.ts
|
|
3165
3620
|
import { z as z17 } from "zod";
|
|
3166
|
-
|
|
3167
|
-
// src/model/events.ts
|
|
3168
|
-
import { z as z16 } from "zod";
|
|
3169
|
-
|
|
3170
|
-
// src/model/content.ts
|
|
3171
|
-
import { z as z14 } from "zod";
|
|
3172
|
-
var contentKindSchema = z14.enum([
|
|
3173
|
-
"prompt",
|
|
3174
|
-
"response",
|
|
3175
|
-
"reasoning",
|
|
3176
|
-
"tool-input",
|
|
3177
|
-
"tool-output",
|
|
3178
|
-
"error-message",
|
|
3179
|
-
"system-instruction",
|
|
3180
|
-
"attachment"
|
|
3181
|
-
]);
|
|
3182
|
-
var contentRoleSchema = z14.enum(["user", "assistant", "system", "tool", "unknown"]);
|
|
3183
|
-
var contentDisclosureSchema = z14.enum(["omitted", "masked", "redacted", "raw"]);
|
|
3184
|
-
var CONTENT_HASH_PATTERN = /^sha256:[0-9a-f]{64}$/;
|
|
3185
|
-
var contentFactSchema = z14.strictObject({
|
|
3186
|
-
kind: contentKindSchema,
|
|
3187
|
-
role: contentRoleSchema.optional(),
|
|
3188
|
-
/** Unicode code point count of the original content. */
|
|
3189
|
-
characterLength: z14.number().int().min(0),
|
|
3190
|
-
/** UTF-8 byte length of the original content. */
|
|
3191
|
-
byteLength: z14.number().int().min(0),
|
|
3192
|
-
/** Stable salted digest of the original content. */
|
|
3193
|
-
contentHash: z14.string().regex(CONTENT_HASH_PATTERN),
|
|
3194
|
-
disclosure: contentDisclosureSchema,
|
|
3195
|
-
/** Disclosed text, bounded by the privacy policy. Absent when omitted. */
|
|
3196
|
-
text: z14.string().optional(),
|
|
3197
|
-
/** True when `text` was cut short by the configured string bound. */
|
|
3198
|
-
truncated: z14.boolean(),
|
|
3199
|
-
/** Number of secret-looking spans replaced while producing `text`. */
|
|
3200
|
-
secretsRedacted: z14.number().int().min(0),
|
|
3201
|
-
/** Optional non-sensitive label, e.g. a MIME type or tool name. */
|
|
3202
|
-
label: nonEmptyStringSchema.optional()
|
|
3203
|
-
});
|
|
3204
|
-
var contentFactsSchema = z14.array(contentFactSchema).max(64);
|
|
3205
|
-
var isContentFactConsistent = (fact) => fact.disclosure === "omitted" ? fact.text === void 0 : fact.text !== void 0;
|
|
3206
|
-
var isUnavailableContentFact = (fact) => fact.disclosure === "omitted" && fact.text === void 0 && fact.characterLength === 0 && fact.byteLength === 0;
|
|
3207
|
-
|
|
3208
|
-
// src/model/target.ts
|
|
3209
|
-
import { z as z15 } from "zod";
|
|
3210
|
-
var targetSourceSchema = z15.enum(["tool-path", "shell-cwd", "session-cwd"]);
|
|
3211
|
-
var MAX_TARGET_HINT_PATHS = 8;
|
|
3212
|
-
var MAX_TARGET_PATH_LENGTH = 4096;
|
|
3213
|
-
var localPathSchema = z15.string().min(1).max(MAX_TARGET_PATH_LENGTH).refine((value) => !value.includes("\0"), "path must not contain NUL");
|
|
3214
|
-
var targetHintSchema = z15.strictObject({
|
|
3215
|
-
source: targetSourceSchema,
|
|
3216
|
-
paths: z15.array(localPathSchema).min(1).max(MAX_TARGET_HINT_PATHS).readonly(),
|
|
3217
|
-
/** Absolute directory that relative `paths` resolve against. */
|
|
3218
|
-
baseDirectory: localPathSchema.optional()
|
|
3219
|
-
}).readonly();
|
|
3220
|
-
var sessionCwdHint = (cwd) => cwd === void 0 || cwd.length === 0 ? void 0 : { source: "session-cwd", paths: [cwd] };
|
|
3221
|
-
var worktreeKindSchema = z15.enum(["main", "linked"]);
|
|
3222
|
-
var workspaceTargetSchema = z15.strictObject({
|
|
3223
|
-
workspaceId: workspaceIdSchema,
|
|
3224
|
-
/** Branch checked out in that worktree; absent on a detached HEAD. */
|
|
3225
|
-
vcsBranchName: nonEmptyStringSchema.optional(),
|
|
3226
|
-
source: targetSourceSchema,
|
|
3227
|
-
/** `git-root` handle of the repository's main worktree; absent when there is none to name. */
|
|
3228
|
-
repositoryId: workspaceIdSchema.optional(),
|
|
3229
|
-
worktreeKind: worktreeKindSchema.optional()
|
|
3230
|
-
}).readonly();
|
|
3231
|
-
var SUBAGENT_ID_PATTERN = /^[A-Za-z0-9_.:@+=-]{1,256}$/;
|
|
3232
|
-
var subagentIdSchema = z15.string().regex(SUBAGENT_ID_PATTERN);
|
|
3233
|
-
|
|
3234
|
-
// src/model/events.ts
|
|
3235
|
-
var modelDescriptorSchema = z16.strictObject({
|
|
3236
|
-
modelId: nonEmptyStringSchema,
|
|
3237
|
-
/** Vendor of the model, e.g. `anthropic`. Distinct from the agent provider. */
|
|
3238
|
-
vendor: nonEmptyStringSchema.optional(),
|
|
3239
|
-
family: nonEmptyStringSchema.optional()
|
|
3240
|
-
});
|
|
3241
|
-
var costFactsSchema = z16.strictObject({
|
|
3242
|
-
/** ISO 4217 code. */
|
|
3243
|
-
currency: z16.string().length(3),
|
|
3244
|
-
amount: z16.number().min(0).finite(),
|
|
3245
|
-
source: z16.enum(["provider-reported", "computed"])
|
|
3246
|
-
});
|
|
3247
|
-
var canonicalEventTypeSchema = z16.enum([
|
|
3248
|
-
"session.start",
|
|
3249
|
-
"session.end",
|
|
3250
|
-
"prompt.submitted",
|
|
3251
|
-
"generation.start",
|
|
3252
|
-
"generation.end",
|
|
3253
|
-
"tool.start",
|
|
3254
|
-
"tool.end",
|
|
3255
|
-
"subagent.start",
|
|
3256
|
-
"subagent.end",
|
|
3257
|
-
"compaction.performed",
|
|
3258
|
-
"error.raised"
|
|
3259
|
-
]);
|
|
3260
|
-
var CANONICAL_EVENT_TYPES = canonicalEventTypeSchema.options;
|
|
3261
|
-
var outcomeSchema = z16.enum(["ok", "error", "cancelled", "timeout", "denied", "unknown"]);
|
|
3262
|
-
var baseEventFields = {
|
|
3263
|
-
schemaVersion: canonicalSchemaVersionSchema,
|
|
3264
|
-
eventId: eventIdSchema,
|
|
3265
|
-
invocationId: invocationIdSchema,
|
|
3266
|
-
sessionId: sessionIdSchema,
|
|
3267
|
-
/** Per-invocation ordering key. Stable across replays of the same input. */
|
|
3268
|
-
sequence: sequenceNumberSchema,
|
|
3269
|
-
occurredAt: epochMillisSchema,
|
|
3270
|
-
provenance: sourceProvenanceSchema,
|
|
3271
|
-
workspace: workspaceIdentitySchema,
|
|
3272
|
-
/**
|
|
3273
|
-
* The provider's own id for the subagent this event was emitted inside (e.g.
|
|
3274
|
-
* Claude Code's `agent_id`). Absent for the top-level agent. Set by the event
|
|
3275
|
-
* factory, never by hand.
|
|
3276
|
-
*/
|
|
3277
|
-
subagentId: subagentIdSchema.optional(),
|
|
3278
|
-
extensions: extensionsSchema.default(emptyExtensions)
|
|
3279
|
-
};
|
|
3280
|
-
var event = (shape) => z16.strictObject({ ...baseEventFields, ...shape });
|
|
3281
|
-
var sessionStartEventSchema = event({
|
|
3282
|
-
type: z16.literal("session.start"),
|
|
3283
|
-
sessionKind: z16.enum(["interactive", "non-interactive", "unknown"]),
|
|
3284
|
-
agentName: nonEmptyStringSchema.optional(),
|
|
3285
|
-
agentVersion: nonEmptyStringSchema.optional(),
|
|
3286
|
-
model: modelDescriptorSchema.optional(),
|
|
3287
|
-
/** The git worktree the session runs in, resolved by the core (ADR 0008). */
|
|
3288
|
-
target: workspaceTargetSchema.optional()
|
|
3289
|
-
});
|
|
3290
|
-
var sessionEndEventSchema = event({
|
|
3291
|
-
type: z16.literal("session.end"),
|
|
3292
|
-
reason: z16.enum(["completed", "aborted", "error", "timeout", "unknown"]),
|
|
3293
|
-
durationMillis: durationMillisSchema.optional(),
|
|
3294
|
-
/** Session totals, typically cumulative. */
|
|
3295
|
-
usage: canonicalUsageSchema.optional(),
|
|
3296
|
-
cost: costFactsSchema.optional()
|
|
3297
|
-
});
|
|
3298
|
-
var promptSubmittedEventSchema = event({
|
|
3299
|
-
type: z16.literal("prompt.submitted"),
|
|
3300
|
-
promptSource: z16.enum(["user", "automation", "resumed", "unknown"]),
|
|
3301
|
-
content: contentFactSchema.optional(),
|
|
3302
|
-
turnIndex: z16.number().int().min(0).optional(),
|
|
3303
|
-
/** The git worktree the session runs in, resolved by the core (ADR 0008). */
|
|
3304
|
-
target: workspaceTargetSchema.optional()
|
|
3305
|
-
});
|
|
3306
|
-
var generationStartEventSchema = event({
|
|
3307
|
-
type: z16.literal("generation.start"),
|
|
3308
|
-
generationId: nonEmptyStringSchema,
|
|
3309
|
-
model: modelDescriptorSchema,
|
|
3310
|
-
requestedMaxOutputTokens: tokenCountSchema.optional(),
|
|
3311
|
-
inputContent: contentFactsSchema.optional()
|
|
3312
|
-
});
|
|
3313
|
-
var generationEndEventSchema = event({
|
|
3314
|
-
type: z16.literal("generation.end"),
|
|
3315
|
-
generationId: nonEmptyStringSchema,
|
|
3316
|
-
model: modelDescriptorSchema,
|
|
3317
|
-
outcome: outcomeSchema,
|
|
3318
|
-
stopReason: nonEmptyStringSchema.optional(),
|
|
3319
|
-
durationMillis: durationMillisSchema.optional(),
|
|
3320
|
-
usage: canonicalUsageSchema.optional(),
|
|
3321
|
-
cost: costFactsSchema.optional(),
|
|
3322
|
-
outputContent: contentFactsSchema.optional()
|
|
3323
|
-
});
|
|
3324
|
-
var toolKindSchema = z16.enum([
|
|
3325
|
-
"read",
|
|
3326
|
-
"write",
|
|
3327
|
-
"execute",
|
|
3328
|
-
"search",
|
|
3329
|
-
"network",
|
|
3330
|
-
"delegate",
|
|
3331
|
-
"other",
|
|
3332
|
-
"unknown"
|
|
3333
|
-
]);
|
|
3334
|
-
var toolStartEventSchema = event({
|
|
3335
|
-
type: z16.literal("tool.start"),
|
|
3336
|
-
toolCallId: nonEmptyStringSchema,
|
|
3337
|
-
toolName: nonEmptyStringSchema,
|
|
3338
|
-
toolKind: toolKindSchema,
|
|
3339
|
-
generationId: nonEmptyStringSchema.optional(),
|
|
3340
|
-
input: contentFactSchema.optional(),
|
|
3341
|
-
/** The git worktree this call targeted, resolved by the core (ADR 0008). */
|
|
3342
|
-
target: workspaceTargetSchema.optional()
|
|
3343
|
-
});
|
|
3344
|
-
var toolEndEventSchema = event({
|
|
3345
|
-
type: z16.literal("tool.end"),
|
|
3346
|
-
toolCallId: nonEmptyStringSchema,
|
|
3347
|
-
toolName: nonEmptyStringSchema,
|
|
3348
|
-
outcome: outcomeSchema,
|
|
3349
|
-
durationMillis: durationMillisSchema.optional(),
|
|
3350
|
-
/** Present when the host asked for or recorded a permission decision. */
|
|
3351
|
-
permissionDecision: z16.enum(["allowed", "denied", "deferred", "not-required"]).optional(),
|
|
3352
|
-
output: contentFactSchema.optional(),
|
|
3353
|
-
/** The git worktree this call targeted, resolved by the core (ADR 0008). */
|
|
3354
|
-
target: workspaceTargetSchema.optional()
|
|
3355
|
-
});
|
|
3356
|
-
var subagentStartEventSchema = event({
|
|
3357
|
-
type: z16.literal("subagent.start"),
|
|
3358
|
-
subagentInvocationId: invocationIdSchema,
|
|
3359
|
-
subagentType: nonEmptyStringSchema.optional(),
|
|
3360
|
-
/** 0 for the top-level agent; 1 for its direct children. */
|
|
3361
|
-
delegationDepth: z16.number().int().min(0).max(64),
|
|
3362
|
-
model: modelDescriptorSchema.optional()
|
|
3363
|
-
});
|
|
3364
|
-
var subagentEndEventSchema = event({
|
|
3365
|
-
type: z16.literal("subagent.end"),
|
|
3366
|
-
subagentInvocationId: invocationIdSchema,
|
|
3367
|
-
outcome: outcomeSchema,
|
|
3368
|
-
durationMillis: durationMillisSchema.optional(),
|
|
3369
|
-
usage: canonicalUsageSchema.optional()
|
|
3370
|
-
});
|
|
3371
|
-
var compactionPerformedEventSchema = event({
|
|
3372
|
-
type: z16.literal("compaction.performed"),
|
|
3373
|
-
trigger: z16.enum(["automatic", "manual", "unknown"]),
|
|
3374
|
-
/** Provider-reported context size before and after compaction, if known. */
|
|
3375
|
-
contextTokensBefore: tokenCountSchema.optional(),
|
|
3376
|
-
contextTokensAfter: tokenCountSchema.optional(),
|
|
3377
|
-
droppedMessageCount: z16.number().int().min(0).optional(),
|
|
3378
|
-
usage: canonicalUsageSchema.optional()
|
|
3379
|
-
});
|
|
3380
|
-
var errorRaisedEventSchema = event({
|
|
3381
|
-
type: z16.literal("error.raised"),
|
|
3382
|
-
errorCode: otelHookErrorCodeSchema,
|
|
3383
|
-
severity: errorSeveritySchema,
|
|
3384
|
-
phase: errorPhaseSchema,
|
|
3385
|
-
retryable: z16.boolean(),
|
|
3386
|
-
/** Error text is content: it is described, never embedded verbatim by default. */
|
|
3387
|
-
message: contentFactSchema.optional(),
|
|
3388
|
-
/** Non-sensitive, provider-agnostic short label. */
|
|
3389
|
-
detail: nonEmptyStringSchema.optional()
|
|
3390
|
-
});
|
|
3391
|
-
var canonicalEventSchema = z16.discriminatedUnion("type", [
|
|
3392
|
-
sessionStartEventSchema,
|
|
3393
|
-
sessionEndEventSchema,
|
|
3394
|
-
promptSubmittedEventSchema,
|
|
3395
|
-
generationStartEventSchema,
|
|
3396
|
-
generationEndEventSchema,
|
|
3397
|
-
toolStartEventSchema,
|
|
3398
|
-
toolEndEventSchema,
|
|
3399
|
-
subagentStartEventSchema,
|
|
3400
|
-
subagentEndEventSchema,
|
|
3401
|
-
compactionPerformedEventSchema,
|
|
3402
|
-
errorRaisedEventSchema
|
|
3403
|
-
]);
|
|
3404
|
-
var TARGETED_EVENT_TYPES = ["session.start", "prompt.submitted", "tool.start", "tool.end"];
|
|
3405
|
-
var TARGETED = new Set(TARGETED_EVENT_TYPES);
|
|
3406
|
-
var isTargetedEvent = (event3) => TARGETED.has(event3.type);
|
|
3407
|
-
|
|
3408
|
-
// src/providers/adapter.ts
|
|
3409
3621
|
var providerDetectionSchema = z17.strictObject({
|
|
3410
3622
|
providerId: resolvedProviderIdSchema,
|
|
3411
3623
|
confidence: detectionConfidenceSchema,
|
|
@@ -4062,7 +4274,25 @@ var stopPayloadSchema2 = z19.object({
|
|
|
4062
4274
|
* the former without suppressing the latter.
|
|
4063
4275
|
*/
|
|
4064
4276
|
stop_hook_active: z19.boolean().optional(),
|
|
4065
|
-
usage: claudeUsageSchema.optional()
|
|
4277
|
+
usage: claudeUsageSchema.optional(),
|
|
4278
|
+
/**
|
|
4279
|
+
* The model that answered this turn — harness-supplied, never upstream.
|
|
4280
|
+
*
|
|
4281
|
+
* Claude Code's `Stop` carries no model id; the per-turn model sits only at
|
|
4282
|
+
* `message.model` in the transcript, beside `message.usage`. A wrapping harness
|
|
4283
|
+
* that read it (for instance with `readClaudeTranscriptTurn`) attaches it here
|
|
4284
|
+
* with `usage`, and it becomes the generation's response model. An unusable
|
|
4285
|
+
* value (empty, over 256 characters, not a string) is dropped rather than
|
|
4286
|
+
* failing the whole payload: the turn is still worth reporting without it.
|
|
4287
|
+
*/
|
|
4288
|
+
model: z19.string().min(1).max(256).optional().catch(void 0),
|
|
4289
|
+
/**
|
|
4290
|
+
* Harness-supplied, never upstream: whether `usage` covers only part of the
|
|
4291
|
+
* turn. `true` when it is the last model request alone (the tail fallback),
|
|
4292
|
+
* `false` when it sums every request since the previous stop. Exported as
|
|
4293
|
+
* `otelhook.usage.partial`; absent means the attacher did not say.
|
|
4294
|
+
*/
|
|
4295
|
+
usage_partial: z19.boolean().optional().catch(void 0)
|
|
4066
4296
|
});
|
|
4067
4297
|
var stopFailurePayloadSchema = z19.object({
|
|
4068
4298
|
...commonFields2,
|
|
@@ -4074,7 +4304,11 @@ var stopFailurePayloadSchema = z19.object({
|
|
|
4074
4304
|
*/
|
|
4075
4305
|
error_type: z19.string().min(1),
|
|
4076
4306
|
error_message: z19.string().optional(),
|
|
4077
|
-
usage: claudeUsageSchema.optional()
|
|
4307
|
+
usage: claudeUsageSchema.optional(),
|
|
4308
|
+
/** Harness-supplied, never upstream: see `stopPayloadSchema.model`. */
|
|
4309
|
+
model: z19.string().min(1).max(256).optional().catch(void 0),
|
|
4310
|
+
/** Harness-supplied, never upstream: see `stopPayloadSchema.usage_partial`. */
|
|
4311
|
+
usage_partial: z19.boolean().optional().catch(void 0)
|
|
4078
4312
|
});
|
|
4079
4313
|
var claudeHookPayloadSchema = z19.discriminatedUnion("hook_event_name", [
|
|
4080
4314
|
sessionStartPayloadSchema,
|
|
@@ -4606,6 +4840,13 @@ var inferToolKind = (toolName) => {
|
|
|
4606
4840
|
|
|
4607
4841
|
// src/providers/claude/events.ts
|
|
4608
4842
|
var UNKNOWN_MODEL = { modelId: "unknown" };
|
|
4843
|
+
var generationModels = (attached, sessionModel) => {
|
|
4844
|
+
const turnModel = attached === void 0 ? void 0 : { modelId: attached };
|
|
4845
|
+
return {
|
|
4846
|
+
request: sessionModel ?? turnModel ?? UNKNOWN_MODEL,
|
|
4847
|
+
response: turnModel ?? sessionModel ?? UNKNOWN_MODEL
|
|
4848
|
+
};
|
|
4849
|
+
};
|
|
4609
4850
|
var SESSION_END_REASON = Object.freeze({
|
|
4610
4851
|
completed: "completed",
|
|
4611
4852
|
aborted: "aborted",
|
|
@@ -4672,6 +4913,10 @@ var parseClaudeCode = (input, context) => {
|
|
|
4672
4913
|
warnings.push(...normalized.warnings);
|
|
4673
4914
|
return applyUsage(normalized);
|
|
4674
4915
|
};
|
|
4916
|
+
const withPartialUsage = (usage, partial) => {
|
|
4917
|
+
const applied = withUsage(usage);
|
|
4918
|
+
return applied.usage === void 0 || partial === void 0 ? applied : { ...applied, usagePartial: partial };
|
|
4919
|
+
};
|
|
4675
4920
|
switch (payload.hook_event_name) {
|
|
4676
4921
|
case "SessionStart":
|
|
4677
4922
|
factory.build({
|
|
@@ -4784,11 +5029,12 @@ var parseClaudeCode = (input, context) => {
|
|
|
4784
5029
|
payload.prompt_id ?? String(input.sequenceBase)
|
|
4785
5030
|
]);
|
|
4786
5031
|
const assistantText = extractClaudeAssistantText(normalizedPayload);
|
|
4787
|
-
|
|
5032
|
+
const models = generationModels(payload.model, input.sessionModel);
|
|
5033
|
+
factory.build({ type: "generation.start", generationId, model: models.request });
|
|
4788
5034
|
factory.build({
|
|
4789
5035
|
type: "generation.end",
|
|
4790
5036
|
generationId,
|
|
4791
|
-
model:
|
|
5037
|
+
model: models.response,
|
|
4792
5038
|
outcome: "ok",
|
|
4793
5039
|
// Always a response fact: a body when Claude sent text, otherwise a
|
|
4794
5040
|
// zero-length omitted fact so the log mapping can emit metadata_only
|
|
@@ -4800,7 +5046,7 @@ var parseClaudeCode = (input, context) => {
|
|
|
4800
5046
|
text: assistantText
|
|
4801
5047
|
})
|
|
4802
5048
|
],
|
|
4803
|
-
...
|
|
5049
|
+
...withPartialUsage(extractedUsage ?? payload.usage, payload.usage_partial)
|
|
4804
5050
|
});
|
|
4805
5051
|
break;
|
|
4806
5052
|
}
|
|
@@ -4811,11 +5057,12 @@ var parseClaudeCode = (input, context) => {
|
|
|
4811
5057
|
payload.prompt_id ?? String(input.sequenceBase)
|
|
4812
5058
|
]);
|
|
4813
5059
|
const assistantText = extractClaudeAssistantText(normalizedPayload);
|
|
4814
|
-
|
|
5060
|
+
const models = generationModels(payload.model, input.sessionModel);
|
|
5061
|
+
factory.build({ type: "generation.start", generationId, model: models.request });
|
|
4815
5062
|
factory.build({
|
|
4816
5063
|
type: "generation.end",
|
|
4817
5064
|
generationId,
|
|
4818
|
-
model:
|
|
5065
|
+
model: models.response,
|
|
4819
5066
|
outcome: mapStopFailureOutcome(payload.error_type),
|
|
4820
5067
|
stopReason: payload.error_type,
|
|
4821
5068
|
...assistantText === void 0 ? {} : {
|
|
@@ -4827,7 +5074,7 @@ var parseClaudeCode = (input, context) => {
|
|
|
4827
5074
|
})
|
|
4828
5075
|
]
|
|
4829
5076
|
},
|
|
4830
|
-
...
|
|
5077
|
+
...withPartialUsage(extractedUsage ?? payload.usage, payload.usage_partial)
|
|
4831
5078
|
});
|
|
4832
5079
|
break;
|
|
4833
5080
|
}
|
|
@@ -8383,7 +8630,7 @@ import {
|
|
|
8383
8630
|
} from "@opentelemetry/semantic-conventions/incubating";
|
|
8384
8631
|
|
|
8385
8632
|
// src/version.ts
|
|
8386
|
-
var VERSION = "0.
|
|
8633
|
+
var VERSION = "0.11.0";
|
|
8387
8634
|
|
|
8388
8635
|
// src/telemetry/semconv.ts
|
|
8389
8636
|
var SCOPE_NAME = "@osfactory/otel-hook";
|
|
@@ -8396,6 +8643,7 @@ var ATTR_OTELHOOK_SPAN_PAIRING = "otelhook.span.pairing";
|
|
|
8396
8643
|
var ATTR_OTELHOOK_SPAN_ORPHAN = "otelhook.span.orphan";
|
|
8397
8644
|
var ATTR_OTELHOOK_OUTCOME = "otelhook.outcome";
|
|
8398
8645
|
var ATTR_OTELHOOK_RESET_DETECTED = "otelhook.usage.reset_detected";
|
|
8646
|
+
var ATTR_OTELHOOK_USAGE_PARTIAL = "otelhook.usage.partial";
|
|
8399
8647
|
var ATTR_OTELHOOK_TOOL_KIND = "otelhook.tool.kind";
|
|
8400
8648
|
var ATTR_OTELHOOK_DELEGATION_DEPTH = "otelhook.delegation_depth";
|
|
8401
8649
|
var ATTR_OTELHOOK_COMPACTION_TRIGGER = "otelhook.compaction.trigger";
|
|
@@ -8668,7 +8916,8 @@ var buildLifecycleSpan = (plan, resource, scope) => {
|
|
|
8668
8916
|
// Codex turn): the key a consumer stores a usage observation under.
|
|
8669
8917
|
[ATTR_OTELHOOK_GENERATION_ID]: group.ref.scopeKey,
|
|
8670
8918
|
...end?.outcome === void 0 ? {} : { [ATTR_OTELHOOK_OUTCOME]: end.outcome },
|
|
8671
|
-
...usageAttributes(end?.usage, false)
|
|
8919
|
+
...usageAttributes(end?.usage, false),
|
|
8920
|
+
...end?.usage === void 0 || end.usagePartial === void 0 ? {} : { [ATTR_OTELHOOK_USAGE_PARTIAL]: end.usagePartial }
|
|
8672
8921
|
};
|
|
8673
8922
|
status = outcomeStatus(end?.outcome);
|
|
8674
8923
|
break;
|
|
@@ -9066,7 +9315,8 @@ var eventAttributes = (event3) => {
|
|
|
9066
9315
|
...event3.model.vendor === void 0 ? {} : { [ATTR_GEN_AI_SYSTEM2]: event3.model.vendor },
|
|
9067
9316
|
[ATTR_OTELHOOK_OUTCOME2]: event3.outcome,
|
|
9068
9317
|
...event3.stopReason === void 0 ? {} : { [ATTR_OTELHOOK_STOP_REASON]: event3.stopReason },
|
|
9069
|
-
...usageAttributes2(event3.usage)
|
|
9318
|
+
...usageAttributes2(event3.usage),
|
|
9319
|
+
...event3.usage === void 0 || event3.usagePartial === void 0 ? {} : { [ATTR_OTELHOOK_USAGE_PARTIAL]: event3.usagePartial }
|
|
9070
9320
|
};
|
|
9071
9321
|
case "tool.start":
|
|
9072
9322
|
return {
|
|
@@ -9751,7 +10001,621 @@ var createOtlpTraceSink = (options) => {
|
|
|
9751
10001
|
}
|
|
9752
10002
|
};
|
|
9753
10003
|
return {
|
|
9754
|
-
emit,
|
|
10004
|
+
emit,
|
|
10005
|
+
flush,
|
|
10006
|
+
shutdown,
|
|
10007
|
+
health: () => health.snapshot(),
|
|
10008
|
+
drainSpool
|
|
10009
|
+
};
|
|
10010
|
+
};
|
|
10011
|
+
|
|
10012
|
+
// src/telemetry/metric-model.ts
|
|
10013
|
+
var TOKEN_USAGE_BUCKETS = Object.freeze([
|
|
10014
|
+
1,
|
|
10015
|
+
4,
|
|
10016
|
+
16,
|
|
10017
|
+
64,
|
|
10018
|
+
256,
|
|
10019
|
+
1024,
|
|
10020
|
+
4096,
|
|
10021
|
+
16384,
|
|
10022
|
+
65536,
|
|
10023
|
+
262144,
|
|
10024
|
+
1048576,
|
|
10025
|
+
4194304,
|
|
10026
|
+
16777216,
|
|
10027
|
+
67108864
|
|
10028
|
+
]);
|
|
10029
|
+
var OPERATION_DURATION_BUCKETS = Object.freeze([
|
|
10030
|
+
0.01,
|
|
10031
|
+
0.02,
|
|
10032
|
+
0.04,
|
|
10033
|
+
0.08,
|
|
10034
|
+
0.16,
|
|
10035
|
+
0.32,
|
|
10036
|
+
0.64,
|
|
10037
|
+
1.28,
|
|
10038
|
+
2.56,
|
|
10039
|
+
5.12,
|
|
10040
|
+
10.24,
|
|
10041
|
+
20.48,
|
|
10042
|
+
40.96,
|
|
10043
|
+
81.92
|
|
10044
|
+
]);
|
|
10045
|
+
var METRIC_TOKEN_USAGE = "gen_ai.client.token.usage";
|
|
10046
|
+
var METRIC_OPERATION_DURATION = "gen_ai.client.operation.duration";
|
|
10047
|
+
var METRIC_SESSIONS = "otelhook.sessions";
|
|
10048
|
+
var METRIC_TOOL_CALLS = "otelhook.tool.calls";
|
|
10049
|
+
var METRIC_COST_USAGE = "otelhook.cost.usage";
|
|
10050
|
+
var METRIC_INSTRUMENTS = Object.freeze({
|
|
10051
|
+
[METRIC_TOKEN_USAGE]: {
|
|
10052
|
+
name: METRIC_TOKEN_USAGE,
|
|
10053
|
+
kind: "histogram",
|
|
10054
|
+
unit: "{token}",
|
|
10055
|
+
description: "Tokens used per generation, by token type (hook-derived)",
|
|
10056
|
+
valueType: "int",
|
|
10057
|
+
boundaries: TOKEN_USAGE_BUCKETS
|
|
10058
|
+
},
|
|
10059
|
+
[METRIC_OPERATION_DURATION]: {
|
|
10060
|
+
name: METRIC_OPERATION_DURATION,
|
|
10061
|
+
kind: "histogram",
|
|
10062
|
+
unit: "s",
|
|
10063
|
+
description: "Generation duration, from its start hook to its end hook (hook-derived)",
|
|
10064
|
+
valueType: "double",
|
|
10065
|
+
boundaries: OPERATION_DURATION_BUCKETS
|
|
10066
|
+
},
|
|
10067
|
+
[METRIC_SESSIONS]: {
|
|
10068
|
+
name: METRIC_SESSIONS,
|
|
10069
|
+
kind: "counter",
|
|
10070
|
+
unit: "{session}",
|
|
10071
|
+
description: "Agent sessions started",
|
|
10072
|
+
valueType: "int"
|
|
10073
|
+
},
|
|
10074
|
+
[METRIC_TOOL_CALLS]: {
|
|
10075
|
+
name: METRIC_TOOL_CALLS,
|
|
10076
|
+
kind: "counter",
|
|
10077
|
+
unit: "{call}",
|
|
10078
|
+
description: "Completed tool calls, by tool name and outcome",
|
|
10079
|
+
valueType: "int"
|
|
10080
|
+
},
|
|
10081
|
+
[METRIC_COST_USAGE]: {
|
|
10082
|
+
name: METRIC_COST_USAGE,
|
|
10083
|
+
kind: "counter",
|
|
10084
|
+
unit: "USD",
|
|
10085
|
+
description: "Cost reported by the provider; never estimated",
|
|
10086
|
+
valueType: "double"
|
|
10087
|
+
}
|
|
10088
|
+
});
|
|
10089
|
+
var isMetricInstrumentName = (value) => typeof value === "string" && Object.hasOwn(METRIC_INSTRUMENTS, value);
|
|
10090
|
+
var ATTR_GEN_AI_TOKEN_TYPE = "gen_ai.token.type";
|
|
10091
|
+
var ATTR_GEN_AI_PROVIDER_NAME = "gen_ai.provider.name";
|
|
10092
|
+
var ATTR_GEN_AI_OPERATION_NAME3 = "gen_ai.operation.name";
|
|
10093
|
+
var ATTR_GEN_AI_REQUEST_MODEL3 = "gen_ai.request.model";
|
|
10094
|
+
var ATTR_GEN_AI_RESPONSE_MODEL3 = "gen_ai.response.model";
|
|
10095
|
+
var ATTR_GEN_AI_TOOL_NAME3 = "gen_ai.tool.name";
|
|
10096
|
+
var ATTR_ERROR_TYPE3 = "error.type";
|
|
10097
|
+
var ATTR_SESSION_ID2 = "session.id";
|
|
10098
|
+
var ATTR_OTELHOOK_PROVIDER_ID2 = "otelhook.provider.id";
|
|
10099
|
+
var ATTR_OTELHOOK_OUTCOME3 = "otelhook.outcome";
|
|
10100
|
+
var ATTR_OTELHOOK_SESSION_KIND2 = "otelhook.session.kind";
|
|
10101
|
+
var commonAttributes = (event3, resource, includeSessionId) => ({
|
|
10102
|
+
[ATTR_OTELHOOK_PROVIDER_ID2]: event3.provenance.providerId,
|
|
10103
|
+
...includeSessionId ? { [ATTR_SESSION_ID2]: resolveExportedSessionId(event3.sessionId, resource).sessionId } : {}
|
|
10104
|
+
});
|
|
10105
|
+
var generationAttributes = (end, requestModel) => ({
|
|
10106
|
+
[ATTR_GEN_AI_OPERATION_NAME3]: "chat",
|
|
10107
|
+
...end.model.vendor === void 0 ? {} : { [ATTR_GEN_AI_PROVIDER_NAME]: end.model.vendor },
|
|
10108
|
+
[ATTR_GEN_AI_REQUEST_MODEL3]: requestModel ?? end.model.modelId,
|
|
10109
|
+
[ATTR_GEN_AI_RESPONSE_MODEL3]: end.model.modelId
|
|
10110
|
+
});
|
|
10111
|
+
var TOKEN_FIELDS = [
|
|
10112
|
+
["input", (usage) => usage.inputTokens],
|
|
10113
|
+
["output", (usage) => usage.outputTokens],
|
|
10114
|
+
["cache_read", (usage) => usage.cachedInputTokens],
|
|
10115
|
+
["cache_creation", (usage) => usage.cacheCreationInputTokens]
|
|
10116
|
+
];
|
|
10117
|
+
var isFailedOutcome = (outcome) => outcome !== "ok" && outcome !== "unknown" && outcome !== "cancelled";
|
|
10118
|
+
var deriveMetricObservations = (input) => {
|
|
10119
|
+
const includeSessionId = input.includeSessionId ?? true;
|
|
10120
|
+
const observations = [];
|
|
10121
|
+
const byId = /* @__PURE__ */ new Map();
|
|
10122
|
+
const startsInBatch = /* @__PURE__ */ new Map();
|
|
10123
|
+
for (const event3 of input.events) {
|
|
10124
|
+
byId.set(event3.eventId, event3);
|
|
10125
|
+
if (event3.type === "generation.start") {
|
|
10126
|
+
startsInBatch.set(event3.generationId, {
|
|
10127
|
+
startMillis: event3.occurredAt,
|
|
10128
|
+
requestModel: event3.model.modelId
|
|
10129
|
+
});
|
|
10130
|
+
}
|
|
10131
|
+
}
|
|
10132
|
+
const requestModelOf = (generationId) => startsInBatch.get(generationId)?.requestModel ?? input.generationStarts?.(generationId)?.requestModel;
|
|
10133
|
+
let lastPromptInBatch;
|
|
10134
|
+
for (const event3 of input.events) {
|
|
10135
|
+
if (event3.type === "prompt.submitted") {
|
|
10136
|
+
lastPromptInBatch ??= /* @__PURE__ */ new Map();
|
|
10137
|
+
lastPromptInBatch.set(event3.sessionId, Math.max(lastPromptInBatch.get(event3.sessionId) ?? 0, event3.occurredAt));
|
|
10138
|
+
}
|
|
10139
|
+
}
|
|
10140
|
+
const measuredDurationOf = (end) => {
|
|
10141
|
+
if (end.durationMillis !== void 0) {
|
|
10142
|
+
return end.durationMillis;
|
|
10143
|
+
}
|
|
10144
|
+
const recovered = startsInBatch.has(end.generationId) ? void 0 : input.generationStarts?.(end.generationId);
|
|
10145
|
+
if (recovered !== void 0) {
|
|
10146
|
+
return end.occurredAt - recovered.startMillis;
|
|
10147
|
+
}
|
|
10148
|
+
const turn = lastPromptInBatch?.get(end.sessionId) ?? input.turnStart?.(end.sessionId);
|
|
10149
|
+
return turn === void 0 || turn > end.occurredAt ? void 0 : end.occurredAt - turn;
|
|
10150
|
+
};
|
|
10151
|
+
const push = (event3, instrument, value, attributes) => {
|
|
10152
|
+
if (!Number.isFinite(value) || value < 0) {
|
|
10153
|
+
return;
|
|
10154
|
+
}
|
|
10155
|
+
observations.push({
|
|
10156
|
+
instrument,
|
|
10157
|
+
value,
|
|
10158
|
+
attributes: { ...commonAttributes(event3, input.resource, includeSessionId), ...attributes },
|
|
10159
|
+
timeMillis: event3.occurredAt,
|
|
10160
|
+
sessionId: event3.sessionId
|
|
10161
|
+
});
|
|
10162
|
+
};
|
|
10163
|
+
for (const event3 of input.events) {
|
|
10164
|
+
switch (event3.type) {
|
|
10165
|
+
case "session.start":
|
|
10166
|
+
push(event3, METRIC_SESSIONS, 1, { [ATTR_OTELHOOK_SESSION_KIND2]: event3.sessionKind });
|
|
10167
|
+
break;
|
|
10168
|
+
case "tool.end":
|
|
10169
|
+
push(event3, METRIC_TOOL_CALLS, 1, {
|
|
10170
|
+
[ATTR_GEN_AI_TOOL_NAME3]: event3.toolName,
|
|
10171
|
+
[ATTR_OTELHOOK_OUTCOME3]: event3.outcome
|
|
10172
|
+
});
|
|
10173
|
+
break;
|
|
10174
|
+
case "generation.end": {
|
|
10175
|
+
const attributes = generationAttributes(event3, requestModelOf(event3.generationId));
|
|
10176
|
+
const durationMillis = measuredDurationOf(event3);
|
|
10177
|
+
if (durationMillis !== void 0 && durationMillis >= 0) {
|
|
10178
|
+
push(event3, METRIC_OPERATION_DURATION, durationMillis / 1e3, {
|
|
10179
|
+
...attributes,
|
|
10180
|
+
...isFailedOutcome(event3.outcome) ? { [ATTR_ERROR_TYPE3]: event3.outcome } : {}
|
|
10181
|
+
});
|
|
10182
|
+
}
|
|
10183
|
+
if (event3.cost !== void 0 && event3.cost.source === "provider-reported" && event3.cost.currency === "USD") {
|
|
10184
|
+
push(event3, METRIC_COST_USAGE, event3.cost.amount, attributes);
|
|
10185
|
+
}
|
|
10186
|
+
break;
|
|
10187
|
+
}
|
|
10188
|
+
default:
|
|
10189
|
+
break;
|
|
10190
|
+
}
|
|
10191
|
+
}
|
|
10192
|
+
for (const observation of input.usage) {
|
|
10193
|
+
if (observation.scope !== "generation") {
|
|
10194
|
+
continue;
|
|
10195
|
+
}
|
|
10196
|
+
const event3 = byId.get(observation.eventId);
|
|
10197
|
+
if (event3?.type !== "generation.end") {
|
|
10198
|
+
continue;
|
|
10199
|
+
}
|
|
10200
|
+
const attributes = generationAttributes(event3, requestModelOf(event3.generationId));
|
|
10201
|
+
for (const [tokenType, read] of TOKEN_FIELDS) {
|
|
10202
|
+
const value = read(observation.delta);
|
|
10203
|
+
if (value === 0 && (tokenType === "cache_read" || tokenType === "cache_creation")) {
|
|
10204
|
+
continue;
|
|
10205
|
+
}
|
|
10206
|
+
push(event3, METRIC_TOKEN_USAGE, value, { ...attributes, [ATTR_GEN_AI_TOKEN_TYPE]: tokenType });
|
|
10207
|
+
}
|
|
10208
|
+
}
|
|
10209
|
+
return observations;
|
|
10210
|
+
};
|
|
10211
|
+
var emptyHistogram = (boundaries) => ({
|
|
10212
|
+
count: 0,
|
|
10213
|
+
sum: 0,
|
|
10214
|
+
min: Number.POSITIVE_INFINITY,
|
|
10215
|
+
max: Number.NEGATIVE_INFINITY,
|
|
10216
|
+
bucketCounts: new Array(boundaries.length + 1).fill(0)
|
|
10217
|
+
});
|
|
10218
|
+
var bucketIndex = (boundaries, value) => {
|
|
10219
|
+
for (let index = 0; index < boundaries.length; index += 1) {
|
|
10220
|
+
const bound = boundaries[index];
|
|
10221
|
+
if (bound !== void 0 && value <= bound) {
|
|
10222
|
+
return index;
|
|
10223
|
+
}
|
|
10224
|
+
}
|
|
10225
|
+
return boundaries.length;
|
|
10226
|
+
};
|
|
10227
|
+
var recordIntoHistogram = (state, boundaries, value) => {
|
|
10228
|
+
const bucketCounts = [...state.bucketCounts];
|
|
10229
|
+
const index = bucketIndex(boundaries, value);
|
|
10230
|
+
bucketCounts[index] = (bucketCounts[index] ?? 0) + 1;
|
|
10231
|
+
return {
|
|
10232
|
+
count: state.count + 1,
|
|
10233
|
+
sum: state.sum + value,
|
|
10234
|
+
min: Math.min(state.min, value),
|
|
10235
|
+
max: Math.max(state.max, value),
|
|
10236
|
+
bucketCounts
|
|
10237
|
+
};
|
|
10238
|
+
};
|
|
10239
|
+
var seriesIdentity = (instrument, attributes) => JSON.stringify([
|
|
10240
|
+
instrument,
|
|
10241
|
+
Object.entries(attributes).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0)
|
|
10242
|
+
]);
|
|
10243
|
+
var aggregateDeltaPoints = (observations, nowMillis) => {
|
|
10244
|
+
const series = /* @__PURE__ */ new Map();
|
|
10245
|
+
for (const observation of observations) {
|
|
10246
|
+
const instrument = METRIC_INSTRUMENTS[observation.instrument];
|
|
10247
|
+
const key = seriesIdentity(observation.instrument, observation.attributes);
|
|
10248
|
+
const existing = series.get(key) ?? {
|
|
10249
|
+
observation,
|
|
10250
|
+
start: observation.timeMillis,
|
|
10251
|
+
value: 0,
|
|
10252
|
+
...instrument.boundaries === void 0 ? {} : { histogram: emptyHistogram(instrument.boundaries) }
|
|
10253
|
+
};
|
|
10254
|
+
existing.start = Math.min(existing.start, observation.timeMillis);
|
|
10255
|
+
if (existing.histogram !== void 0 && instrument.boundaries !== void 0) {
|
|
10256
|
+
existing.histogram = recordIntoHistogram(existing.histogram, instrument.boundaries, observation.value);
|
|
10257
|
+
} else {
|
|
10258
|
+
existing.value += observation.value;
|
|
10259
|
+
}
|
|
10260
|
+
series.set(key, existing);
|
|
10261
|
+
}
|
|
10262
|
+
return [...series.values()].map((entry) => ({
|
|
10263
|
+
instrument: entry.observation.instrument,
|
|
10264
|
+
temporality: "delta",
|
|
10265
|
+
attributes: entry.observation.attributes,
|
|
10266
|
+
startTimeMillis: Math.min(entry.start, nowMillis),
|
|
10267
|
+
timeMillis: Math.max(nowMillis, entry.start),
|
|
10268
|
+
...entry.histogram === void 0 ? { value: entry.value } : { histogram: entry.histogram }
|
|
10269
|
+
}));
|
|
10270
|
+
};
|
|
10271
|
+
var FORBIDDEN_METRIC_ATTRIBUTE_PREFIXES = Object.freeze([
|
|
10272
|
+
"user.",
|
|
10273
|
+
"enduser.",
|
|
10274
|
+
"organization."
|
|
10275
|
+
]);
|
|
10276
|
+
var withoutAccountIdentity = (attributes) => Object.fromEntries(
|
|
10277
|
+
Object.entries(attributes).filter(
|
|
10278
|
+
([key]) => !FORBIDDEN_METRIC_ATTRIBUTE_PREFIXES.some((prefix) => key.startsWith(prefix))
|
|
10279
|
+
)
|
|
10280
|
+
);
|
|
10281
|
+
|
|
10282
|
+
// src/telemetry/durable-metric-spool.ts
|
|
10283
|
+
var MAX_SPOOLED_METRIC_POINTS_PER_BATCH = 4096;
|
|
10284
|
+
var MAX_STRING_LENGTH = 8192;
|
|
10285
|
+
var MAX_ATTRIBUTES_PER_POINT = 64;
|
|
10286
|
+
var MAX_BUCKETS = 64;
|
|
10287
|
+
var isPlainObject5 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
10288
|
+
var isFiniteNonNegative3 = (value) => typeof value === "number" && Number.isFinite(value) && value >= 0;
|
|
10289
|
+
var isBoundedString3 = (value) => typeof value === "string" && value.length > 0 && value.length <= MAX_STRING_LENGTH;
|
|
10290
|
+
var isPrimitiveAttribute2 = (value) => typeof value === "string" && value.length <= MAX_STRING_LENGTH || typeof value === "number" && Number.isFinite(value) || typeof value === "boolean";
|
|
10291
|
+
var isReplayablePoint = (value) => {
|
|
10292
|
+
if (!isPlainObject5(value) || !isMetricInstrumentName(value.instrument)) {
|
|
10293
|
+
return false;
|
|
10294
|
+
}
|
|
10295
|
+
if (value.temporality !== "cumulative" && value.temporality !== "delta") {
|
|
10296
|
+
return false;
|
|
10297
|
+
}
|
|
10298
|
+
if (!isFiniteNonNegative3(value.startTimeMillis) || !isFiniteNonNegative3(value.timeMillis)) {
|
|
10299
|
+
return false;
|
|
10300
|
+
}
|
|
10301
|
+
if (!isPlainObject5(value.attributes)) {
|
|
10302
|
+
return false;
|
|
10303
|
+
}
|
|
10304
|
+
const entries = Object.entries(value.attributes);
|
|
10305
|
+
if (entries.length > MAX_ATTRIBUTES_PER_POINT || !entries.every(([, item]) => isPrimitiveAttribute2(item))) {
|
|
10306
|
+
return false;
|
|
10307
|
+
}
|
|
10308
|
+
const instrument = METRIC_INSTRUMENTS[value.instrument];
|
|
10309
|
+
if (instrument.kind === "counter") {
|
|
10310
|
+
return isFiniteNonNegative3(value.value) && value.histogram === void 0;
|
|
10311
|
+
}
|
|
10312
|
+
const histogram = value.histogram;
|
|
10313
|
+
if (!isPlainObject5(histogram) || value.value !== void 0) {
|
|
10314
|
+
return false;
|
|
10315
|
+
}
|
|
10316
|
+
const buckets = histogram.bucketCounts;
|
|
10317
|
+
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));
|
|
10318
|
+
};
|
|
10319
|
+
var validateMetricSpoolBatch = (value, identity) => {
|
|
10320
|
+
if (!isPlainObject5(value)) {
|
|
10321
|
+
return { rejection: "not-an-object" };
|
|
10322
|
+
}
|
|
10323
|
+
if (value.providerId !== identity.providerId || value.installationId !== identity.installationId) {
|
|
10324
|
+
return { rejection: "identity-mismatch" };
|
|
10325
|
+
}
|
|
10326
|
+
if (!isPlainObject5(value.resourceAttributes)) {
|
|
10327
|
+
return { rejection: "resource-attributes-invalid" };
|
|
10328
|
+
}
|
|
10329
|
+
if (!isPlainObject5(value.instrumentationScope) || !isBoundedString3(value.instrumentationScope.name)) {
|
|
10330
|
+
return { rejection: "instrumentation-scope-invalid" };
|
|
10331
|
+
}
|
|
10332
|
+
if (value.instrumentationScope.version !== void 0 && typeof value.instrumentationScope.version !== "string") {
|
|
10333
|
+
return { rejection: "instrumentation-scope-invalid" };
|
|
10334
|
+
}
|
|
10335
|
+
if (!Array.isArray(value.points) || value.points.length === 0 || value.points.length > MAX_SPOOLED_METRIC_POINTS_PER_BATCH) {
|
|
10336
|
+
return { rejection: "points-invalid" };
|
|
10337
|
+
}
|
|
10338
|
+
if (!value.points.every(isReplayablePoint)) {
|
|
10339
|
+
return { rejection: "point-field-invalid" };
|
|
10340
|
+
}
|
|
10341
|
+
if (!isFiniteNonNegative3(value.enqueuedAt)) {
|
|
10342
|
+
return { rejection: "not-an-object" };
|
|
10343
|
+
}
|
|
10344
|
+
return { batch: value };
|
|
10345
|
+
};
|
|
10346
|
+
var DEFAULT_MAX_METRIC_SPOOL_FILES = 500;
|
|
10347
|
+
var createFileDurableMetricSpool = (options) => createSpoolQueue({
|
|
10348
|
+
rootDir: options.rootDir,
|
|
10349
|
+
providerId: options.providerId,
|
|
10350
|
+
installationId: options.installationId,
|
|
10351
|
+
clock: options.clock,
|
|
10352
|
+
...options.logger === void 0 ? {} : { logger: options.logger },
|
|
10353
|
+
maxFiles: options.maxSpoolFiles ?? DEFAULT_MAX_METRIC_SPOOL_FILES,
|
|
10354
|
+
queueName: options.queueName ?? "spool-metrics",
|
|
10355
|
+
...options.maxBytes === void 0 ? {} : { maxBytes: options.maxBytes },
|
|
10356
|
+
...options.maxAgeMillis === void 0 ? {} : { maxAgeMillis: options.maxAgeMillis },
|
|
10357
|
+
...options.overflow === void 0 ? {} : { overflow: options.overflow },
|
|
10358
|
+
validate: validateMetricSpoolBatch
|
|
10359
|
+
});
|
|
10360
|
+
|
|
10361
|
+
// src/telemetry/otlp-metric-sink.ts
|
|
10362
|
+
import { ValueType } from "@opentelemetry/api";
|
|
10363
|
+
import { ExportResultCode as ExportResultCode3, millisToHrTime as millisToHrTime4 } from "@opentelemetry/core";
|
|
10364
|
+
import { OTLPMetricExporter } from "@opentelemetry/exporter-metrics-otlp-proto";
|
|
10365
|
+
import { resourceFromAttributes as resourceFromAttributes2 } from "@opentelemetry/resources";
|
|
10366
|
+
import {
|
|
10367
|
+
AggregationTemporality,
|
|
10368
|
+
DataPointType
|
|
10369
|
+
} from "@opentelemetry/sdk-metrics";
|
|
10370
|
+
var resolveMetricsEndpoint = (exporter) => {
|
|
10371
|
+
const stated = exporter.metrics?.endpoint;
|
|
10372
|
+
if (stated !== void 0) {
|
|
10373
|
+
return { endpoint: stated, derived: false };
|
|
10374
|
+
}
|
|
10375
|
+
if (exporter.endpoint === void 0) {
|
|
10376
|
+
return { unresolvable: "no-endpoint" };
|
|
10377
|
+
}
|
|
10378
|
+
return { endpoint: siblingSignalEndpoint(exporter.endpoint, "metrics"), derived: true };
|
|
10379
|
+
};
|
|
10380
|
+
var describeMetricsDeliverability = (exporter) => {
|
|
10381
|
+
if (exporter.metrics?.enabled !== true) {
|
|
10382
|
+
return { status: "disabled", reason: "metrics-disabled" };
|
|
10383
|
+
}
|
|
10384
|
+
if (!exporter.enabled) {
|
|
10385
|
+
return { status: "disabled", reason: "exporter-disabled" };
|
|
10386
|
+
}
|
|
10387
|
+
if (exporter.protocol === "none") {
|
|
10388
|
+
return { status: "disabled", reason: "protocol-none" };
|
|
10389
|
+
}
|
|
10390
|
+
if (exporter.protocol !== "http/protobuf") {
|
|
10391
|
+
return { status: "disabled", reason: "protocol-unsupported" };
|
|
10392
|
+
}
|
|
10393
|
+
const resolved = resolveMetricsEndpoint(exporter);
|
|
10394
|
+
if ("unresolvable" in resolved) {
|
|
10395
|
+
return { status: "disabled", reason: "no-endpoint" };
|
|
10396
|
+
}
|
|
10397
|
+
return { status: "configured", endpoint: resolved.endpoint, derivedEndpoint: resolved.derived };
|
|
10398
|
+
};
|
|
10399
|
+
var DISABLED_DETAIL2 = Object.freeze({
|
|
10400
|
+
"exporter-disabled": "otlp metric sink disabled: the exporter is disabled",
|
|
10401
|
+
"protocol-none": "otlp metric sink disabled: protocol is none",
|
|
10402
|
+
"protocol-unsupported": "otlp metric sink disabled: protocol not supported by this build",
|
|
10403
|
+
"no-endpoint": "otlp metric sink disabled: no metrics endpoint configured and none could be derived"
|
|
10404
|
+
});
|
|
10405
|
+
var createDisabledMetricSink = (destination) => {
|
|
10406
|
+
const health = createHealthTracker(
|
|
10407
|
+
"telemetry-metric-sink",
|
|
10408
|
+
destination === void 0 ? {} : { destination }
|
|
10409
|
+
);
|
|
10410
|
+
return {
|
|
10411
|
+
enabled: false,
|
|
10412
|
+
exportPoints: () => Promise.resolve({ accepted: 0, rejected: 0, errors: [] }),
|
|
10413
|
+
flush: () => Promise.resolve(),
|
|
10414
|
+
shutdown: () => Promise.resolve(),
|
|
10415
|
+
health: () => health.snapshot(),
|
|
10416
|
+
drainSpool: () => Promise.resolve({ drained: 0, remaining: 0, failed: 0 })
|
|
10417
|
+
};
|
|
10418
|
+
};
|
|
10419
|
+
var createDisabledOtlpMetricSink = createDisabledMetricSink;
|
|
10420
|
+
var toMetricData = (points) => {
|
|
10421
|
+
const byInstrument = /* @__PURE__ */ new Map();
|
|
10422
|
+
for (const point of points) {
|
|
10423
|
+
const key = `${point.instrument}|${point.temporality}`;
|
|
10424
|
+
const group = byInstrument.get(key) ?? [];
|
|
10425
|
+
group.push(point);
|
|
10426
|
+
byInstrument.set(key, group);
|
|
10427
|
+
}
|
|
10428
|
+
const metrics = [];
|
|
10429
|
+
for (const group of byInstrument.values()) {
|
|
10430
|
+
const first = group[0];
|
|
10431
|
+
if (first === void 0) {
|
|
10432
|
+
continue;
|
|
10433
|
+
}
|
|
10434
|
+
const instrument = METRIC_INSTRUMENTS[first.instrument];
|
|
10435
|
+
const descriptor = {
|
|
10436
|
+
name: instrument.name,
|
|
10437
|
+
description: instrument.description,
|
|
10438
|
+
unit: instrument.unit,
|
|
10439
|
+
valueType: instrument.valueType === "int" ? ValueType.INT : ValueType.DOUBLE
|
|
10440
|
+
};
|
|
10441
|
+
const aggregationTemporality = first.temporality === "cumulative" ? AggregationTemporality.CUMULATIVE : AggregationTemporality.DELTA;
|
|
10442
|
+
const times = (point) => ({
|
|
10443
|
+
startTime: millisToHrTime4(point.startTimeMillis),
|
|
10444
|
+
endTime: millisToHrTime4(point.timeMillis)
|
|
10445
|
+
});
|
|
10446
|
+
if (instrument.kind === "counter") {
|
|
10447
|
+
metrics.push({
|
|
10448
|
+
descriptor,
|
|
10449
|
+
aggregationTemporality,
|
|
10450
|
+
dataPointType: DataPointType.SUM,
|
|
10451
|
+
isMonotonic: true,
|
|
10452
|
+
dataPoints: group.map((point) => ({
|
|
10453
|
+
...times(point),
|
|
10454
|
+
attributes: { ...point.attributes },
|
|
10455
|
+
value: point.value ?? 0
|
|
10456
|
+
}))
|
|
10457
|
+
});
|
|
10458
|
+
continue;
|
|
10459
|
+
}
|
|
10460
|
+
metrics.push({
|
|
10461
|
+
descriptor,
|
|
10462
|
+
aggregationTemporality,
|
|
10463
|
+
dataPointType: DataPointType.HISTOGRAM,
|
|
10464
|
+
dataPoints: group.map((point) => {
|
|
10465
|
+
const histogram = point.histogram;
|
|
10466
|
+
return {
|
|
10467
|
+
...times(point),
|
|
10468
|
+
attributes: { ...point.attributes },
|
|
10469
|
+
value: {
|
|
10470
|
+
buckets: {
|
|
10471
|
+
boundaries: [...instrument.boundaries ?? []],
|
|
10472
|
+
counts: [...histogram?.bucketCounts ?? []]
|
|
10473
|
+
},
|
|
10474
|
+
count: histogram?.count ?? 0,
|
|
10475
|
+
sum: histogram?.sum ?? 0,
|
|
10476
|
+
...histogram === void 0 || histogram.count === 0 ? {} : { min: histogram.min, max: histogram.max }
|
|
10477
|
+
}
|
|
10478
|
+
};
|
|
10479
|
+
})
|
|
10480
|
+
});
|
|
10481
|
+
}
|
|
10482
|
+
return metrics;
|
|
10483
|
+
};
|
|
10484
|
+
var createOtlpMetricSink = (options) => {
|
|
10485
|
+
const destinationFields = options.destination === void 0 ? {} : { "export.destination": options.destination };
|
|
10486
|
+
const deliverability = describeMetricsDeliverability(options.exporter);
|
|
10487
|
+
if (deliverability.status === "disabled") {
|
|
10488
|
+
if (deliverability.reason !== "metrics-disabled") {
|
|
10489
|
+
options.logger?.warn(DISABLED_DETAIL2[deliverability.reason], {
|
|
10490
|
+
"exporter.protocol": options.exporter.protocol,
|
|
10491
|
+
...destinationFields
|
|
10492
|
+
});
|
|
10493
|
+
}
|
|
10494
|
+
return createDisabledMetricSink(options.destination);
|
|
10495
|
+
}
|
|
10496
|
+
const scope = options.instrumentationScope ?? DEFAULT_INSTRUMENTATION_SCOPE;
|
|
10497
|
+
const resource = resourceFromAttributes2(
|
|
10498
|
+
withoutAccountIdentity(resourceFromExporterPolicy(options.exporter).attributes)
|
|
10499
|
+
);
|
|
10500
|
+
const health = createHealthTracker(
|
|
10501
|
+
"telemetry-metric-sink",
|
|
10502
|
+
options.destination === void 0 ? {} : { destination: options.destination }
|
|
10503
|
+
);
|
|
10504
|
+
const exporter = new OTLPMetricExporter({
|
|
10505
|
+
url: deliverability.endpoint,
|
|
10506
|
+
headers: { ...options.headers },
|
|
10507
|
+
timeoutMillis: options.exporter.timeoutMillis
|
|
10508
|
+
});
|
|
10509
|
+
let shutdownCompleted = false;
|
|
10510
|
+
const exportResourceMetrics = (points, batchResource, batchScope) => new Promise((resolve8) => {
|
|
10511
|
+
const payload = {
|
|
10512
|
+
resource: batchResource,
|
|
10513
|
+
scopeMetrics: [{ scope: batchScope, metrics: toMetricData(points) }]
|
|
10514
|
+
};
|
|
10515
|
+
try {
|
|
10516
|
+
exporter.export(payload, (result) => resolve8(result));
|
|
10517
|
+
} catch (thrown) {
|
|
10518
|
+
resolve8({
|
|
10519
|
+
code: ExportResultCode3.FAILED,
|
|
10520
|
+
error: thrown instanceof Error ? thrown : new Error("export threw")
|
|
10521
|
+
});
|
|
10522
|
+
}
|
|
10523
|
+
});
|
|
10524
|
+
const toSpoolBatch = (points) => ({
|
|
10525
|
+
providerId: options.providerId,
|
|
10526
|
+
installationId: options.installationId,
|
|
10527
|
+
resourceAttributes: { ...resource.attributes },
|
|
10528
|
+
instrumentationScope: {
|
|
10529
|
+
name: scope.name,
|
|
10530
|
+
...scope.version === void 0 ? {} : { version: scope.version }
|
|
10531
|
+
},
|
|
10532
|
+
points: points.map((point) => ({ ...point })),
|
|
10533
|
+
enqueuedAt: options.clock.now()
|
|
10534
|
+
});
|
|
10535
|
+
const sendSerializedBatch = async (batch) => {
|
|
10536
|
+
const batchResource = resourceFromAttributes2(
|
|
10537
|
+
withoutAccountIdentity(replayResource(batch.resourceAttributes, options.exporter).attributes)
|
|
10538
|
+
);
|
|
10539
|
+
const result = await exportResourceMetrics(batch.points, batchResource, batch.instrumentationScope);
|
|
10540
|
+
if (result.code === ExportResultCode3.SUCCESS) {
|
|
10541
|
+
return true;
|
|
10542
|
+
}
|
|
10543
|
+
return isPermanentExportFailure(result) ? "discard" : false;
|
|
10544
|
+
};
|
|
10545
|
+
const exportPoints = async (points) => {
|
|
10546
|
+
if (points.length === 0) {
|
|
10547
|
+
return { accepted: 0, rejected: 0, errors: [] };
|
|
10548
|
+
}
|
|
10549
|
+
const result = await exportResourceMetrics(points, resource, scope);
|
|
10550
|
+
if (result.code === ExportResultCode3.SUCCESS) {
|
|
10551
|
+
health.recordSuccess(points.length, options.clock.now());
|
|
10552
|
+
return { accepted: points.length, rejected: 0, errors: [] };
|
|
10553
|
+
}
|
|
10554
|
+
health.recordFailure("telemetry-export-failure", points.length, options.clock.now());
|
|
10555
|
+
const permanent = isPermanentExportFailure(result);
|
|
10556
|
+
if (options.spool !== void 0 && !permanent) {
|
|
10557
|
+
const spooled = await options.spool.enqueue(toSpoolBatch(points)).catch(() => ({
|
|
10558
|
+
spooled: false,
|
|
10559
|
+
reason: "capacity-exceeded"
|
|
10560
|
+
}));
|
|
10561
|
+
if (spooled.spooled) {
|
|
10562
|
+
options.logger?.warn("metric batch not delivered; spooled for the next invocation", {
|
|
10563
|
+
"export.batch_size": points.length,
|
|
10564
|
+
...destinationFields
|
|
10565
|
+
});
|
|
10566
|
+
return { accepted: points.length, rejected: 0, errors: [] };
|
|
10567
|
+
}
|
|
10568
|
+
}
|
|
10569
|
+
return {
|
|
10570
|
+
accepted: 0,
|
|
10571
|
+
rejected: points.length,
|
|
10572
|
+
errors: [
|
|
10573
|
+
createErrorInfo({
|
|
10574
|
+
code: "telemetry-export-failure",
|
|
10575
|
+
phase: "export",
|
|
10576
|
+
detail: permanent ? "collector refused a metric batch with a non-retryable status" : "collector rejected or was unreachable for a metric batch",
|
|
10577
|
+
details: {
|
|
10578
|
+
"export.batch_size": points.length,
|
|
10579
|
+
"export.signal": "metrics",
|
|
10580
|
+
...destinationFields
|
|
10581
|
+
}
|
|
10582
|
+
})
|
|
10583
|
+
]
|
|
10584
|
+
};
|
|
10585
|
+
};
|
|
10586
|
+
const drainSpool = async (maxBatches) => {
|
|
10587
|
+
if (options.spool === void 0) {
|
|
10588
|
+
return { drained: 0, remaining: 0, failed: 0 };
|
|
10589
|
+
}
|
|
10590
|
+
const result = await options.spool.drain(sendSerializedBatch, {
|
|
10591
|
+
...maxBatches === void 0 ? {} : { maxBatches }
|
|
10592
|
+
});
|
|
10593
|
+
if (result.drained > 0) {
|
|
10594
|
+
health.recordSuccess(result.drained, options.clock.now());
|
|
10595
|
+
}
|
|
10596
|
+
return result;
|
|
10597
|
+
};
|
|
10598
|
+
const flush = async () => {
|
|
10599
|
+
try {
|
|
10600
|
+
await exporter.forceFlush();
|
|
10601
|
+
} catch {
|
|
10602
|
+
}
|
|
10603
|
+
await drainSpool().catch(() => void 0);
|
|
10604
|
+
};
|
|
10605
|
+
const shutdown = async () => {
|
|
10606
|
+
if (shutdownCompleted) {
|
|
10607
|
+
return;
|
|
10608
|
+
}
|
|
10609
|
+
shutdownCompleted = true;
|
|
10610
|
+
await flush();
|
|
10611
|
+
try {
|
|
10612
|
+
await exporter.shutdown();
|
|
10613
|
+
} catch {
|
|
10614
|
+
}
|
|
10615
|
+
};
|
|
10616
|
+
return {
|
|
10617
|
+
enabled: true,
|
|
10618
|
+
exportPoints,
|
|
9755
10619
|
flush,
|
|
9756
10620
|
shutdown,
|
|
9757
10621
|
health: () => health.snapshot(),
|
|
@@ -9802,7 +10666,11 @@ var shareCorrelationPerBatch = (correlate) => {
|
|
|
9802
10666
|
};
|
|
9803
10667
|
|
|
9804
10668
|
// src/telemetry/export-destinations.ts
|
|
9805
|
-
var spoolQueueNamesFor = (destination) => destination === DEFAULT_DESTINATION_NAME ? { traces: "spool", logs: "spool-logs"
|
|
10669
|
+
var spoolQueueNamesFor = (destination) => destination === DEFAULT_DESTINATION_NAME ? { traces: "spool", logs: "spool-logs", metrics: "spool-metrics" } : {
|
|
10670
|
+
traces: `destinations/${destination}/spool`,
|
|
10671
|
+
logs: `destinations/${destination}/spool-logs`,
|
|
10672
|
+
metrics: `destinations/${destination}/spool-metrics`
|
|
10673
|
+
};
|
|
9806
10674
|
var exporterPolicyForDestination = (exporter, destination) => {
|
|
9807
10675
|
if (destination.source === "exporter") {
|
|
9808
10676
|
return exporter;
|
|
@@ -9819,8 +10687,10 @@ var exporterPolicyForDestination = (exporter, destination) => {
|
|
|
9819
10687
|
});
|
|
9820
10688
|
return "endpoint" in derived ? derived.endpoint : void 0;
|
|
9821
10689
|
})());
|
|
10690
|
+
const { metrics: sharedMetrics, ...rest } = shared;
|
|
10691
|
+
const derivedMetrics = destination.metricsEndpoint ?? (destination.endpoint === void 0 ? void 0 : siblingSignalEndpoint(destination.endpoint, "metrics"));
|
|
9822
10692
|
return {
|
|
9823
|
-
...
|
|
10693
|
+
...rest,
|
|
9824
10694
|
protocol: destination.protocol,
|
|
9825
10695
|
...tracesEndpoint === void 0 ? {} : { endpoint: tracesEndpoint },
|
|
9826
10696
|
headerNames: Object.keys(destination.headers).sort(),
|
|
@@ -9828,6 +10698,11 @@ var exporterPolicyForDestination = (exporter, destination) => {
|
|
|
9828
10698
|
...logs,
|
|
9829
10699
|
enabled: destination.signals.logs,
|
|
9830
10700
|
...derivedLogs === void 0 ? {} : { endpoint: derivedLogs }
|
|
10701
|
+
},
|
|
10702
|
+
metrics: {
|
|
10703
|
+
...effectiveMetricsPolicy({ ...exporter, metrics: sharedMetrics }),
|
|
10704
|
+
enabled: destination.signals.metrics,
|
|
10705
|
+
...derivedMetrics === void 0 ? {} : { endpoint: derivedMetrics }
|
|
9831
10706
|
}
|
|
9832
10707
|
};
|
|
9833
10708
|
};
|
|
@@ -9899,6 +10774,12 @@ var createExportDestinationSinks = (options) => {
|
|
|
9899
10774
|
...bounds,
|
|
9900
10775
|
queueName: queues.logs
|
|
9901
10776
|
});
|
|
10777
|
+
const metricSpool = options.spoolRootDir === void 0 || !destination.signals.metrics ? void 0 : createFileDurableMetricSpool({
|
|
10778
|
+
rootDir: options.spoolRootDir,
|
|
10779
|
+
...shared,
|
|
10780
|
+
...bounds,
|
|
10781
|
+
queueName: queues.metrics
|
|
10782
|
+
});
|
|
9902
10783
|
const sinkShared = {
|
|
9903
10784
|
exporter: policy,
|
|
9904
10785
|
...shared,
|
|
@@ -9916,12 +10797,21 @@ var createExportDestinationSinks = (options) => {
|
|
|
9916
10797
|
...logSpool === void 0 ? {} : { spool: logSpool },
|
|
9917
10798
|
content: options.logContent
|
|
9918
10799
|
});
|
|
10800
|
+
const metrics = destination.signals.metrics ? createOtlpMetricSink({
|
|
10801
|
+
exporter: policy,
|
|
10802
|
+
...shared,
|
|
10803
|
+
...label === void 0 ? {} : { destination: label },
|
|
10804
|
+
...headers === void 0 || Object.keys(headers).length === 0 ? {} : { headers },
|
|
10805
|
+
...metricSpool === void 0 ? {} : { spool: metricSpool }
|
|
10806
|
+
}) : createDisabledOtlpMetricSink(label);
|
|
9919
10807
|
destinations.push({
|
|
9920
10808
|
name: destination.name,
|
|
9921
10809
|
traces,
|
|
9922
10810
|
logs,
|
|
10811
|
+
metrics,
|
|
9923
10812
|
...spool === void 0 ? {} : { spool },
|
|
9924
|
-
...logSpool === void 0 ? {} : { logSpool }
|
|
10813
|
+
...logSpool === void 0 ? {} : { logSpool },
|
|
10814
|
+
...metricSpool === void 0 ? {} : { metricSpool }
|
|
9925
10815
|
});
|
|
9926
10816
|
}
|
|
9927
10817
|
return { destinations, skipped };
|
|
@@ -10126,6 +11016,9 @@ var describeDestinationLine = (destination) => {
|
|
|
10126
11016
|
if (destination.logsEndpointOrigin !== void 0) {
|
|
10127
11017
|
parts.push(`logs -> ${destination.logsEndpointOrigin}`);
|
|
10128
11018
|
}
|
|
11019
|
+
if (destination.metricsEndpointOrigin !== void 0) {
|
|
11020
|
+
parts.push(`metrics -> ${destination.metricsEndpointOrigin}`);
|
|
11021
|
+
}
|
|
10129
11022
|
if (destination.headerNames.length > 0) {
|
|
10130
11023
|
parts.push(`headers ${destination.headerNames.join(", ")}`);
|
|
10131
11024
|
}
|
|
@@ -10189,7 +11082,7 @@ var describeDoctorDestinations = async (exporter, environment, spool) => {
|
|
|
10189
11082
|
const headers = configured.get(description.name)?.headers ?? {};
|
|
10190
11083
|
const missingVariables = resolveDestinationHeaders(headers, environment).missingVariables;
|
|
10191
11084
|
const sends = description.signals.length > 0;
|
|
10192
|
-
const reachable = description.signals.includes("traces") && description.tracesEndpointOrigin !== void 0 || description.signals.includes("logs") && description.logsEndpointOrigin !== void 0;
|
|
11085
|
+
const reachable = description.signals.includes("traces") && description.tracesEndpointOrigin !== void 0 || description.signals.includes("logs") && description.logsEndpointOrigin !== void 0 || description.signals.includes("metrics") && description.metricsEndpointOrigin !== void 0;
|
|
10193
11086
|
let detail = "resolves";
|
|
10194
11087
|
let ok = true;
|
|
10195
11088
|
if (!description.enabled) {
|
|
@@ -10207,7 +11100,8 @@ var describeDoctorDestinations = async (exporter, environment, spool) => {
|
|
|
10207
11100
|
const queues = spoolQueueNamesFor(description.name);
|
|
10208
11101
|
const spoolStats = spool === void 0 || !resolvedNames.has(description.name) ? void 0 : {
|
|
10209
11102
|
...description.signals.includes("traces") ? { traces: await inspectQueue(spool, queues.traces) } : {},
|
|
10210
|
-
...description.signals.includes("logs") ? { logs: await inspectQueue(spool, queues.logs) } : {}
|
|
11103
|
+
...description.signals.includes("logs") ? { logs: await inspectQueue(spool, queues.logs) } : {},
|
|
11104
|
+
...description.signals.includes("metrics") ? { metrics: await inspectQueue(spool, queues.metrics) } : {}
|
|
10211
11105
|
};
|
|
10212
11106
|
return {
|
|
10213
11107
|
...description,
|
|
@@ -10261,12 +11155,12 @@ var runDoctorCommand = async (command, io) => {
|
|
|
10261
11155
|
};
|
|
10262
11156
|
|
|
10263
11157
|
// src/providers/antigravity/registration.ts
|
|
10264
|
-
var
|
|
11158
|
+
var isPlainObject6 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
10265
11159
|
var mergeAntigravityHookRegistration = (input) => {
|
|
10266
11160
|
const events = input.events ?? ANTIGRAVITY_HOOK_EVENT_NAMES;
|
|
10267
|
-
const base =
|
|
10268
|
-
const existingHooks =
|
|
10269
|
-
let changed = !
|
|
11161
|
+
const base = isPlainObject6(input.existing) ? input.existing : {};
|
|
11162
|
+
const existingHooks = isPlainObject6(base.hooks) ? base.hooks : {};
|
|
11163
|
+
let changed = !isPlainObject6(input.existing) || !isPlainObject6(base.hooks);
|
|
10270
11164
|
const nextHooks = { ...existingHooks };
|
|
10271
11165
|
const identifies = input.identifies ?? ((entry) => entry.command === input.command);
|
|
10272
11166
|
const desired = {
|
|
@@ -10275,7 +11169,7 @@ var mergeAntigravityHookRegistration = (input) => {
|
|
|
10275
11169
|
};
|
|
10276
11170
|
for (const event3 of events) {
|
|
10277
11171
|
const currentList = Array.isArray(existingHooks[event3]) ? [...existingHooks[event3]] : [];
|
|
10278
|
-
const managedIndex = currentList.findIndex((entry) =>
|
|
11172
|
+
const managedIndex = currentList.findIndex((entry) => isPlainObject6(entry) && identifies(entry));
|
|
10279
11173
|
if (managedIndex === -1) {
|
|
10280
11174
|
changed = true;
|
|
10281
11175
|
nextHooks[event3] = [...currentList, desired];
|
|
@@ -10284,7 +11178,7 @@ var mergeAntigravityHookRegistration = (input) => {
|
|
|
10284
11178
|
const managed = currentList[managedIndex];
|
|
10285
11179
|
const updated = { ...managed, ...desired };
|
|
10286
11180
|
const next = currentList.filter(
|
|
10287
|
-
(entry, index) => index === managedIndex || !(
|
|
11181
|
+
(entry, index) => index === managedIndex || !(isPlainObject6(entry) && identifies(entry))
|
|
10288
11182
|
);
|
|
10289
11183
|
next[next.indexOf(managed)] = updated;
|
|
10290
11184
|
const rewritten = Object.entries(desired).some(([key, value]) => managed[key] !== value);
|
|
@@ -10299,8 +11193,8 @@ var mergeAntigravityHookRegistration = (input) => {
|
|
|
10299
11193
|
};
|
|
10300
11194
|
};
|
|
10301
11195
|
var removeAntigravityHookRegistration = (input) => {
|
|
10302
|
-
const base =
|
|
10303
|
-
if (!
|
|
11196
|
+
const base = isPlainObject6(input.existing) ? { ...input.existing } : {};
|
|
11197
|
+
if (!isPlainObject6(base.hooks)) {
|
|
10304
11198
|
return { config: base, changed: false };
|
|
10305
11199
|
}
|
|
10306
11200
|
const nextHooks = { ...base.hooks };
|
|
@@ -10312,7 +11206,7 @@ var removeAntigravityHookRegistration = (input) => {
|
|
|
10312
11206
|
continue;
|
|
10313
11207
|
}
|
|
10314
11208
|
const kept = currentList.filter(
|
|
10315
|
-
(entry) => !(
|
|
11209
|
+
(entry) => !(isPlainObject6(entry) && input.identifies(entry))
|
|
10316
11210
|
);
|
|
10317
11211
|
if (kept.length === currentList.length) {
|
|
10318
11212
|
continue;
|
|
@@ -10337,7 +11231,7 @@ var removeAntigravityHookRegistration = (input) => {
|
|
|
10337
11231
|
};
|
|
10338
11232
|
var readAntigravityHookRegistrations = (existing, identifies) => {
|
|
10339
11233
|
const found = /* @__PURE__ */ new Map();
|
|
10340
|
-
if (!
|
|
11234
|
+
if (!isPlainObject6(existing) || !isPlainObject6(existing.hooks)) {
|
|
10341
11235
|
return found;
|
|
10342
11236
|
}
|
|
10343
11237
|
for (const [event3, list] of Object.entries(existing.hooks)) {
|
|
@@ -10345,7 +11239,7 @@ var readAntigravityHookRegistrations = (existing, identifies) => {
|
|
|
10345
11239
|
continue;
|
|
10346
11240
|
}
|
|
10347
11241
|
const commands = list.filter(
|
|
10348
|
-
(entry) =>
|
|
11242
|
+
(entry) => isPlainObject6(entry) && typeof entry.command === "string" && identifies(entry)
|
|
10349
11243
|
).map((entry) => entry.command);
|
|
10350
11244
|
if (commands.length > 0) {
|
|
10351
11245
|
found.set(event3, commands);
|
|
@@ -10355,10 +11249,10 @@ var readAntigravityHookRegistrations = (existing, identifies) => {
|
|
|
10355
11249
|
};
|
|
10356
11250
|
|
|
10357
11251
|
// src/providers/hook-document.ts
|
|
10358
|
-
var
|
|
11252
|
+
var isPlainObject7 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
10359
11253
|
var normalizeMatcher = (value) => typeof value === "string" && value !== "" && value !== "*" ? value : void 0;
|
|
10360
|
-
var isManaged = (value, identifies) =>
|
|
10361
|
-
var cloneGroup = (value) =>
|
|
11254
|
+
var isManaged = (value, identifies) => isPlainObject7(value) && identifies(value);
|
|
11255
|
+
var cloneGroup = (value) => isPlainObject7(value) && Array.isArray(value.hooks) ? { ...value, hooks: [...value.hooks] } : void 0;
|
|
10362
11256
|
var matchesDesired = (existing, desired) => {
|
|
10363
11257
|
for (const [key, value] of Object.entries(desired)) {
|
|
10364
11258
|
if (existing[key] !== value) {
|
|
@@ -10386,7 +11280,7 @@ var readHooksObject = (base, conflicts) => {
|
|
|
10386
11280
|
if (raw === void 0) {
|
|
10387
11281
|
return {};
|
|
10388
11282
|
}
|
|
10389
|
-
if (!
|
|
11283
|
+
if (!isPlainObject7(raw)) {
|
|
10390
11284
|
conflicts.push({
|
|
10391
11285
|
location: "hooks",
|
|
10392
11286
|
detail: `expected an object keyed by hook event name, found ${Array.isArray(raw) ? "an array" : raw === null ? "null" : typeof raw}`
|
|
@@ -10395,7 +11289,7 @@ var readHooksObject = (base, conflicts) => {
|
|
|
10395
11289
|
}
|
|
10396
11290
|
return { ...raw };
|
|
10397
11291
|
};
|
|
10398
|
-
var pruneEventList = (list) => list.filter((group) => !(
|
|
11292
|
+
var pruneEventList = (list) => list.filter((group) => !(isPlainObject7(group) && Array.isArray(group.hooks) && group.hooks.length === 0));
|
|
10399
11293
|
var finalize = (base, hooks) => {
|
|
10400
11294
|
const next = { ...base };
|
|
10401
11295
|
if (Object.keys(hooks).length === 0) {
|
|
@@ -10406,7 +11300,7 @@ var finalize = (base, hooks) => {
|
|
|
10406
11300
|
return next;
|
|
10407
11301
|
};
|
|
10408
11302
|
var mergeNestedHookRegistration = (input) => {
|
|
10409
|
-
const base =
|
|
11303
|
+
const base = isPlainObject7(input.existing) ? { ...input.existing } : {};
|
|
10410
11304
|
const conflicts = [];
|
|
10411
11305
|
const hooks = readHooksObject(base, conflicts);
|
|
10412
11306
|
if (hooks === void 0) {
|
|
@@ -10422,7 +11316,7 @@ var mergeNestedHookRegistration = (input) => {
|
|
|
10422
11316
|
}
|
|
10423
11317
|
const groups = list.map((group) => cloneGroup(group) ?? group);
|
|
10424
11318
|
const usableGroups = groups.filter(
|
|
10425
|
-
(group) =>
|
|
11319
|
+
(group) => isPlainObject7(group) && Array.isArray(group.hooks)
|
|
10426
11320
|
);
|
|
10427
11321
|
let ownHandler;
|
|
10428
11322
|
let ownGroup;
|
|
@@ -10487,7 +11381,7 @@ var mergeNestedHookRegistration = (input) => {
|
|
|
10487
11381
|
return { document: finalize(base, hooks), changed, changes, conflicts };
|
|
10488
11382
|
};
|
|
10489
11383
|
var removeNestedHookRegistrations = (input) => {
|
|
10490
|
-
const base =
|
|
11384
|
+
const base = isPlainObject7(input.existing) ? { ...input.existing } : {};
|
|
10491
11385
|
const conflicts = [];
|
|
10492
11386
|
const hooks = readHooksObject(base, conflicts);
|
|
10493
11387
|
if (hooks === void 0) {
|
|
@@ -10540,7 +11434,7 @@ var removeNestedHookRegistrations = (input) => {
|
|
|
10540
11434
|
};
|
|
10541
11435
|
var readNestedHookRegistrations = (existing, identifies) => {
|
|
10542
11436
|
const found = /* @__PURE__ */ new Map();
|
|
10543
|
-
if (!
|
|
11437
|
+
if (!isPlainObject7(existing) || !isPlainObject7(existing.hooks)) {
|
|
10544
11438
|
return found;
|
|
10545
11439
|
}
|
|
10546
11440
|
for (const [event3, list] of Object.entries(existing.hooks)) {
|
|
@@ -10549,7 +11443,7 @@ var readNestedHookRegistrations = (existing, identifies) => {
|
|
|
10549
11443
|
}
|
|
10550
11444
|
const commands = [];
|
|
10551
11445
|
for (const group of list) {
|
|
10552
|
-
if (!
|
|
11446
|
+
if (!isPlainObject7(group) || !Array.isArray(group.hooks)) {
|
|
10553
11447
|
continue;
|
|
10554
11448
|
}
|
|
10555
11449
|
for (const handler of group.hooks) {
|
|
@@ -10686,7 +11580,7 @@ var CURSOR_UNREGISTERED_HOOK_EVENTS = Object.freeze({
|
|
|
10686
11580
|
workspaceOpen: "an app-lifecycle hook that carries no conversation_id, so it has no session to attribute telemetry to"
|
|
10687
11581
|
});
|
|
10688
11582
|
var CURSOR_HOOKS_DOCUMENT_VERSION = 1;
|
|
10689
|
-
var
|
|
11583
|
+
var isPlainObject8 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
10690
11584
|
var buildEntry3 = (input) => ({
|
|
10691
11585
|
type: "command",
|
|
10692
11586
|
command: input.command,
|
|
@@ -10695,8 +11589,8 @@ var buildEntry3 = (input) => ({
|
|
|
10695
11589
|
});
|
|
10696
11590
|
var mergeCursorHookRegistration = (input) => {
|
|
10697
11591
|
const events = input.events ?? CURSOR_REGISTRABLE_HOOK_EVENTS;
|
|
10698
|
-
const base =
|
|
10699
|
-
const existingHooks =
|
|
11592
|
+
const base = isPlainObject8(input.existing) ? { ...input.existing } : {};
|
|
11593
|
+
const existingHooks = isPlainObject8(base.hooks) ? base.hooks : {};
|
|
10700
11594
|
const nextHooks = { ...existingHooks };
|
|
10701
11595
|
const desired = buildEntry3(input);
|
|
10702
11596
|
let changed = false;
|
|
@@ -10707,7 +11601,7 @@ var mergeCursorHookRegistration = (input) => {
|
|
|
10707
11601
|
for (const event3 of events) {
|
|
10708
11602
|
const currentList = Array.isArray(existingHooks[event3]) ? [...existingHooks[event3]] : [];
|
|
10709
11603
|
const managed = currentList.filter(
|
|
10710
|
-
(entry) =>
|
|
11604
|
+
(entry) => isPlainObject8(entry) && input.identifies(entry)
|
|
10711
11605
|
);
|
|
10712
11606
|
const [ours] = managed;
|
|
10713
11607
|
if (ours === void 0) {
|
|
@@ -10716,7 +11610,7 @@ var mergeCursorHookRegistration = (input) => {
|
|
|
10716
11610
|
continue;
|
|
10717
11611
|
}
|
|
10718
11612
|
const rewritten = { ...ours, ...desired };
|
|
10719
|
-
const next = currentList.filter((entry) => entry === ours || !(
|
|
11613
|
+
const next = currentList.filter((entry) => entry === ours || !(isPlainObject8(entry) && input.identifies(entry))).map((entry) => entry === ours ? rewritten : entry);
|
|
10720
11614
|
const entryChanged = Object.entries(desired).some(([key, value]) => ours[key] !== value);
|
|
10721
11615
|
if (entryChanged || managed.length > 1) {
|
|
10722
11616
|
changed = true;
|
|
@@ -10726,8 +11620,8 @@ var mergeCursorHookRegistration = (input) => {
|
|
|
10726
11620
|
return { config: { ...base, hooks: nextHooks }, changed };
|
|
10727
11621
|
};
|
|
10728
11622
|
var removeCursorHookRegistration = (input) => {
|
|
10729
|
-
const base =
|
|
10730
|
-
if (!
|
|
11623
|
+
const base = isPlainObject8(input.existing) ? { ...input.existing } : {};
|
|
11624
|
+
if (!isPlainObject8(base.hooks)) {
|
|
10731
11625
|
return { config: base, changed: false };
|
|
10732
11626
|
}
|
|
10733
11627
|
const nextHooks = { ...base.hooks };
|
|
@@ -10739,7 +11633,7 @@ var removeCursorHookRegistration = (input) => {
|
|
|
10739
11633
|
continue;
|
|
10740
11634
|
}
|
|
10741
11635
|
const kept = currentList.filter(
|
|
10742
|
-
(entry) => !(
|
|
11636
|
+
(entry) => !(isPlainObject8(entry) && input.identifies(entry))
|
|
10743
11637
|
);
|
|
10744
11638
|
if (kept.length === currentList.length) {
|
|
10745
11639
|
continue;
|
|
@@ -10767,7 +11661,7 @@ var removeCursorHookRegistration = (input) => {
|
|
|
10767
11661
|
};
|
|
10768
11662
|
var readCursorHookRegistrations = (existing, identifies) => {
|
|
10769
11663
|
const found = /* @__PURE__ */ new Map();
|
|
10770
|
-
if (!
|
|
11664
|
+
if (!isPlainObject8(existing) || !isPlainObject8(existing.hooks)) {
|
|
10771
11665
|
return found;
|
|
10772
11666
|
}
|
|
10773
11667
|
for (const [event3, list] of Object.entries(existing.hooks)) {
|
|
@@ -10775,7 +11669,7 @@ var readCursorHookRegistrations = (existing, identifies) => {
|
|
|
10775
11669
|
continue;
|
|
10776
11670
|
}
|
|
10777
11671
|
const commands = list.filter(
|
|
10778
|
-
(entry) =>
|
|
11672
|
+
(entry) => isPlainObject8(entry) && typeof entry.command === "string" && identifies(entry)
|
|
10779
11673
|
).map((entry) => entry.command);
|
|
10780
11674
|
if (commands.length > 0) {
|
|
10781
11675
|
found.set(event3, commands);
|
|
@@ -10875,7 +11769,7 @@ var managedHookPredicate = (marker) => {
|
|
|
10875
11769
|
}
|
|
10876
11770
|
return (handler) => handler.name === MANAGED_HOOK_NAME || typeof handler.command === "string" && handler.command.includes(marker);
|
|
10877
11771
|
};
|
|
10878
|
-
var
|
|
11772
|
+
var isPlainObject9 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
10879
11773
|
var adaptFlatResult = (read, existing, events, identifies, result, removal) => {
|
|
10880
11774
|
const before = read(existing, identifies);
|
|
10881
11775
|
const after = read(result.config, identifies);
|
|
@@ -10899,10 +11793,10 @@ var adaptFlatResult = (read, existing, events, identifies, result, removal) => {
|
|
|
10899
11793
|
return { document: result.config, changed: result.changed, changes, conflicts: [] };
|
|
10900
11794
|
};
|
|
10901
11795
|
var flatHookConflicts = (existing) => {
|
|
10902
|
-
if (!
|
|
11796
|
+
if (!isPlainObject9(existing) || existing.hooks === void 0) {
|
|
10903
11797
|
return [];
|
|
10904
11798
|
}
|
|
10905
|
-
if (!
|
|
11799
|
+
if (!isPlainObject9(existing.hooks)) {
|
|
10906
11800
|
return [
|
|
10907
11801
|
{
|
|
10908
11802
|
location: "hooks",
|
|
@@ -10922,7 +11816,7 @@ var flatHookConflicts = (existing) => {
|
|
|
10922
11816
|
return conflicts;
|
|
10923
11817
|
};
|
|
10924
11818
|
var asAntigravityEvents = (events) => events;
|
|
10925
|
-
var documentEventNames = (existing) =>
|
|
11819
|
+
var documentEventNames = (existing) => isPlainObject9(existing) && isPlainObject9(existing.hooks) ? Object.keys(existing.hooks) : [];
|
|
10926
11820
|
var PLANNERS = Object.freeze([
|
|
10927
11821
|
Object.freeze({
|
|
10928
11822
|
providerId: ANTIGRAVITY_PROVIDER_ID,
|
|
@@ -10931,7 +11825,7 @@ var PLANNERS = Object.freeze([
|
|
|
10931
11825
|
const conflicts = flatHookConflicts(input.existing);
|
|
10932
11826
|
if (conflicts.length > 0) {
|
|
10933
11827
|
return {
|
|
10934
|
-
document:
|
|
11828
|
+
document: isPlainObject9(input.existing) ? input.existing : {},
|
|
10935
11829
|
changed: false,
|
|
10936
11830
|
changes: [],
|
|
10937
11831
|
conflicts
|
|
@@ -10957,7 +11851,7 @@ var PLANNERS = Object.freeze([
|
|
|
10957
11851
|
const conflicts = flatHookConflicts(input.existing);
|
|
10958
11852
|
if (conflicts.length > 0) {
|
|
10959
11853
|
return {
|
|
10960
|
-
document:
|
|
11854
|
+
document: isPlainObject9(input.existing) ? input.existing : {},
|
|
10961
11855
|
changed: false,
|
|
10962
11856
|
changes: [],
|
|
10963
11857
|
conflicts
|
|
@@ -11000,7 +11894,7 @@ var PLANNERS = Object.freeze([
|
|
|
11000
11894
|
const conflicts = flatHookConflicts(input.existing);
|
|
11001
11895
|
if (conflicts.length > 0) {
|
|
11002
11896
|
return {
|
|
11003
|
-
document:
|
|
11897
|
+
document: isPlainObject9(input.existing) ? input.existing : {},
|
|
11004
11898
|
changed: false,
|
|
11005
11899
|
changes: [],
|
|
11006
11900
|
conflicts
|
|
@@ -11027,7 +11921,7 @@ var PLANNERS = Object.freeze([
|
|
|
11027
11921
|
const conflicts = flatHookConflicts(input.existing);
|
|
11028
11922
|
if (conflicts.length > 0) {
|
|
11029
11923
|
return {
|
|
11030
|
-
document:
|
|
11924
|
+
document: isPlainObject9(input.existing) ? input.existing : {},
|
|
11031
11925
|
changed: false,
|
|
11032
11926
|
changes: [],
|
|
11033
11927
|
conflicts
|
|
@@ -11852,7 +12746,7 @@ var runRegistrationCommand = async (command, io) => {
|
|
|
11852
12746
|
};
|
|
11853
12747
|
|
|
11854
12748
|
// src/cli/run.ts
|
|
11855
|
-
import * as
|
|
12749
|
+
import * as path13 from "path";
|
|
11856
12750
|
|
|
11857
12751
|
// src/lifecycle/dedup.ts
|
|
11858
12752
|
import { randomBytes as randomBytes5 } from "crypto";
|
|
@@ -11880,6 +12774,8 @@ var rollupUsageKey = (sessionId, scope, scopeKey) => `${rollupScanPrefix(session
|
|
|
11880
12774
|
var rollupEpochKey = (sessionId, scope, scopeKey) => `${rollupEpochScanPrefix(sessionId)}${encodeSegment(scope)}:${encodeSegment(scopeKey)}`;
|
|
11881
12775
|
var rollupScanPrefix = (sessionId) => sessionId === void 0 ? `${LIFECYCLE_PREFIX}:usage:` : `${LIFECYCLE_PREFIX}:usage:${encodeSegment(sessionId)}:`;
|
|
11882
12776
|
var rollupEpochScanPrefix = (sessionId) => sessionId === void 0 ? `${LIFECYCLE_PREFIX}:epoch:` : `${LIFECYCLE_PREFIX}:epoch:${encodeSegment(sessionId)}:`;
|
|
12777
|
+
var metricSeriesKey = (sessionScope2, seriesDigest) => `${metricSeriesScanPrefix(sessionScope2)}${encodeSegment(seriesDigest)}`;
|
|
12778
|
+
var metricSeriesScanPrefix = (sessionScope2) => sessionScope2 === void 0 ? `${LIFECYCLE_PREFIX}:metric:v1:` : `${LIFECYCLE_PREFIX}:metric:v1:${encodeSegment(sessionScope2)}:`;
|
|
11883
12779
|
|
|
11884
12780
|
// src/lifecycle/dedup.ts
|
|
11885
12781
|
var DEFAULT_STALE_CLAIM_MILLIS = 6e4;
|
|
@@ -12049,6 +12945,150 @@ var createCallbackDeduplicator = (deps) => {
|
|
|
12049
12945
|
return { checkAndMark, claim, commit, release, cleanup };
|
|
12050
12946
|
};
|
|
12051
12947
|
|
|
12948
|
+
// src/lifecycle/metric-series.ts
|
|
12949
|
+
import { createHash as createHash4 } from "crypto";
|
|
12950
|
+
var TURN_START_SEGMENT = "turn-start";
|
|
12951
|
+
var SHARED_SCOPE = "all";
|
|
12952
|
+
var SHARED_LOCK = "otelhook.metrics.shared";
|
|
12953
|
+
var sessionScope = (sessionId) => `s=${sessionId}`;
|
|
12954
|
+
var digest = (identity) => createHash4("sha256").update(identity).digest("base64url").slice(0, 43);
|
|
12955
|
+
var toStoredHistogram = (histogram) => ({
|
|
12956
|
+
count: histogram.count,
|
|
12957
|
+
sum: histogram.sum,
|
|
12958
|
+
// An empty histogram has infinite min/max, which JSON cannot hold. A stored
|
|
12959
|
+
// histogram always has at least one value, so these are finite in practice.
|
|
12960
|
+
min: Number.isFinite(histogram.min) ? histogram.min : 0,
|
|
12961
|
+
max: Number.isFinite(histogram.max) ? histogram.max : 0,
|
|
12962
|
+
bucketCounts: [...histogram.bucketCounts]
|
|
12963
|
+
});
|
|
12964
|
+
var createMetricSeriesStore = (deps) => {
|
|
12965
|
+
const { stateStore, clock } = deps;
|
|
12966
|
+
const readSeries = async (key) => {
|
|
12967
|
+
const record = await stateStore.read(key);
|
|
12968
|
+
if (record?.value.kind !== "metric-series") {
|
|
12969
|
+
return void 0;
|
|
12970
|
+
}
|
|
12971
|
+
return record.value;
|
|
12972
|
+
};
|
|
12973
|
+
const recordGroup = async (scope, observations, deliveryToken) => {
|
|
12974
|
+
const bySeries = /* @__PURE__ */ new Map();
|
|
12975
|
+
for (const observation of observations) {
|
|
12976
|
+
const identity = seriesIdentity(observation.instrument, observation.attributes);
|
|
12977
|
+
const group = bySeries.get(identity) ?? [];
|
|
12978
|
+
group.push(observation);
|
|
12979
|
+
bySeries.set(identity, group);
|
|
12980
|
+
}
|
|
12981
|
+
const now = clock.now();
|
|
12982
|
+
const points = [];
|
|
12983
|
+
for (const [identity, group] of bySeries) {
|
|
12984
|
+
const first = group[0];
|
|
12985
|
+
if (first === void 0) {
|
|
12986
|
+
continue;
|
|
12987
|
+
}
|
|
12988
|
+
const instrument = METRIC_INSTRUMENTS[first.instrument];
|
|
12989
|
+
const key = metricSeriesKey(scope, digest(identity));
|
|
12990
|
+
const existing = await readSeries(key);
|
|
12991
|
+
const boundaries = instrument.boundaries;
|
|
12992
|
+
const compatible = existing !== void 0 && (boundaries === void 0 ? existing.value !== void 0 : existing.histogram?.bucketCounts.length === boundaries.length + 1);
|
|
12993
|
+
const base = compatible ? existing : void 0;
|
|
12994
|
+
const replay = deliveryToken !== void 0 && base?.appliedDelivery === deliveryToken;
|
|
12995
|
+
const earliest = Math.min(...group.map((observation) => observation.timeMillis));
|
|
12996
|
+
const startTimeMillis = base?.startTimeMillis ?? Math.min(earliest, now);
|
|
12997
|
+
let value = base?.value ?? 0;
|
|
12998
|
+
let histogram = boundaries === void 0 ? void 0 : base?.histogram === void 0 ? emptyHistogram(boundaries) : base.histogram;
|
|
12999
|
+
if (!replay) {
|
|
13000
|
+
for (const observation of group) {
|
|
13001
|
+
if (histogram !== void 0 && boundaries !== void 0) {
|
|
13002
|
+
histogram = recordIntoHistogram(histogram, boundaries, observation.value);
|
|
13003
|
+
} else {
|
|
13004
|
+
value += observation.value;
|
|
13005
|
+
}
|
|
13006
|
+
}
|
|
13007
|
+
await stateStore.write(key, {
|
|
13008
|
+
kind: "metric-series",
|
|
13009
|
+
startTimeMillis,
|
|
13010
|
+
...histogram === void 0 ? { value } : { histogram: toStoredHistogram(histogram) },
|
|
13011
|
+
...deliveryToken === void 0 ? {} : { appliedDelivery: deliveryToken }
|
|
13012
|
+
});
|
|
13013
|
+
}
|
|
13014
|
+
points.push({
|
|
13015
|
+
instrument: first.instrument,
|
|
13016
|
+
temporality: "cumulative",
|
|
13017
|
+
attributes: first.attributes,
|
|
13018
|
+
startTimeMillis,
|
|
13019
|
+
timeMillis: Math.max(now, startTimeMillis),
|
|
13020
|
+
...histogram === void 0 ? { value } : { histogram }
|
|
13021
|
+
});
|
|
13022
|
+
}
|
|
13023
|
+
return points;
|
|
13024
|
+
};
|
|
13025
|
+
const recordCumulative = async (observations, options) => {
|
|
13026
|
+
if (observations.length === 0) {
|
|
13027
|
+
return [];
|
|
13028
|
+
}
|
|
13029
|
+
if (options?.perSession === false) {
|
|
13030
|
+
return withOptionalSessionLock(
|
|
13031
|
+
stateStore,
|
|
13032
|
+
SHARED_LOCK,
|
|
13033
|
+
() => recordGroup(SHARED_SCOPE, observations, options.deliveryToken)
|
|
13034
|
+
);
|
|
13035
|
+
}
|
|
13036
|
+
const bySession = /* @__PURE__ */ new Map();
|
|
13037
|
+
for (const observation of observations) {
|
|
13038
|
+
const group = bySession.get(observation.sessionId) ?? [];
|
|
13039
|
+
group.push(observation);
|
|
13040
|
+
bySession.set(observation.sessionId, group);
|
|
13041
|
+
}
|
|
13042
|
+
const points = [];
|
|
13043
|
+
for (const [sessionId, group] of bySession) {
|
|
13044
|
+
points.push(
|
|
13045
|
+
...await withOptionalSessionLock(
|
|
13046
|
+
stateStore,
|
|
13047
|
+
sessionId,
|
|
13048
|
+
() => recordGroup(sessionScope(sessionId), group, options?.deliveryToken)
|
|
13049
|
+
)
|
|
13050
|
+
);
|
|
13051
|
+
}
|
|
13052
|
+
return points;
|
|
13053
|
+
};
|
|
13054
|
+
const cleanup = async (maxAgeMillis, options) => {
|
|
13055
|
+
const cap = options?.maxEntries ?? 1e3;
|
|
13056
|
+
const now = clock.now();
|
|
13057
|
+
let removed = 0;
|
|
13058
|
+
let scanned = 0;
|
|
13059
|
+
const prefix = metricSeriesScanPrefix(
|
|
13060
|
+
options?.sessionId === void 0 ? void 0 : sessionScope(options.sessionId)
|
|
13061
|
+
);
|
|
13062
|
+
for (const key of await stateStore.keys(prefix)) {
|
|
13063
|
+
if (scanned >= cap) {
|
|
13064
|
+
break;
|
|
13065
|
+
}
|
|
13066
|
+
scanned += 1;
|
|
13067
|
+
const record = await stateStore.read(key);
|
|
13068
|
+
if (record !== void 0 && now - record.updatedAt > maxAgeMillis) {
|
|
13069
|
+
await stateStore.delete(key);
|
|
13070
|
+
removed += 1;
|
|
13071
|
+
}
|
|
13072
|
+
}
|
|
13073
|
+
return { removed, scanned };
|
|
13074
|
+
};
|
|
13075
|
+
const turnKey = (sessionId) => metricSeriesKey(sessionScope(sessionId), TURN_START_SEGMENT);
|
|
13076
|
+
const recordTurnStart = (sessionId, startMillis) => withOptionalSessionLock(stateStore, sessionId, async () => {
|
|
13077
|
+
const existing = await stateStore.read(turnKey(sessionId));
|
|
13078
|
+
const previous = existing?.value.kind === "attributes" && typeof existing.value.attributes.startMillis === "number" ? existing.value.attributes.startMillis : void 0;
|
|
13079
|
+
if (previous !== void 0 && previous >= startMillis) {
|
|
13080
|
+
return;
|
|
13081
|
+
}
|
|
13082
|
+
await stateStore.write(turnKey(sessionId), { kind: "attributes", attributes: { startMillis } });
|
|
13083
|
+
});
|
|
13084
|
+
const readTurnStart = async (sessionId) => {
|
|
13085
|
+
const record = await stateStore.read(turnKey(sessionId));
|
|
13086
|
+
const value = record?.value.kind === "attributes" ? record.value.attributes.startMillis : void 0;
|
|
13087
|
+
return typeof value === "number" ? value : void 0;
|
|
13088
|
+
};
|
|
13089
|
+
return { recordCumulative, recordTurnStart, readTurnStart, cleanup };
|
|
13090
|
+
};
|
|
13091
|
+
|
|
12052
13092
|
// src/lifecycle/janitor.ts
|
|
12053
13093
|
var DEFAULT_MAX_AGE_MILLIS = 24 * 60 * 60 * 1e3;
|
|
12054
13094
|
var DEFAULT_MAX_ENTRIES_PER_COMPONENT = 1e3;
|
|
@@ -12059,7 +13099,7 @@ var createLifecycleJanitor = (options) => {
|
|
|
12059
13099
|
const usageMaxAge = options.usageMaxAgeMillis ?? DEFAULT_MAX_AGE_MILLIS;
|
|
12060
13100
|
const runOnce = async (sessionId) => {
|
|
12061
13101
|
const scope = { maxEntries, ...sessionId === void 0 ? {} : { sessionId } };
|
|
12062
|
-
const [span, dedup, usage] = await Promise.all([
|
|
13102
|
+
const [span, dedup, usage, metrics] = await Promise.all([
|
|
12063
13103
|
options.spanCorrelator?.cleanup(spanMaxAge, scope),
|
|
12064
13104
|
// Deduplication is deliberately swept across every scope rather than the
|
|
12065
13105
|
// ending session's: a delivery scope is a host-chosen namespace or a
|
|
@@ -12070,12 +13110,14 @@ var createLifecycleJanitor = (options) => {
|
|
|
12070
13110
|
maxEntries,
|
|
12071
13111
|
...options.dedupStaleClaimMillis === void 0 ? {} : { staleClaimMillis: options.dedupStaleClaimMillis }
|
|
12072
13112
|
}),
|
|
12073
|
-
options.usageAccumulator?.cleanup(usageMaxAge, scope)
|
|
13113
|
+
options.usageAccumulator?.cleanup(usageMaxAge, scope),
|
|
13114
|
+
options.metricSeries?.cleanup(usageMaxAge, scope)
|
|
12074
13115
|
]);
|
|
12075
13116
|
return {
|
|
12076
13117
|
...span === void 0 ? {} : { span },
|
|
12077
13118
|
...dedup === void 0 ? {} : { dedup },
|
|
12078
|
-
...usage === void 0 ? {} : { usage }
|
|
13119
|
+
...usage === void 0 ? {} : { usage },
|
|
13120
|
+
...metrics === void 0 ? {} : { metrics }
|
|
12079
13121
|
};
|
|
12080
13122
|
};
|
|
12081
13123
|
return { runOnce };
|
|
@@ -12588,6 +13630,301 @@ var createUsageAccumulator = (deps) => {
|
|
|
12588
13630
|
return { accumulateDelta, recordReset, read, cleanup };
|
|
12589
13631
|
};
|
|
12590
13632
|
|
|
13633
|
+
// src/providers/claude/transcript.ts
|
|
13634
|
+
import { createHash as createHash5 } from "crypto";
|
|
13635
|
+
import { open as open4, stat as stat4 } from "fs/promises";
|
|
13636
|
+
import path10 from "path";
|
|
13637
|
+
var DEFAULT_CLAUDE_TRANSCRIPT_TAIL_BYTES = 1048576;
|
|
13638
|
+
var DEFAULT_CLAUDE_TRANSCRIPT_TIMEOUT_MILLIS = 250;
|
|
13639
|
+
var DEFAULT_CLAUDE_TRANSCRIPT_RANGE_BYTES = 8388608;
|
|
13640
|
+
var DEFAULT_CLAUDE_TRANSCRIPT_RANGE_TIMEOUT_MILLIS = 500;
|
|
13641
|
+
var MIN_TAIL_BYTES = 65536;
|
|
13642
|
+
var MAX_TAIL_BYTES = 16777216;
|
|
13643
|
+
var MAX_RANGE_BYTES = 67108864;
|
|
13644
|
+
var MIN_TIMEOUT_MILLIS = 10;
|
|
13645
|
+
var MAX_TIMEOUT_MILLIS = 5e3;
|
|
13646
|
+
var MAX_MODEL_ID_LENGTH = 256;
|
|
13647
|
+
var MAX_REQUESTS_PER_RANGE = 1e4;
|
|
13648
|
+
var SYNTHETIC_MODEL = "<synthetic>";
|
|
13649
|
+
var TIMED_OUT = /* @__PURE__ */ Symbol("timed-out");
|
|
13650
|
+
var clamp = (value, fallback, min, max) => {
|
|
13651
|
+
if (value === void 0 || !Number.isFinite(value)) {
|
|
13652
|
+
return fallback;
|
|
13653
|
+
}
|
|
13654
|
+
return Math.min(max, Math.max(min, Math.floor(value)));
|
|
13655
|
+
};
|
|
13656
|
+
var asRecord7 = (value) => typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
|
|
13657
|
+
var isTranscriptPath = (transcriptPath) => typeof transcriptPath === "string" && transcriptPath.length > 0 && !transcriptPath.includes("\0") && path10.isAbsolute(transcriptPath) && path10.extname(transcriptPath) === ".jsonl";
|
|
13658
|
+
var assistantRecordOf = (line) => {
|
|
13659
|
+
if (!line.includes('"assistant"')) {
|
|
13660
|
+
return void 0;
|
|
13661
|
+
}
|
|
13662
|
+
let parsed;
|
|
13663
|
+
try {
|
|
13664
|
+
parsed = JSON.parse(line);
|
|
13665
|
+
} catch {
|
|
13666
|
+
return void 0;
|
|
13667
|
+
}
|
|
13668
|
+
const record = asRecord7(parsed);
|
|
13669
|
+
if (record === void 0 || record.type !== "assistant" || record.isSidechain === true) {
|
|
13670
|
+
return void 0;
|
|
13671
|
+
}
|
|
13672
|
+
const message = asRecord7(record.message);
|
|
13673
|
+
if (message === void 0 || message.model === SYNTHETIC_MODEL) {
|
|
13674
|
+
return void 0;
|
|
13675
|
+
}
|
|
13676
|
+
const model = typeof message.model === "string" && message.model.length > 0 && message.model.length <= MAX_MODEL_ID_LENGTH ? message.model : void 0;
|
|
13677
|
+
const usage = coerceClaudeUsage(message.usage);
|
|
13678
|
+
if (model === void 0 && usage === void 0) {
|
|
13679
|
+
return void 0;
|
|
13680
|
+
}
|
|
13681
|
+
const id = typeof message.id === "string" && message.id.length > 0 && message.id.length <= 256 ? message.id : void 0;
|
|
13682
|
+
return {
|
|
13683
|
+
...id === void 0 ? {} : { id },
|
|
13684
|
+
...model === void 0 ? {} : { model },
|
|
13685
|
+
...usage === void 0 ? {} : { usage }
|
|
13686
|
+
};
|
|
13687
|
+
};
|
|
13688
|
+
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));
|
|
13689
|
+
var sumUsage = (usages) => {
|
|
13690
|
+
let input = 0;
|
|
13691
|
+
let output = 0;
|
|
13692
|
+
let cacheRead = 0;
|
|
13693
|
+
let cacheCreation = 0;
|
|
13694
|
+
for (const usage of usages) {
|
|
13695
|
+
input += usage.input_tokens;
|
|
13696
|
+
output += usage.output_tokens;
|
|
13697
|
+
cacheRead += usage.cache_read_input_tokens ?? 0;
|
|
13698
|
+
cacheCreation += cacheCreationOf(usage);
|
|
13699
|
+
}
|
|
13700
|
+
return {
|
|
13701
|
+
input_tokens: input,
|
|
13702
|
+
output_tokens: output,
|
|
13703
|
+
cache_read_input_tokens: cacheRead,
|
|
13704
|
+
cache_creation_input_tokens: cacheCreation
|
|
13705
|
+
};
|
|
13706
|
+
};
|
|
13707
|
+
var withTimeout = async (work, timeoutMillis, onError) => {
|
|
13708
|
+
let timer;
|
|
13709
|
+
const timeout = new Promise((resolve8) => {
|
|
13710
|
+
timer = setTimeout(() => {
|
|
13711
|
+
resolve8(TIMED_OUT);
|
|
13712
|
+
}, timeoutMillis);
|
|
13713
|
+
timer.unref();
|
|
13714
|
+
});
|
|
13715
|
+
try {
|
|
13716
|
+
return await Promise.race([work.catch(() => onError), timeout]);
|
|
13717
|
+
} finally {
|
|
13718
|
+
clearTimeout(timer);
|
|
13719
|
+
}
|
|
13720
|
+
};
|
|
13721
|
+
var withRegularFile = async (transcriptPath, body) => {
|
|
13722
|
+
let info;
|
|
13723
|
+
try {
|
|
13724
|
+
info = await stat4(transcriptPath);
|
|
13725
|
+
} catch {
|
|
13726
|
+
return { status: "unavailable", reason: "unreadable" };
|
|
13727
|
+
}
|
|
13728
|
+
if (!info.isFile()) {
|
|
13729
|
+
return { status: "unavailable", reason: "not-a-file" };
|
|
13730
|
+
}
|
|
13731
|
+
let handle;
|
|
13732
|
+
try {
|
|
13733
|
+
handle = await open4(transcriptPath, "r");
|
|
13734
|
+
} catch {
|
|
13735
|
+
return { status: "unavailable", reason: "unreadable" };
|
|
13736
|
+
}
|
|
13737
|
+
try {
|
|
13738
|
+
const { size } = await handle.stat();
|
|
13739
|
+
return await body(handle, size);
|
|
13740
|
+
} catch {
|
|
13741
|
+
return { status: "unavailable", reason: "unreadable" };
|
|
13742
|
+
} finally {
|
|
13743
|
+
await handle.close().catch(() => void 0);
|
|
13744
|
+
}
|
|
13745
|
+
};
|
|
13746
|
+
var readBytes = async (handle, start, length) => {
|
|
13747
|
+
const buffer = Buffer.alloc(length);
|
|
13748
|
+
let filled = 0;
|
|
13749
|
+
while (filled < length) {
|
|
13750
|
+
const { bytesRead } = await handle.read(buffer, filled, length - filled, start + filled);
|
|
13751
|
+
if (bytesRead === 0) {
|
|
13752
|
+
break;
|
|
13753
|
+
}
|
|
13754
|
+
filled += bytesRead;
|
|
13755
|
+
}
|
|
13756
|
+
return buffer.subarray(0, filled);
|
|
13757
|
+
};
|
|
13758
|
+
var completeLinesEnd = (bytes, start) => {
|
|
13759
|
+
const lastNewline = bytes.lastIndexOf(10);
|
|
13760
|
+
return lastNewline < 0 ? start : start + lastNewline + 1;
|
|
13761
|
+
};
|
|
13762
|
+
var readTail = (transcriptPath, maxTailBytes) => withRegularFile(transcriptPath, async (handle, size) => {
|
|
13763
|
+
const length = Math.min(size, maxTailBytes);
|
|
13764
|
+
const start = size - length;
|
|
13765
|
+
const bytes = await readBytes(handle, start, length);
|
|
13766
|
+
const endOffset = completeLinesEnd(bytes, start);
|
|
13767
|
+
const lines = bytes.toString("utf8").split("\n");
|
|
13768
|
+
if (start > 0) {
|
|
13769
|
+
lines.shift();
|
|
13770
|
+
}
|
|
13771
|
+
for (let index = lines.length - 1; index >= 0; index -= 1) {
|
|
13772
|
+
const record = assistantRecordOf((lines[index] ?? "").trim());
|
|
13773
|
+
if (record !== void 0) {
|
|
13774
|
+
return {
|
|
13775
|
+
turn: {
|
|
13776
|
+
status: "found",
|
|
13777
|
+
...record.model === void 0 ? {} : { model: record.model },
|
|
13778
|
+
...record.usage === void 0 ? {} : { usage: record.usage }
|
|
13779
|
+
},
|
|
13780
|
+
endOffset
|
|
13781
|
+
};
|
|
13782
|
+
}
|
|
13783
|
+
}
|
|
13784
|
+
return { turn: { status: "unavailable", reason: "no-assistant-message" }, endOffset };
|
|
13785
|
+
});
|
|
13786
|
+
var boundedTail = async (transcriptPath, options) => withTimeout(
|
|
13787
|
+
readTail(
|
|
13788
|
+
transcriptPath,
|
|
13789
|
+
clamp(options.maxTailBytes, DEFAULT_CLAUDE_TRANSCRIPT_TAIL_BYTES, MIN_TAIL_BYTES, MAX_TAIL_BYTES)
|
|
13790
|
+
),
|
|
13791
|
+
clamp(options.timeoutMillis, DEFAULT_CLAUDE_TRANSCRIPT_TIMEOUT_MILLIS, MIN_TIMEOUT_MILLIS, MAX_TIMEOUT_MILLIS),
|
|
13792
|
+
{ status: "unavailable", reason: "unreadable" }
|
|
13793
|
+
);
|
|
13794
|
+
var readClaudeTranscriptRange = async (transcriptPath, fromOffset, options = {}) => {
|
|
13795
|
+
if (!isTranscriptPath(transcriptPath) || !Number.isSafeInteger(fromOffset) || fromOffset < 0) {
|
|
13796
|
+
return { status: "unavailable", reason: "invalid-path" };
|
|
13797
|
+
}
|
|
13798
|
+
const maxRangeBytes = clamp(options.maxRangeBytes, DEFAULT_CLAUDE_TRANSCRIPT_RANGE_BYTES, MIN_TAIL_BYTES, MAX_RANGE_BYTES);
|
|
13799
|
+
const timeoutMillis = clamp(
|
|
13800
|
+
options.rangeTimeoutMillis,
|
|
13801
|
+
DEFAULT_CLAUDE_TRANSCRIPT_RANGE_TIMEOUT_MILLIS,
|
|
13802
|
+
MIN_TIMEOUT_MILLIS,
|
|
13803
|
+
MAX_TIMEOUT_MILLIS
|
|
13804
|
+
);
|
|
13805
|
+
const work = withRegularFile(transcriptPath, async (handle, size) => {
|
|
13806
|
+
if (size < fromOffset) {
|
|
13807
|
+
return { status: "unavailable", reason: "truncated" };
|
|
13808
|
+
}
|
|
13809
|
+
if (size - fromOffset > maxRangeBytes) {
|
|
13810
|
+
return { status: "unavailable", reason: "over-cap" };
|
|
13811
|
+
}
|
|
13812
|
+
const bytes = await readBytes(handle, fromOffset, size - fromOffset);
|
|
13813
|
+
const endOffset = completeLinesEnd(bytes, fromOffset);
|
|
13814
|
+
const complete = bytes.subarray(0, endOffset - fromOffset).toString("utf8");
|
|
13815
|
+
const requests = /* @__PURE__ */ new Map();
|
|
13816
|
+
let anonymous = 0;
|
|
13817
|
+
let model;
|
|
13818
|
+
for (const line of complete.split("\n")) {
|
|
13819
|
+
const record = assistantRecordOf(line.trim());
|
|
13820
|
+
if (record === void 0) {
|
|
13821
|
+
continue;
|
|
13822
|
+
}
|
|
13823
|
+
if (record.model !== void 0) {
|
|
13824
|
+
model = record.model;
|
|
13825
|
+
}
|
|
13826
|
+
anonymous += record.id === void 0 ? 1 : 0;
|
|
13827
|
+
requests.set(record.id ?? `#${String(anonymous)}`, record);
|
|
13828
|
+
if (requests.size > MAX_REQUESTS_PER_RANGE) {
|
|
13829
|
+
return { status: "unavailable", reason: "over-cap" };
|
|
13830
|
+
}
|
|
13831
|
+
}
|
|
13832
|
+
const usages = [...requests.values()].flatMap((record) => record.usage === void 0 ? [] : [record.usage]);
|
|
13833
|
+
return {
|
|
13834
|
+
status: "found",
|
|
13835
|
+
...model === void 0 ? {} : { model },
|
|
13836
|
+
...usages.length === 0 ? {} : { usage: sumUsage(usages) },
|
|
13837
|
+
requestCount: requests.size,
|
|
13838
|
+
endOffset
|
|
13839
|
+
};
|
|
13840
|
+
});
|
|
13841
|
+
const result = await withTimeout(work, timeoutMillis, {
|
|
13842
|
+
status: "unavailable",
|
|
13843
|
+
reason: "unreadable"
|
|
13844
|
+
});
|
|
13845
|
+
return result === TIMED_OUT ? { status: "unavailable", reason: "timeout" } : result;
|
|
13846
|
+
};
|
|
13847
|
+
var STOP_EVENTS = /* @__PURE__ */ new Set(["Stop", "StopFailure"]);
|
|
13848
|
+
var hasUsage = (record) => record.usage !== void 0 || record.token_usage !== void 0 || record.tokenUsage !== void 0;
|
|
13849
|
+
var eventNameOf = (record) => record.hook_event_name ?? record.hookEventName;
|
|
13850
|
+
var transcriptPathOf = (record) => record.transcript_path ?? record.transcriptPath;
|
|
13851
|
+
var CLAUDE_TRANSCRIPT_USAGE_ENRICHER_ID = "claude-transcript-usage";
|
|
13852
|
+
var sourceDigest = (transcriptPath) => createHash5("sha256").update(transcriptPath, "utf8").digest("hex").slice(0, 32);
|
|
13853
|
+
var createClaudeTranscriptUsageEnricher = (options = {}) => {
|
|
13854
|
+
const fileSize = async (transcriptPath) => {
|
|
13855
|
+
try {
|
|
13856
|
+
const info = await stat4(transcriptPath);
|
|
13857
|
+
return info.isFile() ? info.size : void 0;
|
|
13858
|
+
} catch (thrown) {
|
|
13859
|
+
return thrown?.code === "ENOENT" ? "absent" : void 0;
|
|
13860
|
+
}
|
|
13861
|
+
};
|
|
13862
|
+
const enrich = async (input) => {
|
|
13863
|
+
const unchanged = { payload: input.payload };
|
|
13864
|
+
const record = asRecord7(input.payload);
|
|
13865
|
+
if (record === void 0) {
|
|
13866
|
+
return unchanged;
|
|
13867
|
+
}
|
|
13868
|
+
const eventName = eventNameOf(record);
|
|
13869
|
+
const transcriptPath = transcriptPathOf(record);
|
|
13870
|
+
if (typeof eventName !== "string" || !isTranscriptPath(transcriptPath)) {
|
|
13871
|
+
return unchanged;
|
|
13872
|
+
}
|
|
13873
|
+
const source = sourceDigest(transcriptPath);
|
|
13874
|
+
const cursor = input.cursor?.source === source ? input.cursor : void 0;
|
|
13875
|
+
if (eventName === "SessionStart") {
|
|
13876
|
+
if (cursor !== void 0) {
|
|
13877
|
+
return unchanged;
|
|
13878
|
+
}
|
|
13879
|
+
const size = await fileSize(transcriptPath);
|
|
13880
|
+
if (size === void 0) {
|
|
13881
|
+
return { ...unchanged, notes: ["transcript is not a readable regular file; no cursor recorded"] };
|
|
13882
|
+
}
|
|
13883
|
+
return { payload: input.payload, cursor: { source, offset: size === "absent" ? 0 : size } };
|
|
13884
|
+
}
|
|
13885
|
+
if (!STOP_EVENTS.has(eventName)) {
|
|
13886
|
+
return unchanged;
|
|
13887
|
+
}
|
|
13888
|
+
if (hasUsage(record)) {
|
|
13889
|
+
const size = await fileSize(transcriptPath);
|
|
13890
|
+
return typeof size === "number" ? { payload: input.payload, cursor: { source, offset: size } } : unchanged;
|
|
13891
|
+
}
|
|
13892
|
+
const attach = (model, usage, partial) => ({
|
|
13893
|
+
...record,
|
|
13894
|
+
...record.model === void 0 && model !== void 0 ? { model } : {},
|
|
13895
|
+
...usage === void 0 ? {} : { usage, usage_partial: partial }
|
|
13896
|
+
});
|
|
13897
|
+
if (cursor !== void 0) {
|
|
13898
|
+
const range = await readClaudeTranscriptRange(transcriptPath, cursor.offset, options);
|
|
13899
|
+
if (range.status === "found") {
|
|
13900
|
+
return {
|
|
13901
|
+
payload: attach(range.model, range.usage, false),
|
|
13902
|
+
cursor: { source, offset: range.endOffset },
|
|
13903
|
+
notes: [`summed ${String(range.requestCount)} request(s) since the last stop`]
|
|
13904
|
+
};
|
|
13905
|
+
}
|
|
13906
|
+
if (range.reason !== "truncated" && range.reason !== "over-cap") {
|
|
13907
|
+
return { ...unchanged, notes: [`transcript range not read (${range.reason}); cursor kept`] };
|
|
13908
|
+
}
|
|
13909
|
+
}
|
|
13910
|
+
const tail = await boundedTail(transcriptPath, options);
|
|
13911
|
+
if (tail === TIMED_OUT || !("turn" in tail)) {
|
|
13912
|
+
return { ...unchanged, notes: [`transcript tail not read (${tail === TIMED_OUT ? "timeout" : tail.reason})`] };
|
|
13913
|
+
}
|
|
13914
|
+
const why = cursor === void 0 ? "no cursor for this transcript" : "range not summable within bounds";
|
|
13915
|
+
return {
|
|
13916
|
+
payload: tail.turn.status === "found" ? attach(tail.turn.model, tail.turn.usage, true) : input.payload,
|
|
13917
|
+
cursor: { source, offset: tail.endOffset },
|
|
13918
|
+
notes: [`${why}; attached the last request only (usage_partial)`]
|
|
13919
|
+
};
|
|
13920
|
+
};
|
|
13921
|
+
return Object.freeze({
|
|
13922
|
+
id: CLAUDE_TRANSCRIPT_USAGE_ENRICHER_ID,
|
|
13923
|
+
providerId: CLAUDE_CODE_PROVIDER_ID,
|
|
13924
|
+
enrich
|
|
13925
|
+
});
|
|
13926
|
+
};
|
|
13927
|
+
|
|
12591
13928
|
// src/runtime/hook.ts
|
|
12592
13929
|
import { z as z23 } from "zod";
|
|
12593
13930
|
|
|
@@ -12621,9 +13958,9 @@ var resolveDeliveryIdentity = (input) => {
|
|
|
12621
13958
|
};
|
|
12622
13959
|
|
|
12623
13960
|
// src/runtime/ids.ts
|
|
12624
|
-
import { createHash as
|
|
12625
|
-
var
|
|
12626
|
-
const hash =
|
|
13961
|
+
import { createHash as createHash6, randomUUID } from "crypto";
|
|
13962
|
+
var digest2 = (namespace, parts) => {
|
|
13963
|
+
const hash = createHash6("sha256");
|
|
12627
13964
|
hash.update(namespace);
|
|
12628
13965
|
for (const part of parts) {
|
|
12629
13966
|
hash.update("\0");
|
|
@@ -12638,7 +13975,7 @@ var createDeterministicIdGenerator = (options = {}) => {
|
|
|
12638
13975
|
return {
|
|
12639
13976
|
newInvocationId: (seed) => invocationIdSchema.parse(
|
|
12640
13977
|
`inv_${truncate(
|
|
12641
|
-
|
|
13978
|
+
digest2(`${namespace}/invocation`, [
|
|
12642
13979
|
seed.providerId,
|
|
12643
13980
|
seed.sessionId,
|
|
12644
13981
|
seed.sourceEventName,
|
|
@@ -12649,7 +13986,7 @@ var createDeterministicIdGenerator = (options = {}) => {
|
|
|
12649
13986
|
),
|
|
12650
13987
|
newEventId: (seed) => eventIdSchema.parse(
|
|
12651
13988
|
`evt_${truncate(
|
|
12652
|
-
|
|
13989
|
+
digest2(`${namespace}/event`, [
|
|
12653
13990
|
seed.invocationId,
|
|
12654
13991
|
seed.sequence,
|
|
12655
13992
|
seed.eventType,
|
|
@@ -12657,21 +13994,21 @@ var createDeterministicIdGenerator = (options = {}) => {
|
|
|
12657
13994
|
])
|
|
12658
13995
|
)}`
|
|
12659
13996
|
),
|
|
12660
|
-
newOpaqueId: (parts) => truncate(
|
|
13997
|
+
newOpaqueId: (parts) => truncate(digest2(`${namespace}/opaque`, parts))
|
|
12661
13998
|
};
|
|
12662
13999
|
};
|
|
12663
14000
|
|
|
12664
14001
|
// src/runtime/target-resolution.ts
|
|
12665
|
-
import * as
|
|
14002
|
+
import * as path11 from "path";
|
|
12666
14003
|
var DEFAULT_TARGET_RESOLUTION_BUDGET_MILLIS = 50;
|
|
12667
14004
|
var absolutePathsOf = (hint) => {
|
|
12668
|
-
const base = hint.baseDirectory !== void 0 &&
|
|
14005
|
+
const base = hint.baseDirectory !== void 0 && path11.isAbsolute(hint.baseDirectory) ? hint.baseDirectory : void 0;
|
|
12669
14006
|
const resolved = [];
|
|
12670
14007
|
for (const candidate of hint.paths) {
|
|
12671
|
-
if (
|
|
12672
|
-
resolved.push(
|
|
14008
|
+
if (path11.isAbsolute(candidate)) {
|
|
14009
|
+
resolved.push(path11.resolve(candidate));
|
|
12673
14010
|
} else if (base !== void 0) {
|
|
12674
|
-
resolved.push(
|
|
14011
|
+
resolved.push(path11.resolve(base, candidate));
|
|
12675
14012
|
} else {
|
|
12676
14013
|
return void 0;
|
|
12677
14014
|
}
|
|
@@ -12808,6 +14145,22 @@ var usageScopeOf = (event3) => {
|
|
|
12808
14145
|
}
|
|
12809
14146
|
};
|
|
12810
14147
|
var sequenceKey = (sessionId) => `sequence:${sessionId}`;
|
|
14148
|
+
var sessionModelKey = (sessionId) => `model:${sessionId}`;
|
|
14149
|
+
var readCursorKey = (enricherId, sessionId) => `cursor:${enricherId}:${sessionId}`;
|
|
14150
|
+
var UNKNOWN_MODEL_ID = "unknown";
|
|
14151
|
+
var latestSessionModel = (events) => {
|
|
14152
|
+
let latest;
|
|
14153
|
+
for (const event3 of events) {
|
|
14154
|
+
if (event3.subagentId !== void 0) {
|
|
14155
|
+
continue;
|
|
14156
|
+
}
|
|
14157
|
+
if ((event3.type === "session.start" || event3.type === "generation.start" || event3.type === "generation.end") && event3.model !== void 0 && event3.model.modelId !== UNKNOWN_MODEL_ID) {
|
|
14158
|
+
latest = event3.model;
|
|
14159
|
+
}
|
|
14160
|
+
}
|
|
14161
|
+
return latest;
|
|
14162
|
+
};
|
|
14163
|
+
var sameModel = (left, right) => left !== void 0 && left.modelId === right.modelId && left.vendor === right.vendor && left.family === right.family;
|
|
12811
14164
|
var usageKey = (sessionId, scope, scopeKey) => `usage:${sessionId}:${scope}:${scopeKey}`;
|
|
12812
14165
|
var baselineScopeOf = (scope, scopeKey, sessionId, series) => series === "session-lifetime" && scope === "generation" ? { scope: "session", scopeKey: sessionId } : { scope, scopeKey };
|
|
12813
14166
|
var createOtelHook = (deps) => {
|
|
@@ -12855,6 +14208,66 @@ var createOtelHook = (deps) => {
|
|
|
12855
14208
|
return 0;
|
|
12856
14209
|
}
|
|
12857
14210
|
};
|
|
14211
|
+
const enrichPayload = async (payload, providerId, sessionId, diagnostics) => {
|
|
14212
|
+
let current = payload;
|
|
14213
|
+
for (const enricher of deps.payloadEnrichers ?? []) {
|
|
14214
|
+
if (enricher.providerId !== providerId) {
|
|
14215
|
+
continue;
|
|
14216
|
+
}
|
|
14217
|
+
const key = readCursorKey(enricher.id, sessionId);
|
|
14218
|
+
let cursor;
|
|
14219
|
+
try {
|
|
14220
|
+
const record = await deps.stateStore.read(key);
|
|
14221
|
+
if (record?.value.kind === "read-cursor") {
|
|
14222
|
+
cursor = { source: record.value.source, offset: record.value.offset };
|
|
14223
|
+
}
|
|
14224
|
+
} catch (thrown) {
|
|
14225
|
+
diagnostics.push(
|
|
14226
|
+
errorInfoFromThrown(thrown, { code: "state-store-failure", phase: "state", occurredAt: clock.now() })
|
|
14227
|
+
);
|
|
14228
|
+
continue;
|
|
14229
|
+
}
|
|
14230
|
+
let result;
|
|
14231
|
+
try {
|
|
14232
|
+
result = await enricher.enrich({ payload: current, sessionId, ...cursor === void 0 ? {} : { cursor } });
|
|
14233
|
+
} catch (thrown) {
|
|
14234
|
+
logger.warn("payload enricher failed; parsing the payload as delivered", {
|
|
14235
|
+
"enricher.id": enricher.id,
|
|
14236
|
+
"error.name": thrown instanceof Error ? thrown.name : typeof thrown
|
|
14237
|
+
});
|
|
14238
|
+
continue;
|
|
14239
|
+
}
|
|
14240
|
+
current = result.payload;
|
|
14241
|
+
if (result.notes !== void 0 && result.notes.length > 0) {
|
|
14242
|
+
logger.debug("payload enricher notes", {
|
|
14243
|
+
"enricher.id": enricher.id,
|
|
14244
|
+
"enricher.notes": result.notes.slice(0, 8).map((note) => note.slice(0, 200))
|
|
14245
|
+
});
|
|
14246
|
+
}
|
|
14247
|
+
const next = result.cursor;
|
|
14248
|
+
if (next !== void 0 && (next.source !== cursor?.source || next.offset !== cursor.offset)) {
|
|
14249
|
+
try {
|
|
14250
|
+
await deps.stateStore.write(key, { kind: "read-cursor", source: next.source, offset: next.offset });
|
|
14251
|
+
} catch (thrown) {
|
|
14252
|
+
diagnostics.push(
|
|
14253
|
+
errorInfoFromThrown(thrown, { code: "state-store-failure", phase: "state", occurredAt: clock.now() })
|
|
14254
|
+
);
|
|
14255
|
+
}
|
|
14256
|
+
}
|
|
14257
|
+
}
|
|
14258
|
+
return current;
|
|
14259
|
+
};
|
|
14260
|
+
const readSessionModel = async (sessionId, diagnostics) => {
|
|
14261
|
+
try {
|
|
14262
|
+
const record = await deps.stateStore.read(sessionModelKey(sessionId));
|
|
14263
|
+
return record?.value.kind === "session-model" ? record.value.model : void 0;
|
|
14264
|
+
} catch (thrown) {
|
|
14265
|
+
diagnostics.push(
|
|
14266
|
+
errorInfoFromThrown(thrown, { code: "state-store-failure", phase: "state", occurredAt: clock.now() })
|
|
14267
|
+
);
|
|
14268
|
+
return void 0;
|
|
14269
|
+
}
|
|
14270
|
+
};
|
|
12858
14271
|
const deriveUsage = async (events, diagnostics, suppress, series) => {
|
|
12859
14272
|
const observations = [];
|
|
12860
14273
|
for (const event3 of events) {
|
|
@@ -13175,10 +14588,19 @@ var createOtelHook = (deps) => {
|
|
|
13175
14588
|
const identity = resolution.identity;
|
|
13176
14589
|
const prepare = async () => {
|
|
13177
14590
|
const sequenceBase = await readSequenceBase(identity.sessionId, diagnostics);
|
|
14591
|
+
const sessionModel = await readSessionModel(identity.sessionId, diagnostics);
|
|
14592
|
+
const payload = suppress ? detectionInput.payload : await enrichPayload(detectionInput.payload, detection.providerId, identity.sessionId, diagnostics);
|
|
13178
14593
|
let parsed;
|
|
13179
14594
|
try {
|
|
13180
14595
|
parsed = adapter.parse(
|
|
13181
|
-
{
|
|
14596
|
+
{
|
|
14597
|
+
...detectionInput,
|
|
14598
|
+
payload,
|
|
14599
|
+
detection,
|
|
14600
|
+
identity,
|
|
14601
|
+
sequenceBase,
|
|
14602
|
+
...sessionModel === void 0 ? {} : { sessionModel }
|
|
14603
|
+
},
|
|
13182
14604
|
providerContext
|
|
13183
14605
|
);
|
|
13184
14606
|
} catch (thrown) {
|
|
@@ -13288,6 +14710,23 @@ var createOtelHook = (deps) => {
|
|
|
13288
14710
|
})
|
|
13289
14711
|
);
|
|
13290
14712
|
}
|
|
14713
|
+
const reportedModel = latestSessionModel(screened.kept);
|
|
14714
|
+
if (reportedModel !== void 0 && !sameModel(sessionModel, reportedModel)) {
|
|
14715
|
+
try {
|
|
14716
|
+
await deps.stateStore.write(sessionModelKey(identity.sessionId), {
|
|
14717
|
+
kind: "session-model",
|
|
14718
|
+
model: reportedModel
|
|
14719
|
+
});
|
|
14720
|
+
} catch (thrown) {
|
|
14721
|
+
diagnostics.push(
|
|
14722
|
+
errorInfoFromThrown(thrown, {
|
|
14723
|
+
code: "state-store-failure",
|
|
14724
|
+
phase: "state",
|
|
14725
|
+
occurredAt: clock.now()
|
|
14726
|
+
})
|
|
14727
|
+
);
|
|
14728
|
+
}
|
|
14729
|
+
}
|
|
13291
14730
|
}
|
|
13292
14731
|
return {
|
|
13293
14732
|
kind: "ready",
|
|
@@ -13506,8 +14945,8 @@ var buildErrorEvents = (diagnostics, identity, sequenceBase, ids, privacy) => {
|
|
|
13506
14945
|
};
|
|
13507
14946
|
|
|
13508
14947
|
// src/runtime/git-worktree.ts
|
|
13509
|
-
import { lstat, open as
|
|
13510
|
-
import * as
|
|
14948
|
+
import { lstat, open as open5, stat as stat5 } from "fs/promises";
|
|
14949
|
+
import * as path12 from "path";
|
|
13511
14950
|
var MAX_WORKTREE_WALK_DEPTH = 128;
|
|
13512
14951
|
var MAX_GIT_FILE_BYTES = 4096;
|
|
13513
14952
|
var MAX_CACHE_ENTRIES = 1024;
|
|
@@ -13518,7 +14957,7 @@ var INVALID = Object.freeze({ kind: "invalid" });
|
|
|
13518
14957
|
var readBounded = async (filePath) => {
|
|
13519
14958
|
let handle;
|
|
13520
14959
|
try {
|
|
13521
|
-
handle = await
|
|
14960
|
+
handle = await open5(filePath, "r");
|
|
13522
14961
|
const buffer = Buffer.alloc(MAX_GIT_FILE_BYTES);
|
|
13523
14962
|
const { bytesRead } = await handle.read(buffer, 0, MAX_GIT_FILE_BYTES, 0);
|
|
13524
14963
|
return buffer.subarray(0, bytesRead).toString("utf8");
|
|
@@ -13539,7 +14978,7 @@ var parseHeadBranch = (head) => {
|
|
|
13539
14978
|
return branch;
|
|
13540
14979
|
};
|
|
13541
14980
|
var firstLine = (content) => content.split(/\r?\n/, 1)[0]?.trim() ?? "";
|
|
13542
|
-
var resolveGitPath = (target, base) => target === void 0 || target.length === 0 || target.includes("\0") ? void 0 :
|
|
14981
|
+
var resolveGitPath = (target, base) => target === void 0 || target.length === 0 || target.includes("\0") ? void 0 : path12.resolve(base, target);
|
|
13543
14982
|
var parseGitDirFile = (content, worktreeRoot) => {
|
|
13544
14983
|
const line = firstLine(content);
|
|
13545
14984
|
return resolveGitPath(
|
|
@@ -13559,26 +14998,26 @@ var isMissing = async (filePath) => {
|
|
|
13559
14998
|
};
|
|
13560
14999
|
var isDirectory = async (directory) => {
|
|
13561
15000
|
try {
|
|
13562
|
-
return (await
|
|
15001
|
+
return (await stat5(directory)).isDirectory();
|
|
13563
15002
|
} catch {
|
|
13564
15003
|
return false;
|
|
13565
15004
|
}
|
|
13566
15005
|
};
|
|
13567
15006
|
var repositoryOf = async (worktreeRoot, gitDir) => {
|
|
13568
|
-
const commonDirFile =
|
|
15007
|
+
const commonDirFile = path12.join(gitDir, "commondir");
|
|
13569
15008
|
const content = await readBounded(commonDirFile);
|
|
13570
15009
|
if (content === void 0) {
|
|
13571
15010
|
return await isMissing(commonDirFile) ? { kind: "main", mainRoot: worktreeRoot } : { kind: "linked" };
|
|
13572
15011
|
}
|
|
13573
15012
|
const commonDir = parseCommonDirFile(content, gitDir);
|
|
13574
|
-
const mainRoot = commonDir !== void 0 &&
|
|
15013
|
+
const mainRoot = commonDir !== void 0 && path12.basename(commonDir) === ".git" && await isDirectory(commonDir) ? path12.dirname(commonDir) : void 0;
|
|
13575
15014
|
return { kind: "linked", ...mainRoot === void 0 ? {} : { mainRoot } };
|
|
13576
15015
|
};
|
|
13577
15016
|
var probeDirectory = async (directory) => {
|
|
13578
|
-
const dotGit =
|
|
15017
|
+
const dotGit = path12.join(directory, ".git");
|
|
13579
15018
|
let info;
|
|
13580
15019
|
try {
|
|
13581
|
-
info = await
|
|
15020
|
+
info = await stat5(dotGit);
|
|
13582
15021
|
} catch {
|
|
13583
15022
|
return ABSENT;
|
|
13584
15023
|
}
|
|
@@ -13592,7 +15031,7 @@ var probeDirectory = async (directory) => {
|
|
|
13592
15031
|
if (gitDir === void 0) {
|
|
13593
15032
|
return INVALID;
|
|
13594
15033
|
}
|
|
13595
|
-
const head = await readBounded(
|
|
15034
|
+
const head = await readBounded(path12.join(gitDir, "HEAD"));
|
|
13596
15035
|
if (head === void 0) {
|
|
13597
15036
|
return INVALID;
|
|
13598
15037
|
}
|
|
@@ -13622,10 +15061,10 @@ var createFilesystemWorktreeLocator = (options = {}) => {
|
|
|
13622
15061
|
};
|
|
13623
15062
|
const locate = async (absolutePath) => {
|
|
13624
15063
|
try {
|
|
13625
|
-
if (!
|
|
15064
|
+
if (!path12.isAbsolute(absolutePath) || absolutePath.includes("\0")) {
|
|
13626
15065
|
return void 0;
|
|
13627
15066
|
}
|
|
13628
|
-
let directory =
|
|
15067
|
+
let directory = path12.resolve(absolutePath);
|
|
13629
15068
|
for (let depth = 0; depth < MAX_WORKTREE_WALK_DEPTH; depth += 1) {
|
|
13630
15069
|
const probe = await cachedProbe(directory);
|
|
13631
15070
|
if (probe.kind === "worktree") {
|
|
@@ -13634,7 +15073,7 @@ var createFilesystemWorktreeLocator = (options = {}) => {
|
|
|
13634
15073
|
if (probe.kind === "invalid") {
|
|
13635
15074
|
return void 0;
|
|
13636
15075
|
}
|
|
13637
|
-
const parent =
|
|
15076
|
+
const parent = path12.dirname(directory);
|
|
13638
15077
|
if (parent === directory) {
|
|
13639
15078
|
return void 0;
|
|
13640
15079
|
}
|
|
@@ -13760,6 +15199,7 @@ var createHookRuntime = (options) => {
|
|
|
13760
15199
|
privacy,
|
|
13761
15200
|
logger,
|
|
13762
15201
|
installationId: options.installationId,
|
|
15202
|
+
payloadEnrichers: options.payloadEnrichers ?? (readsClaudeTranscriptUsage(options.config) ? [createClaudeTranscriptUsageEnricher()] : []),
|
|
13763
15203
|
...options.worktreeLocator === null ? {} : {
|
|
13764
15204
|
worktreeLocator: options.worktreeLocator ?? createFilesystemWorktreeLocator({ monotonicMillis: () => clock.monotonicMillis() })
|
|
13765
15205
|
}
|
|
@@ -13767,6 +15207,12 @@ var createHookRuntime = (options) => {
|
|
|
13767
15207
|
const hook = createOtelHook({ ...hookDeps, sink });
|
|
13768
15208
|
const deduplicator = createCallbackDeduplicator({ stateStore, clock });
|
|
13769
15209
|
const usageAccumulator = createUsageAccumulator({ stateStore, clock });
|
|
15210
|
+
const metricSeries = createMetricSeriesStore({ stateStore, clock });
|
|
15211
|
+
const metricsPolicy = effectiveMetricsPolicy(options.config.exporter);
|
|
15212
|
+
const metricDestinations = exportDestinations.destinations.filter(
|
|
15213
|
+
(destination) => destination.metrics.enabled
|
|
15214
|
+
);
|
|
15215
|
+
const metricResource = resourceFromExporterPolicy(options.config.exporter);
|
|
13770
15216
|
const deliveryRetentionMillis = options.deliveryRetentionMillis ?? lifecycleMaxAge;
|
|
13771
15217
|
if (deliveryRetentionMillis < staleClaimMillis) {
|
|
13772
15218
|
logger.warn("delivery retention is shorter than the stale-claim window", {
|
|
@@ -13778,6 +15224,7 @@ var createHookRuntime = (options) => {
|
|
|
13778
15224
|
spanCorrelator,
|
|
13779
15225
|
deduplicator,
|
|
13780
15226
|
usageAccumulator,
|
|
15227
|
+
metricSeries,
|
|
13781
15228
|
spanMaxAgeMillis: lifecycleMaxAge,
|
|
13782
15229
|
dedupMaxAgeMillis: deliveryRetentionMillis,
|
|
13783
15230
|
// The *effective* window, not the requested one: a sweep that considered a
|
|
@@ -13788,6 +15235,86 @@ var createHookRuntime = (options) => {
|
|
|
13788
15235
|
});
|
|
13789
15236
|
const deliveryLock = createAsyncLock();
|
|
13790
15237
|
const stateDiagnostic = (thrown) => errorInfoFromThrown(thrown, { code: "state-store-failure", phase: "state", occurredAt: clock.now() });
|
|
15238
|
+
const generationStartsFor = async (events) => {
|
|
15239
|
+
const needed = events.some(
|
|
15240
|
+
(event3) => event3.type === "generation.end" && event3.durationMillis === void 0 && !events.some(
|
|
15241
|
+
(other) => other.type === "generation.start" && other.generationId === event3.generationId
|
|
15242
|
+
)
|
|
15243
|
+
);
|
|
15244
|
+
if (!needed) {
|
|
15245
|
+
return void 0;
|
|
15246
|
+
}
|
|
15247
|
+
try {
|
|
15248
|
+
const starts = /* @__PURE__ */ new Map();
|
|
15249
|
+
for (const correlation of await correlate(events)) {
|
|
15250
|
+
if (correlation.ref.family !== "generation" || correlation.startMillis === void 0) {
|
|
15251
|
+
continue;
|
|
15252
|
+
}
|
|
15253
|
+
const requestModel = correlation.attributes?.["gen_ai.request.model"];
|
|
15254
|
+
starts.set(correlation.ref.scopeKey, {
|
|
15255
|
+
startMillis: correlation.startMillis,
|
|
15256
|
+
...typeof requestModel === "string" ? { requestModel } : {}
|
|
15257
|
+
});
|
|
15258
|
+
}
|
|
15259
|
+
return (generationId) => starts.get(generationId);
|
|
15260
|
+
} catch {
|
|
15261
|
+
return void 0;
|
|
15262
|
+
}
|
|
15263
|
+
};
|
|
15264
|
+
const recordMetrics = async (ingest, deliveryToken, diagnostics) => {
|
|
15265
|
+
if (metricDestinations.length === 0 || ingest.events.length === 0) {
|
|
15266
|
+
return void 0;
|
|
15267
|
+
}
|
|
15268
|
+
try {
|
|
15269
|
+
for (const event3 of ingest.events) {
|
|
15270
|
+
if (event3.type === "prompt.submitted") {
|
|
15271
|
+
await metricSeries.recordTurnStart(event3.sessionId, event3.occurredAt);
|
|
15272
|
+
}
|
|
15273
|
+
}
|
|
15274
|
+
const generationStarts = await generationStartsFor(ingest.events);
|
|
15275
|
+
const turnStarts = /* @__PURE__ */ new Map();
|
|
15276
|
+
for (const event3 of ingest.events) {
|
|
15277
|
+
if (event3.type === "generation.end" && !turnStarts.has(event3.sessionId)) {
|
|
15278
|
+
turnStarts.set(event3.sessionId, await metricSeries.readTurnStart(event3.sessionId));
|
|
15279
|
+
}
|
|
15280
|
+
}
|
|
15281
|
+
const observations = deriveMetricObservations({
|
|
15282
|
+
events: ingest.events,
|
|
15283
|
+
usage: ingest.usageObservations,
|
|
15284
|
+
resource: metricResource,
|
|
15285
|
+
includeSessionId: metricsPolicy.includeSessionId,
|
|
15286
|
+
...generationStarts === void 0 ? {} : { generationStarts },
|
|
15287
|
+
turnStart: (sessionId) => turnStarts.get(sessionId)
|
|
15288
|
+
});
|
|
15289
|
+
if (observations.length === 0) {
|
|
15290
|
+
return void 0;
|
|
15291
|
+
}
|
|
15292
|
+
const points = metricsPolicy.temporality === "delta" ? aggregateDeltaPoints(observations, clock.now()) : await metricSeries.recordCumulative(observations, {
|
|
15293
|
+
perSession: metricsPolicy.includeSessionId,
|
|
15294
|
+
...deliveryToken === void 0 ? {} : { deliveryToken }
|
|
15295
|
+
});
|
|
15296
|
+
const results = await Promise.all(
|
|
15297
|
+
metricDestinations.map(async (destination) => {
|
|
15298
|
+
const result = await destination.metrics.exportPoints(points).catch(
|
|
15299
|
+
(thrown) => ({
|
|
15300
|
+
accepted: 0,
|
|
15301
|
+
rejected: points.length,
|
|
15302
|
+
errors: [
|
|
15303
|
+
errorInfoFromThrown(thrown, { code: "telemetry-export-failure", phase: "export" })
|
|
15304
|
+
]
|
|
15305
|
+
})
|
|
15306
|
+
);
|
|
15307
|
+
diagnostics.push(...result.errors);
|
|
15308
|
+
return { name: destination.name, accepted: result.accepted, rejected: result.rejected };
|
|
15309
|
+
})
|
|
15310
|
+
);
|
|
15311
|
+
return { points: points.length, destinations: results };
|
|
15312
|
+
} catch (thrown) {
|
|
15313
|
+
diagnostics.push(stateDiagnostic(thrown));
|
|
15314
|
+
logger.warn("hook-derived metrics could not be recorded for this callback", {});
|
|
15315
|
+
return void 0;
|
|
15316
|
+
}
|
|
15317
|
+
};
|
|
13791
15318
|
const rollupDeliveryToken = (identity) => {
|
|
13792
15319
|
const token = ids.newOpaqueId(["usage-delivery", identity.scope, identity.callbackId]).replace(/[^A-Za-z0-9_-]/g, "").slice(0, 128);
|
|
13793
15320
|
return token.length === 0 ? void 0 : token;
|
|
@@ -13908,6 +15435,11 @@ var createHookRuntime = (options) => {
|
|
|
13908
15435
|
identity === void 0 ? void 0 : rollupDeliveryToken(identity)
|
|
13909
15436
|
);
|
|
13910
15437
|
}
|
|
15438
|
+
const metrics = !duplicateDelivery && ingest.identity !== void 0 && isCommittable(ingest.durability) ? await recordMetrics(
|
|
15439
|
+
ingest,
|
|
15440
|
+
identity === void 0 ? void 0 : rollupDeliveryToken(identity),
|
|
15441
|
+
diagnostics
|
|
15442
|
+
) : void 0;
|
|
13911
15443
|
if (owned && identity !== void 0) {
|
|
13912
15444
|
try {
|
|
13913
15445
|
if (isCommittable(ingest.durability)) {
|
|
@@ -13974,6 +15506,7 @@ var createHookRuntime = (options) => {
|
|
|
13974
15506
|
duplicateDelivery,
|
|
13975
15507
|
delivery,
|
|
13976
15508
|
usageRollups,
|
|
15509
|
+
...metrics === void 0 ? {} : { metrics },
|
|
13977
15510
|
...cleanup === void 0 ? {} : { cleanup },
|
|
13978
15511
|
diagnostics
|
|
13979
15512
|
};
|
|
@@ -13990,12 +15523,20 @@ var createHookRuntime = (options) => {
|
|
|
13990
15523
|
() => runProcess(input, identified.identity, report, diagnostics)
|
|
13991
15524
|
);
|
|
13992
15525
|
};
|
|
13993
|
-
const snapshots = () =>
|
|
15526
|
+
const snapshots = () => [
|
|
15527
|
+
...sink.health(),
|
|
15528
|
+
...metricDestinations.map((destination) => destination.metrics.health())
|
|
15529
|
+
];
|
|
13994
15530
|
let shutdownReport;
|
|
13995
15531
|
const shutdown = () => {
|
|
13996
15532
|
shutdownReport ??= (async () => {
|
|
13997
15533
|
const raced = await Promise.race([
|
|
13998
|
-
|
|
15534
|
+
Promise.all([
|
|
15535
|
+
hook.shutdown(),
|
|
15536
|
+
// Metric sinks are not behind the hook's sink: they replay their own
|
|
15537
|
+
// spools here, inside the same bounded window.
|
|
15538
|
+
...metricDestinations.map((destination) => destination.metrics.shutdown().catch(() => void 0))
|
|
15539
|
+
]).then(() => "completed"),
|
|
13999
15540
|
delay3(flushTimeoutMillis)
|
|
14000
15541
|
]);
|
|
14001
15542
|
if (raced === "timeout") {
|
|
@@ -14025,6 +15566,7 @@ var createHookRuntime = (options) => {
|
|
|
14025
15566
|
deduplicator,
|
|
14026
15567
|
usageAccumulator,
|
|
14027
15568
|
spanCorrelator,
|
|
15569
|
+
metricSeries,
|
|
14028
15570
|
janitor,
|
|
14029
15571
|
process: process_,
|
|
14030
15572
|
shutdown,
|
|
@@ -14322,13 +15864,13 @@ var runHookCommand = async (command, io) => {
|
|
|
14322
15864
|
}
|
|
14323
15865
|
const identityClaims = [];
|
|
14324
15866
|
if (command.identity.identityFile !== void 0) {
|
|
14325
|
-
const read = await readIdentityFile(
|
|
15867
|
+
const read = await readIdentityFile(path13.resolve(command.identity.identityFile));
|
|
14326
15868
|
if ("error" in read) {
|
|
14327
15869
|
logDiagnostics(logger, [read.error]);
|
|
14328
15870
|
} else {
|
|
14329
15871
|
const fromFile = claimFromIdentityFile(
|
|
14330
15872
|
read.value,
|
|
14331
|
-
|
|
15873
|
+
path13.basename(command.identity.identityFile)
|
|
14332
15874
|
);
|
|
14333
15875
|
logDiagnostics(logger, fromFile.errors);
|
|
14334
15876
|
identityClaims.push(...fromFile.claims);
|