@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/index.js CHANGED
@@ -1,7 +1,7 @@
1
1
  // src/rasputin-init.ts
2
2
  import { join } from "node:path";
3
3
  import {
4
- copyRedactKeys,
4
+ copyRedactKeys as copyRedactKeys2,
5
5
  createClient,
6
6
  isClientEnabled
7
7
  } from "@rasputin-ai/core";
@@ -670,6 +670,23 @@ import {
670
670
  runtimeFunctionId as runtimeFunctionId2
671
671
  } from "@rasputin-ai/core";
672
672
 
673
+ // src/execution-recorder/adaptive-recording-options.ts
674
+ var DEFAULT_FULL_CAPTURE_DURATION_MS = 24 * 60 * 60 * 1e3;
675
+ var MIN_FULL_CAPTURE_DURATION_MS = 1e3;
676
+ var MAX_FULL_CAPTURE_DURATION_MS = 7 * 24 * 60 * 60 * 1e3;
677
+ var sanitizeRecorderMode = (mode) => {
678
+ return mode === "adaptive" ? "adaptive" : "full";
679
+ };
680
+ var sanitizeFullCaptureDurationMs = (value) => {
681
+ if (typeof value !== "number" || !Number.isFinite(value)) {
682
+ return DEFAULT_FULL_CAPTURE_DURATION_MS;
683
+ }
684
+ return Math.min(
685
+ MAX_FULL_CAPTURE_DURATION_MS,
686
+ Math.max(MIN_FULL_CAPTURE_DURATION_MS, Math.floor(value))
687
+ );
688
+ };
689
+
673
690
  // src/execution-recorder/error-observation.ts
674
691
  var bindings = /* @__PURE__ */ new WeakMap();
675
692
  var mintErrorObservation = (binding) => {
@@ -685,11 +702,36 @@ var inertErrorObservation = () => {
685
702
  return Object.freeze(/* @__PURE__ */ Object.create(null));
686
703
  };
687
704
 
705
+ // src/execution-recorder/execution-identity.ts
706
+ var MAX_EXECUTION_TYPE_KEY_LENGTH = 256;
707
+ var NAMED_KINDS = /* @__PURE__ */ new Set(["job", "scheduled", "custom", "serverless"]);
708
+ var trimmed = (value) => typeof value === "string" ? value.trim() : "";
709
+ var boundedKey = (key) => {
710
+ return key.length > 0 && key.length <= MAX_EXECUTION_TYPE_KEY_LENGTH ? key : void 0;
711
+ };
712
+ var executionTypeKey = (metadata) => {
713
+ if (metadata.kind === "http") {
714
+ const method = trimmed(metadata.request?.method).toUpperCase();
715
+ const route = trimmed(metadata.request?.route);
716
+ if (!method || !route) return void 0;
717
+ if (route.includes("?") || route.includes("://")) return void 0;
718
+ return boundedKey(`http:${method}:${route}`);
719
+ }
720
+ if (!NAMED_KINDS.has(metadata.kind)) return void 0;
721
+ const name = trimmed(metadata.name);
722
+ if (!name) return void 0;
723
+ return boundedKey(`${metadata.kind}:${name}`);
724
+ };
725
+ var isHttpClientErrorStatus = (status) => {
726
+ return typeof status === "number" && Number.isFinite(status) && status >= 400 && status < 500;
727
+ };
728
+
688
729
  // src/execution-recorder/execution-journal.ts
689
730
  var KIND_ENTER = 1;
690
731
  var KIND_EXIT = 2;
691
732
  var KIND_THROW = 3;
692
733
  var KIND_SUPPRESSED = 4;
734
+ var ARGS_OMITTED = Symbol("rasputin.argsOmitted");
693
735
  var NO_PARENT = 4294967295;
694
736
  var NO_SUPPRESSION = 4294967295;
695
737
  var MAX_POOLED_JOURNALS = 8;
@@ -887,17 +929,18 @@ var ExecutionJournal = class {
887
929
  callId: this.callId[index] ?? 0,
888
930
  functionId,
889
931
  timestampMs: relativeMs(this.timestampNs[index] ?? 0n),
890
- args: Array.isArray(payload) ? payload : [],
932
+ ...payload === ARGS_OMITTED ? { argsOmitted: true } : { args: Array.isArray(payload) ? payload : [] },
891
933
  ...parentCallId === NO_PARENT ? {} : { parentCallId }
892
934
  };
893
935
  }
894
936
  if (kind === KIND_EXIT) {
937
+ const payload = this.payloads[index];
895
938
  return {
896
939
  type: "function_exit",
897
940
  callId: this.callId[index] ?? 0,
898
941
  timestampMs: relativeMs(this.timestampNs[index] ?? 0n),
899
942
  durationMs: relativeMs(this.durationNs[index] ?? 0n),
900
- returnValue: this.payloads[index]
943
+ ...payload === ARGS_OMITTED ? {} : { returnValue: payload }
901
944
  };
902
945
  }
903
946
  if (kind === KIND_THROW) {
@@ -1256,7 +1299,7 @@ var settleFinalBytes = (state) => {
1256
1299
  var dropEventValues = (events) => {
1257
1300
  let dropped = 0;
1258
1301
  const marker = () => rasputinUnavailable(VALUE_OMITTED_REASON);
1259
- const bounded = events.map((event) => {
1302
+ const bounded2 = events.map((event) => {
1260
1303
  if (event.type === "function_enter") {
1261
1304
  if (event.args === void 0) return { ...event };
1262
1305
  dropped += event.args.length;
@@ -1272,7 +1315,7 @@ var dropEventValues = (events) => {
1272
1315
  }
1273
1316
  return { ...event };
1274
1317
  });
1275
- return { events: bounded, dropped };
1318
+ return { events: bounded2, dropped };
1276
1319
  };
1277
1320
  var truncateUtf8 = (value, maximumBytes) => {
1278
1321
  if (value === void 0 || Buffer.byteLength(value, "utf8") <= maximumBytes) return value;
@@ -2378,8 +2421,8 @@ var encodeFrozenWithBytes = (frozen, visitedNodes, maxSerializedValueBytes) => {
2378
2421
  const encoded = encodeFrozen(frozen);
2379
2422
  const bytes = jsonLiteralUtf8Bytes(encoded);
2380
2423
  if (!isByteBudgetStub(encoded) && bytes > maxSerializedValueBytes) {
2381
- const bounded = truncation("max_serialized_value_bytes", { __serialized_bytes: bytes });
2382
- return { value: bounded, bytes: jsonLiteralUtf8Bytes(bounded), visitedNodes };
2424
+ const bounded2 = truncation("max_serialized_value_bytes", { __serialized_bytes: bytes });
2425
+ return { value: bounded2, bytes: jsonLiteralUtf8Bytes(bounded2), visitedNodes };
2383
2426
  }
2384
2427
  return { value: encoded, bytes, visitedNodes };
2385
2428
  };
@@ -2583,7 +2626,13 @@ var emptyStats = {
2583
2626
  journalPoolMisses: 0,
2584
2627
  journalPoolSize: 0,
2585
2628
  journalAllocatedCapacity: 0,
2586
- attributionDegradations: 0
2629
+ attributionDegradations: 0,
2630
+ adaptiveLightExecutions: 0,
2631
+ adaptiveFullExecutions: 0,
2632
+ adaptiveActivations: 0,
2633
+ adaptiveNotifyFailures: 0,
2634
+ adaptiveRefreshFailures: 0,
2635
+ lastAdaptiveFailureKind: null
2587
2636
  };
2588
2637
  var noOpExecution = {
2589
2638
  createScope: () => ({
@@ -2591,6 +2640,8 @@ var noOpExecution = {
2591
2640
  getErrorState: () => void 0,
2592
2641
  observeError: () => inertErrorObservation(),
2593
2642
  finish: () => {
2643
+ },
2644
+ mergeMetadata: () => {
2594
2645
  }
2595
2646
  }),
2596
2647
  getErrorState: () => void 0,
@@ -2632,9 +2683,28 @@ var newSuppression = (group, parentCallId, startedAtNs, endedAtNs) => ({
2632
2683
  storageIndex: -1,
2633
2684
  retainedIndex: -1
2634
2685
  });
2635
- var createExecutionRecorder = (options) => {
2686
+ var EMPTY_POLICY_SNAPSHOT = /* @__PURE__ */ new Map();
2687
+ var EMPTY_SESSION_SNAPSHOT = /* @__PURE__ */ new Map();
2688
+ var createExecutionRecorder = (options, hooks = {}) => {
2636
2689
  if (!options?.enabled) return noOpExecution;
2637
2690
  warnIfMissingAsyncContextFrame();
2691
+ const recorderMode = sanitizeRecorderMode(options.mode);
2692
+ const fullCaptureDurationMs = sanitizeFullCaptureDurationMs(
2693
+ options.adaptive?.fullCaptureDurationMs
2694
+ );
2695
+ const localActivations = /* @__PURE__ */ new Map();
2696
+ const nowMs = () => hooks.nowMs?.() ?? Date.now();
2697
+ const policySnapshotFor = () => hooks.policySnapshot?.() ?? localActivations;
2698
+ const keyIsActive = (snapshot, key, atMs) => {
2699
+ const expiresAt = snapshot.get(key);
2700
+ return expiresAt !== void 0 && expiresAt > atMs;
2701
+ };
2702
+ const captureValuesFor = (metadata, snapshot, atMs) => {
2703
+ if (recorderMode !== "adaptive") return true;
2704
+ const key = executionTypeKey(metadata);
2705
+ if (!key) return false;
2706
+ return keyIsActive(snapshot, key, atMs);
2707
+ };
2638
2708
  const storage = new AsyncLocalStorage();
2639
2709
  const currentStore = () => {
2640
2710
  try {
@@ -2723,7 +2793,10 @@ var createExecutionRecorder = (options) => {
2723
2793
  measuredExecutions: 0,
2724
2794
  totalInlineWallTimeMs: 0,
2725
2795
  maxInlineWallTimeMs: 0,
2726
- attributionDegradations: 0
2796
+ attributionDegradations: 0,
2797
+ adaptiveLightExecutions: 0,
2798
+ adaptiveFullExecutions: 0,
2799
+ adaptiveActivations: 0
2727
2800
  };
2728
2801
  const addPhase = (key, nanoseconds) => {
2729
2802
  if (phases && nanoseconds > 0n) phases[key] += nanoseconds;
@@ -2734,8 +2807,8 @@ var createExecutionRecorder = (options) => {
2734
2807
  stats.totalInlineWallTimeMs = Math.round((stats.totalInlineWallTimeMs + inlineWallTimeMs) * 1e4) / 1e4;
2735
2808
  stats.maxInlineWallTimeMs = Math.max(stats.maxInlineWallTimeMs, inlineWallTimeMs);
2736
2809
  };
2737
- const freezeAndCount = (value) => {
2738
- const frozen = serializer.freeze(value);
2810
+ const freezeAndCount = (recording, value) => {
2811
+ const frozen = (recording.serializer ?? serializer).freeze(value);
2739
2812
  stats.serializedValues++;
2740
2813
  stats.serializedValueNodes += frozen.visitedNodes;
2741
2814
  stats.serializedValueBytes += frozen.estimatedBytes;
@@ -2743,26 +2816,118 @@ var createExecutionRecorder = (options) => {
2743
2816
  };
2744
2817
  const captureValue = (recording, value) => {
2745
2818
  try {
2746
- return memoryBudget.captureValue(recording.memory, value, freezeAndCount);
2819
+ return memoryBudget.captureValue(
2820
+ recording.memory,
2821
+ value,
2822
+ (item) => freezeAndCount(recording, item)
2823
+ );
2747
2824
  } catch {
2748
2825
  return { __rasputin_type: "unserializable" };
2749
2826
  }
2750
2827
  };
2751
- const encodeEventValues = (events) => events.map((event) => {
2828
+ const encodeEventValues = (recording, events) => events.map((event) => {
2829
+ const encode = (recording.serializer ?? serializer).encode;
2752
2830
  if (event.type === "function_enter") {
2753
2831
  return {
2754
2832
  ...event,
2755
- ...event.args === void 0 ? {} : { args: event.args.map((argument) => serializer.encode(argument)) }
2833
+ ...event.args === void 0 ? {} : { args: event.args.map((argument) => encode(argument)) }
2756
2834
  };
2757
2835
  }
2758
2836
  if (event.type === "function_exit") {
2759
- return { ...event, returnValue: serializer.encode(event.returnValue) };
2837
+ return event.returnValue === void 0 ? event : { ...event, returnValue: encode(event.returnValue) };
2760
2838
  }
2761
2839
  if (event.type === "function_throw") {
2762
- return { ...event, error: serializer.encode(event.error) };
2840
+ return { ...event, error: encode(event.error) };
2763
2841
  }
2764
2842
  return event;
2765
2843
  });
2844
+ const enterPayload = (recording, omitCallValues, args) => {
2845
+ if (!recording.captureValues) return ARGS_OMITTED;
2846
+ if (omitCallValues) return mapArrayLike(args, () => rasputinOmitted());
2847
+ return mapArrayLike(args, (argument) => captureValue(recording, argument));
2848
+ };
2849
+ const exitPayload = (recording, omitCallValues, value) => {
2850
+ if (!recording.captureValues) return ARGS_OMITTED;
2851
+ if (omitCallValues) return rasputinOmitted();
2852
+ return captureValue(recording, value);
2853
+ };
2854
+ const admitSession = (recording, session) => {
2855
+ const wasLight = recorderMode === "adaptive" && !recording.captureValues;
2856
+ recording.retainSuccess = true;
2857
+ recording.sessionId = session.sessionId;
2858
+ recording.captureValues = true;
2859
+ if (session.serializer) recording.serializer = session.serializer;
2860
+ if (session.redactKeys?.length) recording.sessionRedactKeys = session.redactKeys;
2861
+ if (session.scrubPII !== void 0) recording.sessionScrubPii = session.scrubPII;
2862
+ if (session.excludeSources?.length) {
2863
+ recording.sessionExcludes = createSourceExclusionMatcher(session.excludeSources);
2864
+ }
2865
+ if (session.maxCapturedCallsPerFunction !== void 0) {
2866
+ recording.sessionMaxCapturedCalls = Math.max(
2867
+ 1,
2868
+ Math.round(session.maxCapturedCallsPerFunction)
2869
+ );
2870
+ }
2871
+ if (session.maxExecutionHoldMs !== void 0) {
2872
+ recording.sessionHoldNs = BigInt(Math.max(1, Math.round(session.maxExecutionHoldMs))) * 1000000n;
2873
+ }
2874
+ if (wasLight) {
2875
+ stats.adaptiveLightExecutions = Math.max(0, stats.adaptiveLightExecutions - 1);
2876
+ stats.adaptiveFullExecutions++;
2877
+ }
2878
+ };
2879
+ const skipCapture = (store, plan) => store.suppressCapture || plan.excluded || Boolean(store.recording.sessionExcludes?.(plan.definition));
2880
+ const capturedCallLimitFor = (recording) => recording.sessionMaxCapturedCalls ?? maxCapturedCallsPerFunction;
2881
+ const tryAdmitLiveSession = (recording) => {
2882
+ if (recording.retainSuccess || recording.finished) return;
2883
+ const key = executionTypeKey(recording.execution);
2884
+ if (!key) return;
2885
+ const peek = hooks.sessionCaptureSnapshot?.().get(key);
2886
+ if (!peek || peek.expiresAtMs <= recording.startedAtMs) return;
2887
+ const live = hooks.consumeSession?.(key, peek.sessionId);
2888
+ if (live) admitSession(recording, live);
2889
+ };
2890
+ const tryAdmitFromStartSnapshot = (recording) => {
2891
+ if (recording.retainSuccess || recording.finished) return;
2892
+ const key = executionTypeKey(recording.execution);
2893
+ if (!key) return;
2894
+ const peek = recording.sessionCaptureSnapshot.get(key);
2895
+ if (!peek || peek.expiresAtMs <= recording.startedAtMs) return;
2896
+ const live = hooks.consumeSession?.(key, peek.sessionId);
2897
+ if (live) admitSession(recording, live);
2898
+ };
2899
+ const completeIdentityFromSnapshot = (recording) => {
2900
+ if (recording.identityResolved || recording.finished) return;
2901
+ const key = executionTypeKey(recording.execution);
2902
+ if (!key) return;
2903
+ recording.identityResolved = true;
2904
+ tryAdmitFromStartSnapshot(recording);
2905
+ if (recording.captureValues || recorderMode !== "adaptive") return;
2906
+ if (keyIsActive(recording.policySnapshot, key, recording.startedAtMs)) {
2907
+ recording.captureValues = true;
2908
+ stats.adaptiveLightExecutions = Math.max(0, stats.adaptiveLightExecutions - 1);
2909
+ stats.adaptiveFullExecutions++;
2910
+ }
2911
+ };
2912
+ const maybeActivateAdaptive = (recording) => {
2913
+ if (recorderMode !== "adaptive" || recording.adaptiveActivated) return;
2914
+ if (isHttpClientErrorStatus(recording.execution.request?.status)) return;
2915
+ const key = executionTypeKey(recording.execution);
2916
+ if (!key) return;
2917
+ const atMs = nowMs();
2918
+ const snapshot = policySnapshotFor();
2919
+ if (keyIsActive(snapshot, key, atMs)) return;
2920
+ recording.adaptiveActivated = true;
2921
+ const window = { activatedAtMs: atMs, expiresAtMs: atMs + fullCaptureDurationMs };
2922
+ stats.adaptiveActivations++;
2923
+ if (hooks.onQualifyingFailure) {
2924
+ hooks.onQualifyingFailure(recording.execution, window);
2925
+ return;
2926
+ }
2927
+ if (!keyIsActive(localActivations, key, atMs)) {
2928
+ localActivations.set(key, window.expiresAtMs);
2929
+ }
2930
+ };
2766
2931
  const storePlan = (plan) => {
2767
2932
  plansByRuntimeId[plan.runtimePlanId] = plan;
2768
2933
  return plan;
@@ -2800,8 +2965,10 @@ var createExecutionRecorder = (options) => {
2800
2965
  };
2801
2966
  const eventsHaveOmittedValues = (events) => {
2802
2967
  for (const event of events) {
2803
- if (event.type === "function_enter" && (event.args ?? []).some((arg) => rasputinTagKind(arg) === "omitted")) {
2804
- return true;
2968
+ if (event.type === "function_enter") {
2969
+ if (event.argsOmitted || (event.args ?? []).some((arg) => rasputinTagKind(arg) === "omitted")) {
2970
+ return true;
2971
+ }
2805
2972
  }
2806
2973
  if (event.type === "function_exit" && rasputinTagKind(event.returnValue) === "omitted") {
2807
2974
  return true;
@@ -2847,7 +3014,7 @@ var createExecutionRecorder = (options) => {
2847
3014
  return {
2848
3015
  source,
2849
3016
  functionBoundaries: droppedEvents ? "partial" : "full",
2850
- functionValues: eventsHaveOmittedValues(events) ? "selective" : "full",
3017
+ functionValues: recording.captureValues ? eventsHaveOmittedValues(events) ? "selective" : "full" : "none",
2851
3018
  timings: droppedEvents ? "partial" : "full"
2852
3019
  };
2853
3020
  };
@@ -2865,7 +3032,7 @@ var createExecutionRecorder = (options) => {
2865
3032
  } else {
2866
3033
  if (recording.journal) {
2867
3034
  const materialized = recording.journal.materialize(plansByRuntimeId, recording.startedAtNs);
2868
- events = encodeEventValues(materialized.events);
3035
+ events = encodeEventValues(recording, materialized.events);
2869
3036
  if (recording.lateCapturedCallIds && recording.lateCapturedCallIds.size > 0) {
2870
3037
  events = events.map(
2871
3038
  (event) => event.type === "function_enter" && recording.lateCapturedCallIds?.has(event.callId) ? { ...event, capturedAt: "throw" } : event
@@ -3061,7 +3228,7 @@ var createExecutionRecorder = (options) => {
3061
3228
  liveRecordings.splice(index, 1);
3062
3229
  continue;
3063
3230
  }
3064
- if (nowNs - recording.startedAtNs < maxExecutionHoldNs) continue;
3231
+ if (nowNs - recording.startedAtNs < (recording.sessionHoldNs ?? maxExecutionHoldNs)) continue;
3065
3232
  try {
3066
3233
  expireLongLivedRecording(recording, nowNs);
3067
3234
  } catch {
@@ -3101,6 +3268,7 @@ var createExecutionRecorder = (options) => {
3101
3268
  const observeFailure = (recording, provenance) => {
3102
3269
  if (!recording.evidenceDiscarded) {
3103
3270
  retainFailure(recording);
3271
+ maybeActivateAdaptive(recording);
3104
3272
  }
3105
3273
  return mintOccurrence(recording, provenance);
3106
3274
  };
@@ -3168,7 +3336,7 @@ var createExecutionRecorder = (options) => {
3168
3336
  // snapshot without the exception itself would not be useful for investigation.
3169
3337
  value: (() => {
3170
3338
  try {
3171
- return freezeAndCount(error).value;
3339
+ return freezeAndCount(recording, error).value;
3172
3340
  } catch {
3173
3341
  return { __rasputin_type: "unserializable" };
3174
3342
  }
@@ -3187,7 +3355,7 @@ var createExecutionRecorder = (options) => {
3187
3355
  }
3188
3356
  const callId = ++recording.nextCallId;
3189
3357
  const capturedError = serializedError(recording, error, callId);
3190
- const recordedArgs = capturedArgs ?? mapArrayLike(args, (argument) => captureValue(recording, argument));
3358
+ const recordedArgs = capturedArgs ?? (recording.captureValues ? mapArrayLike(args, (argument) => captureValue(recording, argument)) : ARGS_OMITTED);
3191
3359
  const endedAtNs = process.hrtime.bigint();
3192
3360
  const droppedBefore = recording.journal.dropped;
3193
3361
  const retained = recording.journal.forceCompletedCall(
@@ -3245,6 +3413,23 @@ var createExecutionRecorder = (options) => {
3245
3413
  return void 0;
3246
3414
  }
3247
3415
  };
3416
+ const enqueueSessionRecording = (recording) => {
3417
+ if (recording.sessionRecordingEnqueued || !recording.sessionId) {
3418
+ return;
3419
+ }
3420
+ recording.sessionRecordingEnqueued = true;
3421
+ try {
3422
+ hooks.onSessionRecording?.({
3423
+ sessionId: recording.sessionId,
3424
+ executionId: recording.executionId,
3425
+ outcome: recording.hasError || recording.runFailed ? "error" : "success",
3426
+ runtimeState: stateFrom(recording),
3427
+ redactKeys: recording.sessionRedactKeys,
3428
+ scrubPii: recording.sessionScrubPii
3429
+ });
3430
+ } catch {
3431
+ }
3432
+ };
3248
3433
  const settleInFlight = (recording) => {
3249
3434
  if (recording.inFlightCalls > 0) recording.inFlightCalls--;
3250
3435
  releaseWhenIdle(recording);
@@ -3253,6 +3438,9 @@ var createExecutionRecorder = (options) => {
3253
3438
  try {
3254
3439
  if (!recording.finished || recording.inFlightCalls > 0) return;
3255
3440
  memoryBudget.release(recording.memory);
3441
+ if (recording.retainSuccess && !recording.sessionRecordingEnqueued) {
3442
+ enqueueSessionRecording(recording);
3443
+ }
3256
3444
  if (!recording.hasError && !recording.retainedForError) {
3257
3445
  discardSuccessfulEvidence(recording);
3258
3446
  return;
@@ -3272,10 +3460,13 @@ var createExecutionRecorder = (options) => {
3272
3460
  stats.activeExecutions = Math.max(0, stats.activeExecutions - 1);
3273
3461
  if (recording.runFailed && !recording.hasError) {
3274
3462
  retainFailure(recording);
3463
+ maybeActivateAdaptive(recording);
3275
3464
  }
3276
- if (!recording.hasError) {
3465
+ if (!recording.hasError && !recording.retainSuccess) {
3277
3466
  stats.successfulExecutionsDiscarded++;
3278
3467
  }
3468
+ const finishedKey = executionTypeKey(recording.execution);
3469
+ if (finishedKey) hooks.observeExecutionType?.(finishedKey);
3279
3470
  recording.finishedAtNs = process.hrtime.bigint();
3280
3471
  addRecorderTime(recording, recording.finishedAtNs - recorderStartedAtNs);
3281
3472
  recordInlineTiming(recording);
@@ -3296,16 +3487,28 @@ var createExecutionRecorder = (options) => {
3296
3487
  try {
3297
3488
  const recorderStartedAtNs = process.hrtime.bigint();
3298
3489
  sweepLongLivedExecutions(recorderStartedAtNs);
3490
+ const startedAtMs = nowMs();
3491
+ const livePolicy = policySnapshotFor();
3492
+ const execution = {
3493
+ ...metadata,
3494
+ ...metadata.request ? { request: { ...metadata.request } } : {}
3495
+ };
3496
+ const identityComplete = executionTypeKey(execution) !== void 0;
3497
+ const captureValues = captureValuesFor(execution, livePolicy, startedAtMs);
3498
+ const policySnapshot = recorderMode === "adaptive" && !identityComplete ? new Map(livePolicy) : EMPTY_POLICY_SNAPSHOT;
3499
+ const liveSessions = hooks.sessionCaptureSnapshot?.() ?? EMPTY_SESSION_SNAPSHOT;
3500
+ const sessionCaptureSnapshot = identityComplete ? EMPTY_SESSION_SNAPSHOT : new Map(liveSessions);
3501
+ if (recorderMode === "adaptive") {
3502
+ if (captureValues) stats.adaptiveFullExecutions++;
3503
+ else stats.adaptiveLightExecutions++;
3504
+ }
3299
3505
  const recording = {
3300
3506
  executionId: `${Date.now()}-${process.pid}-${++executionCounter}`,
3301
3507
  storageGeneration: ++storageClock,
3302
- startedAtMs: Date.now(),
3508
+ startedAtMs,
3303
3509
  startedAtNs: recorderStartedAtNs,
3304
3510
  inlineRecorderTimeNs: 0n,
3305
- execution: {
3306
- ...metadata,
3307
- ...metadata.request ? { request: { ...metadata.request } } : {}
3308
- },
3511
+ execution,
3309
3512
  journal: void 0,
3310
3513
  capturedErrors: /* @__PURE__ */ new WeakMap(),
3311
3514
  nextCallId: 0,
@@ -3315,8 +3518,13 @@ var createExecutionRecorder = (options) => {
3315
3518
  memory: memoryBudget.startExecution(),
3316
3519
  partialSnapshotCounted: false,
3317
3520
  sawAutomatic: false,
3318
- sawManual: false
3521
+ sawManual: false,
3522
+ captureValues,
3523
+ policySnapshot,
3524
+ identityResolved: identityComplete,
3525
+ sessionCaptureSnapshot
3319
3526
  };
3527
+ if (identityComplete) tryAdmitLiveSession(recording);
3320
3528
  stats.activeExecutions++;
3321
3529
  stats.peakActiveExecutions = Math.max(stats.peakActiveExecutions, stats.activeExecutions);
3322
3530
  liveRecordings.push(recording);
@@ -3363,7 +3571,14 @@ var createExecutionRecorder = (options) => {
3363
3571
  return void 0;
3364
3572
  }
3365
3573
  },
3366
- finish: (finishMetadata) => finish(store, finishMetadata)
3574
+ finish: (finishMetadata) => finish(store, finishMetadata),
3575
+ mergeMetadata: (nextMetadata) => {
3576
+ try {
3577
+ mergeExecutionMetadata(recording.execution, nextMetadata);
3578
+ completeIdentityFromSnapshot(recording);
3579
+ } catch {
3580
+ }
3581
+ }
3367
3582
  };
3368
3583
  } catch {
3369
3584
  return noOpExecution.createScope(metadata);
@@ -3413,7 +3628,7 @@ var createExecutionRecorder = (options) => {
3413
3628
  }
3414
3629
  stats.functionCallsObserved++;
3415
3630
  const recorderStartedAtNs = process.hrtime.bigint();
3416
- if (store.suppressCapture || plan.excluded) {
3631
+ if (skipCapture(store, plan)) {
3417
3632
  stats.functionCallsExcluded++;
3418
3633
  return runStore({ ...store, suppressCapture: true }, function __rasputinHandleRun__5() {
3419
3634
  addRecorderTime(store.recording, process.hrtime.bigint() - recorderStartedAtNs);
@@ -3430,7 +3645,7 @@ var createExecutionRecorder = (options) => {
3430
3645
  if (group.observedCalls === 1) journal?.notePlan(plan.runtimePlanId);
3431
3646
  } catch {
3432
3647
  }
3433
- if (group.observedCalls > maxCapturedCallsPerFunction) {
3648
+ if (group.observedCalls > capturedCallLimitFor(recording)) {
3434
3649
  const startedAtNs2 = process.hrtime.bigint();
3435
3650
  try {
3436
3651
  const result = runStore(store, function __rasputinHandleRun__5() {
@@ -3493,7 +3708,7 @@ var createExecutionRecorder = (options) => {
3493
3708
  }
3494
3709
  const callId = ++recording.nextCallId;
3495
3710
  const enterTimestampNs = process.hrtime.bigint() - recording.startedAtNs;
3496
- const capturedArgs = omitCallValues ? mapArrayLike(args, () => rasputinOmitted()) : mapArrayLike(args, (argument) => captureValue(recording, argument));
3711
+ const capturedArgs = enterPayload(recording, omitCallValues, args);
3497
3712
  try {
3498
3713
  journal.startCall(plan.runtimePlanId, callId, parentCallId, enterTimestampNs, capturedArgs);
3499
3714
  } catch {
@@ -3519,7 +3734,7 @@ var createExecutionRecorder = (options) => {
3519
3734
  (value) => {
3520
3735
  if (recording.journal) {
3521
3736
  const endedAtNs = process.hrtime.bigint();
3522
- const returnValue = omitCallValues ? rasputinOmitted() : captureValue(recording, value);
3737
+ const returnValue = exitPayload(recording, omitCallValues, value);
3523
3738
  recording.journal.finishCall(
3524
3739
  KIND_EXIT,
3525
3740
  callId,
@@ -3576,7 +3791,7 @@ var createExecutionRecorder = (options) => {
3576
3791
  try {
3577
3792
  if (this.status !== "failed") {
3578
3793
  this.status = "left";
3579
- this.pendingReturn = value;
3794
+ if (this.recording.captureValues) this.pendingReturn = value;
3580
3795
  }
3581
3796
  return value;
3582
3797
  } catch {
@@ -3592,19 +3807,21 @@ var createExecutionRecorder = (options) => {
3592
3807
  captureCompletedThrow(
3593
3808
  this.recording,
3594
3809
  this.plan,
3595
- liveArgs ?? this.args,
3810
+ this.recording.captureValues ? liveArgs ?? this.args : EMPTY_ARGS,
3596
3811
  this.parentCallId,
3597
3812
  this.startedAtNs,
3598
- error
3813
+ error,
3814
+ this.recording.captureValues ? void 0 : ARGS_OMITTED
3599
3815
  );
3600
3816
  } else if (this.mode === "dropped" && this.captureDroppedThrow && this.plan) {
3601
3817
  captureCompletedThrow(
3602
3818
  this.recording,
3603
3819
  this.plan,
3604
- this.args,
3820
+ this.recording.captureValues ? this.args : EMPTY_ARGS,
3605
3821
  this.parentCallId,
3606
3822
  this.startedAtNs,
3607
- error
3823
+ error,
3824
+ this.recording.captureValues ? void 0 : ARGS_OMITTED
3608
3825
  );
3609
3826
  }
3610
3827
  } catch {
@@ -3694,7 +3911,7 @@ var createExecutionRecorder = (options) => {
3694
3911
  const writeCapturedExit = (frame, value) => {
3695
3912
  if (!frame.recording.journal) return;
3696
3913
  const endedAtNs = process.hrtime.bigint();
3697
- const returnValue = frame.omitCallValues ? rasputinOmitted() : captureValue(frame.recording, value);
3914
+ const returnValue = exitPayload(frame.recording, frame.omitCallValues, value);
3698
3915
  frame.recording.journal.finishCall(
3699
3916
  KIND_EXIT,
3700
3917
  frame.callId,
@@ -3764,7 +3981,7 @@ var createExecutionRecorder = (options) => {
3764
3981
  const recording = store.recording;
3765
3982
  const omitCallValues = omitValues === true || plan.omitCallValues;
3766
3983
  const parentCallId = store.currentCallId;
3767
- if (store.suppressCapture || plan.excluded) {
3984
+ if (skipCapture(store, plan)) {
3768
3985
  stats.functionCallsExcluded++;
3769
3986
  const excludedStore = { ...store, suppressCapture: true };
3770
3987
  const frame = new CallFrame(
@@ -3794,13 +4011,14 @@ var createExecutionRecorder = (options) => {
3794
4011
  }
3795
4012
  const startedAtNs = process.hrtime.bigint();
3796
4013
  const parentStore = store;
3797
- if (group.observedCalls > maxCapturedCallsPerFunction) {
4014
+ const retainedArgs = recording.captureValues ? args : EMPTY_ARGS;
4015
+ if (group.observedCalls > capturedCallLimitFor(recording)) {
3798
4016
  return activateUncaptured(
3799
4017
  "suppressed",
3800
4018
  recording,
3801
4019
  parentStore,
3802
4020
  plan,
3803
- args,
4021
+ retainedArgs,
3804
4022
  omitCallValues,
3805
4023
  parentCallId,
3806
4024
  startedAtNs,
@@ -3815,7 +4033,7 @@ var createExecutionRecorder = (options) => {
3815
4033
  recording,
3816
4034
  parentStore,
3817
4035
  plan,
3818
- args,
4036
+ retainedArgs,
3819
4037
  omitCallValues,
3820
4038
  parentCallId,
3821
4039
  startedAtNs,
@@ -3829,7 +4047,7 @@ var createExecutionRecorder = (options) => {
3829
4047
  recording,
3830
4048
  parentStore,
3831
4049
  plan,
3832
- args,
4050
+ retainedArgs,
3833
4051
  omitCallValues,
3834
4052
  parentCallId,
3835
4053
  startedAtNs,
@@ -3843,7 +4061,7 @@ var createExecutionRecorder = (options) => {
3843
4061
  recording,
3844
4062
  parentStore,
3845
4063
  plan,
3846
- args,
4064
+ retainedArgs,
3847
4065
  omitCallValues,
3848
4066
  parentCallId,
3849
4067
  startedAtNs,
@@ -3853,7 +4071,7 @@ var createExecutionRecorder = (options) => {
3853
4071
  }
3854
4072
  const callId = ++recording.nextCallId;
3855
4073
  const enterTimestampNs = process.hrtime.bigint() - recording.startedAtNs;
3856
- const capturedArgs = omitCallValues ? mapArrayLike(args, () => rasputinOmitted()) : mapArrayLike(args, (argument) => captureValue(recording, argument));
4074
+ const capturedArgs = enterPayload(recording, omitCallValues, args);
3857
4075
  try {
3858
4076
  journal.startCall(plan.runtimePlanId, callId, parentCallId, enterTimestampNs, capturedArgs);
3859
4077
  } catch {
@@ -3863,7 +4081,7 @@ var createExecutionRecorder = (options) => {
3863
4081
  recording,
3864
4082
  parentStore,
3865
4083
  plan,
3866
- args,
4084
+ retainedArgs,
3867
4085
  omitCallValues,
3868
4086
  parentCallId,
3869
4087
  startedAtNs,
@@ -3878,7 +4096,7 @@ var createExecutionRecorder = (options) => {
3878
4096
  parentStore,
3879
4097
  callStore,
3880
4098
  plan,
3881
- args,
4099
+ retainedArgs,
3882
4100
  omitCallValues,
3883
4101
  parentCallId,
3884
4102
  startedAtNs,
@@ -3954,6 +4172,10 @@ var createExecutionRecorder = (options) => {
3954
4172
  ...stats,
3955
4173
  ...memoryBudget.getStats(),
3956
4174
  ...journalPool.stats(),
4175
+ adaptiveNotifyFailures: 0,
4176
+ adaptiveRefreshFailures: 0,
4177
+ lastAdaptiveFailureKind: null,
4178
+ ...hooks.getStats?.(),
3957
4179
  ...phases ? {
3958
4180
  phaseAlsNs: Number(phases.alsNs),
3959
4181
  phaseMaterializeNs: Number(phases.materializeNs)
@@ -3998,6 +4220,881 @@ var installAutomaticExecutionRuntime = (execution) => {
3998
4220
  };
3999
4221
  };
4000
4222
 
4223
+ // src/execution-recorder/bind-adaptive-recorder.ts
4224
+ import {
4225
+ resolveClientActivation,
4226
+ resolveEndpointUrls as resolveEndpointUrls2
4227
+ } from "@rasputin-ai/core";
4228
+
4229
+ // src/execution-recorder/execution-recording-sync.ts
4230
+ import {
4231
+ copyRedactKeys,
4232
+ defaultIngestFetch,
4233
+ encodeJsonRequestBodyAsync,
4234
+ MAX_REDACT_KEYS
4235
+ } from "@rasputin-ai/core";
4236
+
4237
+ // src/execution-recorder/session-freeze-overrides.ts
4238
+ var BOUNDS = {
4239
+ maxDepth: { min: 1, max: 8 },
4240
+ maxObjectKeys: { min: 1, max: 100 },
4241
+ maxArrayElements: { min: 1, max: 100 },
4242
+ maxStringLength: { min: 32, max: 4e3 },
4243
+ maxSerializedValueBytes: { min: 1024, max: 64 * 1024 },
4244
+ maxCapturedCallsPerFunction: { min: 1, max: 100 },
4245
+ maxExecutionHoldMs: { min: 1e3, max: 5 * 6e4 }
4246
+ };
4247
+ var MAX_SERIALIZER_CACHE = 32;
4248
+ var isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
4249
+ var optionalFiniteNumber = (value) => typeof value === "number" && Number.isFinite(value) ? value : void 0;
4250
+ var optionalStringList = (value) => {
4251
+ if (!Array.isArray(value)) return void 0;
4252
+ const out = [];
4253
+ for (const item of value) {
4254
+ if (typeof item !== "string" || !item.trim()) continue;
4255
+ out.push(item.trim());
4256
+ }
4257
+ return out.length > 0 ? out : void 0;
4258
+ };
4259
+ var bounded = (value, min, max) => Math.min(max, Math.max(min, Math.round(value)));
4260
+ var clampToBounds = (requested, fallback, min, max) => {
4261
+ if (requested === void 0 || !Number.isFinite(requested)) return fallback;
4262
+ return bounded(requested, min, max);
4263
+ };
4264
+ var parseSessionSettings = (value) => {
4265
+ if (!isRecord(value)) return void 0;
4266
+ const overrides = {};
4267
+ const maxDepth = optionalFiniteNumber(value.maxDepth);
4268
+ const maxObjectKeys = optionalFiniteNumber(value.maxObjectKeys);
4269
+ const maxArrayElements = optionalFiniteNumber(value.maxArrayElements);
4270
+ const maxStringLength = optionalFiniteNumber(value.maxStringLength);
4271
+ const maxSerializedValueBytes = optionalFiniteNumber(value.maxSerializedValueBytes);
4272
+ const maxCapturedCallsPerFunction = optionalFiniteNumber(value.maxCapturedCallsPerFunction);
4273
+ const maxExecutionHoldMs = optionalFiniteNumber(value.maxExecutionHoldMs);
4274
+ if (maxDepth !== void 0)
4275
+ overrides.maxDepth = bounded(maxDepth, BOUNDS.maxDepth.min, BOUNDS.maxDepth.max);
4276
+ if (maxObjectKeys !== void 0) {
4277
+ overrides.maxObjectKeys = bounded(
4278
+ maxObjectKeys,
4279
+ BOUNDS.maxObjectKeys.min,
4280
+ BOUNDS.maxObjectKeys.max
4281
+ );
4282
+ }
4283
+ if (maxArrayElements !== void 0) {
4284
+ overrides.maxArrayElements = bounded(
4285
+ maxArrayElements,
4286
+ BOUNDS.maxArrayElements.min,
4287
+ BOUNDS.maxArrayElements.max
4288
+ );
4289
+ }
4290
+ if (maxStringLength !== void 0) {
4291
+ overrides.maxStringLength = bounded(
4292
+ maxStringLength,
4293
+ BOUNDS.maxStringLength.min,
4294
+ BOUNDS.maxStringLength.max
4295
+ );
4296
+ }
4297
+ if (maxSerializedValueBytes !== void 0) {
4298
+ overrides.maxSerializedValueBytes = bounded(
4299
+ maxSerializedValueBytes,
4300
+ BOUNDS.maxSerializedValueBytes.min,
4301
+ BOUNDS.maxSerializedValueBytes.max
4302
+ );
4303
+ }
4304
+ if (maxCapturedCallsPerFunction !== void 0) {
4305
+ overrides.maxCapturedCallsPerFunction = bounded(
4306
+ maxCapturedCallsPerFunction,
4307
+ BOUNDS.maxCapturedCallsPerFunction.min,
4308
+ BOUNDS.maxCapturedCallsPerFunction.max
4309
+ );
4310
+ }
4311
+ if (maxExecutionHoldMs !== void 0) {
4312
+ overrides.maxExecutionHoldMs = bounded(
4313
+ maxExecutionHoldMs,
4314
+ BOUNDS.maxExecutionHoldMs.min,
4315
+ BOUNDS.maxExecutionHoldMs.max
4316
+ );
4317
+ }
4318
+ const excludeSources = optionalStringList(value.excludeSources);
4319
+ const redactKeys = optionalStringList(value.redactKeys);
4320
+ if (excludeSources) overrides.excludeSources = excludeSources;
4321
+ if (redactKeys) overrides.redactKeys = redactKeys;
4322
+ if (typeof value.scrubPII === "boolean") overrides.scrubPII = value.scrubPII;
4323
+ return Object.keys(overrides).length > 0 ? overrides : void 0;
4324
+ };
4325
+ var clampSessionFreezeLimits = (overrides, processLimits) => ({
4326
+ maxDepth: clampToBounds(
4327
+ overrides?.maxDepth,
4328
+ processLimits.maxDepth,
4329
+ BOUNDS.maxDepth.min,
4330
+ BOUNDS.maxDepth.max
4331
+ ),
4332
+ maxObjectKeys: clampToBounds(
4333
+ overrides?.maxObjectKeys,
4334
+ processLimits.maxObjectKeys,
4335
+ BOUNDS.maxObjectKeys.min,
4336
+ BOUNDS.maxObjectKeys.max
4337
+ ),
4338
+ maxArrayElements: clampToBounds(
4339
+ overrides?.maxArrayElements,
4340
+ processLimits.maxArrayElements,
4341
+ BOUNDS.maxArrayElements.min,
4342
+ BOUNDS.maxArrayElements.max
4343
+ ),
4344
+ maxStringLength: clampToBounds(
4345
+ overrides?.maxStringLength,
4346
+ processLimits.maxStringLength,
4347
+ BOUNDS.maxStringLength.min,
4348
+ BOUNDS.maxStringLength.max
4349
+ ),
4350
+ maxSerializedValueBytes: clampToBounds(
4351
+ overrides?.maxSerializedValueBytes,
4352
+ processLimits.maxSerializedValueBytes,
4353
+ BOUNDS.maxSerializedValueBytes.min,
4354
+ BOUNDS.maxSerializedValueBytes.max
4355
+ )
4356
+ });
4357
+ var freezeLimitsFingerprint = (limits) => `${limits.maxDepth}:${limits.maxObjectKeys}:${limits.maxArrayElements}:${limits.maxStringLength}:${limits.maxSerializedValueBytes}`;
4358
+ var serializeSourceExclusions = (exclusions) => {
4359
+ if (!exclusions?.length) return void 0;
4360
+ const out = [];
4361
+ for (const item of exclusions) {
4362
+ if (typeof item === "string" && item.trim()) out.push(item.trim());
4363
+ else if (item instanceof RegExp) out.push(item.toString());
4364
+ }
4365
+ return out.length > 0 ? out : void 0;
4366
+ };
4367
+ var reportedRecorderSettings = (options, scrubPII) => ({
4368
+ maxDepth: options?.maxDepth,
4369
+ maxObjectKeys: options?.maxObjectKeys,
4370
+ maxArrayElements: options?.maxArrayElements,
4371
+ maxStringLength: options?.maxStringLength,
4372
+ maxSerializedValueBytes: options?.maxSerializedValueBytes,
4373
+ maxEventsPerExecution: options?.maxEventsPerExecution,
4374
+ maxCapturedCallsPerFunction: options?.maxCapturedCallsPerFunction,
4375
+ maxActiveMemoryBytes: options?.maxActiveMemoryBytes,
4376
+ maxExecutionHoldMs: options?.maxExecutionHoldMs,
4377
+ maxRetainedErrorRecordings: options?.maxRetainedErrorRecordings,
4378
+ fullCaptureDurationMs: options?.adaptive?.fullCaptureDurationMs,
4379
+ recorder_enabled: options?.enabled !== false,
4380
+ excludeSources: serializeSourceExclusions(options?.excludeSources),
4381
+ redactKeys: options?.redactKeys,
4382
+ scrubPII: scrubPII === true
4383
+ });
4384
+ var createSerializerCache = (options) => {
4385
+ const processLimits = compileFreezeLimits(options ?? {});
4386
+ const processFingerprint = freezeLimitsFingerprint(processLimits);
4387
+ const cache = /* @__PURE__ */ new Map();
4388
+ return {
4389
+ serializerFor: (overrides) => {
4390
+ const clamped = clampSessionFreezeLimits(overrides, processLimits);
4391
+ const fingerprint = freezeLimitsFingerprint(clamped);
4392
+ if (fingerprint === processFingerprint) return void 0;
4393
+ const existing = cache.get(fingerprint);
4394
+ if (existing) {
4395
+ cache.delete(fingerprint);
4396
+ cache.set(fingerprint, existing);
4397
+ return existing;
4398
+ }
4399
+ while (cache.size >= MAX_SERIALIZER_CACHE) {
4400
+ const oldest = cache.keys().next().value;
4401
+ if (oldest === void 0) break;
4402
+ cache.delete(oldest);
4403
+ }
4404
+ const created = createSafeSerializer(clamped);
4405
+ cache.set(fingerprint, created);
4406
+ return created;
4407
+ }
4408
+ };
4409
+ };
4410
+
4411
+ // src/execution-recorder/execution-recording-sync.ts
4412
+ var MAX_CACHE_ENTRIES = 1024;
4413
+ var MAX_PENDING_NOTIFIES = 32;
4414
+ var MAX_PENDING_TYPES = 64;
4415
+ var DEFAULT_POLL_INTERVAL_MS = 1e4;
4416
+ var REQUEST_TIMEOUT_MS = 5e3;
4417
+ var MAX_RETRIES = 5;
4418
+ var MAX_POLL_JITTER_MS = 2e3;
4419
+ var trimmed2 = (value) => typeof value === "string" ? value.trim() : "";
4420
+ var isRecord2 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
4421
+ var unwrapPayload = (body) => {
4422
+ if (!isRecord2(body)) return void 0;
4423
+ if ("payload" in body && isRecord2(body.payload)) return body.payload;
4424
+ return body;
4425
+ };
4426
+ var classifyHttpFailure = (status) => {
4427
+ if (status === 429) return "rate_limited";
4428
+ if (status >= 500) return "server_error";
4429
+ return "non_retryable_http";
4430
+ };
4431
+ var backoffMs = (attempt) => Math.min(3e3, 250 * 2 ** attempt);
4432
+ var createExecutionRecordingCoordinator = (options) => {
4433
+ const environment = trimmed2(options.environment);
4434
+ const nowMs = () => options.nowMs?.() ?? Date.now();
4435
+ const fetchFn = options.fetch ?? defaultIngestFetch();
4436
+ const networkEnabled = environment.length > 0;
4437
+ const instanceId = crypto.randomUUID();
4438
+ const startedAt = /* @__PURE__ */ new Date();
4439
+ const redactKeys = copyRedactKeys(options.recorderOptions?.redactKeys);
4440
+ const scrubPii = options.scrubPII === true;
4441
+ const serializers = createSerializerCache(options.recorderOptions);
4442
+ const cache = /* @__PURE__ */ new Map();
4443
+ const pending = /* @__PURE__ */ new Map();
4444
+ const catalog = /* @__PURE__ */ new Map();
4445
+ const sessionsById = /* @__PURE__ */ new Map();
4446
+ const completedSessionIds = /* @__PURE__ */ new Set();
4447
+ const recordings = [];
4448
+ const capabilities = ["catalog", "manual_sessions", "settings_overrides"];
4449
+ let closed = false;
4450
+ let closing = false;
4451
+ let sessionsDirty = true;
4452
+ let sessionSnapshot = /* @__PURE__ */ new Map();
4453
+ let syncFlight;
4454
+ let pollTimer;
4455
+ let pollStartTimer;
4456
+ let pump;
4457
+ let pumpAgain = false;
4458
+ let sendingKey;
4459
+ let recordingPump;
4460
+ let notifyFailures = 0;
4461
+ let refreshFailures = 0;
4462
+ let lastFailureKind = null;
4463
+ let pollAbort;
4464
+ let notifyAbort;
4465
+ let recordingAbort;
4466
+ let cancelWork = new AbortController();
4467
+ const rememberFailure = (kind) => {
4468
+ lastFailureKind = kind;
4469
+ };
4470
+ const dropExpiredCache = (atMs) => {
4471
+ for (const [key, expiresAt] of cache) {
4472
+ if (expiresAt <= atMs) cache.delete(key);
4473
+ }
4474
+ };
4475
+ const trimCache = () => {
4476
+ const atMs = nowMs();
4477
+ dropExpiredCache(atMs);
4478
+ while (cache.size > MAX_CACHE_ENTRIES) {
4479
+ const oldest = cache.keys().next().value;
4480
+ if (oldest === void 0) break;
4481
+ cache.delete(oldest);
4482
+ }
4483
+ };
4484
+ const peek = () => cache;
4485
+ const sessionView = (session) => ({
4486
+ sessionId: session.sessionId,
4487
+ expiresAtMs: session.expiresAtMs,
4488
+ serializer: session.serializer,
4489
+ redactKeys: session.redactKeys,
4490
+ excludeSources: session.excludeSources,
4491
+ maxCapturedCallsPerFunction: session.maxCapturedCallsPerFunction,
4492
+ maxExecutionHoldMs: session.maxExecutionHoldMs,
4493
+ scrubPII: session.scrubPII
4494
+ });
4495
+ const sessionHasRoom = (session, atMs) => session.admitted < session.requestedCount && session.expiresAtMs > atMs;
4496
+ const rebuildSessionSnapshot = () => {
4497
+ const atMs = nowMs();
4498
+ const map = /* @__PURE__ */ new Map();
4499
+ for (const session of sessionsById.values()) {
4500
+ if (!sessionHasRoom(session, atMs) || map.has(session.executionKey)) continue;
4501
+ map.set(session.executionKey, sessionView(session));
4502
+ }
4503
+ sessionSnapshot = map;
4504
+ sessionsDirty = false;
4505
+ };
4506
+ const markSessionsDirty = () => {
4507
+ sessionsDirty = true;
4508
+ };
4509
+ const notifySignal = () => {
4510
+ if (!notifyAbort || notifyAbort.signal.aborted) notifyAbort = new AbortController();
4511
+ return notifyAbort.signal;
4512
+ };
4513
+ const recordingSignal = () => {
4514
+ if (!recordingAbort || recordingAbort.signal.aborted) recordingAbort = new AbortController();
4515
+ return recordingAbort.signal;
4516
+ };
4517
+ const pollSignal = () => {
4518
+ if (!pollAbort || pollAbort.signal.aborted) pollAbort = new AbortController();
4519
+ return pollAbort.signal;
4520
+ };
4521
+ const wait = (ms, signal) => new Promise((resolve) => {
4522
+ if (signal.aborted) {
4523
+ resolve();
4524
+ return;
4525
+ }
4526
+ const timer = setTimeout(() => {
4527
+ signal.removeEventListener("abort", onAbort);
4528
+ resolve();
4529
+ }, ms);
4530
+ timer.unref?.();
4531
+ const onAbort = () => {
4532
+ clearTimeout(timer);
4533
+ resolve();
4534
+ };
4535
+ signal.addEventListener("abort", onAbort, { once: true });
4536
+ });
4537
+ const joinUntil = async (work, signal) => {
4538
+ if (!work || signal.aborted) return;
4539
+ let onAbort;
4540
+ const aborted = new Promise((resolve) => {
4541
+ onAbort = () => resolve();
4542
+ signal.addEventListener("abort", onAbort, { once: true });
4543
+ });
4544
+ try {
4545
+ await Promise.race([work, aborted]);
4546
+ } finally {
4547
+ if (onAbort) signal.removeEventListener("abort", onAbort);
4548
+ }
4549
+ };
4550
+ const workSignal = (signal) => AbortSignal.any([signal, cancelWork.signal]);
4551
+ const interruptWork = () => {
4552
+ cancelWork.abort();
4553
+ cancelWork = new AbortController();
4554
+ notifyAbort?.abort();
4555
+ recordingAbort?.abort();
4556
+ pollAbort?.abort();
4557
+ };
4558
+ const fetchEncoded = (url, encoded, requestSignal) => {
4559
+ const headers = {
4560
+ Authorization: `Bearer ${options.ingestToken}`,
4561
+ "Content-Type": "application/json",
4562
+ Accept: "application/json"
4563
+ };
4564
+ if (encoded.gzip) headers["Content-Encoding"] = "gzip";
4565
+ return fetchFn(url, {
4566
+ method: "POST",
4567
+ headers,
4568
+ body: encoded.body,
4569
+ signal: requestSignal
4570
+ });
4571
+ };
4572
+ const withRequestTimeout = async (signal, run) => {
4573
+ const combined = workSignal(signal);
4574
+ const timeout = new AbortController();
4575
+ const timer = setTimeout(() => timeout.abort(), REQUEST_TIMEOUT_MS);
4576
+ timer.unref?.();
4577
+ const onAbort = () => timeout.abort();
4578
+ combined.addEventListener("abort", onAbort, { once: true });
4579
+ if (combined.aborted) timeout.abort();
4580
+ const requestSignal = AbortSignal.any([combined, timeout.signal]);
4581
+ try {
4582
+ return await run(requestSignal);
4583
+ } finally {
4584
+ clearTimeout(timer);
4585
+ combined.removeEventListener("abort", onAbort);
4586
+ }
4587
+ };
4588
+ const postEncoded = async (url, encoded, signal, readBody) => withRequestTimeout(signal, async (requestSignal) => {
4589
+ const response = await fetchEncoded(url, encoded, requestSignal);
4590
+ const body = await readBody(response);
4591
+ return { response, body };
4592
+ });
4593
+ const postJson = async (url, body, signal, readBody) => postEncoded(url, { body: JSON.stringify(body), gzip: false }, signal, readBody);
4594
+ const sendNotify = async (item, signal) => {
4595
+ if (item.expiresAtMs <= nowMs()) return true;
4596
+ for (let attempt = 0; attempt <= MAX_RETRIES; attempt++) {
4597
+ if (signal.aborted) return false;
4598
+ if (item.expiresAtMs <= nowMs()) return true;
4599
+ try {
4600
+ const { response, body: payload } = await postJson(
4601
+ options.activateUrl,
4602
+ {
4603
+ environment,
4604
+ execution_key: item.executionKey,
4605
+ activated_at: new Date(item.activatedAtMs).toISOString(),
4606
+ expires_at: new Date(item.expiresAtMs).toISOString(),
4607
+ duration_ms: Math.max(1, item.expiresAtMs - item.activatedAtMs)
4608
+ },
4609
+ signal,
4610
+ async (activateResponse) => {
4611
+ if (!activateResponse.ok) return void 0;
4612
+ try {
4613
+ return unwrapPayload(await activateResponse.json());
4614
+ } catch {
4615
+ return void 0;
4616
+ }
4617
+ }
4618
+ );
4619
+ if (response.ok) {
4620
+ const expiresAt = Date.parse(String(payload?.expires_at ?? ""));
4621
+ if (Number.isFinite(expiresAt) && expiresAt > nowMs()) {
4622
+ cache.set(item.executionKey, expiresAt);
4623
+ }
4624
+ return true;
4625
+ }
4626
+ const kind = classifyHttpFailure(response.status);
4627
+ rememberFailure(kind);
4628
+ if (kind === "non_retryable_http") {
4629
+ notifyFailures++;
4630
+ return true;
4631
+ }
4632
+ if (attempt === MAX_RETRIES) {
4633
+ notifyFailures++;
4634
+ return false;
4635
+ }
4636
+ await wait(backoffMs(attempt), signal);
4637
+ } catch (error) {
4638
+ if (signal.aborted || error instanceof Error && error.name === "AbortError") {
4639
+ rememberFailure("aborted");
4640
+ return false;
4641
+ }
4642
+ rememberFailure("network_error");
4643
+ if (attempt === MAX_RETRIES) {
4644
+ notifyFailures++;
4645
+ return false;
4646
+ }
4647
+ await wait(backoffMs(attempt), signal);
4648
+ }
4649
+ }
4650
+ return false;
4651
+ };
4652
+ const runPump = async (signal) => {
4653
+ do {
4654
+ pumpAgain = false;
4655
+ const queued = new Set(pending.keys());
4656
+ for (const key of queued) {
4657
+ if (signal.aborted) return;
4658
+ const current = pending.get(key);
4659
+ if (!current) continue;
4660
+ sendingKey = key;
4661
+ const done = await sendNotify(current, signal);
4662
+ sendingKey = void 0;
4663
+ if (pending.get(key) !== current) pumpAgain = true;
4664
+ else if (done || !signal.aborted) pending.delete(key);
4665
+ }
4666
+ for (const key of pending.keys()) {
4667
+ if (!queued.has(key)) {
4668
+ pumpAgain = true;
4669
+ break;
4670
+ }
4671
+ }
4672
+ } while (pumpAgain && pending.size > 0 && !signal.aborted);
4673
+ };
4674
+ const drainNotifies = async (signal) => {
4675
+ while (pending.size > 0 && !signal.aborted) {
4676
+ if (pump) {
4677
+ pumpAgain = true;
4678
+ await joinUntil(pump, signal);
4679
+ continue;
4680
+ }
4681
+ const running = runPump(signal);
4682
+ pump = running;
4683
+ try {
4684
+ await running;
4685
+ } finally {
4686
+ if (pump === running) pump = void 0;
4687
+ }
4688
+ break;
4689
+ }
4690
+ };
4691
+ const kickNotify = () => {
4692
+ if (!networkEnabled || closed || closing || pending.size === 0 || options.mode !== "adaptive")
4693
+ return;
4694
+ void drainNotifies(notifySignal());
4695
+ };
4696
+ const rememberCatalog = (key, atMs) => {
4697
+ if (key.length === 0 || key.length > MAX_EXECUTION_TYPE_KEY_LENGTH) return;
4698
+ if (catalog.size >= MAX_CACHE_ENTRIES && !catalog.has(key)) {
4699
+ const oldest = catalog.keys().next().value;
4700
+ if (oldest !== void 0) catalog.delete(oldest);
4701
+ }
4702
+ catalog.set(key, atMs);
4703
+ };
4704
+ const applyCompletedSessionIds = (value) => {
4705
+ if (!Array.isArray(value)) return;
4706
+ for (const entry of value) {
4707
+ const sessionId = trimmed2(entry);
4708
+ if (!sessionId) continue;
4709
+ completedSessionIds.add(sessionId);
4710
+ sessionsById.delete(sessionId);
4711
+ }
4712
+ markSessionsDirty();
4713
+ };
4714
+ const applySessions = (entries) => {
4715
+ if (!Array.isArray(entries)) return;
4716
+ const atMs = nowMs();
4717
+ const next = /* @__PURE__ */ new Map();
4718
+ for (const entry of entries) {
4719
+ if (!isRecord2(entry)) continue;
4720
+ const sessionId = trimmed2(entry.id);
4721
+ const executionKeyValue = trimmed2(entry.execution_key);
4722
+ const status = trimmed2(entry.status);
4723
+ const expiresAtMs = Date.parse(String(entry.expires_at ?? ""));
4724
+ const requestedCount = typeof entry.requested_count === "number" && Number.isFinite(entry.requested_count) ? Math.round(entry.requested_count) : 0;
4725
+ if (!sessionId || !executionKeyValue || status !== "active") continue;
4726
+ if (completedSessionIds.has(sessionId)) continue;
4727
+ if (!Number.isFinite(expiresAtMs) || expiresAtMs <= atMs || requestedCount < 1) continue;
4728
+ const existing = sessionsById.get(sessionId);
4729
+ const overrides = parseSessionSettings(entry.overrides);
4730
+ next.set(sessionId, {
4731
+ sessionId,
4732
+ executionKey: executionKeyValue,
4733
+ expiresAtMs,
4734
+ requestedCount,
4735
+ admitted: existing?.admitted ?? 0,
4736
+ serializer: serializers.serializerFor(overrides),
4737
+ redactKeys: overrides?.redactKeys,
4738
+ excludeSources: overrides?.excludeSources,
4739
+ maxCapturedCallsPerFunction: overrides?.maxCapturedCallsPerFunction,
4740
+ maxExecutionHoldMs: overrides?.maxExecutionHoldMs,
4741
+ scrubPII: overrides?.scrubPII
4742
+ });
4743
+ }
4744
+ sessionsById.clear();
4745
+ for (const [id, session] of next) sessionsById.set(id, session);
4746
+ markSessionsDirty();
4747
+ };
4748
+ const applyActivations = (activations) => {
4749
+ if (!Array.isArray(activations)) return;
4750
+ const atMs = nowMs();
4751
+ const seen = /* @__PURE__ */ new Set();
4752
+ for (const entry of activations) {
4753
+ if (!isRecord2(entry)) continue;
4754
+ const key = trimmed2(entry.execution_key);
4755
+ const expiresAt = Date.parse(String(entry.expires_at ?? ""));
4756
+ if (!key || !Number.isFinite(expiresAt) || expiresAt <= atMs) continue;
4757
+ cache.set(key, expiresAt);
4758
+ seen.add(key);
4759
+ }
4760
+ trimCache();
4761
+ for (const key of seen) pending.delete(key);
4762
+ };
4763
+ const catalogTypes = () => {
4764
+ const entries = [];
4765
+ for (const [executionKey, lastSeenAtMs] of catalog) {
4766
+ entries.push({ executionKey, lastSeenAtMs });
4767
+ if (entries.length >= MAX_PENDING_TYPES) break;
4768
+ }
4769
+ return entries;
4770
+ };
4771
+ const syncOnce = async (signal) => {
4772
+ if (!networkEnabled || closed) return;
4773
+ const types2 = catalogTypes();
4774
+ try {
4775
+ const { response, body: payload } = await postJson(
4776
+ options.syncUrl,
4777
+ {
4778
+ environment,
4779
+ instance: {
4780
+ id: instanceId,
4781
+ sdk_name: options.sdkName,
4782
+ sdk_version: options.sdkVersion,
4783
+ release: options.release,
4784
+ pid: process.pid,
4785
+ started_at: startedAt.toISOString(),
4786
+ reported_mode: options.mode,
4787
+ reported_settings: reportedRecorderSettings(options.recorderOptions, options.scrubPII),
4788
+ capabilities
4789
+ },
4790
+ types: types2.map((entry) => ({
4791
+ execution_key: entry.executionKey,
4792
+ last_seen_at: new Date(entry.lastSeenAtMs).toISOString()
4793
+ }))
4794
+ },
4795
+ signal,
4796
+ async (syncResponse) => {
4797
+ if (!syncResponse.ok) return void 0;
4798
+ return unwrapPayload(await syncResponse.json());
4799
+ }
4800
+ );
4801
+ if (!response.ok) {
4802
+ rememberFailure(classifyHttpFailure(response.status));
4803
+ refreshFailures++;
4804
+ return;
4805
+ }
4806
+ applyActivations(payload?.activations);
4807
+ applySessions(payload?.sessions);
4808
+ for (const entry of types2) {
4809
+ const current = catalog.get(entry.executionKey);
4810
+ if (current === void 0) continue;
4811
+ catalog.delete(entry.executionKey);
4812
+ if (current !== entry.lastSeenAtMs) {
4813
+ catalog.set(entry.executionKey, current);
4814
+ }
4815
+ }
4816
+ } catch (error) {
4817
+ if (signal.aborted || error instanceof Error && error.name === "AbortError") {
4818
+ rememberFailure("aborted");
4819
+ } else {
4820
+ rememberFailure("network_error");
4821
+ }
4822
+ refreshFailures++;
4823
+ }
4824
+ };
4825
+ const runSyncOnce = async (signal) => {
4826
+ if (syncFlight) {
4827
+ await joinUntil(syncFlight, signal);
4828
+ return;
4829
+ }
4830
+ const running = syncOnce(signal);
4831
+ const flight = running.finally(() => {
4832
+ if (syncFlight === flight) syncFlight = void 0;
4833
+ });
4834
+ syncFlight = flight;
4835
+ await joinUntil(flight, signal);
4836
+ };
4837
+ const sendRecordings = async (batch, signal) => {
4838
+ const combined = workSignal(signal);
4839
+ if (combined.aborted) return false;
4840
+ let encoded;
4841
+ try {
4842
+ encoded = await encodeJsonRequestBodyAsync(
4843
+ {
4844
+ instance_id: instanceId,
4845
+ recordings: batch.map((item) => ({
4846
+ session_id: item.sessionId,
4847
+ execution_id: item.executionId,
4848
+ outcome: item.outcome,
4849
+ runtime_state: item.runtimeState,
4850
+ release: options.release,
4851
+ redact_keys: copyRedactKeys([...redactKeys ?? [], ...item.redactKeys ?? []])?.slice(
4852
+ 0,
4853
+ MAX_REDACT_KEYS
4854
+ ),
4855
+ scrub_pii: item.scrubPii ?? scrubPii
4856
+ }))
4857
+ },
4858
+ void 0,
4859
+ combined
4860
+ );
4861
+ } catch (error) {
4862
+ if (combined.aborted || error instanceof Error && error.name === "AbortError") {
4863
+ rememberFailure("aborted");
4864
+ return false;
4865
+ }
4866
+ rememberFailure("network_error");
4867
+ return false;
4868
+ }
4869
+ for (let attempt = 0; attempt <= MAX_RETRIES; attempt++) {
4870
+ if (combined.aborted) return false;
4871
+ try {
4872
+ const { response, body } = await postEncoded(
4873
+ options.recordingsUrl,
4874
+ encoded,
4875
+ combined,
4876
+ async (uploadResponse) => {
4877
+ if (!uploadResponse.ok) return void 0;
4878
+ try {
4879
+ return unwrapPayload(await uploadResponse.json());
4880
+ } catch {
4881
+ return void 0;
4882
+ }
4883
+ }
4884
+ );
4885
+ if (response.ok) {
4886
+ applyCompletedSessionIds(body?.completed_session_ids);
4887
+ return true;
4888
+ }
4889
+ const kind = classifyHttpFailure(response.status);
4890
+ rememberFailure(kind);
4891
+ if (kind === "non_retryable_http") return true;
4892
+ if (attempt === MAX_RETRIES) return false;
4893
+ await wait(backoffMs(attempt), combined);
4894
+ } catch (error) {
4895
+ if (combined.aborted || error instanceof Error && error.name === "AbortError") {
4896
+ rememberFailure("aborted");
4897
+ return false;
4898
+ }
4899
+ rememberFailure("network_error");
4900
+ if (attempt === MAX_RETRIES) return false;
4901
+ await wait(backoffMs(attempt), combined);
4902
+ }
4903
+ }
4904
+ return false;
4905
+ };
4906
+ const drainRecordings = async (signal) => {
4907
+ while (recordings.length > 0 && !signal.aborted) {
4908
+ const batch = recordings.splice(0, 8);
4909
+ const ok = await sendRecordings(batch, signal);
4910
+ if (!ok) {
4911
+ recordings.unshift(...batch);
4912
+ break;
4913
+ }
4914
+ }
4915
+ };
4916
+ const kickRecordings = () => {
4917
+ if (!networkEnabled || closed || closing || recordings.length === 0) return;
4918
+ if (recordingPump) return;
4919
+ const running = drainRecordings(recordingSignal());
4920
+ recordingPump = running;
4921
+ void running.finally(() => {
4922
+ if (recordingPump === running) recordingPump = void 0;
4923
+ if (recordings.length > 0) kickRecordings();
4924
+ });
4925
+ };
4926
+ const activate = (metadata, window) => {
4927
+ if (closed || options.mode !== "adaptive") return;
4928
+ const key = executionTypeKey(metadata);
4929
+ if (!key) return;
4930
+ const atMs = nowMs();
4931
+ const existing = cache.get(key);
4932
+ if (existing !== void 0 && existing > atMs) return;
4933
+ cache.set(key, window.expiresAtMs);
4934
+ trimCache();
4935
+ if (!networkEnabled || window.expiresAtMs <= atMs) return;
4936
+ if (pending.size >= MAX_PENDING_NOTIFIES && !pending.has(key)) {
4937
+ for (const oldest of pending.keys()) {
4938
+ if (oldest !== sendingKey) {
4939
+ pending.delete(oldest);
4940
+ break;
4941
+ }
4942
+ }
4943
+ }
4944
+ pending.set(key, { executionKey: key, ...window });
4945
+ kickNotify();
4946
+ };
4947
+ const peekSessions = () => {
4948
+ if (sessionsDirty) rebuildSessionSnapshot();
4949
+ else {
4950
+ const atMs = nowMs();
4951
+ for (const session of sessionSnapshot.values()) {
4952
+ if (session.expiresAtMs <= atMs) {
4953
+ rebuildSessionSnapshot();
4954
+ break;
4955
+ }
4956
+ }
4957
+ }
4958
+ return sessionSnapshot;
4959
+ };
4960
+ const consumeSession = (executionKeyValue, sessionId) => {
4961
+ const atMs = nowMs();
4962
+ for (const session of sessionsById.values()) {
4963
+ if (session.executionKey !== executionKeyValue) continue;
4964
+ if (sessionId !== void 0 && session.sessionId !== sessionId) continue;
4965
+ if (!sessionHasRoom(session, atMs)) continue;
4966
+ session.admitted += 1;
4967
+ markSessionsDirty();
4968
+ return sessionView(session);
4969
+ }
4970
+ return void 0;
4971
+ };
4972
+ const observeType = (executionKeyValue) => {
4973
+ rememberCatalog(executionKeyValue, nowMs());
4974
+ };
4975
+ const enqueueRecording = (payload) => {
4976
+ if (closed || closing) return;
4977
+ recordings.push(payload);
4978
+ kickRecordings();
4979
+ };
4980
+ if (networkEnabled) {
4981
+ const interval = options.pollIntervalMs ?? DEFAULT_POLL_INTERVAL_MS;
4982
+ const jitterMax = Math.max(0, options.pollJitterMs ?? MAX_POLL_JITTER_MS);
4983
+ const delay = interval + Math.floor(Math.random() * jitterMax);
4984
+ pollStartTimer = setTimeout(() => {
4985
+ pollStartTimer = void 0;
4986
+ if (closed || closing) return;
4987
+ void runSyncOnce(pollSignal());
4988
+ pollTimer = setInterval(() => {
4989
+ if (closed || closing) return;
4990
+ void runSyncOnce(pollSignal());
4991
+ }, interval);
4992
+ pollTimer.unref?.();
4993
+ }, delay);
4994
+ pollStartTimer.unref?.();
4995
+ }
4996
+ const stopTimers = () => {
4997
+ if (pollStartTimer) {
4998
+ clearTimeout(pollStartTimer);
4999
+ pollStartTimer = void 0;
5000
+ }
5001
+ if (pollTimer) {
5002
+ clearInterval(pollTimer);
5003
+ pollTimer = void 0;
5004
+ }
5005
+ };
5006
+ return {
5007
+ peek,
5008
+ activate,
5009
+ peekSessions,
5010
+ consumeSession,
5011
+ observeType,
5012
+ enqueueRecording,
5013
+ getStats: () => ({
5014
+ adaptiveNotifyFailures: notifyFailures,
5015
+ adaptiveRefreshFailures: refreshFailures,
5016
+ lastAdaptiveFailureKind: lastFailureKind
5017
+ }),
5018
+ flush: async (timeoutMs = 2e3) => {
5019
+ if (!networkEnabled || closed || closing) return;
5020
+ const flushAbort = new AbortController();
5021
+ const onAbort = () => interruptWork();
5022
+ flushAbort.signal.addEventListener("abort", onAbort, { once: true });
5023
+ const timer = setTimeout(() => flushAbort.abort(), Math.max(0, timeoutMs));
5024
+ try {
5025
+ await runSyncOnce(flushAbort.signal);
5026
+ if (!flushAbort.signal.aborted) await drainNotifies(flushAbort.signal);
5027
+ await joinUntil(recordingPump, flushAbort.signal);
5028
+ if (!flushAbort.signal.aborted) await drainRecordings(flushAbort.signal);
5029
+ } finally {
5030
+ clearTimeout(timer);
5031
+ flushAbort.signal.removeEventListener("abort", onAbort);
5032
+ }
5033
+ },
5034
+ close: async () => {
5035
+ if (closed || closing) return;
5036
+ closing = true;
5037
+ stopTimers();
5038
+ const deadline = new AbortController();
5039
+ const timer = setTimeout(() => {
5040
+ deadline.abort();
5041
+ interruptWork();
5042
+ }, 2e3);
5043
+ try {
5044
+ if (networkEnabled) await runSyncOnce(deadline.signal);
5045
+ if (!deadline.signal.aborted) await drainNotifies(deadline.signal);
5046
+ await joinUntil(recordingPump, deadline.signal);
5047
+ if (!deadline.signal.aborted) await drainRecordings(deadline.signal);
5048
+ } finally {
5049
+ clearTimeout(timer);
5050
+ closed = true;
5051
+ interruptWork();
5052
+ pending.clear();
5053
+ }
5054
+ }
5055
+ };
5056
+ };
5057
+
5058
+ // src/execution-recorder/bind-adaptive-recorder.ts
5059
+ var bindAdaptiveRecorder = (input) => {
5060
+ const options = input.executionRecorder;
5061
+ const mode = sanitizeRecorderMode(options?.mode);
5062
+ const activation = resolveClientActivation({
5063
+ enabled: input.enabled,
5064
+ dsn: input.dsn,
5065
+ projectApiKey: input.projectApiKey,
5066
+ apiUrl: input.apiUrl,
5067
+ release: input.release
5068
+ });
5069
+ const coordinator = input.recorderEnabled && activation.enabled ? createExecutionRecordingCoordinator({
5070
+ environment: input.environment ?? "",
5071
+ ingestToken: activation.ingestToken,
5072
+ activateUrl: resolveEndpointUrls2(activation.apiUrl).executionRecordingActivateUrl,
5073
+ syncUrl: resolveEndpointUrls2(activation.apiUrl).executionRecordingSyncUrl,
5074
+ recordingsUrl: resolveEndpointUrls2(activation.apiUrl).executionRecordingRecordingsUrl,
5075
+ sdkName: input.sdkName,
5076
+ sdkVersion: input.sdkVersion,
5077
+ release: activation.release,
5078
+ recorderOptions: options,
5079
+ scrubPII: input.scrubPII,
5080
+ mode,
5081
+ fetch: input.fetch
5082
+ }) : void 0;
5083
+ const runtime = createExecutionRecorder(
5084
+ { ...options, enabled: input.recorderEnabled },
5085
+ coordinator ? {
5086
+ policySnapshot: coordinator.peek,
5087
+ onQualifyingFailure: mode === "adaptive" ? coordinator.activate : void 0,
5088
+ getStats: coordinator.getStats,
5089
+ sessionCaptureSnapshot: coordinator.peekSessions,
5090
+ consumeSession: coordinator.consumeSession,
5091
+ observeExecutionType: coordinator.observeType,
5092
+ onSessionRecording: coordinator.enqueueRecording
5093
+ } : void 0
5094
+ );
5095
+ return { runtime, policy: coordinator };
5096
+ };
5097
+
4001
5098
  // src/install-global-handlers.ts
4002
5099
  var RASPUTIN_PROCESS_LISTENER = Symbol.for("rasputin.process.listener.v1");
4003
5100
  var unhandledRejectionMode = () => {
@@ -4136,7 +5233,7 @@ var installGlobalHandlers = (client, options = {}) => {
4136
5233
 
4137
5234
  // src/sdk-meta.ts
4138
5235
  var SDK_NAME = "@rasputin-ai/node";
4139
- var SDK_VERSION = "0.10.2";
5236
+ var SDK_VERSION = "0.11.1";
4140
5237
 
4141
5238
  // src/rasputin-init.ts
4142
5239
  var publicExecution = (runtime) => ({
@@ -4152,7 +5249,7 @@ var publicExecution = (runtime) => ({
4152
5249
  getStats: runtime.getStats
4153
5250
  });
4154
5251
  var withExecution = (client, runtime, installRuntime, manifest, uninstallHandlers = () => {
4155
- }) => {
5252
+ }, policy) => {
4156
5253
  const uninstallRuntime = installRuntime ? installAutomaticExecutionRuntime(runtime) : () => {
4157
5254
  };
4158
5255
  const manifestUpload = scheduleInstrumentationManifestUpload(manifest);
@@ -4171,9 +5268,11 @@ var withExecution = (client, runtime, installRuntime, manifest, uninstallHandler
4171
5268
  const startedAt = Date.now();
4172
5269
  await client.flush(timeoutMs);
4173
5270
  if (timeoutMs === void 0) {
5271
+ await policy?.flush();
4174
5272
  await manifestUpload.wait();
4175
5273
  return;
4176
5274
  }
5275
+ await policy?.flush(Math.max(0, timeoutMs - (Date.now() - startedAt)));
4177
5276
  await manifestUpload.wait(Math.max(0, timeoutMs - (Date.now() - startedAt)));
4178
5277
  },
4179
5278
  close: async () => {
@@ -4181,6 +5280,7 @@ var withExecution = (client, runtime, installRuntime, manifest, uninstallHandler
4181
5280
  uninstallRuntime();
4182
5281
  manifestUpload.disconnect();
4183
5282
  const startedAt = Date.now();
5283
+ await policy?.close();
4184
5284
  await client.close();
4185
5285
  await manifestUpload.wait(Math.max(0, 2e3 - (Date.now() - startedAt)));
4186
5286
  }
@@ -4190,15 +5290,24 @@ var RasputinInit = (options) => {
4190
5290
  try {
4191
5291
  const enabled = isClientEnabled(options);
4192
5292
  const recorderEnabled = enabled && options.executionRecorder?.enabled !== false;
4193
- const runtime = createExecutionRecorder({
4194
- ...options.executionRecorder,
4195
- enabled: recorderEnabled
5293
+ const { runtime, policy } = bindAdaptiveRecorder({
5294
+ executionRecorder: options.executionRecorder,
5295
+ recorderEnabled,
5296
+ dsn: options.dsn,
5297
+ projectApiKey: options.projectApiKey,
5298
+ apiUrl: options.apiUrl,
5299
+ release: options.release,
5300
+ environment: options.environment,
5301
+ enabled: options.enabled,
5302
+ sdkName: SDK_NAME,
5303
+ sdkVersion: SDK_VERSION,
5304
+ scrubPII: options.scrubPII
4196
5305
  });
4197
5306
  const client = createClient(options, {
4198
5307
  sdkVersion: SDK_VERSION,
4199
5308
  sdkName: SDK_NAME,
4200
5309
  installTransportSignalHandlers: options.installTransportSignalHandlers,
4201
- redactKeys: copyRedactKeys(options.executionRecorder?.redactKeys),
5310
+ redactKeys: copyRedactKeys2(options.executionRecorder?.redactKeys),
4202
5311
  resolveObservation: (observation) => runtime.getErrorState(observation)
4203
5312
  });
4204
5313
  if (enabled) {
@@ -4221,7 +5330,8 @@ var RasputinInit = (options) => {
4221
5330
  sourceRoots: options.sourceRoots,
4222
5331
  logSuccess: options.logSuccess
4223
5332
  },
4224
- () => uninstallHandlers()
5333
+ () => uninstallHandlers(),
5334
+ policy
4225
5335
  );
4226
5336
  if (enabled && options.installGlobalHandlers !== false) {
4227
5337
  uninstallHandlers = installGlobalHandlers(wrappedClient);