@rasputin-ai/node 0.15.1 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (38) hide show
  1. package/dist/auto-instrumentation/instrumentation-manifest-registry.d.ts.map +1 -1
  2. package/dist/auto-instrumentation/schedule-instrumentation-manifest-upload.d.ts.map +1 -1
  3. package/dist/create-rasputin-runtime.d.ts +72 -0
  4. package/dist/create-rasputin-runtime.d.ts.map +1 -0
  5. package/dist/execution-metrics/encode-execution-metrics-upload.d.ts.map +1 -1
  6. package/dist/execution-metrics/execution-metrics-collector.d.ts +3 -3
  7. package/dist/execution-metrics/execution-metrics-collector.d.ts.map +1 -1
  8. package/dist/execution-recorder/adaptive-recording-options.d.ts +3 -0
  9. package/dist/execution-recorder/adaptive-recording-options.d.ts.map +1 -1
  10. package/dist/execution-recorder/bind-adaptive-recorder.d.ts +0 -1
  11. package/dist/execution-recorder/bind-adaptive-recorder.d.ts.map +1 -1
  12. package/dist/execution-recorder/execution-journal.d.ts +16 -1
  13. package/dist/execution-recorder/execution-journal.d.ts.map +1 -1
  14. package/dist/execution-recorder/execution-recorder-hooks.d.ts +0 -2
  15. package/dist/execution-recorder/execution-recorder-hooks.d.ts.map +1 -1
  16. package/dist/execution-recorder/execution-recorder-types.d.ts +18 -13
  17. package/dist/execution-recorder/execution-recorder-types.d.ts.map +1 -1
  18. package/dist/execution-recorder/execution-recorder.d.ts.map +1 -1
  19. package/dist/execution-recorder/execution-recording-sync.d.ts +0 -2
  20. package/dist/execution-recorder/execution-recording-sync.d.ts.map +1 -1
  21. package/dist/execution-recorder/runtime-state-size-budget.d.ts +3 -3
  22. package/dist/execution-recorder/runtime-state-size-budget.d.ts.map +1 -1
  23. package/dist/execution-recorder/session-freeze-overrides.d.ts +1 -3
  24. package/dist/execution-recorder/session-freeze-overrides.d.ts.map +1 -1
  25. package/dist/function-metrics/create-metrics-only-runtime.d.ts.map +1 -1
  26. package/dist/function-metrics/function-metrics-collector.d.ts.map +1 -1
  27. package/dist/index.js +885 -429
  28. package/dist/instrument/build.js +211 -355
  29. package/dist/instrument/bun.js +135 -246
  30. package/dist/instrument/node.js +135 -246
  31. package/dist/internal.d.ts +2 -0
  32. package/dist/internal.d.ts.map +1 -1
  33. package/dist/internal.js +990 -357
  34. package/dist/rasputin-init.d.ts +7 -60
  35. package/dist/rasputin-init.d.ts.map +1 -1
  36. package/dist/sdk-meta.d.ts +1 -1
  37. package/dist/sdk-meta.d.ts.map +1 -1
  38. package/package.json +3 -3
package/dist/index.js CHANGED
@@ -1,18 +1,20 @@
1
- // src/rasputin-init.ts
1
+ // src/create-rasputin-runtime.ts
2
2
  import { join } from "node:path";
3
3
  import {
4
4
  copyRedactKeys as copyRedactKeys2,
5
5
  createClient,
6
6
  isClientEnabled,
7
- resolveClientActivation as resolveClientActivation2
7
+ resolveClientActivation as resolveClientActivation2,
8
+ resolveEndpointUrls as resolveEndpointUrls5,
9
+ scheduleAnnounceDeploy
8
10
  } from "@rasputin-ai/core";
9
11
 
10
12
  // src/auto-instrumentation/instrumentation-manifest-registry.ts
11
- import { createHash } from "node:crypto";
12
13
  import { existsSync, readFileSync } from "node:fs";
13
14
  import {
14
15
  INSTRUMENTATION_MANIFEST_SCHEMA_VERSION,
15
- sourceLocatorFromFile as sourceLocatorFromFile2
16
+ sourceLocatorFromFile as sourceLocatorFromFile2,
17
+ sourceLocatorKey
16
18
  } from "@rasputin-ai/core";
17
19
 
18
20
  // ../recorder/src/run-exactly-once.ts
@@ -129,7 +131,7 @@ var getAutomaticRuntimeRegistry = () => {
129
131
  };
130
132
 
131
133
  // src/auto-instrumentation/instrumentation-manifest-registry.ts
132
- var INSTRUMENTATION_MANIFEST_SYMBOL = "rasputin.instrumentation.manifest.v3";
134
+ var INSTRUMENTATION_MANIFEST_SYMBOL = "rasputin.instrumentation.manifest.v4";
133
135
  var registrySymbol = Symbol.for(INSTRUMENTATION_MANIFEST_SYMBOL);
134
136
  var getRegistry = () => {
135
137
  const existing = Reflect.get(globalThis, registrySymbol);
@@ -148,11 +150,16 @@ var getRegistry = () => {
148
150
  Reflect.set(globalThis, registrySymbol, registry);
149
151
  return registry;
150
152
  };
151
- var sourceAt = (filePath, line, column) => {
152
- const source = sourceLocatorFromFile2(filePath);
153
- return source ? { ...source, line, column } : void 0;
153
+ var rememberSource = (sources, source) => {
154
+ const key = sourceLocatorKey(source);
155
+ const previous = sources.get(key);
156
+ sources.set(key, {
157
+ ...previous,
158
+ packageRelativePath: source.packageRelativePath,
159
+ ...source.packageName ? { packageName: source.packageName } : previous?.packageName ? { packageName: previous.packageName } : {},
160
+ ...source.repositoryPath ? { repositoryPath: source.repositoryPath } : previous?.repositoryPath ? { repositoryPath: previous.repositoryPath } : {}
161
+ });
154
162
  };
155
- var stableId = (kind, ...parts) => `${kind}_${createHash("sha256").update(parts.join("\0")).digest("base64url").slice(0, 24)}`;
156
163
  var recordPrebuiltInstrumentationManifest = (manifest) => {
157
164
  const registry = getRegistry();
158
165
  registry.prebuilt = manifest;
@@ -163,7 +170,7 @@ var loadInstrumentationManifestFile = (path) => {
163
170
  try {
164
171
  const parsed = JSON.parse(readFileSync(path, "utf8"));
165
172
  if (parsed.schema_version !== INSTRUMENTATION_MANIFEST_SCHEMA_VERSION) return false;
166
- if (!Array.isArray(parsed.functions)) return false;
173
+ if (!Array.isArray(parsed.sources)) return false;
167
174
  recordPrebuiltInstrumentationManifest(parsed);
168
175
  return true;
169
176
  } catch {
@@ -209,7 +216,7 @@ var instrumentationManifestModuleCount = () => {
209
216
  const registry = getRegistry();
210
217
  if (registry.files.size > 0) return registry.files.size;
211
218
  if (!registry.prebuilt) return 0;
212
- return new Set(registry.prebuilt.functions.map((fn) => fn.source.packageRelativePath)).size;
219
+ return registry.prebuilt.sources.length;
213
220
  };
214
221
  var snapshotOptionsKey = (options) => JSON.stringify({
215
222
  sourceRoot: options.sourceRoot ?? "",
@@ -221,12 +228,8 @@ var snapshotInstrumentationManifest = (options = {}) => {
221
228
  if (registry.snapshotCache && registry.snapshotCache.generation === registry.generation && registry.snapshotCache.optionsKey === optionsKey) {
222
229
  return registry.snapshotCache.manifest;
223
230
  }
224
- const functions = new Map(
225
- registry.prebuilt?.functions.map((fn) => [fn.functionId, fn])
226
- );
227
- const callSites = new Map(
228
- registry.prebuilt?.callSites.map((site) => [site.id, site])
229
- );
231
+ const sources = /* @__PURE__ */ new Map();
232
+ for (const source of registry.prebuilt?.sources ?? []) rememberSource(sources, source);
230
233
  const remember = (manifest) => {
231
234
  registry.snapshotCache = {
232
235
  generation: registry.generation,
@@ -235,53 +238,21 @@ var snapshotInstrumentationManifest = (options = {}) => {
235
238
  };
236
239
  return manifest;
237
240
  };
238
- for (const delta of registry.files.values()) {
241
+ for (const [filePath, delta] of registry.files) {
242
+ let recorded = false;
239
243
  for (const fn of delta.functions) {
240
244
  const definition = definitionFromEncodedPlan(fn.plan);
241
245
  if (!definition.source) continue;
242
- if (!fn.metricsDeclaration) {
243
- throw new Error(`Missing function metrics declaration: ${fn.functionId}`);
244
- }
245
- functions.set(definition.functionId, {
246
- ...functions.get(definition.functionId),
247
- functionId: definition.functionId,
248
- source: {
249
- packageRelativePath: definition.source.packageRelativePath,
250
- ...definition.source.packageName ? { packageName: definition.source.packageName } : {},
251
- ...definition.source.repositoryPath ? { repositoryPath: definition.source.repositoryPath } : {}
252
- },
253
- name: fn.name,
254
- startLine: fn.startLine,
255
- startColumn: fn.startColumn,
256
- endLine: fn.endLine,
257
- endColumn: fn.endColumn,
258
- metricsDeclaration: fn.metricsDeclaration,
259
- ...fn.instrumented === false ? { instrumented: false, skipReason: fn.skipReason } : {}
260
- });
261
- }
262
- for (const site of delta.callSites) {
263
- const source = sourceAt(site.filePath, site.line, site.column);
264
- if (!source) continue;
265
- const id = stableId(
266
- "cs",
267
- site.callerFunctionId,
268
- source.packageName ?? "",
269
- source.packageRelativePath,
270
- site.line,
271
- site.column
272
- );
273
- callSites.set(id, {
274
- id,
275
- callerFunctionId: site.callerFunctionId,
276
- calleeName: site.calleeName,
277
- calleeText: site.calleeText,
278
- line: site.line,
279
- column: site.column,
280
- endLine: site.endLine,
281
- endColumn: site.endColumn,
282
- resultBinding: site.resultBinding
246
+ rememberSource(sources, {
247
+ packageRelativePath: definition.source.packageRelativePath,
248
+ ...definition.source.packageName ? { packageName: definition.source.packageName } : {},
249
+ ...definition.source.repositoryPath ? { repositoryPath: definition.source.repositoryPath } : {}
283
250
  });
251
+ recorded = true;
284
252
  }
253
+ if (recorded) continue;
254
+ const locator = sourceLocatorFromFile2(filePath);
255
+ if (locator) rememberSource(sources, locator);
285
256
  }
286
257
  if (registry.prebuilt && registry.files.size === 0) {
287
258
  if (!options.sourceRoot && !options.sourceRoots) return remember(registry.prebuilt);
@@ -293,9 +264,7 @@ var snapshotInstrumentationManifest = (options = {}) => {
293
264
  }
294
265
  });
295
266
  }
296
- if (functions.size === 0 && callSites.size === 0) {
297
- return remember(void 0);
298
- }
267
+ if (sources.size === 0) return remember(void 0);
299
268
  const packages = { ...registry.prebuilt?.sourceRoots?.packages, ...options.sourceRoots };
300
269
  const sourceRoot = options.sourceRoot ?? registry.prebuilt?.sourceRoots?.default;
301
270
  return remember({
@@ -306,8 +275,7 @@ var snapshotInstrumentationManifest = (options = {}) => {
306
275
  packages
307
276
  }
308
277
  } : {},
309
- functions: [...functions.values()],
310
- callSites: [...callSites.values()]
278
+ sources: [...sources.values()]
311
279
  });
312
280
  };
313
281
  var collectParamsByFunctionId = () => {
@@ -500,17 +468,21 @@ var scheduleInstrumentationManifestUpload = (options) => {
500
468
  const maxAttempts = 5;
501
469
  const packageNamesOf = (manifest) => [
502
470
  ...new Set(
503
- manifest.functions.map((fn) => fn.source.packageName).filter((name) => Boolean(name))
471
+ manifest.sources.map((source) => source.packageName).filter((name) => Boolean(name))
504
472
  )
505
473
  ].sort();
506
474
  const report = (manifest, uploaded, next) => {
507
475
  const coverage = instrumentationCoverageStats();
476
+ const skippedFunctions = Object.values(coverage.skippedByReason).reduce(
477
+ (total, count) => total + count,
478
+ 0
479
+ );
508
480
  return formatConfigurationReport({
509
481
  release,
510
482
  runtime: runtimeLabel(),
511
483
  modules: instrumentationManifestModuleCount(),
512
- functions: manifest.functions.filter((fn) => fn.instrumented !== false).length,
513
- skippedFunctions: manifest.functions.filter((fn) => fn.instrumented === false).length,
484
+ functions: coverage.instrumented,
485
+ skippedFunctions,
514
486
  instrumentedAsync: coverage.instrumentedAsync,
515
487
  skippedByReason: coverage.skippedByReason,
516
488
  packageNames: packageNamesOf(manifest),
@@ -942,6 +914,18 @@ var createExecutionMetricsCollector = (options) => {
942
914
  executionHandleByKey.set(key, handle);
943
915
  return handle;
944
916
  };
917
+ const newSeries = () => ({
918
+ started: 0,
919
+ completed: 0,
920
+ failed: 0,
921
+ sampleCount: 0,
922
+ sampleSumUs: 0,
923
+ sampleMinUs: null,
924
+ sampleMaxUs: null,
925
+ invalidTiming: 0,
926
+ histogram: new Uint32Array(FUNCTION_METRICS_HISTOGRAM_BUCKET_COUNT),
927
+ bytes: SERIES_BYTES + HISTOGRAM_BYTES
928
+ });
945
929
  const ensureSeries = (minute, executionHandle) => {
946
930
  let byExecution = active.get(minute);
947
931
  if (!byExecution) {
@@ -955,18 +939,7 @@ var createExecutionMetricsCollector = (options) => {
955
939
  return void 0;
956
940
  }
957
941
  if (!reserve(SERIES_BYTES + HISTOGRAM_BYTES)) return void 0;
958
- const series = {
959
- started: 0,
960
- completed: 0,
961
- failed: 0,
962
- sampleCount: 0,
963
- sampleSumUs: 0,
964
- sampleMinUs: null,
965
- sampleMaxUs: null,
966
- invalidTiming: 0,
967
- histogram: new Uint32Array(FUNCTION_METRICS_HISTOGRAM_BUCKET_COUNT),
968
- bytes: SERIES_BYTES + HISTOGRAM_BYTES
969
- };
942
+ const series = newSeries();
970
943
  byExecution.set(executionHandle, series);
971
944
  activeSeries += 1;
972
945
  return series;
@@ -987,11 +960,22 @@ var createExecutionMetricsCollector = (options) => {
987
960
  note(coverage, "dropped_queue_budget", discardedMarks(dropped.series));
988
961
  }
989
962
  };
963
+ const markedSeries = (table) => {
964
+ const marked = /* @__PURE__ */ new Map();
965
+ for (const [executionHandle, series] of table) {
966
+ if (seriesHasMarks(series)) marked.set(executionHandle, series);
967
+ }
968
+ return marked;
969
+ };
990
970
  const closeMinute = (minute, table) => {
991
971
  active.delete(minute);
992
972
  activeSeries -= countSeries(table);
993
973
  if (minute > lastClosedMinute) lastClosedMinute = minute;
994
- appendQueue({ minute, series: table, bytes: tableBytes(table) });
974
+ const marked = markedSeries(table);
975
+ const markedBytes = tableBytes(marked);
976
+ stateBytes -= tableBytes(table) - markedBytes;
977
+ if (stateBytes < 0) stateBytes = 0;
978
+ appendQueue({ minute, series: marked, bytes: markedBytes });
995
979
  };
996
980
  const rotate = (currentMinute2) => {
997
981
  for (const minute of [...active.keys()]) {
@@ -1031,6 +1015,63 @@ var createExecutionMetricsCollector = (options) => {
1031
1015
  }
1032
1016
  return minute;
1033
1017
  };
1018
+ const bumpStarted = (series) => {
1019
+ const started = series.started + 1;
1020
+ if (!Number.isSafeInteger(started)) {
1021
+ note(coverage, "dropped_unexportable");
1022
+ return false;
1023
+ }
1024
+ series.started = started;
1025
+ return true;
1026
+ };
1027
+ const incrementStarted = (minute, handle) => {
1028
+ if (sealed) {
1029
+ note(coverage, "dropped_unexportable");
1030
+ return false;
1031
+ }
1032
+ const current = Math.floor(clock.wallTimeMs() / FUNCTION_METRICS_MINUTE_MS);
1033
+ rotateIfNeeded(current);
1034
+ if (minute > current) {
1035
+ note(coverage, "dropped_late_completion");
1036
+ return false;
1037
+ }
1038
+ if (minute === current || active.has(minute)) {
1039
+ const series2 = ensureSeries(minute, handle);
1040
+ if (!series2) return false;
1041
+ return bumpStarted(series2);
1042
+ }
1043
+ for (const entry of queue) {
1044
+ if (entry.minute !== minute) continue;
1045
+ let series2 = entry.series.get(handle);
1046
+ if (!series2) {
1047
+ if (!reserve(SERIES_BYTES + HISTOGRAM_BYTES)) return false;
1048
+ series2 = newSeries();
1049
+ entry.series.set(handle, series2);
1050
+ entry.bytes += series2.bytes;
1051
+ }
1052
+ return bumpStarted(series2);
1053
+ }
1054
+ if (!reserve(SERIES_BYTES + HISTOGRAM_BYTES)) return false;
1055
+ const series = newSeries();
1056
+ if (!bumpStarted(series)) {
1057
+ stateBytes -= series.bytes;
1058
+ if (stateBytes < 0) stateBytes = 0;
1059
+ return false;
1060
+ }
1061
+ appendQueue({ minute, series: /* @__PURE__ */ new Map([[handle, series]]), bytes: series.bytes });
1062
+ return true;
1063
+ };
1064
+ const rememberStart = (state, key) => {
1065
+ if (state.started) return;
1066
+ if (!key || !isCanonicalFunctionMetricsExecutionKey(key)) return;
1067
+ const handle = internExecutionKey(key);
1068
+ if (handle === void 0) return;
1069
+ if (incrementStarted(state.startedMinute, handle)) state.started = true;
1070
+ };
1071
+ const bindIdentity = (state, key) => {
1072
+ if (state.finished || state.started) return;
1073
+ rememberStart(state, key);
1074
+ };
1034
1075
  const rememberSample = (series, durationUs, bucket) => {
1035
1076
  const sampleCount = series.sampleCount + 1;
1036
1077
  const sampleSumUs = series.sampleSumUs + durationUs;
@@ -1046,46 +1087,19 @@ var createExecutionMetricsCollector = (options) => {
1046
1087
  series.sampleMaxUs = series.sampleMaxUs === null ? durationUs : Math.max(series.sampleMaxUs, durationUs);
1047
1088
  return true;
1048
1089
  };
1049
- const rememberStart = (handle) => {
1050
- const minute = currentMinute(false);
1051
- if (minute === void 0) return false;
1052
- const series = ensureSeries(minute, handle);
1053
- if (!series) return false;
1054
- const started = series.started + 1;
1055
- if (!Number.isSafeInteger(started)) {
1056
- note(coverage, "dropped_unexportable");
1057
- return false;
1058
- }
1059
- series.started = started;
1060
- return true;
1061
- };
1062
- const bindIdentity = (state, key) => {
1063
- if (state.finished || state.dropped || state.handle !== void 0) return;
1064
- if (!key) return;
1065
- const handle = internExecutionKey(key);
1066
- if (handle === void 0) {
1067
- state.dropped = true;
1068
- return;
1069
- }
1070
- state.handle = handle;
1071
- if (state.started) return;
1072
- if (rememberStart(handle)) state.started = true;
1073
- };
1074
1090
  const finishExecution = (state, input) => {
1075
1091
  if (state.finished) return;
1076
1092
  state.finished = true;
1077
- if (state.dropped) return;
1078
- if (state.handle === void 0) {
1093
+ if (!input.key || !isCanonicalFunctionMetricsExecutionKey(input.key)) {
1079
1094
  note(coverage, "skipped_unresolved_execution_type");
1080
1095
  return;
1081
1096
  }
1082
- if (!state.started) {
1083
- if (!rememberStart(state.handle)) return;
1084
- state.started = true;
1085
- }
1086
- const minute = currentMinute(true);
1097
+ const handle = internExecutionKey(input.key);
1098
+ if (handle === void 0) return;
1099
+ rememberStart(state, input.key);
1100
+ const minute = currentMinute(false);
1087
1101
  if (minute === void 0) return;
1088
- const series = ensureSeries(minute, state.handle);
1102
+ const series = ensureSeries(minute, handle);
1089
1103
  if (!series) return;
1090
1104
  const completed = series.completed + 1;
1091
1105
  const failed = series.failed + (input.failed ? 1 : 0);
@@ -1151,10 +1165,9 @@ var createExecutionMetricsCollector = (options) => {
1151
1165
  };
1152
1166
  return {
1153
1167
  createState: () => ({
1154
- handle: void 0,
1155
- started: false,
1156
1168
  finished: false,
1157
- dropped: false
1169
+ started: false,
1170
+ startedMinute: Math.floor(clock.wallTimeMs() / FUNCTION_METRICS_MINUTE_MS)
1158
1171
  }),
1159
1172
  bindIdentity,
1160
1173
  finishExecution,
@@ -1263,15 +1276,39 @@ var minuteMarks = (minute) => {
1263
1276
  const next = minute.started_executions + minute.completed_executions;
1264
1277
  return Number.isSafeInteger(next) ? next : Number.MAX_SAFE_INTEGER;
1265
1278
  };
1279
+ var bucketExpiresAtMs = (bucketStart3) => {
1280
+ const bucket = parseFunctionMetricsBucketStart(bucketStart3);
1281
+ if (bucket === void 0) return void 0;
1282
+ return bucket + FUNCTION_METRICS_MINUTE_MS2 + FUNCTION_METRICS_BUCKET_LATENESS_MS;
1283
+ };
1266
1284
  var expiresAtMsFor = (batch, nowMs) => {
1267
- let oldest;
1285
+ let earliest;
1268
1286
  for (const start of batch.coverage.covered_bucket_starts) {
1269
- const bucket = parseFunctionMetricsBucketStart(start);
1270
- if (bucket === void 0) continue;
1271
- if (oldest === void 0 || bucket < oldest) oldest = bucket;
1287
+ const expires = bucketExpiresAtMs(start);
1288
+ if (expires === void 0) continue;
1289
+ if (earliest === void 0 || expires < earliest) earliest = expires;
1290
+ }
1291
+ if (earliest === void 0) return nowMs + FUNCTION_METRICS_BUCKET_LATENESS_MS;
1292
+ return earliest;
1293
+ };
1294
+ var minuteAlreadyExpired = (minute, nowMs) => {
1295
+ const expires = bucketExpiresAtMs(minute.bucket_start);
1296
+ return expires !== void 0 && expires <= nowMs;
1297
+ };
1298
+ var hasCoverageLoss = (coverage) => Object.entries(coverage).some(
1299
+ ([key, value]) => key !== "covered_bucket_starts" && typeof value === "number" && value > 0
1300
+ );
1301
+ var liveMinutesOf = (batch, nowMs) => {
1302
+ const live = [];
1303
+ let droppedLate = 0;
1304
+ for (const minute of batch.minutes) {
1305
+ if (minuteAlreadyExpired(minute, nowMs)) {
1306
+ droppedLate += minuteMarks(minute);
1307
+ continue;
1308
+ }
1309
+ live.push(minute);
1272
1310
  }
1273
- if (oldest === void 0) return nowMs + FUNCTION_METRICS_BUCKET_LATENESS_MS;
1274
- return oldest + FUNCTION_METRICS_MINUTE_MS2 + FUNCTION_METRICS_BUCKET_LATENESS_MS;
1311
+ return { live, droppedLate };
1275
1312
  };
1276
1313
  var zeroLossCoverage = (coverage) => ({
1277
1314
  ...coverage,
@@ -1311,7 +1348,8 @@ var withLoss = (batch, loss) => ({
1311
1348
  coverage: {
1312
1349
  ...batch.coverage,
1313
1350
  dropped_unexportable: batch.coverage.dropped_unexportable + loss.dropped_unexportable,
1314
- dropped_queue_budget: batch.coverage.dropped_queue_budget + loss.dropped_queue_budget
1351
+ dropped_queue_budget: batch.coverage.dropped_queue_budget + loss.dropped_queue_budget,
1352
+ dropped_late_completion: batch.coverage.dropped_late_completion + loss.dropped_late_completion
1315
1353
  }
1316
1354
  });
1317
1355
  var encodeOne = async (batch, nowMs, signal) => {
@@ -1354,11 +1392,30 @@ var encodeExecutionMetricsUploads = async (batches, input) => {
1354
1392
  const uploads = [];
1355
1393
  let extra = {
1356
1394
  dropped_unexportable: 0,
1357
- dropped_queue_budget: input.queueDrops ?? 0
1395
+ dropped_queue_budget: input.queueDrops ?? 0,
1396
+ dropped_late_completion: 0
1358
1397
  };
1359
1398
  for (const batch of batches) {
1360
- const fitted = await encodeFitting(withLoss(batch, extra), input.nowMs, input.signal);
1361
- extra = { dropped_unexportable: fitted.droppedUnexportable, dropped_queue_budget: 0 };
1399
+ const { live, droppedLate } = liveMinutesOf(batch, input.nowMs);
1400
+ const loss = {
1401
+ dropped_unexportable: extra.dropped_unexportable,
1402
+ dropped_queue_budget: extra.dropped_queue_budget,
1403
+ dropped_late_completion: extra.dropped_late_completion + droppedLate
1404
+ };
1405
+ const lost = withLoss(batch, loss);
1406
+ const prepared = live.length === batch.minutes.length ? lost : projectMinutes(batch, live, lost.coverage, batch.batch_id);
1407
+ extra = {
1408
+ dropped_unexportable: 0,
1409
+ dropped_queue_budget: 0,
1410
+ dropped_late_completion: 0
1411
+ };
1412
+ if (prepared.minutes.length === 0 && !hasCoverageLoss(prepared.coverage)) continue;
1413
+ const fitted = await encodeFitting(prepared, input.nowMs, input.signal);
1414
+ extra = {
1415
+ dropped_unexportable: fitted.droppedUnexportable,
1416
+ dropped_queue_budget: 0,
1417
+ dropped_late_completion: 0
1418
+ };
1362
1419
  uploads.push(...fitted.uploads);
1363
1420
  }
1364
1421
  return uploads;
@@ -1937,13 +1994,13 @@ var definitionOf = (input) => {
1937
1994
  return { name: input, functionId: runtimeFunctionId2({ name: input }) };
1938
1995
  return input;
1939
1996
  };
1940
- var bindExecutionHandle = (collector, store) => {
1941
- if (!collector) return;
1942
- store.executionHandle = collector.internExecutionKey(executionTypeKey(store.execution));
1943
- };
1944
- var bindExecutionMetricsIdentity = (collector, store) => {
1945
- if (!collector || !store.executionMetrics) return;
1946
- collector.bindIdentity(store.executionMetrics, executionTypeKey(store.execution));
1997
+ var ensureExecutionHandle = (collector, store) => {
1998
+ if (!collector || !store) return void 0;
1999
+ const key = executionTypeKey(store.execution);
2000
+ if (store.executionKey === key) return store.executionHandle;
2001
+ store.executionKey = key;
2002
+ store.executionHandle = collector.internExecutionKey(key);
2003
+ return store.executionHandle;
1947
2004
  };
1948
2005
  var settleStarted = (collector, functionHandle, executionHandle, started, value, failed, endedNs) => {
1949
2006
  if (!started || functionHandle === void 0 || executionHandle === void 0) return;
@@ -1964,7 +2021,8 @@ var runWithMetrics = (collector, durationSampler, plan, store, callback) => {
1964
2021
  });
1965
2022
  const startedNs = duration.measure ? tryCallClock2() : void 0;
1966
2023
  const functionHandle = internPreparedMetrics(collector, plan);
1967
- const started = startMetricsCall(collector, functionHandle, store?.executionHandle, {
2024
+ const executionHandle = functionHandle !== void 0 ? ensureExecutionHandle(collector, store) : void 0;
2025
+ const started = startMetricsCall(collector, functionHandle, executionHandle, {
1968
2026
  measure: duration.selected,
1969
2027
  ...duration.selected ? { startedNs } : {}
1970
2028
  });
@@ -1974,7 +2032,7 @@ var runWithMetrics = (collector, durationSampler, plan, store, callback) => {
1974
2032
  settleStarted(
1975
2033
  collector,
1976
2034
  functionHandle,
1977
- store?.executionHandle,
2035
+ executionHandle,
1978
2036
  started,
1979
2037
  result,
1980
2038
  false,
@@ -1985,7 +2043,7 @@ var runWithMetrics = (collector, durationSampler, plan, store, callback) => {
1985
2043
  settleStarted(
1986
2044
  collector,
1987
2045
  functionHandle,
1988
- store?.executionHandle,
2046
+ executionHandle,
1989
2047
  started,
1990
2048
  error,
1991
2049
  true,
@@ -2007,14 +2065,14 @@ var metricsHandle = (collector, durationSampler, plan, store) => {
2007
2065
  });
2008
2066
  const startedNs = duration.measure ? tryCallClock2() : void 0;
2009
2067
  const functionHandle = internPreparedMetrics(collector, plan);
2010
- const started = startMetricsCall(collector, functionHandle, store?.executionHandle, {
2068
+ const executionHandle = functionHandle !== void 0 ? ensureExecutionHandle(collector, store) : void 0;
2069
+ const started = startMetricsCall(collector, functionHandle, executionHandle, {
2011
2070
  measure: duration.selected,
2012
2071
  ...duration.selected ? { startedNs } : {}
2013
2072
  });
2014
- if (!started || functionHandle === void 0 || store?.executionHandle === void 0) {
2073
+ if (!started || functionHandle === void 0 || executionHandle === void 0 || !store) {
2015
2074
  return passthroughHandle();
2016
2075
  }
2017
- const executionHandle = store.executionHandle;
2018
2076
  let failed = false;
2019
2077
  let settled = false;
2020
2078
  let previousFunctionId = store.currentFunctionId;
@@ -2106,18 +2164,21 @@ var createMetricsOnlyRuntime = (input) => {
2106
2164
  return runPrepared(plan, args, () => fn.apply(this, args));
2107
2165
  };
2108
2166
  }
2167
+ const bindNamedExecutionMetrics = (store) => {
2168
+ if (!executionMetrics || !store.executionMetrics) return;
2169
+ if (store.execution.kind === "http") return;
2170
+ executionMetrics.bindIdentity(store.executionMetrics, executionTypeKey(store.execution));
2171
+ };
2109
2172
  const finishScope = (store, next) => {
2110
2173
  if (next) {
2111
2174
  mergeMetadata(store, next);
2112
- bindExecutionHandle(collector, store);
2113
- bindExecutionMetricsIdentity(executionMetrics, store);
2114
2175
  }
2115
2176
  if (!executionMetrics || !store.executionMetrics) return;
2116
2177
  if (store.executionMetrics.finished) return;
2117
2178
  const endedNs = tryCallClock2();
2118
2179
  const executionKey = executionTypeKey(store.execution);
2119
- bindExecutionMetricsIdentity(executionMetrics, store);
2120
2180
  executionMetrics.finishExecution(store.executionMetrics, {
2181
+ key: executionKey,
2121
2182
  failed: executionOutcomeFailed({
2122
2183
  hasError: store.hasError,
2123
2184
  runFailed: store.runFailed,
@@ -2140,10 +2201,9 @@ var createMetricsOnlyRuntime = (input) => {
2140
2201
  hasError: false,
2141
2202
  runFailed: false
2142
2203
  };
2143
- bindExecutionHandle(collector, store);
2144
2204
  if (executionMetrics) {
2145
2205
  store.executionMetrics = executionMetrics.createState();
2146
- bindExecutionMetricsIdentity(executionMetrics, store);
2206
+ bindNamedExecutionMetrics(store);
2147
2207
  }
2148
2208
  return {
2149
2209
  run: (callback) => metricsStorage.run(store, () => {
@@ -2162,8 +2222,9 @@ var createMetricsOnlyRuntime = (input) => {
2162
2222
  finish: (next) => finishScope(store, next),
2163
2223
  mergeMetadata: (next) => {
2164
2224
  mergeMetadata(store, next);
2165
- bindExecutionHandle(collector, store);
2166
- bindExecutionMetricsIdentity(executionMetrics, store);
2225
+ bindNamedExecutionMetrics(store);
2226
+ },
2227
+ captureInput: () => {
2167
2228
  }
2168
2229
  };
2169
2230
  },
@@ -2185,9 +2246,12 @@ var createMetricsOnlyRuntime = (input) => {
2185
2246
  };
2186
2247
 
2187
2248
  // src/execution-recorder/adaptive-recording-options.ts
2188
- var DEFAULT_FULL_CAPTURE_DURATION_MS = 24 * 60 * 60 * 1e3;
2249
+ var DEFAULT_FULL_CAPTURE_DURATION_MS = 60 * 60 * 1e3;
2189
2250
  var MIN_FULL_CAPTURE_DURATION_MS = 1e3;
2190
2251
  var MAX_FULL_CAPTURE_DURATION_MS = 7 * 24 * 60 * 60 * 1e3;
2252
+ var resolveExecutionRecordingMode = (options) => {
2253
+ return options?.alwaysCaptureValues === true ? "full" : "adaptive";
2254
+ };
2191
2255
  var sanitizeFullCaptureDurationMs = (value) => {
2192
2256
  if (typeof value !== "number" || !Number.isFinite(value)) {
2193
2257
  return DEFAULT_FULL_CAPTURE_DURATION_MS;
@@ -2204,6 +2268,45 @@ var KIND_EXIT = 2;
2204
2268
  var KIND_THROW = 3;
2205
2269
  var KIND_SUPPRESSED = 4;
2206
2270
  var ARGS_OMITTED = Symbol("rasputin.argsOmitted");
2271
+ var SESSION_CAPTURE_ID = "__rasputin_session_capture";
2272
+ var ORDINARY_VALUE = "__rasputin_ordinary_value";
2273
+ var tagSessionCapture = (sessionId, value) => ({
2274
+ [SESSION_CAPTURE_ID]: sessionId,
2275
+ value
2276
+ });
2277
+ var tagOrdinaryAndSessionCapture = (sessionId, sessionValue, ordinaryValue) => ({
2278
+ [SESSION_CAPTURE_ID]: sessionId,
2279
+ [ORDINARY_VALUE]: ordinaryValue,
2280
+ value: sessionValue
2281
+ });
2282
+ var sessionCaptureOf = (payload) => {
2283
+ if (typeof payload !== "object" || payload === null) return void 0;
2284
+ if (!Object.hasOwn(payload, SESSION_CAPTURE_ID)) return void 0;
2285
+ const sessionId = Object.getOwnPropertyDescriptor(payload, SESSION_CAPTURE_ID)?.value;
2286
+ if (typeof sessionId !== "string") return void 0;
2287
+ return {
2288
+ sessionId,
2289
+ value: Object.getOwnPropertyDescriptor(payload, "value")?.value
2290
+ };
2291
+ };
2292
+ var unpackCapture = (payload) => {
2293
+ const tagged = sessionCaptureOf(payload);
2294
+ if (!tagged) return { ordinaryPresent: true, ordinary: payload };
2295
+ if (typeof payload !== "object" || payload === null || !Object.hasOwn(payload, ORDINARY_VALUE)) {
2296
+ return {
2297
+ ordinaryPresent: false,
2298
+ ordinary: ARGS_OMITTED,
2299
+ sessionId: tagged.sessionId,
2300
+ sessionValue: tagged.value
2301
+ };
2302
+ }
2303
+ return {
2304
+ ordinaryPresent: true,
2305
+ ordinary: Object.getOwnPropertyDescriptor(payload, ORDINARY_VALUE)?.value,
2306
+ sessionId: tagged.sessionId,
2307
+ sessionValue: tagged.value
2308
+ };
2309
+ };
2207
2310
  var NO_PARENT = 4294967295;
2208
2311
  var NO_SUPPRESSION = 4294967295;
2209
2312
  var TIMING_UNAVAILABLE = -1n;
@@ -2406,19 +2509,24 @@ var ExecutionJournal = class {
2406
2509
  const functionId = plansByRuntimeId[this.planId[index] ?? 0]?.functionId;
2407
2510
  if (!functionId) return void 0;
2408
2511
  const parentCallId = this.parentCallId[index] ?? NO_PARENT;
2409
- const payload = this.payloads[index];
2512
+ const unpacked = unpackCapture(this.payloads[index]);
2513
+ const inner = unpacked.ordinaryPresent ? unpacked.ordinary : ARGS_OMITTED;
2410
2514
  const timestampMs = measuredRelativeMs(this.timestampNs[index] ?? TIMING_UNAVAILABLE);
2411
2515
  return {
2412
2516
  type: "function_enter",
2413
2517
  callId: this.callId[index] ?? 0,
2414
2518
  functionId,
2415
2519
  ...timestampMs === void 0 ? {} : { timestampMs },
2416
- ...payload === ARGS_OMITTED ? { argsOmitted: true } : { args: Array.isArray(payload) ? payload : [] },
2417
- ...parentCallId === NO_PARENT ? {} : { parentCallId }
2520
+ ...inner === ARGS_OMITTED ? { argsOmitted: true } : { args: Array.isArray(inner) ? inner : [] },
2521
+ ...parentCallId === NO_PARENT ? {} : { parentCallId },
2522
+ ...unpacked.ordinaryPresent && unpacked.sessionId ? { ordinaryCapture: true } : {},
2523
+ ...unpacked.sessionId ? { sessionCaptureId: unpacked.sessionId } : {},
2524
+ ...unpacked.sessionId && unpacked.sessionValue !== ARGS_OMITTED ? { sessionArgs: Array.isArray(unpacked.sessionValue) ? unpacked.sessionValue : [] } : {}
2418
2525
  };
2419
2526
  }
2420
2527
  if (kind === KIND_EXIT) {
2421
- const payload = this.payloads[index];
2528
+ const unpacked = unpackCapture(this.payloads[index]);
2529
+ const inner = unpacked.ordinaryPresent ? unpacked.ordinary : ARGS_OMITTED;
2422
2530
  const timestampMs = measuredRelativeMs(this.timestampNs[index] ?? TIMING_UNAVAILABLE);
2423
2531
  const durationMs = measuredRelativeMs(this.durationNs[index] ?? TIMING_UNAVAILABLE);
2424
2532
  return {
@@ -2426,7 +2534,10 @@ var ExecutionJournal = class {
2426
2534
  callId: this.callId[index] ?? 0,
2427
2535
  ...timestampMs === void 0 ? {} : { timestampMs },
2428
2536
  ...durationMs === void 0 ? {} : { durationMs },
2429
- ...payload === ARGS_OMITTED ? {} : { returnValue: payload }
2537
+ ...inner === ARGS_OMITTED ? {} : { returnValue: inner },
2538
+ ...unpacked.ordinaryPresent && unpacked.sessionId ? { ordinaryCapture: true } : {},
2539
+ ...unpacked.sessionId ? { sessionCaptureId: unpacked.sessionId } : {},
2540
+ ...unpacked.sessionId && unpacked.sessionValue !== ARGS_OMITTED ? { sessionReturnValue: unpacked.sessionValue } : {}
2430
2541
  };
2431
2542
  }
2432
2543
  if (kind === KIND_THROW) {
@@ -2933,6 +3044,13 @@ var enforceRuntimeStateSizeBudget = (input) => {
2933
3044
  withSizeMetadata({ ...state, captureProfile, events: stripped.events }, size)
2934
3045
  );
2935
3046
  if (encodedBytes(state) <= MAX_RUNTIME_STATE_BYTES) return state;
3047
+ if ("input" in state) {
3048
+ size.eventValuesDropped += 1;
3049
+ state = settleFinalBytes(
3050
+ withSizeMetadata({ ...state, input: rasputinUnavailable(VALUE_OMITTED_REASON) }, size)
3051
+ );
3052
+ if (encodedBytes(state) <= MAX_RUNTIME_STATE_BYTES) return state;
3053
+ }
2936
3054
  size.eventsDropped += state.events.length;
2937
3055
  size.functionDefinitionsDropped += state.functions.length;
2938
3056
  state = settleFinalBytes(
@@ -4188,6 +4306,8 @@ var noOpExecution = {
4188
4306
  finish: () => {
4189
4307
  },
4190
4308
  mergeMetadata: () => {
4309
+ },
4310
+ captureInput: () => {
4191
4311
  }
4192
4312
  }),
4193
4313
  getErrorState: () => void 0,
@@ -4250,24 +4370,17 @@ var createExecutionRecorder = (options, hooks = {}) => {
4250
4370
  const functionMetrics = hooks.functionMetrics;
4251
4371
  const executionMetrics = hooks.executionMetrics;
4252
4372
  const durationSampler = hooks.durationSampler;
4253
- const bindMetricsExecution = (recording) => {
4254
- if (!functionMetrics) return;
4255
- recording.metricsExecutionHandle = functionMetrics.internExecutionKey(
4256
- executionTypeKey(recording.execution)
4257
- );
4258
- };
4259
- const bindExecutionMetricsIdentity2 = (recording) => {
4260
- if (!executionMetrics || !recording.executionMetrics) return;
4261
- executionMetrics.bindIdentity(
4262
- recording.executionMetrics,
4263
- executionTypeKey(recording.execution)
4264
- );
4373
+ const metricsExecutionHandleFor = (recording) => {
4374
+ if (!functionMetrics) return void 0;
4375
+ const key = executionTypeKey(recording.execution);
4376
+ if (recording.metricsExecutionKey === key) return recording.metricsExecutionHandle;
4377
+ recording.metricsExecutionKey = key;
4378
+ recording.metricsExecutionHandle = functionMetrics.internExecutionKey(key);
4379
+ return recording.metricsExecutionHandle;
4265
4380
  };
4266
4381
  warnIfMissingAsyncContextFrame();
4267
- const adaptiveEnabled = options.adaptive?.enabled === true;
4268
- const fullCaptureDurationMs = sanitizeFullCaptureDurationMs(
4269
- options.adaptive?.fullCaptureDurationMs
4270
- );
4382
+ const adaptiveEnabled = resolveExecutionRecordingMode(options) === "adaptive";
4383
+ const fullCaptureDurationMs = sanitizeFullCaptureDurationMs(options.dynamicFullCaptureDurationMs);
4271
4384
  const trackCallers = durationSampler !== void 0;
4272
4385
  const readCallClock = () => process.hrtime.bigint();
4273
4386
  const tryCallClock3 = () => {
@@ -4398,58 +4511,179 @@ var createExecutionRecorder = (options, hooks = {}) => {
4398
4511
  stats.totalInlineWallTimeMs = Math.round((stats.totalInlineWallTimeMs + inlineWallTimeMs) * 1e4) / 1e4;
4399
4512
  stats.maxInlineWallTimeMs = Math.max(stats.maxInlineWallTimeMs, inlineWallTimeMs);
4400
4513
  };
4401
- const freezeAndCount = (recording, value) => {
4402
- const frozen = (recording.serializer ?? serializer).freeze(value);
4514
+ const EMPTY_POLICY = {
4515
+ ordinary: false,
4516
+ sessionValues: false,
4517
+ captureValues: false
4518
+ };
4519
+ const freezeAndCount = (value, encodeSerializer = serializer) => {
4520
+ const frozen = encodeSerializer.freeze(value);
4403
4521
  stats.serializedValues++;
4404
4522
  stats.serializedValueNodes += frozen.visitedNodes;
4405
4523
  stats.serializedValueBytes += frozen.estimatedBytes;
4406
4524
  return frozen;
4407
4525
  };
4408
- const captureValue = (recording, value) => {
4526
+ const captureValue = (recording, value, encodeSerializer = serializer) => {
4409
4527
  try {
4410
4528
  return memoryBudget.captureValue(
4411
4529
  recording.memory,
4412
4530
  value,
4413
- (item) => freezeAndCount(recording, item)
4531
+ (item) => freezeAndCount(item, encodeSerializer)
4414
4532
  );
4415
4533
  } catch {
4416
4534
  return { __rasputin_type: "unserializable" };
4417
4535
  }
4418
4536
  };
4419
- const encodeEventValues = (recording, events) => events.map((event) => {
4420
- const encode = (recording.serializer ?? serializer).encode;
4421
- if (event.type === "function_enter") {
4422
- return {
4423
- ...event,
4424
- ...event.args === void 0 ? {} : { args: event.args.map((argument) => encode(argument)) }
4425
- };
4537
+ const sessionExcludedFor = (store, plan) => Boolean(store.sessionSuppressCapture) || Boolean(store.recording.sessionExcludes?.(plan.definition));
4538
+ const capturePolicyFor = (recording, store, plan, observedCalls) => {
4539
+ const sessionId = sessionExcludedFor(store, plan) ? void 0 : recording.sessionId;
4540
+ return {
4541
+ ordinary: recording.captureValues && observedCalls <= maxCapturedCallsPerFunction,
4542
+ sessionValues: Boolean(sessionId) && observedCalls <= (recording.sessionMaxCapturedCalls ?? maxCapturedCallsPerFunction),
4543
+ captureValues: recording.captureValues,
4544
+ ...sessionId ? { sessionId, serializer: recording.serializer ?? serializer } : {}
4545
+ };
4546
+ };
4547
+ const throwPolicyFrom = (policy) => ({
4548
+ ordinary: policy.captureValues,
4549
+ sessionValues: Boolean(policy.sessionId),
4550
+ captureValues: policy.captureValues,
4551
+ ...policy.sessionId ? { sessionId: policy.sessionId, serializer: policy.serializer } : {}
4552
+ });
4553
+ const packCapturedValue = (policy, ordinaryValue, sessionValue) => {
4554
+ if (policy.ordinary && policy.sessionValues && policy.sessionId) {
4555
+ return tagOrdinaryAndSessionCapture(policy.sessionId, sessionValue, ordinaryValue);
4426
4556
  }
4427
- if (event.type === "function_exit") {
4428
- return event.returnValue === void 0 ? event : { ...event, returnValue: encode(event.returnValue) };
4557
+ if (policy.sessionValues && policy.sessionId) {
4558
+ return tagSessionCapture(policy.sessionId, sessionValue);
4429
4559
  }
4430
- if (event.type === "function_throw") {
4431
- return { ...event, error: encode(event.error) };
4560
+ return ordinaryValue;
4561
+ };
4562
+ const encodeEventValues = (recording, events, includeSessionId) => {
4563
+ const encode = (includeSessionId ? recording.serializer ?? serializer : serializer).encode;
4564
+ const sessionCallIds = includeSessionId === void 0 ? void 0 : new Set(
4565
+ events.flatMap(
4566
+ (event) => event.type === "function_enter" && event.sessionCaptureId === includeSessionId ? [event.callId] : []
4567
+ )
4568
+ );
4569
+ const mapped = [];
4570
+ for (const event of events) {
4571
+ if (includeSessionId !== void 0) {
4572
+ if ((event.type === "function_enter" || event.type === "function_exit") && event.sessionCaptureId !== includeSessionId) {
4573
+ continue;
4574
+ }
4575
+ if (event.type === "function_throw" && !sessionCallIds?.has(event.callId)) continue;
4576
+ if (event.type === "function_calls_suppressed" && !events.some(
4577
+ (candidate) => candidate.type === "function_enter" && candidate.functionId === event.functionId && candidate.sessionCaptureId === includeSessionId
4578
+ )) {
4579
+ continue;
4580
+ }
4581
+ }
4582
+ if (event.type === "function_enter") {
4583
+ const next = {
4584
+ type: event.type,
4585
+ callId: event.callId,
4586
+ functionId: event.functionId,
4587
+ ...event.timestampMs === void 0 ? {} : { timestampMs: event.timestampMs },
4588
+ ...event.parentCallId === void 0 ? {} : { parentCallId: event.parentCallId },
4589
+ ...event.capturedAt === void 0 ? {} : { capturedAt: event.capturedAt },
4590
+ ...event.provenance === void 0 ? {} : { provenance: event.provenance }
4591
+ };
4592
+ if (includeSessionId !== void 0) {
4593
+ if (event.sessionArgs === void 0) {
4594
+ mapped.push({ ...next, argsOmitted: true });
4595
+ continue;
4596
+ }
4597
+ mapped.push({
4598
+ ...next,
4599
+ args: event.sessionArgs.map((argument) => encode(argument))
4600
+ });
4601
+ continue;
4602
+ }
4603
+ const keepOrdinary = event.ordinaryCapture || event.sessionCaptureId === void 0;
4604
+ if (!keepOrdinary || event.argsOmitted) {
4605
+ mapped.push({ ...next, argsOmitted: true });
4606
+ continue;
4607
+ }
4608
+ if (event.args === void 0) {
4609
+ mapped.push(next);
4610
+ continue;
4611
+ }
4612
+ mapped.push({ ...next, args: event.args.map((argument) => encode(argument)) });
4613
+ continue;
4614
+ }
4615
+ if (event.type === "function_exit") {
4616
+ const next = {
4617
+ type: event.type,
4618
+ callId: event.callId,
4619
+ ...event.timestampMs === void 0 ? {} : { timestampMs: event.timestampMs },
4620
+ ...event.durationMs === void 0 ? {} : { durationMs: event.durationMs }
4621
+ };
4622
+ if (includeSessionId !== void 0) {
4623
+ if (!Object.hasOwn(event, "sessionReturnValue")) {
4624
+ mapped.push(next);
4625
+ continue;
4626
+ }
4627
+ mapped.push({ ...next, returnValue: encode(event.sessionReturnValue) });
4628
+ continue;
4629
+ }
4630
+ const keepOrdinary = event.ordinaryCapture || event.sessionCaptureId === void 0;
4631
+ if (!keepOrdinary || event.returnValue === void 0) {
4632
+ mapped.push(next);
4633
+ continue;
4634
+ }
4635
+ mapped.push({ ...next, returnValue: encode(event.returnValue) });
4636
+ continue;
4637
+ }
4638
+ if (event.type === "function_throw") {
4639
+ mapped.push({
4640
+ type: event.type,
4641
+ callId: event.callId,
4642
+ ...event.timestampMs === void 0 ? {} : { timestampMs: event.timestampMs },
4643
+ ...event.durationMs === void 0 ? {} : { durationMs: event.durationMs },
4644
+ error: encode(event.error)
4645
+ });
4646
+ continue;
4647
+ }
4648
+ mapped.push(event);
4432
4649
  }
4433
- return event;
4434
- });
4435
- const enterPayload = (recording, omitCallValues, args) => {
4436
- if (!recording.captureValues) return ARGS_OMITTED;
4650
+ return mapped;
4651
+ };
4652
+ const captureArgs = (recording, omitCallValues, args, encodeSerializer) => {
4437
4653
  if (omitCallValues) return mapArrayLike(args, () => rasputinOmitted());
4438
- return mapArrayLike(args, (argument) => captureValue(recording, argument));
4654
+ return mapArrayLike(args, (argument) => captureValue(recording, argument, encodeSerializer));
4439
4655
  };
4440
- const exitPayload = (recording, omitCallValues, value) => {
4441
- if (!recording.captureValues) return ARGS_OMITTED;
4442
- if (omitCallValues) return rasputinOmitted();
4443
- return captureValue(recording, value);
4656
+ const enterPayload = (recording, omitCallValues, args, policy) => {
4657
+ if (!policy.ordinary && !policy.sessionValues) return ARGS_OMITTED;
4658
+ const sessionSerializer = policy.serializer ?? serializer;
4659
+ if (omitCallValues || !policy.ordinary || !policy.sessionValues || sessionSerializer === serializer) {
4660
+ const shared = policy.ordinary ? captureArgs(recording, omitCallValues, args, serializer) : captureArgs(recording, omitCallValues, args, sessionSerializer);
4661
+ return packCapturedValue(policy, shared, shared);
4662
+ }
4663
+ return packCapturedValue(
4664
+ policy,
4665
+ captureArgs(recording, false, args, serializer),
4666
+ captureArgs(recording, false, args, sessionSerializer)
4667
+ );
4668
+ };
4669
+ const exitPayload = (recording, omitCallValues, value, policy) => {
4670
+ if (!policy.ordinary && !policy.sessionValues) return ARGS_OMITTED;
4671
+ const sessionSerializer = policy.serializer ?? serializer;
4672
+ if (omitCallValues || !policy.ordinary || !policy.sessionValues || sessionSerializer === serializer) {
4673
+ const shared = omitCallValues ? rasputinOmitted() : captureValue(recording, value, policy.ordinary ? serializer : sessionSerializer);
4674
+ return packCapturedValue(policy, shared, shared);
4675
+ }
4676
+ return packCapturedValue(
4677
+ policy,
4678
+ captureValue(recording, value, serializer),
4679
+ captureValue(recording, value, sessionSerializer)
4680
+ );
4444
4681
  };
4445
4682
  const admitSession = (recording, session) => {
4446
- const wasLight = adaptiveEnabled && !recording.captureValues;
4447
4683
  recording.retainSuccess = true;
4448
4684
  recording.sessionId = session.sessionId;
4449
- recording.captureValues = true;
4450
4685
  if (session.serializer) recording.serializer = session.serializer;
4451
4686
  if (session.redactKeys?.length) recording.sessionRedactKeys = session.redactKeys;
4452
- if (session.scrubPII !== void 0) recording.sessionScrubPii = session.scrubPII;
4453
4687
  if (session.excludeSources?.length) {
4454
4688
  recording.sessionExcludes = createSourceExclusionMatcher(session.excludeSources);
4455
4689
  }
@@ -4462,28 +4696,29 @@ var createExecutionRecorder = (options, hooks = {}) => {
4462
4696
  if (session.maxExecutionHoldMs !== void 0) {
4463
4697
  recording.sessionHoldNs = BigInt(Math.max(1, Math.round(session.maxExecutionHoldMs))) * 1000000n;
4464
4698
  }
4465
- if (wasLight) {
4466
- stats.adaptiveLightExecutions = Math.max(0, stats.adaptiveLightExecutions - 1);
4467
- stats.adaptiveFullExecutions++;
4468
- }
4469
4699
  };
4470
- const skipCapture = (store, plan) => store.suppressCapture || plan.excluded || Boolean(store.recording.sessionExcludes?.(plan.definition));
4471
- const callStoreFor = (store, functionId, callId) => {
4472
- const next = { ...store, currentCallId: callId };
4700
+ const skipCapture = (store, plan) => store.suppressCapture || plan.excluded;
4701
+ const callStoreFor = (store, functionId, callId, sessionSuppress) => {
4702
+ const next = {
4703
+ ...store,
4704
+ currentCallId: callId,
4705
+ ...sessionSuppress ? { sessionSuppressCapture: true } : {}
4706
+ };
4473
4707
  if (trackCallers) next.currentFunctionId = functionId;
4474
4708
  return next;
4475
4709
  };
4476
4710
  const samplingStore = (store, functionId) => {
4477
4711
  return trackCallers ? { ...store, currentFunctionId: functionId } : store;
4478
4712
  };
4479
- const recorderForceMeasure = (recording) => !(adaptiveEnabled && recording.identityResolved === true && !recording.captureValues && !recording.retainSuccess);
4713
+ const sessionBodyStore = (store, sessionExcluded) => sessionExcluded ? { ...store, sessionSuppressCapture: true } : store;
4714
+ const recorderForceMeasure = (recording) => !(adaptiveEnabled && recording.resolvedExecutionKey !== void 0 && !recording.captureValues && !recording.retainSuccess);
4480
4715
  const planInvocationDuration = (recording, plan, callerFunctionId) => planCallDuration(durationSampler, {
4481
4716
  forceMeasure: recorderForceMeasure(recording),
4482
4717
  executionType: executionTypeKey(recording.execution),
4483
4718
  callerFunctionId: callerFunctionId ?? "",
4484
4719
  functionId: plan.functionId
4485
4720
  });
4486
- const capturedCallLimitFor = (recording) => recording.sessionMaxCapturedCalls ?? maxCapturedCallsPerFunction;
4721
+ const capturedCallLimitFor = (recording) => Math.max(maxCapturedCallsPerFunction, recording.sessionMaxCapturedCalls ?? 0);
4487
4722
  const tryAdmitLiveSession = (recording) => {
4488
4723
  if (recording.retainSuccess || recording.finished) return;
4489
4724
  const key = executionTypeKey(recording.execution);
@@ -4491,29 +4726,59 @@ var createExecutionRecorder = (options, hooks = {}) => {
4491
4726
  const peek = hooks.sessionCaptureSnapshot?.().get(key);
4492
4727
  if (!peek || peek.expiresAtMs <= recording.startedAtMs) return;
4493
4728
  const live = hooks.consumeSession?.(key, peek.sessionId);
4494
- if (live) admitSession(recording, live);
4495
- };
4496
- const tryAdmitFromStartSnapshot = (recording) => {
4497
- if (recording.retainSuccess || recording.finished) return;
4729
+ if (!live) return;
4730
+ admitSession(recording, live);
4731
+ recording.sessionReserved = true;
4732
+ };
4733
+ const setCaptureValues = (recording, next) => {
4734
+ if (recording.captureValues === next) return;
4735
+ recording.captureValues = next;
4736
+ if (!adaptiveEnabled) return;
4737
+ if (next) {
4738
+ stats.adaptiveLightExecutions = Math.max(0, stats.adaptiveLightExecutions - 1);
4739
+ stats.adaptiveFullExecutions++;
4740
+ return;
4741
+ }
4742
+ stats.adaptiveFullExecutions = Math.max(0, stats.adaptiveFullExecutions - 1);
4743
+ stats.adaptiveLightExecutions++;
4744
+ };
4745
+ const detachSession = (recording) => {
4746
+ if (!recording.sessionId) return;
4747
+ delete recording.sessionId;
4748
+ delete recording.sessionReserved;
4749
+ delete recording.retainSuccess;
4750
+ delete recording.serializer;
4751
+ delete recording.sessionRedactKeys;
4752
+ delete recording.sessionExcludes;
4753
+ delete recording.sessionMaxCapturedCalls;
4754
+ delete recording.sessionHoldNs;
4755
+ };
4756
+ const applyExecutionIdentity = (recording) => {
4757
+ if (recording.finished) return;
4498
4758
  const key = executionTypeKey(recording.execution);
4499
- if (!key) return;
4500
- const peek = recording.sessionCaptureSnapshot.get(key);
4501
- if (!peek || peek.expiresAtMs <= recording.startedAtMs) return;
4502
- const live = hooks.consumeSession?.(key, peek.sessionId);
4503
- if (live) admitSession(recording, live);
4759
+ if (!key || recording.resolvedExecutionKey === key) return;
4760
+ detachSession(recording);
4761
+ recording.resolvedExecutionKey = key;
4762
+ if (adaptiveEnabled) {
4763
+ setCaptureValues(
4764
+ recording,
4765
+ keyIsActive(recording.policySnapshot, key, recording.startedAtMs)
4766
+ );
4767
+ }
4768
+ const session = recording.sessionCaptureSnapshot.get(key);
4769
+ if (session && session.expiresAtMs > recording.startedAtMs) {
4770
+ admitSession(recording, session);
4771
+ }
4504
4772
  };
4505
- const completeIdentityFromSnapshot = (recording) => {
4506
- if (recording.identityResolved || recording.finished) return;
4773
+ const reserveSession = (recording) => {
4774
+ if (!recording.sessionId || recording.sessionReserved || !hooks.consumeSession) return;
4507
4775
  const key = executionTypeKey(recording.execution);
4508
- if (!key) return;
4509
- recording.identityResolved = true;
4510
- tryAdmitFromStartSnapshot(recording);
4511
- if (recording.captureValues || !adaptiveEnabled) return;
4512
- if (keyIsActive(recording.policySnapshot, key, recording.startedAtMs)) {
4513
- recording.captureValues = true;
4514
- stats.adaptiveLightExecutions = Math.max(0, stats.adaptiveLightExecutions - 1);
4515
- stats.adaptiveFullExecutions++;
4776
+ const reserved = key ? hooks.consumeSession(key, recording.sessionId) : void 0;
4777
+ if (reserved) {
4778
+ recording.sessionReserved = true;
4779
+ return;
4516
4780
  }
4781
+ detachSession(recording);
4517
4782
  };
4518
4783
  const maybeActivateAdaptive = (recording) => {
4519
4784
  if (!adaptiveEnabled || recording.adaptiveActivated) return;
@@ -4586,7 +4851,7 @@ var createExecutionRecorder = (options, hooks = {}) => {
4586
4851
  }
4587
4852
  return false;
4588
4853
  };
4589
- const resolveCaptureProfile = (recording, events, truncated, capture) => {
4854
+ const resolveCaptureProfile = (recording, events, truncated, capture, includeSessionId) => {
4590
4855
  const source = recording.sawAutomatic ? "automatic" : recording.sawManual ? "manual" : "scope-only";
4591
4856
  if (source === "scope-only") {
4592
4857
  return {
@@ -4622,20 +4887,21 @@ var createExecutionRecorder = (options, hooks = {}) => {
4622
4887
  }
4623
4888
  const droppedEvents = Boolean(truncated?.eventsDropped || capture?.eventsDropped);
4624
4889
  const evidence = retainedTimingsCoverage(events);
4890
+ const includeValues = recording.captureValues || includeSessionId !== void 0;
4625
4891
  return {
4626
4892
  source,
4627
4893
  functionBoundaries: droppedEvents ? "partial" : "full",
4628
- functionValues: recording.captureValues ? eventsHaveOmittedValues(events) ? "selective" : "full" : "none",
4894
+ functionValues: includeValues ? eventsHaveOmittedValues(events) ? "selective" : "full" : "none",
4629
4895
  timings: droppedEvents && evidence === "full" ? "partial" : evidence
4630
4896
  };
4631
4897
  };
4632
- const stateFrom = (recording, endedAtNs = process.hrtime.bigint()) => {
4898
+ const stateFrom = (recording, endedAtNs = process.hrtime.bigint(), includeSessionId) => {
4633
4899
  const recorderStartedAtNs = process.hrtime.bigint();
4634
4900
  let events = [];
4635
4901
  let functions = [];
4636
4902
  let truncated;
4637
4903
  let capture;
4638
- if (recording.cachedState) {
4904
+ if (recording.cachedState && includeSessionId === void 0) {
4639
4905
  events = recording.cachedState.events;
4640
4906
  functions = recording.cachedState.functions;
4641
4907
  truncated = recording.cachedState.truncated;
@@ -4643,13 +4909,25 @@ var createExecutionRecorder = (options, hooks = {}) => {
4643
4909
  } else {
4644
4910
  if (recording.journal) {
4645
4911
  const materialized = recording.journal.materialize(plansByRuntimeId, recording.startedAtNs);
4646
- events = encodeEventValues(recording, materialized.events);
4912
+ events = encodeEventValues(recording, materialized.events, includeSessionId);
4647
4913
  if (recording.lateCapturedCallIds && recording.lateCapturedCallIds.size > 0) {
4648
4914
  events = events.map(
4649
4915
  (event) => event.type === "function_enter" && recording.lateCapturedCallIds?.has(event.callId) ? { ...event, capturedAt: "throw" } : event
4650
4916
  );
4651
4917
  }
4652
- functions = materialized.functions;
4918
+ if (includeSessionId === void 0) {
4919
+ functions = materialized.functions;
4920
+ } else {
4921
+ const usedIds = /* @__PURE__ */ new Set();
4922
+ for (const event of events) {
4923
+ if (event.type === "function_enter" || event.type === "function_calls_suppressed") {
4924
+ usedIds.add(event.functionId);
4925
+ }
4926
+ }
4927
+ functions = materialized.functions.filter(
4928
+ (definition) => usedIds.has(definition.functionId)
4929
+ );
4930
+ }
4653
4931
  truncated = recording.journal.dropped > 0 ? { eventsDropped: recording.journal.dropped } : void 0;
4654
4932
  }
4655
4933
  if (recording.budgetExpired) {
@@ -4674,13 +4952,19 @@ var createExecutionRecorder = (options, hooks = {}) => {
4674
4952
  eventsDropped: recording.memory.eventsDropped
4675
4953
  };
4676
4954
  }
4677
- if (recording.finished && recording.inFlightCalls === 0 && recording.journal) {
4955
+ if (includeSessionId === void 0 && recording.finished && recording.inFlightCalls === 0 && recording.journal) {
4678
4956
  recording.cachedState = { events, functions, truncated, capture };
4679
4957
  journalPool.release(recording.journal);
4680
4958
  recording.journal = void 0;
4681
4959
  }
4682
4960
  }
4683
- const captureProfile = resolveCaptureProfile(recording, events, truncated, capture);
4961
+ const captureProfile = resolveCaptureProfile(
4962
+ recording,
4963
+ events,
4964
+ truncated,
4965
+ capture,
4966
+ includeSessionId
4967
+ );
4684
4968
  const fullyTimed = eventsAreFullyTimed(events);
4685
4969
  const state = {
4686
4970
  version: 4,
@@ -4697,7 +4981,12 @@ var createExecutionRecorder = (options, hooks = {}) => {
4697
4981
  events: fullyTimed ? asFullyTimedEvents(events) : events.slice(),
4698
4982
  ...fullyTimed || !durationSampler ? {} : { durationSampling: { policy: "progressive" } },
4699
4983
  ...truncated ? { truncated: { ...truncated } } : {},
4700
- ...capture ? { capture: { ...capture } } : {}
4984
+ ...capture ? { capture: { ...capture } } : {},
4985
+ ...includeSessionId === void 0 ? recording.inputSnapshot && Object.hasOwn(recording.inputSnapshot, "ordinary") ? { input: serializer.encode(recording.inputSnapshot.ordinary) } : {} : recording.inputSnapshot?.sessionId === includeSessionId && Object.hasOwn(recording.inputSnapshot, "sessionValue") ? {
4986
+ input: (recording.serializer ?? serializer).encode(
4987
+ recording.inputSnapshot.sessionValue
4988
+ )
4989
+ } : {}
4701
4990
  };
4702
4991
  if (phaseTimingEnabled)
4703
4992
  addPhase("materializeNs", process.hrtime.bigint() - recorderStartedAtNs);
@@ -4723,6 +5012,7 @@ var createExecutionRecorder = (options, hooks = {}) => {
4723
5012
  recording.cachedState = void 0;
4724
5013
  recording.repeatedCalls = void 0;
4725
5014
  recording.lateCapturedCallIds = void 0;
5015
+ recording.inputSnapshot = void 0;
4726
5016
  recording.capturedErrors = /* @__PURE__ */ new WeakMap();
4727
5017
  if (recording.journal) {
4728
5018
  journalPool.release(recording.journal);
@@ -4758,6 +5048,7 @@ var createExecutionRecorder = (options, hooks = {}) => {
4758
5048
  recording.journal = void 0;
4759
5049
  }
4760
5050
  recording.evicted = true;
5051
+ recording.inputSnapshot = void 0;
4761
5052
  detachLiveRecording(recording);
4762
5053
  recording.cachedState = {
4763
5054
  events: [],
@@ -4811,6 +5102,7 @@ var createExecutionRecorder = (options, hooks = {}) => {
4811
5102
  journalPool.release(recording.journal);
4812
5103
  recording.journal = void 0;
4813
5104
  }
5105
+ recording.inputSnapshot = void 0;
4814
5106
  recording.cachedState = {
4815
5107
  events: [],
4816
5108
  functions: [],
@@ -4847,7 +5139,8 @@ var createExecutionRecorder = (options, hooks = {}) => {
4847
5139
  liveRecordings.splice(index, 1);
4848
5140
  continue;
4849
5141
  }
4850
- if (nowNs - recording.startedAtNs < (recording.sessionHoldNs ?? maxExecutionHoldNs)) continue;
5142
+ const holdNs = recording.sessionHoldNs !== void 0 && recording.sessionHoldNs > maxExecutionHoldNs ? recording.sessionHoldNs : maxExecutionHoldNs;
5143
+ if (nowNs - recording.startedAtNs < holdNs) continue;
4851
5144
  try {
4852
5145
  expireLongLivedRecording(recording, nowNs);
4853
5146
  } catch {
@@ -4955,7 +5248,7 @@ var createExecutionRecorder = (options, hooks = {}) => {
4955
5248
  // snapshot without the exception itself would not be useful for investigation.
4956
5249
  value: (() => {
4957
5250
  try {
4958
- return freezeAndCount(recording, error).value;
5251
+ return freezeAndCount(error).value;
4959
5252
  } catch {
4960
5253
  return { __rasputin_type: "unserializable" };
4961
5254
  }
@@ -4965,7 +5258,7 @@ var createExecutionRecorder = (options, hooks = {}) => {
4965
5258
  }
4966
5259
  };
4967
5260
  };
4968
- const captureCompletedThrow = (recording, plan, args, parentCallId, startedAtNs, error, timed, capturedArgs, completedAtNs) => {
5261
+ const captureCompletedThrow = (recording, plan, parentCallId, startedAtNs, error, timed, capturedArgs, completedAtNs) => {
4969
5262
  if (!recording.journal) {
4970
5263
  return;
4971
5264
  }
@@ -4974,7 +5267,7 @@ var createExecutionRecorder = (options, hooks = {}) => {
4974
5267
  }
4975
5268
  const callId = ++recording.nextCallId;
4976
5269
  const capturedError = serializedError(recording, error, callId);
4977
- const recordedArgs = capturedArgs ?? (recording.captureValues ? mapArrayLike(args, (argument) => captureValue(recording, argument)) : ARGS_OMITTED);
5270
+ const recordedArgs = capturedArgs;
4978
5271
  const endedAtNs = timed ? completedAtNs : void 0;
4979
5272
  const droppedBefore = recording.journal.dropped;
4980
5273
  const retained = recording.journal.forceCompletedCall(
@@ -5058,9 +5351,8 @@ var createExecutionRecorder = (options, hooks = {}) => {
5058
5351
  sessionId: recording.sessionId,
5059
5352
  executionId: recording.executionId,
5060
5353
  outcome: recording.hasError || recording.runFailed ? "error" : "success",
5061
- runtimeState: stateFrom(recording),
5062
- redactKeys: recording.sessionRedactKeys,
5063
- scrubPii: recording.sessionScrubPii
5354
+ runtimeState: stateFrom(recording, void 0, recording.sessionId),
5355
+ redactKeys: recording.sessionRedactKeys
5064
5356
  });
5065
5357
  } catch {
5066
5358
  }
@@ -5095,16 +5387,16 @@ var createExecutionRecorder = (options, hooks = {}) => {
5095
5387
  return;
5096
5388
  }
5097
5389
  const recorderStartedAtNs = process.hrtime.bigint();
5098
- recording.finished = true;
5099
5390
  if (metadata) {
5100
5391
  mergeExecutionMetadata(recording.execution, metadata);
5101
- bindMetricsExecution(recording);
5102
- bindExecutionMetricsIdentity2(recording);
5392
+ applyExecutionIdentity(recording);
5103
5393
  }
5394
+ recording.finished = true;
5395
+ reserveSession(recording);
5104
5396
  if (executionMetrics && recording.executionMetrics) {
5105
5397
  const executionKey = executionTypeKey(recording.execution);
5106
- bindExecutionMetricsIdentity2(recording);
5107
5398
  executionMetrics.finishExecution(recording.executionMetrics, {
5399
+ key: executionKey,
5108
5400
  failed: executionOutcomeFailed({
5109
5401
  hasError: recording.hasError,
5110
5402
  runFailed: recording.runFailed === true,
@@ -5149,7 +5441,8 @@ var createExecutionRecorder = (options, hooks = {}) => {
5149
5441
  ...metadata,
5150
5442
  ...metadata.request ? { request: { ...metadata.request } } : {}
5151
5443
  };
5152
- const identityComplete = executionTypeKey(execution) !== void 0;
5444
+ const initialKey = executionTypeKey(execution);
5445
+ const identityComplete = initialKey !== void 0;
5153
5446
  const captureValues = captureValuesFor(execution, livePolicy, startedAtMs);
5154
5447
  const policySnapshot = adaptiveEnabled && !identityComplete ? new Map(livePolicy) : EMPTY_POLICY_SNAPSHOT;
5155
5448
  const liveSessions = hooks.sessionCaptureSnapshot?.() ?? EMPTY_SESSION_SNAPSHOT;
@@ -5177,14 +5470,15 @@ var createExecutionRecorder = (options, hooks = {}) => {
5177
5470
  sawManual: false,
5178
5471
  captureValues,
5179
5472
  policySnapshot,
5180
- identityResolved: identityComplete,
5473
+ resolvedExecutionKey: initialKey,
5181
5474
  sessionCaptureSnapshot
5182
5475
  };
5183
5476
  if (identityComplete) tryAdmitLiveSession(recording);
5184
- bindMetricsExecution(recording);
5185
5477
  if (executionMetrics) {
5186
5478
  recording.executionMetrics = executionMetrics.createState();
5187
- bindExecutionMetricsIdentity2(recording);
5479
+ if (execution.kind !== "http") {
5480
+ executionMetrics.bindIdentity(recording.executionMetrics, initialKey);
5481
+ }
5188
5482
  }
5189
5483
  stats.activeExecutions++;
5190
5484
  stats.peakActiveExecutions = Math.max(stats.peakActiveExecutions, stats.activeExecutions);
@@ -5236,9 +5530,32 @@ var createExecutionRecorder = (options, hooks = {}) => {
5236
5530
  mergeMetadata: (nextMetadata) => {
5237
5531
  try {
5238
5532
  mergeExecutionMetadata(recording.execution, nextMetadata);
5239
- completeIdentityFromSnapshot(recording);
5240
- bindMetricsExecution(recording);
5241
- bindExecutionMetricsIdentity2(recording);
5533
+ applyExecutionIdentity(recording);
5534
+ if (executionMetrics && recording.executionMetrics && recording.execution.kind !== "http") {
5535
+ executionMetrics.bindIdentity(
5536
+ recording.executionMetrics,
5537
+ executionTypeKey(recording.execution)
5538
+ );
5539
+ }
5540
+ } catch {
5541
+ }
5542
+ },
5543
+ captureInput: (value) => {
5544
+ try {
5545
+ if (recording.inputSnapshot || recording.evidenceDiscarded || recording.evicted || recording.budgetExpired) {
5546
+ return;
5547
+ }
5548
+ const ordinary = captureValue(recording, value, serializer);
5549
+ if (!recording.sessionId) {
5550
+ recording.inputSnapshot = { ordinary };
5551
+ return;
5552
+ }
5553
+ const sessionSerializer = recording.serializer ?? serializer;
5554
+ recording.inputSnapshot = {
5555
+ ordinary,
5556
+ sessionId: recording.sessionId,
5557
+ sessionValue: sessionSerializer === serializer ? ordinary : captureValue(recording, value, sessionSerializer)
5558
+ };
5242
5559
  } catch {
5243
5560
  }
5244
5561
  }
@@ -5258,7 +5575,7 @@ var createExecutionRecorder = (options, hooks = {}) => {
5258
5575
  const duration = plan.excluded ? { selected: false, measure: false } : store ? planInvocationDuration(store.recording, plan, store.currentFunctionId) : { selected: false, measure: false };
5259
5576
  const startedNs = duration.measure ? tryCallClock3() : void 0;
5260
5577
  const functionHandle = functionMetrics && !plan.excluded ? internPreparedMetrics(functionMetrics, plan) : void 0;
5261
- const executionHandle = store?.recording.metricsExecutionHandle;
5578
+ const executionHandle = functionHandle !== void 0 && store ? metricsExecutionHandleFor(store.recording) : void 0;
5262
5579
  const metricsStart = startMetricsCall(functionMetrics, functionHandle, executionHandle, {
5263
5580
  measure: duration.selected,
5264
5581
  ...duration.selected ? { startedNs } : {}
@@ -5349,10 +5666,13 @@ var createExecutionRecorder = (options, hooks = {}) => {
5349
5666
  const recorderStartedAtNs = process.hrtime.bigint();
5350
5667
  if (skipCapture(store, plan)) {
5351
5668
  stats.functionCallsExcluded++;
5352
- return runStore({ ...store, suppressCapture: true }, function __rasputinHandleRun__5() {
5353
- addRecorderTime(store.recording, process.hrtime.bigint() - recorderStartedAtNs);
5354
- return callback();
5355
- });
5669
+ return runStore(
5670
+ { ...store, suppressCapture: true, sessionSuppressCapture: true },
5671
+ function __rasputinHandleRun__5() {
5672
+ addRecorderTime(store.recording, process.hrtime.bigint() - recorderStartedAtNs);
5673
+ return callback();
5674
+ }
5675
+ );
5356
5676
  }
5357
5677
  const recording = store.recording;
5358
5678
  recording.inFlightCalls++;
@@ -5366,10 +5686,12 @@ var createExecutionRecorder = (options, hooks = {}) => {
5366
5686
  }
5367
5687
  const timed = sharedClock.timed;
5368
5688
  const startedAtNs = sharedClock.start ?? 0n;
5689
+ const sessionExcluded = sessionExcludedFor(store, plan);
5690
+ const policy = capturePolicyFor(recording, store, plan, group.observedCalls);
5369
5691
  if (group.observedCalls > capturedCallLimitFor(recording)) {
5370
5692
  try {
5371
5693
  const result = runStore(
5372
- samplingStore(store, plan.functionId),
5694
+ sessionBodyStore(samplingStore(store, plan.functionId), sessionExcluded),
5373
5695
  function __rasputinHandleRun__5() {
5374
5696
  return callback();
5375
5697
  }
@@ -5404,12 +5726,11 @@ var createExecutionRecorder = (options, hooks = {}) => {
5404
5726
  captureCompletedThrow(
5405
5727
  recording,
5406
5728
  plan,
5407
- args,
5408
5729
  parentCallId,
5409
5730
  startedAtNs,
5410
5731
  error,
5411
5732
  timed,
5412
- void 0,
5733
+ enterPayload(recording, omitCallValues, args, throwPolicyFrom(policy)),
5413
5734
  sharedClock.end
5414
5735
  );
5415
5736
  settleInFlight(recording);
@@ -5418,17 +5739,20 @@ var createExecutionRecorder = (options, hooks = {}) => {
5418
5739
  }
5419
5740
  if (!journal) {
5420
5741
  memoryBudget.reserveCall(recording.memory, plan.estimatedCallBytes);
5421
- return runStore(samplingStore(store, plan.functionId), function __rasputinHandleRun__5() {
5422
- return observeRecordedCallback(
5423
- recording,
5424
- recorderStartedAtNs,
5425
- callback,
5426
- () => settleInFlight(recording),
5427
- (_error) => {
5428
- settleInFlight(recording);
5429
- }
5430
- );
5431
- });
5742
+ return runStore(
5743
+ sessionBodyStore(samplingStore(store, plan.functionId), sessionExcluded),
5744
+ function __rasputinHandleRun__5() {
5745
+ return observeRecordedCallback(
5746
+ recording,
5747
+ recorderStartedAtNs,
5748
+ callback,
5749
+ () => settleInFlight(recording),
5750
+ (_error) => {
5751
+ settleInFlight(recording);
5752
+ }
5753
+ );
5754
+ }
5755
+ );
5432
5756
  }
5433
5757
  if (!journal.canStartCall()) {
5434
5758
  const captureSuccess = () => {
@@ -5437,63 +5761,71 @@ var createExecutionRecorder = (options, hooks = {}) => {
5437
5761
  countDroppedEvents(recording, droppedBefore);
5438
5762
  settleInFlight(recording);
5439
5763
  };
5440
- return runStore(samplingStore(store, plan.functionId), function __rasputinHandleRun__5() {
5441
- return observeRecordedCallback(
5442
- recording,
5443
- recorderStartedAtNs,
5444
- callback,
5445
- captureSuccess,
5446
- (error) => {
5447
- if (timed && sharedClock.end === void 0) sharedClock.end = tryCallClock3();
5448
- captureCompletedThrow(
5449
- recording,
5450
- plan,
5451
- args,
5452
- parentCallId,
5453
- startedAtNs,
5454
- error,
5455
- timed,
5456
- void 0,
5457
- sharedClock.end
5458
- );
5459
- settleInFlight(recording);
5460
- }
5461
- );
5462
- });
5764
+ return runStore(
5765
+ sessionBodyStore(samplingStore(store, plan.functionId), sessionExcluded),
5766
+ function __rasputinHandleRun__5() {
5767
+ return observeRecordedCallback(
5768
+ recording,
5769
+ recorderStartedAtNs,
5770
+ callback,
5771
+ captureSuccess,
5772
+ (error) => {
5773
+ if (timed && sharedClock.end === void 0) sharedClock.end = tryCallClock3();
5774
+ captureCompletedThrow(
5775
+ recording,
5776
+ plan,
5777
+ parentCallId,
5778
+ startedAtNs,
5779
+ error,
5780
+ timed,
5781
+ enterPayload(recording, omitCallValues, args, policy),
5782
+ sharedClock.end
5783
+ );
5784
+ settleInFlight(recording);
5785
+ }
5786
+ );
5787
+ }
5788
+ );
5463
5789
  }
5464
5790
  if (!memoryBudget.reserveCall(recording.memory, plan.estimatedCallBytes)) {
5465
- return runStore(samplingStore(store, plan.functionId), function __rasputinHandleRun__5() {
5466
- return observeRecordedCallback(
5467
- recording,
5468
- recorderStartedAtNs,
5469
- callback,
5470
- () => settleInFlight(recording),
5471
- (_error) => {
5472
- settleInFlight(recording);
5473
- }
5474
- );
5475
- });
5791
+ return runStore(
5792
+ sessionBodyStore(samplingStore(store, plan.functionId), sessionExcluded),
5793
+ function __rasputinHandleRun__5() {
5794
+ return observeRecordedCallback(
5795
+ recording,
5796
+ recorderStartedAtNs,
5797
+ callback,
5798
+ () => settleInFlight(recording),
5799
+ (_error) => {
5800
+ settleInFlight(recording);
5801
+ }
5802
+ );
5803
+ }
5804
+ );
5476
5805
  }
5477
5806
  const callId = ++recording.nextCallId;
5478
5807
  const enterTimestampNs = timed ? startedAtNs - recording.startedAtNs : TIMING_UNAVAILABLE;
5479
- const capturedArgs = enterPayload(recording, omitCallValues, args);
5808
+ const capturedArgs = enterPayload(recording, omitCallValues, args, policy);
5480
5809
  try {
5481
5810
  journal.startCall(plan.runtimePlanId, callId, parentCallId, enterTimestampNs, capturedArgs);
5482
5811
  } catch {
5483
5812
  journal.dropCall();
5484
- return runStore(samplingStore(store, plan.functionId), function __rasputinHandleRun__5() {
5485
- return observeRecordedCallback(
5486
- recording,
5487
- recorderStartedAtNs,
5488
- callback,
5489
- () => settleInFlight(recording),
5490
- (_error) => {
5491
- settleInFlight(recording);
5492
- }
5493
- );
5494
- });
5813
+ return runStore(
5814
+ sessionBodyStore(samplingStore(store, plan.functionId), sessionExcluded),
5815
+ function __rasputinHandleRun__5() {
5816
+ return observeRecordedCallback(
5817
+ recording,
5818
+ recorderStartedAtNs,
5819
+ callback,
5820
+ () => settleInFlight(recording),
5821
+ (_error) => {
5822
+ settleInFlight(recording);
5823
+ }
5824
+ );
5825
+ }
5826
+ );
5495
5827
  }
5496
- const callStore = callStoreFor(store, plan.functionId, callId);
5828
+ const callStore = callStoreFor(store, plan.functionId, callId, sessionExcluded);
5497
5829
  return runStore(callStore, function __rasputinHandleRun__5() {
5498
5830
  return observeRecordedCallback(
5499
5831
  recording,
@@ -5504,7 +5836,7 @@ var createExecutionRecorder = (options, hooks = {}) => {
5504
5836
  const pending = value instanceof Promise;
5505
5837
  const endedAtNs = timed && !pending ? tryCallClock3() : void 0;
5506
5838
  if (endedAtNs !== void 0) sharedClock.end = endedAtNs;
5507
- const returnValue = exitPayload(recording, omitCallValues, value);
5839
+ const returnValue = exitPayload(recording, omitCallValues, value, policy);
5508
5840
  if (endedAtNs !== void 0) {
5509
5841
  recording.journal.finishCall(
5510
5842
  KIND_EXIT,
@@ -5586,6 +5918,7 @@ var createExecutionRecorder = (options, hooks = {}) => {
5586
5918
  this.plan = plan;
5587
5919
  this.args = args;
5588
5920
  this.omitCallValues = omitCallValues;
5921
+ this.policy = EMPTY_POLICY;
5589
5922
  this.parentCallId = parentCallId;
5590
5923
  this.activeStore = activeStore;
5591
5924
  this.parentStore = parentStore;
@@ -5623,7 +5956,7 @@ var createExecutionRecorder = (options, hooks = {}) => {
5623
5956
  try {
5624
5957
  if (this.status !== "failed") {
5625
5958
  this.status = "left";
5626
- if (this.recording.captureValues) this.pendingReturn = value;
5959
+ if (this.policy.ordinary || this.policy.sessionValues) this.pendingReturn = value;
5627
5960
  }
5628
5961
  return value;
5629
5962
  } catch {
@@ -5640,27 +5973,32 @@ var createExecutionRecorder = (options, hooks = {}) => {
5640
5973
  }
5641
5974
  if (this.mode === "captured") writeCapturedThrow(this, error);
5642
5975
  else if (this.mode === "suppressed" && this.plan) {
5976
+ const throwPolicy = throwPolicyFrom(this.policy);
5643
5977
  captureCompletedThrow(
5644
5978
  this.recording,
5645
5979
  this.plan,
5646
- this.recording.captureValues ? liveArgs ?? this.args : EMPTY_ARGS,
5647
5980
  this.parentCallId,
5648
5981
  this.startedAtNs,
5649
5982
  error,
5650
5983
  this.timed,
5651
- this.recording.captureValues ? void 0 : ARGS_OMITTED,
5984
+ throwPolicy.ordinary || throwPolicy.sessionValues ? enterPayload(
5985
+ this.recording,
5986
+ this.omitCallValues,
5987
+ liveArgs ?? this.args,
5988
+ throwPolicy
5989
+ ) : ARGS_OMITTED,
5652
5990
  this.completedAtNs
5653
5991
  );
5654
5992
  } else if (this.mode === "dropped" && this.captureDroppedThrow && this.plan) {
5993
+ const throwPolicy = throwPolicyFrom(this.policy);
5655
5994
  captureCompletedThrow(
5656
5995
  this.recording,
5657
5996
  this.plan,
5658
- this.recording.captureValues ? this.args : EMPTY_ARGS,
5659
5997
  this.parentCallId,
5660
5998
  this.startedAtNs,
5661
5999
  error,
5662
6000
  this.timed,
5663
- this.recording.captureValues ? void 0 : ARGS_OMITTED,
6001
+ throwPolicy.ordinary || throwPolicy.sessionValues ? enterPayload(this.recording, this.omitCallValues, this.args, throwPolicy) : ARGS_OMITTED,
5664
6002
  this.completedAtNs
5665
6003
  );
5666
6004
  }
@@ -5777,7 +6115,7 @@ var createExecutionRecorder = (options, hooks = {}) => {
5777
6115
  const writeCapturedExit = (frame, value, completedAtNs) => {
5778
6116
  if (!frame.recording.journal) return;
5779
6117
  const endedAtNs = frame.timed ? completedAtNs : void 0;
5780
- const returnValue = exitPayload(frame.recording, frame.omitCallValues, value);
6118
+ const returnValue = exitPayload(frame.recording, frame.omitCallValues, value, frame.policy);
5781
6119
  if (endedAtNs !== void 0) {
5782
6120
  frame.recording.journal.finishCall(
5783
6121
  KIND_EXIT,
@@ -5824,14 +6162,14 @@ var createExecutionRecorder = (options, hooks = {}) => {
5824
6162
  const armCallFrameMetrics = (frame, plan) => {
5825
6163
  if (!functionMetrics || plan.excluded) return;
5826
6164
  const functionHandle = internPreparedMetrics(functionMetrics, plan);
6165
+ const executionHandle = functionHandle !== void 0 ? metricsExecutionHandleFor(frame.recording) : void 0;
5827
6166
  const started = startMetricsCall(
5828
6167
  functionMetrics,
5829
6168
  functionHandle,
5830
- frame.recording.metricsExecutionHandle,
6169
+ executionHandle,
5831
6170
  frame.metricsSelected ? { measure: true, startedNs: frame.timed ? frame.startedAtNs : void 0 } : { measure: false }
5832
6171
  );
5833
6172
  if (!started || functionHandle === void 0) return;
5834
- const executionHandle = frame.recording.metricsExecutionHandle;
5835
6173
  if (executionHandle === void 0) return;
5836
6174
  frame.metricsOpen = true;
5837
6175
  frame.metricsMeasure = started.measure;
@@ -5839,12 +6177,17 @@ var createExecutionRecorder = (options, hooks = {}) => {
5839
6177
  frame.metricsExecutionHandle = executionHandle;
5840
6178
  frame.metricsStartedNs = started.startedNs;
5841
6179
  };
5842
- const activateUncaptured = (mode, recording, parentStore, plan, args, omitCallValues, parentCallId, startedAtNs, timed, group, captureDroppedThrow, selected) => {
6180
+ const activateUncaptured = (mode, recording, parentStore, plan, args, omitCallValues, parentCallId, startedAtNs, timed, group, captureDroppedThrow, selected, policy = EMPTY_POLICY, sessionExcluded = false) => {
6181
+ const activeStore = sessionExcluded ? {
6182
+ ...parentStore,
6183
+ sessionSuppressCapture: true,
6184
+ ...trackCallers ? { currentFunctionId: plan.functionId } : {}
6185
+ } : parentStore;
5843
6186
  const frame = new CallFrame(
5844
6187
  mode,
5845
6188
  recording,
5846
6189
  parentStore,
5847
- parentStore,
6190
+ activeStore,
5848
6191
  plan,
5849
6192
  args,
5850
6193
  omitCallValues,
@@ -5856,8 +6199,9 @@ var createExecutionRecorder = (options, hooks = {}) => {
5856
6199
  captureDroppedThrow
5857
6200
  );
5858
6201
  frame.metricsSelected = selected;
6202
+ frame.policy = policy;
5859
6203
  frame.claimCaller();
5860
- enterStore(frame, parentStore);
6204
+ enterStore(frame, activeStore);
5861
6205
  armCallFrameMetrics(frame, plan);
5862
6206
  return frame;
5863
6207
  };
@@ -5899,7 +6243,11 @@ var createExecutionRecorder = (options, hooks = {}) => {
5899
6243
  stats.functionCallsExcluded++;
5900
6244
  const excludedDuration = plan.excluded ? { selected: false, measure: false } : planInvocationDuration(recording, plan, store.currentFunctionId);
5901
6245
  const start2 = invocationStart(excludedDuration.measure);
5902
- const excludedStore = { ...store, suppressCapture: true };
6246
+ const excludedStore = {
6247
+ ...store,
6248
+ suppressCapture: true,
6249
+ sessionSuppressCapture: true
6250
+ };
5903
6251
  const frame = new CallFrame(
5904
6252
  "excluded",
5905
6253
  recording,
@@ -5933,7 +6281,9 @@ var createExecutionRecorder = (options, hooks = {}) => {
5933
6281
  const timed = start.timed;
5934
6282
  const startedAtNs = start.startedAtNs;
5935
6283
  const parentStore = store;
5936
- const retainedArgs = recording.captureValues ? args : EMPTY_ARGS;
6284
+ const sessionExcluded = sessionExcludedFor(store, plan);
6285
+ const policy = capturePolicyFor(recording, store, plan, group.observedCalls);
6286
+ const retainedArgs = policy.ordinary || policy.sessionValues || recording.captureValues || policy.sessionId ? args : EMPTY_ARGS;
5937
6287
  if (group.observedCalls > capturedCallLimitFor(recording)) {
5938
6288
  return activateUncaptured(
5939
6289
  "suppressed",
@@ -5947,7 +6297,9 @@ var createExecutionRecorder = (options, hooks = {}) => {
5947
6297
  timed,
5948
6298
  group,
5949
6299
  false,
5950
- duration.selected
6300
+ duration.selected,
6301
+ policy,
6302
+ sessionExcluded
5951
6303
  );
5952
6304
  }
5953
6305
  if (!journal) {
@@ -5964,7 +6316,9 @@ var createExecutionRecorder = (options, hooks = {}) => {
5964
6316
  timed,
5965
6317
  group,
5966
6318
  false,
5967
- duration.selected
6319
+ duration.selected,
6320
+ policy,
6321
+ sessionExcluded
5968
6322
  );
5969
6323
  }
5970
6324
  if (!journal.canStartCall()) {
@@ -5980,7 +6334,9 @@ var createExecutionRecorder = (options, hooks = {}) => {
5980
6334
  timed,
5981
6335
  group,
5982
6336
  true,
5983
- duration.selected
6337
+ duration.selected,
6338
+ policy,
6339
+ sessionExcluded
5984
6340
  );
5985
6341
  }
5986
6342
  if (!memoryBudget.reserveCall(recording.memory, plan.estimatedCallBytes)) {
@@ -5996,12 +6352,14 @@ var createExecutionRecorder = (options, hooks = {}) => {
5996
6352
  timed,
5997
6353
  group,
5998
6354
  false,
5999
- duration.selected
6355
+ duration.selected,
6356
+ policy,
6357
+ sessionExcluded
6000
6358
  );
6001
6359
  }
6002
6360
  const callId = ++recording.nextCallId;
6003
6361
  const enterTimestampNs = timed ? startedAtNs - recording.startedAtNs : TIMING_UNAVAILABLE;
6004
- const capturedArgs = enterPayload(recording, omitCallValues, args);
6362
+ const capturedArgs = enterPayload(recording, omitCallValues, args, policy);
6005
6363
  try {
6006
6364
  journal.startCall(plan.runtimePlanId, callId, parentCallId, enterTimestampNs, capturedArgs);
6007
6365
  } catch {
@@ -6018,10 +6376,12 @@ var createExecutionRecorder = (options, hooks = {}) => {
6018
6376
  timed,
6019
6377
  group,
6020
6378
  false,
6021
- duration.selected
6379
+ duration.selected,
6380
+ policy,
6381
+ sessionExcluded
6022
6382
  );
6023
6383
  }
6024
- const callStore = callStoreFor(store, plan.functionId, callId);
6384
+ const callStore = callStoreFor(store, plan.functionId, callId, sessionExcluded);
6025
6385
  const captured = new CallFrame(
6026
6386
  "captured",
6027
6387
  recording,
@@ -6038,6 +6398,7 @@ var createExecutionRecorder = (options, hooks = {}) => {
6038
6398
  false
6039
6399
  );
6040
6400
  captured.metricsSelected = duration.selected;
6401
+ captured.policy = policy;
6041
6402
  enterStore(captured, callStore);
6042
6403
  armCallFrameMetrics(captured, plan);
6043
6404
  return captured;
@@ -6260,7 +6621,6 @@ var parseSessionSettings = (value) => {
6260
6621
  const redactKeys = optionalStringList(value.redactKeys);
6261
6622
  if (excludeSources) overrides.excludeSources = excludeSources;
6262
6623
  if (redactKeys) overrides.redactKeys = redactKeys;
6263
- if (typeof value.scrubPII === "boolean") overrides.scrubPII = value.scrubPII;
6264
6624
  return Object.keys(overrides).length > 0 ? overrides : void 0;
6265
6625
  };
6266
6626
  var clampSessionFreezeLimits = (overrides, processLimits) => ({
@@ -6305,7 +6665,7 @@ var serializeSourceExclusions = (exclusions) => {
6305
6665
  }
6306
6666
  return out.length > 0 ? out : void 0;
6307
6667
  };
6308
- var reportedRecorderSettings = (options, scrubPII) => ({
6668
+ var reportedRecorderSettings = (options) => ({
6309
6669
  maxDepth: options?.maxDepth,
6310
6670
  maxObjectKeys: options?.maxObjectKeys,
6311
6671
  maxArrayElements: options?.maxArrayElements,
@@ -6316,11 +6676,10 @@ var reportedRecorderSettings = (options, scrubPII) => ({
6316
6676
  maxActiveMemoryBytes: options?.maxActiveMemoryBytes,
6317
6677
  maxExecutionHoldMs: options?.maxExecutionHoldMs,
6318
6678
  maxRetainedErrorRecordings: options?.maxRetainedErrorRecordings,
6319
- fullCaptureDurationMs: options?.adaptive?.fullCaptureDurationMs,
6679
+ fullCaptureDurationMs: options?.dynamicFullCaptureDurationMs,
6320
6680
  recorder_enabled: options?.enabled !== false,
6321
6681
  excludeSources: serializeSourceExclusions(options?.excludeSources),
6322
- redactKeys: options?.redactKeys,
6323
- scrubPII: scrubPII === true
6682
+ redactKeys: options?.redactKeys
6324
6683
  });
6325
6684
  var createSerializerCache = (options) => {
6326
6685
  const processLimits = compileFreezeLimits(options ?? {});
@@ -6356,6 +6715,8 @@ var DEFAULT_POLL_INTERVAL_MS = 3e4;
6356
6715
  var REQUEST_TIMEOUT_MS2 = 5e3;
6357
6716
  var MAX_RETRIES = 5;
6358
6717
  var MAX_POLL_JITTER_MS = 2e3;
6718
+ var UPLOAD_GRACE_MS = 6e4;
6719
+ var MAX_RETAINED_SESSIONS = 256;
6359
6720
  var trimmed2 = (value) => typeof value === "string" ? value.trim() : "";
6360
6721
  var isRecord2 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
6361
6722
  var unwrapPayload = (body) => {
@@ -6377,16 +6738,17 @@ var abortFrom = (parent, child) => {
6377
6738
  };
6378
6739
  var createExecutionRecordingCoordinator = (options) => {
6379
6740
  const environment = options.environment;
6741
+ const mode = resolveExecutionRecordingMode(options.recorderOptions);
6380
6742
  const nowMs = () => options.nowMs?.() ?? Date.now();
6381
6743
  const fetchFn = options.fetch ?? defaultIngestFetch2();
6382
6744
  const instanceId = crypto.randomUUID();
6383
6745
  const startedAt = /* @__PURE__ */ new Date();
6384
6746
  const redactKeys = copyRedactKeys(options.recorderOptions?.redactKeys);
6385
- const scrubPii = options.scrubPII === true;
6386
6747
  const serializers = createSerializerCache(options.recorderOptions);
6387
6748
  const cache = /* @__PURE__ */ new Map();
6388
6749
  const pending = /* @__PURE__ */ new Map();
6389
6750
  const sessionsById = /* @__PURE__ */ new Map();
6751
+ const retainedById = /* @__PURE__ */ new Map();
6390
6752
  const completedSessionIds = /* @__PURE__ */ new Set();
6391
6753
  const recordings = [];
6392
6754
  const capabilities = ["manual_sessions", "settings_overrides"];
@@ -6433,10 +6795,29 @@ var createExecutionRecordingCoordinator = (options) => {
6433
6795
  redactKeys: session.redactKeys,
6434
6796
  excludeSources: session.excludeSources,
6435
6797
  maxCapturedCallsPerFunction: session.maxCapturedCallsPerFunction,
6436
- maxExecutionHoldMs: session.maxExecutionHoldMs,
6437
- scrubPII: session.scrubPII
6798
+ maxExecutionHoldMs: session.maxExecutionHoldMs
6438
6799
  });
6439
6800
  const sessionHasRoom = (session, atMs) => session.admitted < session.requestedCount && session.expiresAtMs > atMs;
6801
+ const withinUploadGrace = (session, atMs) => atMs <= session.expiresAtMs + UPLOAD_GRACE_MS;
6802
+ const pruneRetained = (atMs) => {
6803
+ for (const [id, session] of retainedById) {
6804
+ if (completedSessionIds.has(id) || session.admitted >= session.requestedCount || !withinUploadGrace(session, atMs)) {
6805
+ retainedById.delete(id);
6806
+ }
6807
+ }
6808
+ while (retainedById.size > MAX_RETAINED_SESSIONS) {
6809
+ let oldestId;
6810
+ let oldestExpires = Number.POSITIVE_INFINITY;
6811
+ for (const [id, session] of retainedById) {
6812
+ if (session.expiresAtMs < oldestExpires) {
6813
+ oldestExpires = session.expiresAtMs;
6814
+ oldestId = id;
6815
+ }
6816
+ }
6817
+ if (oldestId === void 0) break;
6818
+ retainedById.delete(oldestId);
6819
+ }
6820
+ };
6440
6821
  const rebuildSessionSnapshot = () => {
6441
6822
  const atMs = nowMs();
6442
6823
  const map = /* @__PURE__ */ new Map();
@@ -6630,7 +7011,7 @@ var createExecutionRecordingCoordinator = (options) => {
6630
7011
  }
6631
7012
  };
6632
7013
  const kickNotify = () => {
6633
- if (closed || closing || pending.size === 0 || options.mode !== "adaptive") return;
7014
+ if (closed || closing || pending.size === 0 || mode !== "adaptive") return;
6634
7015
  void drainNotifies(notifySignal());
6635
7016
  };
6636
7017
  const applyCompletedSessionIds = (value) => {
@@ -6640,6 +7021,7 @@ var createExecutionRecordingCoordinator = (options) => {
6640
7021
  if (!sessionId) continue;
6641
7022
  completedSessionIds.add(sessionId);
6642
7023
  sessionsById.delete(sessionId);
7024
+ retainedById.delete(sessionId);
6643
7025
  }
6644
7026
  markSessionsDirty();
6645
7027
  };
@@ -6657,7 +7039,7 @@ var createExecutionRecordingCoordinator = (options) => {
6657
7039
  if (!sessionId || !executionKeyValue || status !== "active") continue;
6658
7040
  if (completedSessionIds.has(sessionId)) continue;
6659
7041
  if (!Number.isFinite(expiresAtMs) || expiresAtMs <= atMs || requestedCount < 1) continue;
6660
- const existing = sessionsById.get(sessionId);
7042
+ const existing = sessionsById.get(sessionId) ?? retainedById.get(sessionId);
6661
7043
  const overrides = parseSessionSettings(entry.overrides);
6662
7044
  next.set(sessionId, {
6663
7045
  sessionId,
@@ -6669,12 +7051,22 @@ var createExecutionRecordingCoordinator = (options) => {
6669
7051
  redactKeys: overrides?.redactKeys,
6670
7052
  excludeSources: overrides?.excludeSources,
6671
7053
  maxCapturedCallsPerFunction: overrides?.maxCapturedCallsPerFunction,
6672
- maxExecutionHoldMs: overrides?.maxExecutionHoldMs,
6673
- scrubPII: overrides?.scrubPII
7054
+ maxExecutionHoldMs: overrides?.maxExecutionHoldMs
6674
7055
  });
6675
7056
  }
7057
+ for (const [id, existing] of sessionsById) {
7058
+ if (next.has(id) || completedSessionIds.has(id)) continue;
7059
+ if (existing.expiresAtMs > atMs) continue;
7060
+ if (existing.admitted >= existing.requestedCount) continue;
7061
+ if (!withinUploadGrace(existing, atMs)) continue;
7062
+ retainedById.set(id, existing);
7063
+ }
7064
+ for (const id of [...retainedById.keys()]) {
7065
+ if (next.has(id) || completedSessionIds.has(id)) retainedById.delete(id);
7066
+ }
6676
7067
  sessionsById.clear();
6677
7068
  for (const [id, session] of next) sessionsById.set(id, session);
7069
+ pruneRetained(atMs);
6678
7070
  markSessionsDirty();
6679
7071
  };
6680
7072
  const applyActivations = (activations) => {
@@ -6706,8 +7098,8 @@ var createExecutionRecordingCoordinator = (options) => {
6706
7098
  release: options.release,
6707
7099
  pid: process.pid,
6708
7100
  started_at: startedAt.toISOString(),
6709
- reported_mode: options.mode,
6710
- reported_settings: reportedRecorderSettings(options.recorderOptions, options.scrubPII),
7101
+ reported_mode: mode,
7102
+ reported_settings: reportedRecorderSettings(options.recorderOptions),
6711
7103
  capabilities
6712
7104
  }
6713
7105
  },
@@ -6766,8 +7158,7 @@ var createExecutionRecordingCoordinator = (options) => {
6766
7158
  redact_keys: copyRedactKeys([
6767
7159
  ...redactKeys ?? [],
6768
7160
  ...item.redactKeys ?? []
6769
- ])?.slice(0, MAX_REDACT_KEYS),
6770
- scrub_pii: item.scrubPii ?? scrubPii
7161
+ ])?.slice(0, MAX_REDACT_KEYS)
6771
7162
  }))
6772
7163
  },
6773
7164
  void 0,
@@ -6843,7 +7234,7 @@ var createExecutionRecordingCoordinator = (options) => {
6843
7234
  });
6844
7235
  };
6845
7236
  const activate = (metadata, window) => {
6846
- if (closed || options.mode !== "adaptive") return;
7237
+ if (closed || mode !== "adaptive") return;
6847
7238
  const key = executionTypeKey(metadata);
6848
7239
  if (!key) return;
6849
7240
  const atMs = nowMs();
@@ -6878,11 +7269,15 @@ var createExecutionRecordingCoordinator = (options) => {
6878
7269
  };
6879
7270
  const consumeSession = (executionKeyValue, sessionId) => {
6880
7271
  const atMs = nowMs();
6881
- for (const session of sessionsById.values()) {
7272
+ pruneRetained(atMs);
7273
+ const candidates = [...sessionsById.values(), ...retainedById.values()];
7274
+ for (const session of candidates) {
6882
7275
  if (session.executionKey !== executionKeyValue) continue;
6883
7276
  if (sessionId !== void 0 && session.sessionId !== sessionId) continue;
6884
- if (!sessionHasRoom(session, atMs)) continue;
7277
+ if (session.admitted >= session.requestedCount) continue;
7278
+ if (!withinUploadGrace(session, atMs)) continue;
6885
7279
  session.admitted += 1;
7280
+ if (session.admitted >= session.requestedCount) retainedById.delete(session.sessionId);
6886
7281
  markSessionsDirty();
6887
7282
  return sessionView(session);
6888
7283
  }
@@ -6963,6 +7358,7 @@ var createExecutionRecordingCoordinator = (options) => {
6963
7358
  closed = true;
6964
7359
  interruptWork();
6965
7360
  pending.clear();
7361
+ retainedById.clear();
6966
7362
  }
6967
7363
  }
6968
7364
  };
@@ -6971,7 +7367,7 @@ var createExecutionRecordingCoordinator = (options) => {
6971
7367
  // src/execution-recorder/bind-adaptive-recorder.ts
6972
7368
  var bindAdaptiveRecorder = (input) => {
6973
7369
  const options = input.executionRecorder;
6974
- const adaptiveEnabled = options?.adaptive?.enabled === true;
7370
+ const adaptiveEnabled = resolveExecutionRecordingMode(options) === "adaptive";
6975
7371
  const activation = resolveClientActivation({
6976
7372
  enabled: input.enabled,
6977
7373
  dsn: input.dsn,
@@ -6990,8 +7386,6 @@ var bindAdaptiveRecorder = (input) => {
6990
7386
  sdkVersion: input.sdkVersion,
6991
7387
  release: activation.release,
6992
7388
  recorderOptions: options,
6993
- scrubPII: input.scrubPII,
6994
- mode: adaptiveEnabled ? "adaptive" : "full",
6995
7389
  fetch: input.fetch
6996
7390
  }) : void 0;
6997
7391
  const recorderHooks = {};
@@ -7387,11 +7781,26 @@ var createFunctionMetricsCollector = (options) => {
7387
7781
  note2(coverage, "dropped_queue_budget", discardedMarks2(dropped.series));
7388
7782
  }
7389
7783
  };
7784
+ const markedSeries = (table) => {
7785
+ const marked = /* @__PURE__ */ new Map();
7786
+ for (const [functionHandle, byExecution] of table) {
7787
+ const copied = /* @__PURE__ */ new Map();
7788
+ for (const [executionHandle, series] of byExecution) {
7789
+ if (seriesHasMarks2(series)) copied.set(executionHandle, series);
7790
+ }
7791
+ if (copied.size > 0) marked.set(functionHandle, copied);
7792
+ }
7793
+ return marked;
7794
+ };
7390
7795
  const closeMinute = (minute, table) => {
7391
7796
  active.delete(minute);
7392
7797
  activeSeries -= countSeries2(table);
7393
7798
  if (minute > lastClosedMinute) lastClosedMinute = minute;
7394
- appendQueue({ minute, series: table, bytes: tableBytes2(table) });
7799
+ const marked = markedSeries(table);
7800
+ const markedBytes = tableBytes2(marked);
7801
+ stateBytes -= tableBytes2(table) - markedBytes;
7802
+ if (stateBytes < 0) stateBytes = 0;
7803
+ appendQueue({ minute, series: marked, bytes: markedBytes });
7395
7804
  };
7396
7805
  const rotate = (currentMinute) => {
7397
7806
  for (const minute of [...active.keys()]) {
@@ -8278,81 +8687,104 @@ var createDynamicDurationSampleBuckets = (options) => {
8278
8687
  };
8279
8688
  };
8280
8689
 
8281
- // src/sdk-meta.ts
8282
- var SDK_NAME = "@rasputin-ai/node";
8283
- var SDK_VERSION = "0.15.1";
8284
-
8285
- // src/rasputin-init.ts
8690
+ // src/create-rasputin-runtime.ts
8286
8691
  var publicExecution = (runtime) => ({
8287
8692
  createScope: (metadata) => {
8288
8693
  const scope = runtime.createScope(metadata);
8289
8694
  return {
8290
8695
  run: scope.run,
8291
8696
  observeError: scope.observeError,
8292
- finish: scope.finish
8697
+ finish: scope.finish,
8698
+ captureInput: scope.captureInput
8293
8699
  };
8294
8700
  },
8295
8701
  trace: runtime.trace,
8296
8702
  getStats: runtime.getStats
8297
8703
  });
8298
- var withExecution = (client, runtime, installRuntime, manifest, uninstallHandlers = () => {
8704
+ var wrapClient = (client, runtime, installRuntime, manifest, uninstallHandlers = () => {
8299
8705
  }, policy, metrics, executionMetrics) => {
8300
8706
  const uninstallRuntime = installRuntime ? installAutomaticExecutionRuntime(runtime) : () => {
8301
8707
  };
8302
- const manifestUpload = scheduleInstrumentationManifestUpload(manifest);
8708
+ const manifestUpload = scheduleInstrumentationManifestUpload({
8709
+ ...manifest,
8710
+ deferStart: true
8711
+ });
8303
8712
  const execution = publicExecution(runtime);
8304
8713
  return {
8305
- ...client,
8306
- execution,
8307
- getStats: () => ({ ...client.getStats(), recorder: execution.getStats() }),
8308
- verifyConfiguration: manifestUpload.verify,
8309
- captureException: (error, context) => {
8310
- const result = client.captureException(error, context);
8311
- manifestUpload.flushSoon();
8312
- return result;
8313
- },
8314
- flush: async (timeoutMs) => {
8315
- const startedAt = Date.now();
8316
- await client.flush(timeoutMs);
8317
- if (timeoutMs === void 0) {
8318
- await policy?.flush();
8319
- await metrics?.exporter.flush();
8320
- await executionMetrics?.exporter.flush();
8321
- await manifestUpload.wait();
8322
- return;
8714
+ client: {
8715
+ ...client,
8716
+ execution,
8717
+ getStats: () => ({ ...client.getStats(), recorder: execution.getStats() }),
8718
+ verifyConfiguration: manifestUpload.verify,
8719
+ captureException: (error, context) => {
8720
+ const result = client.captureException(error, context);
8721
+ manifestUpload.flushSoon();
8722
+ return result;
8723
+ },
8724
+ flush: async (timeoutMs) => {
8725
+ const startedAt = Date.now();
8726
+ await client.flush(timeoutMs);
8727
+ if (timeoutMs === void 0) {
8728
+ await policy?.flush();
8729
+ await metrics?.exporter.flush();
8730
+ await executionMetrics?.exporter.flush();
8731
+ await manifestUpload.wait();
8732
+ return;
8733
+ }
8734
+ await policy?.flush(Math.max(0, timeoutMs - (Date.now() - startedAt)));
8735
+ await metrics?.exporter.flush(Math.max(0, timeoutMs - (Date.now() - startedAt)));
8736
+ await executionMetrics?.exporter.flush(Math.max(0, timeoutMs - (Date.now() - startedAt)));
8737
+ await manifestUpload.wait(Math.max(0, timeoutMs - (Date.now() - startedAt)));
8738
+ },
8739
+ close: async () => {
8740
+ uninstallHandlers();
8741
+ uninstallRuntime();
8742
+ runtime.close();
8743
+ manifestUpload.disconnect();
8744
+ const startedAt = Date.now();
8745
+ await policy?.close();
8746
+ await releaseFunctionMetricsBindings(metrics);
8747
+ await releaseExecutionMetricsBindings(executionMetrics);
8748
+ await client.close();
8749
+ await manifestUpload.wait(Math.max(0, 2e3 - (Date.now() - startedAt)));
8323
8750
  }
8324
- await policy?.flush(Math.max(0, timeoutMs - (Date.now() - startedAt)));
8325
- await metrics?.exporter.flush(Math.max(0, timeoutMs - (Date.now() - startedAt)));
8326
- await executionMetrics?.exporter.flush(Math.max(0, timeoutMs - (Date.now() - startedAt)));
8327
- await manifestUpload.wait(Math.max(0, timeoutMs - (Date.now() - startedAt)));
8328
8751
  },
8329
- close: async () => {
8330
- uninstallHandlers();
8331
- uninstallRuntime();
8332
- runtime.close();
8333
- manifestUpload.disconnect();
8334
- const startedAt = Date.now();
8335
- await policy?.close();
8336
- await releaseFunctionMetricsBindings(metrics);
8337
- await releaseExecutionMetricsBindings(executionMetrics);
8338
- await client.close();
8339
- await manifestUpload.wait(Math.max(0, 2e3 - (Date.now() - startedAt)));
8752
+ startManifestUpload: manifestUpload.start
8753
+ };
8754
+ };
8755
+ var inertHandle = (options) => {
8756
+ const runtime = createExecutionRecorder({ enabled: false });
8757
+ const { client } = wrapClient(createClient({ ...options, enabled: false }), runtime, false, {
8758
+ projectApiKey: options.projectApiKey,
8759
+ release: options.release,
8760
+ apiUrl: options.apiUrl,
8761
+ enabled: false,
8762
+ sourceRoot: options.sourceRoot,
8763
+ sourceRoots: options.sourceRoots,
8764
+ logSuccess: options.logSuccess
8765
+ });
8766
+ return {
8767
+ client,
8768
+ runtime,
8769
+ observeExecutions: false,
8770
+ startStartupWork: () => {
8340
8771
  }
8341
8772
  };
8342
8773
  };
8343
- function RasputinInit(options, hooks = {}) {
8774
+ var createRasputinRuntime = (options, config) => {
8344
8775
  try {
8345
8776
  const enabled = isClientEnabled(options);
8346
8777
  const activation = resolveClientActivation2(options);
8347
8778
  const recorderEnabled = enabled && options.executionRecorder?.enabled !== false;
8348
8779
  const durationSampling = options.dynamicDurationSampling === true;
8780
+ const fetch = config.fetch;
8349
8781
  const metrics = activation.enabled ? bindFunctionMetrics({
8350
8782
  clientEnabled: true,
8351
8783
  environment: activation.environment,
8352
8784
  release: activation.release,
8353
8785
  ingestToken: activation.ingestToken,
8354
8786
  apiUrl: activation.apiUrl,
8355
- fetch: hooks.fetch,
8787
+ fetch,
8356
8788
  sampledMeasurementFormat: durationSampling
8357
8789
  }) : void 0;
8358
8790
  const executionMetrics = activation.enabled ? bindExecutionMetrics({
@@ -8361,7 +8793,7 @@ function RasputinInit(options, hooks = {}) {
8361
8793
  release: activation.release,
8362
8794
  ingestToken: activation.ingestToken,
8363
8795
  apiUrl: activation.apiUrl,
8364
- fetch: hooks.fetch,
8796
+ fetch,
8365
8797
  sampledMeasurementFormat: durationSampling
8366
8798
  }) : void 0;
8367
8799
  const observeExecutions = recorderEnabled || Boolean(metrics) || Boolean(executionMetrics);
@@ -8375,19 +8807,19 @@ function RasputinInit(options, hooks = {}) {
8375
8807
  release: options.release,
8376
8808
  environment: options.environment,
8377
8809
  enabled: options.enabled,
8378
- sdkName: SDK_NAME,
8379
- sdkVersion: SDK_VERSION,
8380
- scrubPII: options.scrubPII,
8381
- fetch: hooks.fetch,
8810
+ sdkName: config.sdkName,
8811
+ sdkVersion: config.sdkVersion,
8812
+ fetch,
8382
8813
  functionMetrics: metrics?.collector,
8383
8814
  executionMetrics: executionMetrics?.collector,
8384
8815
  durationSampler
8385
8816
  });
8386
8817
  const client = createClient(options, {
8387
- sdkVersion: SDK_VERSION,
8388
- sdkName: SDK_NAME,
8389
- fetch: hooks.fetch,
8390
- installTransportSignalHandlers: options.installTransportSignalHandlers,
8818
+ sdkVersion: config.sdkVersion,
8819
+ sdkName: config.sdkName,
8820
+ fetch,
8821
+ announceDeploy: false,
8822
+ installTransportSignalHandlers: config.installTransportSignalHandlers ?? options.installTransportSignalHandlers,
8391
8823
  redactKeys: copyRedactKeys2(options.executionRecorder?.redactKeys),
8392
8824
  resolveObservation: (observation) => runtime.getErrorState(observation)
8393
8825
  });
@@ -8398,7 +8830,7 @@ function RasputinInit(options, hooks = {}) {
8398
8830
  }
8399
8831
  let uninstallHandlers = () => {
8400
8832
  };
8401
- const wrappedClient = withExecution(
8833
+ const { client: wrappedClient, startManifestUpload } = wrapClient(
8402
8834
  client,
8403
8835
  runtime,
8404
8836
  observeExecutions,
@@ -8406,6 +8838,7 @@ function RasputinInit(options, hooks = {}) {
8406
8838
  projectApiKey: options.projectApiKey,
8407
8839
  release: options.release,
8408
8840
  apiUrl: options.apiUrl,
8841
+ fetch,
8409
8842
  enabled,
8410
8843
  sourceRoot: options.sourceRoot,
8411
8844
  sourceRoots: options.sourceRoots,
@@ -8416,26 +8849,49 @@ function RasputinInit(options, hooks = {}) {
8416
8849
  metrics,
8417
8850
  executionMetrics
8418
8851
  );
8419
- if (enabled && options.installGlobalHandlers !== false) {
8852
+ const installProcessHandlers = (config.installGlobalHandlers ?? options.installGlobalHandlers) !== false;
8853
+ if (enabled && installProcessHandlers) {
8420
8854
  uninstallHandlers = installGlobalHandlers(wrappedClient);
8421
8855
  }
8422
- return wrappedClient;
8856
+ let started = false;
8857
+ const startStartupWork = () => {
8858
+ if (started) return;
8859
+ started = true;
8860
+ startManifestUpload();
8861
+ if (!enabled || config.announceDeploy === false || !activation.enabled) return;
8862
+ scheduleAnnounceDeploy({
8863
+ deployUrl: resolveEndpointUrls5(activation.apiUrl).deployUrl,
8864
+ projectApiKey: activation.projectApiKey,
8865
+ environment: activation.environment,
8866
+ release: activation.release,
8867
+ fetch
8868
+ });
8869
+ };
8870
+ if (!config.deferStartupWork) startStartupWork();
8871
+ return {
8872
+ client: wrappedClient,
8873
+ runtime,
8874
+ observeExecutions,
8875
+ startStartupWork
8876
+ };
8423
8877
  } catch {
8424
- return withExecution(
8425
- createClient({ ...options, enabled: false }),
8426
- createExecutionRecorder({ enabled: false }),
8427
- false,
8428
- {
8429
- projectApiKey: options.projectApiKey,
8430
- release: options.release,
8431
- apiUrl: options.apiUrl,
8432
- enabled: false,
8433
- sourceRoot: options.sourceRoot,
8434
- sourceRoots: options.sourceRoots,
8435
- logSuccess: options.logSuccess
8436
- }
8437
- );
8878
+ return inertHandle(options);
8438
8879
  }
8880
+ };
8881
+
8882
+ // src/sdk-meta.ts
8883
+ var SDK_NAME = "@rasputin-ai/node";
8884
+ var SDK_VERSION = "1.0.0";
8885
+
8886
+ // src/rasputin-init.ts
8887
+ function RasputinInit(options, hooks = {}) {
8888
+ return createRasputinRuntime(options, {
8889
+ sdkName: SDK_NAME,
8890
+ sdkVersion: SDK_VERSION,
8891
+ fetch: hooks.fetch,
8892
+ installGlobalHandlers: options.installGlobalHandlers,
8893
+ installTransportSignalHandlers: options.installTransportSignalHandlers
8894
+ }).client;
8439
8895
  }
8440
8896
  export {
8441
8897
  RasputinInit