@launchdarkly/server-sdk-ai 0.16.8 → 0.17.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.
package/dist/index.d.cts CHANGED
@@ -49,26 +49,23 @@ interface StructuredResponse {
49
49
  metrics: LDAIMetrics;
50
50
  }
51
51
  /**
52
- * Score and reasoning for a single evaluation metric.
52
+ * Result from a judge evaluation containing score, reasoning, and metadata.
53
53
  */
54
- interface EvalScore {
55
- /** Score between 0.0 and 1.0 indicating the evaluation result for this metric */
56
- score: number;
57
- /** Reasoning behind the provided score for this metric */
58
- reasoning: string;
59
- }
60
- /**
61
- * Response from a judge evaluation containing scores and reasoning for multiple metrics.
62
- */
63
- interface JudgeResponse {
64
- /** The key of the judge configuration that was used to generate this response */
54
+ interface LDJudgeResult {
55
+ /** The key of the judge configuration that was used to generate this result */
65
56
  judgeConfigKey?: string;
66
- /** Dictionary where keys are metric names and values contain score and reasoning */
67
- evals: Record<string, EvalScore>;
68
57
  /** Whether the evaluation completed successfully */
69
58
  success: boolean;
70
59
  /** Error message if evaluation failed */
71
- error?: string;
60
+ errorMessage?: string;
61
+ /** Whether this evaluation was sampled (i.e. actually run). False when skipped by sampling. */
62
+ sampled: boolean;
63
+ /** The metric key for this evaluation */
64
+ metricKey?: string;
65
+ /** Score between 0.0 and 1.0 indicating the evaluation result */
66
+ score?: number;
67
+ /** Reasoning behind the provided score */
68
+ reasoning?: string;
72
69
  }
73
70
 
74
71
  declare function createBedrockTokenUsage(data: {
@@ -140,15 +137,28 @@ interface LDAIConfigTracker {
140
137
  * Get the data for tracking.
141
138
  */
142
139
  getTrackData(): {
143
- variationKey: string;
140
+ runId: string;
144
141
  configKey: string;
142
+ variationKey: string;
145
143
  version: number;
146
144
  modelName: string;
147
145
  providerName: string;
146
+ graphKey?: string;
148
147
  };
148
+ /**
149
+ * A URL-safe Base64-encoded token that encodes the tracker's runId, configKey,
150
+ * variationKey, and version. Pass this to AIClient.createTracker() to reconstruct
151
+ * the tracker across process boundaries (e.g. for associating deferred feedback
152
+ * with the original invocation).
153
+ */
154
+ readonly resumptionToken: string;
149
155
  /**
150
156
  * Track the duration of generation.
151
157
  *
158
+ * At-most-once per execution: subsequent calls on the same tracker are dropped
159
+ * with a warning. Use createTracker() on the config result to obtain a fresh
160
+ * tracker for a new execution.
161
+ *
152
162
  * Ideally this would not include overhead time such as network communication.
153
163
  *
154
164
  * @param durationMs The duration in milliseconds.
@@ -157,20 +167,32 @@ interface LDAIConfigTracker {
157
167
  /**
158
168
  * Track information about token usage.
159
169
  *
170
+ * At-most-once per execution: subsequent calls on the same tracker are dropped
171
+ * with a warning.
172
+ *
160
173
  * @param tokens Token usage information.
161
174
  */
162
175
  trackTokens(tokens: LDTokenUsage): void;
163
176
  /**
164
177
  * Generation was successful.
178
+ *
179
+ * At-most-once per execution: subsequent calls (including trackError) on the
180
+ * same tracker are dropped with a warning.
165
181
  */
166
182
  trackSuccess(): void;
167
183
  /**
168
184
  * An error was encountered during generation.
185
+ *
186
+ * At-most-once per execution: subsequent calls (including trackSuccess) on the
187
+ * same tracker are dropped with a warning.
169
188
  */
170
189
  trackError(): void;
171
190
  /**
172
191
  * Track sentiment about the generation.
173
192
  *
193
+ * At-most-once per execution: subsequent calls on the same tracker are dropped
194
+ * with a warning.
195
+ *
174
196
  * @param feedback Feedback about the generation.
175
197
  */
176
198
  trackFeedback(feedback: {
@@ -179,21 +201,32 @@ interface LDAIConfigTracker {
179
201
  /**
180
202
  * Track the time to first token for this generation.
181
203
  *
204
+ * At-most-once per execution: subsequent calls on the same tracker are dropped
205
+ * with a warning.
206
+ *
182
207
  * @param timeToFirstTokenMs The duration in milliseconds.
183
208
  */
184
209
  trackTimeToFirstToken(timeToFirstTokenMs: number): void;
185
210
  /**
186
- * Track evaluation scores for multiple metrics.
211
+ * Track a judge evaluation result.
212
+ *
213
+ * No event is emitted when the result was not sampled (result.sampled is false).
214
+ *
215
+ * @param result Judge result containing score, reasoning, and metadata
216
+ */
217
+ trackJudgeResult(result: LDJudgeResult): void;
218
+ /**
219
+ * Track a single tool invocation.
187
220
  *
188
- * @param scores Record mapping metric keys to their evaluation scores
221
+ * @param toolKey The identifier of the tool that was invoked.
189
222
  */
190
- trackEvalScores(scores: Record<string, EvalScore>): void;
223
+ trackToolCall(toolKey: string): void;
191
224
  /**
192
- * Track a judge response containing evaluation scores and judge configuration key.
225
+ * Track multiple tool invocations.
193
226
  *
194
- * @param response Judge response containing evaluation scores and judge configuration key
227
+ * @param toolKeys The identifiers of the tools that were invoked.
195
228
  */
196
- trackJudgeResponse(response: JudgeResponse): void;
229
+ trackToolCalls(toolKeys: string[]): void;
197
230
  /**
198
231
  * Track the duration of execution of the provided function.
199
232
  *
@@ -396,10 +429,11 @@ interface LDAIConfig extends Omit<LDAIConfigDefault, 'enabled'> {
396
429
  */
397
430
  enabled: boolean;
398
431
  /**
399
- * A tracker which can be used to generate analytics.
400
- * Undefined for disabled configs.
432
+ * Creates a new tracker for this AI Config invocation. Each call returns a
433
+ * new tracker with a fresh runId. Use createTracker() at the start of each
434
+ * execution to obtain a tracker, then use it to record metrics for that run.
401
435
  */
402
- tracker?: LDAIConfigTracker;
436
+ createTracker?: () => LDAIConfigTracker;
403
437
  }
404
438
  /**
405
439
  * Default Agent-specific AI Config with instructions.
@@ -543,7 +577,7 @@ interface ChatResponse {
543
577
  * Promise that resolves to judge evaluation results.
544
578
  * Only present when judges are configured for evaluation.
545
579
  */
546
- evaluations?: Promise<Array<JudgeResponse | undefined>>;
580
+ evaluations?: Promise<LDJudgeResult[]>;
547
581
  }
548
582
 
549
583
  /**
@@ -602,11 +636,9 @@ declare abstract class AIProvider {
602
636
  */
603
637
  declare class Judge {
604
638
  private readonly _aiConfig;
605
- private readonly _aiConfigTracker;
606
639
  private readonly _aiProvider;
607
640
  private readonly _logger?;
608
- private readonly _evaluationResponseStructure;
609
- constructor(_aiConfig: LDAIJudgeConfig, _aiConfigTracker: LDAIConfigTracker, _aiProvider: AIProvider, logger?: LDLogger$1);
641
+ constructor(_aiConfig: LDAIJudgeConfig, _aiProvider: AIProvider, logger?: LDLogger$1);
610
642
  /**
611
643
  * Gets the evaluation metric key, prioritizing evaluationMetricKey over evaluationMetricKeys.
612
644
  * Falls back to the first valid (non-empty, non-whitespace) value in evaluationMetricKeys if evaluationMetricKey is not provided.
@@ -620,26 +652,22 @@ declare class Judge {
620
652
  * @param input The input prompt or question that was provided to the AI
621
653
  * @param output The AI-generated response to be evaluated
622
654
  * @param samplingRate Sampling rate (0-1) to determine if evaluation should be processed (defaults to 1)
623
- * @returns Promise that resolves to evaluation results or undefined if not sampled
655
+ * @returns Promise that resolves to evaluation results
624
656
  */
625
- evaluate(input: string, output: string, samplingRate?: number): Promise<JudgeResponse | undefined>;
657
+ evaluate(input: string, output: string, samplingRate?: number): Promise<LDJudgeResult>;
626
658
  /**
627
659
  * Evaluates an AI response from chat messages and response.
628
660
  *
629
661
  * @param messages Array of messages representing the conversation history
630
662
  * @param response The AI response to be evaluated
631
663
  * @param samplingRatio Sampling ratio (0-1) to determine if evaluation should be processed (defaults to 1)
632
- * @returns Promise that resolves to evaluation results or undefined if not sampled
664
+ * @returns Promise that resolves to evaluation results
633
665
  */
634
- evaluateMessages(messages: LDMessage[], response: ChatResponse, samplingRatio?: number): Promise<JudgeResponse | undefined>;
666
+ evaluateMessages(messages: LDMessage[], response: ChatResponse, samplingRatio?: number): Promise<LDJudgeResult>;
635
667
  /**
636
668
  * Returns the AI Config used by this judge.
637
669
  */
638
670
  getAIConfig(): LDAIJudgeConfig;
639
- /**
640
- * Returns the tracker associated with this judge.
641
- */
642
- getTracker(): LDAIConfigTracker;
643
671
  /**
644
672
  * Returns the AI provider used by this judge.
645
673
  */
@@ -653,7 +681,8 @@ declare class Judge {
653
681
  */
654
682
  private _interpolateMessage;
655
683
  /**
656
- * Parses the structured evaluation response from the AI provider.
684
+ * Parses the structured evaluation response. Expects top-level {score, reasoning}.
685
+ * Returns score and reasoning, or undefined if parsing fails.
657
686
  */
658
687
  private _parseEvaluationResponse;
659
688
  }
@@ -666,12 +695,11 @@ declare class Judge {
666
695
  */
667
696
  declare class TrackedChat {
668
697
  protected readonly aiConfig: LDAICompletionConfig;
669
- protected readonly tracker: LDAIConfigTracker;
670
698
  protected readonly provider: AIProvider;
671
699
  protected readonly judges: Record<string, Judge>;
672
700
  private readonly _logger?;
673
701
  protected messages: LDMessage[];
674
- constructor(aiConfig: LDAICompletionConfig, tracker: LDAIConfigTracker, provider: AIProvider, judges?: Record<string, Judge>, _logger?: LDLogger$1 | undefined);
702
+ constructor(aiConfig: LDAICompletionConfig, provider: AIProvider, judges?: Record<string, Judge>, _logger?: LDLogger$1 | undefined);
675
703
  /**
676
704
  * Invoke the chat model with a prompt string.
677
705
  * This method handles conversation management and tracking, delegating to the provider's invokeModel method.
@@ -690,10 +718,6 @@ declare class TrackedChat {
690
718
  * Get the underlying AI configuration used to initialize this TrackedChat.
691
719
  */
692
720
  getConfig(): LDAICompletionConfig;
693
- /**
694
- * Get the underlying AI configuration tracker used to initialize this TrackedChat.
695
- */
696
- getTracker(): LDAIConfigTracker;
697
721
  /**
698
722
  * Get the underlying AI provider instance.
699
723
  * This provides direct access to the provider for advanced use cases.
@@ -724,6 +748,322 @@ declare class TrackedChat {
724
748
  getMessages(includeConfigMessages?: boolean): LDMessage[];
725
749
  }
726
750
 
751
+ /**
752
+ * Represents a directed edge in an agent graph, connecting a source node to a target node.
753
+ */
754
+ interface LDGraphEdge {
755
+ /**
756
+ * The key of the target AIAgentConfig node.
757
+ */
758
+ key: string;
759
+ /**
760
+ * Optional handoff options that customize how data flows between nodes.
761
+ */
762
+ handoff?: Record<string, unknown>;
763
+ }
764
+ /**
765
+ * Raw flag value for an agent graph configuration as returned by LaunchDarkly.
766
+ * This represents the data structure delivered by LaunchDarkly for graph configurations.
767
+ */
768
+ interface LDAgentGraphFlagValue {
769
+ _ldMeta?: {
770
+ variationKey?: string;
771
+ version?: number;
772
+ enabled?: boolean;
773
+ };
774
+ /**
775
+ * The key of the root AIAgentConfig in the graph.
776
+ */
777
+ root: string;
778
+ /**
779
+ * Object mapping source agent config keys to arrays of target edges.
780
+ */
781
+ edges?: Record<string, LDGraphEdge[]>;
782
+ }
783
+ /**
784
+ * Accumulated graph-level metrics collected by an LDGraphTracker.
785
+ */
786
+ interface LDGraphMetricSummary {
787
+ /**
788
+ * Whether the graph invocation succeeded. Absent if not yet tracked.
789
+ */
790
+ success?: boolean;
791
+ /**
792
+ * Total graph execution duration in milliseconds. Absent if not yet tracked.
793
+ */
794
+ durationMs?: number;
795
+ /**
796
+ * Aggregate token usage across the entire graph invocation. Absent if not yet tracked.
797
+ */
798
+ tokens?: LDTokenUsage;
799
+ /**
800
+ * Execution path through the graph as an array of config keys. Absent if not yet tracked.
801
+ */
802
+ path?: string[];
803
+ }
804
+ /**
805
+ * Tracking metadata returned by {@link LDGraphTracker.getTrackData}.
806
+ */
807
+ interface LDGraphTrackData {
808
+ /**
809
+ * UUID v4 uniquely identifying this tracker and all events it emits.
810
+ */
811
+ runId: string;
812
+ /**
813
+ * The graph configuration key.
814
+ */
815
+ graphKey: string;
816
+ /**
817
+ * The variation key. Absent when a default config was used rather than a real flag evaluation.
818
+ */
819
+ variationKey?: string;
820
+ /**
821
+ * The version of the flag variation.
822
+ */
823
+ version: number;
824
+ }
825
+
826
+ /**
827
+ * Tracks graph-level and edge-level metrics for an agent graph invocation.
828
+ *
829
+ * Graph-level methods enforce at-most-once semantics: calling the same method
830
+ * twice on a tracker instance drops the second call and emits a warning.
831
+ * Edge-level methods (trackRedirect, trackHandoffSuccess, trackHandoffFailure)
832
+ * are multi-fire and are not subject to this constraint.
833
+ *
834
+ * @example
835
+ * ```typescript
836
+ * const tracker = graphDefinition.createTracker();
837
+ * try {
838
+ * // ... execute graph ...
839
+ * tracker.trackInvocationSuccess();
840
+ * tracker.trackDuration(durationMs);
841
+ * } catch {
842
+ * tracker.trackInvocationFailure();
843
+ * }
844
+ * ```
845
+ */
846
+ interface LDGraphTracker {
847
+ /**
848
+ * Returns tracking metadata to be included in every LDClient.track call.
849
+ */
850
+ getTrackData(): LDGraphTrackData;
851
+ /**
852
+ * Returns a snapshot of all graph-level metrics tracked so far.
853
+ */
854
+ getSummary(): LDGraphMetricSummary;
855
+ /**
856
+ * A URL-safe Base64-encoded (RFC 4648, no padding) token encoding the tracker's
857
+ * identity. Pass this token to {@link LDGraphTrackerImpl.fromResumptionToken} to
858
+ * reconstruct the tracker across process boundaries, preserving the original runId.
859
+ *
860
+ * **Security note:** The token contains the flag variation key and version. If passed
861
+ * to an untrusted client (e.g., a browser) this could expose feature-flag targeting
862
+ * details. Keep the token server-side and use an opaque reference in client-facing APIs.
863
+ */
864
+ readonly resumptionToken: string;
865
+ /**
866
+ * Tracks a successful graph invocation.
867
+ * Emits event `$ld:ai:graph:invocation_success` with metric value `1`.
868
+ * At-most-once: subsequent calls are dropped with a warning.
869
+ */
870
+ trackInvocationSuccess(): void;
871
+ /**
872
+ * Tracks an unsuccessful graph invocation.
873
+ * Emits event `$ld:ai:graph:invocation_failure` with metric value `1`.
874
+ * At-most-once: subsequent calls are dropped with a warning.
875
+ */
876
+ trackInvocationFailure(): void;
877
+ /**
878
+ * Tracks the total duration of the graph execution in milliseconds.
879
+ * Emits event `$ld:ai:graph:duration:total` with the duration as the metric value.
880
+ * At-most-once: subsequent calls are dropped with a warning.
881
+ *
882
+ * @param durationMs Duration in milliseconds.
883
+ */
884
+ trackDuration(durationMs: number): void;
885
+ /**
886
+ * Tracks aggregate token usage across the entire graph invocation.
887
+ * Emits event `$ld:ai:graph:total_tokens` with the total token count as the metric value.
888
+ * At-most-once: subsequent calls are dropped with a warning.
889
+ *
890
+ * @param tokens Token usage information.
891
+ */
892
+ trackTotalTokens(tokens: LDTokenUsage): void;
893
+ /**
894
+ * Tracks the execution path through the graph.
895
+ * Emits event `$ld:ai:graph:path` with metric value `1`.
896
+ * The data payload includes the path array in addition to standard track data.
897
+ * At-most-once: subsequent calls are dropped with a warning.
898
+ *
899
+ * @param path An ordered array of agent config keys representing the execution path.
900
+ */
901
+ trackPath(path: string[]): void;
902
+ /**
903
+ * Tracks when a node redirects to a different target than originally specified.
904
+ * Emits event `$ld:ai:graph:redirect` with metric value `1`.
905
+ *
906
+ * @param sourceKey Config key of the source node.
907
+ * @param redirectedTarget Config key of the actual target node.
908
+ */
909
+ trackRedirect(sourceKey: string, redirectedTarget: string): void;
910
+ /**
911
+ * Tracks a successful handoff between two nodes.
912
+ * Emits event `$ld:ai:graph:handoff_success` with metric value `1`.
913
+ *
914
+ * @param sourceKey Config key of the source node.
915
+ * @param targetKey Config key of the target node.
916
+ */
917
+ trackHandoffSuccess(sourceKey: string, targetKey: string): void;
918
+ /**
919
+ * Tracks a failed handoff between two nodes.
920
+ * Emits event `$ld:ai:graph:handoff_failure` with metric value `1`.
921
+ *
922
+ * @param sourceKey Config key of the source node.
923
+ * @param targetKey Config key of the target node.
924
+ */
925
+ trackHandoffFailure(sourceKey: string, targetKey: string): void;
926
+ }
927
+
928
+ /**
929
+ * Represents a single node within an agent graph.
930
+ *
931
+ * Each node wraps an {@link LDAIAgentConfig} and carries the outgoing edges
932
+ * to its children. Use the node's tracker (via `getConfig().tracker`) to record
933
+ * node-level metrics against the underlying agent config.
934
+ */
935
+ declare class AgentGraphNode {
936
+ private readonly _key;
937
+ private readonly _config;
938
+ private readonly _edges;
939
+ constructor(_key: string, _config: LDAIAgentConfig, _edges: LDGraphEdge[]);
940
+ /**
941
+ * Returns the agent config key that identifies this node in the graph.
942
+ */
943
+ getKey(): string;
944
+ /**
945
+ * Returns the underlying AIAgentConfig for this node.
946
+ * Use `getConfig().tracker` to record node-level metrics.
947
+ */
948
+ getConfig(): LDAIAgentConfig;
949
+ /**
950
+ * Returns the outgoing edges from this node to its children.
951
+ */
952
+ getEdges(): LDGraphEdge[];
953
+ /**
954
+ * Returns `true` if this node has no outgoing edges (i.e., it is a terminal/leaf node).
955
+ */
956
+ isTerminal(): boolean;
957
+ }
958
+
959
+ /**
960
+ * Callback function signature for graph traversal methods.
961
+ */
962
+ type TraversalFn = (node: AgentGraphNode, executionContext: Record<string, unknown>) => unknown;
963
+ /**
964
+ * Encapsulates an agent graph configuration and its pre-built node collection.
965
+ *
966
+ * Provides graph-level orchestration including relationship queries (parent/child),
967
+ * breadth-first traversal in both forward and reverse directions, and graph tracker creation.
968
+ *
969
+ * Obtain an instance via {@link LDAIClient.agentGraph}. When the graph is disabled
970
+ * or invalid, the returned instance has {@link enabled} set to `false` and an
971
+ * empty node collection.
972
+ */
973
+ declare class AgentGraphDefinition {
974
+ private readonly _agentGraph;
975
+ private readonly _nodes;
976
+ readonly enabled: boolean;
977
+ private readonly _createTracker;
978
+ constructor(_agentGraph: LDAgentGraphFlagValue, _nodes: Record<string, AgentGraphNode>, enabled: boolean, _createTracker: () => LDGraphTracker);
979
+ /**
980
+ * Builds a node map from a raw agent graph flag value and a map of pre-fetched agent configs.
981
+ *
982
+ * @param graph Raw graph flag value from LaunchDarkly.
983
+ * @param agentConfigs Map of agent config key to resolved LDAIAgentConfig.
984
+ * @returns Record mapping agent config keys to AgentGraphNode instances.
985
+ */
986
+ static buildNodes(graph: LDAgentGraphFlagValue, agentConfigs: Record<string, LDAIAgentConfig>): Record<string, AgentGraphNode>;
987
+ /**
988
+ * Returns the children of the node identified by `nodeKey`.
989
+ *
990
+ * @param nodeKey The agent config key of the parent node.
991
+ */
992
+ getChildNodes(nodeKey: string): AgentGraphNode[];
993
+ /**
994
+ * Returns all nodes that have a direct edge to the node identified by `nodeKey`.
995
+ *
996
+ * @param nodeKey The agent config key of the child node.
997
+ */
998
+ getParentNodes(nodeKey: string): AgentGraphNode[];
999
+ /**
1000
+ * Returns all terminal nodes (nodes with no outgoing edges).
1001
+ */
1002
+ terminalNodes(): AgentGraphNode[];
1003
+ /**
1004
+ * Returns the root node of the graph.
1005
+ */
1006
+ rootNode(): AgentGraphNode;
1007
+ /**
1008
+ * Returns the node with the given key, or `null` if not found.
1009
+ *
1010
+ * @param nodeKey The agent config key to look up.
1011
+ */
1012
+ getNode(nodeKey: string): AgentGraphNode | null;
1013
+ /**
1014
+ * Returns the underlying raw graph configuration from LaunchDarkly.
1015
+ */
1016
+ getConfig(): LDAgentGraphFlagValue;
1017
+ /**
1018
+ * Returns a new {@link LDGraphTracker} for this graph invocation.
1019
+ *
1020
+ * Call this once per invocation. Each call produces a tracker with a fresh `runId`
1021
+ * that groups all events for that invocation.
1022
+ */
1023
+ createTracker(): LDGraphTracker;
1024
+ /**
1025
+ * Traverses the graph breadth-first from the root to all terminal nodes.
1026
+ *
1027
+ * Nodes at the same depth are processed before advancing to the next depth.
1028
+ * The value returned by `fn` is stored in the mutable `executionContext` under
1029
+ * the node's key, making upstream results available to downstream nodes.
1030
+ *
1031
+ * Cyclic graphs are handled safely — each node is visited at most once.
1032
+ *
1033
+ * @param fn Callback invoked for each node. Its return value is added to
1034
+ * `executionContext` keyed by the node's config key.
1035
+ * @param initialExecutionContext Optional initial context to seed the traversal.
1036
+ */
1037
+ traverse(fn: TraversalFn, initialExecutionContext?: Record<string, unknown>): void;
1038
+ /**
1039
+ * Traverses the graph from terminal nodes up to the root.
1040
+ *
1041
+ * Uses BFS upward via parent edges so that each node is processed only after
1042
+ * all of its reachable descendants have been processed. The root is always
1043
+ * visited last. Cyclic graphs are handled safely — each node is visited at
1044
+ * most once; if the graph has no terminal nodes, this method returns without
1045
+ * invoking `fn`.
1046
+ *
1047
+ * **Ordering note:** Within a single BFS level (nodes at the same depth from a
1048
+ * terminal) the visit order is not strictly guaranteed. The guarantee is only
1049
+ * that a node is visited before any of its ancestors — not that siblings at the
1050
+ * same depth are visited in a specific order relative to each other.
1051
+ *
1052
+ * The value returned by `fn` is stored in the mutable `executionContext` under
1053
+ * the node's key.
1054
+ *
1055
+ * @param fn Callback invoked for each node. Its return value is added to
1056
+ * `executionContext` keyed by the node's config key.
1057
+ * @param initialExecutionContext Optional initial context to seed the traversal.
1058
+ */
1059
+ reverseTraverse(fn: TraversalFn, initialExecutionContext?: Record<string, unknown>): void;
1060
+ /**
1061
+ * Collects every unique node key referenced in the graph (root + all edge sources
1062
+ * and targets).
1063
+ */
1064
+ static collectAllKeys(graph: LDAgentGraphFlagValue): Set<string>;
1065
+ }
1066
+
727
1067
  /**
728
1068
  * List of supported AI providers.
729
1069
  */
@@ -1010,6 +1350,61 @@ interface LDAIClient {
1010
1350
  * ```
1011
1351
  */
1012
1352
  createJudge(key: string, context: LDContext, defaultValue?: LDAIJudgeConfigDefault, variables?: Record<string, unknown>, defaultAiProvider?: SupportedAIProvider): Promise<Judge | undefined>;
1353
+ /**
1354
+ * Reconstructs an AIConfigTracker from a resumption token string previously
1355
+ * obtained from a tracker's `resumptionToken` property. Use this to associate
1356
+ * deferred events (such as user feedback) with the original invocation's runId.
1357
+ *
1358
+ * @param token A URL-safe Base64-encoded resumption token string.
1359
+ * @param context The evaluation context to use for subsequent track calls.
1360
+ * @returns A reconstructed AIConfigTracker with the original runId preserved.
1361
+ */
1362
+ createTracker(token: string, context: LDContext): LDAIConfigTracker;
1363
+ /**
1364
+ * Fetches an agent graph configuration from LaunchDarkly and returns an
1365
+ * {@link AgentGraphDefinition}.
1366
+ *
1367
+ * When the graph is enabled the method validates that:
1368
+ * - The graph flag can be evaluated.
1369
+ * - A single root node is present.
1370
+ * - All nodes in the graph are reachable from the root (no disconnected nodes).
1371
+ * - Every referenced agent config can be fetched and is enabled.
1372
+ *
1373
+ * If any validation check fails, the returned definition has
1374
+ * {@link AgentGraphDefinition.enabled | enabled} set to `false` with an empty
1375
+ * node collection. When the logger level is DEBUG, a message describing the
1376
+ * failure is emitted.
1377
+ *
1378
+ * @param graphKey The LaunchDarkly flag key for the agent graph configuration.
1379
+ * @param context The LaunchDarkly context used for flag evaluation and tracking.
1380
+ * @param variables Optional key-value pairs used for Mustache template interpolation
1381
+ * in each node's agent config instructions. Applied uniformly to all nodes.
1382
+ *
1383
+ * @returns A promise that resolves to an {@link AgentGraphDefinition}. Check
1384
+ * {@link AgentGraphDefinition.enabled | enabled} before traversing.
1385
+ *
1386
+ * @example
1387
+ * ```typescript
1388
+ * const graph = await aiClient.agentGraph('my-agent-graph', context, { userName: 'Sandy' });
1389
+ * if (graph.enabled) {
1390
+ * graph.traverse((node, ctx) => {
1391
+ * // build your provider-specific node here
1392
+ * });
1393
+ * }
1394
+ * ```
1395
+ */
1396
+ agentGraph(graphKey: string, context: LDContext, variables?: Record<string, unknown>): Promise<AgentGraphDefinition>;
1397
+ /**
1398
+ * Reconstructs an {@link LDGraphTracker} from a resumption token, preserving
1399
+ * the original `runId` so events from a resumed session are correlated correctly.
1400
+ *
1401
+ * **Security note:** The token encodes the flag variation key and version.
1402
+ * Keep it server-side; do not expose it to untrusted clients.
1403
+ *
1404
+ * @param token URL-safe Base64-encoded token from {@link LDGraphTracker.resumptionToken}.
1405
+ * @param context LDContext to associate with the reconstructed tracker.
1406
+ */
1407
+ createGraphTracker(token: string, context: LDContext): LDGraphTracker;
1013
1408
  }
1014
1409
 
1015
1410
  /**
@@ -1022,6 +1417,46 @@ interface LDClientMin {
1022
1417
  readonly logger?: LDLogger$1;
1023
1418
  }
1024
1419
 
1420
+ /**
1421
+ * Concrete implementation of {@link LDGraphTracker}.
1422
+ *
1423
+ * Construct directly or reconstruct from a resumption token via
1424
+ * {@link LDGraphTrackerImpl.fromResumptionToken}.
1425
+ */
1426
+ declare class LDGraphTrackerImpl implements LDGraphTracker {
1427
+ private readonly _ldClient;
1428
+ private readonly _runId;
1429
+ private readonly _graphKey;
1430
+ private readonly _variationKey;
1431
+ private readonly _version;
1432
+ private readonly _context;
1433
+ private _summary;
1434
+ constructor(_ldClient: LDClientMin, _runId: string, _graphKey: string, _variationKey: string | undefined, _version: number, _context: LDContext);
1435
+ /**
1436
+ * Reconstructs an {@link LDGraphTrackerImpl} from a resumption token, preserving
1437
+ * the original `runId` so all events continue to be correlated under the same run.
1438
+ *
1439
+ * **Security note:** The token contains the flag variation key and version.
1440
+ * Do not pass the raw token to untrusted clients.
1441
+ *
1442
+ * @param token URL-safe Base64-encoded token produced by {@link LDGraphTrackerImpl.resumptionToken}.
1443
+ * @param ldClient LaunchDarkly client instance.
1444
+ * @param context LDContext for the new tracker.
1445
+ */
1446
+ static fromResumptionToken(token: string, ldClient: LDClientMin, context: LDContext): LDGraphTrackerImpl;
1447
+ getTrackData(): LDGraphTrackData;
1448
+ getSummary(): LDGraphMetricSummary;
1449
+ get resumptionToken(): string;
1450
+ trackInvocationSuccess(): void;
1451
+ trackInvocationFailure(): void;
1452
+ trackDuration(durationMs: number): void;
1453
+ trackTotalTokens(tokens: LDTokenUsage): void;
1454
+ trackPath(path: string[]): void;
1455
+ trackRedirect(sourceKey: string, redirectedTarget: string): void;
1456
+ trackHandoffSuccess(sourceKey: string, targetKey: string): void;
1457
+ trackHandoffFailure(sourceKey: string, targetKey: string): void;
1458
+ }
1459
+
1025
1460
  /**
1026
1461
  * This is the API reference for the LaunchDarkly AI SDK for Server-Side JavaScript.
1027
1462
  *
@@ -1039,4 +1474,4 @@ interface LDClientMin {
1039
1474
  declare function initAi(ldClient: LDClientMin): LDAIClient;
1040
1475
  type LDLogger = common.LDLogger;
1041
1476
 
1042
- export { AIProvider, AIProviderFactory, type ChatResponse, type EvalScore, Judge, type JudgeResponse, type LDAIAgentConfig, type LDAIAgentConfigDefault, type LDAIAgentRequestConfig, type LDAIClient, type LDAICompletionConfig, type LDAICompletionConfigDefault, type LDAIConfig, type LDAIConfigDefault, type LDAIConfigDefaultKind, type LDAIConfigKind, type LDAIConfigMode, type LDAIConfigTracker, type LDAIJudgeConfig, type LDAIJudgeConfigDefault, type LDAIMetrics, LDFeedbackKind, type LDJudge, type LDJudgeConfiguration, type LDLogger, type LDMessage, type LDModelConfig, type LDProviderConfig, type LDTokenUsage, SUPPORTED_AI_PROVIDERS, type StructuredResponse, type SupportedAIProvider, TrackedChat, createBedrockTokenUsage, createOpenAiUsage, createVercelAISDKTokenUsage, initAi };
1477
+ export { AIProvider, AIProviderFactory, AgentGraphDefinition, AgentGraphNode, type ChatResponse, Judge, type LDAIAgentConfig, type LDAIAgentConfigDefault, type LDAIAgentRequestConfig, type LDAIClient, type LDAICompletionConfig, type LDAICompletionConfigDefault, type LDAIConfig, type LDAIConfigDefault, type LDAIConfigDefaultKind, type LDAIConfigKind, type LDAIConfigMode, type LDAIConfigTracker, type LDAIJudgeConfig, type LDAIJudgeConfigDefault, type LDAIMetrics, type LDAgentGraphFlagValue, LDFeedbackKind, type LDGraphEdge, type LDGraphMetricSummary, type LDGraphTrackData, type LDGraphTracker, LDGraphTrackerImpl, type LDJudge, type LDJudgeConfiguration, type LDJudgeResult, type LDLogger, type LDMessage, type LDModelConfig, type LDProviderConfig, type LDTokenUsage, SUPPORTED_AI_PROVIDERS, type StructuredResponse, type SupportedAIProvider, TrackedChat, type TraversalFn, createBedrockTokenUsage, createOpenAiUsage, createVercelAISDKTokenUsage, initAi };