@rasputin-ai/node 0.10.1 → 0.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (33) hide show
  1. package/dist/auto-instrumentation/schedule-instrumentation-manifest-upload.d.ts +1 -1
  2. package/dist/auto-instrumentation/schedule-instrumentation-manifest-upload.d.ts.map +1 -1
  3. package/dist/execution-recorder/adaptive-recording-options.d.ts +4 -0
  4. package/dist/execution-recorder/adaptive-recording-options.d.ts.map +1 -0
  5. package/dist/execution-recorder/adaptive-recording-policy.d.ts +10 -0
  6. package/dist/execution-recorder/adaptive-recording-policy.d.ts.map +1 -0
  7. package/dist/execution-recorder/bind-adaptive-recorder.d.ts +21 -0
  8. package/dist/execution-recorder/bind-adaptive-recorder.d.ts.map +1 -0
  9. package/dist/execution-recorder/execution-identity.d.ts +9 -0
  10. package/dist/execution-recorder/execution-identity.d.ts.map +1 -0
  11. package/dist/execution-recorder/execution-journal.d.ts +4 -2
  12. package/dist/execution-recorder/execution-journal.d.ts.map +1 -1
  13. package/dist/execution-recorder/execution-recorder-hooks.d.ts +39 -0
  14. package/dist/execution-recorder/execution-recorder-hooks.d.ts.map +1 -0
  15. package/dist/execution-recorder/execution-recorder-types.d.ts +32 -1
  16. package/dist/execution-recorder/execution-recorder-types.d.ts.map +1 -1
  17. package/dist/execution-recorder/execution-recorder.d.ts +2 -1
  18. package/dist/execution-recorder/execution-recorder.d.ts.map +1 -1
  19. package/dist/execution-recorder/execution-recording-sync.d.ts +30 -0
  20. package/dist/execution-recorder/execution-recording-sync.d.ts.map +1 -0
  21. package/dist/execution-recorder/session-freeze-overrides.d.ts +37 -0
  22. package/dist/execution-recorder/session-freeze-overrides.d.ts.map +1 -0
  23. package/dist/execution-recorder/value-freeze.d.ts +1 -0
  24. package/dist/execution-recorder/value-freeze.d.ts.map +1 -1
  25. package/dist/index.js +1128 -54
  26. package/dist/instrument/bun.js +1 -1
  27. package/dist/instrument/node.js +1 -1
  28. package/dist/internal.d.ts +2 -0
  29. package/dist/internal.d.ts.map +1 -1
  30. package/dist/internal.js +1108 -46
  31. package/dist/rasputin-init.d.ts.map +1 -1
  32. package/dist/sdk-meta.d.ts +1 -1
  33. package/package.json +2 -2
package/dist/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) {
@@ -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,119 @@ 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.min(
2867
+ maxCapturedCallsPerFunction,
2868
+ Math.max(1, Math.round(session.maxCapturedCallsPerFunction))
2869
+ );
2870
+ }
2871
+ if (session.maxExecutionHoldMs !== void 0) {
2872
+ const requestedNs = BigInt(Math.max(1, Math.round(session.maxExecutionHoldMs))) * 1000000n;
2873
+ recording.sessionHoldNs = requestedNs < maxExecutionHoldNs ? requestedNs : maxExecutionHoldNs;
2874
+ }
2875
+ if (wasLight) {
2876
+ stats.adaptiveLightExecutions = Math.max(0, stats.adaptiveLightExecutions - 1);
2877
+ stats.adaptiveFullExecutions++;
2878
+ }
2879
+ };
2880
+ const skipCapture = (store, plan) => store.suppressCapture || plan.excluded || Boolean(store.recording.sessionExcludes?.(plan.definition));
2881
+ const capturedCallLimitFor = (recording) => recording.sessionMaxCapturedCalls ?? maxCapturedCallsPerFunction;
2882
+ const tryAdmitLiveSession = (recording) => {
2883
+ if (recording.retainSuccess || recording.finished) return;
2884
+ const key = executionTypeKey(recording.execution);
2885
+ if (!key) return;
2886
+ const peek = hooks.sessionCaptureSnapshot?.().get(key);
2887
+ if (!peek || peek.expiresAtMs <= recording.startedAtMs) return;
2888
+ const live = hooks.consumeSession?.(key, peek.sessionId);
2889
+ if (live) admitSession(recording, live);
2890
+ };
2891
+ const tryAdmitFromStartSnapshot = (recording) => {
2892
+ if (recording.retainSuccess || recording.finished) return;
2893
+ const key = executionTypeKey(recording.execution);
2894
+ if (!key) return;
2895
+ const peek = recording.sessionCaptureSnapshot.get(key);
2896
+ if (!peek || peek.expiresAtMs <= recording.startedAtMs) return;
2897
+ const live = hooks.consumeSession?.(key, peek.sessionId);
2898
+ if (live) admitSession(recording, live);
2899
+ };
2900
+ const completeIdentityFromSnapshot = (recording) => {
2901
+ if (recording.identityResolved || recording.finished) return;
2902
+ const key = executionTypeKey(recording.execution);
2903
+ if (!key) return;
2904
+ recording.identityResolved = true;
2905
+ tryAdmitFromStartSnapshot(recording);
2906
+ if (recording.captureValues || recorderMode !== "adaptive") return;
2907
+ if (keyIsActive(recording.policySnapshot, key, recording.startedAtMs)) {
2908
+ recording.captureValues = true;
2909
+ stats.adaptiveLightExecutions = Math.max(0, stats.adaptiveLightExecutions - 1);
2910
+ stats.adaptiveFullExecutions++;
2911
+ }
2912
+ };
2913
+ const maybeActivateAdaptive = (recording) => {
2914
+ if (recorderMode !== "adaptive" || recording.adaptiveActivated) return;
2915
+ if (isHttpClientErrorStatus(recording.execution.request?.status)) return;
2916
+ const key = executionTypeKey(recording.execution);
2917
+ if (!key) return;
2918
+ const atMs = nowMs();
2919
+ const snapshot = policySnapshotFor();
2920
+ if (keyIsActive(snapshot, key, atMs)) return;
2921
+ recording.adaptiveActivated = true;
2922
+ const window = { activatedAtMs: atMs, expiresAtMs: atMs + fullCaptureDurationMs };
2923
+ stats.adaptiveActivations++;
2924
+ if (hooks.onQualifyingFailure) {
2925
+ hooks.onQualifyingFailure(recording.execution, window);
2926
+ return;
2927
+ }
2928
+ if (!keyIsActive(localActivations, key, atMs)) {
2929
+ localActivations.set(key, window.expiresAtMs);
2930
+ }
2931
+ };
2766
2932
  const storePlan = (plan) => {
2767
2933
  plansByRuntimeId[plan.runtimePlanId] = plan;
2768
2934
  return plan;
@@ -2800,8 +2966,10 @@ var createExecutionRecorder = (options) => {
2800
2966
  };
2801
2967
  const eventsHaveOmittedValues = (events) => {
2802
2968
  for (const event of events) {
2803
- if (event.type === "function_enter" && (event.args ?? []).some((arg) => rasputinTagKind(arg) === "omitted")) {
2804
- return true;
2969
+ if (event.type === "function_enter") {
2970
+ if (event.argsOmitted || (event.args ?? []).some((arg) => rasputinTagKind(arg) === "omitted")) {
2971
+ return true;
2972
+ }
2805
2973
  }
2806
2974
  if (event.type === "function_exit" && rasputinTagKind(event.returnValue) === "omitted") {
2807
2975
  return true;
@@ -2847,7 +3015,7 @@ var createExecutionRecorder = (options) => {
2847
3015
  return {
2848
3016
  source,
2849
3017
  functionBoundaries: droppedEvents ? "partial" : "full",
2850
- functionValues: eventsHaveOmittedValues(events) ? "selective" : "full",
3018
+ functionValues: recording.captureValues ? eventsHaveOmittedValues(events) ? "selective" : "full" : "none",
2851
3019
  timings: droppedEvents ? "partial" : "full"
2852
3020
  };
2853
3021
  };
@@ -2865,7 +3033,7 @@ var createExecutionRecorder = (options) => {
2865
3033
  } else {
2866
3034
  if (recording.journal) {
2867
3035
  const materialized = recording.journal.materialize(plansByRuntimeId, recording.startedAtNs);
2868
- events = encodeEventValues(materialized.events);
3036
+ events = encodeEventValues(recording, materialized.events);
2869
3037
  if (recording.lateCapturedCallIds && recording.lateCapturedCallIds.size > 0) {
2870
3038
  events = events.map(
2871
3039
  (event) => event.type === "function_enter" && recording.lateCapturedCallIds?.has(event.callId) ? { ...event, capturedAt: "throw" } : event
@@ -3061,7 +3229,7 @@ var createExecutionRecorder = (options) => {
3061
3229
  liveRecordings.splice(index, 1);
3062
3230
  continue;
3063
3231
  }
3064
- if (nowNs - recording.startedAtNs < maxExecutionHoldNs) continue;
3232
+ if (nowNs - recording.startedAtNs < (recording.sessionHoldNs ?? maxExecutionHoldNs)) continue;
3065
3233
  try {
3066
3234
  expireLongLivedRecording(recording, nowNs);
3067
3235
  } catch {
@@ -3101,6 +3269,7 @@ var createExecutionRecorder = (options) => {
3101
3269
  const observeFailure = (recording, provenance) => {
3102
3270
  if (!recording.evidenceDiscarded) {
3103
3271
  retainFailure(recording);
3272
+ maybeActivateAdaptive(recording);
3104
3273
  }
3105
3274
  return mintOccurrence(recording, provenance);
3106
3275
  };
@@ -3168,7 +3337,7 @@ var createExecutionRecorder = (options) => {
3168
3337
  // snapshot without the exception itself would not be useful for investigation.
3169
3338
  value: (() => {
3170
3339
  try {
3171
- return freezeAndCount(error).value;
3340
+ return freezeAndCount(recording, error).value;
3172
3341
  } catch {
3173
3342
  return { __rasputin_type: "unserializable" };
3174
3343
  }
@@ -3187,7 +3356,7 @@ var createExecutionRecorder = (options) => {
3187
3356
  }
3188
3357
  const callId = ++recording.nextCallId;
3189
3358
  const capturedError = serializedError(recording, error, callId);
3190
- const recordedArgs = capturedArgs ?? mapArrayLike(args, (argument) => captureValue(recording, argument));
3359
+ const recordedArgs = capturedArgs ?? (recording.captureValues ? mapArrayLike(args, (argument) => captureValue(recording, argument)) : ARGS_OMITTED);
3191
3360
  const endedAtNs = process.hrtime.bigint();
3192
3361
  const droppedBefore = recording.journal.dropped;
3193
3362
  const retained = recording.journal.forceCompletedCall(
@@ -3245,6 +3414,23 @@ var createExecutionRecorder = (options) => {
3245
3414
  return void 0;
3246
3415
  }
3247
3416
  };
3417
+ const enqueueSessionRecording = (recording) => {
3418
+ if (recording.sessionRecordingEnqueued || !recording.sessionId) {
3419
+ return;
3420
+ }
3421
+ recording.sessionRecordingEnqueued = true;
3422
+ try {
3423
+ hooks.onSessionRecording?.({
3424
+ sessionId: recording.sessionId,
3425
+ executionId: recording.executionId,
3426
+ outcome: recording.hasError || recording.runFailed ? "error" : "success",
3427
+ runtimeState: stateFrom(recording),
3428
+ redactKeys: recording.sessionRedactKeys,
3429
+ scrubPii: recording.sessionScrubPii
3430
+ });
3431
+ } catch {
3432
+ }
3433
+ };
3248
3434
  const settleInFlight = (recording) => {
3249
3435
  if (recording.inFlightCalls > 0) recording.inFlightCalls--;
3250
3436
  releaseWhenIdle(recording);
@@ -3253,6 +3439,9 @@ var createExecutionRecorder = (options) => {
3253
3439
  try {
3254
3440
  if (!recording.finished || recording.inFlightCalls > 0) return;
3255
3441
  memoryBudget.release(recording.memory);
3442
+ if (recording.retainSuccess && !recording.sessionRecordingEnqueued) {
3443
+ enqueueSessionRecording(recording);
3444
+ }
3256
3445
  if (!recording.hasError && !recording.retainedForError) {
3257
3446
  discardSuccessfulEvidence(recording);
3258
3447
  return;
@@ -3272,10 +3461,13 @@ var createExecutionRecorder = (options) => {
3272
3461
  stats.activeExecutions = Math.max(0, stats.activeExecutions - 1);
3273
3462
  if (recording.runFailed && !recording.hasError) {
3274
3463
  retainFailure(recording);
3464
+ maybeActivateAdaptive(recording);
3275
3465
  }
3276
- if (!recording.hasError) {
3466
+ if (!recording.hasError && !recording.retainSuccess) {
3277
3467
  stats.successfulExecutionsDiscarded++;
3278
3468
  }
3469
+ const finishedKey = executionTypeKey(recording.execution);
3470
+ if (finishedKey) hooks.observeExecutionType?.(finishedKey);
3279
3471
  recording.finishedAtNs = process.hrtime.bigint();
3280
3472
  addRecorderTime(recording, recording.finishedAtNs - recorderStartedAtNs);
3281
3473
  recordInlineTiming(recording);
@@ -3296,16 +3488,28 @@ var createExecutionRecorder = (options) => {
3296
3488
  try {
3297
3489
  const recorderStartedAtNs = process.hrtime.bigint();
3298
3490
  sweepLongLivedExecutions(recorderStartedAtNs);
3491
+ const startedAtMs = nowMs();
3492
+ const livePolicy = policySnapshotFor();
3493
+ const execution = {
3494
+ ...metadata,
3495
+ ...metadata.request ? { request: { ...metadata.request } } : {}
3496
+ };
3497
+ const identityComplete = executionTypeKey(execution) !== void 0;
3498
+ const captureValues = captureValuesFor(execution, livePolicy, startedAtMs);
3499
+ const policySnapshot = recorderMode === "adaptive" && !identityComplete ? new Map(livePolicy) : EMPTY_POLICY_SNAPSHOT;
3500
+ const liveSessions = hooks.sessionCaptureSnapshot?.() ?? EMPTY_SESSION_SNAPSHOT;
3501
+ const sessionCaptureSnapshot = identityComplete ? EMPTY_SESSION_SNAPSHOT : new Map(liveSessions);
3502
+ if (recorderMode === "adaptive") {
3503
+ if (captureValues) stats.adaptiveFullExecutions++;
3504
+ else stats.adaptiveLightExecutions++;
3505
+ }
3299
3506
  const recording = {
3300
3507
  executionId: `${Date.now()}-${process.pid}-${++executionCounter}`,
3301
3508
  storageGeneration: ++storageClock,
3302
- startedAtMs: Date.now(),
3509
+ startedAtMs,
3303
3510
  startedAtNs: recorderStartedAtNs,
3304
3511
  inlineRecorderTimeNs: 0n,
3305
- execution: {
3306
- ...metadata,
3307
- ...metadata.request ? { request: { ...metadata.request } } : {}
3308
- },
3512
+ execution,
3309
3513
  journal: void 0,
3310
3514
  capturedErrors: /* @__PURE__ */ new WeakMap(),
3311
3515
  nextCallId: 0,
@@ -3315,8 +3519,13 @@ var createExecutionRecorder = (options) => {
3315
3519
  memory: memoryBudget.startExecution(),
3316
3520
  partialSnapshotCounted: false,
3317
3521
  sawAutomatic: false,
3318
- sawManual: false
3522
+ sawManual: false,
3523
+ captureValues,
3524
+ policySnapshot,
3525
+ identityResolved: identityComplete,
3526
+ sessionCaptureSnapshot
3319
3527
  };
3528
+ if (identityComplete) tryAdmitLiveSession(recording);
3320
3529
  stats.activeExecutions++;
3321
3530
  stats.peakActiveExecutions = Math.max(stats.peakActiveExecutions, stats.activeExecutions);
3322
3531
  liveRecordings.push(recording);
@@ -3363,7 +3572,14 @@ var createExecutionRecorder = (options) => {
3363
3572
  return void 0;
3364
3573
  }
3365
3574
  },
3366
- finish: (finishMetadata) => finish(store, finishMetadata)
3575
+ finish: (finishMetadata) => finish(store, finishMetadata),
3576
+ mergeMetadata: (nextMetadata) => {
3577
+ try {
3578
+ mergeExecutionMetadata(recording.execution, nextMetadata);
3579
+ completeIdentityFromSnapshot(recording);
3580
+ } catch {
3581
+ }
3582
+ }
3367
3583
  };
3368
3584
  } catch {
3369
3585
  return noOpExecution.createScope(metadata);
@@ -3413,7 +3629,7 @@ var createExecutionRecorder = (options) => {
3413
3629
  }
3414
3630
  stats.functionCallsObserved++;
3415
3631
  const recorderStartedAtNs = process.hrtime.bigint();
3416
- if (store.suppressCapture || plan.excluded) {
3632
+ if (skipCapture(store, plan)) {
3417
3633
  stats.functionCallsExcluded++;
3418
3634
  return runStore({ ...store, suppressCapture: true }, function __rasputinHandleRun__5() {
3419
3635
  addRecorderTime(store.recording, process.hrtime.bigint() - recorderStartedAtNs);
@@ -3430,7 +3646,7 @@ var createExecutionRecorder = (options) => {
3430
3646
  if (group.observedCalls === 1) journal?.notePlan(plan.runtimePlanId);
3431
3647
  } catch {
3432
3648
  }
3433
- if (group.observedCalls > maxCapturedCallsPerFunction) {
3649
+ if (group.observedCalls > capturedCallLimitFor(recording)) {
3434
3650
  const startedAtNs2 = process.hrtime.bigint();
3435
3651
  try {
3436
3652
  const result = runStore(store, function __rasputinHandleRun__5() {
@@ -3493,7 +3709,7 @@ var createExecutionRecorder = (options) => {
3493
3709
  }
3494
3710
  const callId = ++recording.nextCallId;
3495
3711
  const enterTimestampNs = process.hrtime.bigint() - recording.startedAtNs;
3496
- const capturedArgs = omitCallValues ? mapArrayLike(args, () => rasputinOmitted()) : mapArrayLike(args, (argument) => captureValue(recording, argument));
3712
+ const capturedArgs = enterPayload(recording, omitCallValues, args);
3497
3713
  try {
3498
3714
  journal.startCall(plan.runtimePlanId, callId, parentCallId, enterTimestampNs, capturedArgs);
3499
3715
  } catch {
@@ -3519,7 +3735,7 @@ var createExecutionRecorder = (options) => {
3519
3735
  (value) => {
3520
3736
  if (recording.journal) {
3521
3737
  const endedAtNs = process.hrtime.bigint();
3522
- const returnValue = omitCallValues ? rasputinOmitted() : captureValue(recording, value);
3738
+ const returnValue = exitPayload(recording, omitCallValues, value);
3523
3739
  recording.journal.finishCall(
3524
3740
  KIND_EXIT,
3525
3741
  callId,
@@ -3576,7 +3792,7 @@ var createExecutionRecorder = (options) => {
3576
3792
  try {
3577
3793
  if (this.status !== "failed") {
3578
3794
  this.status = "left";
3579
- this.pendingReturn = value;
3795
+ if (this.recording.captureValues) this.pendingReturn = value;
3580
3796
  }
3581
3797
  return value;
3582
3798
  } catch {
@@ -3592,19 +3808,21 @@ var createExecutionRecorder = (options) => {
3592
3808
  captureCompletedThrow(
3593
3809
  this.recording,
3594
3810
  this.plan,
3595
- liveArgs ?? this.args,
3811
+ this.recording.captureValues ? liveArgs ?? this.args : EMPTY_ARGS,
3596
3812
  this.parentCallId,
3597
3813
  this.startedAtNs,
3598
- error
3814
+ error,
3815
+ this.recording.captureValues ? void 0 : ARGS_OMITTED
3599
3816
  );
3600
3817
  } else if (this.mode === "dropped" && this.captureDroppedThrow && this.plan) {
3601
3818
  captureCompletedThrow(
3602
3819
  this.recording,
3603
3820
  this.plan,
3604
- this.args,
3821
+ this.recording.captureValues ? this.args : EMPTY_ARGS,
3605
3822
  this.parentCallId,
3606
3823
  this.startedAtNs,
3607
- error
3824
+ error,
3825
+ this.recording.captureValues ? void 0 : ARGS_OMITTED
3608
3826
  );
3609
3827
  }
3610
3828
  } catch {
@@ -3694,7 +3912,7 @@ var createExecutionRecorder = (options) => {
3694
3912
  const writeCapturedExit = (frame, value) => {
3695
3913
  if (!frame.recording.journal) return;
3696
3914
  const endedAtNs = process.hrtime.bigint();
3697
- const returnValue = frame.omitCallValues ? rasputinOmitted() : captureValue(frame.recording, value);
3915
+ const returnValue = exitPayload(frame.recording, frame.omitCallValues, value);
3698
3916
  frame.recording.journal.finishCall(
3699
3917
  KIND_EXIT,
3700
3918
  frame.callId,
@@ -3764,7 +3982,7 @@ var createExecutionRecorder = (options) => {
3764
3982
  const recording = store.recording;
3765
3983
  const omitCallValues = omitValues === true || plan.omitCallValues;
3766
3984
  const parentCallId = store.currentCallId;
3767
- if (store.suppressCapture || plan.excluded) {
3985
+ if (skipCapture(store, plan)) {
3768
3986
  stats.functionCallsExcluded++;
3769
3987
  const excludedStore = { ...store, suppressCapture: true };
3770
3988
  const frame = new CallFrame(
@@ -3794,13 +4012,14 @@ var createExecutionRecorder = (options) => {
3794
4012
  }
3795
4013
  const startedAtNs = process.hrtime.bigint();
3796
4014
  const parentStore = store;
3797
- if (group.observedCalls > maxCapturedCallsPerFunction) {
4015
+ const retainedArgs = recording.captureValues ? args : EMPTY_ARGS;
4016
+ if (group.observedCalls > capturedCallLimitFor(recording)) {
3798
4017
  return activateUncaptured(
3799
4018
  "suppressed",
3800
4019
  recording,
3801
4020
  parentStore,
3802
4021
  plan,
3803
- args,
4022
+ retainedArgs,
3804
4023
  omitCallValues,
3805
4024
  parentCallId,
3806
4025
  startedAtNs,
@@ -3815,7 +4034,7 @@ var createExecutionRecorder = (options) => {
3815
4034
  recording,
3816
4035
  parentStore,
3817
4036
  plan,
3818
- args,
4037
+ retainedArgs,
3819
4038
  omitCallValues,
3820
4039
  parentCallId,
3821
4040
  startedAtNs,
@@ -3829,7 +4048,7 @@ var createExecutionRecorder = (options) => {
3829
4048
  recording,
3830
4049
  parentStore,
3831
4050
  plan,
3832
- args,
4051
+ retainedArgs,
3833
4052
  omitCallValues,
3834
4053
  parentCallId,
3835
4054
  startedAtNs,
@@ -3843,7 +4062,7 @@ var createExecutionRecorder = (options) => {
3843
4062
  recording,
3844
4063
  parentStore,
3845
4064
  plan,
3846
- args,
4065
+ retainedArgs,
3847
4066
  omitCallValues,
3848
4067
  parentCallId,
3849
4068
  startedAtNs,
@@ -3853,7 +4072,7 @@ var createExecutionRecorder = (options) => {
3853
4072
  }
3854
4073
  const callId = ++recording.nextCallId;
3855
4074
  const enterTimestampNs = process.hrtime.bigint() - recording.startedAtNs;
3856
- const capturedArgs = omitCallValues ? mapArrayLike(args, () => rasputinOmitted()) : mapArrayLike(args, (argument) => captureValue(recording, argument));
4075
+ const capturedArgs = enterPayload(recording, omitCallValues, args);
3857
4076
  try {
3858
4077
  journal.startCall(plan.runtimePlanId, callId, parentCallId, enterTimestampNs, capturedArgs);
3859
4078
  } catch {
@@ -3863,7 +4082,7 @@ var createExecutionRecorder = (options) => {
3863
4082
  recording,
3864
4083
  parentStore,
3865
4084
  plan,
3866
- args,
4085
+ retainedArgs,
3867
4086
  omitCallValues,
3868
4087
  parentCallId,
3869
4088
  startedAtNs,
@@ -3878,7 +4097,7 @@ var createExecutionRecorder = (options) => {
3878
4097
  parentStore,
3879
4098
  callStore,
3880
4099
  plan,
3881
- args,
4100
+ retainedArgs,
3882
4101
  omitCallValues,
3883
4102
  parentCallId,
3884
4103
  startedAtNs,
@@ -3954,6 +4173,10 @@ var createExecutionRecorder = (options) => {
3954
4173
  ...stats,
3955
4174
  ...memoryBudget.getStats(),
3956
4175
  ...journalPool.stats(),
4176
+ adaptiveNotifyFailures: 0,
4177
+ adaptiveRefreshFailures: 0,
4178
+ lastAdaptiveFailureKind: null,
4179
+ ...hooks.getStats?.(),
3957
4180
  ...phases ? {
3958
4181
  phaseAlsNs: Number(phases.alsNs),
3959
4182
  phaseMaterializeNs: Number(phases.materializeNs)
@@ -3998,6 +4221,844 @@ var installAutomaticExecutionRuntime = (execution) => {
3998
4221
  };
3999
4222
  };
4000
4223
 
4224
+ // src/execution-recorder/bind-adaptive-recorder.ts
4225
+ import {
4226
+ resolveClientActivation,
4227
+ resolveEndpointUrls as resolveEndpointUrls2
4228
+ } from "@rasputin-ai/core";
4229
+
4230
+ // src/execution-recorder/execution-recording-sync.ts
4231
+ import {
4232
+ copyRedactKeys,
4233
+ defaultIngestFetch,
4234
+ encodeJsonRequestBodyAsync,
4235
+ MAX_REDACT_KEYS
4236
+ } from "@rasputin-ai/core";
4237
+
4238
+ // src/execution-recorder/session-freeze-overrides.ts
4239
+ var BOUNDS = {
4240
+ maxDepth: { min: 1, max: 8 },
4241
+ maxObjectKeys: { min: 1, max: 100 },
4242
+ maxArrayElements: { min: 1, max: 100 },
4243
+ maxStringLength: { min: 32, max: 4e3 },
4244
+ maxSerializedValueBytes: { min: 1024, max: 64 * 1024 }
4245
+ };
4246
+ var MAX_SERIALIZER_CACHE = 32;
4247
+ var isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
4248
+ var optionalFiniteNumber = (value) => typeof value === "number" && Number.isFinite(value) ? value : void 0;
4249
+ var optionalStringList = (value) => {
4250
+ if (!Array.isArray(value)) return void 0;
4251
+ const out = [];
4252
+ for (const item of value) {
4253
+ if (typeof item !== "string" || !item.trim()) continue;
4254
+ out.push(item.trim());
4255
+ }
4256
+ return out.length > 0 ? out : void 0;
4257
+ };
4258
+ var clampAgainstProcess = (requested, processValue, min, max) => {
4259
+ if (requested === void 0 || !Number.isFinite(requested)) return processValue;
4260
+ return Math.min(processValue, Math.min(max, Math.max(min, Math.round(requested))));
4261
+ };
4262
+ var parseSessionSettings = (value) => {
4263
+ if (!isRecord(value)) return void 0;
4264
+ const overrides = {};
4265
+ const maxDepth = optionalFiniteNumber(value.maxDepth);
4266
+ const maxObjectKeys = optionalFiniteNumber(value.maxObjectKeys);
4267
+ const maxArrayElements = optionalFiniteNumber(value.maxArrayElements);
4268
+ const maxStringLength = optionalFiniteNumber(value.maxStringLength);
4269
+ const maxSerializedValueBytes = optionalFiniteNumber(value.maxSerializedValueBytes);
4270
+ const maxCapturedCallsPerFunction = optionalFiniteNumber(value.maxCapturedCallsPerFunction);
4271
+ const maxExecutionHoldMs = optionalFiniteNumber(value.maxExecutionHoldMs);
4272
+ if (maxDepth !== void 0) overrides.maxDepth = maxDepth;
4273
+ if (maxObjectKeys !== void 0) overrides.maxObjectKeys = maxObjectKeys;
4274
+ if (maxArrayElements !== void 0) overrides.maxArrayElements = maxArrayElements;
4275
+ if (maxStringLength !== void 0) overrides.maxStringLength = maxStringLength;
4276
+ if (maxSerializedValueBytes !== void 0)
4277
+ overrides.maxSerializedValueBytes = maxSerializedValueBytes;
4278
+ if (maxCapturedCallsPerFunction !== void 0) {
4279
+ overrides.maxCapturedCallsPerFunction = maxCapturedCallsPerFunction;
4280
+ }
4281
+ if (maxExecutionHoldMs !== void 0) overrides.maxExecutionHoldMs = maxExecutionHoldMs;
4282
+ const excludeSources = optionalStringList(value.excludeSources);
4283
+ const redactKeys = optionalStringList(value.redactKeys);
4284
+ if (excludeSources) overrides.excludeSources = excludeSources;
4285
+ if (redactKeys) overrides.redactKeys = redactKeys;
4286
+ if (typeof value.scrubPII === "boolean") overrides.scrubPII = value.scrubPII;
4287
+ return Object.keys(overrides).length > 0 ? overrides : void 0;
4288
+ };
4289
+ var clampSessionFreezeLimits = (overrides, processLimits) => ({
4290
+ maxDepth: clampAgainstProcess(
4291
+ overrides?.maxDepth,
4292
+ processLimits.maxDepth,
4293
+ BOUNDS.maxDepth.min,
4294
+ BOUNDS.maxDepth.max
4295
+ ),
4296
+ maxObjectKeys: clampAgainstProcess(
4297
+ overrides?.maxObjectKeys,
4298
+ processLimits.maxObjectKeys,
4299
+ BOUNDS.maxObjectKeys.min,
4300
+ BOUNDS.maxObjectKeys.max
4301
+ ),
4302
+ maxArrayElements: clampAgainstProcess(
4303
+ overrides?.maxArrayElements,
4304
+ processLimits.maxArrayElements,
4305
+ BOUNDS.maxArrayElements.min,
4306
+ BOUNDS.maxArrayElements.max
4307
+ ),
4308
+ maxStringLength: clampAgainstProcess(
4309
+ overrides?.maxStringLength,
4310
+ processLimits.maxStringLength,
4311
+ BOUNDS.maxStringLength.min,
4312
+ BOUNDS.maxStringLength.max
4313
+ ),
4314
+ maxSerializedValueBytes: clampAgainstProcess(
4315
+ overrides?.maxSerializedValueBytes,
4316
+ processLimits.maxSerializedValueBytes,
4317
+ BOUNDS.maxSerializedValueBytes.min,
4318
+ BOUNDS.maxSerializedValueBytes.max
4319
+ )
4320
+ });
4321
+ var freezeLimitsFingerprint = (limits) => `${limits.maxDepth}:${limits.maxObjectKeys}:${limits.maxArrayElements}:${limits.maxStringLength}:${limits.maxSerializedValueBytes}`;
4322
+ var serializeSourceExclusions = (exclusions) => {
4323
+ if (!exclusions?.length) return void 0;
4324
+ const out = [];
4325
+ for (const item of exclusions) {
4326
+ if (typeof item === "string" && item.trim()) out.push(item.trim());
4327
+ else if (item instanceof RegExp) out.push(item.toString());
4328
+ }
4329
+ return out.length > 0 ? out : void 0;
4330
+ };
4331
+ var reportedRecorderSettings = (options, scrubPII) => ({
4332
+ maxDepth: options?.maxDepth,
4333
+ maxObjectKeys: options?.maxObjectKeys,
4334
+ maxArrayElements: options?.maxArrayElements,
4335
+ maxStringLength: options?.maxStringLength,
4336
+ maxSerializedValueBytes: options?.maxSerializedValueBytes,
4337
+ maxEventsPerExecution: options?.maxEventsPerExecution,
4338
+ maxCapturedCallsPerFunction: options?.maxCapturedCallsPerFunction,
4339
+ maxActiveMemoryBytes: options?.maxActiveMemoryBytes,
4340
+ maxExecutionHoldMs: options?.maxExecutionHoldMs,
4341
+ maxRetainedErrorRecordings: options?.maxRetainedErrorRecordings,
4342
+ fullCaptureDurationMs: options?.adaptive?.fullCaptureDurationMs,
4343
+ recorder_enabled: options?.enabled !== false,
4344
+ excludeSources: serializeSourceExclusions(options?.excludeSources),
4345
+ redactKeys: options?.redactKeys,
4346
+ scrubPII: scrubPII === true
4347
+ });
4348
+ var createSerializerCache = (options) => {
4349
+ const processLimits = compileFreezeLimits(options ?? {});
4350
+ const processFingerprint = freezeLimitsFingerprint(processLimits);
4351
+ const cache = /* @__PURE__ */ new Map();
4352
+ return {
4353
+ serializerFor: (overrides) => {
4354
+ const clamped = clampSessionFreezeLimits(overrides, processLimits);
4355
+ const fingerprint = freezeLimitsFingerprint(clamped);
4356
+ if (fingerprint === processFingerprint) return void 0;
4357
+ const existing = cache.get(fingerprint);
4358
+ if (existing) {
4359
+ cache.delete(fingerprint);
4360
+ cache.set(fingerprint, existing);
4361
+ return existing;
4362
+ }
4363
+ while (cache.size >= MAX_SERIALIZER_CACHE) {
4364
+ const oldest = cache.keys().next().value;
4365
+ if (oldest === void 0) break;
4366
+ cache.delete(oldest);
4367
+ }
4368
+ const created = createSafeSerializer(clamped);
4369
+ cache.set(fingerprint, created);
4370
+ return created;
4371
+ }
4372
+ };
4373
+ };
4374
+
4375
+ // src/execution-recorder/execution-recording-sync.ts
4376
+ var MAX_CACHE_ENTRIES = 1024;
4377
+ var MAX_PENDING_NOTIFIES = 32;
4378
+ var MAX_PENDING_TYPES = 64;
4379
+ var DEFAULT_POLL_INTERVAL_MS = 1e4;
4380
+ var REQUEST_TIMEOUT_MS = 5e3;
4381
+ var MAX_RETRIES = 5;
4382
+ var MAX_POLL_JITTER_MS = 2e3;
4383
+ var trimmed2 = (value) => typeof value === "string" ? value.trim() : "";
4384
+ var isRecord2 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
4385
+ var unwrapPayload = (body) => {
4386
+ if (!isRecord2(body)) return void 0;
4387
+ if ("payload" in body && isRecord2(body.payload)) return body.payload;
4388
+ return body;
4389
+ };
4390
+ var classifyHttpFailure = (status) => {
4391
+ if (status === 429) return "rate_limited";
4392
+ if (status >= 500) return "server_error";
4393
+ return "non_retryable_http";
4394
+ };
4395
+ var backoffMs = (attempt) => Math.min(3e3, 250 * 2 ** attempt);
4396
+ var createExecutionRecordingCoordinator = (options) => {
4397
+ const environment = trimmed2(options.environment);
4398
+ const nowMs = () => options.nowMs?.() ?? Date.now();
4399
+ const fetchFn = options.fetch ?? defaultIngestFetch();
4400
+ const networkEnabled = environment.length > 0;
4401
+ const instanceId = crypto.randomUUID();
4402
+ const startedAt = /* @__PURE__ */ new Date();
4403
+ const redactKeys = copyRedactKeys(options.recorderOptions?.redactKeys);
4404
+ const scrubPii = options.scrubPII === true;
4405
+ const serializers = createSerializerCache(options.recorderOptions);
4406
+ const cache = /* @__PURE__ */ new Map();
4407
+ const pending = /* @__PURE__ */ new Map();
4408
+ const catalog = /* @__PURE__ */ new Map();
4409
+ const sessionsById = /* @__PURE__ */ new Map();
4410
+ const completedSessionIds = /* @__PURE__ */ new Set();
4411
+ const recordings = [];
4412
+ const capabilities = ["catalog", "manual_sessions", "settings_overrides"];
4413
+ let closed = false;
4414
+ let closing = false;
4415
+ let sessionsDirty = true;
4416
+ let sessionSnapshot = /* @__PURE__ */ new Map();
4417
+ let syncFlight;
4418
+ let pollTimer;
4419
+ let pollStartTimer;
4420
+ let pump;
4421
+ let pumpAgain = false;
4422
+ let sendingKey;
4423
+ let recordingPump;
4424
+ let notifyFailures = 0;
4425
+ let refreshFailures = 0;
4426
+ let lastFailureKind = null;
4427
+ let pollAbort;
4428
+ let notifyAbort;
4429
+ let recordingAbort;
4430
+ let cancelWork = new AbortController();
4431
+ const rememberFailure = (kind) => {
4432
+ lastFailureKind = kind;
4433
+ };
4434
+ const dropExpiredCache = (atMs) => {
4435
+ for (const [key, expiresAt] of cache) {
4436
+ if (expiresAt <= atMs) cache.delete(key);
4437
+ }
4438
+ };
4439
+ const trimCache = () => {
4440
+ const atMs = nowMs();
4441
+ dropExpiredCache(atMs);
4442
+ while (cache.size > MAX_CACHE_ENTRIES) {
4443
+ const oldest = cache.keys().next().value;
4444
+ if (oldest === void 0) break;
4445
+ cache.delete(oldest);
4446
+ }
4447
+ };
4448
+ const peek = () => cache;
4449
+ const sessionView = (session) => ({
4450
+ sessionId: session.sessionId,
4451
+ expiresAtMs: session.expiresAtMs,
4452
+ serializer: session.serializer,
4453
+ redactKeys: session.redactKeys,
4454
+ excludeSources: session.excludeSources,
4455
+ maxCapturedCallsPerFunction: session.maxCapturedCallsPerFunction,
4456
+ maxExecutionHoldMs: session.maxExecutionHoldMs,
4457
+ scrubPII: session.scrubPII
4458
+ });
4459
+ const sessionHasRoom = (session, atMs) => session.admitted < session.requestedCount && session.expiresAtMs > atMs;
4460
+ const rebuildSessionSnapshot = () => {
4461
+ const atMs = nowMs();
4462
+ const map = /* @__PURE__ */ new Map();
4463
+ for (const session of sessionsById.values()) {
4464
+ if (!sessionHasRoom(session, atMs) || map.has(session.executionKey)) continue;
4465
+ map.set(session.executionKey, sessionView(session));
4466
+ }
4467
+ sessionSnapshot = map;
4468
+ sessionsDirty = false;
4469
+ };
4470
+ const markSessionsDirty = () => {
4471
+ sessionsDirty = true;
4472
+ };
4473
+ const notifySignal = () => {
4474
+ if (!notifyAbort || notifyAbort.signal.aborted) notifyAbort = new AbortController();
4475
+ return notifyAbort.signal;
4476
+ };
4477
+ const recordingSignal = () => {
4478
+ if (!recordingAbort || recordingAbort.signal.aborted) recordingAbort = new AbortController();
4479
+ return recordingAbort.signal;
4480
+ };
4481
+ const pollSignal = () => {
4482
+ if (!pollAbort || pollAbort.signal.aborted) pollAbort = new AbortController();
4483
+ return pollAbort.signal;
4484
+ };
4485
+ const wait = (ms, signal) => new Promise((resolve) => {
4486
+ if (signal.aborted) {
4487
+ resolve();
4488
+ return;
4489
+ }
4490
+ const timer = setTimeout(() => {
4491
+ signal.removeEventListener("abort", onAbort);
4492
+ resolve();
4493
+ }, ms);
4494
+ timer.unref?.();
4495
+ const onAbort = () => {
4496
+ clearTimeout(timer);
4497
+ resolve();
4498
+ };
4499
+ signal.addEventListener("abort", onAbort, { once: true });
4500
+ });
4501
+ const joinUntil = async (work, signal) => {
4502
+ if (!work || signal.aborted) return;
4503
+ let onAbort;
4504
+ const aborted = new Promise((resolve) => {
4505
+ onAbort = () => resolve();
4506
+ signal.addEventListener("abort", onAbort, { once: true });
4507
+ });
4508
+ try {
4509
+ await Promise.race([work, aborted]);
4510
+ } finally {
4511
+ if (onAbort) signal.removeEventListener("abort", onAbort);
4512
+ }
4513
+ };
4514
+ const workSignal = (signal) => AbortSignal.any([signal, cancelWork.signal]);
4515
+ const interruptWork = () => {
4516
+ cancelWork.abort();
4517
+ cancelWork = new AbortController();
4518
+ notifyAbort?.abort();
4519
+ recordingAbort?.abort();
4520
+ pollAbort?.abort();
4521
+ };
4522
+ const fetchEncoded = (url, encoded, requestSignal) => {
4523
+ const headers = {
4524
+ Authorization: `Bearer ${options.ingestToken}`,
4525
+ "Content-Type": "application/json",
4526
+ Accept: "application/json"
4527
+ };
4528
+ if (encoded.gzip) headers["Content-Encoding"] = "gzip";
4529
+ return fetchFn(url, {
4530
+ method: "POST",
4531
+ headers,
4532
+ body: encoded.body,
4533
+ signal: requestSignal
4534
+ });
4535
+ };
4536
+ const withRequestTimeout = async (signal, run) => {
4537
+ const combined = workSignal(signal);
4538
+ const timeout = new AbortController();
4539
+ const timer = setTimeout(() => timeout.abort(), REQUEST_TIMEOUT_MS);
4540
+ timer.unref?.();
4541
+ const onAbort = () => timeout.abort();
4542
+ combined.addEventListener("abort", onAbort, { once: true });
4543
+ if (combined.aborted) timeout.abort();
4544
+ const requestSignal = AbortSignal.any([combined, timeout.signal]);
4545
+ try {
4546
+ return await run(requestSignal);
4547
+ } finally {
4548
+ clearTimeout(timer);
4549
+ combined.removeEventListener("abort", onAbort);
4550
+ }
4551
+ };
4552
+ const postEncoded = async (url, encoded, signal, readBody) => withRequestTimeout(signal, async (requestSignal) => {
4553
+ const response = await fetchEncoded(url, encoded, requestSignal);
4554
+ const body = await readBody(response);
4555
+ return { response, body };
4556
+ });
4557
+ const postJson = async (url, body, signal, readBody) => postEncoded(url, { body: JSON.stringify(body), gzip: false }, signal, readBody);
4558
+ const sendNotify = async (item, signal) => {
4559
+ if (item.expiresAtMs <= nowMs()) return true;
4560
+ for (let attempt = 0; attempt <= MAX_RETRIES; attempt++) {
4561
+ if (signal.aborted) return false;
4562
+ if (item.expiresAtMs <= nowMs()) return true;
4563
+ try {
4564
+ const { response, body: payload } = await postJson(
4565
+ options.activateUrl,
4566
+ {
4567
+ environment,
4568
+ execution_key: item.executionKey,
4569
+ activated_at: new Date(item.activatedAtMs).toISOString(),
4570
+ expires_at: new Date(item.expiresAtMs).toISOString(),
4571
+ duration_ms: Math.max(1, item.expiresAtMs - item.activatedAtMs)
4572
+ },
4573
+ signal,
4574
+ async (activateResponse) => {
4575
+ if (!activateResponse.ok) return void 0;
4576
+ try {
4577
+ return unwrapPayload(await activateResponse.json());
4578
+ } catch {
4579
+ return void 0;
4580
+ }
4581
+ }
4582
+ );
4583
+ if (response.ok) {
4584
+ const expiresAt = Date.parse(String(payload?.expires_at ?? ""));
4585
+ if (Number.isFinite(expiresAt) && expiresAt > nowMs()) {
4586
+ cache.set(item.executionKey, expiresAt);
4587
+ }
4588
+ return true;
4589
+ }
4590
+ const kind = classifyHttpFailure(response.status);
4591
+ rememberFailure(kind);
4592
+ if (kind === "non_retryable_http") {
4593
+ notifyFailures++;
4594
+ return true;
4595
+ }
4596
+ if (attempt === MAX_RETRIES) {
4597
+ notifyFailures++;
4598
+ return false;
4599
+ }
4600
+ await wait(backoffMs(attempt), signal);
4601
+ } catch (error) {
4602
+ if (signal.aborted || error instanceof Error && error.name === "AbortError") {
4603
+ rememberFailure("aborted");
4604
+ return false;
4605
+ }
4606
+ rememberFailure("network_error");
4607
+ if (attempt === MAX_RETRIES) {
4608
+ notifyFailures++;
4609
+ return false;
4610
+ }
4611
+ await wait(backoffMs(attempt), signal);
4612
+ }
4613
+ }
4614
+ return false;
4615
+ };
4616
+ const runPump = async (signal) => {
4617
+ do {
4618
+ pumpAgain = false;
4619
+ const queued = new Set(pending.keys());
4620
+ for (const key of queued) {
4621
+ if (signal.aborted) return;
4622
+ const current = pending.get(key);
4623
+ if (!current) continue;
4624
+ sendingKey = key;
4625
+ const done = await sendNotify(current, signal);
4626
+ sendingKey = void 0;
4627
+ if (pending.get(key) !== current) pumpAgain = true;
4628
+ else if (done || !signal.aborted) pending.delete(key);
4629
+ }
4630
+ for (const key of pending.keys()) {
4631
+ if (!queued.has(key)) {
4632
+ pumpAgain = true;
4633
+ break;
4634
+ }
4635
+ }
4636
+ } while (pumpAgain && pending.size > 0 && !signal.aborted);
4637
+ };
4638
+ const drainNotifies = async (signal) => {
4639
+ while (pending.size > 0 && !signal.aborted) {
4640
+ if (pump) {
4641
+ pumpAgain = true;
4642
+ await joinUntil(pump, signal);
4643
+ continue;
4644
+ }
4645
+ const running = runPump(signal);
4646
+ pump = running;
4647
+ try {
4648
+ await running;
4649
+ } finally {
4650
+ if (pump === running) pump = void 0;
4651
+ }
4652
+ break;
4653
+ }
4654
+ };
4655
+ const kickNotify = () => {
4656
+ if (!networkEnabled || closed || closing || pending.size === 0 || options.mode !== "adaptive")
4657
+ return;
4658
+ void drainNotifies(notifySignal());
4659
+ };
4660
+ const rememberCatalog = (key, atMs) => {
4661
+ if (key.length === 0 || key.length > MAX_EXECUTION_TYPE_KEY_LENGTH) return;
4662
+ if (catalog.size >= MAX_CACHE_ENTRIES && !catalog.has(key)) {
4663
+ const oldest = catalog.keys().next().value;
4664
+ if (oldest !== void 0) catalog.delete(oldest);
4665
+ }
4666
+ catalog.set(key, atMs);
4667
+ };
4668
+ const applyCompletedSessionIds = (value) => {
4669
+ if (!Array.isArray(value)) return;
4670
+ for (const entry of value) {
4671
+ const sessionId = trimmed2(entry);
4672
+ if (!sessionId) continue;
4673
+ completedSessionIds.add(sessionId);
4674
+ sessionsById.delete(sessionId);
4675
+ }
4676
+ markSessionsDirty();
4677
+ };
4678
+ const applySessions = (entries) => {
4679
+ if (!Array.isArray(entries)) return;
4680
+ const atMs = nowMs();
4681
+ const next = /* @__PURE__ */ new Map();
4682
+ for (const entry of entries) {
4683
+ if (!isRecord2(entry)) continue;
4684
+ const sessionId = trimmed2(entry.id);
4685
+ const executionKeyValue = trimmed2(entry.execution_key);
4686
+ const status = trimmed2(entry.status);
4687
+ const expiresAtMs = Date.parse(String(entry.expires_at ?? ""));
4688
+ const requestedCount = typeof entry.requested_count === "number" && Number.isFinite(entry.requested_count) ? Math.round(entry.requested_count) : 0;
4689
+ if (!sessionId || !executionKeyValue || status !== "active") continue;
4690
+ if (completedSessionIds.has(sessionId)) continue;
4691
+ if (!Number.isFinite(expiresAtMs) || expiresAtMs <= atMs || requestedCount < 1) continue;
4692
+ const existing = sessionsById.get(sessionId);
4693
+ const overrides = parseSessionSettings(entry.overrides);
4694
+ next.set(sessionId, {
4695
+ sessionId,
4696
+ executionKey: executionKeyValue,
4697
+ expiresAtMs,
4698
+ requestedCount,
4699
+ admitted: existing?.admitted ?? 0,
4700
+ serializer: serializers.serializerFor(overrides),
4701
+ redactKeys: overrides?.redactKeys,
4702
+ excludeSources: overrides?.excludeSources,
4703
+ maxCapturedCallsPerFunction: overrides?.maxCapturedCallsPerFunction,
4704
+ maxExecutionHoldMs: overrides?.maxExecutionHoldMs,
4705
+ scrubPII: overrides?.scrubPII
4706
+ });
4707
+ }
4708
+ sessionsById.clear();
4709
+ for (const [id, session] of next) sessionsById.set(id, session);
4710
+ markSessionsDirty();
4711
+ };
4712
+ const applyActivations = (activations) => {
4713
+ if (!Array.isArray(activations)) return;
4714
+ const atMs = nowMs();
4715
+ const seen = /* @__PURE__ */ new Set();
4716
+ for (const entry of activations) {
4717
+ if (!isRecord2(entry)) continue;
4718
+ const key = trimmed2(entry.execution_key);
4719
+ const expiresAt = Date.parse(String(entry.expires_at ?? ""));
4720
+ if (!key || !Number.isFinite(expiresAt) || expiresAt <= atMs) continue;
4721
+ cache.set(key, expiresAt);
4722
+ seen.add(key);
4723
+ }
4724
+ trimCache();
4725
+ for (const key of seen) pending.delete(key);
4726
+ };
4727
+ const catalogTypes = () => {
4728
+ const entries = [];
4729
+ for (const [executionKey, lastSeenAtMs] of catalog) {
4730
+ entries.push({ executionKey, lastSeenAtMs });
4731
+ if (entries.length >= MAX_PENDING_TYPES) break;
4732
+ }
4733
+ return entries;
4734
+ };
4735
+ const syncOnce = async (signal) => {
4736
+ if (!networkEnabled || closed) return;
4737
+ const types2 = catalogTypes();
4738
+ try {
4739
+ const { response, body: payload } = await postJson(
4740
+ options.syncUrl,
4741
+ {
4742
+ environment,
4743
+ instance: {
4744
+ id: instanceId,
4745
+ sdk_name: options.sdkName,
4746
+ sdk_version: options.sdkVersion,
4747
+ release: options.release,
4748
+ pid: process.pid,
4749
+ started_at: startedAt.toISOString(),
4750
+ reported_mode: options.mode,
4751
+ reported_settings: reportedRecorderSettings(options.recorderOptions, options.scrubPII),
4752
+ capabilities
4753
+ },
4754
+ types: types2.map((entry) => ({
4755
+ execution_key: entry.executionKey,
4756
+ last_seen_at: new Date(entry.lastSeenAtMs).toISOString()
4757
+ }))
4758
+ },
4759
+ signal,
4760
+ async (syncResponse) => {
4761
+ if (!syncResponse.ok) return void 0;
4762
+ return unwrapPayload(await syncResponse.json());
4763
+ }
4764
+ );
4765
+ if (!response.ok) {
4766
+ rememberFailure(classifyHttpFailure(response.status));
4767
+ refreshFailures++;
4768
+ return;
4769
+ }
4770
+ applyActivations(payload?.activations);
4771
+ applySessions(payload?.sessions);
4772
+ for (const entry of types2) {
4773
+ const current = catalog.get(entry.executionKey);
4774
+ if (current === void 0) continue;
4775
+ catalog.delete(entry.executionKey);
4776
+ if (current !== entry.lastSeenAtMs) {
4777
+ catalog.set(entry.executionKey, current);
4778
+ }
4779
+ }
4780
+ } catch (error) {
4781
+ if (signal.aborted || error instanceof Error && error.name === "AbortError") {
4782
+ rememberFailure("aborted");
4783
+ } else {
4784
+ rememberFailure("network_error");
4785
+ }
4786
+ refreshFailures++;
4787
+ }
4788
+ };
4789
+ const runSyncOnce = async (signal) => {
4790
+ if (syncFlight) {
4791
+ await joinUntil(syncFlight, signal);
4792
+ return;
4793
+ }
4794
+ const running = syncOnce(signal);
4795
+ const flight = running.finally(() => {
4796
+ if (syncFlight === flight) syncFlight = void 0;
4797
+ });
4798
+ syncFlight = flight;
4799
+ await joinUntil(flight, signal);
4800
+ };
4801
+ const sendRecordings = async (batch, signal) => {
4802
+ const combined = workSignal(signal);
4803
+ if (combined.aborted) return false;
4804
+ let encoded;
4805
+ try {
4806
+ encoded = await encodeJsonRequestBodyAsync(
4807
+ {
4808
+ instance_id: instanceId,
4809
+ recordings: batch.map((item) => ({
4810
+ session_id: item.sessionId,
4811
+ execution_id: item.executionId,
4812
+ outcome: item.outcome,
4813
+ runtime_state: item.runtimeState,
4814
+ release: options.release,
4815
+ redact_keys: copyRedactKeys([...redactKeys ?? [], ...item.redactKeys ?? []])?.slice(
4816
+ 0,
4817
+ MAX_REDACT_KEYS
4818
+ ),
4819
+ scrub_pii: item.scrubPii ?? scrubPii
4820
+ }))
4821
+ },
4822
+ void 0,
4823
+ combined
4824
+ );
4825
+ } catch (error) {
4826
+ if (combined.aborted || error instanceof Error && error.name === "AbortError") {
4827
+ rememberFailure("aborted");
4828
+ return false;
4829
+ }
4830
+ rememberFailure("network_error");
4831
+ return false;
4832
+ }
4833
+ for (let attempt = 0; attempt <= MAX_RETRIES; attempt++) {
4834
+ if (combined.aborted) return false;
4835
+ try {
4836
+ const { response, body } = await postEncoded(
4837
+ options.recordingsUrl,
4838
+ encoded,
4839
+ combined,
4840
+ async (uploadResponse) => {
4841
+ if (!uploadResponse.ok) return void 0;
4842
+ try {
4843
+ return unwrapPayload(await uploadResponse.json());
4844
+ } catch {
4845
+ return void 0;
4846
+ }
4847
+ }
4848
+ );
4849
+ if (response.ok) {
4850
+ applyCompletedSessionIds(body?.completed_session_ids);
4851
+ return true;
4852
+ }
4853
+ const kind = classifyHttpFailure(response.status);
4854
+ rememberFailure(kind);
4855
+ if (kind === "non_retryable_http") return true;
4856
+ if (attempt === MAX_RETRIES) return false;
4857
+ await wait(backoffMs(attempt), combined);
4858
+ } catch (error) {
4859
+ if (combined.aborted || error instanceof Error && error.name === "AbortError") {
4860
+ rememberFailure("aborted");
4861
+ return false;
4862
+ }
4863
+ rememberFailure("network_error");
4864
+ if (attempt === MAX_RETRIES) return false;
4865
+ await wait(backoffMs(attempt), combined);
4866
+ }
4867
+ }
4868
+ return false;
4869
+ };
4870
+ const drainRecordings = async (signal) => {
4871
+ while (recordings.length > 0 && !signal.aborted) {
4872
+ const batch = recordings.splice(0, 8);
4873
+ const ok = await sendRecordings(batch, signal);
4874
+ if (!ok) {
4875
+ recordings.unshift(...batch);
4876
+ break;
4877
+ }
4878
+ }
4879
+ };
4880
+ const kickRecordings = () => {
4881
+ if (!networkEnabled || closed || closing || recordings.length === 0) return;
4882
+ if (recordingPump) return;
4883
+ const running = drainRecordings(recordingSignal());
4884
+ recordingPump = running;
4885
+ void running.finally(() => {
4886
+ if (recordingPump === running) recordingPump = void 0;
4887
+ if (recordings.length > 0) kickRecordings();
4888
+ });
4889
+ };
4890
+ const activate = (metadata, window) => {
4891
+ if (closed || options.mode !== "adaptive") return;
4892
+ const key = executionTypeKey(metadata);
4893
+ if (!key) return;
4894
+ const atMs = nowMs();
4895
+ const existing = cache.get(key);
4896
+ if (existing !== void 0 && existing > atMs) return;
4897
+ cache.set(key, window.expiresAtMs);
4898
+ trimCache();
4899
+ if (!networkEnabled || window.expiresAtMs <= atMs) return;
4900
+ if (pending.size >= MAX_PENDING_NOTIFIES && !pending.has(key)) {
4901
+ for (const oldest of pending.keys()) {
4902
+ if (oldest !== sendingKey) {
4903
+ pending.delete(oldest);
4904
+ break;
4905
+ }
4906
+ }
4907
+ }
4908
+ pending.set(key, { executionKey: key, ...window });
4909
+ kickNotify();
4910
+ };
4911
+ const peekSessions = () => {
4912
+ if (sessionsDirty) rebuildSessionSnapshot();
4913
+ else {
4914
+ const atMs = nowMs();
4915
+ for (const session of sessionSnapshot.values()) {
4916
+ if (session.expiresAtMs <= atMs) {
4917
+ rebuildSessionSnapshot();
4918
+ break;
4919
+ }
4920
+ }
4921
+ }
4922
+ return sessionSnapshot;
4923
+ };
4924
+ const consumeSession = (executionKeyValue, sessionId) => {
4925
+ const atMs = nowMs();
4926
+ for (const session of sessionsById.values()) {
4927
+ if (session.executionKey !== executionKeyValue) continue;
4928
+ if (sessionId !== void 0 && session.sessionId !== sessionId) continue;
4929
+ if (!sessionHasRoom(session, atMs)) continue;
4930
+ session.admitted += 1;
4931
+ markSessionsDirty();
4932
+ return sessionView(session);
4933
+ }
4934
+ return void 0;
4935
+ };
4936
+ const observeType = (executionKeyValue) => {
4937
+ rememberCatalog(executionKeyValue, nowMs());
4938
+ };
4939
+ const enqueueRecording = (payload) => {
4940
+ if (closed || closing) return;
4941
+ recordings.push(payload);
4942
+ kickRecordings();
4943
+ };
4944
+ if (networkEnabled) {
4945
+ const interval = options.pollIntervalMs ?? DEFAULT_POLL_INTERVAL_MS;
4946
+ const jitterMax = Math.max(0, options.pollJitterMs ?? MAX_POLL_JITTER_MS);
4947
+ const delay = interval + Math.floor(Math.random() * jitterMax);
4948
+ pollStartTimer = setTimeout(() => {
4949
+ pollStartTimer = void 0;
4950
+ if (closed || closing) return;
4951
+ void runSyncOnce(pollSignal());
4952
+ pollTimer = setInterval(() => {
4953
+ if (closed || closing) return;
4954
+ void runSyncOnce(pollSignal());
4955
+ }, interval);
4956
+ pollTimer.unref?.();
4957
+ }, delay);
4958
+ pollStartTimer.unref?.();
4959
+ }
4960
+ const stopTimers = () => {
4961
+ if (pollStartTimer) {
4962
+ clearTimeout(pollStartTimer);
4963
+ pollStartTimer = void 0;
4964
+ }
4965
+ if (pollTimer) {
4966
+ clearInterval(pollTimer);
4967
+ pollTimer = void 0;
4968
+ }
4969
+ };
4970
+ return {
4971
+ peek,
4972
+ activate,
4973
+ peekSessions,
4974
+ consumeSession,
4975
+ observeType,
4976
+ enqueueRecording,
4977
+ getStats: () => ({
4978
+ adaptiveNotifyFailures: notifyFailures,
4979
+ adaptiveRefreshFailures: refreshFailures,
4980
+ lastAdaptiveFailureKind: lastFailureKind
4981
+ }),
4982
+ flush: async (timeoutMs = 2e3) => {
4983
+ if (!networkEnabled || closed || closing) return;
4984
+ const flushAbort = new AbortController();
4985
+ const onAbort = () => interruptWork();
4986
+ flushAbort.signal.addEventListener("abort", onAbort, { once: true });
4987
+ const timer = setTimeout(() => flushAbort.abort(), Math.max(0, timeoutMs));
4988
+ try {
4989
+ await runSyncOnce(flushAbort.signal);
4990
+ if (!flushAbort.signal.aborted) await drainNotifies(flushAbort.signal);
4991
+ await joinUntil(recordingPump, flushAbort.signal);
4992
+ if (!flushAbort.signal.aborted) await drainRecordings(flushAbort.signal);
4993
+ } finally {
4994
+ clearTimeout(timer);
4995
+ flushAbort.signal.removeEventListener("abort", onAbort);
4996
+ }
4997
+ },
4998
+ close: async () => {
4999
+ if (closed || closing) return;
5000
+ closing = true;
5001
+ stopTimers();
5002
+ const deadline = new AbortController();
5003
+ const timer = setTimeout(() => {
5004
+ deadline.abort();
5005
+ interruptWork();
5006
+ }, 2e3);
5007
+ try {
5008
+ if (networkEnabled) await runSyncOnce(deadline.signal);
5009
+ if (!deadline.signal.aborted) await drainNotifies(deadline.signal);
5010
+ await joinUntil(recordingPump, deadline.signal);
5011
+ if (!deadline.signal.aborted) await drainRecordings(deadline.signal);
5012
+ } finally {
5013
+ clearTimeout(timer);
5014
+ closed = true;
5015
+ interruptWork();
5016
+ pending.clear();
5017
+ }
5018
+ }
5019
+ };
5020
+ };
5021
+
5022
+ // src/execution-recorder/bind-adaptive-recorder.ts
5023
+ var bindAdaptiveRecorder = (input) => {
5024
+ const options = input.executionRecorder;
5025
+ const mode = sanitizeRecorderMode(options?.mode);
5026
+ const activation = resolveClientActivation({
5027
+ enabled: input.enabled,
5028
+ dsn: input.dsn,
5029
+ projectApiKey: input.projectApiKey,
5030
+ apiUrl: input.apiUrl,
5031
+ release: input.release
5032
+ });
5033
+ const coordinator = input.recorderEnabled && activation.enabled ? createExecutionRecordingCoordinator({
5034
+ environment: input.environment ?? "",
5035
+ ingestToken: activation.ingestToken,
5036
+ activateUrl: resolveEndpointUrls2(activation.apiUrl).executionRecordingActivateUrl,
5037
+ syncUrl: resolveEndpointUrls2(activation.apiUrl).executionRecordingSyncUrl,
5038
+ recordingsUrl: resolveEndpointUrls2(activation.apiUrl).executionRecordingRecordingsUrl,
5039
+ sdkName: input.sdkName,
5040
+ sdkVersion: input.sdkVersion,
5041
+ release: activation.release,
5042
+ recorderOptions: options,
5043
+ scrubPII: input.scrubPII,
5044
+ mode,
5045
+ fetch: input.fetch
5046
+ }) : void 0;
5047
+ const runtime = createExecutionRecorder(
5048
+ { ...options, enabled: input.recorderEnabled },
5049
+ coordinator ? {
5050
+ policySnapshot: coordinator.peek,
5051
+ onQualifyingFailure: mode === "adaptive" ? coordinator.activate : void 0,
5052
+ getStats: coordinator.getStats,
5053
+ sessionCaptureSnapshot: coordinator.peekSessions,
5054
+ consumeSession: coordinator.consumeSession,
5055
+ observeExecutionType: coordinator.observeType,
5056
+ onSessionRecording: coordinator.enqueueRecording
5057
+ } : void 0
5058
+ );
5059
+ return { runtime, policy: coordinator };
5060
+ };
5061
+
4001
5062
  // src/install-global-handlers.ts
4002
5063
  var RASPUTIN_PROCESS_LISTENER = Symbol.for("rasputin.process.listener.v1");
4003
5064
  var unhandledRejectionMode = () => {
@@ -4136,7 +5197,7 @@ var installGlobalHandlers = (client, options = {}) => {
4136
5197
 
4137
5198
  // src/sdk-meta.ts
4138
5199
  var SDK_NAME = "@rasputin-ai/node";
4139
- var SDK_VERSION = "0.10.1";
5200
+ var SDK_VERSION = "0.11.0";
4140
5201
 
4141
5202
  // src/rasputin-init.ts
4142
5203
  var publicExecution = (runtime) => ({
@@ -4152,7 +5213,7 @@ var publicExecution = (runtime) => ({
4152
5213
  getStats: runtime.getStats
4153
5214
  });
4154
5215
  var withExecution = (client, runtime, installRuntime, manifest, uninstallHandlers = () => {
4155
- }) => {
5216
+ }, policy) => {
4156
5217
  const uninstallRuntime = installRuntime ? installAutomaticExecutionRuntime(runtime) : () => {
4157
5218
  };
4158
5219
  const manifestUpload = scheduleInstrumentationManifestUpload(manifest);
@@ -4171,9 +5232,11 @@ var withExecution = (client, runtime, installRuntime, manifest, uninstallHandler
4171
5232
  const startedAt = Date.now();
4172
5233
  await client.flush(timeoutMs);
4173
5234
  if (timeoutMs === void 0) {
5235
+ await policy?.flush();
4174
5236
  await manifestUpload.wait();
4175
5237
  return;
4176
5238
  }
5239
+ await policy?.flush(Math.max(0, timeoutMs - (Date.now() - startedAt)));
4177
5240
  await manifestUpload.wait(Math.max(0, timeoutMs - (Date.now() - startedAt)));
4178
5241
  },
4179
5242
  close: async () => {
@@ -4181,6 +5244,7 @@ var withExecution = (client, runtime, installRuntime, manifest, uninstallHandler
4181
5244
  uninstallRuntime();
4182
5245
  manifestUpload.disconnect();
4183
5246
  const startedAt = Date.now();
5247
+ await policy?.close();
4184
5248
  await client.close();
4185
5249
  await manifestUpload.wait(Math.max(0, 2e3 - (Date.now() - startedAt)));
4186
5250
  }
@@ -4190,15 +5254,24 @@ var RasputinInit = (options) => {
4190
5254
  try {
4191
5255
  const enabled = isClientEnabled(options);
4192
5256
  const recorderEnabled = enabled && options.executionRecorder?.enabled !== false;
4193
- const runtime = createExecutionRecorder({
4194
- ...options.executionRecorder,
4195
- enabled: recorderEnabled
5257
+ const { runtime, policy } = bindAdaptiveRecorder({
5258
+ executionRecorder: options.executionRecorder,
5259
+ recorderEnabled,
5260
+ dsn: options.dsn,
5261
+ projectApiKey: options.projectApiKey,
5262
+ apiUrl: options.apiUrl,
5263
+ release: options.release,
5264
+ environment: options.environment,
5265
+ enabled: options.enabled,
5266
+ sdkName: SDK_NAME,
5267
+ sdkVersion: SDK_VERSION,
5268
+ scrubPII: options.scrubPII
4196
5269
  });
4197
5270
  const client = createClient(options, {
4198
5271
  sdkVersion: SDK_VERSION,
4199
5272
  sdkName: SDK_NAME,
4200
5273
  installTransportSignalHandlers: options.installTransportSignalHandlers,
4201
- redactKeys: copyRedactKeys(options.executionRecorder?.redactKeys),
5274
+ redactKeys: copyRedactKeys2(options.executionRecorder?.redactKeys),
4202
5275
  resolveObservation: (observation) => runtime.getErrorState(observation)
4203
5276
  });
4204
5277
  if (enabled) {
@@ -4221,7 +5294,8 @@ var RasputinInit = (options) => {
4221
5294
  sourceRoots: options.sourceRoots,
4222
5295
  logSuccess: options.logSuccess
4223
5296
  },
4224
- () => uninstallHandlers()
5297
+ () => uninstallHandlers(),
5298
+ policy
4225
5299
  );
4226
5300
  if (enabled && options.installGlobalHandlers !== false) {
4227
5301
  uninstallHandlers = installGlobalHandlers(wrappedClient);