bitfab 0.9.2 → 0.11.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +10 -10
- package/dist/{chunk-WUJR72QY.js → chunk-6EZCV5TU.js} +1014 -3
- package/dist/chunk-6EZCV5TU.js.map +1 -0
- package/dist/{chunk-VGALEXKQ.js → chunk-C4KRLEXZ.js} +47 -47
- package/dist/chunk-C4KRLEXZ.js.map +1 -0
- package/dist/index.cjs +1059 -40
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +221 -3
- package/dist/index.d.ts +221 -3
- package/dist/index.js +6 -2
- package/dist/node.cjs +1020 -1
- package/dist/node.cjs.map +1 -1
- package/dist/node.d.cts +1 -1
- package/dist/node.d.ts +1 -1
- package/dist/node.js +6 -2
- package/dist/node.js.map +1 -1
- package/dist/{replay-DJ2HXTHQ.js → replay-PIWVDXIF.js} +2 -2
- package/package.json +3 -3
- package/dist/chunk-VGALEXKQ.js.map +0 -1
- package/dist/chunk-WUJR72QY.js.map +0 -1
- /package/dist/{replay-DJ2HXTHQ.js.map → replay-PIWVDXIF.js.map} +0 -0
package/dist/index.cjs
CHANGED
|
@@ -30,51 +30,12 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
|
|
|
30
30
|
));
|
|
31
31
|
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
32
32
|
|
|
33
|
-
// src/asyncStorage.ts
|
|
34
|
-
function registerAsyncLocalStorageClass(cls) {
|
|
35
|
-
if (!AsyncLocalStorageClass) {
|
|
36
|
-
AsyncLocalStorageClass = cls;
|
|
37
|
-
}
|
|
38
|
-
initDone = true;
|
|
39
|
-
}
|
|
40
|
-
function isAsyncStorageInitDone() {
|
|
41
|
-
return initDone;
|
|
42
|
-
}
|
|
43
|
-
function createAsyncLocalStorage() {
|
|
44
|
-
return AsyncLocalStorageClass ? new AsyncLocalStorageClass() : null;
|
|
45
|
-
}
|
|
46
|
-
var AsyncLocalStorageClass, initDone, asyncStorageReady;
|
|
47
|
-
var init_asyncStorage = __esm({
|
|
48
|
-
"src/asyncStorage.ts"() {
|
|
49
|
-
"use strict";
|
|
50
|
-
AsyncLocalStorageClass = null;
|
|
51
|
-
initDone = false;
|
|
52
|
-
asyncStorageReady = (typeof process !== "undefined" && process.versions?.node ? (
|
|
53
|
-
// The join trick hides "node:async_hooks" from static analysis so
|
|
54
|
-
// bundlers that ban Node.js built-ins don't fail at build time.
|
|
55
|
-
// webpackIgnore tells webpack/turbopack to emit a native import()
|
|
56
|
-
// so Node.js can resolve the module at runtime.
|
|
57
|
-
import(
|
|
58
|
-
/* webpackIgnore: true */
|
|
59
|
-
["node", "async_hooks"].join(":")
|
|
60
|
-
).then(
|
|
61
|
-
(mod) => {
|
|
62
|
-
registerAsyncLocalStorageClass(mod.AsyncLocalStorage);
|
|
63
|
-
}
|
|
64
|
-
).catch(() => {
|
|
65
|
-
})
|
|
66
|
-
) : Promise.resolve()).then(() => {
|
|
67
|
-
initDone = true;
|
|
68
|
-
});
|
|
69
|
-
}
|
|
70
|
-
});
|
|
71
|
-
|
|
72
33
|
// src/version.generated.ts
|
|
73
34
|
var __version__;
|
|
74
35
|
var init_version_generated = __esm({
|
|
75
36
|
"src/version.generated.ts"() {
|
|
76
37
|
"use strict";
|
|
77
|
-
__version__ = "0.
|
|
38
|
+
__version__ = "0.11.0";
|
|
78
39
|
}
|
|
79
40
|
});
|
|
80
41
|
|
|
@@ -338,6 +299,45 @@ var init_http = __esm({
|
|
|
338
299
|
}
|
|
339
300
|
});
|
|
340
301
|
|
|
302
|
+
// src/asyncStorage.ts
|
|
303
|
+
function registerAsyncLocalStorageClass(cls) {
|
|
304
|
+
if (!AsyncLocalStorageClass) {
|
|
305
|
+
AsyncLocalStorageClass = cls;
|
|
306
|
+
}
|
|
307
|
+
initDone = true;
|
|
308
|
+
}
|
|
309
|
+
function isAsyncStorageInitDone() {
|
|
310
|
+
return initDone;
|
|
311
|
+
}
|
|
312
|
+
function createAsyncLocalStorage() {
|
|
313
|
+
return AsyncLocalStorageClass ? new AsyncLocalStorageClass() : null;
|
|
314
|
+
}
|
|
315
|
+
var AsyncLocalStorageClass, initDone, asyncStorageReady;
|
|
316
|
+
var init_asyncStorage = __esm({
|
|
317
|
+
"src/asyncStorage.ts"() {
|
|
318
|
+
"use strict";
|
|
319
|
+
AsyncLocalStorageClass = null;
|
|
320
|
+
initDone = false;
|
|
321
|
+
asyncStorageReady = (typeof process !== "undefined" && process.versions?.node ? (
|
|
322
|
+
// The join trick hides "node:async_hooks" from static analysis so
|
|
323
|
+
// bundlers that ban Node.js built-ins don't fail at build time.
|
|
324
|
+
// webpackIgnore tells webpack/turbopack to emit a native import()
|
|
325
|
+
// so Node.js can resolve the module at runtime.
|
|
326
|
+
import(
|
|
327
|
+
/* webpackIgnore: true */
|
|
328
|
+
["node", "async_hooks"].join(":")
|
|
329
|
+
).then(
|
|
330
|
+
(mod) => {
|
|
331
|
+
registerAsyncLocalStorageClass(mod.AsyncLocalStorage);
|
|
332
|
+
}
|
|
333
|
+
).catch(() => {
|
|
334
|
+
})
|
|
335
|
+
) : Promise.resolve()).then(() => {
|
|
336
|
+
initDone = true;
|
|
337
|
+
});
|
|
338
|
+
}
|
|
339
|
+
});
|
|
340
|
+
|
|
341
341
|
// src/replayContext.ts
|
|
342
342
|
function getReplayContext() {
|
|
343
343
|
return replayContextStorage?.getStore() ?? null;
|
|
@@ -496,8 +496,10 @@ var init_replay = __esm({
|
|
|
496
496
|
var index_exports = {};
|
|
497
497
|
__export(index_exports, {
|
|
498
498
|
Bitfab: () => Bitfab,
|
|
499
|
+
BitfabClaudeAgentHandler: () => BitfabClaudeAgentHandler,
|
|
499
500
|
BitfabError: () => BitfabError,
|
|
500
501
|
BitfabFunction: () => BitfabFunction,
|
|
502
|
+
BitfabLangGraphCallbackHandler: () => BitfabLangGraphCallbackHandler,
|
|
501
503
|
BitfabOpenAITracingProcessor: () => BitfabOpenAITracingProcessor,
|
|
502
504
|
DEFAULT_SERVICE_URL: () => DEFAULT_SERVICE_URL,
|
|
503
505
|
__version__: () => __version__,
|
|
@@ -507,6 +509,482 @@ __export(index_exports, {
|
|
|
507
509
|
});
|
|
508
510
|
module.exports = __toCommonJS(index_exports);
|
|
509
511
|
|
|
512
|
+
// src/claudeAgentSdk.ts
|
|
513
|
+
init_constants();
|
|
514
|
+
init_http();
|
|
515
|
+
function nowIso() {
|
|
516
|
+
return (/* @__PURE__ */ new Date()).toISOString();
|
|
517
|
+
}
|
|
518
|
+
function safeSerialize(value) {
|
|
519
|
+
if (value === null || value === void 0) {
|
|
520
|
+
return value;
|
|
521
|
+
}
|
|
522
|
+
if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
|
|
523
|
+
return value;
|
|
524
|
+
}
|
|
525
|
+
if (Array.isArray(value)) {
|
|
526
|
+
return value.map(safeSerialize);
|
|
527
|
+
}
|
|
528
|
+
if (typeof value === "object") {
|
|
529
|
+
if (typeof value.toJSON === "function") {
|
|
530
|
+
return value.toJSON();
|
|
531
|
+
}
|
|
532
|
+
const result = {};
|
|
533
|
+
for (const [k, v] of Object.entries(value)) {
|
|
534
|
+
if (!k.startsWith("_")) {
|
|
535
|
+
result[k] = safeSerialize(v);
|
|
536
|
+
}
|
|
537
|
+
}
|
|
538
|
+
return result;
|
|
539
|
+
}
|
|
540
|
+
return String(value);
|
|
541
|
+
}
|
|
542
|
+
function extractContentBlocks(content) {
|
|
543
|
+
if (!Array.isArray(content)) {
|
|
544
|
+
return [];
|
|
545
|
+
}
|
|
546
|
+
return content.map((block) => safeSerialize(block));
|
|
547
|
+
}
|
|
548
|
+
function extractUsage(message) {
|
|
549
|
+
const usageInfo = {};
|
|
550
|
+
const usage = message.usage;
|
|
551
|
+
if (!usage) {
|
|
552
|
+
return usageInfo;
|
|
553
|
+
}
|
|
554
|
+
const mapping = {
|
|
555
|
+
input_tokens: "inputTokens",
|
|
556
|
+
output_tokens: "outputTokens",
|
|
557
|
+
cache_read_input_tokens: "cacheReadTokens",
|
|
558
|
+
cache_creation_input_tokens: "cacheCreationTokens"
|
|
559
|
+
};
|
|
560
|
+
for (const [srcKey, dstKey] of Object.entries(mapping)) {
|
|
561
|
+
const val = usage[srcKey];
|
|
562
|
+
if (val !== void 0 && val !== null) {
|
|
563
|
+
usageInfo[dstKey] = val;
|
|
564
|
+
}
|
|
565
|
+
}
|
|
566
|
+
return usageInfo;
|
|
567
|
+
}
|
|
568
|
+
var BitfabClaudeAgentHandler = class {
|
|
569
|
+
constructor(config) {
|
|
570
|
+
// Span tracking
|
|
571
|
+
this.runToSpan = /* @__PURE__ */ new Map();
|
|
572
|
+
this.traceId = null;
|
|
573
|
+
this.rootSpanId = null;
|
|
574
|
+
this.activeContext = null;
|
|
575
|
+
this.traceStartedAt = null;
|
|
576
|
+
// LLM turn tracking
|
|
577
|
+
this.conversationHistory = [];
|
|
578
|
+
this.pendingMessages = [];
|
|
579
|
+
this.currentLlmSpanId = null;
|
|
580
|
+
this.currentLlmMessageId = null;
|
|
581
|
+
this.currentLlmContent = [];
|
|
582
|
+
this.currentLlmModel = null;
|
|
583
|
+
this.currentLlmUsage = {};
|
|
584
|
+
this.currentLlmStartedAt = null;
|
|
585
|
+
this.currentLlmHistorySnapshot = [];
|
|
586
|
+
// Subagent tracking
|
|
587
|
+
this.activeSubagentSpans = /* @__PURE__ */ new Map();
|
|
588
|
+
this.httpClient = new HttpClient({
|
|
589
|
+
apiKey: config.apiKey,
|
|
590
|
+
serviceUrl: config.serviceUrl ?? DEFAULT_SERVICE_URL,
|
|
591
|
+
timeout: config.timeout ?? 1e4
|
|
592
|
+
});
|
|
593
|
+
this.traceFunctionKey = config.traceFunctionKey;
|
|
594
|
+
this.getActiveSpanContext = config.getActiveSpanContext ?? null;
|
|
595
|
+
this.preToolUseHook = this.preToolUseHook.bind(this);
|
|
596
|
+
this.postToolUseHook = this.postToolUseHook.bind(this);
|
|
597
|
+
this.postToolUseFailureHook = this.postToolUseFailureHook.bind(this);
|
|
598
|
+
this.subagentStartHook = this.subagentStartHook.bind(this);
|
|
599
|
+
this.subagentStopHook = this.subagentStopHook.bind(this);
|
|
600
|
+
}
|
|
601
|
+
// ── trace lifecycle ──────────────────────────────────────────
|
|
602
|
+
ensureTrace() {
|
|
603
|
+
if (this.traceId !== null) {
|
|
604
|
+
return this.traceId;
|
|
605
|
+
}
|
|
606
|
+
this.activeContext = this.getActiveSpanContext?.() ?? null;
|
|
607
|
+
if (this.activeContext) {
|
|
608
|
+
this.traceId = this.activeContext.traceId;
|
|
609
|
+
} else {
|
|
610
|
+
this.traceId = crypto.randomUUID();
|
|
611
|
+
}
|
|
612
|
+
this.traceStartedAt = nowIso();
|
|
613
|
+
return this.traceId;
|
|
614
|
+
}
|
|
615
|
+
getParentId(agentId) {
|
|
616
|
+
if (agentId) {
|
|
617
|
+
const subagentSpanId = this.activeSubagentSpans.get(agentId);
|
|
618
|
+
if (subagentSpanId) {
|
|
619
|
+
return subagentSpanId;
|
|
620
|
+
}
|
|
621
|
+
}
|
|
622
|
+
return this.activeContext?.spanId ?? this.rootSpanId ?? null;
|
|
623
|
+
}
|
|
624
|
+
// ── span helpers ─────────────────────────────────────────────
|
|
625
|
+
startSpan(spanId, name, spanType, inputData, parentId) {
|
|
626
|
+
const traceId = this.ensureTrace();
|
|
627
|
+
const spanInfo = {
|
|
628
|
+
spanId,
|
|
629
|
+
traceId,
|
|
630
|
+
parentId: parentId ?? null,
|
|
631
|
+
startedAt: nowIso(),
|
|
632
|
+
name,
|
|
633
|
+
type: spanType,
|
|
634
|
+
input: safeSerialize(inputData),
|
|
635
|
+
contexts: []
|
|
636
|
+
};
|
|
637
|
+
this.runToSpan.set(spanId, spanInfo);
|
|
638
|
+
return spanInfo;
|
|
639
|
+
}
|
|
640
|
+
completeSpan(spanId, output, error, extraContexts) {
|
|
641
|
+
const spanInfo = this.runToSpan.get(spanId);
|
|
642
|
+
if (!spanInfo) {
|
|
643
|
+
return;
|
|
644
|
+
}
|
|
645
|
+
this.runToSpan.delete(spanId);
|
|
646
|
+
spanInfo.endedAt = nowIso();
|
|
647
|
+
spanInfo.output = safeSerialize(output);
|
|
648
|
+
if (error !== void 0) {
|
|
649
|
+
spanInfo.error = error;
|
|
650
|
+
}
|
|
651
|
+
if (extraContexts) {
|
|
652
|
+
spanInfo.contexts.push(extraContexts);
|
|
653
|
+
}
|
|
654
|
+
this.sendSpan(spanInfo);
|
|
655
|
+
}
|
|
656
|
+
sendSpan(spanInfo) {
|
|
657
|
+
const spanData = {
|
|
658
|
+
name: spanInfo.name,
|
|
659
|
+
type: spanInfo.type
|
|
660
|
+
};
|
|
661
|
+
if (spanInfo.input !== void 0) {
|
|
662
|
+
spanData.input = spanInfo.input;
|
|
663
|
+
}
|
|
664
|
+
if (spanInfo.output !== void 0) {
|
|
665
|
+
spanData.output = spanInfo.output;
|
|
666
|
+
}
|
|
667
|
+
if (spanInfo.error !== void 0) {
|
|
668
|
+
spanData.error = spanInfo.error;
|
|
669
|
+
}
|
|
670
|
+
if (spanInfo.contexts.length > 0) {
|
|
671
|
+
spanData.contexts = spanInfo.contexts;
|
|
672
|
+
}
|
|
673
|
+
const rawSpan = {
|
|
674
|
+
id: spanInfo.spanId,
|
|
675
|
+
trace_id: spanInfo.traceId,
|
|
676
|
+
started_at: spanInfo.startedAt,
|
|
677
|
+
ended_at: spanInfo.endedAt ?? nowIso(),
|
|
678
|
+
span_data: spanData
|
|
679
|
+
};
|
|
680
|
+
if (spanInfo.parentId !== null) {
|
|
681
|
+
rawSpan.parent_id = spanInfo.parentId;
|
|
682
|
+
}
|
|
683
|
+
const payload = {
|
|
684
|
+
type: "sdk-function",
|
|
685
|
+
source: "typescript-sdk-claude-agent-sdk",
|
|
686
|
+
traceFunctionKey: this.traceFunctionKey,
|
|
687
|
+
sourceTraceId: spanInfo.traceId,
|
|
688
|
+
rawSpan
|
|
689
|
+
};
|
|
690
|
+
try {
|
|
691
|
+
this.httpClient.sendExternalSpan(payload);
|
|
692
|
+
} catch {
|
|
693
|
+
}
|
|
694
|
+
}
|
|
695
|
+
sendTraceCompletion(endedAt, metadata) {
|
|
696
|
+
if (this.traceId === null) {
|
|
697
|
+
return;
|
|
698
|
+
}
|
|
699
|
+
const completed = this.activeContext === null;
|
|
700
|
+
const traceId = this.traceId;
|
|
701
|
+
this.traceId = null;
|
|
702
|
+
const externalTrace = {
|
|
703
|
+
id: traceId,
|
|
704
|
+
started_at: this.traceStartedAt ?? nowIso(),
|
|
705
|
+
ended_at: endedAt ?? nowIso(),
|
|
706
|
+
workflow_name: this.traceFunctionKey
|
|
707
|
+
};
|
|
708
|
+
if (metadata) {
|
|
709
|
+
externalTrace.metadata = metadata;
|
|
710
|
+
}
|
|
711
|
+
const traceData = {
|
|
712
|
+
type: "sdk-function",
|
|
713
|
+
source: "typescript-sdk-claude-agent-sdk",
|
|
714
|
+
traceFunctionKey: this.traceFunctionKey,
|
|
715
|
+
externalTrace,
|
|
716
|
+
completed
|
|
717
|
+
};
|
|
718
|
+
try {
|
|
719
|
+
this.httpClient.sendExternalTrace(traceData);
|
|
720
|
+
} catch {
|
|
721
|
+
}
|
|
722
|
+
}
|
|
723
|
+
// ── hook callbacks ───────────────────────────────────────────
|
|
724
|
+
async preToolUseHook(inputData, toolUseId, _context) {
|
|
725
|
+
try {
|
|
726
|
+
const sid = inputData.tool_use_id ?? toolUseId ?? crypto.randomUUID();
|
|
727
|
+
const toolName = inputData.tool_name ?? "tool";
|
|
728
|
+
const toolInput = inputData.tool_input ?? {};
|
|
729
|
+
const agentId = inputData.agent_id;
|
|
730
|
+
const parentId = this.getParentId(agentId);
|
|
731
|
+
this.startSpan(sid, toolName, "function", toolInput, parentId);
|
|
732
|
+
} catch {
|
|
733
|
+
}
|
|
734
|
+
return {};
|
|
735
|
+
}
|
|
736
|
+
async postToolUseHook(inputData, toolUseId, _context) {
|
|
737
|
+
try {
|
|
738
|
+
const sid = inputData.tool_use_id ?? toolUseId ?? "";
|
|
739
|
+
const toolResponse = inputData.tool_response;
|
|
740
|
+
this.completeSpan(sid, toolResponse);
|
|
741
|
+
} catch {
|
|
742
|
+
}
|
|
743
|
+
return {};
|
|
744
|
+
}
|
|
745
|
+
async postToolUseFailureHook(inputData, toolUseId, _context) {
|
|
746
|
+
try {
|
|
747
|
+
const sid = inputData.tool_use_id ?? toolUseId ?? "";
|
|
748
|
+
const error = String(inputData.error ?? "Unknown error");
|
|
749
|
+
this.completeSpan(sid, void 0, error);
|
|
750
|
+
} catch {
|
|
751
|
+
}
|
|
752
|
+
return {};
|
|
753
|
+
}
|
|
754
|
+
async subagentStartHook(inputData, _toolUseId, _context) {
|
|
755
|
+
try {
|
|
756
|
+
const agentId = inputData.agent_id ?? crypto.randomUUID();
|
|
757
|
+
const agentType = inputData.agent_type ?? "subagent";
|
|
758
|
+
const parentId = this.getParentId();
|
|
759
|
+
const spanId = crypto.randomUUID();
|
|
760
|
+
this.activeSubagentSpans.set(agentId, spanId);
|
|
761
|
+
this.startSpan(
|
|
762
|
+
spanId,
|
|
763
|
+
`Agent: ${agentType}`,
|
|
764
|
+
"agent",
|
|
765
|
+
void 0,
|
|
766
|
+
parentId
|
|
767
|
+
);
|
|
768
|
+
} catch {
|
|
769
|
+
}
|
|
770
|
+
return {};
|
|
771
|
+
}
|
|
772
|
+
async subagentStopHook(inputData, _toolUseId, _context) {
|
|
773
|
+
try {
|
|
774
|
+
const agentId = inputData.agent_id ?? "";
|
|
775
|
+
const spanId = this.activeSubagentSpans.get(agentId);
|
|
776
|
+
if (spanId) {
|
|
777
|
+
this.activeSubagentSpans.delete(agentId);
|
|
778
|
+
this.completeSpan(spanId);
|
|
779
|
+
}
|
|
780
|
+
} catch {
|
|
781
|
+
}
|
|
782
|
+
return {};
|
|
783
|
+
}
|
|
784
|
+
// ── public API ───────────────────────────────────────────────
|
|
785
|
+
/**
|
|
786
|
+
* Inject Bitfab tracing hooks into Claude Agent SDK options.
|
|
787
|
+
*
|
|
788
|
+
* Modifies the options object and returns it for convenience.
|
|
789
|
+
* The SDK's `HookMatcher` is constructed as a plain object
|
|
790
|
+
* (`{ matcher: null, hooks: [callback] }`) to avoid requiring
|
|
791
|
+
* `@anthropic-ai/claude-agent-sdk` as a dependency.
|
|
792
|
+
*
|
|
793
|
+
* @param options - Options object with a `hooks` property
|
|
794
|
+
* @returns The modified options object with Bitfab hooks injected
|
|
795
|
+
*/
|
|
796
|
+
instrumentOptions(options) {
|
|
797
|
+
const hooks = options.hooks ?? {};
|
|
798
|
+
if (!options.hooks) {
|
|
799
|
+
;
|
|
800
|
+
options.hooks = hooks;
|
|
801
|
+
}
|
|
802
|
+
const hookConfig = [
|
|
803
|
+
["PreToolUse", this.preToolUseHook],
|
|
804
|
+
["PostToolUse", this.postToolUseHook],
|
|
805
|
+
["PostToolUseFailure", this.postToolUseFailureHook],
|
|
806
|
+
["SubagentStart", this.subagentStartHook],
|
|
807
|
+
["SubagentStop", this.subagentStopHook]
|
|
808
|
+
];
|
|
809
|
+
for (const [event, callback] of hookConfig) {
|
|
810
|
+
if (!hooks[event]) {
|
|
811
|
+
hooks[event] = [];
|
|
812
|
+
}
|
|
813
|
+
hooks[event].push({ matcher: null, hooks: [callback] });
|
|
814
|
+
}
|
|
815
|
+
return options;
|
|
816
|
+
}
|
|
817
|
+
/**
|
|
818
|
+
* Wrap a `ClaudeSDKClient.receiveResponse()` stream to capture LLM turns.
|
|
819
|
+
*
|
|
820
|
+
* Yields every message unchanged while capturing AssistantMessage
|
|
821
|
+
* content as LLM turn spans.
|
|
822
|
+
*/
|
|
823
|
+
async *wrapResponse(stream) {
|
|
824
|
+
yield* this.processStream(stream);
|
|
825
|
+
}
|
|
826
|
+
/**
|
|
827
|
+
* Wrap a `query()` async iterator to capture LLM turns.
|
|
828
|
+
*
|
|
829
|
+
* Same as `wrapResponse` but for the simpler `query()` API
|
|
830
|
+
* which does not support hooks (no tool/subagent spans).
|
|
831
|
+
*/
|
|
832
|
+
async *wrapQuery(stream) {
|
|
833
|
+
yield* this.processStream(stream);
|
|
834
|
+
}
|
|
835
|
+
// ── stream processing ────────────────────────────────────────
|
|
836
|
+
async *processStream(stream) {
|
|
837
|
+
try {
|
|
838
|
+
for await (const message of stream) {
|
|
839
|
+
try {
|
|
840
|
+
this.processMessage(message);
|
|
841
|
+
} catch {
|
|
842
|
+
}
|
|
843
|
+
yield message;
|
|
844
|
+
}
|
|
845
|
+
} finally {
|
|
846
|
+
try {
|
|
847
|
+
this.flushLlmTurn();
|
|
848
|
+
this.sendTraceCompletion();
|
|
849
|
+
} catch {
|
|
850
|
+
}
|
|
851
|
+
this.resetState();
|
|
852
|
+
}
|
|
853
|
+
}
|
|
854
|
+
processMessage(message) {
|
|
855
|
+
const typeName = message.constructor?.name ?? "";
|
|
856
|
+
if (typeName === "AssistantMessage") {
|
|
857
|
+
this.handleAssistantMessage(message);
|
|
858
|
+
} else if (typeName === "UserMessage") {
|
|
859
|
+
this.handleUserMessage(message);
|
|
860
|
+
} else if (typeName === "ResultMessage") {
|
|
861
|
+
this.handleResultMessage(message);
|
|
862
|
+
}
|
|
863
|
+
}
|
|
864
|
+
handleAssistantMessage(message) {
|
|
865
|
+
this.ensureTrace();
|
|
866
|
+
const messageId = message.message_id;
|
|
867
|
+
if (messageId !== this.currentLlmMessageId) {
|
|
868
|
+
this.flushLlmTurn();
|
|
869
|
+
this.conversationHistory.push(...this.pendingMessages);
|
|
870
|
+
this.pendingMessages = [];
|
|
871
|
+
this.currentLlmSpanId = crypto.randomUUID();
|
|
872
|
+
this.currentLlmMessageId = messageId ?? null;
|
|
873
|
+
this.currentLlmContent = [];
|
|
874
|
+
this.currentLlmModel = message.model ?? null;
|
|
875
|
+
this.currentLlmUsage = {};
|
|
876
|
+
this.currentLlmStartedAt = nowIso();
|
|
877
|
+
this.currentLlmHistorySnapshot = [...this.conversationHistory];
|
|
878
|
+
}
|
|
879
|
+
const content = message.content;
|
|
880
|
+
if (Array.isArray(content)) {
|
|
881
|
+
this.currentLlmContent.push(...extractContentBlocks(content));
|
|
882
|
+
}
|
|
883
|
+
const usage = extractUsage(message);
|
|
884
|
+
if (Object.keys(usage).length > 0) {
|
|
885
|
+
Object.assign(this.currentLlmUsage, usage);
|
|
886
|
+
}
|
|
887
|
+
const model = message.model;
|
|
888
|
+
if (model) {
|
|
889
|
+
this.currentLlmModel = model;
|
|
890
|
+
}
|
|
891
|
+
}
|
|
892
|
+
handleUserMessage(message) {
|
|
893
|
+
const content = message.content;
|
|
894
|
+
const toolUseResult = message.tool_use_result;
|
|
895
|
+
if (toolUseResult !== void 0) {
|
|
896
|
+
this.pendingMessages.push({
|
|
897
|
+
role: "tool",
|
|
898
|
+
content: safeSerialize(content),
|
|
899
|
+
tool_result: safeSerialize(toolUseResult)
|
|
900
|
+
});
|
|
901
|
+
} else {
|
|
902
|
+
this.pendingMessages.push({
|
|
903
|
+
role: "user",
|
|
904
|
+
content: safeSerialize(content)
|
|
905
|
+
});
|
|
906
|
+
}
|
|
907
|
+
}
|
|
908
|
+
handleResultMessage(message) {
|
|
909
|
+
this.flushLlmTurn();
|
|
910
|
+
const metadata = {};
|
|
911
|
+
for (const attr of [
|
|
912
|
+
"num_turns",
|
|
913
|
+
"total_cost_usd",
|
|
914
|
+
"duration_ms",
|
|
915
|
+
"duration_api_ms",
|
|
916
|
+
"session_id"
|
|
917
|
+
]) {
|
|
918
|
+
const val = message[attr];
|
|
919
|
+
if (val !== void 0 && val !== null) {
|
|
920
|
+
metadata[attr] = val;
|
|
921
|
+
}
|
|
922
|
+
}
|
|
923
|
+
const usage = message.usage;
|
|
924
|
+
if (usage && typeof usage === "object") {
|
|
925
|
+
metadata.usage = safeSerialize(usage);
|
|
926
|
+
}
|
|
927
|
+
this.sendTraceCompletion(
|
|
928
|
+
void 0,
|
|
929
|
+
Object.keys(metadata).length > 0 ? metadata : void 0
|
|
930
|
+
);
|
|
931
|
+
}
|
|
932
|
+
flushLlmTurn() {
|
|
933
|
+
if (this.currentLlmSpanId === null) {
|
|
934
|
+
return;
|
|
935
|
+
}
|
|
936
|
+
const spanId = this.currentLlmSpanId;
|
|
937
|
+
const traceId = this.ensureTrace();
|
|
938
|
+
const parentId = this.getParentId();
|
|
939
|
+
const llmContext = {};
|
|
940
|
+
if (this.currentLlmModel) {
|
|
941
|
+
llmContext.model = this.currentLlmModel;
|
|
942
|
+
}
|
|
943
|
+
Object.assign(llmContext, this.currentLlmUsage);
|
|
944
|
+
const spanInfo = {
|
|
945
|
+
spanId,
|
|
946
|
+
traceId,
|
|
947
|
+
parentId,
|
|
948
|
+
startedAt: this.currentLlmStartedAt ?? nowIso(),
|
|
949
|
+
endedAt: nowIso(),
|
|
950
|
+
name: this.currentLlmModel ?? "llm",
|
|
951
|
+
type: "llm",
|
|
952
|
+
input: this.currentLlmHistorySnapshot,
|
|
953
|
+
output: this.currentLlmContent,
|
|
954
|
+
contexts: Object.keys(llmContext).length > 0 ? [llmContext] : []
|
|
955
|
+
};
|
|
956
|
+
this.sendSpan(spanInfo);
|
|
957
|
+
this.conversationHistory.push({
|
|
958
|
+
role: "assistant",
|
|
959
|
+
content: this.currentLlmContent
|
|
960
|
+
});
|
|
961
|
+
this.currentLlmSpanId = null;
|
|
962
|
+
this.currentLlmMessageId = null;
|
|
963
|
+
this.currentLlmContent = [];
|
|
964
|
+
this.currentLlmModel = null;
|
|
965
|
+
this.currentLlmUsage = {};
|
|
966
|
+
this.currentLlmStartedAt = null;
|
|
967
|
+
this.currentLlmHistorySnapshot = [];
|
|
968
|
+
}
|
|
969
|
+
resetState() {
|
|
970
|
+
this.runToSpan.clear();
|
|
971
|
+
this.traceId = null;
|
|
972
|
+
this.rootSpanId = null;
|
|
973
|
+
this.activeContext = null;
|
|
974
|
+
this.traceStartedAt = null;
|
|
975
|
+
this.conversationHistory = [];
|
|
976
|
+
this.pendingMessages = [];
|
|
977
|
+
this.currentLlmSpanId = null;
|
|
978
|
+
this.currentLlmMessageId = null;
|
|
979
|
+
this.currentLlmContent = [];
|
|
980
|
+
this.currentLlmModel = null;
|
|
981
|
+
this.currentLlmUsage = {};
|
|
982
|
+
this.currentLlmStartedAt = null;
|
|
983
|
+
this.currentLlmHistorySnapshot = [];
|
|
984
|
+
this.activeSubagentSpans.clear();
|
|
985
|
+
}
|
|
986
|
+
};
|
|
987
|
+
|
|
510
988
|
// src/client.ts
|
|
511
989
|
init_asyncStorage();
|
|
512
990
|
|
|
@@ -801,6 +1279,484 @@ async function runFunctionWithBaml(bamlSource, inputs, providers, envVars) {
|
|
|
801
1279
|
// src/client.ts
|
|
802
1280
|
init_constants();
|
|
803
1281
|
init_http();
|
|
1282
|
+
|
|
1283
|
+
// src/langgraph.ts
|
|
1284
|
+
init_constants();
|
|
1285
|
+
init_http();
|
|
1286
|
+
var LANGSMITH_HIDDEN_TAG = "langsmith:hidden";
|
|
1287
|
+
var LANGGRAPH_METADATA_KEYS = [
|
|
1288
|
+
"langgraph_step",
|
|
1289
|
+
"langgraph_node",
|
|
1290
|
+
"langgraph_triggers",
|
|
1291
|
+
"langgraph_path",
|
|
1292
|
+
"langgraph_checkpoint_ns"
|
|
1293
|
+
];
|
|
1294
|
+
function nowIso2() {
|
|
1295
|
+
return (/* @__PURE__ */ new Date()).toISOString();
|
|
1296
|
+
}
|
|
1297
|
+
var MAX_SERIALIZE_DEPTH = 6;
|
|
1298
|
+
function safeSerialize2(value) {
|
|
1299
|
+
return safeSerializeInner(value, 0, /* @__PURE__ */ new WeakSet());
|
|
1300
|
+
}
|
|
1301
|
+
function safeSerializeInner(value, depth, seen) {
|
|
1302
|
+
if (value === null || value === void 0) {
|
|
1303
|
+
return value;
|
|
1304
|
+
}
|
|
1305
|
+
if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
|
|
1306
|
+
return value;
|
|
1307
|
+
}
|
|
1308
|
+
const className = value?.constructor?.name ?? typeof value;
|
|
1309
|
+
if (depth > MAX_SERIALIZE_DEPTH) {
|
|
1310
|
+
return `<${className}>`;
|
|
1311
|
+
}
|
|
1312
|
+
if (typeof value === "object") {
|
|
1313
|
+
if (seen.has(value)) {
|
|
1314
|
+
return `<cycle ${className}>`;
|
|
1315
|
+
}
|
|
1316
|
+
seen.add(value);
|
|
1317
|
+
}
|
|
1318
|
+
if (Array.isArray(value)) {
|
|
1319
|
+
return value.map((item) => safeSerializeInner(item, depth + 1, seen));
|
|
1320
|
+
}
|
|
1321
|
+
if (typeof value === "object") {
|
|
1322
|
+
if (typeof value.toJSON === "function") {
|
|
1323
|
+
try {
|
|
1324
|
+
return value.toJSON();
|
|
1325
|
+
} catch {
|
|
1326
|
+
return `<${className}>`;
|
|
1327
|
+
}
|
|
1328
|
+
}
|
|
1329
|
+
try {
|
|
1330
|
+
const result = {};
|
|
1331
|
+
for (const [k, v] of Object.entries(value)) {
|
|
1332
|
+
if (!k.startsWith("_")) {
|
|
1333
|
+
result[k] = safeSerializeInner(v, depth + 1, seen);
|
|
1334
|
+
}
|
|
1335
|
+
}
|
|
1336
|
+
return result;
|
|
1337
|
+
} catch {
|
|
1338
|
+
return `<${className}>`;
|
|
1339
|
+
}
|
|
1340
|
+
}
|
|
1341
|
+
try {
|
|
1342
|
+
return String(value);
|
|
1343
|
+
} catch {
|
|
1344
|
+
return `<${className}>`;
|
|
1345
|
+
}
|
|
1346
|
+
}
|
|
1347
|
+
function convertMessage(message) {
|
|
1348
|
+
if (typeof message !== "object" || message === null) {
|
|
1349
|
+
return { role: "unknown", content: String(message) };
|
|
1350
|
+
}
|
|
1351
|
+
const msg = message;
|
|
1352
|
+
if (typeof msg.toDict === "function") {
|
|
1353
|
+
return msg.toDict();
|
|
1354
|
+
}
|
|
1355
|
+
const typeToRole = {
|
|
1356
|
+
human: "user",
|
|
1357
|
+
ai: "assistant",
|
|
1358
|
+
system: "system",
|
|
1359
|
+
tool: "tool",
|
|
1360
|
+
function: "function"
|
|
1361
|
+
};
|
|
1362
|
+
const result = {};
|
|
1363
|
+
const msgType = msg._getType ? String(msg._getType()) : msg.type;
|
|
1364
|
+
result.role = (msgType ? typeToRole[msgType] : void 0) ?? msg.role ?? "unknown";
|
|
1365
|
+
result.content = msg.content ?? "";
|
|
1366
|
+
if (msg.tool_calls) {
|
|
1367
|
+
result.tool_calls = msg.tool_calls;
|
|
1368
|
+
}
|
|
1369
|
+
if (msg.tool_call_id) {
|
|
1370
|
+
result.tool_call_id = msg.tool_call_id;
|
|
1371
|
+
}
|
|
1372
|
+
if (msg.name) {
|
|
1373
|
+
result.name = msg.name;
|
|
1374
|
+
}
|
|
1375
|
+
return result;
|
|
1376
|
+
}
|
|
1377
|
+
function extractModelName(serialized, metadata) {
|
|
1378
|
+
if (serialized) {
|
|
1379
|
+
const kwargs = serialized.kwargs;
|
|
1380
|
+
if (kwargs) {
|
|
1381
|
+
const model = kwargs.model_name ?? kwargs.model ?? kwargs.model_id;
|
|
1382
|
+
if (model) {
|
|
1383
|
+
return String(model);
|
|
1384
|
+
}
|
|
1385
|
+
}
|
|
1386
|
+
}
|
|
1387
|
+
if (metadata) {
|
|
1388
|
+
const lsModel = metadata.ls_model_name;
|
|
1389
|
+
if (lsModel) {
|
|
1390
|
+
return String(lsModel);
|
|
1391
|
+
}
|
|
1392
|
+
}
|
|
1393
|
+
return void 0;
|
|
1394
|
+
}
|
|
1395
|
+
function extractUsage2(output) {
|
|
1396
|
+
const usage = {};
|
|
1397
|
+
const llmOutput = output.llmOutput;
|
|
1398
|
+
const tokenUsage = llmOutput?.tokenUsage ?? llmOutput?.token_usage ?? llmOutput?.usage ?? {};
|
|
1399
|
+
const inputTokens = tokenUsage.promptTokens ?? tokenUsage.prompt_tokens ?? tokenUsage.input_tokens;
|
|
1400
|
+
const outputTokens = tokenUsage.completionTokens ?? tokenUsage.completion_tokens ?? tokenUsage.output_tokens;
|
|
1401
|
+
const totalTokens = tokenUsage.totalTokens ?? tokenUsage.total_tokens;
|
|
1402
|
+
if (inputTokens !== void 0 && inputTokens !== null) {
|
|
1403
|
+
usage.inputTokens = inputTokens;
|
|
1404
|
+
}
|
|
1405
|
+
if (outputTokens !== void 0 && outputTokens !== null) {
|
|
1406
|
+
usage.outputTokens = outputTokens;
|
|
1407
|
+
}
|
|
1408
|
+
if (totalTokens !== void 0 && totalTokens !== null) {
|
|
1409
|
+
usage.totalTokens = totalTokens;
|
|
1410
|
+
}
|
|
1411
|
+
return usage;
|
|
1412
|
+
}
|
|
1413
|
+
function extractLangGraphMetadata(metadata) {
|
|
1414
|
+
if (!metadata) {
|
|
1415
|
+
return {};
|
|
1416
|
+
}
|
|
1417
|
+
const result = {};
|
|
1418
|
+
for (const key of LANGGRAPH_METADATA_KEYS) {
|
|
1419
|
+
if (key in metadata) {
|
|
1420
|
+
result[key] = metadata[key];
|
|
1421
|
+
}
|
|
1422
|
+
}
|
|
1423
|
+
return result;
|
|
1424
|
+
}
|
|
1425
|
+
var BitfabLangGraphCallbackHandler = class {
|
|
1426
|
+
constructor(config) {
|
|
1427
|
+
this.name = "BitfabLangGraphCallbackHandler";
|
|
1428
|
+
this.ignoreRetriever = true;
|
|
1429
|
+
this.ignoreRetry = true;
|
|
1430
|
+
this.ignoreCustomEvent = true;
|
|
1431
|
+
this.runToSpan = /* @__PURE__ */ new Map();
|
|
1432
|
+
this.invocations = /* @__PURE__ */ new Map();
|
|
1433
|
+
this.httpClient = new HttpClient({
|
|
1434
|
+
apiKey: config.apiKey,
|
|
1435
|
+
serviceUrl: config.serviceUrl ?? DEFAULT_SERVICE_URL,
|
|
1436
|
+
timeout: config.timeout ?? 1e4
|
|
1437
|
+
});
|
|
1438
|
+
this.traceFunctionKey = config.traceFunctionKey;
|
|
1439
|
+
this.getActiveSpanContext = config.getActiveSpanContext ?? null;
|
|
1440
|
+
}
|
|
1441
|
+
// ── lifecycle helpers ──────────────────────────────────────────
|
|
1442
|
+
startSpan(runId, parentRunId, name, spanType, inputData, metadata, tags) {
|
|
1443
|
+
const parentSpan = parentRunId ? this.runToSpan.get(parentRunId) : void 0;
|
|
1444
|
+
const willHide = tags?.includes(LANGSMITH_HIDDEN_TAG) === true;
|
|
1445
|
+
let invocation;
|
|
1446
|
+
let effectiveParentId;
|
|
1447
|
+
if (parentSpan) {
|
|
1448
|
+
const existing = this.invocations.get(parentSpan.rootRunId);
|
|
1449
|
+
if (existing) {
|
|
1450
|
+
invocation = existing;
|
|
1451
|
+
} else {
|
|
1452
|
+
invocation = {
|
|
1453
|
+
traceId: parentSpan.traceId,
|
|
1454
|
+
activeContext: null,
|
|
1455
|
+
rootRunId: parentSpan.rootRunId
|
|
1456
|
+
};
|
|
1457
|
+
this.invocations.set(invocation.rootRunId, invocation);
|
|
1458
|
+
}
|
|
1459
|
+
if (!willHide) {
|
|
1460
|
+
let resolved = parentSpan;
|
|
1461
|
+
while (resolved?.hidden === true) {
|
|
1462
|
+
resolved = resolved.parentId ? this.runToSpan.get(resolved.parentId) : void 0;
|
|
1463
|
+
}
|
|
1464
|
+
effectiveParentId = resolved ? resolved.spanId : invocation.activeContext?.spanId ?? null;
|
|
1465
|
+
} else {
|
|
1466
|
+
effectiveParentId = parentRunId ?? null;
|
|
1467
|
+
}
|
|
1468
|
+
} else {
|
|
1469
|
+
const activeContext = this.getActiveSpanContext?.() ?? null;
|
|
1470
|
+
invocation = {
|
|
1471
|
+
traceId: activeContext ? activeContext.traceId : crypto.randomUUID(),
|
|
1472
|
+
activeContext,
|
|
1473
|
+
rootRunId: runId
|
|
1474
|
+
};
|
|
1475
|
+
this.invocations.set(runId, invocation);
|
|
1476
|
+
effectiveParentId = activeContext?.spanId ?? null;
|
|
1477
|
+
}
|
|
1478
|
+
const lgMetadata = extractLangGraphMetadata(metadata);
|
|
1479
|
+
const contexts = Object.keys(lgMetadata).length > 0 ? [lgMetadata] : [];
|
|
1480
|
+
const spanInfo = {
|
|
1481
|
+
spanId: runId,
|
|
1482
|
+
traceId: invocation.traceId,
|
|
1483
|
+
rootRunId: invocation.rootRunId,
|
|
1484
|
+
parentId: effectiveParentId,
|
|
1485
|
+
startedAt: nowIso2(),
|
|
1486
|
+
name,
|
|
1487
|
+
type: spanType,
|
|
1488
|
+
input: safeSerialize2(inputData),
|
|
1489
|
+
contexts
|
|
1490
|
+
};
|
|
1491
|
+
if (willHide) {
|
|
1492
|
+
spanInfo.hidden = true;
|
|
1493
|
+
}
|
|
1494
|
+
this.runToSpan.set(runId, spanInfo);
|
|
1495
|
+
return spanInfo;
|
|
1496
|
+
}
|
|
1497
|
+
completeSpan(runId, output, error, extraContexts) {
|
|
1498
|
+
const spanInfo = this.runToSpan.get(runId);
|
|
1499
|
+
if (!spanInfo) {
|
|
1500
|
+
return;
|
|
1501
|
+
}
|
|
1502
|
+
this.runToSpan.delete(runId);
|
|
1503
|
+
spanInfo.endedAt = nowIso2();
|
|
1504
|
+
spanInfo.output = safeSerialize2(output);
|
|
1505
|
+
if (error !== void 0) {
|
|
1506
|
+
spanInfo.error = error;
|
|
1507
|
+
}
|
|
1508
|
+
if (extraContexts && Object.keys(extraContexts).length > 0) {
|
|
1509
|
+
spanInfo.contexts.push(extraContexts);
|
|
1510
|
+
}
|
|
1511
|
+
this.sendSpan(spanInfo);
|
|
1512
|
+
if (runId === spanInfo.rootRunId) {
|
|
1513
|
+
const invocation = this.invocations.get(runId);
|
|
1514
|
+
this.sendTraceCompletion(spanInfo, invocation?.activeContext ?? null);
|
|
1515
|
+
this.invocations.delete(runId);
|
|
1516
|
+
}
|
|
1517
|
+
}
|
|
1518
|
+
sendSpan(spanInfo) {
|
|
1519
|
+
const spanData = {
|
|
1520
|
+
name: spanInfo.name,
|
|
1521
|
+
type: spanInfo.type
|
|
1522
|
+
};
|
|
1523
|
+
if (spanInfo.input !== void 0) {
|
|
1524
|
+
spanData.input = spanInfo.input;
|
|
1525
|
+
}
|
|
1526
|
+
if (spanInfo.output !== void 0) {
|
|
1527
|
+
spanData.output = spanInfo.output;
|
|
1528
|
+
}
|
|
1529
|
+
if (spanInfo.error !== void 0) {
|
|
1530
|
+
spanData.error = spanInfo.error;
|
|
1531
|
+
}
|
|
1532
|
+
if (spanInfo.contexts.length > 0) {
|
|
1533
|
+
spanData.contexts = spanInfo.contexts;
|
|
1534
|
+
}
|
|
1535
|
+
if (spanInfo.hidden) {
|
|
1536
|
+
spanData.hidden = true;
|
|
1537
|
+
}
|
|
1538
|
+
const rawSpan = {
|
|
1539
|
+
id: spanInfo.spanId,
|
|
1540
|
+
trace_id: spanInfo.traceId,
|
|
1541
|
+
started_at: spanInfo.startedAt,
|
|
1542
|
+
ended_at: spanInfo.endedAt ?? nowIso2(),
|
|
1543
|
+
span_data: spanData
|
|
1544
|
+
};
|
|
1545
|
+
if (spanInfo.parentId !== null) {
|
|
1546
|
+
rawSpan.parent_id = spanInfo.parentId;
|
|
1547
|
+
}
|
|
1548
|
+
const payload = {
|
|
1549
|
+
type: "sdk-function",
|
|
1550
|
+
source: "typescript-sdk-langgraph",
|
|
1551
|
+
traceFunctionKey: this.traceFunctionKey,
|
|
1552
|
+
sourceTraceId: spanInfo.traceId,
|
|
1553
|
+
rawSpan
|
|
1554
|
+
};
|
|
1555
|
+
try {
|
|
1556
|
+
this.httpClient.sendExternalSpan(payload);
|
|
1557
|
+
} catch {
|
|
1558
|
+
}
|
|
1559
|
+
}
|
|
1560
|
+
sendTraceCompletion(rootSpan, activeContext) {
|
|
1561
|
+
const completed = activeContext === null;
|
|
1562
|
+
const traceData = {
|
|
1563
|
+
type: "sdk-function",
|
|
1564
|
+
source: "typescript-sdk-langgraph",
|
|
1565
|
+
traceFunctionKey: this.traceFunctionKey,
|
|
1566
|
+
externalTrace: {
|
|
1567
|
+
id: rootSpan.traceId,
|
|
1568
|
+
started_at: rootSpan.startedAt,
|
|
1569
|
+
ended_at: rootSpan.endedAt ?? nowIso2(),
|
|
1570
|
+
workflow_name: this.traceFunctionKey
|
|
1571
|
+
},
|
|
1572
|
+
completed
|
|
1573
|
+
};
|
|
1574
|
+
try {
|
|
1575
|
+
this.httpClient.sendExternalTrace(traceData);
|
|
1576
|
+
} catch {
|
|
1577
|
+
}
|
|
1578
|
+
}
|
|
1579
|
+
// ── chain callbacks (graph nodes) ─────────────────────────────
|
|
1580
|
+
async handleChainStart(chain, inputs, runId, parentRunId, tags, metadata) {
|
|
1581
|
+
try {
|
|
1582
|
+
const idArr = chain.id;
|
|
1583
|
+
const name = chain.name ?? idArr?.[idArr.length - 1] ?? "chain";
|
|
1584
|
+
this.startSpan(
|
|
1585
|
+
runId,
|
|
1586
|
+
parentRunId,
|
|
1587
|
+
String(name),
|
|
1588
|
+
"agent",
|
|
1589
|
+
inputs,
|
|
1590
|
+
metadata,
|
|
1591
|
+
tags
|
|
1592
|
+
);
|
|
1593
|
+
} catch {
|
|
1594
|
+
}
|
|
1595
|
+
}
|
|
1596
|
+
async handleChainEnd(outputs, runId) {
|
|
1597
|
+
try {
|
|
1598
|
+
this.completeSpan(runId, outputs);
|
|
1599
|
+
} catch {
|
|
1600
|
+
}
|
|
1601
|
+
}
|
|
1602
|
+
async handleChainError(error, runId) {
|
|
1603
|
+
try {
|
|
1604
|
+
const errorObj = error;
|
|
1605
|
+
if (errorObj?.constructor?.name === "GraphBubbleUp") {
|
|
1606
|
+
this.completeSpan(runId, void 0, void 0);
|
|
1607
|
+
return;
|
|
1608
|
+
}
|
|
1609
|
+
this.completeSpan(
|
|
1610
|
+
runId,
|
|
1611
|
+
void 0,
|
|
1612
|
+
error instanceof Error ? error.message : String(error)
|
|
1613
|
+
);
|
|
1614
|
+
} catch {
|
|
1615
|
+
}
|
|
1616
|
+
}
|
|
1617
|
+
// ── LLM callbacks ─────────────────────────────────────────────
|
|
1618
|
+
async handleChatModelStart(llm, messages, runId, parentRunId, _extraParams, tags, metadata) {
|
|
1619
|
+
try {
|
|
1620
|
+
const model = extractModelName(llm, metadata);
|
|
1621
|
+
const idArr = llm.id;
|
|
1622
|
+
const name = model ?? idArr?.[idArr.length - 1] ?? "llm";
|
|
1623
|
+
const converted = messages.map((batch) => batch.map(convertMessage));
|
|
1624
|
+
const spanInfo = this.startSpan(
|
|
1625
|
+
runId,
|
|
1626
|
+
parentRunId,
|
|
1627
|
+
String(name),
|
|
1628
|
+
"llm",
|
|
1629
|
+
converted,
|
|
1630
|
+
metadata,
|
|
1631
|
+
tags
|
|
1632
|
+
);
|
|
1633
|
+
spanInfo.model = model;
|
|
1634
|
+
} catch {
|
|
1635
|
+
}
|
|
1636
|
+
}
|
|
1637
|
+
async handleLLMStart(llm, prompts, runId, parentRunId, _extraParams, tags, metadata) {
|
|
1638
|
+
try {
|
|
1639
|
+
const model = extractModelName(llm, metadata);
|
|
1640
|
+
const idArr = llm.id;
|
|
1641
|
+
const name = model ?? idArr?.[idArr.length - 1] ?? "llm";
|
|
1642
|
+
const spanInfo = this.startSpan(
|
|
1643
|
+
runId,
|
|
1644
|
+
parentRunId,
|
|
1645
|
+
String(name),
|
|
1646
|
+
"llm",
|
|
1647
|
+
prompts,
|
|
1648
|
+
metadata,
|
|
1649
|
+
tags
|
|
1650
|
+
);
|
|
1651
|
+
spanInfo.model = model;
|
|
1652
|
+
} catch {
|
|
1653
|
+
}
|
|
1654
|
+
}
|
|
1655
|
+
async handleLLMEnd(output, runId) {
|
|
1656
|
+
try {
|
|
1657
|
+
let llmOutput;
|
|
1658
|
+
const generations = output.generations;
|
|
1659
|
+
if (generations?.length && generations[generations.length - 1]?.length) {
|
|
1660
|
+
const gen = generations[generations.length - 1][generations[generations.length - 1].length - 1];
|
|
1661
|
+
const msg = gen.message;
|
|
1662
|
+
llmOutput = msg ? convertMessage(msg) : gen.text ?? String(gen);
|
|
1663
|
+
}
|
|
1664
|
+
const usage = extractUsage2(output);
|
|
1665
|
+
const spanInfo = this.runToSpan.get(runId);
|
|
1666
|
+
const model = spanInfo?.model;
|
|
1667
|
+
const llmContext = {};
|
|
1668
|
+
if (model) {
|
|
1669
|
+
llmContext.model = model;
|
|
1670
|
+
}
|
|
1671
|
+
Object.assign(llmContext, usage);
|
|
1672
|
+
this.completeSpan(
|
|
1673
|
+
runId,
|
|
1674
|
+
llmOutput,
|
|
1675
|
+
void 0,
|
|
1676
|
+
Object.keys(llmContext).length > 0 ? llmContext : void 0
|
|
1677
|
+
);
|
|
1678
|
+
} catch {
|
|
1679
|
+
}
|
|
1680
|
+
}
|
|
1681
|
+
async handleLLMError(error, runId) {
|
|
1682
|
+
try {
|
|
1683
|
+
this.completeSpan(
|
|
1684
|
+
runId,
|
|
1685
|
+
void 0,
|
|
1686
|
+
error instanceof Error ? error.message : String(error)
|
|
1687
|
+
);
|
|
1688
|
+
} catch {
|
|
1689
|
+
}
|
|
1690
|
+
}
|
|
1691
|
+
async handleLLMNewToken() {
|
|
1692
|
+
}
|
|
1693
|
+
// ── tool callbacks ────────────────────────────────────────────
|
|
1694
|
+
async handleToolStart(tool, input, runId, parentRunId, tags, metadata) {
|
|
1695
|
+
try {
|
|
1696
|
+
const name = tool.name ?? "tool";
|
|
1697
|
+
this.startSpan(
|
|
1698
|
+
runId,
|
|
1699
|
+
parentRunId,
|
|
1700
|
+
String(name),
|
|
1701
|
+
"function",
|
|
1702
|
+
input,
|
|
1703
|
+
metadata,
|
|
1704
|
+
tags
|
|
1705
|
+
);
|
|
1706
|
+
} catch {
|
|
1707
|
+
}
|
|
1708
|
+
}
|
|
1709
|
+
async handleToolEnd(output, runId) {
|
|
1710
|
+
try {
|
|
1711
|
+
this.completeSpan(runId, output);
|
|
1712
|
+
} catch {
|
|
1713
|
+
}
|
|
1714
|
+
}
|
|
1715
|
+
async handleToolError(error, runId) {
|
|
1716
|
+
try {
|
|
1717
|
+
this.completeSpan(
|
|
1718
|
+
runId,
|
|
1719
|
+
void 0,
|
|
1720
|
+
error instanceof Error ? error.message : String(error)
|
|
1721
|
+
);
|
|
1722
|
+
} catch {
|
|
1723
|
+
}
|
|
1724
|
+
}
|
|
1725
|
+
// ── retriever callbacks ───────────────────────────────────────
|
|
1726
|
+
async handleRetrieverStart(retriever, query, runId, parentRunId, tags, metadata) {
|
|
1727
|
+
try {
|
|
1728
|
+
const name = retriever.name ?? "retriever";
|
|
1729
|
+
this.startSpan(
|
|
1730
|
+
runId,
|
|
1731
|
+
parentRunId,
|
|
1732
|
+
String(name),
|
|
1733
|
+
"function",
|
|
1734
|
+
query,
|
|
1735
|
+
metadata,
|
|
1736
|
+
tags
|
|
1737
|
+
);
|
|
1738
|
+
} catch {
|
|
1739
|
+
}
|
|
1740
|
+
}
|
|
1741
|
+
async handleRetrieverEnd(documents, runId) {
|
|
1742
|
+
try {
|
|
1743
|
+
this.completeSpan(runId, documents);
|
|
1744
|
+
} catch {
|
|
1745
|
+
}
|
|
1746
|
+
}
|
|
1747
|
+
async handleRetrieverError(error, runId) {
|
|
1748
|
+
try {
|
|
1749
|
+
this.completeSpan(
|
|
1750
|
+
runId,
|
|
1751
|
+
void 0,
|
|
1752
|
+
error instanceof Error ? error.message : String(error)
|
|
1753
|
+
);
|
|
1754
|
+
} catch {
|
|
1755
|
+
}
|
|
1756
|
+
}
|
|
1757
|
+
};
|
|
1758
|
+
|
|
1759
|
+
// src/client.ts
|
|
804
1760
|
init_replayContext();
|
|
805
1761
|
init_serialize();
|
|
806
1762
|
|
|
@@ -1314,6 +2270,67 @@ var Bitfab = class {
|
|
|
1314
2270
|
}
|
|
1315
2271
|
});
|
|
1316
2272
|
}
|
|
2273
|
+
/**
|
|
2274
|
+
* Get a LangGraph/LangChain callback handler for tracing.
|
|
2275
|
+
*
|
|
2276
|
+
* The handler captures graph node execution, LLM calls, and tool
|
|
2277
|
+
* invocations as Bitfab spans with proper parent-child hierarchy.
|
|
2278
|
+
*
|
|
2279
|
+
* ```typescript
|
|
2280
|
+
* const handler = client.getLangGraphCallbackHandler("my-agent");
|
|
2281
|
+
* const result = await agent.invoke(
|
|
2282
|
+
* { messages: [...] },
|
|
2283
|
+
* { callbacks: [handler] },
|
|
2284
|
+
* );
|
|
2285
|
+
* ```
|
|
2286
|
+
*
|
|
2287
|
+
* @param traceFunctionKey - Groups traces under this key in Bitfab
|
|
2288
|
+
* @returns A BitfabLangGraphCallbackHandler configured for this client
|
|
2289
|
+
*/
|
|
2290
|
+
getLangGraphCallbackHandler(traceFunctionKey) {
|
|
2291
|
+
return new BitfabLangGraphCallbackHandler({
|
|
2292
|
+
apiKey: this.apiKey,
|
|
2293
|
+
traceFunctionKey,
|
|
2294
|
+
serviceUrl: this.serviceUrl,
|
|
2295
|
+
getActiveSpanContext: () => {
|
|
2296
|
+
const stack = getSpanStack();
|
|
2297
|
+
return stack[stack.length - 1] ?? null;
|
|
2298
|
+
}
|
|
2299
|
+
});
|
|
2300
|
+
}
|
|
2301
|
+
/**
|
|
2302
|
+
* Get a Claude Agent SDK handler for tracing.
|
|
2303
|
+
*
|
|
2304
|
+
* The handler captures LLM turns, tool invocations, and subagent
|
|
2305
|
+
* execution as Bitfab spans with proper parent-child hierarchy.
|
|
2306
|
+
*
|
|
2307
|
+
* ```typescript
|
|
2308
|
+
* const handler = client.getClaudeAgentHandler("my-agent");
|
|
2309
|
+
* const options = handler.instrumentOptions({
|
|
2310
|
+
* model: "claude-sonnet-4-5-...",
|
|
2311
|
+
* });
|
|
2312
|
+
* const sdkClient = new ClaudeSDKClient(options);
|
|
2313
|
+
* await sdkClient.connect();
|
|
2314
|
+
* await sdkClient.query("Do something");
|
|
2315
|
+
* for await (const msg of handler.wrapResponse(sdkClient.receiveResponse())) {
|
|
2316
|
+
* // process messages
|
|
2317
|
+
* }
|
|
2318
|
+
* ```
|
|
2319
|
+
*
|
|
2320
|
+
* @param traceFunctionKey - Groups traces under this key in Bitfab
|
|
2321
|
+
* @returns A BitfabClaudeAgentHandler configured for this client
|
|
2322
|
+
*/
|
|
2323
|
+
getClaudeAgentHandler(traceFunctionKey) {
|
|
2324
|
+
return new BitfabClaudeAgentHandler({
|
|
2325
|
+
apiKey: this.apiKey,
|
|
2326
|
+
traceFunctionKey,
|
|
2327
|
+
serviceUrl: this.serviceUrl,
|
|
2328
|
+
getActiveSpanContext: () => {
|
|
2329
|
+
const stack = getSpanStack();
|
|
2330
|
+
return stack[stack.length - 1] ?? null;
|
|
2331
|
+
}
|
|
2332
|
+
});
|
|
2333
|
+
}
|
|
1317
2334
|
/**
|
|
1318
2335
|
* Wrap a BAML client method to automatically capture prompt and LLM metadata.
|
|
1319
2336
|
*
|
|
@@ -1719,8 +2736,10 @@ init_http();
|
|
|
1719
2736
|
// Annotate the CommonJS export names for ESM import in node:
|
|
1720
2737
|
0 && (module.exports = {
|
|
1721
2738
|
Bitfab,
|
|
2739
|
+
BitfabClaudeAgentHandler,
|
|
1722
2740
|
BitfabError,
|
|
1723
2741
|
BitfabFunction,
|
|
2742
|
+
BitfabLangGraphCallbackHandler,
|
|
1724
2743
|
BitfabOpenAITracingProcessor,
|
|
1725
2744
|
DEFAULT_SERVICE_URL,
|
|
1726
2745
|
__version__,
|