@introspection-sdk/introspection-node 0.4.3 → 0.4.4

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 (122) hide show
  1. package/.turbo/turbo-build.log +1 -1
  2. package/dist/otel/anthropic.d.ts +14 -12
  3. package/dist/otel/anthropic.d.ts.map +1 -1
  4. package/dist/otel/anthropic.js +89 -47
  5. package/dist/otel/anthropic.js.map +1 -1
  6. package/dist/otel/gemini.d.ts +15 -7
  7. package/dist/otel/gemini.d.ts.map +1 -1
  8. package/dist/otel/gemini.js +88 -37
  9. package/dist/otel/gemini.js.map +1 -1
  10. package/dist/otel/index.d.ts +5 -0
  11. package/dist/otel/index.d.ts.map +1 -1
  12. package/dist/otel/index.js +8 -0
  13. package/dist/otel/index.js.map +1 -1
  14. package/dist/otel/init.d.ts +126 -0
  15. package/dist/otel/init.d.ts.map +1 -0
  16. package/dist/otel/init.js +259 -0
  17. package/dist/otel/init.js.map +1 -0
  18. package/dist/otel/integrations/anthropic.d.ts +10 -0
  19. package/dist/otel/integrations/anthropic.d.ts.map +1 -0
  20. package/dist/otel/integrations/anthropic.js +22 -0
  21. package/dist/otel/integrations/anthropic.js.map +1 -0
  22. package/dist/otel/integrations/base.d.ts +83 -0
  23. package/dist/otel/integrations/base.d.ts.map +1 -0
  24. package/dist/otel/integrations/base.js +23 -0
  25. package/dist/otel/integrations/base.js.map +1 -0
  26. package/dist/otel/integrations/claude-agent.d.ts +13 -0
  27. package/dist/otel/integrations/claude-agent.d.ts.map +1 -0
  28. package/dist/otel/integrations/claude-agent.js +27 -0
  29. package/dist/otel/integrations/claude-agent.js.map +1 -0
  30. package/dist/otel/integrations/gemini.d.ts +11 -0
  31. package/dist/otel/integrations/gemini.d.ts.map +1 -0
  32. package/dist/otel/integrations/gemini.js +21 -0
  33. package/dist/otel/integrations/gemini.js.map +1 -0
  34. package/dist/otel/integrations/index.d.ts +39 -0
  35. package/dist/otel/integrations/index.d.ts.map +1 -0
  36. package/dist/otel/integrations/index.js +131 -0
  37. package/dist/otel/integrations/index.js.map +1 -0
  38. package/dist/otel/integrations/langchain.d.ts +16 -0
  39. package/dist/otel/integrations/langchain.d.ts.map +1 -0
  40. package/dist/otel/integrations/langchain.js +41 -0
  41. package/dist/otel/integrations/langchain.js.map +1 -0
  42. package/dist/otel/integrations/mastra.d.ts +14 -0
  43. package/dist/otel/integrations/mastra.d.ts.map +1 -0
  44. package/dist/otel/integrations/mastra.js +27 -0
  45. package/dist/otel/integrations/mastra.js.map +1 -0
  46. package/dist/otel/integrations/openai-agents.d.ts +11 -0
  47. package/dist/otel/integrations/openai-agents.d.ts.map +1 -0
  48. package/dist/otel/integrations/openai-agents.js +25 -0
  49. package/dist/otel/integrations/openai-agents.js.map +1 -0
  50. package/dist/otel/integrations/pi.d.ts +12 -0
  51. package/dist/otel/integrations/pi.d.ts.map +1 -0
  52. package/dist/otel/integrations/pi.js +20 -0
  53. package/dist/otel/integrations/pi.js.map +1 -0
  54. package/dist/otel/integrations/vercel.d.ts +15 -0
  55. package/dist/otel/integrations/vercel.d.ts.map +1 -0
  56. package/dist/otel/integrations/vercel.js +20 -0
  57. package/dist/otel/integrations/vercel.js.map +1 -0
  58. package/dist/otel/register.d.ts +8 -0
  59. package/dist/otel/register.d.ts.map +1 -0
  60. package/dist/otel/register.js +48 -0
  61. package/dist/otel/register.js.map +1 -0
  62. package/dist/otel/setup.d.ts +29 -0
  63. package/dist/otel/setup.d.ts.map +1 -1
  64. package/dist/otel/setup.js +22 -3
  65. package/dist/otel/setup.js.map +1 -1
  66. package/dist/utils.d.ts +10 -0
  67. package/dist/utils.d.ts.map +1 -1
  68. package/dist/utils.js +12 -4
  69. package/dist/utils.js.map +1 -1
  70. package/package.json +17 -5
  71. package/src/otel/anthropic.ts +128 -63
  72. package/src/otel/gemini.ts +139 -45
  73. package/src/otel/index.ts +41 -0
  74. package/src/otel/init.ts +411 -0
  75. package/src/otel/integrations/anthropic.ts +26 -0
  76. package/src/otel/integrations/base.ts +95 -0
  77. package/src/otel/integrations/claude-agent.ts +32 -0
  78. package/src/otel/integrations/gemini.ts +25 -0
  79. package/src/otel/integrations/index.ts +151 -0
  80. package/src/otel/integrations/langchain.ts +45 -0
  81. package/src/otel/integrations/mastra.ts +30 -0
  82. package/src/otel/integrations/openai-agents.ts +31 -0
  83. package/src/otel/integrations/pi.ts +24 -0
  84. package/src/otel/integrations/vercel.ts +24 -0
  85. package/src/otel/register.ts +50 -0
  86. package/src/otel/setup.ts +44 -3
  87. package/src/utils.ts +12 -5
  88. package/.turbo/turbo-check-types.log +0 -4
  89. package/.turbo/turbo-lint.log +0 -5
  90. package/dist/ai-sdk-integration.d.ts +0 -123
  91. package/dist/ai-sdk-integration.d.ts.map +0 -1
  92. package/dist/ai-sdk-integration.js +0 -475
  93. package/dist/anthropic.d.ts +0 -54
  94. package/dist/anthropic.d.ts.map +0 -1
  95. package/dist/anthropic.js +0 -375
  96. package/dist/claude-hooks.d.ts +0 -328
  97. package/dist/claude-hooks.d.ts.map +0 -1
  98. package/dist/claude-hooks.js +0 -571
  99. package/dist/claude-wrapper.d.ts +0 -93
  100. package/dist/claude-wrapper.d.ts.map +0 -1
  101. package/dist/claude-wrapper.js +0 -154
  102. package/dist/converters/ai-sdk.d.ts +0 -65
  103. package/dist/converters/ai-sdk.d.ts.map +0 -1
  104. package/dist/converters/ai-sdk.js +0 -261
  105. package/dist/converters/openclaw.d.ts +0 -16
  106. package/dist/converters/openclaw.d.ts.map +0 -1
  107. package/dist/converters/openclaw.js +0 -49
  108. package/dist/langchain-handler.d.ts +0 -103
  109. package/dist/langchain-handler.d.ts.map +0 -1
  110. package/dist/langchain-handler.js +0 -518
  111. package/dist/mastra-exporter.d.ts +0 -85
  112. package/dist/mastra-exporter.d.ts.map +0 -1
  113. package/dist/mastra-exporter.js +0 -471
  114. package/dist/span-processor.d.ts +0 -62
  115. package/dist/span-processor.d.ts.map +0 -1
  116. package/dist/span-processor.js +0 -313
  117. package/dist/tracing-processor.d.ts +0 -136
  118. package/dist/tracing-processor.d.ts.map +0 -1
  119. package/dist/tracing-processor.js +0 -368
  120. package/dist/types/genai.d.ts +0 -165
  121. package/dist/types/genai.d.ts.map +0 -1
  122. package/dist/types/genai.js +0 -82
@@ -1,154 +0,0 @@
1
- /**
2
- * Claude Agent SDK Wrapper
3
- *
4
- * Provides a zero-friction `withIntrospection()` wrapper for the Claude Agent SDK.
5
- * Automatically instruments all query() calls with OpenTelemetry tracing via
6
- * IntrospectionClaudeHooks — no manual hook wiring or recordUsage() calls needed.
7
- *
8
- * @example
9
- * ```typescript
10
- * import * as sdk from "@anthropic-ai/claude-agent-sdk";
11
- * import { withIntrospection } from "@introspection-sdk/introspection-node";
12
- *
13
- * const tracedSdk = withIntrospection(sdk, { serviceName: "my-agent" });
14
- *
15
- * for await (const message of tracedSdk.query({ prompt: "Hello" })) {
16
- * // messages yielded normally — tracing happens automatically
17
- * }
18
- *
19
- * await tracedSdk.shutdown();
20
- * ```
21
- */
22
- import { IntrospectionClaudeHooks, } from "./claude-hooks.js";
23
- import { logger } from "./utils.js";
24
- // --- Implementation ---
25
- /**
26
- * Wrap the Claude Agent SDK module to automatically instrument every
27
- * `query()` call with OpenTelemetry tracing.
28
- *
29
- * The returned SDK:
30
- * - Auto-captures `prompt` and `systemPrompt` from query params
31
- * - Injects instrumentation hooks (merged with any user-provided hooks)
32
- * - Calls {@link IntrospectionClaudeHooks.recordUsage | recordUsage()} on
33
- * every streamed message automatically
34
- * - Flushes spans when each query stream completes
35
- *
36
- * @param sdk - The Claude Agent SDK module
37
- * (`import * as sdk from "@anthropic-ai/claude-agent-sdk"`).
38
- * @param options - Introspection configuration (token, serviceName, baseUrl, etc.).
39
- * @returns An {@link InstrumentedClaudeAgentSDK} with the same API plus
40
- * `forceFlush()`, `shutdown()`, and `hooks`.
41
- *
42
- * @example
43
- * ```ts
44
- * import * as sdk from "@anthropic-ai/claude-agent-sdk";
45
- * import { withIntrospection } from "@introspection-sdk/introspection-node";
46
- *
47
- * const traced = withIntrospection(sdk, { serviceName: "my-agent" });
48
- * for await (const msg of traced.query({ prompt: "Hello" })) { /* … *\/ }
49
- * await traced.shutdown();
50
- * ```
51
- */
52
- export function withIntrospection(sdk, options) {
53
- const hooks = new IntrospectionClaudeHooks(options);
54
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
55
- function wrappedQuery(params) {
56
- // Auto-capture prompt
57
- if (typeof params?.prompt === "string") {
58
- hooks.setInputPrompt(params.prompt);
59
- }
60
- // Auto-capture systemPrompt from options
61
- const opts = (params?.options || {});
62
- if (typeof opts.systemPrompt === "string") {
63
- hooks.setSystemInstructions(opts.systemPrompt);
64
- }
65
- // Merge instrumentation hooks with any user-provided hooks
66
- const introspectionHooks = hooks.getHooks();
67
- const userHooks = opts.hooks;
68
- const mergedHooks = mergeHooks(introspectionHooks, userHooks);
69
- // Call original query with merged hooks
70
- const modifiedOptions = { ...opts, hooks: mergedHooks };
71
- const originalQuery = sdk.query({
72
- ...params,
73
- options: modifiedOptions,
74
- });
75
- // Wrap the async generator to intercept messages
76
- return wrapQueryResult(originalQuery, hooks);
77
- }
78
- return {
79
- ...sdk,
80
- query: wrappedQuery,
81
- hooks,
82
- forceFlush: () => hooks.forceFlush(),
83
- shutdown: () => hooks.shutdown(),
84
- };
85
- }
86
- /**
87
- * Merges introspection hooks with user-provided hooks.
88
- * Introspection hooks fire first, then user hooks.
89
- * User hooks on events we don't handle pass through untouched.
90
- */
91
- function mergeHooks(introspectionHooks, userHooks) {
92
- if (!userHooks) {
93
- return introspectionHooks;
94
- }
95
- const merged = {};
96
- const allEvents = new Set([
97
- ...Object.keys(introspectionHooks),
98
- ...Object.keys(userHooks),
99
- ]);
100
- for (const event of allEvents) {
101
- const ours = introspectionHooks[event] || [];
102
- const theirs = userHooks[event] || [];
103
- merged[event] = [...ours, ...theirs];
104
- }
105
- return merged;
106
- }
107
- /**
108
- * Wraps a Query async generator to intercept messages for usage recording.
109
- * Uses a Proxy to transparently forward all non-iterator properties
110
- * (interrupt, close, setModel, etc.) to the original Query object.
111
- */
112
- function wrapQueryResult(originalQuery, hooks) {
113
- const query = originalQuery;
114
- async function* instrumentedIterator() {
115
- try {
116
- for await (const message of query) {
117
- hooks.recordUsage(message);
118
- yield message;
119
- }
120
- }
121
- finally {
122
- try {
123
- await hooks.forceFlush();
124
- }
125
- catch (flushError) {
126
- logger.warn("Failed to flush spans after query completed", flushError);
127
- }
128
- }
129
- }
130
- const wrapped = instrumentedIterator();
131
- // Use Proxy to transparently delegate non-iterator properties to original query.
132
- // Iterator protocol methods come from our wrapper (bound to the actual generator
133
- // to avoid "incompatible receiver" errors); everything else (interrupt, close,
134
- // setModel, setPermissionMode, etc.) delegates to the original Query.
135
- return new Proxy(wrapped, {
136
- get(target, prop) {
137
- if (prop === Symbol.asyncIterator ||
138
- prop === "next" ||
139
- prop === "return" ||
140
- prop === "throw") {
141
- const value = Reflect.get(target, prop);
142
- if (typeof value === "function") {
143
- return value.bind(target);
144
- }
145
- return value;
146
- }
147
- const original = query[prop];
148
- if (typeof original === "function") {
149
- return original.bind(query);
150
- }
151
- return original;
152
- },
153
- });
154
- }
@@ -1,65 +0,0 @@
1
- /**
2
- * Converter for AI SDK event data → Gen AI semantic conventions.
3
- *
4
- * Converts typed event objects (messages, tool definitions, step results)
5
- * from the AI SDK's TelemetryIntegration callbacks into the standardized
6
- * gen_ai format used by the Introspection backend.
7
- *
8
- * Used by {@link IntrospectionAISDKIntegration}.
9
- */
10
- import type { InputMessage, OutputMessage, SystemInstruction, ToolDefinition } from "@introspection-sdk/types";
11
- /**
12
- * Convert AI SDK messages (ModelMessage[]) to gen_ai InputMessage[].
13
- * System messages are excluded — they're handled separately via
14
- * {@link extractSystemInstructions}.
15
- *
16
- * @param messages - Array of AI SDK ModelMessage objects.
17
- * @returns Array of gen_ai InputMessage objects (without system messages).
18
- */
19
- export declare function convertMessagesToInputMessages(messages: readonly unknown[]): InputMessage[];
20
- /**
21
- * Extract gen_ai system instructions from AI SDK's system field and messages.
22
- *
23
- * The AI SDK provides system prompts in two places:
24
- * - The `system` parameter (string, SystemModelMessage, or array)
25
- * - Messages with role "system"
26
- *
27
- * @param system - The AI SDK `system` field.
28
- * @param messages - The messages array (may contain system-role messages).
29
- * @returns System instructions in gen_ai format, or undefined if none.
30
- */
31
- export declare function extractSystemInstructions(system: unknown, messages: readonly unknown[]): SystemInstruction[] | undefined;
32
- /**
33
- * Build gen_ai output messages from AI SDK step result data.
34
- *
35
- * Combines text, reasoning, and tool call outputs into a single assistant
36
- * OutputMessage, mirroring the order used by vercel.ts (reasoning → text → tool calls).
37
- *
38
- * @param options - Step result fields.
39
- * @returns Array of gen_ai OutputMessage objects.
40
- */
41
- export declare function buildOutputMessages(options: {
42
- text?: string;
43
- reasoningText?: string;
44
- reasoning?: readonly {
45
- text?: string;
46
- }[];
47
- toolCalls?: readonly {
48
- toolCallId: string;
49
- toolName: string;
50
- input: unknown;
51
- }[];
52
- finishReason?: string;
53
- }): OutputMessage[];
54
- /**
55
- * Convert AI SDK ToolSet to gen_ai ToolDefinition[].
56
- *
57
- * The AI SDK represents tools as `Record<string, Tool>` where each Tool has
58
- * description and parameters (usually a Zod schema). We extract what we can
59
- * without importing Zod.
60
- *
61
- * @param tools - AI SDK ToolSet (Record<string, Tool>).
62
- * @returns Array of gen_ai ToolDefinition objects, or undefined if no tools.
63
- */
64
- export declare function convertToolsToToolDefinitions(tools: unknown): ToolDefinition[] | undefined;
65
- //# sourceMappingURL=ai-sdk.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"ai-sdk.d.ts","sourceRoot":"","sources":["../../src/converters/ai-sdk.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAEH,OAAO,KAAK,EACV,YAAY,EACZ,aAAa,EACb,iBAAiB,EACjB,cAAc,EAEf,MAAM,0BAA0B,CAAC;AAuBlC;;;;;;;GAOG;AACH,wBAAgB,8BAA8B,CAC5C,QAAQ,EAAE,SAAS,OAAO,EAAE,GAC3B,YAAY,EAAE,CAQhB;AAED;;;;;;;;;;GAUG;AACH,wBAAgB,yBAAyB,CACvC,MAAM,EAAE,OAAO,EACf,QAAQ,EAAE,SAAS,OAAO,EAAE,GAC3B,iBAAiB,EAAE,GAAG,SAAS,CAoCjC;AAED;;;;;;;;GAQG;AACH,wBAAgB,mBAAmB,CAAC,OAAO,EAAE;IAC3C,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB,SAAS,CAAC,EAAE,SAAS;QAAE,IAAI,CAAC,EAAE,MAAM,CAAA;KAAE,EAAE,CAAC;IACzC,SAAS,CAAC,EAAE,SAAS;QACnB,UAAU,EAAE,MAAM,CAAC;QACnB,QAAQ,EAAE,MAAM,CAAC;QACjB,KAAK,EAAE,OAAO,CAAC;KAChB,EAAE,CAAC;IACJ,YAAY,CAAC,EAAE,MAAM,CAAC;CACvB,GAAG,aAAa,EAAE,CAuClB;AAED;;;;;;;;;GASG;AACH,wBAAgB,6BAA6B,CAC3C,KAAK,EAAE,OAAO,GACb,cAAc,EAAE,GAAG,SAAS,CAgB9B"}
@@ -1,261 +0,0 @@
1
- /**
2
- * Converter for AI SDK event data → Gen AI semantic conventions.
3
- *
4
- * Converts typed event objects (messages, tool definitions, step results)
5
- * from the AI SDK's TelemetryIntegration callbacks into the standardized
6
- * gen_ai format used by the Introspection backend.
7
- *
8
- * Used by {@link IntrospectionAISDKIntegration}.
9
- */
10
- // ---------------------------------------------------------------------------
11
- // Public conversion functions
12
- // ---------------------------------------------------------------------------
13
- /**
14
- * Convert AI SDK messages (ModelMessage[]) to gen_ai InputMessage[].
15
- * System messages are excluded — they're handled separately via
16
- * {@link extractSystemInstructions}.
17
- *
18
- * @param messages - Array of AI SDK ModelMessage objects.
19
- * @returns Array of gen_ai InputMessage objects (without system messages).
20
- */
21
- export function convertMessagesToInputMessages(messages) {
22
- const result = [];
23
- for (const msg of messages) {
24
- const m = msg;
25
- if (!m || !m.role || m.role === "system")
26
- continue;
27
- result.push(convertOneMessage(m));
28
- }
29
- return result;
30
- }
31
- /**
32
- * Extract gen_ai system instructions from AI SDK's system field and messages.
33
- *
34
- * The AI SDK provides system prompts in two places:
35
- * - The `system` parameter (string, SystemModelMessage, or array)
36
- * - Messages with role "system"
37
- *
38
- * @param system - The AI SDK `system` field.
39
- * @param messages - The messages array (may contain system-role messages).
40
- * @returns System instructions in gen_ai format, or undefined if none.
41
- */
42
- export function extractSystemInstructions(system, messages) {
43
- const instructions = [];
44
- // From the `system` field
45
- if (typeof system === "string" && system) {
46
- instructions.push({ type: "text", content: system });
47
- }
48
- else if (system && typeof system === "object") {
49
- if (Array.isArray(system)) {
50
- for (const s of system) {
51
- const text = extractTextFromSystemMessage(s);
52
- if (text)
53
- instructions.push({ type: "text", content: text });
54
- }
55
- }
56
- else {
57
- const text = extractTextFromSystemMessage(system);
58
- if (text)
59
- instructions.push({ type: "text", content: text });
60
- }
61
- }
62
- // From system-role messages
63
- for (const msg of messages) {
64
- const m = msg;
65
- if (m?.role === "system") {
66
- const content = m.content;
67
- if (typeof content === "string") {
68
- instructions.push({ type: "text", content });
69
- }
70
- else if (Array.isArray(content)) {
71
- const text = content
72
- .filter((p) => p.type === "text")
73
- .map((p) => p.text || "")
74
- .join("");
75
- if (text)
76
- instructions.push({ type: "text", content: text });
77
- }
78
- }
79
- }
80
- return instructions.length > 0 ? instructions : undefined;
81
- }
82
- /**
83
- * Build gen_ai output messages from AI SDK step result data.
84
- *
85
- * Combines text, reasoning, and tool call outputs into a single assistant
86
- * OutputMessage, mirroring the order used by vercel.ts (reasoning → text → tool calls).
87
- *
88
- * @param options - Step result fields.
89
- * @returns Array of gen_ai OutputMessage objects.
90
- */
91
- export function buildOutputMessages(options) {
92
- const parts = [];
93
- // Reasoning first (mirrors vercel.ts order)
94
- if (options.reasoningText) {
95
- parts.push({ type: "thinking", content: options.reasoningText });
96
- }
97
- else if (options.reasoning?.length) {
98
- for (const r of options.reasoning) {
99
- if (r.text)
100
- parts.push({ type: "thinking", content: r.text });
101
- }
102
- }
103
- // Text content
104
- if (options.text) {
105
- parts.push({ type: "text", content: options.text });
106
- }
107
- // Tool calls
108
- if (options.toolCalls?.length) {
109
- for (const tc of options.toolCalls) {
110
- parts.push({
111
- type: "tool_call",
112
- name: tc.toolName,
113
- id: tc.toolCallId,
114
- arguments: typeof tc.input === "string" ? tc.input : JSON.stringify(tc.input),
115
- });
116
- }
117
- }
118
- if (parts.length === 0)
119
- return [];
120
- return [
121
- {
122
- role: "assistant",
123
- parts,
124
- finish_reason: options.finishReason,
125
- },
126
- ];
127
- }
128
- /**
129
- * Convert AI SDK ToolSet to gen_ai ToolDefinition[].
130
- *
131
- * The AI SDK represents tools as `Record<string, Tool>` where each Tool has
132
- * description and parameters (usually a Zod schema). We extract what we can
133
- * without importing Zod.
134
- *
135
- * @param tools - AI SDK ToolSet (Record<string, Tool>).
136
- * @returns Array of gen_ai ToolDefinition objects, or undefined if no tools.
137
- */
138
- export function convertToolsToToolDefinitions(tools) {
139
- if (!tools || typeof tools !== "object")
140
- return undefined;
141
- const defs = [];
142
- for (const [name, tool] of Object.entries(tools)) {
143
- if (!tool || typeof tool !== "object")
144
- continue;
145
- const t = tool;
146
- defs.push({
147
- name,
148
- description: typeof t.description === "string" ? t.description : undefined,
149
- parameters: extractToolParameters(t.inputSchema ?? t.parameters),
150
- });
151
- }
152
- return defs.length > 0 ? defs : undefined;
153
- }
154
- // ---------------------------------------------------------------------------
155
- // Internal helpers
156
- // ---------------------------------------------------------------------------
157
- function convertOneMessage(msg) {
158
- const role = (msg.role || "user");
159
- const content = msg.content;
160
- const parts = [];
161
- if (typeof content === "string") {
162
- parts.push({ type: "text", content });
163
- }
164
- else if (Array.isArray(content)) {
165
- for (const part of content) {
166
- const converted = convertContentPart(part);
167
- if (converted)
168
- parts.push(converted);
169
- }
170
- }
171
- return { role, parts };
172
- }
173
- function convertContentPart(part) {
174
- switch (part.type) {
175
- case "text":
176
- return { type: "text", content: part.text || "" };
177
- case "tool-call": {
178
- const args = part.args ?? part.input;
179
- return {
180
- type: "tool_call",
181
- name: part.toolName || "",
182
- id: part.toolCallId || "",
183
- arguments: typeof args === "string" ? args : JSON.stringify(args ?? {}),
184
- };
185
- }
186
- case "tool-result": {
187
- const rawResult = part.result ?? part.output;
188
- let response;
189
- if (typeof rawResult === "string") {
190
- response = rawResult;
191
- }
192
- else if (rawResult &&
193
- typeof rawResult === "object" &&
194
- "value" in rawResult) {
195
- response = JSON.stringify(rawResult.value);
196
- }
197
- else {
198
- response = JSON.stringify(rawResult);
199
- }
200
- return {
201
- type: "tool_call_response",
202
- id: part.toolCallId || "",
203
- response,
204
- };
205
- }
206
- case "reasoning":
207
- return { type: "thinking", content: part.text || "" };
208
- default:
209
- // Unknown part type — serialize as text fallback
210
- return { type: "text", content: JSON.stringify(part) };
211
- }
212
- }
213
- function extractTextFromSystemMessage(msg) {
214
- if (typeof msg === "string")
215
- return msg;
216
- if (msg && typeof msg === "object") {
217
- const m = msg;
218
- if (typeof m.content === "string")
219
- return m.content;
220
- if (typeof m.text === "string")
221
- return m.text;
222
- }
223
- return null;
224
- }
225
- function extractToolParameters(parameters) {
226
- if (!parameters || typeof parameters !== "object")
227
- return undefined;
228
- const p = parameters;
229
- // Zod 4 schema — exposes a toJSONSchema() method.
230
- if (typeof p.toJSONSchema === "function") {
231
- const jsonSchema = p.toJSONSchema();
232
- if (jsonSchema && typeof jsonSchema === "object") {
233
- return jsonSchema;
234
- }
235
- }
236
- // AI SDK v6 tools expose inputSchema instead of parameters. Zod-backed
237
- // schemas usually carry a JSON Schema factory on this property.
238
- if (p["~standard"] && typeof p["~standard"] === "object") {
239
- const standard = p["~standard"];
240
- const standardJsonSchema = standard.jsonSchema;
241
- if (standardJsonSchema && typeof standardJsonSchema === "object") {
242
- const input = standardJsonSchema.input;
243
- if (typeof input === "function") {
244
- const jsonSchema = input();
245
- if (jsonSchema && typeof jsonSchema === "object") {
246
- return jsonSchema;
247
- }
248
- }
249
- return standardJsonSchema;
250
- }
251
- }
252
- // jsonSchema() wrapper — has a jsonSchema property
253
- if (p.jsonSchema && typeof p.jsonSchema === "object") {
254
- return p.jsonSchema;
255
- }
256
- // Plain JSON Schema object (has 'type' and 'properties')
257
- if (p.type === "object" && p.properties) {
258
- return p;
259
- }
260
- return undefined;
261
- }
@@ -1,16 +0,0 @@
1
- import type { Attributes } from "@opentelemetry/api";
2
- /**
3
- * Detect openclaw spans by the presence of openclaw.* attributes.
4
- * openclaw does not set a distinguishing instrumentation scope, so we
5
- * use attribute-key presence instead.
6
- */
7
- export declare function isOpenClawSpan(attrs?: Attributes): boolean;
8
- /**
9
- * Replace mapped openclaw.* attributes with gen_ai semantic conventions.
10
- * Unmapped openclaw.* attributes (e.g. openclaw.channel, openclaw.sessionId)
11
- * are preserved unchanged.
12
- */
13
- export declare function replaceOpenClawWithGenAI(
14
- attrs?: Attributes,
15
- ): Attributes;
16
- //# sourceMappingURL=openclaw.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"openclaw.d.ts","sourceRoot":"","sources":["../../src/converters/openclaw.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,oBAAoB,CAAC;AAiBrD;;;;GAIG;AACH,wBAAgB,cAAc,CAAC,KAAK,CAAC,EAAE,UAAU,GAAG,OAAO,CAG1D;AAED;;;;GAIG;AACH,wBAAgB,wBAAwB,CAAC,KAAK,CAAC,EAAE,UAAU,GAAG,UAAU,CAyBvE"}
@@ -1,49 +0,0 @@
1
- /**
2
- * OpenClaw attribute keys that have gen_ai semantic convention equivalents.
3
- * Other openclaw.* attributes (channel, sessionId, lane, etc.) are preserved as-is.
4
- *
5
- * @see https://github.com/openclaw/openclaw/tree/main/extensions/diagnostics-otel
6
- */
7
- const OC = {
8
- MODEL: "openclaw.model",
9
- PROVIDER: "openclaw.provider",
10
- TOKENS_INPUT: "openclaw.tokens.input",
11
- TOKENS_OUTPUT: "openclaw.tokens.output",
12
- };
13
- const MAPPED_KEYS = new Set(Object.values(OC));
14
- /**
15
- * Detect openclaw spans by the presence of openclaw.* attributes.
16
- * openclaw does not set a distinguishing instrumentation scope, so we
17
- * use attribute-key presence instead.
18
- */
19
- export function isOpenClawSpan(attrs) {
20
- if (!attrs) return false;
21
- return Object.keys(attrs).some((key) => key.startsWith("openclaw."));
22
- }
23
- /**
24
- * Replace mapped openclaw.* attributes with gen_ai semantic conventions.
25
- * Unmapped openclaw.* attributes (e.g. openclaw.channel, openclaw.sessionId)
26
- * are preserved unchanged.
27
- */
28
- export function replaceOpenClawWithGenAI(attrs) {
29
- if (!attrs) return {};
30
- const result = {};
31
- for (const [key, value] of Object.entries(attrs)) {
32
- if (!MAPPED_KEYS.has(key)) {
33
- result[key] = value;
34
- }
35
- }
36
- if (attrs[OC.MODEL] !== undefined) {
37
- result["gen_ai.request.model"] = attrs[OC.MODEL];
38
- }
39
- if (attrs[OC.PROVIDER] !== undefined) {
40
- result["gen_ai.system"] = attrs[OC.PROVIDER];
41
- }
42
- if (attrs[OC.TOKENS_INPUT] !== undefined) {
43
- result["gen_ai.usage.input_tokens"] = attrs[OC.TOKENS_INPUT];
44
- }
45
- if (attrs[OC.TOKENS_OUTPUT] !== undefined) {
46
- result["gen_ai.usage.output_tokens"] = attrs[OC.TOKENS_OUTPUT];
47
- }
48
- return result;
49
- }
@@ -1,103 +0,0 @@
1
- /**
2
- * LangChain/LangGraph Callback Handler for Introspection.
3
- *
4
- * Hooks into LangChain's native callback system to capture LLM, tool, and
5
- * chain interactions as gen_ai.* OTel spans for the Introspection backend.
6
- *
7
- * Similar to IntrospectionTracingProcessor for OpenAI Agents SDK and
8
- * IntrospectionClaudeHooks for Claude Agent SDK.
9
- *
10
- * **Important:** This module requires `@langchain/core` at runtime.
11
- * Import via the subpath: `@introspection-sdk/introspection-node/langchain`
12
- *
13
- * @example
14
- * ```ts
15
- * import { IntrospectionCallbackHandler } from "@introspection-sdk/introspection-node/langchain";
16
- * import { ChatOpenAI } from "@langchain/openai";
17
- *
18
- * const handler = new IntrospectionCallbackHandler({
19
- * serviceName: "my-langchain-app",
20
- * });
21
- *
22
- * const model = new ChatOpenAI({ modelName: "gpt-4o" });
23
- * const response = await model.invoke("Hello!", { callbacks: [handler] });
24
- *
25
- * await handler.shutdown();
26
- * ```
27
- */
28
- import { BaseCallbackHandler } from "@langchain/core/callbacks/base";
29
- import type { Serialized } from "@langchain/core/load/serializable";
30
- import type { LLMResult } from "@langchain/core/outputs";
31
- import type { BaseMessage } from "@langchain/core/messages";
32
- import type { ChainValues } from "@langchain/core/utils/types";
33
- import { type SpanExporter, type IdGenerator } from "@opentelemetry/sdk-trace-base";
34
- /** Advanced options for testing and customization. */
35
- export interface LangChainHandlerAdvancedOptions {
36
- /** Custom span exporter for testing. */
37
- spanExporter?: SpanExporter;
38
- /** Custom ID generator for testing. */
39
- idGenerator?: IdGenerator;
40
- /** Use SimpleSpanProcessor instead of BatchSpanProcessor. */
41
- useSimpleSpanProcessor?: boolean;
42
- }
43
- /** Configuration for {@link IntrospectionCallbackHandler}. */
44
- export interface IntrospectionCallbackHandlerOptions {
45
- /** Authentication token (env: INTROSPECTION_TOKEN). */
46
- token?: string;
47
- /** Base URL for the API (env: INTROSPECTION_BASE_URL). */
48
- baseUrl?: string;
49
- /** Service name for telemetry (env: INTROSPECTION_SERVICE_NAME). */
50
- serviceName?: string;
51
- /** Additional headers to include in requests. */
52
- additionalHeaders?: Record<string, string>;
53
- /** Advanced options for testing. */
54
- advanced?: LangChainHandlerAdvancedOptions;
55
- }
56
- /**
57
- * LangChain callback handler that captures LLM, tool, and chain events
58
- * as gen_ai.* OTel spans and exports them to the Introspection backend.
59
- *
60
- * Pass as a callback to any LangChain invoke call, or set globally via
61
- * `setGlobalHandler()`.
62
- */
63
- export declare class IntrospectionCallbackHandler extends BaseCallbackHandler {
64
- name: string;
65
- private _tracerProvider;
66
- private _tracer;
67
- private _spans;
68
- private _conversationId;
69
- private _spanNames;
70
- private _spanParents;
71
- private _runRoots;
72
- private static _wrapperNames;
73
- private _llmInputs;
74
- constructor(options?: IntrospectionCallbackHandlerOptions);
75
- private _rootRunId;
76
- /** Keep the top-level run span aligned with child conversation IDs. */
77
- private _setRootConversationId;
78
- private _endRootIfComplete;
79
- /** Create a span under a LangChain parent when one exists.
80
- * Sets gen_ai.agent.name to the parent span's name for hierarchy. */
81
- private _createChildSpan;
82
- handleChatModelStart(llm: Serialized, messages: BaseMessage[][], runId: string, parentRunId?: string, extraParams?: Record<string, unknown>, _tags?: string[], metadata?: Record<string, unknown>, runName?: string): void;
83
- handleLLMStart(llm: Serialized, prompts: string[], runId: string, parentRunId?: string, extraParams?: Record<string, unknown>, _tags?: string[], metadata?: Record<string, unknown>, runName?: string): void;
84
- handleLLMEnd(output: LLMResult, runId: string): void;
85
- handleLLMError(err: Error, runId: string): void;
86
- handleChainStart(chain: Serialized, _inputs: ChainValues, runId: string, _runType?: string, _tags?: string[], metadata?: Record<string, unknown>, runName?: string, parentRunId?: string): void;
87
- handleChainEnd(_outputs: ChainValues, runId: string): void;
88
- handleChainError(err: Error, runId: string): void;
89
- handleToolStart(tool: Serialized, input: string, runId: string, parentRunId?: string, _tags?: string[], metadata?: Record<string, unknown>, runName?: string): void;
90
- handleToolEnd(output: unknown, runId: string): void;
91
- handleToolError(err: Error, runId: string): void;
92
- shutdown(): Promise<void>;
93
- forceFlush(): Promise<void>;
94
- private _extractModelName;
95
- private _extractProvider;
96
- /** Walk up the span tree to find the first non-wrapper span name. */
97
- private _findAgentName;
98
- private _getConversationId;
99
- private _convertMessages;
100
- private _mapRole;
101
- private _extractContent;
102
- }
103
- //# sourceMappingURL=langchain-handler.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"langchain-handler.d.ts","sourceRoot":"","sources":["../src/langchain-handler.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;GA0BG;AAEH,OAAO,EAAE,mBAAmB,EAAE,MAAM,gCAAgC,CAAC;AAC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