bitfab 0.68.0 → 0.68.2

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 (56) hide show
  1. package/dist/{autoTrace-BikML0lX.cjs → autoTrace-D3-OZcmR.cjs} +196 -17
  2. package/dist/autoTrace-D3-OZcmR.cjs.map +1 -0
  3. package/dist/{autoTrace-CVt9EDyo.js → autoTrace-ghnojSj9.js} +173 -18
  4. package/dist/autoTrace-ghnojSj9.js.map +1 -0
  5. package/dist/autoTrace.cjs +2 -1
  6. package/dist/autoTrace.d.cts +15 -0
  7. package/dist/autoTrace.d.ts +15 -0
  8. package/dist/autoTrace.js +1 -1
  9. package/dist/{babelPlugin-s8EFjT6e.cjs → babelPlugin-0uOq-j1Q.cjs} +48 -18
  10. package/dist/babelPlugin-0uOq-j1Q.cjs.map +1 -0
  11. package/dist/{babelPlugin-a7ofCoOd.js → babelPlugin-Muq0uuuu.js} +48 -18
  12. package/dist/babelPlugin-Muq0uuuu.js.map +1 -0
  13. package/dist/{http-_cgR_DM2.js → http-Cs_vVjrS.js} +3 -3
  14. package/dist/http-Cs_vVjrS.js.map +1 -0
  15. package/dist/{http-psFF1ptn.cjs → http-Dqc-f3sp.cjs} +3 -3
  16. package/dist/http-Dqc-f3sp.cjs.map +1 -0
  17. package/dist/{index-j7SrvOqe.d.cts → index-Cmrec4hc.d.cts} +238 -5
  18. package/dist/{index-j7SrvOqe.d.ts → index-Cmrec4hc.d.ts} +238 -5
  19. package/dist/index.cjs +2 -2
  20. package/dist/index.d.cts +2 -2
  21. package/dist/index.d.ts +2 -2
  22. package/dist/index.js +2 -2
  23. package/dist/node.cjs +3 -3
  24. package/dist/node.d.cts +2 -2
  25. package/dist/node.d.ts +2 -2
  26. package/dist/node.js +3 -3
  27. package/dist/registryCommand-Dk4Y1ZgW.js.map +1 -1
  28. package/dist/{src-DyEKM7yn.js → src-BF95TP1K.js} +494 -87
  29. package/dist/src-BF95TP1K.js.map +1 -0
  30. package/dist/{src-Dze8o7iU.cjs → src-CdQRfsrA.cjs} +494 -87
  31. package/dist/src-CdQRfsrA.cjs.map +1 -0
  32. package/dist/transform/babel.cjs +1 -1
  33. package/dist/transform/babel.d.cts +9 -2
  34. package/dist/transform/babel.d.ts +9 -2
  35. package/dist/transform/babel.js +1 -1
  36. package/dist/transform/loaderRuntime.cjs +2 -2
  37. package/dist/transform/loaderRuntime.js +2 -2
  38. package/dist/transform/nodeLoader.js +47 -17
  39. package/dist/transform/nodeLoader.js.map +1 -1
  40. package/dist/transform/swc.cjs +1 -1
  41. package/dist/transform/swc.js +1 -1
  42. package/dist/transform/unplugin.cjs +2 -2
  43. package/dist/transform/unplugin.js +2 -2
  44. package/dist/{transform-DkcFn_tg.js → transform-CAJyLLe2.js} +2 -2
  45. package/dist/{transform-DkcFn_tg.js.map → transform-CAJyLLe2.js.map} +1 -1
  46. package/dist/{transform-BBzrqpVH.cjs → transform-ClCOpCZ2.cjs} +2 -2
  47. package/dist/{transform-BBzrqpVH.cjs.map → transform-ClCOpCZ2.cjs.map} +1 -1
  48. package/package.json +13 -2
  49. package/dist/autoTrace-BikML0lX.cjs.map +0 -1
  50. package/dist/autoTrace-CVt9EDyo.js.map +0 -1
  51. package/dist/babelPlugin-a7ofCoOd.js.map +0 -1
  52. package/dist/babelPlugin-s8EFjT6e.cjs.map +0 -1
  53. package/dist/http-_cgR_DM2.js.map +0 -1
  54. package/dist/http-psFF1ptn.cjs.map +0 -1
  55. package/dist/src-DyEKM7yn.js.map +0 -1
  56. package/dist/src-Dze8o7iU.cjs.map +0 -1
@@ -1,6 +1,6 @@
1
1
  const require_bamlPeer = require("./bamlPeer-BUoZgNxZ.cjs");
2
- const require_http = require("./http-psFF1ptn.cjs");
3
- const require_autoTrace = require("./autoTrace-BikML0lX.cjs");
2
+ const require_http = require("./http-Dqc-f3sp.cjs");
3
+ const require_autoTrace = require("./autoTrace-D3-OZcmR.cjs");
4
4
  let superjson = require("superjson");
5
5
  superjson = require_bamlPeer.__toESM(superjson, 1);
6
6
  //#region src/categories.ts
@@ -1411,11 +1411,11 @@ var GradersClient = class {
1411
1411
  const JEV_PROVIDER = "typesafe";
1412
1412
  const JEV_WATCH_STORAGE_SYMBOL = Symbol.for("bitfab.jevWatchStorage");
1413
1413
  const repliesRecordedByAutoTrace = /* @__PURE__ */ new WeakSet();
1414
- function isRecord$3(value) {
1414
+ function isRecord$4(value) {
1415
1415
  return typeof value === "object" && value !== null;
1416
1416
  }
1417
1417
  function isJevReply(value) {
1418
- return isRecord$3(value) && typeof value.model === "string" && isRecord$3(value.usage);
1418
+ return isRecord$4(value) && typeof value.model === "string" && isRecord$4(value.usage);
1419
1419
  }
1420
1420
  function tokenCount(usage, key) {
1421
1421
  const count = usage[key];
@@ -1474,7 +1474,7 @@ function recordWatchedJevReply(span, watch, reply, durationMs) {
1474
1474
  markEnclosingWatches(watch);
1475
1475
  }
1476
1476
  function isRecordedByAutoTrace(reply) {
1477
- return isRecord$3(reply) && repliesRecordedByAutoTrace.has(reply);
1477
+ return isRecord$4(reply) && repliesRecordedByAutoTrace.has(reply);
1478
1478
  }
1479
1479
  function recordAutoTracedJev(invokeFn, span) {
1480
1480
  const startedAt = Date.now();
@@ -1492,6 +1492,22 @@ function recordAutoTracedJev(invokeFn, span) {
1492
1492
  //#endregion
1493
1493
  //#region src/langgraph.ts
1494
1494
  const LANGSMITH_HIDDEN_TAG = "langsmith:hidden";
1495
+ function toolCallClaim(traceId, toolCallId) {
1496
+ return `${traceId}\u0000${toolCallId}`;
1497
+ }
1498
+ var OutermostRunOutput = class {
1499
+ constructor() {
1500
+ this.name = "BitfabOutermostRunOutput";
1501
+ this.awaitHandlers = true;
1502
+ this.output = void 0;
1503
+ }
1504
+ handleChainStart(_chain, _inputs, runId) {
1505
+ this.runId ?? (this.runId = runId);
1506
+ }
1507
+ handleChainEnd(outputs, runId) {
1508
+ if (runId === this.runId) this.output = outputs;
1509
+ }
1510
+ };
1495
1511
  const CHAIN_RUN_TYPES = /* @__PURE__ */ new Set([
1496
1512
  "chain",
1497
1513
  "parser",
@@ -1661,11 +1677,15 @@ function extractLangGraphMetadata(metadata) {
1661
1677
  var BitfabLangGraphCallbackHandler = class {
1662
1678
  constructor(config) {
1663
1679
  this.name = "BitfabLangGraphCallbackHandler";
1680
+ this.awaitHandlers = true;
1664
1681
  this.ignoreRetry = true;
1665
1682
  this.ignoreRetriever = false;
1666
1683
  this.ignoreCustomEvent = true;
1667
1684
  this.runToSpan = /* @__PURE__ */ new Map();
1668
1685
  this.invocations = /* @__PURE__ */ new Map();
1686
+ this.claimedToolCalls = /* @__PURE__ */ new Set();
1687
+ this.stepRunIdByNamespace = /* @__PURE__ */ new Map();
1688
+ this.namespaceByStepRunId = /* @__PURE__ */ new Map();
1669
1689
  this.ownsHttpClient = config._httpClient === void 0;
1670
1690
  this.httpClient = config._httpClient ?? new require_http.HttpClient({
1671
1691
  apiKey: config.apiKey,
@@ -1680,6 +1700,37 @@ var BitfabLangGraphCallbackHandler = class {
1680
1700
  async close(timeoutMs) {
1681
1701
  return this.ownsHttpClient ? this.httpClient.close(timeoutMs) : true;
1682
1702
  }
1703
+ claimToolCall(traceId, toolCallId) {
1704
+ const claim = toolCallClaim(traceId, toolCallId);
1705
+ this.claimedToolCalls.add(claim);
1706
+ return () => {
1707
+ this.claimedToolCalls.delete(claim);
1708
+ };
1709
+ }
1710
+ visibleStepSpanId(checkpointNamespace, traceId) {
1711
+ const runId = this.stepRunIdByNamespace.get(checkpointNamespace);
1712
+ let span = runId === void 0 ? void 0 : this.runToSpan.get(runId);
1713
+ while (span?.hidden === true) span = span.parentId ? this.runToSpan.get(span.parentId) : void 0;
1714
+ return span !== void 0 && span.traceId === traceId ? span.spanId : null;
1715
+ }
1716
+ isClaimedToolCall(parentRunId, toolCallId) {
1717
+ if (toolCallId === void 0) return false;
1718
+ const traceId = (parentRunId ? this.runToSpan.get(parentRunId)?.traceId : void 0) ?? this.getActiveSpanContext?.()?.traceId;
1719
+ return traceId !== void 0 && this.claimedToolCalls.has(toolCallClaim(traceId, toolCallId));
1720
+ }
1721
+ rememberStep(runId, metadata) {
1722
+ const namespace = metadata?.langgraph_checkpoint_ns;
1723
+ if (typeof namespace === "string") {
1724
+ this.stepRunIdByNamespace.set(namespace, runId);
1725
+ this.namespaceByStepRunId.set(runId, namespace);
1726
+ }
1727
+ }
1728
+ forgetStep(runId) {
1729
+ const namespace = this.namespaceByStepRunId.get(runId);
1730
+ if (namespace === void 0) return;
1731
+ this.namespaceByStepRunId.delete(runId);
1732
+ if (this.stepRunIdByNamespace.get(namespace) === runId) this.stepRunIdByNamespace.delete(namespace);
1733
+ }
1683
1734
  startSpan(runId, parentRunId, name, spanType, inputData, metadata, tags) {
1684
1735
  const parentSpan = parentRunId ? this.runToSpan.get(parentRunId) : void 0;
1685
1736
  const willHide = tags?.includes(LANGSMITH_HIDDEN_TAG) === true;
@@ -1828,15 +1879,18 @@ var BitfabLangGraphCallbackHandler = class {
1828
1879
  const idArr = serialized.id;
1829
1880
  const name = runName ?? serialized.name ?? idArr?.[idArr.length - 1] ?? "chain";
1830
1881
  this.startSpan(runId, parentRunId, String(name), "agent", inputs, metadata, tags);
1882
+ this.rememberStep(runId, metadata);
1831
1883
  } catch {}
1832
1884
  }
1833
1885
  async handleChainEnd(outputs, runId) {
1834
1886
  try {
1887
+ this.forgetStep(runId);
1835
1888
  this.completeSpan(runId, outputs);
1836
1889
  } catch {}
1837
1890
  }
1838
1891
  async handleChainError(error, runId) {
1839
1892
  try {
1893
+ this.forgetStep(runId);
1840
1894
  if (error?.constructor?.name === "GraphBubbleUp") {
1841
1895
  this.completeSpan(runId, void 0, void 0);
1842
1896
  return;
@@ -1888,8 +1942,8 @@ var BitfabLangGraphCallbackHandler = class {
1888
1942
  } catch {}
1889
1943
  }
1890
1944
  async handleLLMNewToken() {}
1891
- async handleToolStart(tool, input, runId, parentRunId, tags, metadata, runName) {
1892
- if (!this.captureTools) return;
1945
+ async handleToolStart(tool, input, runId, parentRunId, tags, metadata, runName, toolCallId) {
1946
+ if (!this.captureTools || this.isClaimedToolCall(parentRunId, toolCallId)) return;
1893
1947
  try {
1894
1948
  const name = runName ?? (tool ?? {}).name ?? "tool";
1895
1949
  this.startSpan(runId, parentRunId, String(name), "function", input, metadata, tags);
@@ -1925,21 +1979,232 @@ var BitfabLangGraphCallbackHandler = class {
1925
1979
  }
1926
1980
  };
1927
1981
  //#endregion
1982
+ //#region src/integrationFixture.ts
1983
+ const INTEGRATION_FIXTURE_CONTEXT_KEY = "__bitfabIntegrationFixture";
1984
+ const INTEGRATION_FIXTURE_VERSION = 1;
1985
+ function isRecord$3(value) {
1986
+ return typeof value === "object" && value !== null && !Array.isArray(value);
1987
+ }
1988
+ function createIntegrationFixtureContext(name, value) {
1989
+ const serialized = serializeValue(value);
1990
+ return { [INTEGRATION_FIXTURE_CONTEXT_KEY]: {
1991
+ version: INTEGRATION_FIXTURE_VERSION,
1992
+ name,
1993
+ value: serialized.json,
1994
+ ...serialized.meta !== void 0 && { valueMeta: serialized.meta }
1995
+ } };
1996
+ }
1997
+ function extractIntegrationFixtures(spanData) {
1998
+ const contexts = spanData.contexts;
1999
+ if (!Array.isArray(contexts)) return;
2000
+ const fixtures = /* @__PURE__ */ new Map();
2001
+ for (const context of contexts) {
2002
+ if (!isRecord$3(context)) continue;
2003
+ const fixture = context[INTEGRATION_FIXTURE_CONTEXT_KEY];
2004
+ if (!isRecord$3(fixture) || fixture.version !== INTEGRATION_FIXTURE_VERSION || typeof fixture.name !== "string") continue;
2005
+ fixtures.set(fixture.name, deserializeValue({
2006
+ json: fixture.value,
2007
+ ...fixture.valueMeta !== void 0 && { meta: fixture.valueMeta }
2008
+ }));
2009
+ }
2010
+ return fixtures.size > 0 ? fixtures : void 0;
2011
+ }
2012
+ //#endregion
2013
+ //#region src/langgraphRuns.ts
2014
+ function threadFixtureName(traceFunctionKey) {
2015
+ return `langgraph-thread:${traceFunctionKey}`;
2016
+ }
2017
+ const CHECKPOINTER_CONFIG_KEY = "__pregel_checkpointer";
2018
+ const THREAD_CONFIG_KEYS = [
2019
+ "thread_id",
2020
+ "checkpoint_ns",
2021
+ "checkpoint_id"
2022
+ ];
2023
+ function isRecord$2(value) {
2024
+ return typeof value === "object" && value !== null;
2025
+ }
2026
+ function toBase64(bytes) {
2027
+ const buffer = globalThis.Buffer;
2028
+ if (buffer !== void 0) return buffer.from(bytes).toString("base64");
2029
+ let binary = "";
2030
+ for (const byte of bytes) binary += String.fromCharCode(byte);
2031
+ return btoa(binary);
2032
+ }
2033
+ function fromBase64(text) {
2034
+ const buffer = globalThis.Buffer;
2035
+ if (buffer !== void 0) return new Uint8Array(buffer.from(text, "base64"));
2036
+ return Uint8Array.from(atob(text), (char) => char.charCodeAt(0));
2037
+ }
2038
+ async function newMemorySaver() {
2039
+ try {
2040
+ const { MemorySaver } = await require_bamlPeer.importOptionalPeer(["@langchain", "langgraph"]);
2041
+ return new MemorySaver();
2042
+ } catch {
2043
+ throw new require_http.BitfabError("Restoring a LangGraph thread during replay requires @langchain/langgraph.", "https://docs.bitfab.ai/frameworks/langgraph");
2044
+ }
2045
+ }
2046
+ function savingCheckpointer(graph) {
2047
+ const own = isRecord$2(graph) ? graph.checkpointer : void 0;
2048
+ const inner = isRecord$2(graph) && isRecord$2(graph.graph) ? graph.graph.checkpointer : void 0;
2049
+ const checkpointer = own ?? inner;
2050
+ return isRecord$2(checkpointer) && typeof checkpointer.getTuple === "function" ? checkpointer : null;
2051
+ }
2052
+ function threadConfig(config) {
2053
+ const configurable = isRecord$2(config?.configurable) ? config.configurable : {};
2054
+ return Object.fromEntries(THREAD_CONFIG_KEYS.filter((key) => key in configurable).map((key) => [key, configurable[key]]));
2055
+ }
2056
+ function withConfigurable(config, values) {
2057
+ return {
2058
+ ...config ?? {},
2059
+ configurable: {
2060
+ ...isRecord$2(config?.configurable) ? config.configurable : {},
2061
+ ...values
2062
+ }
2063
+ };
2064
+ }
2065
+ async function encodeTyped(saver, value) {
2066
+ const [type, data] = await saver.serde.dumpsTyped(value);
2067
+ return [type, toBase64(data)];
2068
+ }
2069
+ async function decodeTyped(saver, [type, data]) {
2070
+ return saver.serde.loadsTyped(type, fromBase64(data));
2071
+ }
2072
+ async function encodeCheckpoint(tuple) {
2073
+ if (tuple === void 0) return null;
2074
+ const saver = await newMemorySaver();
2075
+ return {
2076
+ config: threadConfig(tuple.config),
2077
+ checkpoint: await encodeTyped(saver, tuple.checkpoint),
2078
+ metadata: await encodeTyped(saver, tuple.metadata ?? {}),
2079
+ pendingWrites: await Promise.all((tuple.pendingWrites ?? []).map(async ([taskId, channel, value]) => [
2080
+ taskId,
2081
+ channel,
2082
+ await encodeTyped(saver, value)
2083
+ ]))
2084
+ };
2085
+ }
2086
+ async function restoredCheckpointer(recorded) {
2087
+ const saver = await newMemorySaver();
2088
+ if (recorded === null) return {
2089
+ saver,
2090
+ thread: {}
2091
+ };
2092
+ const checkpoint = await decodeTyped(saver, recorded.checkpoint);
2093
+ const saved = await saver.put({ configurable: {
2094
+ thread_id: recorded.config.thread_id,
2095
+ checkpoint_ns: recorded.config.checkpoint_ns ?? ""
2096
+ } }, checkpoint, await decodeTyped(saver, recorded.metadata), checkpoint.channel_versions ?? {});
2097
+ const writesByTask = /* @__PURE__ */ new Map();
2098
+ for (const [taskId, channel, value] of recorded.pendingWrites) writesByTask.set(taskId, [...writesByTask.get(taskId) ?? [], [channel, await decodeTyped(saver, value)]]);
2099
+ for (const [taskId, writes] of writesByTask) await saver.putWrites(saved, writes, taskId);
2100
+ return {
2101
+ saver,
2102
+ thread: recorded.config
2103
+ };
2104
+ }
2105
+ var GraphRun = class {
2106
+ constructor(host, graph, config) {
2107
+ this.host = host;
2108
+ this.graph = graph;
2109
+ this.config = config;
2110
+ this.finalState = new OutermostRunOutput();
2111
+ this.traced = graph.withConfig({ callbacks: [host.callbackHandler, this.finalState] });
2112
+ const active = host.activeSpan();
2113
+ this.opensRoot = active?.rootTraceFunctionKey !== host.traceFunctionKey;
2114
+ this.replaysFromRoot = !this.opensRoot && active?.isRoot === true && require_http.getReplayContext() !== null;
2115
+ }
2116
+ invoke(input) {
2117
+ if (this.replaysFromRoot) return this.replayConfig().then(async ({ config, confirm }) => {
2118
+ const result = await this.traced.invoke(await this.host.reviveRootInput(input), config);
2119
+ await confirm();
2120
+ return result;
2121
+ });
2122
+ if (!this.opensRoot) return this.host.reviveRootInput(input).then((rootInput) => this.traced.invoke(rootInput, this.config));
2123
+ return this.host.rootSpan(async (rootInput) => {
2124
+ await this.recordCheckpoint();
2125
+ return this.traced.invoke(await this.host.reviveRootInput(rootInput), this.config);
2126
+ })(this.host.encodeRootInput(input));
2127
+ }
2128
+ stream(input) {
2129
+ return this.chunks(input, async (rootInput, config) => this.traced.stream(rootInput, config));
2130
+ }
2131
+ streamEvents(input, streamOptions) {
2132
+ return this.chunks(input, async (rootInput, config) => this.traced.streamEvents(rootInput, config, streamOptions));
2133
+ }
2134
+ chunks(input, open) {
2135
+ const { host, finalState } = this;
2136
+ if (this.replaysFromRoot) {
2137
+ const replayConfig = () => this.replayConfig();
2138
+ return (async function* replayChunks() {
2139
+ const { config, confirm } = await replayConfig();
2140
+ yield* await open(await host.reviveRootInput(input), config);
2141
+ await confirm();
2142
+ const replay = require_http.getReplayContext();
2143
+ if (replay !== null) replay.streamResult = finalState.output;
2144
+ })();
2145
+ }
2146
+ if (!this.opensRoot) {
2147
+ const config = this.config;
2148
+ return (async function* nestedChunks() {
2149
+ yield* await open(await host.reviveRootInput(input), config);
2150
+ })();
2151
+ }
2152
+ const config = this.config;
2153
+ const recordCheckpoint = () => this.recordCheckpoint();
2154
+ return host.rootSpan(async function* rootChunks(rootInput) {
2155
+ await recordCheckpoint();
2156
+ yield* await open(await host.reviveRootInput(rootInput), config);
2157
+ }, () => finalState.output)(host.encodeRootInput(input));
2158
+ }
2159
+ async recordCheckpoint() {
2160
+ const checkpointer = savingCheckpointer(this.graph);
2161
+ const thread = threadConfig(this.config);
2162
+ if (checkpointer === null || thread.thread_id === void 0) return;
2163
+ const encoded = await encodeCheckpoint(await checkpointer.getTuple({ configurable: thread }));
2164
+ if (encoded !== null) this.host.addRootContext(createIntegrationFixtureContext(threadFixtureName(this.host.traceFunctionKey), encoded));
2165
+ }
2166
+ async replayConfig() {
2167
+ if (savingCheckpointer(this.graph) === null) return {
2168
+ config: this.config,
2169
+ confirm: async () => {}
2170
+ };
2171
+ const { saver, thread } = await restoredCheckpointer(require_http.getReplayContext()?.integrationFixtures?.get(threadFixtureName(this.host.traceFunctionKey)) ?? null);
2172
+ const configurable = isRecord$2(this.config?.configurable) ? this.config.configurable : {};
2173
+ const replayThread = {
2174
+ thread_id: thread.thread_id ?? configurable.thread_id ?? `bitfab-replay-${randomUuid()}`,
2175
+ ...thread.checkpoint_ns !== void 0 && { checkpoint_ns: thread.checkpoint_ns }
2176
+ };
2177
+ const restoredId = (await saver.getTuple({ configurable: replayThread }))?.checkpoint.id;
2178
+ const confirm = async () => {
2179
+ const latest = await saver.getTuple({ configurable: replayThread });
2180
+ if (latest === void 0 || latest.checkpoint.id === restoredId) require_autoTrace.warnOnce("langgraph-replay-checkpointer-not-lent", "LangGraph did not use the in-memory checkpointer Bitfab lent to a replayed run, so the run may have read and written the graph's own checkpointer. Check that your @langchain/langgraph version still lends a checkpointer through the run config.");
2181
+ };
2182
+ return {
2183
+ config: withConfigurable(this.config, {
2184
+ ...replayThread,
2185
+ [CHECKPOINTER_CONFIG_KEY]: saver
2186
+ }),
2187
+ confirm
2188
+ };
2189
+ }
2190
+ };
2191
+ //#endregion
1928
2192
  //#region src/langgraphIntegration.ts
1929
2193
  const TOOL_RESULT_TAG = "__bitfabLangGraphToolResult";
1930
- function isRecord$2(value) {
2194
+ const AGENT_MIDDLEWARE_BRAND = Symbol.for("AgentMiddleware");
2195
+ function isRecord$1(value) {
1931
2196
  return typeof value === "object" && value !== null;
1932
2197
  }
1933
2198
  function isToolMessage(value) {
1934
- return isRecord$2(value) && value.lc_direct_tool_output === true && value.type === "tool" && (typeof value.content === "string" || Array.isArray(value.content));
2199
+ return isRecord$1(value) && value.lc_direct_tool_output === true && value.type === "tool" && (typeof value.content === "string" || Array.isArray(value.content));
1935
2200
  }
1936
2201
  function isCommand(value) {
1937
- return isRecord$2(value) && value.lg_name === "Command";
2202
+ return isRecord$1(value) && value.lg_name === "Command";
1938
2203
  }
1939
2204
  function encodeNested(value) {
1940
2205
  if (isToolMessage(value) || isCommand(value)) return encodeNativeToolResult(value);
1941
2206
  if (Array.isArray(value)) return value.map(encodeNested);
1942
- if (isRecord$2(value)) return Object.fromEntries(Object.entries(value).map(([key, entry]) => [key, encodeNested(entry)]));
2207
+ if (isRecord$1(value)) return Object.fromEntries(Object.entries(value).map(([key, entry]) => [key, encodeNested(entry)]));
1943
2208
  return value;
1944
2209
  }
1945
2210
  function encodeNativeToolResult(value) {
@@ -1956,17 +2221,24 @@ function encodeNativeToolResult(value) {
1956
2221
  };
1957
2222
  return {
1958
2223
  [TOOL_RESULT_TAG]: "command",
1959
- graph: isRecord$2(value) && typeof value.graph === "string" ? value.graph : void 0,
1960
- update: isRecord$2(value) ? encodeNested(value.update) : void 0,
1961
- resume: isRecord$2(value) ? encodeNested(value.resume) : void 0,
1962
- goto: isRecord$2(value) ? encodeNested(value.goto) : void 0
2224
+ graph: isRecord$1(value) && typeof value.graph === "string" ? value.graph : void 0,
2225
+ update: isRecord$1(value) ? encodeNested(value.update) : void 0,
2226
+ resume: isRecord$1(value) ? encodeNested(value.resume) : void 0,
2227
+ goto: isRecord$1(value) ? encodeNested(value.goto) : void 0
1963
2228
  };
1964
2229
  }
1965
2230
  function finalizeToolResult(value) {
1966
2231
  return isToolMessage(value) || isCommand(value) ? encodeNativeToolResult(value) : value;
1967
2232
  }
1968
2233
  function isEncodedToolResult(value) {
1969
- return isRecord$2(value) && typeof value[TOOL_RESULT_TAG] === "string";
2234
+ return isRecord$1(value) && typeof value[TOOL_RESULT_TAG] === "string";
2235
+ }
2236
+ async function loadPeer(specifierParts, packageName, docsPath) {
2237
+ try {
2238
+ return await require_bamlPeer.importOptionalPeer(specifierParts);
2239
+ } catch {
2240
+ throw new require_http.BitfabError(`This LangGraph integration method requires ${packageName}. Install it to use it.`, `https://docs.bitfab.ai${docsPath}`);
2241
+ }
1970
2242
  }
1971
2243
  async function loadLangChainCore() {
1972
2244
  try {
@@ -1989,7 +2261,7 @@ async function loadLangGraph() {
1989
2261
  async function reviveNested(value, toolCallId) {
1990
2262
  if (isEncodedToolResult(value)) return reviveToolResult(value, toolCallId);
1991
2263
  if (Array.isArray(value)) return Promise.all(value.map((entry) => reviveNested(entry, toolCallId)));
1992
- if (isRecord$2(value)) {
2264
+ if (isRecord$1(value)) {
1993
2265
  const entries = await Promise.all(Object.entries(value).map(async ([key, entry]) => [key, await reviveNested(entry, toolCallId)]));
1994
2266
  return Object.fromEntries(entries);
1995
2267
  }
@@ -2005,9 +2277,9 @@ async function reviveToolResult(value, toolCallId) {
2005
2277
  ...typeof value.id === "string" && { id: value.id },
2006
2278
  ...(value.status === "success" || value.status === "error") && { status: value.status },
2007
2279
  ...value.artifact !== void 0 && { artifact: await reviveNested(value.artifact, toolCallId) },
2008
- ...isRecord$2(value.metadata) && { metadata: await reviveNested(value.metadata, toolCallId) },
2009
- ...isRecord$2(value.additionalKwargs) && { additional_kwargs: await reviveNested(value.additionalKwargs, toolCallId) },
2010
- ...isRecord$2(value.responseMetadata) && { response_metadata: await reviveNested(value.responseMetadata, toolCallId) }
2280
+ ...isRecord$1(value.metadata) && { metadata: await reviveNested(value.metadata, toolCallId) },
2281
+ ...isRecord$1(value.additionalKwargs) && { additional_kwargs: await reviveNested(value.additionalKwargs, toolCallId) },
2282
+ ...isRecord$1(value.responseMetadata) && { response_metadata: await reviveNested(value.responseMetadata, toolCallId) }
2011
2283
  });
2012
2284
  }
2013
2285
  const { Command } = await loadLangGraph();
@@ -2024,37 +2296,148 @@ var BitfabLangGraphIntegration = class {
2024
2296
  this.traceFunctionKey = config.traceFunctionKey;
2025
2297
  this.callbackHandler = config.callbackHandler;
2026
2298
  this.mockToolsOnReplay = config.options?.mockToolsOnReplay ?? true;
2299
+ this.getActiveSpan = config.getActiveSpan ?? (() => null);
2300
+ this.addRootContext = config.addContext ?? (() => {});
2301
+ }
2302
+ get middleware() {
2303
+ this.agentMiddleware ?? (this.agentMiddleware = {
2304
+ [AGENT_MIDDLEWARE_BRAND]: true,
2305
+ name: "BitfabAgentMiddleware",
2306
+ wrapToolCall: (request, handler) => this.interceptToolCall(request, handler)
2307
+ });
2308
+ return this.agentMiddleware;
2309
+ }
2310
+ instrument(graph) {
2311
+ const run = (config) => new GraphRun(this.graphRunHost, graph, config);
2312
+ return new Proxy(graph, { get: (target, property) => {
2313
+ if (property === "invoke") return (input, config) => run(config).invoke(input);
2314
+ if (property === "stream") return async (input, config) => run(config).stream(input);
2315
+ if (property === "streamEvents") return (input, config, streamOptions) => run(config).streamEvents(input, streamOptions);
2316
+ if (property === "batch") return (inputs, config) => Promise.all(inputs.map((input, index) => run(Array.isArray(config) ? config[index] : config).invoke(input)));
2317
+ if (property === "withConfig") return (config) => this.instrument(target.withConfig(config));
2318
+ const value = Reflect.get(target, property, target);
2319
+ return typeof value === "function" ? value.bind(target) : value;
2320
+ } });
2321
+ }
2322
+ get graphRunHost() {
2323
+ this.runHost ?? (this.runHost = {
2324
+ traceFunctionKey: this.traceFunctionKey,
2325
+ callbackHandler: this.callbackHandler,
2326
+ activeSpan: () => this.getActiveSpan(),
2327
+ rootSpan: (fn, finalize) => this.client.withSpan(this.traceFunctionKey, {
2328
+ name: this.traceFunctionKey,
2329
+ type: "agent",
2330
+ surface: "inherit",
2331
+ instrumentation: "langgraph",
2332
+ ...finalize !== void 0 && { finalize }
2333
+ }, fn),
2334
+ addRootContext: (context) => this.addRootContext(context),
2335
+ encodeRootInput: (input) => isCommand(input) ? encodeNativeToolResult(input) : input,
2336
+ reviveRootInput: async (input) => isEncodedToolResult(input) ? await reviveToolResult(input, "") : input
2337
+ });
2338
+ return this.runHost;
2339
+ }
2340
+ async createDeepAgent(params = {}) {
2341
+ const { createDeepAgent } = await loadPeer(["deepagents"], "deepagents", "/frameworks/deep-agents");
2342
+ return this.instrument(createDeepAgent({
2343
+ ...params,
2344
+ middleware: this.withMiddleware(params.middleware),
2345
+ ...params.subagents !== void 0 && { subagents: params.subagents.map((spec) => this.withSubagentMiddleware(spec)) }
2346
+ }));
2347
+ }
2348
+ async createAgent(params) {
2349
+ const { createAgent } = await loadPeer(["langchain"], "langchain", "/frameworks/langgraph");
2350
+ return this.instrument(createAgent({
2351
+ ...params,
2352
+ middleware: this.withMiddleware(params.middleware)
2353
+ }));
2354
+ }
2355
+ withMiddleware(middleware = []) {
2356
+ return middleware.includes(this.middleware) ? [...middleware] : [...middleware, this.middleware];
2357
+ }
2358
+ withSubagentMiddleware(spec) {
2359
+ if (!isRecord$1(spec) || "runnable" in spec || "graphId" in spec) return spec;
2360
+ return {
2361
+ ...spec,
2362
+ middleware: this.withMiddleware(Array.isArray(spec.middleware) ? spec.middleware : [])
2363
+ };
2364
+ }
2365
+ async interceptToolCall(request, handler) {
2366
+ const toolName = request.toolCall.name;
2367
+ const toolCallId = request.toolCall.id;
2368
+ const shouldMock = this.shouldMock(toolName);
2369
+ this.assertReplayToolResultExists(toolName, shouldMock);
2370
+ const traceId = this.recordingTraceId(toolName);
2371
+ if (traceId === null || !toolCallId) return await handler(request);
2372
+ const stepSpanId = this.stepSpanIdFor(request.runtime, traceId);
2373
+ return await this.runClaimedToolCall(traceId, toolCallId, toolName, shouldMock, request.toolCall.args, async () => await handler(request), stepSpanId);
2374
+ }
2375
+ stepSpanIdFor(config, traceId) {
2376
+ const namespace = isRecord$1(config) && isRecord$1(config.configurable) ? config.configurable.checkpoint_ns : void 0;
2377
+ return typeof namespace === "string" ? this.callbackHandler.visibleStepSpanId(namespace, traceId) : null;
2378
+ }
2379
+ recordingTraceId(toolName) {
2380
+ const activeSpan = this.getActiveSpan();
2381
+ if (activeSpan === null) {
2382
+ require_autoTrace.warnOnce(`langgraph-tool-call-outside-root:${this.traceFunctionKey}`, `tool call "${toolName}" ran outside a Bitfab trace for "${this.traceFunctionKey}", so it was not recorded as a replayable span. Run the agent through instrument(agent), createAgent(), or createDeepAgent().`);
2383
+ return null;
2384
+ }
2385
+ return activeSpan.traceId;
2386
+ }
2387
+ async runClaimedToolCall(traceId, toolCallId, toolName, shouldMock, args, run, stepSpanId) {
2388
+ const release = this.callbackHandler.claimToolCall(traceId, toolCallId);
2389
+ try {
2390
+ const result = await this.client.withSpan(this.traceFunctionKey, {
2391
+ name: toolName,
2392
+ type: "function",
2393
+ captureWhen: "nested",
2394
+ mockOnReplay: shouldMock,
2395
+ finalize: finalizeToolResult,
2396
+ surface: "inherit",
2397
+ instrumentation: "langgraph",
2398
+ ...stepSpanId !== null && { frameworkParentSpanId: stepSpanId }
2399
+ }, async (_args) => await run())(args);
2400
+ return isEncodedToolResult(result) ? await reviveToolResult(result, toolCallId) : result;
2401
+ } finally {
2402
+ release();
2403
+ }
2404
+ }
2405
+ shouldMock(toolName) {
2406
+ return typeof this.mockToolsOnReplay === "boolean" ? this.mockToolsOnReplay : this.mockToolsOnReplay.includes(toolName);
2027
2407
  }
2028
2408
  wrapTools(tools) {
2029
2409
  return tools.map((tool) => this.wrapTool(tool));
2030
2410
  }
2031
2411
  createInvoker(graph) {
2032
- const configuredGraph = graph.withConfig({ callbacks: [this.callbackHandler] });
2033
- return (input, config) => {
2034
- return this.wrapInvoke((rootInput) => configuredGraph.invoke(rootInput, config))(input);
2035
- };
2412
+ require_autoTrace.warnOnce("deprecated-create-invoker", "createInvoker(graph) is deprecated; use instrument(graph).invoke instead.");
2413
+ const traced = this.instrument(graph);
2414
+ return (input, config) => traced.invoke(input, config);
2036
2415
  }
2037
2416
  wrapTool(tool) {
2038
2417
  const toolName = tool.name;
2039
2418
  if (typeof toolName !== "string" || toolName.length === 0) throw new require_http.BitfabError("LangGraph replayable tools must have a name.", "https://docs.bitfab.ai/frameworks/langgraph");
2040
- const mockToolsOnReplay = this.mockToolsOnReplay;
2041
- const shouldMock = typeof mockToolsOnReplay === "boolean" ? mockToolsOnReplay : mockToolsOnReplay.includes(toolName);
2419
+ const shouldMock = this.shouldMock(toolName);
2042
2420
  const originalInvoke = tool.invoke.bind(tool);
2043
2421
  return new Proxy(tool, { get: (target, property) => {
2044
2422
  if (property === "invoke") return async (input, ...rest) => {
2045
- const toolCallId = isRecord$2(input) && typeof input.id === "string" ? input.id : "";
2046
- const args = isRecord$2(input) && "args" in input ? input.args : input;
2423
+ const toolCallId = isRecord$1(input) && typeof input.id === "string" ? input.id : "";
2424
+ const args = isRecord$1(input) && "args" in input ? input.args : input;
2047
2425
  this.assertReplayToolResultExists(toolName, shouldMock);
2048
- const result = await this.client.withSpan(this.traceFunctionKey, {
2049
- name: toolName,
2050
- type: "function",
2051
- captureWhen: "nested",
2052
- mockOnReplay: shouldMock,
2053
- finalize: finalizeToolResult,
2054
- surface: "inherit",
2055
- instrumentation: "langgraph"
2056
- }, async (_args) => await originalInvoke(input, ...rest))(args);
2057
- return isEncodedToolResult(result) ? await reviveToolResult(result, toolCallId) : result;
2426
+ const traceId = this.getActiveSpan()?.traceId ?? null;
2427
+ const run = async () => await originalInvoke(input, ...rest);
2428
+ if (traceId === null || toolCallId === "") {
2429
+ const result = await this.client.withSpan(this.traceFunctionKey, {
2430
+ name: toolName,
2431
+ type: "function",
2432
+ captureWhen: "nested",
2433
+ mockOnReplay: shouldMock,
2434
+ finalize: finalizeToolResult,
2435
+ surface: "inherit",
2436
+ instrumentation: "langgraph"
2437
+ }, async (_args) => await run())(args);
2438
+ return isEncodedToolResult(result) ? await reviveToolResult(result, toolCallId) : result;
2439
+ }
2440
+ return await this.runClaimedToolCall(traceId, toolCallId, toolName, shouldMock, args, run, this.stepSpanIdFor(rest[0], traceId));
2058
2441
  };
2059
2442
  const value = Reflect.get(target, property, target);
2060
2443
  return typeof value === "function" ? value.bind(target) : value;
@@ -2505,37 +2888,6 @@ function looksBinary(s) {
2505
2888
  return s.slice(0, 8e3).includes(NUL);
2506
2889
  }
2507
2890
  //#endregion
2508
- //#region src/integrationFixture.ts
2509
- const INTEGRATION_FIXTURE_CONTEXT_KEY = "__bitfabIntegrationFixture";
2510
- const INTEGRATION_FIXTURE_VERSION = 1;
2511
- function isRecord$1(value) {
2512
- return typeof value === "object" && value !== null && !Array.isArray(value);
2513
- }
2514
- function createIntegrationFixtureContext(name, value) {
2515
- const serialized = serializeValue(value);
2516
- return { [INTEGRATION_FIXTURE_CONTEXT_KEY]: {
2517
- version: INTEGRATION_FIXTURE_VERSION,
2518
- name,
2519
- value: serialized.json,
2520
- ...serialized.meta !== void 0 && { valueMeta: serialized.meta }
2521
- } };
2522
- }
2523
- function extractIntegrationFixtures(spanData) {
2524
- const contexts = spanData.contexts;
2525
- if (!Array.isArray(contexts)) return;
2526
- const fixtures = /* @__PURE__ */ new Map();
2527
- for (const context of contexts) {
2528
- if (!isRecord$1(context)) continue;
2529
- const fixture = context[INTEGRATION_FIXTURE_CONTEXT_KEY];
2530
- if (!isRecord$1(fixture) || fixture.version !== INTEGRATION_FIXTURE_VERSION || typeof fixture.name !== "string") continue;
2531
- fixtures.set(fixture.name, deserializeValue({
2532
- json: fixture.value,
2533
- ...fixture.valueMeta !== void 0 && { meta: fixture.valueMeta }
2534
- }));
2535
- }
2536
- return fixtures.size > 0 ? fixtures : void 0;
2537
- }
2538
- //#endregion
2539
2891
  //#region src/replayHeartbeat.ts
2540
2892
  const REPLAY_HEARTBEAT_INTERVAL_MS = 6e4;
2541
2893
  function startReplayHeartbeat(send) {
@@ -4686,25 +5038,45 @@ function runWithSpanStack(stack, fn) {
4686
5038
  throw error;
4687
5039
  }
4688
5040
  }
5041
+ function isAsyncIterable(value) {
5042
+ return value !== null && typeof value === "object" && typeof value[Symbol.asyncIterator] === "function";
5043
+ }
5044
+ function drainingStreams(fn) {
5045
+ return async (...args) => {
5046
+ const result = await fn(...args);
5047
+ if (!isAsyncIterable(result)) return result;
5048
+ const chunks = [];
5049
+ for await (const chunk of result) chunks.push(chunk);
5050
+ const replay = require_http.getReplayContext();
5051
+ return replay !== null && "streamResult" in replay ? replay.streamResult : chunks;
5052
+ };
5053
+ }
4689
5054
  function isAsyncGenerator(value) {
4690
5055
  if (value === null || typeof value !== "object") return false;
4691
5056
  const candidate = value;
4692
5057
  return typeof candidate.next === "function" && typeof candidate.return === "function" && typeof candidate.throw === "function" && typeof candidate[Symbol.asyncIterator] === "function";
4693
5058
  }
4694
- function wrapAsyncGenerator(source, spanStack, sendSpan) {
5059
+ function wrapAsyncGenerator(source, spanStack, sendSpan, recordYielded) {
4695
5060
  const yielded = [];
4696
5061
  let returnValue;
4697
5062
  let finalized = false;
4698
5063
  const finalize = (errorMsg) => {
4699
5064
  if (finalized) return;
4700
5065
  finalized = true;
4701
- sendSpan({
4702
- result: {
4703
- yielded,
4704
- return: returnValue
4705
- },
4706
- ...errorMsg && { error: errorMsg }
4707
- });
5066
+ if (recordYielded === void 0 || errorMsg) {
5067
+ sendSpan({
5068
+ result: {
5069
+ yielded,
5070
+ return: returnValue
5071
+ },
5072
+ ...errorMsg && { error: errorMsg }
5073
+ });
5074
+ return;
5075
+ }
5076
+ Promise.resolve().then(() => recordYielded(yielded)).then((output) => sendSpan({ result: output }), (error) => sendSpan({
5077
+ result: void 0,
5078
+ error: `finalize failed: ${error instanceof Error ? error.message : String(error)}`
5079
+ }));
4708
5080
  };
4709
5081
  const step = (method, arg) => runWithSpanStack(spanStack, () => {
4710
5082
  return source[method].call(source, arg);
@@ -4798,7 +5170,7 @@ function extractContextFromCollector(collector) {
4798
5170
  }
4799
5171
  const BOUND_FUNCTION_NAME_PREFIX = /^bound /;
4800
5172
  function discoveredSpanType(definition, nodeConfiguration) {
4801
- const recordsModelCall = definition.baml === true || definition.jev === true;
5173
+ const recordsModelCall = definition.baml === true || definition.jev === true || definition.openrouter === true;
4802
5174
  const ownType = recordsModelCall ? "llm" : "function";
4803
5175
  if (nodeConfiguration === void 0) return ownType;
4804
5176
  if (recordsModelCall && nodeConfiguration.defaultType === true) return ownType;
@@ -5199,7 +5571,7 @@ var Bitfab = class {
5199
5571
  ...nodeConfiguration?.finalize !== void 0 && { finalize: nodeConfiguration.finalize }
5200
5572
  };
5201
5573
  const isAsync = definition.async === true;
5202
- return openChild(entry, childOptions, inputs, isAsync, definition.baml === true ? () => invokeAutoTracedBaml(invokeFn, isAsync) : definition.jev === true ? () => recordAutoTracedJev(invokeFn, getCurrentSpan()) : invokeFn);
5574
+ return openChild(entry, childOptions, inputs, isAsync, definition.baml === true ? () => invokeAutoTracedBaml(invokeFn, isAsync) : definition.jev === true ? () => recordAutoTracedJev(invokeFn, getCurrentSpan()) : definition.openrouter === true ? () => require_autoTrace.recordAutoTracedOpenRouter(invokeFn, inputs[0], getCurrentSpan()) : invokeFn);
5203
5575
  },
5204
5576
  invokeNestedRoot(nestedName, nestedFunctionName, inputs, invokeFn, entry, link, spanDetails) {
5205
5577
  if (excluded.has(nestedName) || excluded.has(nestedFunctionName) || !recordsSpan(entry, nestedName, true)) return invokeFn();
@@ -5378,16 +5750,23 @@ var Bitfab = class {
5378
5750
  const stack = getSpanStack();
5379
5751
  return stack[stack.length - 1] ?? null;
5380
5752
  },
5381
- captureTools: false,
5382
5753
  _httpClient: this.httpClient
5383
5754
  });
5384
5755
  return new BitfabLangGraphIntegration({
5385
5756
  client: this,
5386
5757
  traceFunctionKey,
5387
5758
  callbackHandler,
5388
- options
5759
+ options,
5760
+ getActiveSpan: () => {
5761
+ const stack = getSpanStack();
5762
+ return stack[stack.length - 1] ?? null;
5763
+ },
5764
+ addContext: (context) => getCurrentSpan().addContext(context)
5389
5765
  });
5390
5766
  }
5767
+ getDeepAgentsIntegration(traceFunctionKey, options) {
5768
+ return this.getLangGraphIntegration(traceFunctionKey, options);
5769
+ }
5391
5770
  getRivetIntegration(traceFunctionKey, options) {
5392
5771
  return new BitfabRivetIntegration(traceFunctionKey, {
5393
5772
  wrapEffect: (effect, mockOnReplay, fn, replayOutput) => {
@@ -5503,6 +5882,26 @@ var Bitfab = class {
5503
5882
  });
5504
5883
  return wrappedFn;
5505
5884
  }
5885
+ wrapOpenRouter(method, options) {
5886
+ const methodName = method.name.replace(BOUND_FUNCTION_NAME_PREFIX, "");
5887
+ if (!methodName) throw new require_http.BitfabError("wrapOpenRouter requires a named function (e.g., openai.chat.completions.create.bind(openai.chat.completions)).");
5888
+ const wrappedFn = async (...args) => {
5889
+ const span = getCurrentSpan();
5890
+ const startedAt = Date.now();
5891
+ const { watch, result } = require_autoTrace.watchOpenRouterUsage(() => method(...args));
5892
+ const response = await result;
5893
+ require_autoTrace.recordWatchedOpenRouterCompletion(span, watch, args[0], response, Date.now() - startedAt);
5894
+ try {
5895
+ options?.onResponse?.(response);
5896
+ } catch {}
5897
+ return response;
5898
+ };
5899
+ Object.defineProperty(wrappedFn, "name", {
5900
+ configurable: true,
5901
+ value: methodName
5902
+ });
5903
+ return wrappedFn;
5904
+ }
5506
5905
  withSpan(traceFunctionKey, optionsOrFn, maybeFn) {
5507
5906
  this.simulationPlan.refresh();
5508
5907
  const options = typeof optionsOrFn === "function" ? {} : optionsOrFn;
@@ -5554,7 +5953,9 @@ var Bitfab = class {
5554
5953
  const seedCtxForTraceId = parentContext ? null : getSeedContext();
5555
5954
  const traceId = parentContext?.traceId ?? replayCtxForTraceId?.traceId ?? seedCtxForTraceId?.traceId ?? randomUuid();
5556
5955
  const spanId = randomUuid();
5557
- const parentSpanId = (parentContext !== void 0 && options.instrumentation === "trace" ? openAiAgentsParentSpanId(parentContext.traceId, parentContext.openAiAgentsSpanIds) : void 0) ?? parentContext?.spanId ?? null;
5956
+ const openAiAgentsParent = parentContext !== void 0 && options.instrumentation === "trace" ? openAiAgentsParentSpanId(parentContext.traceId, parentContext.openAiAgentsSpanIds) : void 0;
5957
+ const frameworkParent = parentContext !== void 0 ? options.frameworkParentSpanId : void 0;
5958
+ const parentSpanId = openAiAgentsParent ?? frameworkParent ?? parentContext?.spanId ?? null;
5558
5959
  const isRootSpan = parentSpanId === null;
5559
5960
  if (options.enclosingTrace !== void 0) {
5560
5961
  options.enclosingTrace.link.traceId = traceId;
@@ -5709,7 +6110,7 @@ var Bitfab = class {
5709
6110
  });
5710
6111
  throw error;
5711
6112
  });
5712
- if (isAsyncGenerator(result)) return wrapAsyncGenerator(result, newStack, sendSpan);
6113
+ if (isAsyncGenerator(result)) return wrapAsyncGenerator(result, newStack, sendSpan, options.finalize);
5713
6114
  recordSpan(result);
5714
6115
  return result;
5715
6116
  };
@@ -6139,7 +6540,7 @@ var Bitfab = class {
6139
6540
  await runWithSeedContext({ traceId }, async () => target(...args));
6140
6541
  } finally {
6141
6542
  try {
6142
- const { flushTraces } = await Promise.resolve().then(() => require("./http-psFF1ptn.cjs")).then((n) => n.http_exports);
6543
+ const { flushTraces } = await Promise.resolve().then(() => require("./http-Dqc-f3sp.cjs")).then((n) => n.http_exports);
6143
6544
  await flushTraces(3e4);
6144
6545
  } finally {
6145
6546
  unrecorded = activeTraceStates.delete(traceId);
@@ -6177,7 +6578,7 @@ var Bitfab = class {
6177
6578
  type: "agent",
6178
6579
  surface: "neutral"
6179
6580
  };
6180
- replayFn = this.withSpan(traceFunctionKey, replayRootOptions, fn);
6581
+ replayFn = this.withSpan(traceFunctionKey, replayRootOptions, drainingStreams(fn));
6181
6582
  } else if (wrappedKey !== traceFunctionKey) throw new require_http.BitfabError(`Function is wrapped with trace function key '${wrappedKey}' but replay was called with '${traceFunctionKey}'. Pass matching keys, or pass the unwrapped function to replay it under the explicit key.`);
6182
6583
  const { replay: doReplay } = await Promise.resolve().then(() => replay_exports);
6183
6584
  return doReplay(this.httpClient, this.serviceUrl, traceFunctionKey, replayFn, options, this.mockOverrides);
@@ -6219,6 +6620,9 @@ var BitfabFunction = class {
6219
6620
  getLangGraphIntegration(options) {
6220
6621
  return this.client.getLangGraphIntegration(this.traceFunctionKey, options);
6221
6622
  }
6623
+ getDeepAgentsIntegration(options) {
6624
+ return this.client.getDeepAgentsIntegration(this.traceFunctionKey, options);
6625
+ }
6222
6626
  getRivetIntegration(options) {
6223
6627
  return this.client.getRivetIntegration(this.traceFunctionKey, options);
6224
6628
  }
@@ -6228,6 +6632,9 @@ var BitfabFunction = class {
6228
6632
  wrapJev(method, options) {
6229
6633
  return this.client.wrapJev(method, options);
6230
6634
  }
6635
+ wrapOpenRouter(method, options) {
6636
+ return this.client.wrapOpenRouter(method, options);
6637
+ }
6231
6638
  };
6232
6639
  //#endregion
6233
6640
  //#region src/finalizers.ts
@@ -6330,7 +6737,7 @@ async function seedFromRegistry(registry, pipeline, cases, options = {}) {
6330
6737
  metadata: seedCase.metadata,
6331
6738
  sessionId: seedCase.sessionId
6332
6739
  }));
6333
- const { flushTraces } = await Promise.resolve().then(() => require("./http-psFF1ptn.cjs")).then((n) => n.http_exports);
6740
+ const { flushTraces } = await Promise.resolve().then(() => require("./http-Dqc-f3sp.cjs")).then((n) => n.http_exports);
6334
6741
  await flushTraces(3e4);
6335
6742
  return {
6336
6743
  pipeline,
@@ -6574,4 +6981,4 @@ Object.defineProperty(exports, "serializeReplayResult", {
6574
6981
  }
6575
6982
  });
6576
6983
 
6577
- //# sourceMappingURL=src-Dze8o7iU.cjs.map
6984
+ //# sourceMappingURL=src-CdQRfsrA.cjs.map