@rasputin-ai/node 0.10.2 → 0.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (33) hide show
  1. package/dist/auto-instrumentation/schedule-instrumentation-manifest-upload.d.ts +1 -1
  2. package/dist/auto-instrumentation/schedule-instrumentation-manifest-upload.d.ts.map +1 -1
  3. package/dist/execution-recorder/adaptive-recording-options.d.ts +4 -0
  4. package/dist/execution-recorder/adaptive-recording-options.d.ts.map +1 -0
  5. package/dist/execution-recorder/adaptive-recording-policy.d.ts +10 -0
  6. package/dist/execution-recorder/adaptive-recording-policy.d.ts.map +1 -0
  7. package/dist/execution-recorder/bind-adaptive-recorder.d.ts +21 -0
  8. package/dist/execution-recorder/bind-adaptive-recorder.d.ts.map +1 -0
  9. package/dist/execution-recorder/execution-identity.d.ts +9 -0
  10. package/dist/execution-recorder/execution-identity.d.ts.map +1 -0
  11. package/dist/execution-recorder/execution-journal.d.ts +4 -2
  12. package/dist/execution-recorder/execution-journal.d.ts.map +1 -1
  13. package/dist/execution-recorder/execution-recorder-hooks.d.ts +39 -0
  14. package/dist/execution-recorder/execution-recorder-hooks.d.ts.map +1 -0
  15. package/dist/execution-recorder/execution-recorder-types.d.ts +32 -1
  16. package/dist/execution-recorder/execution-recorder-types.d.ts.map +1 -1
  17. package/dist/execution-recorder/execution-recorder.d.ts +2 -1
  18. package/dist/execution-recorder/execution-recorder.d.ts.map +1 -1
  19. package/dist/execution-recorder/execution-recording-sync.d.ts +30 -0
  20. package/dist/execution-recorder/execution-recording-sync.d.ts.map +1 -0
  21. package/dist/execution-recorder/session-freeze-overrides.d.ts +37 -0
  22. package/dist/execution-recorder/session-freeze-overrides.d.ts.map +1 -0
  23. package/dist/execution-recorder/value-freeze.d.ts +1 -0
  24. package/dist/execution-recorder/value-freeze.d.ts.map +1 -1
  25. package/dist/index.js +1128 -54
  26. package/dist/instrument/bun.js +1 -1
  27. package/dist/instrument/node.js +1 -1
  28. package/dist/internal.d.ts +2 -0
  29. package/dist/internal.d.ts.map +1 -1
  30. package/dist/internal.js +1108 -46
  31. package/dist/rasputin-init.d.ts.map +1 -1
  32. package/dist/sdk-meta.d.ts +1 -1
  33. package/package.json +2 -2
package/dist/internal.js CHANGED
@@ -640,6 +640,23 @@ import {
640
640
  runtimeFunctionId as runtimeFunctionId2
641
641
  } from "@rasputin-ai/core";
642
642
 
643
+ // src/execution-recorder/adaptive-recording-options.ts
644
+ var DEFAULT_FULL_CAPTURE_DURATION_MS = 24 * 60 * 60 * 1e3;
645
+ var MIN_FULL_CAPTURE_DURATION_MS = 1e3;
646
+ var MAX_FULL_CAPTURE_DURATION_MS = 7 * 24 * 60 * 60 * 1e3;
647
+ var sanitizeRecorderMode = (mode) => {
648
+ return mode === "adaptive" ? "adaptive" : "full";
649
+ };
650
+ var sanitizeFullCaptureDurationMs = (value) => {
651
+ if (typeof value !== "number" || !Number.isFinite(value)) {
652
+ return DEFAULT_FULL_CAPTURE_DURATION_MS;
653
+ }
654
+ return Math.min(
655
+ MAX_FULL_CAPTURE_DURATION_MS,
656
+ Math.max(MIN_FULL_CAPTURE_DURATION_MS, Math.floor(value))
657
+ );
658
+ };
659
+
643
660
  // src/execution-recorder/error-observation.ts
644
661
  var bindings = /* @__PURE__ */ new WeakMap();
645
662
  var mintErrorObservation = (binding) => {
@@ -655,11 +672,36 @@ var inertErrorObservation = () => {
655
672
  return Object.freeze(/* @__PURE__ */ Object.create(null));
656
673
  };
657
674
 
675
+ // src/execution-recorder/execution-identity.ts
676
+ var MAX_EXECUTION_TYPE_KEY_LENGTH = 256;
677
+ var NAMED_KINDS = /* @__PURE__ */ new Set(["job", "scheduled", "custom", "serverless"]);
678
+ var trimmed = (value) => typeof value === "string" ? value.trim() : "";
679
+ var boundedKey = (key) => {
680
+ return key.length > 0 && key.length <= MAX_EXECUTION_TYPE_KEY_LENGTH ? key : void 0;
681
+ };
682
+ var executionTypeKey = (metadata) => {
683
+ if (metadata.kind === "http") {
684
+ const method = trimmed(metadata.request?.method).toUpperCase();
685
+ const route = trimmed(metadata.request?.route);
686
+ if (!method || !route) return void 0;
687
+ if (route.includes("?") || route.includes("://")) return void 0;
688
+ return boundedKey(`http:${method}:${route}`);
689
+ }
690
+ if (!NAMED_KINDS.has(metadata.kind)) return void 0;
691
+ const name = trimmed(metadata.name);
692
+ if (!name) return void 0;
693
+ return boundedKey(`${metadata.kind}:${name}`);
694
+ };
695
+ var isHttpClientErrorStatus = (status) => {
696
+ return typeof status === "number" && Number.isFinite(status) && status >= 400 && status < 500;
697
+ };
698
+
658
699
  // src/execution-recorder/execution-journal.ts
659
700
  var KIND_ENTER = 1;
660
701
  var KIND_EXIT = 2;
661
702
  var KIND_THROW = 3;
662
703
  var KIND_SUPPRESSED = 4;
704
+ var ARGS_OMITTED = Symbol("rasputin.argsOmitted");
663
705
  var NO_PARENT = 4294967295;
664
706
  var NO_SUPPRESSION = 4294967295;
665
707
  var MAX_POOLED_JOURNALS = 8;
@@ -857,17 +899,18 @@ var ExecutionJournal = class {
857
899
  callId: this.callId[index] ?? 0,
858
900
  functionId,
859
901
  timestampMs: relativeMs(this.timestampNs[index] ?? 0n),
860
- args: Array.isArray(payload) ? payload : [],
902
+ ...payload === ARGS_OMITTED ? { argsOmitted: true } : { args: Array.isArray(payload) ? payload : [] },
861
903
  ...parentCallId === NO_PARENT ? {} : { parentCallId }
862
904
  };
863
905
  }
864
906
  if (kind === KIND_EXIT) {
907
+ const payload = this.payloads[index];
865
908
  return {
866
909
  type: "function_exit",
867
910
  callId: this.callId[index] ?? 0,
868
911
  timestampMs: relativeMs(this.timestampNs[index] ?? 0n),
869
912
  durationMs: relativeMs(this.durationNs[index] ?? 0n),
870
- returnValue: this.payloads[index]
913
+ ...payload === ARGS_OMITTED ? {} : { returnValue: payload }
871
914
  };
872
915
  }
873
916
  if (kind === KIND_THROW) {
@@ -2553,7 +2596,13 @@ var emptyStats = {
2553
2596
  journalPoolMisses: 0,
2554
2597
  journalPoolSize: 0,
2555
2598
  journalAllocatedCapacity: 0,
2556
- attributionDegradations: 0
2599
+ attributionDegradations: 0,
2600
+ adaptiveLightExecutions: 0,
2601
+ adaptiveFullExecutions: 0,
2602
+ adaptiveActivations: 0,
2603
+ adaptiveNotifyFailures: 0,
2604
+ adaptiveRefreshFailures: 0,
2605
+ lastAdaptiveFailureKind: null
2557
2606
  };
2558
2607
  var noOpExecution = {
2559
2608
  createScope: () => ({
@@ -2561,6 +2610,8 @@ var noOpExecution = {
2561
2610
  getErrorState: () => void 0,
2562
2611
  observeError: () => inertErrorObservation(),
2563
2612
  finish: () => {
2613
+ },
2614
+ mergeMetadata: () => {
2564
2615
  }
2565
2616
  }),
2566
2617
  getErrorState: () => void 0,
@@ -2602,9 +2653,28 @@ var newSuppression = (group, parentCallId, startedAtNs, endedAtNs) => ({
2602
2653
  storageIndex: -1,
2603
2654
  retainedIndex: -1
2604
2655
  });
2605
- var createExecutionRecorder = (options) => {
2656
+ var EMPTY_POLICY_SNAPSHOT = /* @__PURE__ */ new Map();
2657
+ var EMPTY_SESSION_SNAPSHOT = /* @__PURE__ */ new Map();
2658
+ var createExecutionRecorder = (options, hooks = {}) => {
2606
2659
  if (!options?.enabled) return noOpExecution;
2607
2660
  warnIfMissingAsyncContextFrame();
2661
+ const recorderMode = sanitizeRecorderMode(options.mode);
2662
+ const fullCaptureDurationMs = sanitizeFullCaptureDurationMs(
2663
+ options.adaptive?.fullCaptureDurationMs
2664
+ );
2665
+ const localActivations = /* @__PURE__ */ new Map();
2666
+ const nowMs = () => hooks.nowMs?.() ?? Date.now();
2667
+ const policySnapshotFor = () => hooks.policySnapshot?.() ?? localActivations;
2668
+ const keyIsActive = (snapshot, key, atMs) => {
2669
+ const expiresAt = snapshot.get(key);
2670
+ return expiresAt !== void 0 && expiresAt > atMs;
2671
+ };
2672
+ const captureValuesFor = (metadata, snapshot, atMs) => {
2673
+ if (recorderMode !== "adaptive") return true;
2674
+ const key = executionTypeKey(metadata);
2675
+ if (!key) return false;
2676
+ return keyIsActive(snapshot, key, atMs);
2677
+ };
2608
2678
  const storage = new AsyncLocalStorage();
2609
2679
  const currentStore = () => {
2610
2680
  try {
@@ -2693,7 +2763,10 @@ var createExecutionRecorder = (options) => {
2693
2763
  measuredExecutions: 0,
2694
2764
  totalInlineWallTimeMs: 0,
2695
2765
  maxInlineWallTimeMs: 0,
2696
- attributionDegradations: 0
2766
+ attributionDegradations: 0,
2767
+ adaptiveLightExecutions: 0,
2768
+ adaptiveFullExecutions: 0,
2769
+ adaptiveActivations: 0
2697
2770
  };
2698
2771
  const addPhase = (key, nanoseconds) => {
2699
2772
  if (phases && nanoseconds > 0n) phases[key] += nanoseconds;
@@ -2704,8 +2777,8 @@ var createExecutionRecorder = (options) => {
2704
2777
  stats.totalInlineWallTimeMs = Math.round((stats.totalInlineWallTimeMs + inlineWallTimeMs) * 1e4) / 1e4;
2705
2778
  stats.maxInlineWallTimeMs = Math.max(stats.maxInlineWallTimeMs, inlineWallTimeMs);
2706
2779
  };
2707
- const freezeAndCount = (value) => {
2708
- const frozen = serializer.freeze(value);
2780
+ const freezeAndCount = (recording, value) => {
2781
+ const frozen = (recording.serializer ?? serializer).freeze(value);
2709
2782
  stats.serializedValues++;
2710
2783
  stats.serializedValueNodes += frozen.visitedNodes;
2711
2784
  stats.serializedValueBytes += frozen.estimatedBytes;
@@ -2713,26 +2786,119 @@ var createExecutionRecorder = (options) => {
2713
2786
  };
2714
2787
  const captureValue = (recording, value) => {
2715
2788
  try {
2716
- return memoryBudget.captureValue(recording.memory, value, freezeAndCount);
2789
+ return memoryBudget.captureValue(
2790
+ recording.memory,
2791
+ value,
2792
+ (item) => freezeAndCount(recording, item)
2793
+ );
2717
2794
  } catch {
2718
2795
  return { __rasputin_type: "unserializable" };
2719
2796
  }
2720
2797
  };
2721
- const encodeEventValues = (events) => events.map((event) => {
2798
+ const encodeEventValues = (recording, events) => events.map((event) => {
2799
+ const encode = (recording.serializer ?? serializer).encode;
2722
2800
  if (event.type === "function_enter") {
2723
2801
  return {
2724
2802
  ...event,
2725
- ...event.args === void 0 ? {} : { args: event.args.map((argument) => serializer.encode(argument)) }
2803
+ ...event.args === void 0 ? {} : { args: event.args.map((argument) => encode(argument)) }
2726
2804
  };
2727
2805
  }
2728
2806
  if (event.type === "function_exit") {
2729
- return { ...event, returnValue: serializer.encode(event.returnValue) };
2807
+ return event.returnValue === void 0 ? event : { ...event, returnValue: encode(event.returnValue) };
2730
2808
  }
2731
2809
  if (event.type === "function_throw") {
2732
- return { ...event, error: serializer.encode(event.error) };
2810
+ return { ...event, error: encode(event.error) };
2733
2811
  }
2734
2812
  return event;
2735
2813
  });
2814
+ const enterPayload = (recording, omitCallValues, args) => {
2815
+ if (!recording.captureValues) return ARGS_OMITTED;
2816
+ if (omitCallValues) return mapArrayLike(args, () => rasputinOmitted());
2817
+ return mapArrayLike(args, (argument) => captureValue(recording, argument));
2818
+ };
2819
+ const exitPayload = (recording, omitCallValues, value) => {
2820
+ if (!recording.captureValues) return ARGS_OMITTED;
2821
+ if (omitCallValues) return rasputinOmitted();
2822
+ return captureValue(recording, value);
2823
+ };
2824
+ const admitSession = (recording, session) => {
2825
+ const wasLight = recorderMode === "adaptive" && !recording.captureValues;
2826
+ recording.retainSuccess = true;
2827
+ recording.sessionId = session.sessionId;
2828
+ recording.captureValues = true;
2829
+ if (session.serializer) recording.serializer = session.serializer;
2830
+ if (session.redactKeys?.length) recording.sessionRedactKeys = session.redactKeys;
2831
+ if (session.scrubPII !== void 0) recording.sessionScrubPii = session.scrubPII;
2832
+ if (session.excludeSources?.length) {
2833
+ recording.sessionExcludes = createSourceExclusionMatcher(session.excludeSources);
2834
+ }
2835
+ if (session.maxCapturedCallsPerFunction !== void 0) {
2836
+ recording.sessionMaxCapturedCalls = Math.min(
2837
+ maxCapturedCallsPerFunction,
2838
+ Math.max(1, Math.round(session.maxCapturedCallsPerFunction))
2839
+ );
2840
+ }
2841
+ if (session.maxExecutionHoldMs !== void 0) {
2842
+ const requestedNs = BigInt(Math.max(1, Math.round(session.maxExecutionHoldMs))) * 1000000n;
2843
+ recording.sessionHoldNs = requestedNs < maxExecutionHoldNs ? requestedNs : maxExecutionHoldNs;
2844
+ }
2845
+ if (wasLight) {
2846
+ stats.adaptiveLightExecutions = Math.max(0, stats.adaptiveLightExecutions - 1);
2847
+ stats.adaptiveFullExecutions++;
2848
+ }
2849
+ };
2850
+ const skipCapture = (store, plan) => store.suppressCapture || plan.excluded || Boolean(store.recording.sessionExcludes?.(plan.definition));
2851
+ const capturedCallLimitFor = (recording) => recording.sessionMaxCapturedCalls ?? maxCapturedCallsPerFunction;
2852
+ const tryAdmitLiveSession = (recording) => {
2853
+ if (recording.retainSuccess || recording.finished) return;
2854
+ const key = executionTypeKey(recording.execution);
2855
+ if (!key) return;
2856
+ const peek = hooks.sessionCaptureSnapshot?.().get(key);
2857
+ if (!peek || peek.expiresAtMs <= recording.startedAtMs) return;
2858
+ const live = hooks.consumeSession?.(key, peek.sessionId);
2859
+ if (live) admitSession(recording, live);
2860
+ };
2861
+ const tryAdmitFromStartSnapshot = (recording) => {
2862
+ if (recording.retainSuccess || recording.finished) return;
2863
+ const key = executionTypeKey(recording.execution);
2864
+ if (!key) return;
2865
+ const peek = recording.sessionCaptureSnapshot.get(key);
2866
+ if (!peek || peek.expiresAtMs <= recording.startedAtMs) return;
2867
+ const live = hooks.consumeSession?.(key, peek.sessionId);
2868
+ if (live) admitSession(recording, live);
2869
+ };
2870
+ const completeIdentityFromSnapshot = (recording) => {
2871
+ if (recording.identityResolved || recording.finished) return;
2872
+ const key = executionTypeKey(recording.execution);
2873
+ if (!key) return;
2874
+ recording.identityResolved = true;
2875
+ tryAdmitFromStartSnapshot(recording);
2876
+ if (recording.captureValues || recorderMode !== "adaptive") return;
2877
+ if (keyIsActive(recording.policySnapshot, key, recording.startedAtMs)) {
2878
+ recording.captureValues = true;
2879
+ stats.adaptiveLightExecutions = Math.max(0, stats.adaptiveLightExecutions - 1);
2880
+ stats.adaptiveFullExecutions++;
2881
+ }
2882
+ };
2883
+ const maybeActivateAdaptive = (recording) => {
2884
+ if (recorderMode !== "adaptive" || recording.adaptiveActivated) return;
2885
+ if (isHttpClientErrorStatus(recording.execution.request?.status)) return;
2886
+ const key = executionTypeKey(recording.execution);
2887
+ if (!key) return;
2888
+ const atMs = nowMs();
2889
+ const snapshot = policySnapshotFor();
2890
+ if (keyIsActive(snapshot, key, atMs)) return;
2891
+ recording.adaptiveActivated = true;
2892
+ const window = { activatedAtMs: atMs, expiresAtMs: atMs + fullCaptureDurationMs };
2893
+ stats.adaptiveActivations++;
2894
+ if (hooks.onQualifyingFailure) {
2895
+ hooks.onQualifyingFailure(recording.execution, window);
2896
+ return;
2897
+ }
2898
+ if (!keyIsActive(localActivations, key, atMs)) {
2899
+ localActivations.set(key, window.expiresAtMs);
2900
+ }
2901
+ };
2736
2902
  const storePlan = (plan) => {
2737
2903
  plansByRuntimeId[plan.runtimePlanId] = plan;
2738
2904
  return plan;
@@ -2770,8 +2936,10 @@ var createExecutionRecorder = (options) => {
2770
2936
  };
2771
2937
  const eventsHaveOmittedValues = (events) => {
2772
2938
  for (const event of events) {
2773
- if (event.type === "function_enter" && (event.args ?? []).some((arg) => rasputinTagKind(arg) === "omitted")) {
2774
- return true;
2939
+ if (event.type === "function_enter") {
2940
+ if (event.argsOmitted || (event.args ?? []).some((arg) => rasputinTagKind(arg) === "omitted")) {
2941
+ return true;
2942
+ }
2775
2943
  }
2776
2944
  if (event.type === "function_exit" && rasputinTagKind(event.returnValue) === "omitted") {
2777
2945
  return true;
@@ -2817,7 +2985,7 @@ var createExecutionRecorder = (options) => {
2817
2985
  return {
2818
2986
  source,
2819
2987
  functionBoundaries: droppedEvents ? "partial" : "full",
2820
- functionValues: eventsHaveOmittedValues(events) ? "selective" : "full",
2988
+ functionValues: recording.captureValues ? eventsHaveOmittedValues(events) ? "selective" : "full" : "none",
2821
2989
  timings: droppedEvents ? "partial" : "full"
2822
2990
  };
2823
2991
  };
@@ -2835,7 +3003,7 @@ var createExecutionRecorder = (options) => {
2835
3003
  } else {
2836
3004
  if (recording.journal) {
2837
3005
  const materialized = recording.journal.materialize(plansByRuntimeId, recording.startedAtNs);
2838
- events = encodeEventValues(materialized.events);
3006
+ events = encodeEventValues(recording, materialized.events);
2839
3007
  if (recording.lateCapturedCallIds && recording.lateCapturedCallIds.size > 0) {
2840
3008
  events = events.map(
2841
3009
  (event) => event.type === "function_enter" && recording.lateCapturedCallIds?.has(event.callId) ? { ...event, capturedAt: "throw" } : event
@@ -3031,7 +3199,7 @@ var createExecutionRecorder = (options) => {
3031
3199
  liveRecordings.splice(index, 1);
3032
3200
  continue;
3033
3201
  }
3034
- if (nowNs - recording.startedAtNs < maxExecutionHoldNs) continue;
3202
+ if (nowNs - recording.startedAtNs < (recording.sessionHoldNs ?? maxExecutionHoldNs)) continue;
3035
3203
  try {
3036
3204
  expireLongLivedRecording(recording, nowNs);
3037
3205
  } catch {
@@ -3071,6 +3239,7 @@ var createExecutionRecorder = (options) => {
3071
3239
  const observeFailure = (recording, provenance) => {
3072
3240
  if (!recording.evidenceDiscarded) {
3073
3241
  retainFailure(recording);
3242
+ maybeActivateAdaptive(recording);
3074
3243
  }
3075
3244
  return mintOccurrence(recording, provenance);
3076
3245
  };
@@ -3138,7 +3307,7 @@ var createExecutionRecorder = (options) => {
3138
3307
  // snapshot without the exception itself would not be useful for investigation.
3139
3308
  value: (() => {
3140
3309
  try {
3141
- return freezeAndCount(error).value;
3310
+ return freezeAndCount(recording, error).value;
3142
3311
  } catch {
3143
3312
  return { __rasputin_type: "unserializable" };
3144
3313
  }
@@ -3157,7 +3326,7 @@ var createExecutionRecorder = (options) => {
3157
3326
  }
3158
3327
  const callId = ++recording.nextCallId;
3159
3328
  const capturedError = serializedError(recording, error, callId);
3160
- const recordedArgs = capturedArgs ?? mapArrayLike(args, (argument) => captureValue(recording, argument));
3329
+ const recordedArgs = capturedArgs ?? (recording.captureValues ? mapArrayLike(args, (argument) => captureValue(recording, argument)) : ARGS_OMITTED);
3161
3330
  const endedAtNs = process.hrtime.bigint();
3162
3331
  const droppedBefore = recording.journal.dropped;
3163
3332
  const retained = recording.journal.forceCompletedCall(
@@ -3215,6 +3384,23 @@ var createExecutionRecorder = (options) => {
3215
3384
  return void 0;
3216
3385
  }
3217
3386
  };
3387
+ const enqueueSessionRecording = (recording) => {
3388
+ if (recording.sessionRecordingEnqueued || !recording.sessionId) {
3389
+ return;
3390
+ }
3391
+ recording.sessionRecordingEnqueued = true;
3392
+ try {
3393
+ hooks.onSessionRecording?.({
3394
+ sessionId: recording.sessionId,
3395
+ executionId: recording.executionId,
3396
+ outcome: recording.hasError || recording.runFailed ? "error" : "success",
3397
+ runtimeState: stateFrom(recording),
3398
+ redactKeys: recording.sessionRedactKeys,
3399
+ scrubPii: recording.sessionScrubPii
3400
+ });
3401
+ } catch {
3402
+ }
3403
+ };
3218
3404
  const settleInFlight = (recording) => {
3219
3405
  if (recording.inFlightCalls > 0) recording.inFlightCalls--;
3220
3406
  releaseWhenIdle(recording);
@@ -3223,6 +3409,9 @@ var createExecutionRecorder = (options) => {
3223
3409
  try {
3224
3410
  if (!recording.finished || recording.inFlightCalls > 0) return;
3225
3411
  memoryBudget.release(recording.memory);
3412
+ if (recording.retainSuccess && !recording.sessionRecordingEnqueued) {
3413
+ enqueueSessionRecording(recording);
3414
+ }
3226
3415
  if (!recording.hasError && !recording.retainedForError) {
3227
3416
  discardSuccessfulEvidence(recording);
3228
3417
  return;
@@ -3242,10 +3431,13 @@ var createExecutionRecorder = (options) => {
3242
3431
  stats.activeExecutions = Math.max(0, stats.activeExecutions - 1);
3243
3432
  if (recording.runFailed && !recording.hasError) {
3244
3433
  retainFailure(recording);
3434
+ maybeActivateAdaptive(recording);
3245
3435
  }
3246
- if (!recording.hasError) {
3436
+ if (!recording.hasError && !recording.retainSuccess) {
3247
3437
  stats.successfulExecutionsDiscarded++;
3248
3438
  }
3439
+ const finishedKey = executionTypeKey(recording.execution);
3440
+ if (finishedKey) hooks.observeExecutionType?.(finishedKey);
3249
3441
  recording.finishedAtNs = process.hrtime.bigint();
3250
3442
  addRecorderTime(recording, recording.finishedAtNs - recorderStartedAtNs);
3251
3443
  recordInlineTiming(recording);
@@ -3266,16 +3458,28 @@ var createExecutionRecorder = (options) => {
3266
3458
  try {
3267
3459
  const recorderStartedAtNs = process.hrtime.bigint();
3268
3460
  sweepLongLivedExecutions(recorderStartedAtNs);
3461
+ const startedAtMs = nowMs();
3462
+ const livePolicy = policySnapshotFor();
3463
+ const execution = {
3464
+ ...metadata,
3465
+ ...metadata.request ? { request: { ...metadata.request } } : {}
3466
+ };
3467
+ const identityComplete = executionTypeKey(execution) !== void 0;
3468
+ const captureValues = captureValuesFor(execution, livePolicy, startedAtMs);
3469
+ const policySnapshot = recorderMode === "adaptive" && !identityComplete ? new Map(livePolicy) : EMPTY_POLICY_SNAPSHOT;
3470
+ const liveSessions = hooks.sessionCaptureSnapshot?.() ?? EMPTY_SESSION_SNAPSHOT;
3471
+ const sessionCaptureSnapshot = identityComplete ? EMPTY_SESSION_SNAPSHOT : new Map(liveSessions);
3472
+ if (recorderMode === "adaptive") {
3473
+ if (captureValues) stats.adaptiveFullExecutions++;
3474
+ else stats.adaptiveLightExecutions++;
3475
+ }
3269
3476
  const recording = {
3270
3477
  executionId: `${Date.now()}-${process.pid}-${++executionCounter}`,
3271
3478
  storageGeneration: ++storageClock,
3272
- startedAtMs: Date.now(),
3479
+ startedAtMs,
3273
3480
  startedAtNs: recorderStartedAtNs,
3274
3481
  inlineRecorderTimeNs: 0n,
3275
- execution: {
3276
- ...metadata,
3277
- ...metadata.request ? { request: { ...metadata.request } } : {}
3278
- },
3482
+ execution,
3279
3483
  journal: void 0,
3280
3484
  capturedErrors: /* @__PURE__ */ new WeakMap(),
3281
3485
  nextCallId: 0,
@@ -3285,8 +3489,13 @@ var createExecutionRecorder = (options) => {
3285
3489
  memory: memoryBudget.startExecution(),
3286
3490
  partialSnapshotCounted: false,
3287
3491
  sawAutomatic: false,
3288
- sawManual: false
3492
+ sawManual: false,
3493
+ captureValues,
3494
+ policySnapshot,
3495
+ identityResolved: identityComplete,
3496
+ sessionCaptureSnapshot
3289
3497
  };
3498
+ if (identityComplete) tryAdmitLiveSession(recording);
3290
3499
  stats.activeExecutions++;
3291
3500
  stats.peakActiveExecutions = Math.max(stats.peakActiveExecutions, stats.activeExecutions);
3292
3501
  liveRecordings.push(recording);
@@ -3333,7 +3542,14 @@ var createExecutionRecorder = (options) => {
3333
3542
  return void 0;
3334
3543
  }
3335
3544
  },
3336
- finish: (finishMetadata) => finish(store, finishMetadata)
3545
+ finish: (finishMetadata) => finish(store, finishMetadata),
3546
+ mergeMetadata: (nextMetadata) => {
3547
+ try {
3548
+ mergeExecutionMetadata(recording.execution, nextMetadata);
3549
+ completeIdentityFromSnapshot(recording);
3550
+ } catch {
3551
+ }
3552
+ }
3337
3553
  };
3338
3554
  } catch {
3339
3555
  return noOpExecution.createScope(metadata);
@@ -3383,7 +3599,7 @@ var createExecutionRecorder = (options) => {
3383
3599
  }
3384
3600
  stats.functionCallsObserved++;
3385
3601
  const recorderStartedAtNs = process.hrtime.bigint();
3386
- if (store.suppressCapture || plan.excluded) {
3602
+ if (skipCapture(store, plan)) {
3387
3603
  stats.functionCallsExcluded++;
3388
3604
  return runStore({ ...store, suppressCapture: true }, function __rasputinHandleRun__5() {
3389
3605
  addRecorderTime(store.recording, process.hrtime.bigint() - recorderStartedAtNs);
@@ -3400,7 +3616,7 @@ var createExecutionRecorder = (options) => {
3400
3616
  if (group.observedCalls === 1) journal?.notePlan(plan.runtimePlanId);
3401
3617
  } catch {
3402
3618
  }
3403
- if (group.observedCalls > maxCapturedCallsPerFunction) {
3619
+ if (group.observedCalls > capturedCallLimitFor(recording)) {
3404
3620
  const startedAtNs2 = process.hrtime.bigint();
3405
3621
  try {
3406
3622
  const result = runStore(store, function __rasputinHandleRun__5() {
@@ -3463,7 +3679,7 @@ var createExecutionRecorder = (options) => {
3463
3679
  }
3464
3680
  const callId = ++recording.nextCallId;
3465
3681
  const enterTimestampNs = process.hrtime.bigint() - recording.startedAtNs;
3466
- const capturedArgs = omitCallValues ? mapArrayLike(args, () => rasputinOmitted()) : mapArrayLike(args, (argument) => captureValue(recording, argument));
3682
+ const capturedArgs = enterPayload(recording, omitCallValues, args);
3467
3683
  try {
3468
3684
  journal.startCall(plan.runtimePlanId, callId, parentCallId, enterTimestampNs, capturedArgs);
3469
3685
  } catch {
@@ -3489,7 +3705,7 @@ var createExecutionRecorder = (options) => {
3489
3705
  (value) => {
3490
3706
  if (recording.journal) {
3491
3707
  const endedAtNs = process.hrtime.bigint();
3492
- const returnValue = omitCallValues ? rasputinOmitted() : captureValue(recording, value);
3708
+ const returnValue = exitPayload(recording, omitCallValues, value);
3493
3709
  recording.journal.finishCall(
3494
3710
  KIND_EXIT,
3495
3711
  callId,
@@ -3546,7 +3762,7 @@ var createExecutionRecorder = (options) => {
3546
3762
  try {
3547
3763
  if (this.status !== "failed") {
3548
3764
  this.status = "left";
3549
- this.pendingReturn = value;
3765
+ if (this.recording.captureValues) this.pendingReturn = value;
3550
3766
  }
3551
3767
  return value;
3552
3768
  } catch {
@@ -3562,19 +3778,21 @@ var createExecutionRecorder = (options) => {
3562
3778
  captureCompletedThrow(
3563
3779
  this.recording,
3564
3780
  this.plan,
3565
- liveArgs ?? this.args,
3781
+ this.recording.captureValues ? liveArgs ?? this.args : EMPTY_ARGS,
3566
3782
  this.parentCallId,
3567
3783
  this.startedAtNs,
3568
- error
3784
+ error,
3785
+ this.recording.captureValues ? void 0 : ARGS_OMITTED
3569
3786
  );
3570
3787
  } else if (this.mode === "dropped" && this.captureDroppedThrow && this.plan) {
3571
3788
  captureCompletedThrow(
3572
3789
  this.recording,
3573
3790
  this.plan,
3574
- this.args,
3791
+ this.recording.captureValues ? this.args : EMPTY_ARGS,
3575
3792
  this.parentCallId,
3576
3793
  this.startedAtNs,
3577
- error
3794
+ error,
3795
+ this.recording.captureValues ? void 0 : ARGS_OMITTED
3578
3796
  );
3579
3797
  }
3580
3798
  } catch {
@@ -3664,7 +3882,7 @@ var createExecutionRecorder = (options) => {
3664
3882
  const writeCapturedExit = (frame, value) => {
3665
3883
  if (!frame.recording.journal) return;
3666
3884
  const endedAtNs = process.hrtime.bigint();
3667
- const returnValue = frame.omitCallValues ? rasputinOmitted() : captureValue(frame.recording, value);
3885
+ const returnValue = exitPayload(frame.recording, frame.omitCallValues, value);
3668
3886
  frame.recording.journal.finishCall(
3669
3887
  KIND_EXIT,
3670
3888
  frame.callId,
@@ -3734,7 +3952,7 @@ var createExecutionRecorder = (options) => {
3734
3952
  const recording = store.recording;
3735
3953
  const omitCallValues = omitValues === true || plan.omitCallValues;
3736
3954
  const parentCallId = store.currentCallId;
3737
- if (store.suppressCapture || plan.excluded) {
3955
+ if (skipCapture(store, plan)) {
3738
3956
  stats.functionCallsExcluded++;
3739
3957
  const excludedStore = { ...store, suppressCapture: true };
3740
3958
  const frame = new CallFrame(
@@ -3764,13 +3982,14 @@ var createExecutionRecorder = (options) => {
3764
3982
  }
3765
3983
  const startedAtNs = process.hrtime.bigint();
3766
3984
  const parentStore = store;
3767
- if (group.observedCalls > maxCapturedCallsPerFunction) {
3985
+ const retainedArgs = recording.captureValues ? args : EMPTY_ARGS;
3986
+ if (group.observedCalls > capturedCallLimitFor(recording)) {
3768
3987
  return activateUncaptured(
3769
3988
  "suppressed",
3770
3989
  recording,
3771
3990
  parentStore,
3772
3991
  plan,
3773
- args,
3992
+ retainedArgs,
3774
3993
  omitCallValues,
3775
3994
  parentCallId,
3776
3995
  startedAtNs,
@@ -3785,7 +4004,7 @@ var createExecutionRecorder = (options) => {
3785
4004
  recording,
3786
4005
  parentStore,
3787
4006
  plan,
3788
- args,
4007
+ retainedArgs,
3789
4008
  omitCallValues,
3790
4009
  parentCallId,
3791
4010
  startedAtNs,
@@ -3799,7 +4018,7 @@ var createExecutionRecorder = (options) => {
3799
4018
  recording,
3800
4019
  parentStore,
3801
4020
  plan,
3802
- args,
4021
+ retainedArgs,
3803
4022
  omitCallValues,
3804
4023
  parentCallId,
3805
4024
  startedAtNs,
@@ -3813,7 +4032,7 @@ var createExecutionRecorder = (options) => {
3813
4032
  recording,
3814
4033
  parentStore,
3815
4034
  plan,
3816
- args,
4035
+ retainedArgs,
3817
4036
  omitCallValues,
3818
4037
  parentCallId,
3819
4038
  startedAtNs,
@@ -3823,7 +4042,7 @@ var createExecutionRecorder = (options) => {
3823
4042
  }
3824
4043
  const callId = ++recording.nextCallId;
3825
4044
  const enterTimestampNs = process.hrtime.bigint() - recording.startedAtNs;
3826
- const capturedArgs = omitCallValues ? mapArrayLike(args, () => rasputinOmitted()) : mapArrayLike(args, (argument) => captureValue(recording, argument));
4045
+ const capturedArgs = enterPayload(recording, omitCallValues, args);
3827
4046
  try {
3828
4047
  journal.startCall(plan.runtimePlanId, callId, parentCallId, enterTimestampNs, capturedArgs);
3829
4048
  } catch {
@@ -3833,7 +4052,7 @@ var createExecutionRecorder = (options) => {
3833
4052
  recording,
3834
4053
  parentStore,
3835
4054
  plan,
3836
- args,
4055
+ retainedArgs,
3837
4056
  omitCallValues,
3838
4057
  parentCallId,
3839
4058
  startedAtNs,
@@ -3848,7 +4067,7 @@ var createExecutionRecorder = (options) => {
3848
4067
  parentStore,
3849
4068
  callStore,
3850
4069
  plan,
3851
- args,
4070
+ retainedArgs,
3852
4071
  omitCallValues,
3853
4072
  parentCallId,
3854
4073
  startedAtNs,
@@ -3924,6 +4143,10 @@ var createExecutionRecorder = (options) => {
3924
4143
  ...stats,
3925
4144
  ...memoryBudget.getStats(),
3926
4145
  ...journalPool.stats(),
4146
+ adaptiveNotifyFailures: 0,
4147
+ adaptiveRefreshFailures: 0,
4148
+ lastAdaptiveFailureKind: null,
4149
+ ...hooks.getStats?.(),
3927
4150
  ...phases ? {
3928
4151
  phaseAlsNs: Number(phases.alsNs),
3929
4152
  phaseMaterializeNs: Number(phases.materializeNs)
@@ -3968,6 +4191,844 @@ var installAutomaticExecutionRuntime = (execution) => {
3968
4191
  };
3969
4192
  };
3970
4193
 
4194
+ // src/execution-recorder/bind-adaptive-recorder.ts
4195
+ import {
4196
+ resolveClientActivation,
4197
+ resolveEndpointUrls as resolveEndpointUrls2
4198
+ } from "@rasputin-ai/core";
4199
+
4200
+ // src/execution-recorder/execution-recording-sync.ts
4201
+ import {
4202
+ copyRedactKeys,
4203
+ defaultIngestFetch,
4204
+ encodeJsonRequestBodyAsync,
4205
+ MAX_REDACT_KEYS
4206
+ } from "@rasputin-ai/core";
4207
+
4208
+ // src/execution-recorder/session-freeze-overrides.ts
4209
+ var BOUNDS = {
4210
+ maxDepth: { min: 1, max: 8 },
4211
+ maxObjectKeys: { min: 1, max: 100 },
4212
+ maxArrayElements: { min: 1, max: 100 },
4213
+ maxStringLength: { min: 32, max: 4e3 },
4214
+ maxSerializedValueBytes: { min: 1024, max: 64 * 1024 }
4215
+ };
4216
+ var MAX_SERIALIZER_CACHE = 32;
4217
+ var isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
4218
+ var optionalFiniteNumber = (value) => typeof value === "number" && Number.isFinite(value) ? value : void 0;
4219
+ var optionalStringList = (value) => {
4220
+ if (!Array.isArray(value)) return void 0;
4221
+ const out = [];
4222
+ for (const item of value) {
4223
+ if (typeof item !== "string" || !item.trim()) continue;
4224
+ out.push(item.trim());
4225
+ }
4226
+ return out.length > 0 ? out : void 0;
4227
+ };
4228
+ var clampAgainstProcess = (requested, processValue, min, max) => {
4229
+ if (requested === void 0 || !Number.isFinite(requested)) return processValue;
4230
+ return Math.min(processValue, Math.min(max, Math.max(min, Math.round(requested))));
4231
+ };
4232
+ var parseSessionSettings = (value) => {
4233
+ if (!isRecord(value)) return void 0;
4234
+ const overrides = {};
4235
+ const maxDepth = optionalFiniteNumber(value.maxDepth);
4236
+ const maxObjectKeys = optionalFiniteNumber(value.maxObjectKeys);
4237
+ const maxArrayElements = optionalFiniteNumber(value.maxArrayElements);
4238
+ const maxStringLength = optionalFiniteNumber(value.maxStringLength);
4239
+ const maxSerializedValueBytes = optionalFiniteNumber(value.maxSerializedValueBytes);
4240
+ const maxCapturedCallsPerFunction = optionalFiniteNumber(value.maxCapturedCallsPerFunction);
4241
+ const maxExecutionHoldMs = optionalFiniteNumber(value.maxExecutionHoldMs);
4242
+ if (maxDepth !== void 0) overrides.maxDepth = maxDepth;
4243
+ if (maxObjectKeys !== void 0) overrides.maxObjectKeys = maxObjectKeys;
4244
+ if (maxArrayElements !== void 0) overrides.maxArrayElements = maxArrayElements;
4245
+ if (maxStringLength !== void 0) overrides.maxStringLength = maxStringLength;
4246
+ if (maxSerializedValueBytes !== void 0)
4247
+ overrides.maxSerializedValueBytes = maxSerializedValueBytes;
4248
+ if (maxCapturedCallsPerFunction !== void 0) {
4249
+ overrides.maxCapturedCallsPerFunction = maxCapturedCallsPerFunction;
4250
+ }
4251
+ if (maxExecutionHoldMs !== void 0) overrides.maxExecutionHoldMs = maxExecutionHoldMs;
4252
+ const excludeSources = optionalStringList(value.excludeSources);
4253
+ const redactKeys = optionalStringList(value.redactKeys);
4254
+ if (excludeSources) overrides.excludeSources = excludeSources;
4255
+ if (redactKeys) overrides.redactKeys = redactKeys;
4256
+ if (typeof value.scrubPII === "boolean") overrides.scrubPII = value.scrubPII;
4257
+ return Object.keys(overrides).length > 0 ? overrides : void 0;
4258
+ };
4259
+ var clampSessionFreezeLimits = (overrides, processLimits) => ({
4260
+ maxDepth: clampAgainstProcess(
4261
+ overrides?.maxDepth,
4262
+ processLimits.maxDepth,
4263
+ BOUNDS.maxDepth.min,
4264
+ BOUNDS.maxDepth.max
4265
+ ),
4266
+ maxObjectKeys: clampAgainstProcess(
4267
+ overrides?.maxObjectKeys,
4268
+ processLimits.maxObjectKeys,
4269
+ BOUNDS.maxObjectKeys.min,
4270
+ BOUNDS.maxObjectKeys.max
4271
+ ),
4272
+ maxArrayElements: clampAgainstProcess(
4273
+ overrides?.maxArrayElements,
4274
+ processLimits.maxArrayElements,
4275
+ BOUNDS.maxArrayElements.min,
4276
+ BOUNDS.maxArrayElements.max
4277
+ ),
4278
+ maxStringLength: clampAgainstProcess(
4279
+ overrides?.maxStringLength,
4280
+ processLimits.maxStringLength,
4281
+ BOUNDS.maxStringLength.min,
4282
+ BOUNDS.maxStringLength.max
4283
+ ),
4284
+ maxSerializedValueBytes: clampAgainstProcess(
4285
+ overrides?.maxSerializedValueBytes,
4286
+ processLimits.maxSerializedValueBytes,
4287
+ BOUNDS.maxSerializedValueBytes.min,
4288
+ BOUNDS.maxSerializedValueBytes.max
4289
+ )
4290
+ });
4291
+ var freezeLimitsFingerprint = (limits) => `${limits.maxDepth}:${limits.maxObjectKeys}:${limits.maxArrayElements}:${limits.maxStringLength}:${limits.maxSerializedValueBytes}`;
4292
+ var serializeSourceExclusions = (exclusions) => {
4293
+ if (!exclusions?.length) return void 0;
4294
+ const out = [];
4295
+ for (const item of exclusions) {
4296
+ if (typeof item === "string" && item.trim()) out.push(item.trim());
4297
+ else if (item instanceof RegExp) out.push(item.toString());
4298
+ }
4299
+ return out.length > 0 ? out : void 0;
4300
+ };
4301
+ var reportedRecorderSettings = (options, scrubPII) => ({
4302
+ maxDepth: options?.maxDepth,
4303
+ maxObjectKeys: options?.maxObjectKeys,
4304
+ maxArrayElements: options?.maxArrayElements,
4305
+ maxStringLength: options?.maxStringLength,
4306
+ maxSerializedValueBytes: options?.maxSerializedValueBytes,
4307
+ maxEventsPerExecution: options?.maxEventsPerExecution,
4308
+ maxCapturedCallsPerFunction: options?.maxCapturedCallsPerFunction,
4309
+ maxActiveMemoryBytes: options?.maxActiveMemoryBytes,
4310
+ maxExecutionHoldMs: options?.maxExecutionHoldMs,
4311
+ maxRetainedErrorRecordings: options?.maxRetainedErrorRecordings,
4312
+ fullCaptureDurationMs: options?.adaptive?.fullCaptureDurationMs,
4313
+ recorder_enabled: options?.enabled !== false,
4314
+ excludeSources: serializeSourceExclusions(options?.excludeSources),
4315
+ redactKeys: options?.redactKeys,
4316
+ scrubPII: scrubPII === true
4317
+ });
4318
+ var createSerializerCache = (options) => {
4319
+ const processLimits = compileFreezeLimits(options ?? {});
4320
+ const processFingerprint = freezeLimitsFingerprint(processLimits);
4321
+ const cache = /* @__PURE__ */ new Map();
4322
+ return {
4323
+ serializerFor: (overrides) => {
4324
+ const clamped = clampSessionFreezeLimits(overrides, processLimits);
4325
+ const fingerprint = freezeLimitsFingerprint(clamped);
4326
+ if (fingerprint === processFingerprint) return void 0;
4327
+ const existing = cache.get(fingerprint);
4328
+ if (existing) {
4329
+ cache.delete(fingerprint);
4330
+ cache.set(fingerprint, existing);
4331
+ return existing;
4332
+ }
4333
+ while (cache.size >= MAX_SERIALIZER_CACHE) {
4334
+ const oldest = cache.keys().next().value;
4335
+ if (oldest === void 0) break;
4336
+ cache.delete(oldest);
4337
+ }
4338
+ const created = createSafeSerializer(clamped);
4339
+ cache.set(fingerprint, created);
4340
+ return created;
4341
+ }
4342
+ };
4343
+ };
4344
+
4345
+ // src/execution-recorder/execution-recording-sync.ts
4346
+ var MAX_CACHE_ENTRIES = 1024;
4347
+ var MAX_PENDING_NOTIFIES = 32;
4348
+ var MAX_PENDING_TYPES = 64;
4349
+ var DEFAULT_POLL_INTERVAL_MS = 1e4;
4350
+ var REQUEST_TIMEOUT_MS = 5e3;
4351
+ var MAX_RETRIES = 5;
4352
+ var MAX_POLL_JITTER_MS = 2e3;
4353
+ var trimmed2 = (value) => typeof value === "string" ? value.trim() : "";
4354
+ var isRecord2 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
4355
+ var unwrapPayload = (body) => {
4356
+ if (!isRecord2(body)) return void 0;
4357
+ if ("payload" in body && isRecord2(body.payload)) return body.payload;
4358
+ return body;
4359
+ };
4360
+ var classifyHttpFailure = (status) => {
4361
+ if (status === 429) return "rate_limited";
4362
+ if (status >= 500) return "server_error";
4363
+ return "non_retryable_http";
4364
+ };
4365
+ var backoffMs = (attempt) => Math.min(3e3, 250 * 2 ** attempt);
4366
+ var createExecutionRecordingCoordinator = (options) => {
4367
+ const environment = trimmed2(options.environment);
4368
+ const nowMs = () => options.nowMs?.() ?? Date.now();
4369
+ const fetchFn = options.fetch ?? defaultIngestFetch();
4370
+ const networkEnabled = environment.length > 0;
4371
+ const instanceId = crypto.randomUUID();
4372
+ const startedAt = /* @__PURE__ */ new Date();
4373
+ const redactKeys = copyRedactKeys(options.recorderOptions?.redactKeys);
4374
+ const scrubPii = options.scrubPII === true;
4375
+ const serializers = createSerializerCache(options.recorderOptions);
4376
+ const cache = /* @__PURE__ */ new Map();
4377
+ const pending = /* @__PURE__ */ new Map();
4378
+ const catalog = /* @__PURE__ */ new Map();
4379
+ const sessionsById = /* @__PURE__ */ new Map();
4380
+ const completedSessionIds = /* @__PURE__ */ new Set();
4381
+ const recordings = [];
4382
+ const capabilities = ["catalog", "manual_sessions", "settings_overrides"];
4383
+ let closed = false;
4384
+ let closing = false;
4385
+ let sessionsDirty = true;
4386
+ let sessionSnapshot = /* @__PURE__ */ new Map();
4387
+ let syncFlight;
4388
+ let pollTimer;
4389
+ let pollStartTimer;
4390
+ let pump;
4391
+ let pumpAgain = false;
4392
+ let sendingKey;
4393
+ let recordingPump;
4394
+ let notifyFailures = 0;
4395
+ let refreshFailures = 0;
4396
+ let lastFailureKind = null;
4397
+ let pollAbort;
4398
+ let notifyAbort;
4399
+ let recordingAbort;
4400
+ let cancelWork = new AbortController();
4401
+ const rememberFailure = (kind) => {
4402
+ lastFailureKind = kind;
4403
+ };
4404
+ const dropExpiredCache = (atMs) => {
4405
+ for (const [key, expiresAt] of cache) {
4406
+ if (expiresAt <= atMs) cache.delete(key);
4407
+ }
4408
+ };
4409
+ const trimCache = () => {
4410
+ const atMs = nowMs();
4411
+ dropExpiredCache(atMs);
4412
+ while (cache.size > MAX_CACHE_ENTRIES) {
4413
+ const oldest = cache.keys().next().value;
4414
+ if (oldest === void 0) break;
4415
+ cache.delete(oldest);
4416
+ }
4417
+ };
4418
+ const peek = () => cache;
4419
+ const sessionView = (session) => ({
4420
+ sessionId: session.sessionId,
4421
+ expiresAtMs: session.expiresAtMs,
4422
+ serializer: session.serializer,
4423
+ redactKeys: session.redactKeys,
4424
+ excludeSources: session.excludeSources,
4425
+ maxCapturedCallsPerFunction: session.maxCapturedCallsPerFunction,
4426
+ maxExecutionHoldMs: session.maxExecutionHoldMs,
4427
+ scrubPII: session.scrubPII
4428
+ });
4429
+ const sessionHasRoom = (session, atMs) => session.admitted < session.requestedCount && session.expiresAtMs > atMs;
4430
+ const rebuildSessionSnapshot = () => {
4431
+ const atMs = nowMs();
4432
+ const map = /* @__PURE__ */ new Map();
4433
+ for (const session of sessionsById.values()) {
4434
+ if (!sessionHasRoom(session, atMs) || map.has(session.executionKey)) continue;
4435
+ map.set(session.executionKey, sessionView(session));
4436
+ }
4437
+ sessionSnapshot = map;
4438
+ sessionsDirty = false;
4439
+ };
4440
+ const markSessionsDirty = () => {
4441
+ sessionsDirty = true;
4442
+ };
4443
+ const notifySignal = () => {
4444
+ if (!notifyAbort || notifyAbort.signal.aborted) notifyAbort = new AbortController();
4445
+ return notifyAbort.signal;
4446
+ };
4447
+ const recordingSignal = () => {
4448
+ if (!recordingAbort || recordingAbort.signal.aborted) recordingAbort = new AbortController();
4449
+ return recordingAbort.signal;
4450
+ };
4451
+ const pollSignal = () => {
4452
+ if (!pollAbort || pollAbort.signal.aborted) pollAbort = new AbortController();
4453
+ return pollAbort.signal;
4454
+ };
4455
+ const wait = (ms, signal) => new Promise((resolve) => {
4456
+ if (signal.aborted) {
4457
+ resolve();
4458
+ return;
4459
+ }
4460
+ const timer = setTimeout(() => {
4461
+ signal.removeEventListener("abort", onAbort);
4462
+ resolve();
4463
+ }, ms);
4464
+ timer.unref?.();
4465
+ const onAbort = () => {
4466
+ clearTimeout(timer);
4467
+ resolve();
4468
+ };
4469
+ signal.addEventListener("abort", onAbort, { once: true });
4470
+ });
4471
+ const joinUntil = async (work, signal) => {
4472
+ if (!work || signal.aborted) return;
4473
+ let onAbort;
4474
+ const aborted = new Promise((resolve) => {
4475
+ onAbort = () => resolve();
4476
+ signal.addEventListener("abort", onAbort, { once: true });
4477
+ });
4478
+ try {
4479
+ await Promise.race([work, aborted]);
4480
+ } finally {
4481
+ if (onAbort) signal.removeEventListener("abort", onAbort);
4482
+ }
4483
+ };
4484
+ const workSignal = (signal) => AbortSignal.any([signal, cancelWork.signal]);
4485
+ const interruptWork = () => {
4486
+ cancelWork.abort();
4487
+ cancelWork = new AbortController();
4488
+ notifyAbort?.abort();
4489
+ recordingAbort?.abort();
4490
+ pollAbort?.abort();
4491
+ };
4492
+ const fetchEncoded = (url, encoded, requestSignal) => {
4493
+ const headers = {
4494
+ Authorization: `Bearer ${options.ingestToken}`,
4495
+ "Content-Type": "application/json",
4496
+ Accept: "application/json"
4497
+ };
4498
+ if (encoded.gzip) headers["Content-Encoding"] = "gzip";
4499
+ return fetchFn(url, {
4500
+ method: "POST",
4501
+ headers,
4502
+ body: encoded.body,
4503
+ signal: requestSignal
4504
+ });
4505
+ };
4506
+ const withRequestTimeout = async (signal, run) => {
4507
+ const combined = workSignal(signal);
4508
+ const timeout = new AbortController();
4509
+ const timer = setTimeout(() => timeout.abort(), REQUEST_TIMEOUT_MS);
4510
+ timer.unref?.();
4511
+ const onAbort = () => timeout.abort();
4512
+ combined.addEventListener("abort", onAbort, { once: true });
4513
+ if (combined.aborted) timeout.abort();
4514
+ const requestSignal = AbortSignal.any([combined, timeout.signal]);
4515
+ try {
4516
+ return await run(requestSignal);
4517
+ } finally {
4518
+ clearTimeout(timer);
4519
+ combined.removeEventListener("abort", onAbort);
4520
+ }
4521
+ };
4522
+ const postEncoded = async (url, encoded, signal, readBody) => withRequestTimeout(signal, async (requestSignal) => {
4523
+ const response = await fetchEncoded(url, encoded, requestSignal);
4524
+ const body = await readBody(response);
4525
+ return { response, body };
4526
+ });
4527
+ const postJson = async (url, body, signal, readBody) => postEncoded(url, { body: JSON.stringify(body), gzip: false }, signal, readBody);
4528
+ const sendNotify = async (item, signal) => {
4529
+ if (item.expiresAtMs <= nowMs()) return true;
4530
+ for (let attempt = 0; attempt <= MAX_RETRIES; attempt++) {
4531
+ if (signal.aborted) return false;
4532
+ if (item.expiresAtMs <= nowMs()) return true;
4533
+ try {
4534
+ const { response, body: payload } = await postJson(
4535
+ options.activateUrl,
4536
+ {
4537
+ environment,
4538
+ execution_key: item.executionKey,
4539
+ activated_at: new Date(item.activatedAtMs).toISOString(),
4540
+ expires_at: new Date(item.expiresAtMs).toISOString(),
4541
+ duration_ms: Math.max(1, item.expiresAtMs - item.activatedAtMs)
4542
+ },
4543
+ signal,
4544
+ async (activateResponse) => {
4545
+ if (!activateResponse.ok) return void 0;
4546
+ try {
4547
+ return unwrapPayload(await activateResponse.json());
4548
+ } catch {
4549
+ return void 0;
4550
+ }
4551
+ }
4552
+ );
4553
+ if (response.ok) {
4554
+ const expiresAt = Date.parse(String(payload?.expires_at ?? ""));
4555
+ if (Number.isFinite(expiresAt) && expiresAt > nowMs()) {
4556
+ cache.set(item.executionKey, expiresAt);
4557
+ }
4558
+ return true;
4559
+ }
4560
+ const kind = classifyHttpFailure(response.status);
4561
+ rememberFailure(kind);
4562
+ if (kind === "non_retryable_http") {
4563
+ notifyFailures++;
4564
+ return true;
4565
+ }
4566
+ if (attempt === MAX_RETRIES) {
4567
+ notifyFailures++;
4568
+ return false;
4569
+ }
4570
+ await wait(backoffMs(attempt), signal);
4571
+ } catch (error) {
4572
+ if (signal.aborted || error instanceof Error && error.name === "AbortError") {
4573
+ rememberFailure("aborted");
4574
+ return false;
4575
+ }
4576
+ rememberFailure("network_error");
4577
+ if (attempt === MAX_RETRIES) {
4578
+ notifyFailures++;
4579
+ return false;
4580
+ }
4581
+ await wait(backoffMs(attempt), signal);
4582
+ }
4583
+ }
4584
+ return false;
4585
+ };
4586
+ const runPump = async (signal) => {
4587
+ do {
4588
+ pumpAgain = false;
4589
+ const queued = new Set(pending.keys());
4590
+ for (const key of queued) {
4591
+ if (signal.aborted) return;
4592
+ const current = pending.get(key);
4593
+ if (!current) continue;
4594
+ sendingKey = key;
4595
+ const done = await sendNotify(current, signal);
4596
+ sendingKey = void 0;
4597
+ if (pending.get(key) !== current) pumpAgain = true;
4598
+ else if (done || !signal.aborted) pending.delete(key);
4599
+ }
4600
+ for (const key of pending.keys()) {
4601
+ if (!queued.has(key)) {
4602
+ pumpAgain = true;
4603
+ break;
4604
+ }
4605
+ }
4606
+ } while (pumpAgain && pending.size > 0 && !signal.aborted);
4607
+ };
4608
+ const drainNotifies = async (signal) => {
4609
+ while (pending.size > 0 && !signal.aborted) {
4610
+ if (pump) {
4611
+ pumpAgain = true;
4612
+ await joinUntil(pump, signal);
4613
+ continue;
4614
+ }
4615
+ const running = runPump(signal);
4616
+ pump = running;
4617
+ try {
4618
+ await running;
4619
+ } finally {
4620
+ if (pump === running) pump = void 0;
4621
+ }
4622
+ break;
4623
+ }
4624
+ };
4625
+ const kickNotify = () => {
4626
+ if (!networkEnabled || closed || closing || pending.size === 0 || options.mode !== "adaptive")
4627
+ return;
4628
+ void drainNotifies(notifySignal());
4629
+ };
4630
+ const rememberCatalog = (key, atMs) => {
4631
+ if (key.length === 0 || key.length > MAX_EXECUTION_TYPE_KEY_LENGTH) return;
4632
+ if (catalog.size >= MAX_CACHE_ENTRIES && !catalog.has(key)) {
4633
+ const oldest = catalog.keys().next().value;
4634
+ if (oldest !== void 0) catalog.delete(oldest);
4635
+ }
4636
+ catalog.set(key, atMs);
4637
+ };
4638
+ const applyCompletedSessionIds = (value) => {
4639
+ if (!Array.isArray(value)) return;
4640
+ for (const entry of value) {
4641
+ const sessionId = trimmed2(entry);
4642
+ if (!sessionId) continue;
4643
+ completedSessionIds.add(sessionId);
4644
+ sessionsById.delete(sessionId);
4645
+ }
4646
+ markSessionsDirty();
4647
+ };
4648
+ const applySessions = (entries) => {
4649
+ if (!Array.isArray(entries)) return;
4650
+ const atMs = nowMs();
4651
+ const next = /* @__PURE__ */ new Map();
4652
+ for (const entry of entries) {
4653
+ if (!isRecord2(entry)) continue;
4654
+ const sessionId = trimmed2(entry.id);
4655
+ const executionKeyValue = trimmed2(entry.execution_key);
4656
+ const status = trimmed2(entry.status);
4657
+ const expiresAtMs = Date.parse(String(entry.expires_at ?? ""));
4658
+ const requestedCount = typeof entry.requested_count === "number" && Number.isFinite(entry.requested_count) ? Math.round(entry.requested_count) : 0;
4659
+ if (!sessionId || !executionKeyValue || status !== "active") continue;
4660
+ if (completedSessionIds.has(sessionId)) continue;
4661
+ if (!Number.isFinite(expiresAtMs) || expiresAtMs <= atMs || requestedCount < 1) continue;
4662
+ const existing = sessionsById.get(sessionId);
4663
+ const overrides = parseSessionSettings(entry.overrides);
4664
+ next.set(sessionId, {
4665
+ sessionId,
4666
+ executionKey: executionKeyValue,
4667
+ expiresAtMs,
4668
+ requestedCount,
4669
+ admitted: existing?.admitted ?? 0,
4670
+ serializer: serializers.serializerFor(overrides),
4671
+ redactKeys: overrides?.redactKeys,
4672
+ excludeSources: overrides?.excludeSources,
4673
+ maxCapturedCallsPerFunction: overrides?.maxCapturedCallsPerFunction,
4674
+ maxExecutionHoldMs: overrides?.maxExecutionHoldMs,
4675
+ scrubPII: overrides?.scrubPII
4676
+ });
4677
+ }
4678
+ sessionsById.clear();
4679
+ for (const [id, session] of next) sessionsById.set(id, session);
4680
+ markSessionsDirty();
4681
+ };
4682
+ const applyActivations = (activations) => {
4683
+ if (!Array.isArray(activations)) return;
4684
+ const atMs = nowMs();
4685
+ const seen = /* @__PURE__ */ new Set();
4686
+ for (const entry of activations) {
4687
+ if (!isRecord2(entry)) continue;
4688
+ const key = trimmed2(entry.execution_key);
4689
+ const expiresAt = Date.parse(String(entry.expires_at ?? ""));
4690
+ if (!key || !Number.isFinite(expiresAt) || expiresAt <= atMs) continue;
4691
+ cache.set(key, expiresAt);
4692
+ seen.add(key);
4693
+ }
4694
+ trimCache();
4695
+ for (const key of seen) pending.delete(key);
4696
+ };
4697
+ const catalogTypes = () => {
4698
+ const entries = [];
4699
+ for (const [executionKey, lastSeenAtMs] of catalog) {
4700
+ entries.push({ executionKey, lastSeenAtMs });
4701
+ if (entries.length >= MAX_PENDING_TYPES) break;
4702
+ }
4703
+ return entries;
4704
+ };
4705
+ const syncOnce = async (signal) => {
4706
+ if (!networkEnabled || closed) return;
4707
+ const types2 = catalogTypes();
4708
+ try {
4709
+ const { response, body: payload } = await postJson(
4710
+ options.syncUrl,
4711
+ {
4712
+ environment,
4713
+ instance: {
4714
+ id: instanceId,
4715
+ sdk_name: options.sdkName,
4716
+ sdk_version: options.sdkVersion,
4717
+ release: options.release,
4718
+ pid: process.pid,
4719
+ started_at: startedAt.toISOString(),
4720
+ reported_mode: options.mode,
4721
+ reported_settings: reportedRecorderSettings(options.recorderOptions, options.scrubPII),
4722
+ capabilities
4723
+ },
4724
+ types: types2.map((entry) => ({
4725
+ execution_key: entry.executionKey,
4726
+ last_seen_at: new Date(entry.lastSeenAtMs).toISOString()
4727
+ }))
4728
+ },
4729
+ signal,
4730
+ async (syncResponse) => {
4731
+ if (!syncResponse.ok) return void 0;
4732
+ return unwrapPayload(await syncResponse.json());
4733
+ }
4734
+ );
4735
+ if (!response.ok) {
4736
+ rememberFailure(classifyHttpFailure(response.status));
4737
+ refreshFailures++;
4738
+ return;
4739
+ }
4740
+ applyActivations(payload?.activations);
4741
+ applySessions(payload?.sessions);
4742
+ for (const entry of types2) {
4743
+ const current = catalog.get(entry.executionKey);
4744
+ if (current === void 0) continue;
4745
+ catalog.delete(entry.executionKey);
4746
+ if (current !== entry.lastSeenAtMs) {
4747
+ catalog.set(entry.executionKey, current);
4748
+ }
4749
+ }
4750
+ } catch (error) {
4751
+ if (signal.aborted || error instanceof Error && error.name === "AbortError") {
4752
+ rememberFailure("aborted");
4753
+ } else {
4754
+ rememberFailure("network_error");
4755
+ }
4756
+ refreshFailures++;
4757
+ }
4758
+ };
4759
+ const runSyncOnce = async (signal) => {
4760
+ if (syncFlight) {
4761
+ await joinUntil(syncFlight, signal);
4762
+ return;
4763
+ }
4764
+ const running = syncOnce(signal);
4765
+ const flight = running.finally(() => {
4766
+ if (syncFlight === flight) syncFlight = void 0;
4767
+ });
4768
+ syncFlight = flight;
4769
+ await joinUntil(flight, signal);
4770
+ };
4771
+ const sendRecordings = async (batch, signal) => {
4772
+ const combined = workSignal(signal);
4773
+ if (combined.aborted) return false;
4774
+ let encoded;
4775
+ try {
4776
+ encoded = await encodeJsonRequestBodyAsync(
4777
+ {
4778
+ instance_id: instanceId,
4779
+ recordings: batch.map((item) => ({
4780
+ session_id: item.sessionId,
4781
+ execution_id: item.executionId,
4782
+ outcome: item.outcome,
4783
+ runtime_state: item.runtimeState,
4784
+ release: options.release,
4785
+ redact_keys: copyRedactKeys([...redactKeys ?? [], ...item.redactKeys ?? []])?.slice(
4786
+ 0,
4787
+ MAX_REDACT_KEYS
4788
+ ),
4789
+ scrub_pii: item.scrubPii ?? scrubPii
4790
+ }))
4791
+ },
4792
+ void 0,
4793
+ combined
4794
+ );
4795
+ } catch (error) {
4796
+ if (combined.aborted || error instanceof Error && error.name === "AbortError") {
4797
+ rememberFailure("aborted");
4798
+ return false;
4799
+ }
4800
+ rememberFailure("network_error");
4801
+ return false;
4802
+ }
4803
+ for (let attempt = 0; attempt <= MAX_RETRIES; attempt++) {
4804
+ if (combined.aborted) return false;
4805
+ try {
4806
+ const { response, body } = await postEncoded(
4807
+ options.recordingsUrl,
4808
+ encoded,
4809
+ combined,
4810
+ async (uploadResponse) => {
4811
+ if (!uploadResponse.ok) return void 0;
4812
+ try {
4813
+ return unwrapPayload(await uploadResponse.json());
4814
+ } catch {
4815
+ return void 0;
4816
+ }
4817
+ }
4818
+ );
4819
+ if (response.ok) {
4820
+ applyCompletedSessionIds(body?.completed_session_ids);
4821
+ return true;
4822
+ }
4823
+ const kind = classifyHttpFailure(response.status);
4824
+ rememberFailure(kind);
4825
+ if (kind === "non_retryable_http") return true;
4826
+ if (attempt === MAX_RETRIES) return false;
4827
+ await wait(backoffMs(attempt), combined);
4828
+ } catch (error) {
4829
+ if (combined.aborted || error instanceof Error && error.name === "AbortError") {
4830
+ rememberFailure("aborted");
4831
+ return false;
4832
+ }
4833
+ rememberFailure("network_error");
4834
+ if (attempt === MAX_RETRIES) return false;
4835
+ await wait(backoffMs(attempt), combined);
4836
+ }
4837
+ }
4838
+ return false;
4839
+ };
4840
+ const drainRecordings = async (signal) => {
4841
+ while (recordings.length > 0 && !signal.aborted) {
4842
+ const batch = recordings.splice(0, 8);
4843
+ const ok = await sendRecordings(batch, signal);
4844
+ if (!ok) {
4845
+ recordings.unshift(...batch);
4846
+ break;
4847
+ }
4848
+ }
4849
+ };
4850
+ const kickRecordings = () => {
4851
+ if (!networkEnabled || closed || closing || recordings.length === 0) return;
4852
+ if (recordingPump) return;
4853
+ const running = drainRecordings(recordingSignal());
4854
+ recordingPump = running;
4855
+ void running.finally(() => {
4856
+ if (recordingPump === running) recordingPump = void 0;
4857
+ if (recordings.length > 0) kickRecordings();
4858
+ });
4859
+ };
4860
+ const activate = (metadata, window) => {
4861
+ if (closed || options.mode !== "adaptive") return;
4862
+ const key = executionTypeKey(metadata);
4863
+ if (!key) return;
4864
+ const atMs = nowMs();
4865
+ const existing = cache.get(key);
4866
+ if (existing !== void 0 && existing > atMs) return;
4867
+ cache.set(key, window.expiresAtMs);
4868
+ trimCache();
4869
+ if (!networkEnabled || window.expiresAtMs <= atMs) return;
4870
+ if (pending.size >= MAX_PENDING_NOTIFIES && !pending.has(key)) {
4871
+ for (const oldest of pending.keys()) {
4872
+ if (oldest !== sendingKey) {
4873
+ pending.delete(oldest);
4874
+ break;
4875
+ }
4876
+ }
4877
+ }
4878
+ pending.set(key, { executionKey: key, ...window });
4879
+ kickNotify();
4880
+ };
4881
+ const peekSessions = () => {
4882
+ if (sessionsDirty) rebuildSessionSnapshot();
4883
+ else {
4884
+ const atMs = nowMs();
4885
+ for (const session of sessionSnapshot.values()) {
4886
+ if (session.expiresAtMs <= atMs) {
4887
+ rebuildSessionSnapshot();
4888
+ break;
4889
+ }
4890
+ }
4891
+ }
4892
+ return sessionSnapshot;
4893
+ };
4894
+ const consumeSession = (executionKeyValue, sessionId) => {
4895
+ const atMs = nowMs();
4896
+ for (const session of sessionsById.values()) {
4897
+ if (session.executionKey !== executionKeyValue) continue;
4898
+ if (sessionId !== void 0 && session.sessionId !== sessionId) continue;
4899
+ if (!sessionHasRoom(session, atMs)) continue;
4900
+ session.admitted += 1;
4901
+ markSessionsDirty();
4902
+ return sessionView(session);
4903
+ }
4904
+ return void 0;
4905
+ };
4906
+ const observeType = (executionKeyValue) => {
4907
+ rememberCatalog(executionKeyValue, nowMs());
4908
+ };
4909
+ const enqueueRecording = (payload) => {
4910
+ if (closed || closing) return;
4911
+ recordings.push(payload);
4912
+ kickRecordings();
4913
+ };
4914
+ if (networkEnabled) {
4915
+ const interval = options.pollIntervalMs ?? DEFAULT_POLL_INTERVAL_MS;
4916
+ const jitterMax = Math.max(0, options.pollJitterMs ?? MAX_POLL_JITTER_MS);
4917
+ const delay = interval + Math.floor(Math.random() * jitterMax);
4918
+ pollStartTimer = setTimeout(() => {
4919
+ pollStartTimer = void 0;
4920
+ if (closed || closing) return;
4921
+ void runSyncOnce(pollSignal());
4922
+ pollTimer = setInterval(() => {
4923
+ if (closed || closing) return;
4924
+ void runSyncOnce(pollSignal());
4925
+ }, interval);
4926
+ pollTimer.unref?.();
4927
+ }, delay);
4928
+ pollStartTimer.unref?.();
4929
+ }
4930
+ const stopTimers = () => {
4931
+ if (pollStartTimer) {
4932
+ clearTimeout(pollStartTimer);
4933
+ pollStartTimer = void 0;
4934
+ }
4935
+ if (pollTimer) {
4936
+ clearInterval(pollTimer);
4937
+ pollTimer = void 0;
4938
+ }
4939
+ };
4940
+ return {
4941
+ peek,
4942
+ activate,
4943
+ peekSessions,
4944
+ consumeSession,
4945
+ observeType,
4946
+ enqueueRecording,
4947
+ getStats: () => ({
4948
+ adaptiveNotifyFailures: notifyFailures,
4949
+ adaptiveRefreshFailures: refreshFailures,
4950
+ lastAdaptiveFailureKind: lastFailureKind
4951
+ }),
4952
+ flush: async (timeoutMs = 2e3) => {
4953
+ if (!networkEnabled || closed || closing) return;
4954
+ const flushAbort = new AbortController();
4955
+ const onAbort = () => interruptWork();
4956
+ flushAbort.signal.addEventListener("abort", onAbort, { once: true });
4957
+ const timer = setTimeout(() => flushAbort.abort(), Math.max(0, timeoutMs));
4958
+ try {
4959
+ await runSyncOnce(flushAbort.signal);
4960
+ if (!flushAbort.signal.aborted) await drainNotifies(flushAbort.signal);
4961
+ await joinUntil(recordingPump, flushAbort.signal);
4962
+ if (!flushAbort.signal.aborted) await drainRecordings(flushAbort.signal);
4963
+ } finally {
4964
+ clearTimeout(timer);
4965
+ flushAbort.signal.removeEventListener("abort", onAbort);
4966
+ }
4967
+ },
4968
+ close: async () => {
4969
+ if (closed || closing) return;
4970
+ closing = true;
4971
+ stopTimers();
4972
+ const deadline = new AbortController();
4973
+ const timer = setTimeout(() => {
4974
+ deadline.abort();
4975
+ interruptWork();
4976
+ }, 2e3);
4977
+ try {
4978
+ if (networkEnabled) await runSyncOnce(deadline.signal);
4979
+ if (!deadline.signal.aborted) await drainNotifies(deadline.signal);
4980
+ await joinUntil(recordingPump, deadline.signal);
4981
+ if (!deadline.signal.aborted) await drainRecordings(deadline.signal);
4982
+ } finally {
4983
+ clearTimeout(timer);
4984
+ closed = true;
4985
+ interruptWork();
4986
+ pending.clear();
4987
+ }
4988
+ }
4989
+ };
4990
+ };
4991
+
4992
+ // src/execution-recorder/bind-adaptive-recorder.ts
4993
+ var bindAdaptiveRecorder = (input) => {
4994
+ const options = input.executionRecorder;
4995
+ const mode = sanitizeRecorderMode(options?.mode);
4996
+ const activation = resolveClientActivation({
4997
+ enabled: input.enabled,
4998
+ dsn: input.dsn,
4999
+ projectApiKey: input.projectApiKey,
5000
+ apiUrl: input.apiUrl,
5001
+ release: input.release
5002
+ });
5003
+ const coordinator = input.recorderEnabled && activation.enabled ? createExecutionRecordingCoordinator({
5004
+ environment: input.environment ?? "",
5005
+ ingestToken: activation.ingestToken,
5006
+ activateUrl: resolveEndpointUrls2(activation.apiUrl).executionRecordingActivateUrl,
5007
+ syncUrl: resolveEndpointUrls2(activation.apiUrl).executionRecordingSyncUrl,
5008
+ recordingsUrl: resolveEndpointUrls2(activation.apiUrl).executionRecordingRecordingsUrl,
5009
+ sdkName: input.sdkName,
5010
+ sdkVersion: input.sdkVersion,
5011
+ release: activation.release,
5012
+ recorderOptions: options,
5013
+ scrubPII: input.scrubPII,
5014
+ mode,
5015
+ fetch: input.fetch
5016
+ }) : void 0;
5017
+ const runtime = createExecutionRecorder(
5018
+ { ...options, enabled: input.recorderEnabled },
5019
+ coordinator ? {
5020
+ policySnapshot: coordinator.peek,
5021
+ onQualifyingFailure: mode === "adaptive" ? coordinator.activate : void 0,
5022
+ getStats: coordinator.getStats,
5023
+ sessionCaptureSnapshot: coordinator.peekSessions,
5024
+ consumeSession: coordinator.consumeSession,
5025
+ observeExecutionType: coordinator.observeType,
5026
+ onSessionRecording: coordinator.enqueueRecording
5027
+ } : void 0
5028
+ );
5029
+ return { runtime, policy: coordinator };
5030
+ };
5031
+
3971
5032
  // src/install-global-handlers.ts
3972
5033
  var RASPUTIN_PROCESS_LISTENER = Symbol.for("rasputin.process.listener.v1");
3973
5034
  var unhandledRejectionMode = () => {
@@ -4104,6 +5165,7 @@ var installGlobalHandlers = (client, options = {}) => {
4104
5165
  };
4105
5166
  };
4106
5167
  export {
5168
+ bindAdaptiveRecorder,
4107
5169
  createExecutionRecorder,
4108
5170
  inertErrorObservation,
4109
5171
  installAutomaticExecutionRuntime,