@rasputin-ai/node 0.10.2 → 0.11.1

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 +1168 -58
  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 +1148 -50
  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) {
@@ -1226,7 +1269,7 @@ var settleFinalBytes = (state) => {
1226
1269
  var dropEventValues = (events) => {
1227
1270
  let dropped = 0;
1228
1271
  const marker = () => rasputinUnavailable(VALUE_OMITTED_REASON);
1229
- const bounded = events.map((event) => {
1272
+ const bounded2 = events.map((event) => {
1230
1273
  if (event.type === "function_enter") {
1231
1274
  if (event.args === void 0) return { ...event };
1232
1275
  dropped += event.args.length;
@@ -1242,7 +1285,7 @@ var dropEventValues = (events) => {
1242
1285
  }
1243
1286
  return { ...event };
1244
1287
  });
1245
- return { events: bounded, dropped };
1288
+ return { events: bounded2, dropped };
1246
1289
  };
1247
1290
  var truncateUtf8 = (value, maximumBytes) => {
1248
1291
  if (value === void 0 || Buffer.byteLength(value, "utf8") <= maximumBytes) return value;
@@ -2348,8 +2391,8 @@ var encodeFrozenWithBytes = (frozen, visitedNodes, maxSerializedValueBytes) => {
2348
2391
  const encoded = encodeFrozen(frozen);
2349
2392
  const bytes = jsonLiteralUtf8Bytes(encoded);
2350
2393
  if (!isByteBudgetStub(encoded) && bytes > maxSerializedValueBytes) {
2351
- const bounded = truncation("max_serialized_value_bytes", { __serialized_bytes: bytes });
2352
- return { value: bounded, bytes: jsonLiteralUtf8Bytes(bounded), visitedNodes };
2394
+ const bounded2 = truncation("max_serialized_value_bytes", { __serialized_bytes: bytes });
2395
+ return { value: bounded2, bytes: jsonLiteralUtf8Bytes(bounded2), visitedNodes };
2353
2396
  }
2354
2397
  return { value: encoded, bytes, visitedNodes };
2355
2398
  };
@@ -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,118 @@ 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.max(
2837
+ 1,
2838
+ Math.round(session.maxCapturedCallsPerFunction)
2839
+ );
2840
+ }
2841
+ if (session.maxExecutionHoldMs !== void 0) {
2842
+ recording.sessionHoldNs = BigInt(Math.max(1, Math.round(session.maxExecutionHoldMs))) * 1000000n;
2843
+ }
2844
+ if (wasLight) {
2845
+ stats.adaptiveLightExecutions = Math.max(0, stats.adaptiveLightExecutions - 1);
2846
+ stats.adaptiveFullExecutions++;
2847
+ }
2848
+ };
2849
+ const skipCapture = (store, plan) => store.suppressCapture || plan.excluded || Boolean(store.recording.sessionExcludes?.(plan.definition));
2850
+ const capturedCallLimitFor = (recording) => recording.sessionMaxCapturedCalls ?? maxCapturedCallsPerFunction;
2851
+ const tryAdmitLiveSession = (recording) => {
2852
+ if (recording.retainSuccess || recording.finished) return;
2853
+ const key = executionTypeKey(recording.execution);
2854
+ if (!key) return;
2855
+ const peek = hooks.sessionCaptureSnapshot?.().get(key);
2856
+ if (!peek || peek.expiresAtMs <= recording.startedAtMs) return;
2857
+ const live = hooks.consumeSession?.(key, peek.sessionId);
2858
+ if (live) admitSession(recording, live);
2859
+ };
2860
+ const tryAdmitFromStartSnapshot = (recording) => {
2861
+ if (recording.retainSuccess || recording.finished) return;
2862
+ const key = executionTypeKey(recording.execution);
2863
+ if (!key) return;
2864
+ const peek = recording.sessionCaptureSnapshot.get(key);
2865
+ if (!peek || peek.expiresAtMs <= recording.startedAtMs) return;
2866
+ const live = hooks.consumeSession?.(key, peek.sessionId);
2867
+ if (live) admitSession(recording, live);
2868
+ };
2869
+ const completeIdentityFromSnapshot = (recording) => {
2870
+ if (recording.identityResolved || recording.finished) return;
2871
+ const key = executionTypeKey(recording.execution);
2872
+ if (!key) return;
2873
+ recording.identityResolved = true;
2874
+ tryAdmitFromStartSnapshot(recording);
2875
+ if (recording.captureValues || recorderMode !== "adaptive") return;
2876
+ if (keyIsActive(recording.policySnapshot, key, recording.startedAtMs)) {
2877
+ recording.captureValues = true;
2878
+ stats.adaptiveLightExecutions = Math.max(0, stats.adaptiveLightExecutions - 1);
2879
+ stats.adaptiveFullExecutions++;
2880
+ }
2881
+ };
2882
+ const maybeActivateAdaptive = (recording) => {
2883
+ if (recorderMode !== "adaptive" || recording.adaptiveActivated) return;
2884
+ if (isHttpClientErrorStatus(recording.execution.request?.status)) return;
2885
+ const key = executionTypeKey(recording.execution);
2886
+ if (!key) return;
2887
+ const atMs = nowMs();
2888
+ const snapshot = policySnapshotFor();
2889
+ if (keyIsActive(snapshot, key, atMs)) return;
2890
+ recording.adaptiveActivated = true;
2891
+ const window = { activatedAtMs: atMs, expiresAtMs: atMs + fullCaptureDurationMs };
2892
+ stats.adaptiveActivations++;
2893
+ if (hooks.onQualifyingFailure) {
2894
+ hooks.onQualifyingFailure(recording.execution, window);
2895
+ return;
2896
+ }
2897
+ if (!keyIsActive(localActivations, key, atMs)) {
2898
+ localActivations.set(key, window.expiresAtMs);
2899
+ }
2900
+ };
2736
2901
  const storePlan = (plan) => {
2737
2902
  plansByRuntimeId[plan.runtimePlanId] = plan;
2738
2903
  return plan;
@@ -2770,8 +2935,10 @@ var createExecutionRecorder = (options) => {
2770
2935
  };
2771
2936
  const eventsHaveOmittedValues = (events) => {
2772
2937
  for (const event of events) {
2773
- if (event.type === "function_enter" && (event.args ?? []).some((arg) => rasputinTagKind(arg) === "omitted")) {
2774
- return true;
2938
+ if (event.type === "function_enter") {
2939
+ if (event.argsOmitted || (event.args ?? []).some((arg) => rasputinTagKind(arg) === "omitted")) {
2940
+ return true;
2941
+ }
2775
2942
  }
2776
2943
  if (event.type === "function_exit" && rasputinTagKind(event.returnValue) === "omitted") {
2777
2944
  return true;
@@ -2817,7 +2984,7 @@ var createExecutionRecorder = (options) => {
2817
2984
  return {
2818
2985
  source,
2819
2986
  functionBoundaries: droppedEvents ? "partial" : "full",
2820
- functionValues: eventsHaveOmittedValues(events) ? "selective" : "full",
2987
+ functionValues: recording.captureValues ? eventsHaveOmittedValues(events) ? "selective" : "full" : "none",
2821
2988
  timings: droppedEvents ? "partial" : "full"
2822
2989
  };
2823
2990
  };
@@ -2835,7 +3002,7 @@ var createExecutionRecorder = (options) => {
2835
3002
  } else {
2836
3003
  if (recording.journal) {
2837
3004
  const materialized = recording.journal.materialize(plansByRuntimeId, recording.startedAtNs);
2838
- events = encodeEventValues(materialized.events);
3005
+ events = encodeEventValues(recording, materialized.events);
2839
3006
  if (recording.lateCapturedCallIds && recording.lateCapturedCallIds.size > 0) {
2840
3007
  events = events.map(
2841
3008
  (event) => event.type === "function_enter" && recording.lateCapturedCallIds?.has(event.callId) ? { ...event, capturedAt: "throw" } : event
@@ -3031,7 +3198,7 @@ var createExecutionRecorder = (options) => {
3031
3198
  liveRecordings.splice(index, 1);
3032
3199
  continue;
3033
3200
  }
3034
- if (nowNs - recording.startedAtNs < maxExecutionHoldNs) continue;
3201
+ if (nowNs - recording.startedAtNs < (recording.sessionHoldNs ?? maxExecutionHoldNs)) continue;
3035
3202
  try {
3036
3203
  expireLongLivedRecording(recording, nowNs);
3037
3204
  } catch {
@@ -3071,6 +3238,7 @@ var createExecutionRecorder = (options) => {
3071
3238
  const observeFailure = (recording, provenance) => {
3072
3239
  if (!recording.evidenceDiscarded) {
3073
3240
  retainFailure(recording);
3241
+ maybeActivateAdaptive(recording);
3074
3242
  }
3075
3243
  return mintOccurrence(recording, provenance);
3076
3244
  };
@@ -3138,7 +3306,7 @@ var createExecutionRecorder = (options) => {
3138
3306
  // snapshot without the exception itself would not be useful for investigation.
3139
3307
  value: (() => {
3140
3308
  try {
3141
- return freezeAndCount(error).value;
3309
+ return freezeAndCount(recording, error).value;
3142
3310
  } catch {
3143
3311
  return { __rasputin_type: "unserializable" };
3144
3312
  }
@@ -3157,7 +3325,7 @@ var createExecutionRecorder = (options) => {
3157
3325
  }
3158
3326
  const callId = ++recording.nextCallId;
3159
3327
  const capturedError = serializedError(recording, error, callId);
3160
- const recordedArgs = capturedArgs ?? mapArrayLike(args, (argument) => captureValue(recording, argument));
3328
+ const recordedArgs = capturedArgs ?? (recording.captureValues ? mapArrayLike(args, (argument) => captureValue(recording, argument)) : ARGS_OMITTED);
3161
3329
  const endedAtNs = process.hrtime.bigint();
3162
3330
  const droppedBefore = recording.journal.dropped;
3163
3331
  const retained = recording.journal.forceCompletedCall(
@@ -3215,6 +3383,23 @@ var createExecutionRecorder = (options) => {
3215
3383
  return void 0;
3216
3384
  }
3217
3385
  };
3386
+ const enqueueSessionRecording = (recording) => {
3387
+ if (recording.sessionRecordingEnqueued || !recording.sessionId) {
3388
+ return;
3389
+ }
3390
+ recording.sessionRecordingEnqueued = true;
3391
+ try {
3392
+ hooks.onSessionRecording?.({
3393
+ sessionId: recording.sessionId,
3394
+ executionId: recording.executionId,
3395
+ outcome: recording.hasError || recording.runFailed ? "error" : "success",
3396
+ runtimeState: stateFrom(recording),
3397
+ redactKeys: recording.sessionRedactKeys,
3398
+ scrubPii: recording.sessionScrubPii
3399
+ });
3400
+ } catch {
3401
+ }
3402
+ };
3218
3403
  const settleInFlight = (recording) => {
3219
3404
  if (recording.inFlightCalls > 0) recording.inFlightCalls--;
3220
3405
  releaseWhenIdle(recording);
@@ -3223,6 +3408,9 @@ var createExecutionRecorder = (options) => {
3223
3408
  try {
3224
3409
  if (!recording.finished || recording.inFlightCalls > 0) return;
3225
3410
  memoryBudget.release(recording.memory);
3411
+ if (recording.retainSuccess && !recording.sessionRecordingEnqueued) {
3412
+ enqueueSessionRecording(recording);
3413
+ }
3226
3414
  if (!recording.hasError && !recording.retainedForError) {
3227
3415
  discardSuccessfulEvidence(recording);
3228
3416
  return;
@@ -3242,10 +3430,13 @@ var createExecutionRecorder = (options) => {
3242
3430
  stats.activeExecutions = Math.max(0, stats.activeExecutions - 1);
3243
3431
  if (recording.runFailed && !recording.hasError) {
3244
3432
  retainFailure(recording);
3433
+ maybeActivateAdaptive(recording);
3245
3434
  }
3246
- if (!recording.hasError) {
3435
+ if (!recording.hasError && !recording.retainSuccess) {
3247
3436
  stats.successfulExecutionsDiscarded++;
3248
3437
  }
3438
+ const finishedKey = executionTypeKey(recording.execution);
3439
+ if (finishedKey) hooks.observeExecutionType?.(finishedKey);
3249
3440
  recording.finishedAtNs = process.hrtime.bigint();
3250
3441
  addRecorderTime(recording, recording.finishedAtNs - recorderStartedAtNs);
3251
3442
  recordInlineTiming(recording);
@@ -3266,16 +3457,28 @@ var createExecutionRecorder = (options) => {
3266
3457
  try {
3267
3458
  const recorderStartedAtNs = process.hrtime.bigint();
3268
3459
  sweepLongLivedExecutions(recorderStartedAtNs);
3460
+ const startedAtMs = nowMs();
3461
+ const livePolicy = policySnapshotFor();
3462
+ const execution = {
3463
+ ...metadata,
3464
+ ...metadata.request ? { request: { ...metadata.request } } : {}
3465
+ };
3466
+ const identityComplete = executionTypeKey(execution) !== void 0;
3467
+ const captureValues = captureValuesFor(execution, livePolicy, startedAtMs);
3468
+ const policySnapshot = recorderMode === "adaptive" && !identityComplete ? new Map(livePolicy) : EMPTY_POLICY_SNAPSHOT;
3469
+ const liveSessions = hooks.sessionCaptureSnapshot?.() ?? EMPTY_SESSION_SNAPSHOT;
3470
+ const sessionCaptureSnapshot = identityComplete ? EMPTY_SESSION_SNAPSHOT : new Map(liveSessions);
3471
+ if (recorderMode === "adaptive") {
3472
+ if (captureValues) stats.adaptiveFullExecutions++;
3473
+ else stats.adaptiveLightExecutions++;
3474
+ }
3269
3475
  const recording = {
3270
3476
  executionId: `${Date.now()}-${process.pid}-${++executionCounter}`,
3271
3477
  storageGeneration: ++storageClock,
3272
- startedAtMs: Date.now(),
3478
+ startedAtMs,
3273
3479
  startedAtNs: recorderStartedAtNs,
3274
3480
  inlineRecorderTimeNs: 0n,
3275
- execution: {
3276
- ...metadata,
3277
- ...metadata.request ? { request: { ...metadata.request } } : {}
3278
- },
3481
+ execution,
3279
3482
  journal: void 0,
3280
3483
  capturedErrors: /* @__PURE__ */ new WeakMap(),
3281
3484
  nextCallId: 0,
@@ -3285,8 +3488,13 @@ var createExecutionRecorder = (options) => {
3285
3488
  memory: memoryBudget.startExecution(),
3286
3489
  partialSnapshotCounted: false,
3287
3490
  sawAutomatic: false,
3288
- sawManual: false
3491
+ sawManual: false,
3492
+ captureValues,
3493
+ policySnapshot,
3494
+ identityResolved: identityComplete,
3495
+ sessionCaptureSnapshot
3289
3496
  };
3497
+ if (identityComplete) tryAdmitLiveSession(recording);
3290
3498
  stats.activeExecutions++;
3291
3499
  stats.peakActiveExecutions = Math.max(stats.peakActiveExecutions, stats.activeExecutions);
3292
3500
  liveRecordings.push(recording);
@@ -3333,7 +3541,14 @@ var createExecutionRecorder = (options) => {
3333
3541
  return void 0;
3334
3542
  }
3335
3543
  },
3336
- finish: (finishMetadata) => finish(store, finishMetadata)
3544
+ finish: (finishMetadata) => finish(store, finishMetadata),
3545
+ mergeMetadata: (nextMetadata) => {
3546
+ try {
3547
+ mergeExecutionMetadata(recording.execution, nextMetadata);
3548
+ completeIdentityFromSnapshot(recording);
3549
+ } catch {
3550
+ }
3551
+ }
3337
3552
  };
3338
3553
  } catch {
3339
3554
  return noOpExecution.createScope(metadata);
@@ -3383,7 +3598,7 @@ var createExecutionRecorder = (options) => {
3383
3598
  }
3384
3599
  stats.functionCallsObserved++;
3385
3600
  const recorderStartedAtNs = process.hrtime.bigint();
3386
- if (store.suppressCapture || plan.excluded) {
3601
+ if (skipCapture(store, plan)) {
3387
3602
  stats.functionCallsExcluded++;
3388
3603
  return runStore({ ...store, suppressCapture: true }, function __rasputinHandleRun__5() {
3389
3604
  addRecorderTime(store.recording, process.hrtime.bigint() - recorderStartedAtNs);
@@ -3400,7 +3615,7 @@ var createExecutionRecorder = (options) => {
3400
3615
  if (group.observedCalls === 1) journal?.notePlan(plan.runtimePlanId);
3401
3616
  } catch {
3402
3617
  }
3403
- if (group.observedCalls > maxCapturedCallsPerFunction) {
3618
+ if (group.observedCalls > capturedCallLimitFor(recording)) {
3404
3619
  const startedAtNs2 = process.hrtime.bigint();
3405
3620
  try {
3406
3621
  const result = runStore(store, function __rasputinHandleRun__5() {
@@ -3463,7 +3678,7 @@ var createExecutionRecorder = (options) => {
3463
3678
  }
3464
3679
  const callId = ++recording.nextCallId;
3465
3680
  const enterTimestampNs = process.hrtime.bigint() - recording.startedAtNs;
3466
- const capturedArgs = omitCallValues ? mapArrayLike(args, () => rasputinOmitted()) : mapArrayLike(args, (argument) => captureValue(recording, argument));
3681
+ const capturedArgs = enterPayload(recording, omitCallValues, args);
3467
3682
  try {
3468
3683
  journal.startCall(plan.runtimePlanId, callId, parentCallId, enterTimestampNs, capturedArgs);
3469
3684
  } catch {
@@ -3489,7 +3704,7 @@ var createExecutionRecorder = (options) => {
3489
3704
  (value) => {
3490
3705
  if (recording.journal) {
3491
3706
  const endedAtNs = process.hrtime.bigint();
3492
- const returnValue = omitCallValues ? rasputinOmitted() : captureValue(recording, value);
3707
+ const returnValue = exitPayload(recording, omitCallValues, value);
3493
3708
  recording.journal.finishCall(
3494
3709
  KIND_EXIT,
3495
3710
  callId,
@@ -3546,7 +3761,7 @@ var createExecutionRecorder = (options) => {
3546
3761
  try {
3547
3762
  if (this.status !== "failed") {
3548
3763
  this.status = "left";
3549
- this.pendingReturn = value;
3764
+ if (this.recording.captureValues) this.pendingReturn = value;
3550
3765
  }
3551
3766
  return value;
3552
3767
  } catch {
@@ -3562,19 +3777,21 @@ var createExecutionRecorder = (options) => {
3562
3777
  captureCompletedThrow(
3563
3778
  this.recording,
3564
3779
  this.plan,
3565
- liveArgs ?? this.args,
3780
+ this.recording.captureValues ? liveArgs ?? this.args : EMPTY_ARGS,
3566
3781
  this.parentCallId,
3567
3782
  this.startedAtNs,
3568
- error
3783
+ error,
3784
+ this.recording.captureValues ? void 0 : ARGS_OMITTED
3569
3785
  );
3570
3786
  } else if (this.mode === "dropped" && this.captureDroppedThrow && this.plan) {
3571
3787
  captureCompletedThrow(
3572
3788
  this.recording,
3573
3789
  this.plan,
3574
- this.args,
3790
+ this.recording.captureValues ? this.args : EMPTY_ARGS,
3575
3791
  this.parentCallId,
3576
3792
  this.startedAtNs,
3577
- error
3793
+ error,
3794
+ this.recording.captureValues ? void 0 : ARGS_OMITTED
3578
3795
  );
3579
3796
  }
3580
3797
  } catch {
@@ -3664,7 +3881,7 @@ var createExecutionRecorder = (options) => {
3664
3881
  const writeCapturedExit = (frame, value) => {
3665
3882
  if (!frame.recording.journal) return;
3666
3883
  const endedAtNs = process.hrtime.bigint();
3667
- const returnValue = frame.omitCallValues ? rasputinOmitted() : captureValue(frame.recording, value);
3884
+ const returnValue = exitPayload(frame.recording, frame.omitCallValues, value);
3668
3885
  frame.recording.journal.finishCall(
3669
3886
  KIND_EXIT,
3670
3887
  frame.callId,
@@ -3734,7 +3951,7 @@ var createExecutionRecorder = (options) => {
3734
3951
  const recording = store.recording;
3735
3952
  const omitCallValues = omitValues === true || plan.omitCallValues;
3736
3953
  const parentCallId = store.currentCallId;
3737
- if (store.suppressCapture || plan.excluded) {
3954
+ if (skipCapture(store, plan)) {
3738
3955
  stats.functionCallsExcluded++;
3739
3956
  const excludedStore = { ...store, suppressCapture: true };
3740
3957
  const frame = new CallFrame(
@@ -3764,13 +3981,14 @@ var createExecutionRecorder = (options) => {
3764
3981
  }
3765
3982
  const startedAtNs = process.hrtime.bigint();
3766
3983
  const parentStore = store;
3767
- if (group.observedCalls > maxCapturedCallsPerFunction) {
3984
+ const retainedArgs = recording.captureValues ? args : EMPTY_ARGS;
3985
+ if (group.observedCalls > capturedCallLimitFor(recording)) {
3768
3986
  return activateUncaptured(
3769
3987
  "suppressed",
3770
3988
  recording,
3771
3989
  parentStore,
3772
3990
  plan,
3773
- args,
3991
+ retainedArgs,
3774
3992
  omitCallValues,
3775
3993
  parentCallId,
3776
3994
  startedAtNs,
@@ -3785,7 +4003,7 @@ var createExecutionRecorder = (options) => {
3785
4003
  recording,
3786
4004
  parentStore,
3787
4005
  plan,
3788
- args,
4006
+ retainedArgs,
3789
4007
  omitCallValues,
3790
4008
  parentCallId,
3791
4009
  startedAtNs,
@@ -3799,7 +4017,7 @@ var createExecutionRecorder = (options) => {
3799
4017
  recording,
3800
4018
  parentStore,
3801
4019
  plan,
3802
- args,
4020
+ retainedArgs,
3803
4021
  omitCallValues,
3804
4022
  parentCallId,
3805
4023
  startedAtNs,
@@ -3813,7 +4031,7 @@ var createExecutionRecorder = (options) => {
3813
4031
  recording,
3814
4032
  parentStore,
3815
4033
  plan,
3816
- args,
4034
+ retainedArgs,
3817
4035
  omitCallValues,
3818
4036
  parentCallId,
3819
4037
  startedAtNs,
@@ -3823,7 +4041,7 @@ var createExecutionRecorder = (options) => {
3823
4041
  }
3824
4042
  const callId = ++recording.nextCallId;
3825
4043
  const enterTimestampNs = process.hrtime.bigint() - recording.startedAtNs;
3826
- const capturedArgs = omitCallValues ? mapArrayLike(args, () => rasputinOmitted()) : mapArrayLike(args, (argument) => captureValue(recording, argument));
4044
+ const capturedArgs = enterPayload(recording, omitCallValues, args);
3827
4045
  try {
3828
4046
  journal.startCall(plan.runtimePlanId, callId, parentCallId, enterTimestampNs, capturedArgs);
3829
4047
  } catch {
@@ -3833,7 +4051,7 @@ var createExecutionRecorder = (options) => {
3833
4051
  recording,
3834
4052
  parentStore,
3835
4053
  plan,
3836
- args,
4054
+ retainedArgs,
3837
4055
  omitCallValues,
3838
4056
  parentCallId,
3839
4057
  startedAtNs,
@@ -3848,7 +4066,7 @@ var createExecutionRecorder = (options) => {
3848
4066
  parentStore,
3849
4067
  callStore,
3850
4068
  plan,
3851
- args,
4069
+ retainedArgs,
3852
4070
  omitCallValues,
3853
4071
  parentCallId,
3854
4072
  startedAtNs,
@@ -3924,6 +4142,10 @@ var createExecutionRecorder = (options) => {
3924
4142
  ...stats,
3925
4143
  ...memoryBudget.getStats(),
3926
4144
  ...journalPool.stats(),
4145
+ adaptiveNotifyFailures: 0,
4146
+ adaptiveRefreshFailures: 0,
4147
+ lastAdaptiveFailureKind: null,
4148
+ ...hooks.getStats?.(),
3927
4149
  ...phases ? {
3928
4150
  phaseAlsNs: Number(phases.alsNs),
3929
4151
  phaseMaterializeNs: Number(phases.materializeNs)
@@ -3968,6 +4190,881 @@ var installAutomaticExecutionRuntime = (execution) => {
3968
4190
  };
3969
4191
  };
3970
4192
 
4193
+ // src/execution-recorder/bind-adaptive-recorder.ts
4194
+ import {
4195
+ resolveClientActivation,
4196
+ resolveEndpointUrls as resolveEndpointUrls2
4197
+ } from "@rasputin-ai/core";
4198
+
4199
+ // src/execution-recorder/execution-recording-sync.ts
4200
+ import {
4201
+ copyRedactKeys,
4202
+ defaultIngestFetch,
4203
+ encodeJsonRequestBodyAsync,
4204
+ MAX_REDACT_KEYS
4205
+ } from "@rasputin-ai/core";
4206
+
4207
+ // src/execution-recorder/session-freeze-overrides.ts
4208
+ var BOUNDS = {
4209
+ maxDepth: { min: 1, max: 8 },
4210
+ maxObjectKeys: { min: 1, max: 100 },
4211
+ maxArrayElements: { min: 1, max: 100 },
4212
+ maxStringLength: { min: 32, max: 4e3 },
4213
+ maxSerializedValueBytes: { min: 1024, max: 64 * 1024 },
4214
+ maxCapturedCallsPerFunction: { min: 1, max: 100 },
4215
+ maxExecutionHoldMs: { min: 1e3, max: 5 * 6e4 }
4216
+ };
4217
+ var MAX_SERIALIZER_CACHE = 32;
4218
+ var isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
4219
+ var optionalFiniteNumber = (value) => typeof value === "number" && Number.isFinite(value) ? value : void 0;
4220
+ var optionalStringList = (value) => {
4221
+ if (!Array.isArray(value)) return void 0;
4222
+ const out = [];
4223
+ for (const item of value) {
4224
+ if (typeof item !== "string" || !item.trim()) continue;
4225
+ out.push(item.trim());
4226
+ }
4227
+ return out.length > 0 ? out : void 0;
4228
+ };
4229
+ var bounded = (value, min, max) => Math.min(max, Math.max(min, Math.round(value)));
4230
+ var clampToBounds = (requested, fallback, min, max) => {
4231
+ if (requested === void 0 || !Number.isFinite(requested)) return fallback;
4232
+ return bounded(requested, min, max);
4233
+ };
4234
+ var parseSessionSettings = (value) => {
4235
+ if (!isRecord(value)) return void 0;
4236
+ const overrides = {};
4237
+ const maxDepth = optionalFiniteNumber(value.maxDepth);
4238
+ const maxObjectKeys = optionalFiniteNumber(value.maxObjectKeys);
4239
+ const maxArrayElements = optionalFiniteNumber(value.maxArrayElements);
4240
+ const maxStringLength = optionalFiniteNumber(value.maxStringLength);
4241
+ const maxSerializedValueBytes = optionalFiniteNumber(value.maxSerializedValueBytes);
4242
+ const maxCapturedCallsPerFunction = optionalFiniteNumber(value.maxCapturedCallsPerFunction);
4243
+ const maxExecutionHoldMs = optionalFiniteNumber(value.maxExecutionHoldMs);
4244
+ if (maxDepth !== void 0)
4245
+ overrides.maxDepth = bounded(maxDepth, BOUNDS.maxDepth.min, BOUNDS.maxDepth.max);
4246
+ if (maxObjectKeys !== void 0) {
4247
+ overrides.maxObjectKeys = bounded(
4248
+ maxObjectKeys,
4249
+ BOUNDS.maxObjectKeys.min,
4250
+ BOUNDS.maxObjectKeys.max
4251
+ );
4252
+ }
4253
+ if (maxArrayElements !== void 0) {
4254
+ overrides.maxArrayElements = bounded(
4255
+ maxArrayElements,
4256
+ BOUNDS.maxArrayElements.min,
4257
+ BOUNDS.maxArrayElements.max
4258
+ );
4259
+ }
4260
+ if (maxStringLength !== void 0) {
4261
+ overrides.maxStringLength = bounded(
4262
+ maxStringLength,
4263
+ BOUNDS.maxStringLength.min,
4264
+ BOUNDS.maxStringLength.max
4265
+ );
4266
+ }
4267
+ if (maxSerializedValueBytes !== void 0) {
4268
+ overrides.maxSerializedValueBytes = bounded(
4269
+ maxSerializedValueBytes,
4270
+ BOUNDS.maxSerializedValueBytes.min,
4271
+ BOUNDS.maxSerializedValueBytes.max
4272
+ );
4273
+ }
4274
+ if (maxCapturedCallsPerFunction !== void 0) {
4275
+ overrides.maxCapturedCallsPerFunction = bounded(
4276
+ maxCapturedCallsPerFunction,
4277
+ BOUNDS.maxCapturedCallsPerFunction.min,
4278
+ BOUNDS.maxCapturedCallsPerFunction.max
4279
+ );
4280
+ }
4281
+ if (maxExecutionHoldMs !== void 0) {
4282
+ overrides.maxExecutionHoldMs = bounded(
4283
+ maxExecutionHoldMs,
4284
+ BOUNDS.maxExecutionHoldMs.min,
4285
+ BOUNDS.maxExecutionHoldMs.max
4286
+ );
4287
+ }
4288
+ const excludeSources = optionalStringList(value.excludeSources);
4289
+ const redactKeys = optionalStringList(value.redactKeys);
4290
+ if (excludeSources) overrides.excludeSources = excludeSources;
4291
+ if (redactKeys) overrides.redactKeys = redactKeys;
4292
+ if (typeof value.scrubPII === "boolean") overrides.scrubPII = value.scrubPII;
4293
+ return Object.keys(overrides).length > 0 ? overrides : void 0;
4294
+ };
4295
+ var clampSessionFreezeLimits = (overrides, processLimits) => ({
4296
+ maxDepth: clampToBounds(
4297
+ overrides?.maxDepth,
4298
+ processLimits.maxDepth,
4299
+ BOUNDS.maxDepth.min,
4300
+ BOUNDS.maxDepth.max
4301
+ ),
4302
+ maxObjectKeys: clampToBounds(
4303
+ overrides?.maxObjectKeys,
4304
+ processLimits.maxObjectKeys,
4305
+ BOUNDS.maxObjectKeys.min,
4306
+ BOUNDS.maxObjectKeys.max
4307
+ ),
4308
+ maxArrayElements: clampToBounds(
4309
+ overrides?.maxArrayElements,
4310
+ processLimits.maxArrayElements,
4311
+ BOUNDS.maxArrayElements.min,
4312
+ BOUNDS.maxArrayElements.max
4313
+ ),
4314
+ maxStringLength: clampToBounds(
4315
+ overrides?.maxStringLength,
4316
+ processLimits.maxStringLength,
4317
+ BOUNDS.maxStringLength.min,
4318
+ BOUNDS.maxStringLength.max
4319
+ ),
4320
+ maxSerializedValueBytes: clampToBounds(
4321
+ overrides?.maxSerializedValueBytes,
4322
+ processLimits.maxSerializedValueBytes,
4323
+ BOUNDS.maxSerializedValueBytes.min,
4324
+ BOUNDS.maxSerializedValueBytes.max
4325
+ )
4326
+ });
4327
+ var freezeLimitsFingerprint = (limits) => `${limits.maxDepth}:${limits.maxObjectKeys}:${limits.maxArrayElements}:${limits.maxStringLength}:${limits.maxSerializedValueBytes}`;
4328
+ var serializeSourceExclusions = (exclusions) => {
4329
+ if (!exclusions?.length) return void 0;
4330
+ const out = [];
4331
+ for (const item of exclusions) {
4332
+ if (typeof item === "string" && item.trim()) out.push(item.trim());
4333
+ else if (item instanceof RegExp) out.push(item.toString());
4334
+ }
4335
+ return out.length > 0 ? out : void 0;
4336
+ };
4337
+ var reportedRecorderSettings = (options, scrubPII) => ({
4338
+ maxDepth: options?.maxDepth,
4339
+ maxObjectKeys: options?.maxObjectKeys,
4340
+ maxArrayElements: options?.maxArrayElements,
4341
+ maxStringLength: options?.maxStringLength,
4342
+ maxSerializedValueBytes: options?.maxSerializedValueBytes,
4343
+ maxEventsPerExecution: options?.maxEventsPerExecution,
4344
+ maxCapturedCallsPerFunction: options?.maxCapturedCallsPerFunction,
4345
+ maxActiveMemoryBytes: options?.maxActiveMemoryBytes,
4346
+ maxExecutionHoldMs: options?.maxExecutionHoldMs,
4347
+ maxRetainedErrorRecordings: options?.maxRetainedErrorRecordings,
4348
+ fullCaptureDurationMs: options?.adaptive?.fullCaptureDurationMs,
4349
+ recorder_enabled: options?.enabled !== false,
4350
+ excludeSources: serializeSourceExclusions(options?.excludeSources),
4351
+ redactKeys: options?.redactKeys,
4352
+ scrubPII: scrubPII === true
4353
+ });
4354
+ var createSerializerCache = (options) => {
4355
+ const processLimits = compileFreezeLimits(options ?? {});
4356
+ const processFingerprint = freezeLimitsFingerprint(processLimits);
4357
+ const cache = /* @__PURE__ */ new Map();
4358
+ return {
4359
+ serializerFor: (overrides) => {
4360
+ const clamped = clampSessionFreezeLimits(overrides, processLimits);
4361
+ const fingerprint = freezeLimitsFingerprint(clamped);
4362
+ if (fingerprint === processFingerprint) return void 0;
4363
+ const existing = cache.get(fingerprint);
4364
+ if (existing) {
4365
+ cache.delete(fingerprint);
4366
+ cache.set(fingerprint, existing);
4367
+ return existing;
4368
+ }
4369
+ while (cache.size >= MAX_SERIALIZER_CACHE) {
4370
+ const oldest = cache.keys().next().value;
4371
+ if (oldest === void 0) break;
4372
+ cache.delete(oldest);
4373
+ }
4374
+ const created = createSafeSerializer(clamped);
4375
+ cache.set(fingerprint, created);
4376
+ return created;
4377
+ }
4378
+ };
4379
+ };
4380
+
4381
+ // src/execution-recorder/execution-recording-sync.ts
4382
+ var MAX_CACHE_ENTRIES = 1024;
4383
+ var MAX_PENDING_NOTIFIES = 32;
4384
+ var MAX_PENDING_TYPES = 64;
4385
+ var DEFAULT_POLL_INTERVAL_MS = 1e4;
4386
+ var REQUEST_TIMEOUT_MS = 5e3;
4387
+ var MAX_RETRIES = 5;
4388
+ var MAX_POLL_JITTER_MS = 2e3;
4389
+ var trimmed2 = (value) => typeof value === "string" ? value.trim() : "";
4390
+ var isRecord2 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
4391
+ var unwrapPayload = (body) => {
4392
+ if (!isRecord2(body)) return void 0;
4393
+ if ("payload" in body && isRecord2(body.payload)) return body.payload;
4394
+ return body;
4395
+ };
4396
+ var classifyHttpFailure = (status) => {
4397
+ if (status === 429) return "rate_limited";
4398
+ if (status >= 500) return "server_error";
4399
+ return "non_retryable_http";
4400
+ };
4401
+ var backoffMs = (attempt) => Math.min(3e3, 250 * 2 ** attempt);
4402
+ var createExecutionRecordingCoordinator = (options) => {
4403
+ const environment = trimmed2(options.environment);
4404
+ const nowMs = () => options.nowMs?.() ?? Date.now();
4405
+ const fetchFn = options.fetch ?? defaultIngestFetch();
4406
+ const networkEnabled = environment.length > 0;
4407
+ const instanceId = crypto.randomUUID();
4408
+ const startedAt = /* @__PURE__ */ new Date();
4409
+ const redactKeys = copyRedactKeys(options.recorderOptions?.redactKeys);
4410
+ const scrubPii = options.scrubPII === true;
4411
+ const serializers = createSerializerCache(options.recorderOptions);
4412
+ const cache = /* @__PURE__ */ new Map();
4413
+ const pending = /* @__PURE__ */ new Map();
4414
+ const catalog = /* @__PURE__ */ new Map();
4415
+ const sessionsById = /* @__PURE__ */ new Map();
4416
+ const completedSessionIds = /* @__PURE__ */ new Set();
4417
+ const recordings = [];
4418
+ const capabilities = ["catalog", "manual_sessions", "settings_overrides"];
4419
+ let closed = false;
4420
+ let closing = false;
4421
+ let sessionsDirty = true;
4422
+ let sessionSnapshot = /* @__PURE__ */ new Map();
4423
+ let syncFlight;
4424
+ let pollTimer;
4425
+ let pollStartTimer;
4426
+ let pump;
4427
+ let pumpAgain = false;
4428
+ let sendingKey;
4429
+ let recordingPump;
4430
+ let notifyFailures = 0;
4431
+ let refreshFailures = 0;
4432
+ let lastFailureKind = null;
4433
+ let pollAbort;
4434
+ let notifyAbort;
4435
+ let recordingAbort;
4436
+ let cancelWork = new AbortController();
4437
+ const rememberFailure = (kind) => {
4438
+ lastFailureKind = kind;
4439
+ };
4440
+ const dropExpiredCache = (atMs) => {
4441
+ for (const [key, expiresAt] of cache) {
4442
+ if (expiresAt <= atMs) cache.delete(key);
4443
+ }
4444
+ };
4445
+ const trimCache = () => {
4446
+ const atMs = nowMs();
4447
+ dropExpiredCache(atMs);
4448
+ while (cache.size > MAX_CACHE_ENTRIES) {
4449
+ const oldest = cache.keys().next().value;
4450
+ if (oldest === void 0) break;
4451
+ cache.delete(oldest);
4452
+ }
4453
+ };
4454
+ const peek = () => cache;
4455
+ const sessionView = (session) => ({
4456
+ sessionId: session.sessionId,
4457
+ expiresAtMs: session.expiresAtMs,
4458
+ serializer: session.serializer,
4459
+ redactKeys: session.redactKeys,
4460
+ excludeSources: session.excludeSources,
4461
+ maxCapturedCallsPerFunction: session.maxCapturedCallsPerFunction,
4462
+ maxExecutionHoldMs: session.maxExecutionHoldMs,
4463
+ scrubPII: session.scrubPII
4464
+ });
4465
+ const sessionHasRoom = (session, atMs) => session.admitted < session.requestedCount && session.expiresAtMs > atMs;
4466
+ const rebuildSessionSnapshot = () => {
4467
+ const atMs = nowMs();
4468
+ const map = /* @__PURE__ */ new Map();
4469
+ for (const session of sessionsById.values()) {
4470
+ if (!sessionHasRoom(session, atMs) || map.has(session.executionKey)) continue;
4471
+ map.set(session.executionKey, sessionView(session));
4472
+ }
4473
+ sessionSnapshot = map;
4474
+ sessionsDirty = false;
4475
+ };
4476
+ const markSessionsDirty = () => {
4477
+ sessionsDirty = true;
4478
+ };
4479
+ const notifySignal = () => {
4480
+ if (!notifyAbort || notifyAbort.signal.aborted) notifyAbort = new AbortController();
4481
+ return notifyAbort.signal;
4482
+ };
4483
+ const recordingSignal = () => {
4484
+ if (!recordingAbort || recordingAbort.signal.aborted) recordingAbort = new AbortController();
4485
+ return recordingAbort.signal;
4486
+ };
4487
+ const pollSignal = () => {
4488
+ if (!pollAbort || pollAbort.signal.aborted) pollAbort = new AbortController();
4489
+ return pollAbort.signal;
4490
+ };
4491
+ const wait = (ms, signal) => new Promise((resolve) => {
4492
+ if (signal.aborted) {
4493
+ resolve();
4494
+ return;
4495
+ }
4496
+ const timer = setTimeout(() => {
4497
+ signal.removeEventListener("abort", onAbort);
4498
+ resolve();
4499
+ }, ms);
4500
+ timer.unref?.();
4501
+ const onAbort = () => {
4502
+ clearTimeout(timer);
4503
+ resolve();
4504
+ };
4505
+ signal.addEventListener("abort", onAbort, { once: true });
4506
+ });
4507
+ const joinUntil = async (work, signal) => {
4508
+ if (!work || signal.aborted) return;
4509
+ let onAbort;
4510
+ const aborted = new Promise((resolve) => {
4511
+ onAbort = () => resolve();
4512
+ signal.addEventListener("abort", onAbort, { once: true });
4513
+ });
4514
+ try {
4515
+ await Promise.race([work, aborted]);
4516
+ } finally {
4517
+ if (onAbort) signal.removeEventListener("abort", onAbort);
4518
+ }
4519
+ };
4520
+ const workSignal = (signal) => AbortSignal.any([signal, cancelWork.signal]);
4521
+ const interruptWork = () => {
4522
+ cancelWork.abort();
4523
+ cancelWork = new AbortController();
4524
+ notifyAbort?.abort();
4525
+ recordingAbort?.abort();
4526
+ pollAbort?.abort();
4527
+ };
4528
+ const fetchEncoded = (url, encoded, requestSignal) => {
4529
+ const headers = {
4530
+ Authorization: `Bearer ${options.ingestToken}`,
4531
+ "Content-Type": "application/json",
4532
+ Accept: "application/json"
4533
+ };
4534
+ if (encoded.gzip) headers["Content-Encoding"] = "gzip";
4535
+ return fetchFn(url, {
4536
+ method: "POST",
4537
+ headers,
4538
+ body: encoded.body,
4539
+ signal: requestSignal
4540
+ });
4541
+ };
4542
+ const withRequestTimeout = async (signal, run) => {
4543
+ const combined = workSignal(signal);
4544
+ const timeout = new AbortController();
4545
+ const timer = setTimeout(() => timeout.abort(), REQUEST_TIMEOUT_MS);
4546
+ timer.unref?.();
4547
+ const onAbort = () => timeout.abort();
4548
+ combined.addEventListener("abort", onAbort, { once: true });
4549
+ if (combined.aborted) timeout.abort();
4550
+ const requestSignal = AbortSignal.any([combined, timeout.signal]);
4551
+ try {
4552
+ return await run(requestSignal);
4553
+ } finally {
4554
+ clearTimeout(timer);
4555
+ combined.removeEventListener("abort", onAbort);
4556
+ }
4557
+ };
4558
+ const postEncoded = async (url, encoded, signal, readBody) => withRequestTimeout(signal, async (requestSignal) => {
4559
+ const response = await fetchEncoded(url, encoded, requestSignal);
4560
+ const body = await readBody(response);
4561
+ return { response, body };
4562
+ });
4563
+ const postJson = async (url, body, signal, readBody) => postEncoded(url, { body: JSON.stringify(body), gzip: false }, signal, readBody);
4564
+ const sendNotify = async (item, signal) => {
4565
+ if (item.expiresAtMs <= nowMs()) return true;
4566
+ for (let attempt = 0; attempt <= MAX_RETRIES; attempt++) {
4567
+ if (signal.aborted) return false;
4568
+ if (item.expiresAtMs <= nowMs()) return true;
4569
+ try {
4570
+ const { response, body: payload } = await postJson(
4571
+ options.activateUrl,
4572
+ {
4573
+ environment,
4574
+ execution_key: item.executionKey,
4575
+ activated_at: new Date(item.activatedAtMs).toISOString(),
4576
+ expires_at: new Date(item.expiresAtMs).toISOString(),
4577
+ duration_ms: Math.max(1, item.expiresAtMs - item.activatedAtMs)
4578
+ },
4579
+ signal,
4580
+ async (activateResponse) => {
4581
+ if (!activateResponse.ok) return void 0;
4582
+ try {
4583
+ return unwrapPayload(await activateResponse.json());
4584
+ } catch {
4585
+ return void 0;
4586
+ }
4587
+ }
4588
+ );
4589
+ if (response.ok) {
4590
+ const expiresAt = Date.parse(String(payload?.expires_at ?? ""));
4591
+ if (Number.isFinite(expiresAt) && expiresAt > nowMs()) {
4592
+ cache.set(item.executionKey, expiresAt);
4593
+ }
4594
+ return true;
4595
+ }
4596
+ const kind = classifyHttpFailure(response.status);
4597
+ rememberFailure(kind);
4598
+ if (kind === "non_retryable_http") {
4599
+ notifyFailures++;
4600
+ return true;
4601
+ }
4602
+ if (attempt === MAX_RETRIES) {
4603
+ notifyFailures++;
4604
+ return false;
4605
+ }
4606
+ await wait(backoffMs(attempt), signal);
4607
+ } catch (error) {
4608
+ if (signal.aborted || error instanceof Error && error.name === "AbortError") {
4609
+ rememberFailure("aborted");
4610
+ return false;
4611
+ }
4612
+ rememberFailure("network_error");
4613
+ if (attempt === MAX_RETRIES) {
4614
+ notifyFailures++;
4615
+ return false;
4616
+ }
4617
+ await wait(backoffMs(attempt), signal);
4618
+ }
4619
+ }
4620
+ return false;
4621
+ };
4622
+ const runPump = async (signal) => {
4623
+ do {
4624
+ pumpAgain = false;
4625
+ const queued = new Set(pending.keys());
4626
+ for (const key of queued) {
4627
+ if (signal.aborted) return;
4628
+ const current = pending.get(key);
4629
+ if (!current) continue;
4630
+ sendingKey = key;
4631
+ const done = await sendNotify(current, signal);
4632
+ sendingKey = void 0;
4633
+ if (pending.get(key) !== current) pumpAgain = true;
4634
+ else if (done || !signal.aborted) pending.delete(key);
4635
+ }
4636
+ for (const key of pending.keys()) {
4637
+ if (!queued.has(key)) {
4638
+ pumpAgain = true;
4639
+ break;
4640
+ }
4641
+ }
4642
+ } while (pumpAgain && pending.size > 0 && !signal.aborted);
4643
+ };
4644
+ const drainNotifies = async (signal) => {
4645
+ while (pending.size > 0 && !signal.aborted) {
4646
+ if (pump) {
4647
+ pumpAgain = true;
4648
+ await joinUntil(pump, signal);
4649
+ continue;
4650
+ }
4651
+ const running = runPump(signal);
4652
+ pump = running;
4653
+ try {
4654
+ await running;
4655
+ } finally {
4656
+ if (pump === running) pump = void 0;
4657
+ }
4658
+ break;
4659
+ }
4660
+ };
4661
+ const kickNotify = () => {
4662
+ if (!networkEnabled || closed || closing || pending.size === 0 || options.mode !== "adaptive")
4663
+ return;
4664
+ void drainNotifies(notifySignal());
4665
+ };
4666
+ const rememberCatalog = (key, atMs) => {
4667
+ if (key.length === 0 || key.length > MAX_EXECUTION_TYPE_KEY_LENGTH) return;
4668
+ if (catalog.size >= MAX_CACHE_ENTRIES && !catalog.has(key)) {
4669
+ const oldest = catalog.keys().next().value;
4670
+ if (oldest !== void 0) catalog.delete(oldest);
4671
+ }
4672
+ catalog.set(key, atMs);
4673
+ };
4674
+ const applyCompletedSessionIds = (value) => {
4675
+ if (!Array.isArray(value)) return;
4676
+ for (const entry of value) {
4677
+ const sessionId = trimmed2(entry);
4678
+ if (!sessionId) continue;
4679
+ completedSessionIds.add(sessionId);
4680
+ sessionsById.delete(sessionId);
4681
+ }
4682
+ markSessionsDirty();
4683
+ };
4684
+ const applySessions = (entries) => {
4685
+ if (!Array.isArray(entries)) return;
4686
+ const atMs = nowMs();
4687
+ const next = /* @__PURE__ */ new Map();
4688
+ for (const entry of entries) {
4689
+ if (!isRecord2(entry)) continue;
4690
+ const sessionId = trimmed2(entry.id);
4691
+ const executionKeyValue = trimmed2(entry.execution_key);
4692
+ const status = trimmed2(entry.status);
4693
+ const expiresAtMs = Date.parse(String(entry.expires_at ?? ""));
4694
+ const requestedCount = typeof entry.requested_count === "number" && Number.isFinite(entry.requested_count) ? Math.round(entry.requested_count) : 0;
4695
+ if (!sessionId || !executionKeyValue || status !== "active") continue;
4696
+ if (completedSessionIds.has(sessionId)) continue;
4697
+ if (!Number.isFinite(expiresAtMs) || expiresAtMs <= atMs || requestedCount < 1) continue;
4698
+ const existing = sessionsById.get(sessionId);
4699
+ const overrides = parseSessionSettings(entry.overrides);
4700
+ next.set(sessionId, {
4701
+ sessionId,
4702
+ executionKey: executionKeyValue,
4703
+ expiresAtMs,
4704
+ requestedCount,
4705
+ admitted: existing?.admitted ?? 0,
4706
+ serializer: serializers.serializerFor(overrides),
4707
+ redactKeys: overrides?.redactKeys,
4708
+ excludeSources: overrides?.excludeSources,
4709
+ maxCapturedCallsPerFunction: overrides?.maxCapturedCallsPerFunction,
4710
+ maxExecutionHoldMs: overrides?.maxExecutionHoldMs,
4711
+ scrubPII: overrides?.scrubPII
4712
+ });
4713
+ }
4714
+ sessionsById.clear();
4715
+ for (const [id, session] of next) sessionsById.set(id, session);
4716
+ markSessionsDirty();
4717
+ };
4718
+ const applyActivations = (activations) => {
4719
+ if (!Array.isArray(activations)) return;
4720
+ const atMs = nowMs();
4721
+ const seen = /* @__PURE__ */ new Set();
4722
+ for (const entry of activations) {
4723
+ if (!isRecord2(entry)) continue;
4724
+ const key = trimmed2(entry.execution_key);
4725
+ const expiresAt = Date.parse(String(entry.expires_at ?? ""));
4726
+ if (!key || !Number.isFinite(expiresAt) || expiresAt <= atMs) continue;
4727
+ cache.set(key, expiresAt);
4728
+ seen.add(key);
4729
+ }
4730
+ trimCache();
4731
+ for (const key of seen) pending.delete(key);
4732
+ };
4733
+ const catalogTypes = () => {
4734
+ const entries = [];
4735
+ for (const [executionKey, lastSeenAtMs] of catalog) {
4736
+ entries.push({ executionKey, lastSeenAtMs });
4737
+ if (entries.length >= MAX_PENDING_TYPES) break;
4738
+ }
4739
+ return entries;
4740
+ };
4741
+ const syncOnce = async (signal) => {
4742
+ if (!networkEnabled || closed) return;
4743
+ const types2 = catalogTypes();
4744
+ try {
4745
+ const { response, body: payload } = await postJson(
4746
+ options.syncUrl,
4747
+ {
4748
+ environment,
4749
+ instance: {
4750
+ id: instanceId,
4751
+ sdk_name: options.sdkName,
4752
+ sdk_version: options.sdkVersion,
4753
+ release: options.release,
4754
+ pid: process.pid,
4755
+ started_at: startedAt.toISOString(),
4756
+ reported_mode: options.mode,
4757
+ reported_settings: reportedRecorderSettings(options.recorderOptions, options.scrubPII),
4758
+ capabilities
4759
+ },
4760
+ types: types2.map((entry) => ({
4761
+ execution_key: entry.executionKey,
4762
+ last_seen_at: new Date(entry.lastSeenAtMs).toISOString()
4763
+ }))
4764
+ },
4765
+ signal,
4766
+ async (syncResponse) => {
4767
+ if (!syncResponse.ok) return void 0;
4768
+ return unwrapPayload(await syncResponse.json());
4769
+ }
4770
+ );
4771
+ if (!response.ok) {
4772
+ rememberFailure(classifyHttpFailure(response.status));
4773
+ refreshFailures++;
4774
+ return;
4775
+ }
4776
+ applyActivations(payload?.activations);
4777
+ applySessions(payload?.sessions);
4778
+ for (const entry of types2) {
4779
+ const current = catalog.get(entry.executionKey);
4780
+ if (current === void 0) continue;
4781
+ catalog.delete(entry.executionKey);
4782
+ if (current !== entry.lastSeenAtMs) {
4783
+ catalog.set(entry.executionKey, current);
4784
+ }
4785
+ }
4786
+ } catch (error) {
4787
+ if (signal.aborted || error instanceof Error && error.name === "AbortError") {
4788
+ rememberFailure("aborted");
4789
+ } else {
4790
+ rememberFailure("network_error");
4791
+ }
4792
+ refreshFailures++;
4793
+ }
4794
+ };
4795
+ const runSyncOnce = async (signal) => {
4796
+ if (syncFlight) {
4797
+ await joinUntil(syncFlight, signal);
4798
+ return;
4799
+ }
4800
+ const running = syncOnce(signal);
4801
+ const flight = running.finally(() => {
4802
+ if (syncFlight === flight) syncFlight = void 0;
4803
+ });
4804
+ syncFlight = flight;
4805
+ await joinUntil(flight, signal);
4806
+ };
4807
+ const sendRecordings = async (batch, signal) => {
4808
+ const combined = workSignal(signal);
4809
+ if (combined.aborted) return false;
4810
+ let encoded;
4811
+ try {
4812
+ encoded = await encodeJsonRequestBodyAsync(
4813
+ {
4814
+ instance_id: instanceId,
4815
+ recordings: batch.map((item) => ({
4816
+ session_id: item.sessionId,
4817
+ execution_id: item.executionId,
4818
+ outcome: item.outcome,
4819
+ runtime_state: item.runtimeState,
4820
+ release: options.release,
4821
+ redact_keys: copyRedactKeys([...redactKeys ?? [], ...item.redactKeys ?? []])?.slice(
4822
+ 0,
4823
+ MAX_REDACT_KEYS
4824
+ ),
4825
+ scrub_pii: item.scrubPii ?? scrubPii
4826
+ }))
4827
+ },
4828
+ void 0,
4829
+ combined
4830
+ );
4831
+ } catch (error) {
4832
+ if (combined.aborted || error instanceof Error && error.name === "AbortError") {
4833
+ rememberFailure("aborted");
4834
+ return false;
4835
+ }
4836
+ rememberFailure("network_error");
4837
+ return false;
4838
+ }
4839
+ for (let attempt = 0; attempt <= MAX_RETRIES; attempt++) {
4840
+ if (combined.aborted) return false;
4841
+ try {
4842
+ const { response, body } = await postEncoded(
4843
+ options.recordingsUrl,
4844
+ encoded,
4845
+ combined,
4846
+ async (uploadResponse) => {
4847
+ if (!uploadResponse.ok) return void 0;
4848
+ try {
4849
+ return unwrapPayload(await uploadResponse.json());
4850
+ } catch {
4851
+ return void 0;
4852
+ }
4853
+ }
4854
+ );
4855
+ if (response.ok) {
4856
+ applyCompletedSessionIds(body?.completed_session_ids);
4857
+ return true;
4858
+ }
4859
+ const kind = classifyHttpFailure(response.status);
4860
+ rememberFailure(kind);
4861
+ if (kind === "non_retryable_http") return true;
4862
+ if (attempt === MAX_RETRIES) return false;
4863
+ await wait(backoffMs(attempt), combined);
4864
+ } catch (error) {
4865
+ if (combined.aborted || error instanceof Error && error.name === "AbortError") {
4866
+ rememberFailure("aborted");
4867
+ return false;
4868
+ }
4869
+ rememberFailure("network_error");
4870
+ if (attempt === MAX_RETRIES) return false;
4871
+ await wait(backoffMs(attempt), combined);
4872
+ }
4873
+ }
4874
+ return false;
4875
+ };
4876
+ const drainRecordings = async (signal) => {
4877
+ while (recordings.length > 0 && !signal.aborted) {
4878
+ const batch = recordings.splice(0, 8);
4879
+ const ok = await sendRecordings(batch, signal);
4880
+ if (!ok) {
4881
+ recordings.unshift(...batch);
4882
+ break;
4883
+ }
4884
+ }
4885
+ };
4886
+ const kickRecordings = () => {
4887
+ if (!networkEnabled || closed || closing || recordings.length === 0) return;
4888
+ if (recordingPump) return;
4889
+ const running = drainRecordings(recordingSignal());
4890
+ recordingPump = running;
4891
+ void running.finally(() => {
4892
+ if (recordingPump === running) recordingPump = void 0;
4893
+ if (recordings.length > 0) kickRecordings();
4894
+ });
4895
+ };
4896
+ const activate = (metadata, window) => {
4897
+ if (closed || options.mode !== "adaptive") return;
4898
+ const key = executionTypeKey(metadata);
4899
+ if (!key) return;
4900
+ const atMs = nowMs();
4901
+ const existing = cache.get(key);
4902
+ if (existing !== void 0 && existing > atMs) return;
4903
+ cache.set(key, window.expiresAtMs);
4904
+ trimCache();
4905
+ if (!networkEnabled || window.expiresAtMs <= atMs) return;
4906
+ if (pending.size >= MAX_PENDING_NOTIFIES && !pending.has(key)) {
4907
+ for (const oldest of pending.keys()) {
4908
+ if (oldest !== sendingKey) {
4909
+ pending.delete(oldest);
4910
+ break;
4911
+ }
4912
+ }
4913
+ }
4914
+ pending.set(key, { executionKey: key, ...window });
4915
+ kickNotify();
4916
+ };
4917
+ const peekSessions = () => {
4918
+ if (sessionsDirty) rebuildSessionSnapshot();
4919
+ else {
4920
+ const atMs = nowMs();
4921
+ for (const session of sessionSnapshot.values()) {
4922
+ if (session.expiresAtMs <= atMs) {
4923
+ rebuildSessionSnapshot();
4924
+ break;
4925
+ }
4926
+ }
4927
+ }
4928
+ return sessionSnapshot;
4929
+ };
4930
+ const consumeSession = (executionKeyValue, sessionId) => {
4931
+ const atMs = nowMs();
4932
+ for (const session of sessionsById.values()) {
4933
+ if (session.executionKey !== executionKeyValue) continue;
4934
+ if (sessionId !== void 0 && session.sessionId !== sessionId) continue;
4935
+ if (!sessionHasRoom(session, atMs)) continue;
4936
+ session.admitted += 1;
4937
+ markSessionsDirty();
4938
+ return sessionView(session);
4939
+ }
4940
+ return void 0;
4941
+ };
4942
+ const observeType = (executionKeyValue) => {
4943
+ rememberCatalog(executionKeyValue, nowMs());
4944
+ };
4945
+ const enqueueRecording = (payload) => {
4946
+ if (closed || closing) return;
4947
+ recordings.push(payload);
4948
+ kickRecordings();
4949
+ };
4950
+ if (networkEnabled) {
4951
+ const interval = options.pollIntervalMs ?? DEFAULT_POLL_INTERVAL_MS;
4952
+ const jitterMax = Math.max(0, options.pollJitterMs ?? MAX_POLL_JITTER_MS);
4953
+ const delay = interval + Math.floor(Math.random() * jitterMax);
4954
+ pollStartTimer = setTimeout(() => {
4955
+ pollStartTimer = void 0;
4956
+ if (closed || closing) return;
4957
+ void runSyncOnce(pollSignal());
4958
+ pollTimer = setInterval(() => {
4959
+ if (closed || closing) return;
4960
+ void runSyncOnce(pollSignal());
4961
+ }, interval);
4962
+ pollTimer.unref?.();
4963
+ }, delay);
4964
+ pollStartTimer.unref?.();
4965
+ }
4966
+ const stopTimers = () => {
4967
+ if (pollStartTimer) {
4968
+ clearTimeout(pollStartTimer);
4969
+ pollStartTimer = void 0;
4970
+ }
4971
+ if (pollTimer) {
4972
+ clearInterval(pollTimer);
4973
+ pollTimer = void 0;
4974
+ }
4975
+ };
4976
+ return {
4977
+ peek,
4978
+ activate,
4979
+ peekSessions,
4980
+ consumeSession,
4981
+ observeType,
4982
+ enqueueRecording,
4983
+ getStats: () => ({
4984
+ adaptiveNotifyFailures: notifyFailures,
4985
+ adaptiveRefreshFailures: refreshFailures,
4986
+ lastAdaptiveFailureKind: lastFailureKind
4987
+ }),
4988
+ flush: async (timeoutMs = 2e3) => {
4989
+ if (!networkEnabled || closed || closing) return;
4990
+ const flushAbort = new AbortController();
4991
+ const onAbort = () => interruptWork();
4992
+ flushAbort.signal.addEventListener("abort", onAbort, { once: true });
4993
+ const timer = setTimeout(() => flushAbort.abort(), Math.max(0, timeoutMs));
4994
+ try {
4995
+ await runSyncOnce(flushAbort.signal);
4996
+ if (!flushAbort.signal.aborted) await drainNotifies(flushAbort.signal);
4997
+ await joinUntil(recordingPump, flushAbort.signal);
4998
+ if (!flushAbort.signal.aborted) await drainRecordings(flushAbort.signal);
4999
+ } finally {
5000
+ clearTimeout(timer);
5001
+ flushAbort.signal.removeEventListener("abort", onAbort);
5002
+ }
5003
+ },
5004
+ close: async () => {
5005
+ if (closed || closing) return;
5006
+ closing = true;
5007
+ stopTimers();
5008
+ const deadline = new AbortController();
5009
+ const timer = setTimeout(() => {
5010
+ deadline.abort();
5011
+ interruptWork();
5012
+ }, 2e3);
5013
+ try {
5014
+ if (networkEnabled) await runSyncOnce(deadline.signal);
5015
+ if (!deadline.signal.aborted) await drainNotifies(deadline.signal);
5016
+ await joinUntil(recordingPump, deadline.signal);
5017
+ if (!deadline.signal.aborted) await drainRecordings(deadline.signal);
5018
+ } finally {
5019
+ clearTimeout(timer);
5020
+ closed = true;
5021
+ interruptWork();
5022
+ pending.clear();
5023
+ }
5024
+ }
5025
+ };
5026
+ };
5027
+
5028
+ // src/execution-recorder/bind-adaptive-recorder.ts
5029
+ var bindAdaptiveRecorder = (input) => {
5030
+ const options = input.executionRecorder;
5031
+ const mode = sanitizeRecorderMode(options?.mode);
5032
+ const activation = resolveClientActivation({
5033
+ enabled: input.enabled,
5034
+ dsn: input.dsn,
5035
+ projectApiKey: input.projectApiKey,
5036
+ apiUrl: input.apiUrl,
5037
+ release: input.release
5038
+ });
5039
+ const coordinator = input.recorderEnabled && activation.enabled ? createExecutionRecordingCoordinator({
5040
+ environment: input.environment ?? "",
5041
+ ingestToken: activation.ingestToken,
5042
+ activateUrl: resolveEndpointUrls2(activation.apiUrl).executionRecordingActivateUrl,
5043
+ syncUrl: resolveEndpointUrls2(activation.apiUrl).executionRecordingSyncUrl,
5044
+ recordingsUrl: resolveEndpointUrls2(activation.apiUrl).executionRecordingRecordingsUrl,
5045
+ sdkName: input.sdkName,
5046
+ sdkVersion: input.sdkVersion,
5047
+ release: activation.release,
5048
+ recorderOptions: options,
5049
+ scrubPII: input.scrubPII,
5050
+ mode,
5051
+ fetch: input.fetch
5052
+ }) : void 0;
5053
+ const runtime = createExecutionRecorder(
5054
+ { ...options, enabled: input.recorderEnabled },
5055
+ coordinator ? {
5056
+ policySnapshot: coordinator.peek,
5057
+ onQualifyingFailure: mode === "adaptive" ? coordinator.activate : void 0,
5058
+ getStats: coordinator.getStats,
5059
+ sessionCaptureSnapshot: coordinator.peekSessions,
5060
+ consumeSession: coordinator.consumeSession,
5061
+ observeExecutionType: coordinator.observeType,
5062
+ onSessionRecording: coordinator.enqueueRecording
5063
+ } : void 0
5064
+ );
5065
+ return { runtime, policy: coordinator };
5066
+ };
5067
+
3971
5068
  // src/install-global-handlers.ts
3972
5069
  var RASPUTIN_PROCESS_LISTENER = Symbol.for("rasputin.process.listener.v1");
3973
5070
  var unhandledRejectionMode = () => {
@@ -4104,6 +5201,7 @@ var installGlobalHandlers = (client, options = {}) => {
4104
5201
  };
4105
5202
  };
4106
5203
  export {
5204
+ bindAdaptiveRecorder,
4107
5205
  createExecutionRecorder,
4108
5206
  inertErrorObservation,
4109
5207
  installAutomaticExecutionRuntime,