@bitfab/sdk 0.38.6 → 0.38.7

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.cjs CHANGED
@@ -42,7 +42,7 @@ var __version__, __packageName__;
42
42
  var init_version_generated = __esm({
43
43
  "src/version.generated.ts"() {
44
44
  "use strict";
45
- __version__ = "0.38.6";
45
+ __version__ = "0.38.7";
46
46
  __packageName__ = "@bitfab/sdk";
47
47
  }
48
48
  });
@@ -498,8 +498,8 @@ function encodePayloadBody(payload) {
498
498
  const marker = { error: `payload_serialize_failed: ${message}` };
499
499
  return { body: JSON.stringify(marker), dropped, value: marker };
500
500
  }
501
- const isRecord = typeof sanitized === "object" && sanitized !== null && !Array.isArray(sanitized);
502
- if (dropped.length > 0 && isRecord) {
501
+ const isRecord2 = typeof sanitized === "object" && sanitized !== null && !Array.isArray(sanitized);
502
+ if (dropped.length > 0 && isRecord2) {
503
503
  const obj = sanitized;
504
504
  const existing = Array.isArray(obj.errors) ? obj.errors : [];
505
505
  obj.errors = [
@@ -516,7 +516,7 @@ function encodePayloadBody(payload) {
516
516
  return {
517
517
  body: JSON.stringify(sanitized),
518
518
  dropped,
519
- value: isRecord ? sanitized : void 0
519
+ value: isRecord2 ? sanitized : void 0
520
520
  };
521
521
  }
522
522
  }
@@ -3132,6 +3132,7 @@ __export(index_exports, {
3132
3132
  BitfabFunction: () => BitfabFunction,
3133
3133
  BitfabLangChainCallbackHandler: () => BitfabLangGraphCallbackHandler,
3134
3134
  BitfabLangGraphCallbackHandler: () => BitfabLangGraphCallbackHandler,
3135
+ BitfabLangGraphIntegration: () => BitfabLangGraphIntegration,
3135
3136
  BitfabOpenAIAgentHandler: () => BitfabOpenAIAgentHandler,
3136
3137
  BitfabOpenAITracingProcessor: () => BitfabOpenAITracingProcessor,
3137
3138
  BitfabVercelAiHandler: () => BitfabVercelAiHandler,
@@ -4456,6 +4457,7 @@ var BitfabLangGraphCallbackHandler = class {
4456
4457
  });
4457
4458
  this.traceFunctionKey = config.traceFunctionKey;
4458
4459
  this.getActiveSpanContext = config.getActiveSpanContext ?? null;
4460
+ this.captureTools = config.captureTools ?? true;
4459
4461
  }
4460
4462
  /**
4461
4463
  * Flush and release the span transport this handler started. A no-op when
@@ -4764,6 +4766,9 @@ var BitfabLangGraphCallbackHandler = class {
4764
4766
  }
4765
4767
  // ── tool callbacks ────────────────────────────────────────────
4766
4768
  async handleToolStart(tool, input, runId, parentRunId, tags, metadata, runName) {
4769
+ if (!this.captureTools) {
4770
+ return;
4771
+ }
4767
4772
  try {
4768
4773
  const serialized = tool ?? {};
4769
4774
  const name = runName ?? serialized.name ?? "tool";
@@ -4780,12 +4785,18 @@ var BitfabLangGraphCallbackHandler = class {
4780
4785
  }
4781
4786
  }
4782
4787
  async handleToolEnd(output, runId) {
4788
+ if (!this.captureTools) {
4789
+ return;
4790
+ }
4783
4791
  try {
4784
4792
  this.completeSpan(runId, output);
4785
4793
  } catch {
4786
4794
  }
4787
4795
  }
4788
4796
  async handleToolError(error, runId) {
4797
+ if (!this.captureTools) {
4798
+ return;
4799
+ }
4789
4800
  try {
4790
4801
  this.completeSpan(
4791
4802
  runId,
@@ -4830,6 +4841,258 @@ var BitfabLangGraphCallbackHandler = class {
4830
4841
  }
4831
4842
  };
4832
4843
 
4844
+ // src/langgraphIntegration.ts
4845
+ init_http();
4846
+ init_replayContext();
4847
+ var TOOL_RESULT_TAG = "__bitfabLangGraphToolResult";
4848
+ function isRecord(value) {
4849
+ return typeof value === "object" && value !== null;
4850
+ }
4851
+ function isToolMessage(value) {
4852
+ return isRecord(value) && value.lc_direct_tool_output === true && value.type === "tool" && (typeof value.content === "string" || Array.isArray(value.content));
4853
+ }
4854
+ function isCommand(value) {
4855
+ return isRecord(value) && value.lg_name === "Command";
4856
+ }
4857
+ function encodeNested(value) {
4858
+ if (isToolMessage(value) || isCommand(value)) {
4859
+ return encodeNativeToolResult(value);
4860
+ }
4861
+ if (Array.isArray(value)) {
4862
+ return value.map(encodeNested);
4863
+ }
4864
+ if (isRecord(value)) {
4865
+ return Object.fromEntries(
4866
+ Object.entries(value).map(([key, entry]) => [key, encodeNested(entry)])
4867
+ );
4868
+ }
4869
+ return value;
4870
+ }
4871
+ function encodeNativeToolResult(value) {
4872
+ if (isToolMessage(value)) {
4873
+ return {
4874
+ [TOOL_RESULT_TAG]: "tool-message",
4875
+ content: value.content,
4876
+ name: typeof value.name === "string" ? value.name : void 0,
4877
+ id: typeof value.id === "string" ? value.id : void 0,
4878
+ status: value.status === "success" || value.status === "error" ? value.status : void 0,
4879
+ artifact: encodeNested(value.artifact),
4880
+ metadata: encodeNested(value.metadata),
4881
+ additionalKwargs: encodeNested(value.additional_kwargs),
4882
+ responseMetadata: encodeNested(value.response_metadata)
4883
+ };
4884
+ }
4885
+ return {
4886
+ [TOOL_RESULT_TAG]: "command",
4887
+ graph: isRecord(value) && typeof value.graph === "string" ? value.graph : void 0,
4888
+ update: isRecord(value) ? encodeNested(value.update) : void 0,
4889
+ resume: isRecord(value) ? encodeNested(value.resume) : void 0,
4890
+ goto: isRecord(value) ? encodeNested(value.goto) : void 0
4891
+ };
4892
+ }
4893
+ function finalizeToolResult(value) {
4894
+ return isToolMessage(value) || isCommand(value) ? encodeNativeToolResult(value) : value;
4895
+ }
4896
+ function isEncodedToolResult(value) {
4897
+ return isRecord(value) && typeof value[TOOL_RESULT_TAG] === "string";
4898
+ }
4899
+ async function loadLangChainCore() {
4900
+ try {
4901
+ return await importOptionalPeer([
4902
+ "@langchain",
4903
+ "core",
4904
+ "messages"
4905
+ ]);
4906
+ } catch {
4907
+ throw new BitfabError(
4908
+ "LangGraph tool replay requires @langchain/core. Install @langchain/langgraph before using getLangGraphIntegration().",
4909
+ "https://docs.bitfab.ai/frameworks/langgraph"
4910
+ );
4911
+ }
4912
+ }
4913
+ async function loadLangGraph() {
4914
+ try {
4915
+ return await importOptionalPeer([
4916
+ "@langchain",
4917
+ "langgraph"
4918
+ ]);
4919
+ } catch {
4920
+ throw new BitfabError(
4921
+ "Replaying a LangGraph Command requires @langchain/langgraph.",
4922
+ "https://docs.bitfab.ai/frameworks/langgraph"
4923
+ );
4924
+ }
4925
+ }
4926
+ async function reviveNested(value, toolCallId) {
4927
+ if (isEncodedToolResult(value)) {
4928
+ return reviveToolResult(value, toolCallId);
4929
+ }
4930
+ if (Array.isArray(value)) {
4931
+ return Promise.all(value.map((entry) => reviveNested(entry, toolCallId)));
4932
+ }
4933
+ if (isRecord(value)) {
4934
+ const entries = await Promise.all(
4935
+ Object.entries(value).map(async ([key, entry]) => [
4936
+ key,
4937
+ await reviveNested(entry, toolCallId)
4938
+ ])
4939
+ );
4940
+ return Object.fromEntries(entries);
4941
+ }
4942
+ return value;
4943
+ }
4944
+ async function reviveToolResult(value, toolCallId) {
4945
+ if (value[TOOL_RESULT_TAG] === "tool-message") {
4946
+ const { ToolMessage } = await loadLangChainCore();
4947
+ return new ToolMessage({
4948
+ content: value.content,
4949
+ tool_call_id: toolCallId,
4950
+ ...typeof value.name === "string" && { name: value.name },
4951
+ ...typeof value.id === "string" && { id: value.id },
4952
+ ...(value.status === "success" || value.status === "error") && {
4953
+ status: value.status
4954
+ },
4955
+ ...value.artifact !== void 0 && {
4956
+ artifact: await reviveNested(value.artifact, toolCallId)
4957
+ },
4958
+ ...isRecord(value.metadata) && {
4959
+ metadata: await reviveNested(value.metadata, toolCallId)
4960
+ },
4961
+ ...isRecord(value.additionalKwargs) && {
4962
+ additional_kwargs: await reviveNested(
4963
+ value.additionalKwargs,
4964
+ toolCallId
4965
+ )
4966
+ },
4967
+ ...isRecord(value.responseMetadata) && {
4968
+ response_metadata: await reviveNested(
4969
+ value.responseMetadata,
4970
+ toolCallId
4971
+ )
4972
+ }
4973
+ });
4974
+ }
4975
+ const { Command } = await loadLangGraph();
4976
+ return new Command({
4977
+ ...typeof value.graph === "string" && { graph: value.graph },
4978
+ ...value.update !== void 0 && {
4979
+ update: await reviveNested(value.update, toolCallId)
4980
+ },
4981
+ ...value.resume !== void 0 && {
4982
+ resume: await reviveNested(value.resume, toolCallId)
4983
+ },
4984
+ ...value.goto !== void 0 && {
4985
+ goto: await reviveNested(value.goto, toolCallId)
4986
+ }
4987
+ });
4988
+ }
4989
+ var BitfabLangGraphIntegration = class {
4990
+ constructor(config) {
4991
+ this.client = config.client;
4992
+ this.traceFunctionKey = config.traceFunctionKey;
4993
+ this.callbackHandler = config.callbackHandler;
4994
+ this.mockToolsOnReplay = config.options?.mockToolsOnReplay ?? true;
4995
+ }
4996
+ /**
4997
+ * Wrap tools before passing the same returned array to both
4998
+ * `model.bindTools()` and `new ToolNode()`. Each invocation becomes an
4999
+ * independently mockable child span.
5000
+ */
5001
+ wrapTools(tools) {
5002
+ return tools.map((tool) => this.wrapTool(tool));
5003
+ }
5004
+ /**
5005
+ * Create the normal graph entry point. The returned function adds Bitfab's
5006
+ * callback handler, preserves invocation config, and records only the graph
5007
+ * input as the replayable root input.
5008
+ *
5009
+ * @experimental This API may change before it is stable.
5010
+ */
5011
+ createInvoker(graph) {
5012
+ const configuredGraph = graph.withConfig({
5013
+ callbacks: [this.callbackHandler]
5014
+ });
5015
+ return (input, config) => {
5016
+ const invoke = this.wrapInvoke(
5017
+ (rootInput) => configuredGraph.invoke(rootInput, config)
5018
+ );
5019
+ return invoke(input);
5020
+ };
5021
+ }
5022
+ wrapTool(tool) {
5023
+ const toolName = tool.name;
5024
+ if (typeof toolName !== "string" || toolName.length === 0) {
5025
+ throw new BitfabError(
5026
+ "LangGraph replayable tools must have a name.",
5027
+ "https://docs.bitfab.ai/frameworks/langgraph"
5028
+ );
5029
+ }
5030
+ const mockToolsOnReplay = this.mockToolsOnReplay;
5031
+ const shouldMock = typeof mockToolsOnReplay === "boolean" ? mockToolsOnReplay : mockToolsOnReplay.includes(toolName);
5032
+ const originalInvoke = tool.invoke.bind(tool);
5033
+ return new Proxy(tool, {
5034
+ get: (target, property) => {
5035
+ if (property === "invoke") {
5036
+ return async (input, ...rest) => {
5037
+ const toolCallId = isRecord(input) && typeof input.id === "string" ? input.id : "";
5038
+ const args = isRecord(input) && "args" in input ? input.args : input;
5039
+ this.assertReplayToolResultExists(toolName, shouldMock);
5040
+ const execute = this.client.withSpan(
5041
+ this.traceFunctionKey,
5042
+ {
5043
+ name: toolName,
5044
+ type: "function",
5045
+ captureWhen: "nested",
5046
+ mockOnReplay: shouldMock,
5047
+ finalize: finalizeToolResult
5048
+ },
5049
+ async (_args) => await originalInvoke(input, ...rest)
5050
+ );
5051
+ const result = await execute(args);
5052
+ return isEncodedToolResult(result) ? await reviveToolResult(result, toolCallId) : result;
5053
+ };
5054
+ }
5055
+ const value = Reflect.get(target, property, target);
5056
+ return typeof value === "function" ? value.bind(target) : value;
5057
+ }
5058
+ });
5059
+ }
5060
+ assertReplayToolResultExists(toolName, shouldMock) {
5061
+ const replayContext = getReplayContext();
5062
+ if (!replayContext?.mockTree) {
5063
+ return;
5064
+ }
5065
+ const counterKey = `${this.traceFunctionKey}:${toolName}`;
5066
+ const callIndex = replayContext.callCounters?.get(counterKey) ?? 0;
5067
+ const mockSpan = replayContext.mockTree.spans.get(
5068
+ `${counterKey}:${callIndex}`
5069
+ );
5070
+ const hasMatchingOverride = replayContext.mockOverrides?.some(
5071
+ (override) => override.match({
5072
+ traceFunctionKey: this.traceFunctionKey,
5073
+ spanName: toolName,
5074
+ type: "function",
5075
+ originalSpanId: mockSpan?.sourceSpanId
5076
+ })
5077
+ );
5078
+ const expectsRecordedOutput = replayContext.mockStrategy === "all" || replayContext.mockStrategy === "marked" && shouldMock;
5079
+ if (hasMatchingOverride !== true && expectsRecordedOutput && !mockSpan) {
5080
+ throw new BitfabError(
5081
+ `No recorded LangGraph tool result for "${toolName}" at call ${callIndex + 1}; refusing to execute the live tool during replay.`,
5082
+ "https://docs.bitfab.ai/frameworks/langgraph"
5083
+ );
5084
+ }
5085
+ }
5086
+ /** Wrap the function that invokes the compiled graph as the replay root. */
5087
+ wrapInvoke(fn) {
5088
+ return this.client.withSpan(
5089
+ this.traceFunctionKey,
5090
+ { name: this.traceFunctionKey, type: "agent" },
5091
+ fn
5092
+ );
5093
+ }
5094
+ };
5095
+
4833
5096
  // src/client.ts
4834
5097
  init_mockOverride();
4835
5098
 
@@ -6220,6 +6483,37 @@ var Bitfab = class {
6220
6483
  getLangChainCallbackHandler(traceFunctionKey) {
6221
6484
  return this.getLangGraphCallbackHandler(traceFunctionKey);
6222
6485
  }
6486
+ /**
6487
+ * Get the first-class LangGraph integration for tracing and replaying tools
6488
+ * executed by `ToolNode`.
6489
+ *
6490
+ * The integration combines `wrapTools()` for per-tool replay interception
6491
+ * with `createInvoker()` for a callback-configured replayable graph entry
6492
+ * point. Lower-level callback and root wrappers remain available.
6493
+ *
6494
+ * @param traceFunctionKey - Groups traces under this key in Bitfab
6495
+ * @param options - Controls which tools are marked for replay mocking
6496
+ * @experimental This API may change before it is stable.
6497
+ */
6498
+ getLangGraphIntegration(traceFunctionKey, options) {
6499
+ const callbackHandler = new BitfabLangGraphCallbackHandler({
6500
+ apiKey: this.resolveApiKey(),
6501
+ traceFunctionKey,
6502
+ serviceUrl: this.serviceUrl,
6503
+ getActiveSpanContext: () => {
6504
+ const stack = getSpanStack();
6505
+ return stack[stack.length - 1] ?? null;
6506
+ },
6507
+ captureTools: false,
6508
+ _httpClient: this.httpClient
6509
+ });
6510
+ return new BitfabLangGraphIntegration({
6511
+ client: this,
6512
+ traceFunctionKey,
6513
+ callbackHandler,
6514
+ options
6515
+ });
6516
+ }
6223
6517
  /**
6224
6518
  * Get a Claude Agent SDK handler for tracing.
6225
6519
  *
@@ -7250,6 +7544,14 @@ var BitfabFunction = class {
7250
7544
  getLangChainCallbackHandler() {
7251
7545
  return this.client.getLangChainCallbackHandler(this.traceFunctionKey);
7252
7546
  }
7547
+ /**
7548
+ * Get the first-class LangGraph tool replay integration bound to this key.
7549
+ *
7550
+ * @experimental This API may change before it is stable.
7551
+ */
7552
+ getLangGraphIntegration(options) {
7553
+ return this.client.getLangGraphIntegration(this.traceFunctionKey, options);
7554
+ }
7253
7555
  /**
7254
7556
  * Wrap a BAML client method to automatically capture prompt and LLM metadata.
7255
7557
  * Delegates to the parent client's wrapBAML method.
@@ -7345,6 +7647,7 @@ function defineReplayRegistry(registry) {
7345
7647
  BitfabFunction,
7346
7648
  BitfabLangChainCallbackHandler,
7347
7649
  BitfabLangGraphCallbackHandler,
7650
+ BitfabLangGraphIntegration,
7348
7651
  BitfabOpenAIAgentHandler,
7349
7652
  BitfabOpenAITracingProcessor,
7350
7653
  BitfabVercelAiHandler,