@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/internal.js CHANGED
@@ -121,10 +121,11 @@ var runtimeLabel = () => {
121
121
  };
122
122
 
123
123
  // src/auto-instrumentation/instrumentation-manifest-registry.ts
124
- import { createHash } from "node:crypto";
124
+ import { existsSync, readFileSync } from "node:fs";
125
125
  import {
126
126
  INSTRUMENTATION_MANIFEST_SCHEMA_VERSION,
127
- sourceLocatorFromFile as sourceLocatorFromFile2
127
+ sourceLocatorFromFile as sourceLocatorFromFile2,
128
+ sourceLocatorKey
128
129
  } from "@rasputin-ai/core";
129
130
 
130
131
  // ../recorder/src/run-exactly-once.ts
@@ -241,7 +242,7 @@ var getAutomaticRuntimeRegistry = () => {
241
242
  };
242
243
 
243
244
  // src/auto-instrumentation/instrumentation-manifest-registry.ts
244
- var INSTRUMENTATION_MANIFEST_SYMBOL = "rasputin.instrumentation.manifest.v3";
245
+ var INSTRUMENTATION_MANIFEST_SYMBOL = "rasputin.instrumentation.manifest.v4";
245
246
  var registrySymbol = Symbol.for(INSTRUMENTATION_MANIFEST_SYMBOL);
246
247
  var getRegistry = () => {
247
248
  const existing = Reflect.get(globalThis, registrySymbol);
@@ -260,11 +261,37 @@ var getRegistry = () => {
260
261
  Reflect.set(globalThis, registrySymbol, registry);
261
262
  return registry;
262
263
  };
263
- var sourceAt = (filePath, line, column) => {
264
- const source = sourceLocatorFromFile2(filePath);
265
- return source ? { ...source, line, column } : void 0;
264
+ var rememberSource = (sources, source) => {
265
+ const key = sourceLocatorKey(source);
266
+ const previous = sources.get(key);
267
+ sources.set(key, {
268
+ ...previous,
269
+ packageRelativePath: source.packageRelativePath,
270
+ ...source.packageName ? { packageName: source.packageName } : previous?.packageName ? { packageName: previous.packageName } : {},
271
+ ...source.repositoryPath ? { repositoryPath: source.repositoryPath } : previous?.repositoryPath ? { repositoryPath: previous.repositoryPath } : {}
272
+ });
273
+ };
274
+ var recordPrebuiltInstrumentationManifest = (manifest) => {
275
+ const registry = getRegistry();
276
+ registry.prebuilt = manifest;
277
+ registry.generation += 1;
278
+ registry.onDirty?.();
279
+ };
280
+ var loadInstrumentationManifestFile = (path) => {
281
+ try {
282
+ const parsed = JSON.parse(readFileSync(path, "utf8"));
283
+ if (parsed.schema_version !== INSTRUMENTATION_MANIFEST_SCHEMA_VERSION) return false;
284
+ if (!Array.isArray(parsed.sources)) return false;
285
+ recordPrebuiltInstrumentationManifest(parsed);
286
+ return true;
287
+ } catch {
288
+ return false;
289
+ }
290
+ };
291
+ var loadInstrumentationManifestIfPresent = (path) => {
292
+ if (!path || !existsSync(path)) return;
293
+ loadInstrumentationManifestFile(path);
266
294
  };
267
- var stableId = (kind, ...parts) => `${kind}_${createHash("sha256").update(parts.join("\0")).digest("base64url").slice(0, 24)}`;
268
295
  var isInstrumentationManifestDirty = () => {
269
296
  const registry = getRegistry();
270
297
  return registry.generation !== registry.uploadedGeneration && (registry.files.size > 0 || registry.prebuilt !== void 0);
@@ -300,7 +327,7 @@ var instrumentationManifestModuleCount = () => {
300
327
  const registry = getRegistry();
301
328
  if (registry.files.size > 0) return registry.files.size;
302
329
  if (!registry.prebuilt) return 0;
303
- return new Set(registry.prebuilt.functions.map((fn) => fn.source.packageRelativePath)).size;
330
+ return registry.prebuilt.sources.length;
304
331
  };
305
332
  var snapshotOptionsKey = (options) => JSON.stringify({
306
333
  sourceRoot: options.sourceRoot ?? "",
@@ -312,12 +339,8 @@ var snapshotInstrumentationManifest = (options = {}) => {
312
339
  if (registry.snapshotCache && registry.snapshotCache.generation === registry.generation && registry.snapshotCache.optionsKey === optionsKey) {
313
340
  return registry.snapshotCache.manifest;
314
341
  }
315
- const functions = new Map(
316
- registry.prebuilt?.functions.map((fn) => [fn.functionId, fn])
317
- );
318
- const callSites = new Map(
319
- registry.prebuilt?.callSites.map((site) => [site.id, site])
320
- );
342
+ const sources = /* @__PURE__ */ new Map();
343
+ for (const source of registry.prebuilt?.sources ?? []) rememberSource(sources, source);
321
344
  const remember = (manifest) => {
322
345
  registry.snapshotCache = {
323
346
  generation: registry.generation,
@@ -326,53 +349,21 @@ var snapshotInstrumentationManifest = (options = {}) => {
326
349
  };
327
350
  return manifest;
328
351
  };
329
- for (const delta of registry.files.values()) {
352
+ for (const [filePath, delta] of registry.files) {
353
+ let recorded = false;
330
354
  for (const fn of delta.functions) {
331
355
  const definition = definitionFromEncodedPlan(fn.plan);
332
356
  if (!definition.source) continue;
333
- if (!fn.metricsDeclaration) {
334
- throw new Error(`Missing function metrics declaration: ${fn.functionId}`);
335
- }
336
- functions.set(definition.functionId, {
337
- ...functions.get(definition.functionId),
338
- functionId: definition.functionId,
339
- source: {
340
- packageRelativePath: definition.source.packageRelativePath,
341
- ...definition.source.packageName ? { packageName: definition.source.packageName } : {},
342
- ...definition.source.repositoryPath ? { repositoryPath: definition.source.repositoryPath } : {}
343
- },
344
- name: fn.name,
345
- startLine: fn.startLine,
346
- startColumn: fn.startColumn,
347
- endLine: fn.endLine,
348
- endColumn: fn.endColumn,
349
- metricsDeclaration: fn.metricsDeclaration,
350
- ...fn.instrumented === false ? { instrumented: false, skipReason: fn.skipReason } : {}
351
- });
352
- }
353
- for (const site of delta.callSites) {
354
- const source = sourceAt(site.filePath, site.line, site.column);
355
- if (!source) continue;
356
- const id = stableId(
357
- "cs",
358
- site.callerFunctionId,
359
- source.packageName ?? "",
360
- source.packageRelativePath,
361
- site.line,
362
- site.column
363
- );
364
- callSites.set(id, {
365
- id,
366
- callerFunctionId: site.callerFunctionId,
367
- calleeName: site.calleeName,
368
- calleeText: site.calleeText,
369
- line: site.line,
370
- column: site.column,
371
- endLine: site.endLine,
372
- endColumn: site.endColumn,
373
- resultBinding: site.resultBinding
357
+ rememberSource(sources, {
358
+ packageRelativePath: definition.source.packageRelativePath,
359
+ ...definition.source.packageName ? { packageName: definition.source.packageName } : {},
360
+ ...definition.source.repositoryPath ? { repositoryPath: definition.source.repositoryPath } : {}
374
361
  });
362
+ recorded = true;
375
363
  }
364
+ if (recorded) continue;
365
+ const locator = sourceLocatorFromFile2(filePath);
366
+ if (locator) rememberSource(sources, locator);
376
367
  }
377
368
  if (registry.prebuilt && registry.files.size === 0) {
378
369
  if (!options.sourceRoot && !options.sourceRoots) return remember(registry.prebuilt);
@@ -384,9 +375,7 @@ var snapshotInstrumentationManifest = (options = {}) => {
384
375
  }
385
376
  });
386
377
  }
387
- if (functions.size === 0 && callSites.size === 0) {
388
- return remember(void 0);
389
- }
378
+ if (sources.size === 0) return remember(void 0);
390
379
  const packages = { ...registry.prebuilt?.sourceRoots?.packages, ...options.sourceRoots };
391
380
  const sourceRoot = options.sourceRoot ?? registry.prebuilt?.sourceRoots?.default;
392
381
  return remember({
@@ -397,8 +386,7 @@ var snapshotInstrumentationManifest = (options = {}) => {
397
386
  packages
398
387
  }
399
388
  } : {},
400
- functions: [...functions.values()],
401
- callSites: [...callSites.values()]
389
+ sources: [...sources.values()]
402
390
  });
403
391
  };
404
392
  var collectParamsByFunctionId = () => {
@@ -469,17 +457,21 @@ var scheduleInstrumentationManifestUpload = (options) => {
469
457
  const maxAttempts = 5;
470
458
  const packageNamesOf = (manifest) => [
471
459
  ...new Set(
472
- manifest.functions.map((fn) => fn.source.packageName).filter((name) => Boolean(name))
460
+ manifest.sources.map((source) => source.packageName).filter((name) => Boolean(name))
473
461
  )
474
462
  ].sort();
475
463
  const report = (manifest, uploaded, next) => {
476
464
  const coverage = instrumentationCoverageStats();
465
+ const skippedFunctions = Object.values(coverage.skippedByReason).reduce(
466
+ (total, count) => total + count,
467
+ 0
468
+ );
477
469
  return formatConfigurationReport({
478
470
  release,
479
471
  runtime: runtimeLabel(),
480
472
  modules: instrumentationManifestModuleCount(),
481
- functions: manifest.functions.filter((fn) => fn.instrumented !== false).length,
482
- skippedFunctions: manifest.functions.filter((fn) => fn.instrumented === false).length,
473
+ functions: coverage.instrumented,
474
+ skippedFunctions,
483
475
  instrumentedAsync: coverage.instrumentedAsync,
484
476
  skippedByReason: coverage.skippedByReason,
485
477
  packageNames: packageNamesOf(manifest),
@@ -647,6 +639,17 @@ var scheduleInstrumentationManifestUpload = (options) => {
647
639
  };
648
640
  };
649
641
 
642
+ // src/create-rasputin-runtime.ts
643
+ import { join } from "node:path";
644
+ import {
645
+ copyRedactKeys as copyRedactKeys2,
646
+ createClient,
647
+ isClientEnabled,
648
+ resolveClientActivation as resolveClientActivation2,
649
+ resolveEndpointUrls as resolveEndpointUrls5,
650
+ scheduleAnnounceDeploy
651
+ } from "@rasputin-ai/core";
652
+
650
653
  // src/execution-metrics/bind-execution-metrics.ts
651
654
  import { randomUUID as randomUUID2 } from "node:crypto";
652
655
  import {
@@ -911,6 +914,18 @@ var createExecutionMetricsCollector = (options) => {
911
914
  executionHandleByKey.set(key, handle);
912
915
  return handle;
913
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
+ });
914
929
  const ensureSeries = (minute, executionHandle) => {
915
930
  let byExecution = active.get(minute);
916
931
  if (!byExecution) {
@@ -924,18 +939,7 @@ var createExecutionMetricsCollector = (options) => {
924
939
  return void 0;
925
940
  }
926
941
  if (!reserve(SERIES_BYTES + HISTOGRAM_BYTES)) return void 0;
927
- const series = {
928
- started: 0,
929
- completed: 0,
930
- failed: 0,
931
- sampleCount: 0,
932
- sampleSumUs: 0,
933
- sampleMinUs: null,
934
- sampleMaxUs: null,
935
- invalidTiming: 0,
936
- histogram: new Uint32Array(FUNCTION_METRICS_HISTOGRAM_BUCKET_COUNT),
937
- bytes: SERIES_BYTES + HISTOGRAM_BYTES
938
- };
942
+ const series = newSeries();
939
943
  byExecution.set(executionHandle, series);
940
944
  activeSeries += 1;
941
945
  return series;
@@ -956,11 +960,22 @@ var createExecutionMetricsCollector = (options) => {
956
960
  note(coverage, "dropped_queue_budget", discardedMarks(dropped.series));
957
961
  }
958
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
+ };
959
970
  const closeMinute = (minute, table) => {
960
971
  active.delete(minute);
961
972
  activeSeries -= countSeries(table);
962
973
  if (minute > lastClosedMinute) lastClosedMinute = minute;
963
- 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 });
964
979
  };
965
980
  const rotate = (currentMinute2) => {
966
981
  for (const minute of [...active.keys()]) {
@@ -1000,6 +1015,63 @@ var createExecutionMetricsCollector = (options) => {
1000
1015
  }
1001
1016
  return minute;
1002
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
+ };
1003
1075
  const rememberSample = (series, durationUs, bucket) => {
1004
1076
  const sampleCount = series.sampleCount + 1;
1005
1077
  const sampleSumUs = series.sampleSumUs + durationUs;
@@ -1015,46 +1087,19 @@ var createExecutionMetricsCollector = (options) => {
1015
1087
  series.sampleMaxUs = series.sampleMaxUs === null ? durationUs : Math.max(series.sampleMaxUs, durationUs);
1016
1088
  return true;
1017
1089
  };
1018
- const rememberStart = (handle) => {
1019
- const minute = currentMinute(false);
1020
- if (minute === void 0) return false;
1021
- const series = ensureSeries(minute, handle);
1022
- if (!series) return false;
1023
- const started = series.started + 1;
1024
- if (!Number.isSafeInteger(started)) {
1025
- note(coverage, "dropped_unexportable");
1026
- return false;
1027
- }
1028
- series.started = started;
1029
- return true;
1030
- };
1031
- const bindIdentity = (state, key) => {
1032
- if (state.finished || state.dropped || state.handle !== void 0) return;
1033
- if (!key) return;
1034
- const handle = internExecutionKey(key);
1035
- if (handle === void 0) {
1036
- state.dropped = true;
1037
- return;
1038
- }
1039
- state.handle = handle;
1040
- if (state.started) return;
1041
- if (rememberStart(handle)) state.started = true;
1042
- };
1043
1090
  const finishExecution = (state, input) => {
1044
1091
  if (state.finished) return;
1045
1092
  state.finished = true;
1046
- if (state.dropped) return;
1047
- if (state.handle === void 0) {
1093
+ if (!input.key || !isCanonicalFunctionMetricsExecutionKey(input.key)) {
1048
1094
  note(coverage, "skipped_unresolved_execution_type");
1049
1095
  return;
1050
1096
  }
1051
- if (!state.started) {
1052
- if (!rememberStart(state.handle)) return;
1053
- state.started = true;
1054
- }
1055
- 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);
1056
1101
  if (minute === void 0) return;
1057
- const series = ensureSeries(minute, state.handle);
1102
+ const series = ensureSeries(minute, handle);
1058
1103
  if (!series) return;
1059
1104
  const completed = series.completed + 1;
1060
1105
  const failed = series.failed + (input.failed ? 1 : 0);
@@ -1120,10 +1165,9 @@ var createExecutionMetricsCollector = (options) => {
1120
1165
  };
1121
1166
  return {
1122
1167
  createState: () => ({
1123
- handle: void 0,
1124
- started: false,
1125
1168
  finished: false,
1126
- dropped: false
1169
+ started: false,
1170
+ startedMinute: Math.floor(clock.wallTimeMs() / FUNCTION_METRICS_MINUTE_MS)
1127
1171
  }),
1128
1172
  bindIdentity,
1129
1173
  finishExecution,
@@ -1232,15 +1276,39 @@ var minuteMarks = (minute) => {
1232
1276
  const next = minute.started_executions + minute.completed_executions;
1233
1277
  return Number.isSafeInteger(next) ? next : Number.MAX_SAFE_INTEGER;
1234
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
+ };
1235
1284
  var expiresAtMsFor = (batch, nowMs) => {
1236
- let oldest;
1285
+ let earliest;
1237
1286
  for (const start of batch.coverage.covered_bucket_starts) {
1238
- const bucket = parseFunctionMetricsBucketStart(start);
1239
- if (bucket === void 0) continue;
1240
- 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);
1241
1310
  }
1242
- if (oldest === void 0) return nowMs + FUNCTION_METRICS_BUCKET_LATENESS_MS;
1243
- return oldest + FUNCTION_METRICS_MINUTE_MS2 + FUNCTION_METRICS_BUCKET_LATENESS_MS;
1311
+ return { live, droppedLate };
1244
1312
  };
1245
1313
  var zeroLossCoverage = (coverage) => ({
1246
1314
  ...coverage,
@@ -1280,7 +1348,8 @@ var withLoss = (batch, loss) => ({
1280
1348
  coverage: {
1281
1349
  ...batch.coverage,
1282
1350
  dropped_unexportable: batch.coverage.dropped_unexportable + loss.dropped_unexportable,
1283
- 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
1284
1353
  }
1285
1354
  });
1286
1355
  var encodeOne = async (batch, nowMs, signal) => {
@@ -1323,11 +1392,30 @@ var encodeExecutionMetricsUploads = async (batches, input) => {
1323
1392
  const uploads = [];
1324
1393
  let extra = {
1325
1394
  dropped_unexportable: 0,
1326
- dropped_queue_budget: input.queueDrops ?? 0
1395
+ dropped_queue_budget: input.queueDrops ?? 0,
1396
+ dropped_late_completion: 0
1327
1397
  };
1328
1398
  for (const batch of batches) {
1329
- const fitted = await encodeFitting(withLoss(batch, extra), input.nowMs, input.signal);
1330
- 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
+ };
1331
1419
  uploads.push(...fitted.uploads);
1332
1420
  }
1333
1421
  return uploads;
@@ -1906,13 +1994,13 @@ var definitionOf = (input) => {
1906
1994
  return { name: input, functionId: runtimeFunctionId2({ name: input }) };
1907
1995
  return input;
1908
1996
  };
1909
- var bindExecutionHandle = (collector, store) => {
1910
- if (!collector) return;
1911
- store.executionHandle = collector.internExecutionKey(executionTypeKey(store.execution));
1912
- };
1913
- var bindExecutionMetricsIdentity = (collector, store) => {
1914
- if (!collector || !store.executionMetrics) return;
1915
- 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;
1916
2004
  };
1917
2005
  var settleStarted = (collector, functionHandle, executionHandle, started, value, failed, endedNs) => {
1918
2006
  if (!started || functionHandle === void 0 || executionHandle === void 0) return;
@@ -1933,7 +2021,8 @@ var runWithMetrics = (collector, durationSampler, plan, store, callback) => {
1933
2021
  });
1934
2022
  const startedNs = duration.measure ? tryCallClock2() : void 0;
1935
2023
  const functionHandle = internPreparedMetrics(collector, plan);
1936
- 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, {
1937
2026
  measure: duration.selected,
1938
2027
  ...duration.selected ? { startedNs } : {}
1939
2028
  });
@@ -1943,7 +2032,7 @@ var runWithMetrics = (collector, durationSampler, plan, store, callback) => {
1943
2032
  settleStarted(
1944
2033
  collector,
1945
2034
  functionHandle,
1946
- store?.executionHandle,
2035
+ executionHandle,
1947
2036
  started,
1948
2037
  result,
1949
2038
  false,
@@ -1954,7 +2043,7 @@ var runWithMetrics = (collector, durationSampler, plan, store, callback) => {
1954
2043
  settleStarted(
1955
2044
  collector,
1956
2045
  functionHandle,
1957
- store?.executionHandle,
2046
+ executionHandle,
1958
2047
  started,
1959
2048
  error,
1960
2049
  true,
@@ -1976,14 +2065,14 @@ var metricsHandle = (collector, durationSampler, plan, store) => {
1976
2065
  });
1977
2066
  const startedNs = duration.measure ? tryCallClock2() : void 0;
1978
2067
  const functionHandle = internPreparedMetrics(collector, plan);
1979
- 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, {
1980
2070
  measure: duration.selected,
1981
2071
  ...duration.selected ? { startedNs } : {}
1982
2072
  });
1983
- if (!started || functionHandle === void 0 || store?.executionHandle === void 0) {
2073
+ if (!started || functionHandle === void 0 || executionHandle === void 0 || !store) {
1984
2074
  return passthroughHandle();
1985
2075
  }
1986
- const executionHandle = store.executionHandle;
1987
2076
  let failed = false;
1988
2077
  let settled = false;
1989
2078
  let previousFunctionId = store.currentFunctionId;
@@ -2075,18 +2164,21 @@ var createMetricsOnlyRuntime = (input) => {
2075
2164
  return runPrepared(plan, args, () => fn.apply(this, args));
2076
2165
  };
2077
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
+ };
2078
2172
  const finishScope = (store, next) => {
2079
2173
  if (next) {
2080
2174
  mergeMetadata(store, next);
2081
- bindExecutionHandle(collector, store);
2082
- bindExecutionMetricsIdentity(executionMetrics, store);
2083
2175
  }
2084
2176
  if (!executionMetrics || !store.executionMetrics) return;
2085
2177
  if (store.executionMetrics.finished) return;
2086
2178
  const endedNs = tryCallClock2();
2087
2179
  const executionKey = executionTypeKey(store.execution);
2088
- bindExecutionMetricsIdentity(executionMetrics, store);
2089
2180
  executionMetrics.finishExecution(store.executionMetrics, {
2181
+ key: executionKey,
2090
2182
  failed: executionOutcomeFailed({
2091
2183
  hasError: store.hasError,
2092
2184
  runFailed: store.runFailed,
@@ -2109,10 +2201,9 @@ var createMetricsOnlyRuntime = (input) => {
2109
2201
  hasError: false,
2110
2202
  runFailed: false
2111
2203
  };
2112
- bindExecutionHandle(collector, store);
2113
2204
  if (executionMetrics) {
2114
2205
  store.executionMetrics = executionMetrics.createState();
2115
- bindExecutionMetricsIdentity(executionMetrics, store);
2206
+ bindNamedExecutionMetrics(store);
2116
2207
  }
2117
2208
  return {
2118
2209
  run: (callback) => metricsStorage.run(store, () => {
@@ -2131,8 +2222,9 @@ var createMetricsOnlyRuntime = (input) => {
2131
2222
  finish: (next) => finishScope(store, next),
2132
2223
  mergeMetadata: (next) => {
2133
2224
  mergeMetadata(store, next);
2134
- bindExecutionHandle(collector, store);
2135
- bindExecutionMetricsIdentity(executionMetrics, store);
2225
+ bindNamedExecutionMetrics(store);
2226
+ },
2227
+ captureInput: () => {
2136
2228
  }
2137
2229
  };
2138
2230
  },
@@ -2154,9 +2246,12 @@ var createMetricsOnlyRuntime = (input) => {
2154
2246
  };
2155
2247
 
2156
2248
  // src/execution-recorder/adaptive-recording-options.ts
2157
- var DEFAULT_FULL_CAPTURE_DURATION_MS = 24 * 60 * 60 * 1e3;
2249
+ var DEFAULT_FULL_CAPTURE_DURATION_MS = 60 * 60 * 1e3;
2158
2250
  var MIN_FULL_CAPTURE_DURATION_MS = 1e3;
2159
2251
  var MAX_FULL_CAPTURE_DURATION_MS = 7 * 24 * 60 * 60 * 1e3;
2252
+ var resolveExecutionRecordingMode = (options) => {
2253
+ return options?.alwaysCaptureValues === true ? "full" : "adaptive";
2254
+ };
2160
2255
  var sanitizeFullCaptureDurationMs = (value) => {
2161
2256
  if (typeof value !== "number" || !Number.isFinite(value)) {
2162
2257
  return DEFAULT_FULL_CAPTURE_DURATION_MS;
@@ -2173,6 +2268,45 @@ var KIND_EXIT = 2;
2173
2268
  var KIND_THROW = 3;
2174
2269
  var KIND_SUPPRESSED = 4;
2175
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
+ };
2176
2310
  var NO_PARENT = 4294967295;
2177
2311
  var NO_SUPPRESSION = 4294967295;
2178
2312
  var TIMING_UNAVAILABLE = -1n;
@@ -2375,19 +2509,24 @@ var ExecutionJournal = class {
2375
2509
  const functionId = plansByRuntimeId[this.planId[index] ?? 0]?.functionId;
2376
2510
  if (!functionId) return void 0;
2377
2511
  const parentCallId = this.parentCallId[index] ?? NO_PARENT;
2378
- const payload = this.payloads[index];
2512
+ const unpacked = unpackCapture(this.payloads[index]);
2513
+ const inner = unpacked.ordinaryPresent ? unpacked.ordinary : ARGS_OMITTED;
2379
2514
  const timestampMs = measuredRelativeMs(this.timestampNs[index] ?? TIMING_UNAVAILABLE);
2380
2515
  return {
2381
2516
  type: "function_enter",
2382
2517
  callId: this.callId[index] ?? 0,
2383
2518
  functionId,
2384
2519
  ...timestampMs === void 0 ? {} : { timestampMs },
2385
- ...payload === ARGS_OMITTED ? { argsOmitted: true } : { args: Array.isArray(payload) ? payload : [] },
2386
- ...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 : [] } : {}
2387
2525
  };
2388
2526
  }
2389
2527
  if (kind === KIND_EXIT) {
2390
- const payload = this.payloads[index];
2528
+ const unpacked = unpackCapture(this.payloads[index]);
2529
+ const inner = unpacked.ordinaryPresent ? unpacked.ordinary : ARGS_OMITTED;
2391
2530
  const timestampMs = measuredRelativeMs(this.timestampNs[index] ?? TIMING_UNAVAILABLE);
2392
2531
  const durationMs = measuredRelativeMs(this.durationNs[index] ?? TIMING_UNAVAILABLE);
2393
2532
  return {
@@ -2395,7 +2534,10 @@ var ExecutionJournal = class {
2395
2534
  callId: this.callId[index] ?? 0,
2396
2535
  ...timestampMs === void 0 ? {} : { timestampMs },
2397
2536
  ...durationMs === void 0 ? {} : { durationMs },
2398
- ...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 } : {}
2399
2541
  };
2400
2542
  }
2401
2543
  if (kind === KIND_THROW) {
@@ -2902,6 +3044,13 @@ var enforceRuntimeStateSizeBudget = (input) => {
2902
3044
  withSizeMetadata({ ...state, captureProfile, events: stripped.events }, size)
2903
3045
  );
2904
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
+ }
2905
3054
  size.eventsDropped += state.events.length;
2906
3055
  size.functionDefinitionsDropped += state.functions.length;
2907
3056
  state = settleFinalBytes(
@@ -4157,6 +4306,8 @@ var noOpExecution = {
4157
4306
  finish: () => {
4158
4307
  },
4159
4308
  mergeMetadata: () => {
4309
+ },
4310
+ captureInput: () => {
4160
4311
  }
4161
4312
  }),
4162
4313
  getErrorState: () => void 0,
@@ -4219,24 +4370,17 @@ var createExecutionRecorder = (options, hooks = {}) => {
4219
4370
  const functionMetrics = hooks.functionMetrics;
4220
4371
  const executionMetrics = hooks.executionMetrics;
4221
4372
  const durationSampler = hooks.durationSampler;
4222
- const bindMetricsExecution = (recording) => {
4223
- if (!functionMetrics) return;
4224
- recording.metricsExecutionHandle = functionMetrics.internExecutionKey(
4225
- executionTypeKey(recording.execution)
4226
- );
4227
- };
4228
- const bindExecutionMetricsIdentity2 = (recording) => {
4229
- if (!executionMetrics || !recording.executionMetrics) return;
4230
- executionMetrics.bindIdentity(
4231
- recording.executionMetrics,
4232
- executionTypeKey(recording.execution)
4233
- );
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;
4234
4380
  };
4235
4381
  warnIfMissingAsyncContextFrame();
4236
- const adaptiveEnabled = options.adaptive?.enabled === true;
4237
- const fullCaptureDurationMs = sanitizeFullCaptureDurationMs(
4238
- options.adaptive?.fullCaptureDurationMs
4239
- );
4382
+ const adaptiveEnabled = resolveExecutionRecordingMode(options) === "adaptive";
4383
+ const fullCaptureDurationMs = sanitizeFullCaptureDurationMs(options.dynamicFullCaptureDurationMs);
4240
4384
  const trackCallers = durationSampler !== void 0;
4241
4385
  const readCallClock = () => process.hrtime.bigint();
4242
4386
  const tryCallClock3 = () => {
@@ -4367,58 +4511,179 @@ var createExecutionRecorder = (options, hooks = {}) => {
4367
4511
  stats.totalInlineWallTimeMs = Math.round((stats.totalInlineWallTimeMs + inlineWallTimeMs) * 1e4) / 1e4;
4368
4512
  stats.maxInlineWallTimeMs = Math.max(stats.maxInlineWallTimeMs, inlineWallTimeMs);
4369
4513
  };
4370
- const freezeAndCount = (recording, value) => {
4371
- 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);
4372
4521
  stats.serializedValues++;
4373
4522
  stats.serializedValueNodes += frozen.visitedNodes;
4374
4523
  stats.serializedValueBytes += frozen.estimatedBytes;
4375
4524
  return frozen;
4376
4525
  };
4377
- const captureValue = (recording, value) => {
4526
+ const captureValue = (recording, value, encodeSerializer = serializer) => {
4378
4527
  try {
4379
4528
  return memoryBudget.captureValue(
4380
4529
  recording.memory,
4381
4530
  value,
4382
- (item) => freezeAndCount(recording, item)
4531
+ (item) => freezeAndCount(item, encodeSerializer)
4383
4532
  );
4384
4533
  } catch {
4385
4534
  return { __rasputin_type: "unserializable" };
4386
4535
  }
4387
4536
  };
4388
- const encodeEventValues = (recording, events) => events.map((event) => {
4389
- const encode = (recording.serializer ?? serializer).encode;
4390
- if (event.type === "function_enter") {
4391
- return {
4392
- ...event,
4393
- ...event.args === void 0 ? {} : { args: event.args.map((argument) => encode(argument)) }
4394
- };
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);
4395
4556
  }
4396
- if (event.type === "function_exit") {
4397
- return event.returnValue === void 0 ? event : { ...event, returnValue: encode(event.returnValue) };
4557
+ if (policy.sessionValues && policy.sessionId) {
4558
+ return tagSessionCapture(policy.sessionId, sessionValue);
4398
4559
  }
4399
- if (event.type === "function_throw") {
4400
- 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);
4401
4649
  }
4402
- return event;
4403
- });
4404
- const enterPayload = (recording, omitCallValues, args) => {
4405
- if (!recording.captureValues) return ARGS_OMITTED;
4650
+ return mapped;
4651
+ };
4652
+ const captureArgs = (recording, omitCallValues, args, encodeSerializer) => {
4406
4653
  if (omitCallValues) return mapArrayLike(args, () => rasputinOmitted());
4407
- return mapArrayLike(args, (argument) => captureValue(recording, argument));
4654
+ return mapArrayLike(args, (argument) => captureValue(recording, argument, encodeSerializer));
4655
+ };
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
+ );
4408
4668
  };
4409
- const exitPayload = (recording, omitCallValues, value) => {
4410
- if (!recording.captureValues) return ARGS_OMITTED;
4411
- if (omitCallValues) return rasputinOmitted();
4412
- return captureValue(recording, value);
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
+ );
4413
4681
  };
4414
4682
  const admitSession = (recording, session) => {
4415
- const wasLight = adaptiveEnabled && !recording.captureValues;
4416
4683
  recording.retainSuccess = true;
4417
4684
  recording.sessionId = session.sessionId;
4418
- recording.captureValues = true;
4419
4685
  if (session.serializer) recording.serializer = session.serializer;
4420
4686
  if (session.redactKeys?.length) recording.sessionRedactKeys = session.redactKeys;
4421
- if (session.scrubPII !== void 0) recording.sessionScrubPii = session.scrubPII;
4422
4687
  if (session.excludeSources?.length) {
4423
4688
  recording.sessionExcludes = createSourceExclusionMatcher(session.excludeSources);
4424
4689
  }
@@ -4431,28 +4696,29 @@ var createExecutionRecorder = (options, hooks = {}) => {
4431
4696
  if (session.maxExecutionHoldMs !== void 0) {
4432
4697
  recording.sessionHoldNs = BigInt(Math.max(1, Math.round(session.maxExecutionHoldMs))) * 1000000n;
4433
4698
  }
4434
- if (wasLight) {
4435
- stats.adaptiveLightExecutions = Math.max(0, stats.adaptiveLightExecutions - 1);
4436
- stats.adaptiveFullExecutions++;
4437
- }
4438
4699
  };
4439
- const skipCapture = (store, plan) => store.suppressCapture || plan.excluded || Boolean(store.recording.sessionExcludes?.(plan.definition));
4440
- const callStoreFor = (store, functionId, callId) => {
4441
- 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
+ };
4442
4707
  if (trackCallers) next.currentFunctionId = functionId;
4443
4708
  return next;
4444
4709
  };
4445
4710
  const samplingStore = (store, functionId) => {
4446
4711
  return trackCallers ? { ...store, currentFunctionId: functionId } : store;
4447
4712
  };
4448
- 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);
4449
4715
  const planInvocationDuration = (recording, plan, callerFunctionId) => planCallDuration(durationSampler, {
4450
4716
  forceMeasure: recorderForceMeasure(recording),
4451
4717
  executionType: executionTypeKey(recording.execution),
4452
4718
  callerFunctionId: callerFunctionId ?? "",
4453
4719
  functionId: plan.functionId
4454
4720
  });
4455
- const capturedCallLimitFor = (recording) => recording.sessionMaxCapturedCalls ?? maxCapturedCallsPerFunction;
4721
+ const capturedCallLimitFor = (recording) => Math.max(maxCapturedCallsPerFunction, recording.sessionMaxCapturedCalls ?? 0);
4456
4722
  const tryAdmitLiveSession = (recording) => {
4457
4723
  if (recording.retainSuccess || recording.finished) return;
4458
4724
  const key = executionTypeKey(recording.execution);
@@ -4460,29 +4726,59 @@ var createExecutionRecorder = (options, hooks = {}) => {
4460
4726
  const peek = hooks.sessionCaptureSnapshot?.().get(key);
4461
4727
  if (!peek || peek.expiresAtMs <= recording.startedAtMs) return;
4462
4728
  const live = hooks.consumeSession?.(key, peek.sessionId);
4463
- if (live) admitSession(recording, live);
4464
- };
4465
- const tryAdmitFromStartSnapshot = (recording) => {
4466
- 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;
4467
4758
  const key = executionTypeKey(recording.execution);
4468
- if (!key) return;
4469
- const peek = recording.sessionCaptureSnapshot.get(key);
4470
- if (!peek || peek.expiresAtMs <= recording.startedAtMs) return;
4471
- const live = hooks.consumeSession?.(key, peek.sessionId);
4472
- 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
+ }
4473
4772
  };
4474
- const completeIdentityFromSnapshot = (recording) => {
4475
- if (recording.identityResolved || recording.finished) return;
4773
+ const reserveSession = (recording) => {
4774
+ if (!recording.sessionId || recording.sessionReserved || !hooks.consumeSession) return;
4476
4775
  const key = executionTypeKey(recording.execution);
4477
- if (!key) return;
4478
- recording.identityResolved = true;
4479
- tryAdmitFromStartSnapshot(recording);
4480
- if (recording.captureValues || !adaptiveEnabled) return;
4481
- if (keyIsActive(recording.policySnapshot, key, recording.startedAtMs)) {
4482
- recording.captureValues = true;
4483
- stats.adaptiveLightExecutions = Math.max(0, stats.adaptiveLightExecutions - 1);
4484
- stats.adaptiveFullExecutions++;
4776
+ const reserved = key ? hooks.consumeSession(key, recording.sessionId) : void 0;
4777
+ if (reserved) {
4778
+ recording.sessionReserved = true;
4779
+ return;
4485
4780
  }
4781
+ detachSession(recording);
4486
4782
  };
4487
4783
  const maybeActivateAdaptive = (recording) => {
4488
4784
  if (!adaptiveEnabled || recording.adaptiveActivated) return;
@@ -4555,7 +4851,7 @@ var createExecutionRecorder = (options, hooks = {}) => {
4555
4851
  }
4556
4852
  return false;
4557
4853
  };
4558
- const resolveCaptureProfile = (recording, events, truncated, capture) => {
4854
+ const resolveCaptureProfile = (recording, events, truncated, capture, includeSessionId) => {
4559
4855
  const source = recording.sawAutomatic ? "automatic" : recording.sawManual ? "manual" : "scope-only";
4560
4856
  if (source === "scope-only") {
4561
4857
  return {
@@ -4591,20 +4887,21 @@ var createExecutionRecorder = (options, hooks = {}) => {
4591
4887
  }
4592
4888
  const droppedEvents = Boolean(truncated?.eventsDropped || capture?.eventsDropped);
4593
4889
  const evidence = retainedTimingsCoverage(events);
4890
+ const includeValues = recording.captureValues || includeSessionId !== void 0;
4594
4891
  return {
4595
4892
  source,
4596
4893
  functionBoundaries: droppedEvents ? "partial" : "full",
4597
- functionValues: recording.captureValues ? eventsHaveOmittedValues(events) ? "selective" : "full" : "none",
4894
+ functionValues: includeValues ? eventsHaveOmittedValues(events) ? "selective" : "full" : "none",
4598
4895
  timings: droppedEvents && evidence === "full" ? "partial" : evidence
4599
4896
  };
4600
4897
  };
4601
- const stateFrom = (recording, endedAtNs = process.hrtime.bigint()) => {
4898
+ const stateFrom = (recording, endedAtNs = process.hrtime.bigint(), includeSessionId) => {
4602
4899
  const recorderStartedAtNs = process.hrtime.bigint();
4603
4900
  let events = [];
4604
4901
  let functions = [];
4605
4902
  let truncated;
4606
4903
  let capture;
4607
- if (recording.cachedState) {
4904
+ if (recording.cachedState && includeSessionId === void 0) {
4608
4905
  events = recording.cachedState.events;
4609
4906
  functions = recording.cachedState.functions;
4610
4907
  truncated = recording.cachedState.truncated;
@@ -4612,13 +4909,25 @@ var createExecutionRecorder = (options, hooks = {}) => {
4612
4909
  } else {
4613
4910
  if (recording.journal) {
4614
4911
  const materialized = recording.journal.materialize(plansByRuntimeId, recording.startedAtNs);
4615
- events = encodeEventValues(recording, materialized.events);
4912
+ events = encodeEventValues(recording, materialized.events, includeSessionId);
4616
4913
  if (recording.lateCapturedCallIds && recording.lateCapturedCallIds.size > 0) {
4617
4914
  events = events.map(
4618
4915
  (event) => event.type === "function_enter" && recording.lateCapturedCallIds?.has(event.callId) ? { ...event, capturedAt: "throw" } : event
4619
4916
  );
4620
4917
  }
4621
- 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
+ }
4622
4931
  truncated = recording.journal.dropped > 0 ? { eventsDropped: recording.journal.dropped } : void 0;
4623
4932
  }
4624
4933
  if (recording.budgetExpired) {
@@ -4643,13 +4952,19 @@ var createExecutionRecorder = (options, hooks = {}) => {
4643
4952
  eventsDropped: recording.memory.eventsDropped
4644
4953
  };
4645
4954
  }
4646
- if (recording.finished && recording.inFlightCalls === 0 && recording.journal) {
4955
+ if (includeSessionId === void 0 && recording.finished && recording.inFlightCalls === 0 && recording.journal) {
4647
4956
  recording.cachedState = { events, functions, truncated, capture };
4648
4957
  journalPool.release(recording.journal);
4649
4958
  recording.journal = void 0;
4650
4959
  }
4651
4960
  }
4652
- const captureProfile = resolveCaptureProfile(recording, events, truncated, capture);
4961
+ const captureProfile = resolveCaptureProfile(
4962
+ recording,
4963
+ events,
4964
+ truncated,
4965
+ capture,
4966
+ includeSessionId
4967
+ );
4653
4968
  const fullyTimed = eventsAreFullyTimed(events);
4654
4969
  const state = {
4655
4970
  version: 4,
@@ -4666,7 +4981,12 @@ var createExecutionRecorder = (options, hooks = {}) => {
4666
4981
  events: fullyTimed ? asFullyTimedEvents(events) : events.slice(),
4667
4982
  ...fullyTimed || !durationSampler ? {} : { durationSampling: { policy: "progressive" } },
4668
4983
  ...truncated ? { truncated: { ...truncated } } : {},
4669
- ...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
+ } : {}
4670
4990
  };
4671
4991
  if (phaseTimingEnabled)
4672
4992
  addPhase("materializeNs", process.hrtime.bigint() - recorderStartedAtNs);
@@ -4692,6 +5012,7 @@ var createExecutionRecorder = (options, hooks = {}) => {
4692
5012
  recording.cachedState = void 0;
4693
5013
  recording.repeatedCalls = void 0;
4694
5014
  recording.lateCapturedCallIds = void 0;
5015
+ recording.inputSnapshot = void 0;
4695
5016
  recording.capturedErrors = /* @__PURE__ */ new WeakMap();
4696
5017
  if (recording.journal) {
4697
5018
  journalPool.release(recording.journal);
@@ -4727,6 +5048,7 @@ var createExecutionRecorder = (options, hooks = {}) => {
4727
5048
  recording.journal = void 0;
4728
5049
  }
4729
5050
  recording.evicted = true;
5051
+ recording.inputSnapshot = void 0;
4730
5052
  detachLiveRecording(recording);
4731
5053
  recording.cachedState = {
4732
5054
  events: [],
@@ -4780,6 +5102,7 @@ var createExecutionRecorder = (options, hooks = {}) => {
4780
5102
  journalPool.release(recording.journal);
4781
5103
  recording.journal = void 0;
4782
5104
  }
5105
+ recording.inputSnapshot = void 0;
4783
5106
  recording.cachedState = {
4784
5107
  events: [],
4785
5108
  functions: [],
@@ -4816,7 +5139,8 @@ var createExecutionRecorder = (options, hooks = {}) => {
4816
5139
  liveRecordings.splice(index, 1);
4817
5140
  continue;
4818
5141
  }
4819
- 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;
4820
5144
  try {
4821
5145
  expireLongLivedRecording(recording, nowNs);
4822
5146
  } catch {
@@ -4924,7 +5248,7 @@ var createExecutionRecorder = (options, hooks = {}) => {
4924
5248
  // snapshot without the exception itself would not be useful for investigation.
4925
5249
  value: (() => {
4926
5250
  try {
4927
- return freezeAndCount(recording, error).value;
5251
+ return freezeAndCount(error).value;
4928
5252
  } catch {
4929
5253
  return { __rasputin_type: "unserializable" };
4930
5254
  }
@@ -4934,7 +5258,7 @@ var createExecutionRecorder = (options, hooks = {}) => {
4934
5258
  }
4935
5259
  };
4936
5260
  };
4937
- const captureCompletedThrow = (recording, plan, args, parentCallId, startedAtNs, error, timed, capturedArgs, completedAtNs) => {
5261
+ const captureCompletedThrow = (recording, plan, parentCallId, startedAtNs, error, timed, capturedArgs, completedAtNs) => {
4938
5262
  if (!recording.journal) {
4939
5263
  return;
4940
5264
  }
@@ -4943,7 +5267,7 @@ var createExecutionRecorder = (options, hooks = {}) => {
4943
5267
  }
4944
5268
  const callId = ++recording.nextCallId;
4945
5269
  const capturedError = serializedError(recording, error, callId);
4946
- const recordedArgs = capturedArgs ?? (recording.captureValues ? mapArrayLike(args, (argument) => captureValue(recording, argument)) : ARGS_OMITTED);
5270
+ const recordedArgs = capturedArgs;
4947
5271
  const endedAtNs = timed ? completedAtNs : void 0;
4948
5272
  const droppedBefore = recording.journal.dropped;
4949
5273
  const retained = recording.journal.forceCompletedCall(
@@ -5027,9 +5351,8 @@ var createExecutionRecorder = (options, hooks = {}) => {
5027
5351
  sessionId: recording.sessionId,
5028
5352
  executionId: recording.executionId,
5029
5353
  outcome: recording.hasError || recording.runFailed ? "error" : "success",
5030
- runtimeState: stateFrom(recording),
5031
- redactKeys: recording.sessionRedactKeys,
5032
- scrubPii: recording.sessionScrubPii
5354
+ runtimeState: stateFrom(recording, void 0, recording.sessionId),
5355
+ redactKeys: recording.sessionRedactKeys
5033
5356
  });
5034
5357
  } catch {
5035
5358
  }
@@ -5064,16 +5387,16 @@ var createExecutionRecorder = (options, hooks = {}) => {
5064
5387
  return;
5065
5388
  }
5066
5389
  const recorderStartedAtNs = process.hrtime.bigint();
5067
- recording.finished = true;
5068
5390
  if (metadata) {
5069
5391
  mergeExecutionMetadata(recording.execution, metadata);
5070
- bindMetricsExecution(recording);
5071
- bindExecutionMetricsIdentity2(recording);
5392
+ applyExecutionIdentity(recording);
5072
5393
  }
5394
+ recording.finished = true;
5395
+ reserveSession(recording);
5073
5396
  if (executionMetrics && recording.executionMetrics) {
5074
5397
  const executionKey = executionTypeKey(recording.execution);
5075
- bindExecutionMetricsIdentity2(recording);
5076
5398
  executionMetrics.finishExecution(recording.executionMetrics, {
5399
+ key: executionKey,
5077
5400
  failed: executionOutcomeFailed({
5078
5401
  hasError: recording.hasError,
5079
5402
  runFailed: recording.runFailed === true,
@@ -5118,7 +5441,8 @@ var createExecutionRecorder = (options, hooks = {}) => {
5118
5441
  ...metadata,
5119
5442
  ...metadata.request ? { request: { ...metadata.request } } : {}
5120
5443
  };
5121
- const identityComplete = executionTypeKey(execution) !== void 0;
5444
+ const initialKey = executionTypeKey(execution);
5445
+ const identityComplete = initialKey !== void 0;
5122
5446
  const captureValues = captureValuesFor(execution, livePolicy, startedAtMs);
5123
5447
  const policySnapshot = adaptiveEnabled && !identityComplete ? new Map(livePolicy) : EMPTY_POLICY_SNAPSHOT;
5124
5448
  const liveSessions = hooks.sessionCaptureSnapshot?.() ?? EMPTY_SESSION_SNAPSHOT;
@@ -5146,14 +5470,15 @@ var createExecutionRecorder = (options, hooks = {}) => {
5146
5470
  sawManual: false,
5147
5471
  captureValues,
5148
5472
  policySnapshot,
5149
- identityResolved: identityComplete,
5473
+ resolvedExecutionKey: initialKey,
5150
5474
  sessionCaptureSnapshot
5151
5475
  };
5152
5476
  if (identityComplete) tryAdmitLiveSession(recording);
5153
- bindMetricsExecution(recording);
5154
5477
  if (executionMetrics) {
5155
5478
  recording.executionMetrics = executionMetrics.createState();
5156
- bindExecutionMetricsIdentity2(recording);
5479
+ if (execution.kind !== "http") {
5480
+ executionMetrics.bindIdentity(recording.executionMetrics, initialKey);
5481
+ }
5157
5482
  }
5158
5483
  stats.activeExecutions++;
5159
5484
  stats.peakActiveExecutions = Math.max(stats.peakActiveExecutions, stats.activeExecutions);
@@ -5205,9 +5530,32 @@ var createExecutionRecorder = (options, hooks = {}) => {
5205
5530
  mergeMetadata: (nextMetadata) => {
5206
5531
  try {
5207
5532
  mergeExecutionMetadata(recording.execution, nextMetadata);
5208
- completeIdentityFromSnapshot(recording);
5209
- bindMetricsExecution(recording);
5210
- 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
+ };
5211
5559
  } catch {
5212
5560
  }
5213
5561
  }
@@ -5227,7 +5575,7 @@ var createExecutionRecorder = (options, hooks = {}) => {
5227
5575
  const duration = plan.excluded ? { selected: false, measure: false } : store ? planInvocationDuration(store.recording, plan, store.currentFunctionId) : { selected: false, measure: false };
5228
5576
  const startedNs = duration.measure ? tryCallClock3() : void 0;
5229
5577
  const functionHandle = functionMetrics && !plan.excluded ? internPreparedMetrics(functionMetrics, plan) : void 0;
5230
- const executionHandle = store?.recording.metricsExecutionHandle;
5578
+ const executionHandle = functionHandle !== void 0 && store ? metricsExecutionHandleFor(store.recording) : void 0;
5231
5579
  const metricsStart = startMetricsCall(functionMetrics, functionHandle, executionHandle, {
5232
5580
  measure: duration.selected,
5233
5581
  ...duration.selected ? { startedNs } : {}
@@ -5318,10 +5666,13 @@ var createExecutionRecorder = (options, hooks = {}) => {
5318
5666
  const recorderStartedAtNs = process.hrtime.bigint();
5319
5667
  if (skipCapture(store, plan)) {
5320
5668
  stats.functionCallsExcluded++;
5321
- return runStore({ ...store, suppressCapture: true }, function __rasputinHandleRun__5() {
5322
- addRecorderTime(store.recording, process.hrtime.bigint() - recorderStartedAtNs);
5323
- return callback();
5324
- });
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
+ );
5325
5676
  }
5326
5677
  const recording = store.recording;
5327
5678
  recording.inFlightCalls++;
@@ -5335,10 +5686,12 @@ var createExecutionRecorder = (options, hooks = {}) => {
5335
5686
  }
5336
5687
  const timed = sharedClock.timed;
5337
5688
  const startedAtNs = sharedClock.start ?? 0n;
5689
+ const sessionExcluded = sessionExcludedFor(store, plan);
5690
+ const policy = capturePolicyFor(recording, store, plan, group.observedCalls);
5338
5691
  if (group.observedCalls > capturedCallLimitFor(recording)) {
5339
5692
  try {
5340
5693
  const result = runStore(
5341
- samplingStore(store, plan.functionId),
5694
+ sessionBodyStore(samplingStore(store, plan.functionId), sessionExcluded),
5342
5695
  function __rasputinHandleRun__5() {
5343
5696
  return callback();
5344
5697
  }
@@ -5373,12 +5726,11 @@ var createExecutionRecorder = (options, hooks = {}) => {
5373
5726
  captureCompletedThrow(
5374
5727
  recording,
5375
5728
  plan,
5376
- args,
5377
5729
  parentCallId,
5378
5730
  startedAtNs,
5379
5731
  error,
5380
5732
  timed,
5381
- void 0,
5733
+ enterPayload(recording, omitCallValues, args, throwPolicyFrom(policy)),
5382
5734
  sharedClock.end
5383
5735
  );
5384
5736
  settleInFlight(recording);
@@ -5387,17 +5739,20 @@ var createExecutionRecorder = (options, hooks = {}) => {
5387
5739
  }
5388
5740
  if (!journal) {
5389
5741
  memoryBudget.reserveCall(recording.memory, plan.estimatedCallBytes);
5390
- return runStore(samplingStore(store, plan.functionId), function __rasputinHandleRun__5() {
5391
- return observeRecordedCallback(
5392
- recording,
5393
- recorderStartedAtNs,
5394
- callback,
5395
- () => settleInFlight(recording),
5396
- (_error) => {
5397
- settleInFlight(recording);
5398
- }
5399
- );
5400
- });
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
+ );
5401
5756
  }
5402
5757
  if (!journal.canStartCall()) {
5403
5758
  const captureSuccess = () => {
@@ -5406,63 +5761,71 @@ var createExecutionRecorder = (options, hooks = {}) => {
5406
5761
  countDroppedEvents(recording, droppedBefore);
5407
5762
  settleInFlight(recording);
5408
5763
  };
5409
- return runStore(samplingStore(store, plan.functionId), function __rasputinHandleRun__5() {
5410
- return observeRecordedCallback(
5411
- recording,
5412
- recorderStartedAtNs,
5413
- callback,
5414
- captureSuccess,
5415
- (error) => {
5416
- if (timed && sharedClock.end === void 0) sharedClock.end = tryCallClock3();
5417
- captureCompletedThrow(
5418
- recording,
5419
- plan,
5420
- args,
5421
- parentCallId,
5422
- startedAtNs,
5423
- error,
5424
- timed,
5425
- void 0,
5426
- sharedClock.end
5427
- );
5428
- settleInFlight(recording);
5429
- }
5430
- );
5431
- });
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
+ );
5432
5789
  }
5433
5790
  if (!memoryBudget.reserveCall(recording.memory, plan.estimatedCallBytes)) {
5434
- return runStore(samplingStore(store, plan.functionId), function __rasputinHandleRun__5() {
5435
- return observeRecordedCallback(
5436
- recording,
5437
- recorderStartedAtNs,
5438
- callback,
5439
- () => settleInFlight(recording),
5440
- (_error) => {
5441
- settleInFlight(recording);
5442
- }
5443
- );
5444
- });
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
+ );
5445
5805
  }
5446
5806
  const callId = ++recording.nextCallId;
5447
5807
  const enterTimestampNs = timed ? startedAtNs - recording.startedAtNs : TIMING_UNAVAILABLE;
5448
- const capturedArgs = enterPayload(recording, omitCallValues, args);
5808
+ const capturedArgs = enterPayload(recording, omitCallValues, args, policy);
5449
5809
  try {
5450
5810
  journal.startCall(plan.runtimePlanId, callId, parentCallId, enterTimestampNs, capturedArgs);
5451
5811
  } catch {
5452
5812
  journal.dropCall();
5453
- return runStore(samplingStore(store, plan.functionId), function __rasputinHandleRun__5() {
5454
- return observeRecordedCallback(
5455
- recording,
5456
- recorderStartedAtNs,
5457
- callback,
5458
- () => settleInFlight(recording),
5459
- (_error) => {
5460
- settleInFlight(recording);
5461
- }
5462
- );
5463
- });
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
+ );
5464
5827
  }
5465
- const callStore = callStoreFor(store, plan.functionId, callId);
5828
+ const callStore = callStoreFor(store, plan.functionId, callId, sessionExcluded);
5466
5829
  return runStore(callStore, function __rasputinHandleRun__5() {
5467
5830
  return observeRecordedCallback(
5468
5831
  recording,
@@ -5473,7 +5836,7 @@ var createExecutionRecorder = (options, hooks = {}) => {
5473
5836
  const pending = value instanceof Promise;
5474
5837
  const endedAtNs = timed && !pending ? tryCallClock3() : void 0;
5475
5838
  if (endedAtNs !== void 0) sharedClock.end = endedAtNs;
5476
- const returnValue = exitPayload(recording, omitCallValues, value);
5839
+ const returnValue = exitPayload(recording, omitCallValues, value, policy);
5477
5840
  if (endedAtNs !== void 0) {
5478
5841
  recording.journal.finishCall(
5479
5842
  KIND_EXIT,
@@ -5555,6 +5918,7 @@ var createExecutionRecorder = (options, hooks = {}) => {
5555
5918
  this.plan = plan;
5556
5919
  this.args = args;
5557
5920
  this.omitCallValues = omitCallValues;
5921
+ this.policy = EMPTY_POLICY;
5558
5922
  this.parentCallId = parentCallId;
5559
5923
  this.activeStore = activeStore;
5560
5924
  this.parentStore = parentStore;
@@ -5592,7 +5956,7 @@ var createExecutionRecorder = (options, hooks = {}) => {
5592
5956
  try {
5593
5957
  if (this.status !== "failed") {
5594
5958
  this.status = "left";
5595
- if (this.recording.captureValues) this.pendingReturn = value;
5959
+ if (this.policy.ordinary || this.policy.sessionValues) this.pendingReturn = value;
5596
5960
  }
5597
5961
  return value;
5598
5962
  } catch {
@@ -5609,27 +5973,32 @@ var createExecutionRecorder = (options, hooks = {}) => {
5609
5973
  }
5610
5974
  if (this.mode === "captured") writeCapturedThrow(this, error);
5611
5975
  else if (this.mode === "suppressed" && this.plan) {
5976
+ const throwPolicy = throwPolicyFrom(this.policy);
5612
5977
  captureCompletedThrow(
5613
5978
  this.recording,
5614
5979
  this.plan,
5615
- this.recording.captureValues ? liveArgs ?? this.args : EMPTY_ARGS,
5616
5980
  this.parentCallId,
5617
5981
  this.startedAtNs,
5618
5982
  error,
5619
5983
  this.timed,
5620
- 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,
5621
5990
  this.completedAtNs
5622
5991
  );
5623
5992
  } else if (this.mode === "dropped" && this.captureDroppedThrow && this.plan) {
5993
+ const throwPolicy = throwPolicyFrom(this.policy);
5624
5994
  captureCompletedThrow(
5625
5995
  this.recording,
5626
5996
  this.plan,
5627
- this.recording.captureValues ? this.args : EMPTY_ARGS,
5628
5997
  this.parentCallId,
5629
5998
  this.startedAtNs,
5630
5999
  error,
5631
6000
  this.timed,
5632
- this.recording.captureValues ? void 0 : ARGS_OMITTED,
6001
+ throwPolicy.ordinary || throwPolicy.sessionValues ? enterPayload(this.recording, this.omitCallValues, this.args, throwPolicy) : ARGS_OMITTED,
5633
6002
  this.completedAtNs
5634
6003
  );
5635
6004
  }
@@ -5746,7 +6115,7 @@ var createExecutionRecorder = (options, hooks = {}) => {
5746
6115
  const writeCapturedExit = (frame, value, completedAtNs) => {
5747
6116
  if (!frame.recording.journal) return;
5748
6117
  const endedAtNs = frame.timed ? completedAtNs : void 0;
5749
- const returnValue = exitPayload(frame.recording, frame.omitCallValues, value);
6118
+ const returnValue = exitPayload(frame.recording, frame.omitCallValues, value, frame.policy);
5750
6119
  if (endedAtNs !== void 0) {
5751
6120
  frame.recording.journal.finishCall(
5752
6121
  KIND_EXIT,
@@ -5793,14 +6162,14 @@ var createExecutionRecorder = (options, hooks = {}) => {
5793
6162
  const armCallFrameMetrics = (frame, plan) => {
5794
6163
  if (!functionMetrics || plan.excluded) return;
5795
6164
  const functionHandle = internPreparedMetrics(functionMetrics, plan);
6165
+ const executionHandle = functionHandle !== void 0 ? metricsExecutionHandleFor(frame.recording) : void 0;
5796
6166
  const started = startMetricsCall(
5797
6167
  functionMetrics,
5798
6168
  functionHandle,
5799
- frame.recording.metricsExecutionHandle,
6169
+ executionHandle,
5800
6170
  frame.metricsSelected ? { measure: true, startedNs: frame.timed ? frame.startedAtNs : void 0 } : { measure: false }
5801
6171
  );
5802
6172
  if (!started || functionHandle === void 0) return;
5803
- const executionHandle = frame.recording.metricsExecutionHandle;
5804
6173
  if (executionHandle === void 0) return;
5805
6174
  frame.metricsOpen = true;
5806
6175
  frame.metricsMeasure = started.measure;
@@ -5808,12 +6177,17 @@ var createExecutionRecorder = (options, hooks = {}) => {
5808
6177
  frame.metricsExecutionHandle = executionHandle;
5809
6178
  frame.metricsStartedNs = started.startedNs;
5810
6179
  };
5811
- 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;
5812
6186
  const frame = new CallFrame(
5813
6187
  mode,
5814
6188
  recording,
5815
6189
  parentStore,
5816
- parentStore,
6190
+ activeStore,
5817
6191
  plan,
5818
6192
  args,
5819
6193
  omitCallValues,
@@ -5825,8 +6199,9 @@ var createExecutionRecorder = (options, hooks = {}) => {
5825
6199
  captureDroppedThrow
5826
6200
  );
5827
6201
  frame.metricsSelected = selected;
6202
+ frame.policy = policy;
5828
6203
  frame.claimCaller();
5829
- enterStore(frame, parentStore);
6204
+ enterStore(frame, activeStore);
5830
6205
  armCallFrameMetrics(frame, plan);
5831
6206
  return frame;
5832
6207
  };
@@ -5868,7 +6243,11 @@ var createExecutionRecorder = (options, hooks = {}) => {
5868
6243
  stats.functionCallsExcluded++;
5869
6244
  const excludedDuration = plan.excluded ? { selected: false, measure: false } : planInvocationDuration(recording, plan, store.currentFunctionId);
5870
6245
  const start2 = invocationStart(excludedDuration.measure);
5871
- const excludedStore = { ...store, suppressCapture: true };
6246
+ const excludedStore = {
6247
+ ...store,
6248
+ suppressCapture: true,
6249
+ sessionSuppressCapture: true
6250
+ };
5872
6251
  const frame = new CallFrame(
5873
6252
  "excluded",
5874
6253
  recording,
@@ -5902,7 +6281,9 @@ var createExecutionRecorder = (options, hooks = {}) => {
5902
6281
  const timed = start.timed;
5903
6282
  const startedAtNs = start.startedAtNs;
5904
6283
  const parentStore = store;
5905
- 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;
5906
6287
  if (group.observedCalls > capturedCallLimitFor(recording)) {
5907
6288
  return activateUncaptured(
5908
6289
  "suppressed",
@@ -5916,7 +6297,9 @@ var createExecutionRecorder = (options, hooks = {}) => {
5916
6297
  timed,
5917
6298
  group,
5918
6299
  false,
5919
- duration.selected
6300
+ duration.selected,
6301
+ policy,
6302
+ sessionExcluded
5920
6303
  );
5921
6304
  }
5922
6305
  if (!journal) {
@@ -5933,7 +6316,9 @@ var createExecutionRecorder = (options, hooks = {}) => {
5933
6316
  timed,
5934
6317
  group,
5935
6318
  false,
5936
- duration.selected
6319
+ duration.selected,
6320
+ policy,
6321
+ sessionExcluded
5937
6322
  );
5938
6323
  }
5939
6324
  if (!journal.canStartCall()) {
@@ -5949,7 +6334,9 @@ var createExecutionRecorder = (options, hooks = {}) => {
5949
6334
  timed,
5950
6335
  group,
5951
6336
  true,
5952
- duration.selected
6337
+ duration.selected,
6338
+ policy,
6339
+ sessionExcluded
5953
6340
  );
5954
6341
  }
5955
6342
  if (!memoryBudget.reserveCall(recording.memory, plan.estimatedCallBytes)) {
@@ -5965,12 +6352,14 @@ var createExecutionRecorder = (options, hooks = {}) => {
5965
6352
  timed,
5966
6353
  group,
5967
6354
  false,
5968
- duration.selected
6355
+ duration.selected,
6356
+ policy,
6357
+ sessionExcluded
5969
6358
  );
5970
6359
  }
5971
6360
  const callId = ++recording.nextCallId;
5972
6361
  const enterTimestampNs = timed ? startedAtNs - recording.startedAtNs : TIMING_UNAVAILABLE;
5973
- const capturedArgs = enterPayload(recording, omitCallValues, args);
6362
+ const capturedArgs = enterPayload(recording, omitCallValues, args, policy);
5974
6363
  try {
5975
6364
  journal.startCall(plan.runtimePlanId, callId, parentCallId, enterTimestampNs, capturedArgs);
5976
6365
  } catch {
@@ -5987,10 +6376,12 @@ var createExecutionRecorder = (options, hooks = {}) => {
5987
6376
  timed,
5988
6377
  group,
5989
6378
  false,
5990
- duration.selected
6379
+ duration.selected,
6380
+ policy,
6381
+ sessionExcluded
5991
6382
  );
5992
6383
  }
5993
- const callStore = callStoreFor(store, plan.functionId, callId);
6384
+ const callStore = callStoreFor(store, plan.functionId, callId, sessionExcluded);
5994
6385
  const captured = new CallFrame(
5995
6386
  "captured",
5996
6387
  recording,
@@ -6007,6 +6398,7 @@ var createExecutionRecorder = (options, hooks = {}) => {
6007
6398
  false
6008
6399
  );
6009
6400
  captured.metricsSelected = duration.selected;
6401
+ captured.policy = policy;
6010
6402
  enterStore(captured, callStore);
6011
6403
  armCallFrameMetrics(captured, plan);
6012
6404
  return captured;
@@ -6229,7 +6621,6 @@ var parseSessionSettings = (value) => {
6229
6621
  const redactKeys = optionalStringList(value.redactKeys);
6230
6622
  if (excludeSources) overrides.excludeSources = excludeSources;
6231
6623
  if (redactKeys) overrides.redactKeys = redactKeys;
6232
- if (typeof value.scrubPII === "boolean") overrides.scrubPII = value.scrubPII;
6233
6624
  return Object.keys(overrides).length > 0 ? overrides : void 0;
6234
6625
  };
6235
6626
  var clampSessionFreezeLimits = (overrides, processLimits) => ({
@@ -6274,7 +6665,7 @@ var serializeSourceExclusions = (exclusions) => {
6274
6665
  }
6275
6666
  return out.length > 0 ? out : void 0;
6276
6667
  };
6277
- var reportedRecorderSettings = (options, scrubPII) => ({
6668
+ var reportedRecorderSettings = (options) => ({
6278
6669
  maxDepth: options?.maxDepth,
6279
6670
  maxObjectKeys: options?.maxObjectKeys,
6280
6671
  maxArrayElements: options?.maxArrayElements,
@@ -6285,11 +6676,10 @@ var reportedRecorderSettings = (options, scrubPII) => ({
6285
6676
  maxActiveMemoryBytes: options?.maxActiveMemoryBytes,
6286
6677
  maxExecutionHoldMs: options?.maxExecutionHoldMs,
6287
6678
  maxRetainedErrorRecordings: options?.maxRetainedErrorRecordings,
6288
- fullCaptureDurationMs: options?.adaptive?.fullCaptureDurationMs,
6679
+ fullCaptureDurationMs: options?.dynamicFullCaptureDurationMs,
6289
6680
  recorder_enabled: options?.enabled !== false,
6290
6681
  excludeSources: serializeSourceExclusions(options?.excludeSources),
6291
- redactKeys: options?.redactKeys,
6292
- scrubPII: scrubPII === true
6682
+ redactKeys: options?.redactKeys
6293
6683
  });
6294
6684
  var createSerializerCache = (options) => {
6295
6685
  const processLimits = compileFreezeLimits(options ?? {});
@@ -6325,6 +6715,8 @@ var DEFAULT_POLL_INTERVAL_MS = 3e4;
6325
6715
  var REQUEST_TIMEOUT_MS2 = 5e3;
6326
6716
  var MAX_RETRIES = 5;
6327
6717
  var MAX_POLL_JITTER_MS = 2e3;
6718
+ var UPLOAD_GRACE_MS = 6e4;
6719
+ var MAX_RETAINED_SESSIONS = 256;
6328
6720
  var trimmed2 = (value) => typeof value === "string" ? value.trim() : "";
6329
6721
  var isRecord2 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
6330
6722
  var unwrapPayload = (body) => {
@@ -6346,16 +6738,17 @@ var abortFrom = (parent, child) => {
6346
6738
  };
6347
6739
  var createExecutionRecordingCoordinator = (options) => {
6348
6740
  const environment = options.environment;
6741
+ const mode = resolveExecutionRecordingMode(options.recorderOptions);
6349
6742
  const nowMs = () => options.nowMs?.() ?? Date.now();
6350
6743
  const fetchFn = options.fetch ?? defaultIngestFetch2();
6351
6744
  const instanceId = crypto.randomUUID();
6352
6745
  const startedAt = /* @__PURE__ */ new Date();
6353
6746
  const redactKeys = copyRedactKeys(options.recorderOptions?.redactKeys);
6354
- const scrubPii = options.scrubPII === true;
6355
6747
  const serializers = createSerializerCache(options.recorderOptions);
6356
6748
  const cache = /* @__PURE__ */ new Map();
6357
6749
  const pending = /* @__PURE__ */ new Map();
6358
6750
  const sessionsById = /* @__PURE__ */ new Map();
6751
+ const retainedById = /* @__PURE__ */ new Map();
6359
6752
  const completedSessionIds = /* @__PURE__ */ new Set();
6360
6753
  const recordings = [];
6361
6754
  const capabilities = ["manual_sessions", "settings_overrides"];
@@ -6402,10 +6795,29 @@ var createExecutionRecordingCoordinator = (options) => {
6402
6795
  redactKeys: session.redactKeys,
6403
6796
  excludeSources: session.excludeSources,
6404
6797
  maxCapturedCallsPerFunction: session.maxCapturedCallsPerFunction,
6405
- maxExecutionHoldMs: session.maxExecutionHoldMs,
6406
- scrubPII: session.scrubPII
6798
+ maxExecutionHoldMs: session.maxExecutionHoldMs
6407
6799
  });
6408
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
+ };
6409
6821
  const rebuildSessionSnapshot = () => {
6410
6822
  const atMs = nowMs();
6411
6823
  const map = /* @__PURE__ */ new Map();
@@ -6599,7 +7011,7 @@ var createExecutionRecordingCoordinator = (options) => {
6599
7011
  }
6600
7012
  };
6601
7013
  const kickNotify = () => {
6602
- if (closed || closing || pending.size === 0 || options.mode !== "adaptive") return;
7014
+ if (closed || closing || pending.size === 0 || mode !== "adaptive") return;
6603
7015
  void drainNotifies(notifySignal());
6604
7016
  };
6605
7017
  const applyCompletedSessionIds = (value) => {
@@ -6609,6 +7021,7 @@ var createExecutionRecordingCoordinator = (options) => {
6609
7021
  if (!sessionId) continue;
6610
7022
  completedSessionIds.add(sessionId);
6611
7023
  sessionsById.delete(sessionId);
7024
+ retainedById.delete(sessionId);
6612
7025
  }
6613
7026
  markSessionsDirty();
6614
7027
  };
@@ -6626,7 +7039,7 @@ var createExecutionRecordingCoordinator = (options) => {
6626
7039
  if (!sessionId || !executionKeyValue || status !== "active") continue;
6627
7040
  if (completedSessionIds.has(sessionId)) continue;
6628
7041
  if (!Number.isFinite(expiresAtMs) || expiresAtMs <= atMs || requestedCount < 1) continue;
6629
- const existing = sessionsById.get(sessionId);
7042
+ const existing = sessionsById.get(sessionId) ?? retainedById.get(sessionId);
6630
7043
  const overrides = parseSessionSettings(entry.overrides);
6631
7044
  next.set(sessionId, {
6632
7045
  sessionId,
@@ -6638,12 +7051,22 @@ var createExecutionRecordingCoordinator = (options) => {
6638
7051
  redactKeys: overrides?.redactKeys,
6639
7052
  excludeSources: overrides?.excludeSources,
6640
7053
  maxCapturedCallsPerFunction: overrides?.maxCapturedCallsPerFunction,
6641
- maxExecutionHoldMs: overrides?.maxExecutionHoldMs,
6642
- scrubPII: overrides?.scrubPII
7054
+ maxExecutionHoldMs: overrides?.maxExecutionHoldMs
6643
7055
  });
6644
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
+ }
6645
7067
  sessionsById.clear();
6646
7068
  for (const [id, session] of next) sessionsById.set(id, session);
7069
+ pruneRetained(atMs);
6647
7070
  markSessionsDirty();
6648
7071
  };
6649
7072
  const applyActivations = (activations) => {
@@ -6675,8 +7098,8 @@ var createExecutionRecordingCoordinator = (options) => {
6675
7098
  release: options.release,
6676
7099
  pid: process.pid,
6677
7100
  started_at: startedAt.toISOString(),
6678
- reported_mode: options.mode,
6679
- reported_settings: reportedRecorderSettings(options.recorderOptions, options.scrubPII),
7101
+ reported_mode: mode,
7102
+ reported_settings: reportedRecorderSettings(options.recorderOptions),
6680
7103
  capabilities
6681
7104
  }
6682
7105
  },
@@ -6735,8 +7158,7 @@ var createExecutionRecordingCoordinator = (options) => {
6735
7158
  redact_keys: copyRedactKeys([
6736
7159
  ...redactKeys ?? [],
6737
7160
  ...item.redactKeys ?? []
6738
- ])?.slice(0, MAX_REDACT_KEYS),
6739
- scrub_pii: item.scrubPii ?? scrubPii
7161
+ ])?.slice(0, MAX_REDACT_KEYS)
6740
7162
  }))
6741
7163
  },
6742
7164
  void 0,
@@ -6812,7 +7234,7 @@ var createExecutionRecordingCoordinator = (options) => {
6812
7234
  });
6813
7235
  };
6814
7236
  const activate = (metadata, window) => {
6815
- if (closed || options.mode !== "adaptive") return;
7237
+ if (closed || mode !== "adaptive") return;
6816
7238
  const key = executionTypeKey(metadata);
6817
7239
  if (!key) return;
6818
7240
  const atMs = nowMs();
@@ -6847,11 +7269,15 @@ var createExecutionRecordingCoordinator = (options) => {
6847
7269
  };
6848
7270
  const consumeSession = (executionKeyValue, sessionId) => {
6849
7271
  const atMs = nowMs();
6850
- for (const session of sessionsById.values()) {
7272
+ pruneRetained(atMs);
7273
+ const candidates = [...sessionsById.values(), ...retainedById.values()];
7274
+ for (const session of candidates) {
6851
7275
  if (session.executionKey !== executionKeyValue) continue;
6852
7276
  if (sessionId !== void 0 && session.sessionId !== sessionId) continue;
6853
- if (!sessionHasRoom(session, atMs)) continue;
7277
+ if (session.admitted >= session.requestedCount) continue;
7278
+ if (!withinUploadGrace(session, atMs)) continue;
6854
7279
  session.admitted += 1;
7280
+ if (session.admitted >= session.requestedCount) retainedById.delete(session.sessionId);
6855
7281
  markSessionsDirty();
6856
7282
  return sessionView(session);
6857
7283
  }
@@ -6932,6 +7358,7 @@ var createExecutionRecordingCoordinator = (options) => {
6932
7358
  closed = true;
6933
7359
  interruptWork();
6934
7360
  pending.clear();
7361
+ retainedById.clear();
6935
7362
  }
6936
7363
  }
6937
7364
  };
@@ -6940,7 +7367,7 @@ var createExecutionRecordingCoordinator = (options) => {
6940
7367
  // src/execution-recorder/bind-adaptive-recorder.ts
6941
7368
  var bindAdaptiveRecorder = (input) => {
6942
7369
  const options = input.executionRecorder;
6943
- const adaptiveEnabled = options?.adaptive?.enabled === true;
7370
+ const adaptiveEnabled = resolveExecutionRecordingMode(options) === "adaptive";
6944
7371
  const activation = resolveClientActivation({
6945
7372
  enabled: input.enabled,
6946
7373
  dsn: input.dsn,
@@ -6959,8 +7386,6 @@ var bindAdaptiveRecorder = (input) => {
6959
7386
  sdkVersion: input.sdkVersion,
6960
7387
  release: activation.release,
6961
7388
  recorderOptions: options,
6962
- scrubPII: input.scrubPII,
6963
- mode: adaptiveEnabled ? "adaptive" : "full",
6964
7389
  fetch: input.fetch
6965
7390
  }) : void 0;
6966
7391
  const recorderHooks = {};
@@ -7356,11 +7781,26 @@ var createFunctionMetricsCollector = (options) => {
7356
7781
  note2(coverage, "dropped_queue_budget", discardedMarks2(dropped.series));
7357
7782
  }
7358
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
+ };
7359
7795
  const closeMinute = (minute, table) => {
7360
7796
  active.delete(minute);
7361
7797
  activeSeries -= countSeries2(table);
7362
7798
  if (minute > lastClosedMinute) lastClosedMinute = minute;
7363
- 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 });
7364
7804
  };
7365
7805
  const rotate = (currentMinute) => {
7366
7806
  for (const minute of [...active.keys()]) {
@@ -8246,12 +8686,205 @@ var createDynamicDurationSampleBuckets = (options) => {
8246
8686
  }
8247
8687
  };
8248
8688
  };
8689
+
8690
+ // src/create-rasputin-runtime.ts
8691
+ var publicExecution = (runtime) => ({
8692
+ createScope: (metadata) => {
8693
+ const scope = runtime.createScope(metadata);
8694
+ return {
8695
+ run: scope.run,
8696
+ observeError: scope.observeError,
8697
+ finish: scope.finish,
8698
+ captureInput: scope.captureInput
8699
+ };
8700
+ },
8701
+ trace: runtime.trace,
8702
+ getStats: runtime.getStats
8703
+ });
8704
+ var wrapClient = (client, runtime, installRuntime, manifest, uninstallHandlers = () => {
8705
+ }, policy, metrics, executionMetrics) => {
8706
+ const uninstallRuntime = installRuntime ? installAutomaticExecutionRuntime(runtime) : () => {
8707
+ };
8708
+ const manifestUpload = scheduleInstrumentationManifestUpload({
8709
+ ...manifest,
8710
+ deferStart: true
8711
+ });
8712
+ const execution = publicExecution(runtime);
8713
+ 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)));
8750
+ }
8751
+ },
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: () => {
8771
+ }
8772
+ };
8773
+ };
8774
+ var createRasputinRuntime = (options, config) => {
8775
+ try {
8776
+ const enabled = isClientEnabled(options);
8777
+ const activation = resolveClientActivation2(options);
8778
+ const recorderEnabled = enabled && options.executionRecorder?.enabled !== false;
8779
+ const durationSampling = options.dynamicDurationSampling === true;
8780
+ const fetch = config.fetch;
8781
+ const metrics = activation.enabled ? bindFunctionMetrics({
8782
+ clientEnabled: true,
8783
+ environment: activation.environment,
8784
+ release: activation.release,
8785
+ ingestToken: activation.ingestToken,
8786
+ apiUrl: activation.apiUrl,
8787
+ fetch,
8788
+ sampledMeasurementFormat: durationSampling
8789
+ }) : void 0;
8790
+ const executionMetrics = activation.enabled ? bindExecutionMetrics({
8791
+ clientEnabled: true,
8792
+ environment: activation.environment,
8793
+ release: activation.release,
8794
+ ingestToken: activation.ingestToken,
8795
+ apiUrl: activation.apiUrl,
8796
+ fetch,
8797
+ sampledMeasurementFormat: durationSampling
8798
+ }) : void 0;
8799
+ const observeExecutions = recorderEnabled || Boolean(metrics) || Boolean(executionMetrics);
8800
+ const durationSampler = durationSampling && observeExecutions ? createDynamicDurationSampleBuckets({ nowMs: () => Date.now() }) : void 0;
8801
+ const { runtime, policy } = bindAdaptiveRecorder({
8802
+ executionRecorder: options.executionRecorder,
8803
+ recorderEnabled,
8804
+ dsn: options.dsn,
8805
+ projectApiKey: options.projectApiKey,
8806
+ apiUrl: options.apiUrl,
8807
+ release: options.release,
8808
+ environment: options.environment,
8809
+ enabled: options.enabled,
8810
+ sdkName: config.sdkName,
8811
+ sdkVersion: config.sdkVersion,
8812
+ fetch,
8813
+ functionMetrics: metrics?.collector,
8814
+ executionMetrics: executionMetrics?.collector,
8815
+ durationSampler
8816
+ });
8817
+ const client = createClient(options, {
8818
+ sdkVersion: config.sdkVersion,
8819
+ sdkName: config.sdkName,
8820
+ fetch,
8821
+ announceDeploy: false,
8822
+ installTransportSignalHandlers: config.installTransportSignalHandlers ?? options.installTransportSignalHandlers,
8823
+ redactKeys: copyRedactKeys2(options.executionRecorder?.redactKeys),
8824
+ resolveObservation: (observation) => runtime.getErrorState(observation)
8825
+ });
8826
+ if (enabled) {
8827
+ loadInstrumentationManifestIfPresent(
8828
+ options.instrumentationManifestPath ?? process.env.RASPUTIN_INSTRUMENTATION_MANIFEST ?? join(process.cwd(), ".rasputin", "instrumentation-manifest.json")
8829
+ );
8830
+ }
8831
+ let uninstallHandlers = () => {
8832
+ };
8833
+ const { client: wrappedClient, startManifestUpload } = wrapClient(
8834
+ client,
8835
+ runtime,
8836
+ observeExecutions,
8837
+ {
8838
+ projectApiKey: options.projectApiKey,
8839
+ release: options.release,
8840
+ apiUrl: options.apiUrl,
8841
+ fetch,
8842
+ enabled,
8843
+ sourceRoot: options.sourceRoot,
8844
+ sourceRoots: options.sourceRoots,
8845
+ logSuccess: options.logSuccess
8846
+ },
8847
+ () => uninstallHandlers(),
8848
+ policy,
8849
+ metrics,
8850
+ executionMetrics
8851
+ );
8852
+ const installProcessHandlers = (config.installGlobalHandlers ?? options.installGlobalHandlers) !== false;
8853
+ if (enabled && installProcessHandlers) {
8854
+ uninstallHandlers = installGlobalHandlers(wrappedClient);
8855
+ }
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
+ };
8877
+ } catch {
8878
+ return inertHandle(options);
8879
+ }
8880
+ };
8249
8881
  export {
8250
8882
  bindAdaptiveRecorder,
8251
8883
  bindExecutionMetrics,
8252
8884
  bindFunctionMetrics,
8253
8885
  createDynamicDurationSampleBuckets,
8254
8886
  createExecutionRecorder,
8887
+ createRasputinRuntime,
8255
8888
  inertErrorObservation,
8256
8889
  installAutomaticExecutionRuntime,
8257
8890
  installGlobalHandlers,