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