@introspection-sdk/introspection-node 0.4.2 → 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 (219) hide show
  1. package/.turbo/turbo-build.log +1 -1
  2. package/dist/client.d.ts +42 -132
  3. package/dist/client.d.ts.map +1 -1
  4. package/dist/client.js +67 -366
  5. package/dist/client.js.map +1 -0
  6. package/dist/converters/claude.d.ts +4 -0
  7. package/dist/converters/claude.d.ts.map +1 -1
  8. package/dist/converters/claude.js +7 -0
  9. package/dist/converters/claude.js.map +1 -0
  10. package/dist/converters/gemini.d.ts +90 -0
  11. package/dist/converters/gemini.d.ts.map +1 -0
  12. package/dist/converters/gemini.js +171 -0
  13. package/dist/converters/gemini.js.map +1 -0
  14. package/dist/converters/index.d.ts +1 -1
  15. package/dist/converters/index.d.ts.map +1 -1
  16. package/dist/converters/index.js +2 -1
  17. package/dist/converters/index.js.map +1 -0
  18. package/dist/converters/openai.js +1 -0
  19. package/dist/converters/openai.js.map +1 -0
  20. package/dist/converters/openinference.js +1 -0
  21. package/dist/converters/openinference.js.map +1 -0
  22. package/dist/converters/vercel.d.ts.map +1 -1
  23. package/dist/converters/vercel.js +31 -3
  24. package/dist/converters/vercel.js.map +1 -0
  25. package/dist/http.d.ts +36 -0
  26. package/dist/http.d.ts.map +1 -0
  27. package/dist/http.js +145 -0
  28. package/dist/http.js.map +1 -0
  29. package/dist/index.d.ts +24 -27
  30. package/dist/index.d.ts.map +1 -1
  31. package/dist/index.js +22 -32
  32. package/dist/index.js.map +1 -0
  33. package/dist/{anthropic.d.ts → otel/anthropic.d.ts} +23 -13
  34. package/dist/otel/anthropic.d.ts.map +1 -0
  35. package/dist/{anthropic.js → otel/anthropic.js} +132 -40
  36. package/dist/otel/anthropic.js.map +1 -0
  37. package/dist/{claude-hooks.d.ts → otel/claude-hooks.d.ts} +19 -1
  38. package/dist/otel/claude-hooks.d.ts.map +1 -0
  39. package/dist/{claude-hooks.js → otel/claude-hooks.js} +94 -20
  40. package/dist/otel/claude-hooks.js.map +1 -0
  41. package/dist/otel/claude-wrapper.d.ts.map +1 -0
  42. package/dist/{claude-wrapper.js → otel/claude-wrapper.js} +2 -1
  43. package/dist/otel/claude-wrapper.js.map +1 -0
  44. package/dist/otel/gemini.d.ts +56 -0
  45. package/dist/otel/gemini.d.ts.map +1 -0
  46. package/dist/otel/gemini.js +348 -0
  47. package/dist/otel/gemini.js.map +1 -0
  48. package/dist/otel/index.d.ts +32 -0
  49. package/dist/otel/index.d.ts.map +1 -0
  50. package/dist/otel/index.js +41 -0
  51. package/dist/otel/index.js.map +1 -0
  52. package/dist/otel/init.d.ts +126 -0
  53. package/dist/otel/init.d.ts.map +1 -0
  54. package/dist/otel/init.js +259 -0
  55. package/dist/otel/init.js.map +1 -0
  56. package/dist/otel/integrations/anthropic.d.ts +10 -0
  57. package/dist/otel/integrations/anthropic.d.ts.map +1 -0
  58. package/dist/otel/integrations/anthropic.js +22 -0
  59. package/dist/otel/integrations/anthropic.js.map +1 -0
  60. package/dist/otel/integrations/base.d.ts +83 -0
  61. package/dist/otel/integrations/base.d.ts.map +1 -0
  62. package/dist/otel/integrations/base.js +23 -0
  63. package/dist/otel/integrations/base.js.map +1 -0
  64. package/dist/otel/integrations/claude-agent.d.ts +13 -0
  65. package/dist/otel/integrations/claude-agent.d.ts.map +1 -0
  66. package/dist/otel/integrations/claude-agent.js +27 -0
  67. package/dist/otel/integrations/claude-agent.js.map +1 -0
  68. package/dist/otel/integrations/gemini.d.ts +11 -0
  69. package/dist/otel/integrations/gemini.d.ts.map +1 -0
  70. package/dist/otel/integrations/gemini.js +21 -0
  71. package/dist/otel/integrations/gemini.js.map +1 -0
  72. package/dist/otel/integrations/index.d.ts +39 -0
  73. package/dist/otel/integrations/index.d.ts.map +1 -0
  74. package/dist/otel/integrations/index.js +131 -0
  75. package/dist/otel/integrations/index.js.map +1 -0
  76. package/dist/otel/integrations/langchain.d.ts +16 -0
  77. package/dist/otel/integrations/langchain.d.ts.map +1 -0
  78. package/dist/otel/integrations/langchain.js +41 -0
  79. package/dist/otel/integrations/langchain.js.map +1 -0
  80. package/dist/otel/integrations/mastra.d.ts +14 -0
  81. package/dist/otel/integrations/mastra.d.ts.map +1 -0
  82. package/dist/otel/integrations/mastra.js +27 -0
  83. package/dist/otel/integrations/mastra.js.map +1 -0
  84. package/dist/otel/integrations/openai-agents.d.ts +11 -0
  85. package/dist/otel/integrations/openai-agents.d.ts.map +1 -0
  86. package/dist/otel/integrations/openai-agents.js +25 -0
  87. package/dist/otel/integrations/openai-agents.js.map +1 -0
  88. package/dist/otel/integrations/pi.d.ts +12 -0
  89. package/dist/otel/integrations/pi.d.ts.map +1 -0
  90. package/dist/otel/integrations/pi.js +20 -0
  91. package/dist/otel/integrations/pi.js.map +1 -0
  92. package/dist/otel/integrations/vercel.d.ts +15 -0
  93. package/dist/otel/integrations/vercel.d.ts.map +1 -0
  94. package/dist/otel/integrations/vercel.js +20 -0
  95. package/dist/otel/integrations/vercel.js.map +1 -0
  96. package/dist/{langchain-handler.d.ts → otel/langchain-handler.d.ts} +10 -1
  97. package/dist/otel/langchain-handler.d.ts.map +1 -0
  98. package/dist/{langchain-handler.js → otel/langchain-handler.js} +43 -6
  99. package/dist/otel/langchain-handler.js.map +1 -0
  100. package/dist/otel/logs.d.ts +82 -0
  101. package/dist/otel/logs.d.ts.map +1 -0
  102. package/dist/otel/logs.js +271 -0
  103. package/dist/otel/logs.js.map +1 -0
  104. package/dist/{mastra-exporter.d.ts → otel/mastra-exporter.d.ts} +3 -1
  105. package/dist/otel/mastra-exporter.d.ts.map +1 -0
  106. package/dist/{mastra-exporter.js → otel/mastra-exporter.js} +71 -17
  107. package/dist/otel/mastra-exporter.js.map +1 -0
  108. package/dist/otel/pi.d.ts +59 -0
  109. package/dist/otel/pi.d.ts.map +1 -0
  110. package/dist/otel/pi.js +67 -0
  111. package/dist/otel/pi.js.map +1 -0
  112. package/dist/otel/register.d.ts +8 -0
  113. package/dist/otel/register.d.ts.map +1 -0
  114. package/dist/otel/register.js +48 -0
  115. package/dist/otel/register.js.map +1 -0
  116. package/dist/otel/setup.d.ts +52 -0
  117. package/dist/otel/setup.d.ts.map +1 -0
  118. package/dist/otel/setup.js +146 -0
  119. package/dist/otel/setup.js.map +1 -0
  120. package/dist/{span-processor.d.ts → otel/span-processor.d.ts} +1 -1
  121. package/dist/otel/span-processor.d.ts.map +1 -0
  122. package/dist/{span-processor.js → otel/span-processor.js} +11 -5
  123. package/dist/otel/span-processor.js.map +1 -0
  124. package/dist/{tracing-processor.d.ts → otel/tracing-processor.d.ts} +4 -1
  125. package/dist/otel/tracing-processor.d.ts.map +1 -0
  126. package/dist/{tracing-processor.js → otel/tracing-processor.js} +64 -14
  127. package/dist/otel/tracing-processor.js.map +1 -0
  128. package/dist/resources/experiments.d.ts +31 -0
  129. package/dist/resources/experiments.d.ts.map +1 -0
  130. package/dist/resources/experiments.js +133 -0
  131. package/dist/resources/experiments.js.map +1 -0
  132. package/dist/resources/recipes.d.ts +22 -0
  133. package/dist/resources/recipes.d.ts.map +1 -0
  134. package/dist/resources/recipes.js +61 -0
  135. package/dist/resources/recipes.js.map +1 -0
  136. package/dist/resources/runtimes.d.ts +76 -0
  137. package/dist/resources/runtimes.d.ts.map +1 -0
  138. package/dist/resources/runtimes.js +179 -0
  139. package/dist/resources/runtimes.js.map +1 -0
  140. package/dist/runner-resources/files.d.ts +35 -0
  141. package/dist/runner-resources/files.d.ts.map +1 -0
  142. package/dist/runner-resources/files.js +131 -0
  143. package/dist/runner-resources/files.js.map +1 -0
  144. package/dist/runner-resources/tasks.d.ts +39 -0
  145. package/dist/runner-resources/tasks.d.ts.map +1 -0
  146. package/dist/runner-resources/tasks.js +129 -0
  147. package/dist/runner-resources/tasks.js.map +1 -0
  148. package/dist/runner.d.ts +80 -0
  149. package/dist/runner.d.ts.map +1 -0
  150. package/dist/runner.js +159 -0
  151. package/dist/runner.js.map +1 -0
  152. package/dist/streaming.d.ts +8 -0
  153. package/dist/streaming.d.ts.map +1 -0
  154. package/dist/streaming.js +67 -0
  155. package/dist/streaming.js.map +1 -0
  156. package/dist/types.js +1 -0
  157. package/dist/types.js.map +1 -0
  158. package/dist/utils.d.ts +10 -0
  159. package/dist/utils.d.ts.map +1 -1
  160. package/dist/utils.js +13 -4
  161. package/dist/utils.js.map +1 -0
  162. package/dist/version.js +1 -0
  163. package/dist/version.js.map +1 -0
  164. package/package.json +91 -22
  165. package/src/client.ts +76 -473
  166. package/src/converters/claude.ts +10 -0
  167. package/src/converters/gemini.ts +243 -0
  168. package/src/converters/index.ts +13 -7
  169. package/src/converters/vercel.ts +41 -3
  170. package/src/http.ts +163 -0
  171. package/src/index.ts +110 -75
  172. package/src/{anthropic.ts → otel/anthropic.ts} +206 -54
  173. package/src/{claude-hooks.ts → otel/claude-hooks.ts} +119 -20
  174. package/src/{claude-wrapper.ts → otel/claude-wrapper.ts} +1 -1
  175. package/src/otel/gemini.ts +491 -0
  176. package/src/otel/index.ts +121 -0
  177. package/src/otel/init.ts +411 -0
  178. package/src/otel/integrations/anthropic.ts +26 -0
  179. package/src/otel/integrations/base.ts +95 -0
  180. package/src/otel/integrations/claude-agent.ts +32 -0
  181. package/src/otel/integrations/gemini.ts +25 -0
  182. package/src/otel/integrations/index.ts +151 -0
  183. package/src/otel/integrations/langchain.ts +45 -0
  184. package/src/otel/integrations/mastra.ts +30 -0
  185. package/src/otel/integrations/openai-agents.ts +31 -0
  186. package/src/otel/integrations/pi.ts +24 -0
  187. package/src/otel/integrations/vercel.ts +24 -0
  188. package/src/{langchain-handler.ts → otel/langchain-handler.ts} +53 -6
  189. package/src/otel/logs.ts +394 -0
  190. package/src/{mastra-exporter.ts → otel/mastra-exporter.ts} +83 -22
  191. package/src/otel/pi.ts +88 -0
  192. package/src/otel/register.ts +50 -0
  193. package/src/otel/setup.ts +215 -0
  194. package/src/{span-processor.ts → otel/span-processor.ts} +11 -6
  195. package/src/{tracing-processor.ts → otel/tracing-processor.ts} +94 -19
  196. package/src/resources/experiments.ts +170 -0
  197. package/src/resources/recipes.ts +73 -0
  198. package/src/resources/runtimes.ts +231 -0
  199. package/src/runner-resources/files.ts +163 -0
  200. package/src/runner-resources/tasks.ts +156 -0
  201. package/src/runner.ts +194 -0
  202. package/src/streaming.ts +57 -0
  203. package/src/utils.ts +12 -5
  204. package/dist/ai-sdk-integration.d.ts +0 -123
  205. package/dist/ai-sdk-integration.d.ts.map +0 -1
  206. package/dist/ai-sdk-integration.js +0 -475
  207. package/dist/anthropic.d.ts.map +0 -1
  208. package/dist/claude-hooks.d.ts.map +0 -1
  209. package/dist/claude-wrapper.d.ts.map +0 -1
  210. package/dist/converters/ai-sdk.d.ts +0 -65
  211. package/dist/converters/ai-sdk.d.ts.map +0 -1
  212. package/dist/converters/ai-sdk.js +0 -261
  213. package/dist/langchain-handler.d.ts.map +0 -1
  214. package/dist/mastra-exporter.d.ts.map +0 -1
  215. package/dist/span-processor.d.ts.map +0 -1
  216. package/dist/tracing-processor.d.ts.map +0 -1
  217. package/src/ai-sdk-integration.ts +0 -691
  218. package/src/converters/ai-sdk.ts +0 -323
  219. /package/dist/{claude-wrapper.d.ts → otel/claude-wrapper.d.ts} +0 -0
@@ -0,0 +1,491 @@
1
+ /**
2
+ * Lightweight Google Gemini (`@google/genai`) instrumentor for Introspection SDK.
3
+ *
4
+ * Captures the full Gemini response including per-part `thoughtSignature`
5
+ * payloads (Gemini 3.x extended thinking) as gen_ai `thinking` parts with
6
+ * `signature` set — mirroring how the {@link AnthropicInstrumentor} captures
7
+ * Anthropic thinking blocks.
8
+ *
9
+ * Supports both non-streaming (`client.models.generateContent`) and streaming
10
+ * (`client.models.generateContentStream`) calls.
11
+ *
12
+ * @example
13
+ * ```ts
14
+ * import { GoogleGenAI } from "@google/genai";
15
+ * import { GeminiInstrumentor } from "@introspection-sdk/introspection-node";
16
+ *
17
+ * const client = new GoogleGenAI({ apiKey: process.env.GEMINI_API_KEY });
18
+ * new GeminiInstrumentor().instrument({ tracerProvider: provider, client });
19
+ * // All client.models.generateContent / generateContentStream calls are now traced
20
+ * ```
21
+ *
22
+ * @see https://ai.google.dev/gemini-api/docs/thought-signatures
23
+ */
24
+
25
+ import { trace, SpanKind, SpanStatusCode } from "@opentelemetry/api";
26
+ import type { Tracer, Span } from "@opentelemetry/api";
27
+ import type { BasicTracerProvider } from "@opentelemetry/sdk-trace-base";
28
+
29
+ import type { InputMessage, OutputMessage } from "@introspection-sdk/types";
30
+ import {
31
+ convertGeminiContentsToInputMessages,
32
+ convertGeminiCandidatesToOutputMessages,
33
+ convertGeminiSystemInstructionToSemconv,
34
+ convertGeminiToolsToToolDefinitions,
35
+ GEMINI_PROVIDER_NAME,
36
+ type GeminiCandidate,
37
+ type GeminiContent,
38
+ type GeminiPart,
39
+ type GeminiTool,
40
+ } from "../converters/gemini.js";
41
+
42
+ // ---------------------------------------------------------------------------
43
+ // Span helpers
44
+ // ---------------------------------------------------------------------------
45
+
46
+ function serializeMessages(msgs: InputMessage[] | OutputMessage[]): string {
47
+ return JSON.stringify(
48
+ msgs.map((m) => {
49
+ const obj: Record<string, unknown> = { role: m.role, parts: m.parts };
50
+ if ("finish_reason" in m && m.finish_reason) {
51
+ obj.finish_reason = m.finish_reason;
52
+ }
53
+ return obj;
54
+ }),
55
+ );
56
+ }
57
+
58
+ function startSpan(
59
+ tracer: Tracer,
60
+ model: string,
61
+ conversationId?: string,
62
+ ): Span {
63
+ return tracer.startSpan("chat", {
64
+ kind: SpanKind.CLIENT,
65
+ attributes: {
66
+ "gen_ai.system": GEMINI_PROVIDER_NAME,
67
+ "gen_ai.provider.name": GEMINI_PROVIDER_NAME,
68
+ "gen_ai.operation.name": "chat",
69
+ "gen_ai.request.model": model,
70
+ "openinference.span.kind": "LLM",
71
+ ...(conversationId
72
+ ? { "gen_ai.conversation.id": conversationId }
73
+ : undefined),
74
+ },
75
+ });
76
+ }
77
+
78
+ function setRequestAttrs(span: Span, kwargs: Record<string, unknown>): void {
79
+ const contents = kwargs.contents as
80
+ | string
81
+ | GeminiContent[]
82
+ | GeminiContent
83
+ | undefined;
84
+ const inputMsgs = convertGeminiContentsToInputMessages(contents);
85
+ if (inputMsgs.length > 0) {
86
+ span.setAttribute("gen_ai.input.messages", serializeMessages(inputMsgs));
87
+ }
88
+
89
+ const config = (kwargs.config as Record<string, unknown> | undefined) || {};
90
+
91
+ const systemInstruction = config.systemInstruction as
92
+ | string
93
+ | GeminiContent
94
+ | undefined;
95
+ const systemInstructions =
96
+ convertGeminiSystemInstructionToSemconv(systemInstruction);
97
+ if (systemInstructions && systemInstructions.length > 0) {
98
+ span.setAttribute(
99
+ "gen_ai.system_instructions",
100
+ JSON.stringify(systemInstructions),
101
+ );
102
+ }
103
+
104
+ const tools = config.tools as GeminiTool[] | undefined;
105
+ const toolDefs = convertGeminiToolsToToolDefinitions(tools);
106
+ if (toolDefs && toolDefs.length > 0) {
107
+ span.setAttribute("gen_ai.tool.definitions", JSON.stringify(toolDefs));
108
+ }
109
+ }
110
+
111
+ function setUsageAttrs(
112
+ span: Span,
113
+ usage: Record<string, unknown> | undefined,
114
+ ): void {
115
+ if (!usage) return;
116
+ const promptTokens = usage.promptTokenCount as number | undefined;
117
+ const candidateTokens = usage.candidatesTokenCount as number | undefined;
118
+ const cachedTokens = usage.cachedContentTokenCount as number | undefined;
119
+ const thoughtTokens = usage.thoughtsTokenCount as number | undefined;
120
+ if (typeof promptTokens === "number") {
121
+ span.setAttribute("gen_ai.usage.input_tokens", promptTokens);
122
+ }
123
+ if (typeof candidateTokens === "number") {
124
+ // Gemini reports candidatesTokenCount separately from thoughtsTokenCount;
125
+ // sum them so output_tokens reflects everything billed as model output.
126
+ const total = candidateTokens + (thoughtTokens ?? 0);
127
+ span.setAttribute("gen_ai.usage.output_tokens", total);
128
+ } else if (typeof thoughtTokens === "number") {
129
+ span.setAttribute("gen_ai.usage.output_tokens", thoughtTokens);
130
+ }
131
+ if (typeof cachedTokens === "number") {
132
+ span.setAttribute("gen_ai.usage.cache_read.input_tokens", cachedTokens);
133
+ }
134
+ }
135
+
136
+ function setResponseAttrs(span: Span, response: Record<string, unknown>): void {
137
+ const candidates = response.candidates as GeminiCandidate[] | undefined;
138
+ const outputMsgs = convertGeminiCandidatesToOutputMessages(candidates);
139
+ if (outputMsgs.length > 0) {
140
+ span.setAttribute("gen_ai.output.messages", serializeMessages(outputMsgs));
141
+ const finishReasons = outputMsgs
142
+ .map((m) => m.finish_reason)
143
+ .filter((r): r is string => typeof r === "string");
144
+ if (finishReasons.length > 0) {
145
+ span.setAttribute("gen_ai.response.finish_reasons", finishReasons);
146
+ }
147
+ }
148
+
149
+ const responseId = response.responseId as string | undefined;
150
+ if (responseId) span.setAttribute("gen_ai.response.id", responseId);
151
+
152
+ const modelVersion = response.modelVersion as string | undefined;
153
+ if (modelVersion) span.setAttribute("gen_ai.response.model", modelVersion);
154
+
155
+ setUsageAttrs(span, response.usageMetadata as Record<string, unknown>);
156
+
157
+ span.setStatus({ code: SpanStatusCode.OK });
158
+ }
159
+
160
+ // ---------------------------------------------------------------------------
161
+ // Streaming aggregator
162
+ // ---------------------------------------------------------------------------
163
+
164
+ interface StreamChunk {
165
+ candidates?: GeminiCandidate[];
166
+ usageMetadata?: Record<string, unknown>;
167
+ responseId?: string;
168
+ modelVersion?: string;
169
+ }
170
+
171
+ /** True if a streamed part is just incremental text with no metadata to preserve. */
172
+ function isPlainTextPart(part: GeminiPart): boolean {
173
+ return (
174
+ typeof part.text === "string" &&
175
+ part.thought !== true &&
176
+ !part.thoughtSignature &&
177
+ !part.functionCall &&
178
+ !part.functionResponse
179
+ );
180
+ }
181
+
182
+ /**
183
+ * Async-iterable wrapper that aggregates streamed `GenerateContentResponse`
184
+ * chunks so the underlying span captures the complete final message — including
185
+ * the final per-part `thoughtSignature` values that only arrive on the last
186
+ * chunk of a streamed turn.
187
+ */
188
+ class TracedStream implements AsyncIterable<StreamChunk> {
189
+ private aggregated: Map<number, GeminiCandidate> = new Map();
190
+ private usage: Record<string, unknown> | undefined;
191
+ private responseId: string | undefined;
192
+ private modelVersion: string | undefined;
193
+ private finalized = false;
194
+
195
+ constructor(
196
+ private readonly inner: AsyncIterable<StreamChunk>,
197
+ private readonly span: Span,
198
+ ) {}
199
+
200
+ async *[Symbol.asyncIterator](): AsyncIterableIterator<StreamChunk> {
201
+ try {
202
+ for await (const chunk of this.inner) {
203
+ this.processChunk(chunk);
204
+ yield chunk;
205
+ }
206
+ } catch (err) {
207
+ this.span.setStatus({
208
+ code: SpanStatusCode.ERROR,
209
+ message: String(err),
210
+ });
211
+ this.span.end();
212
+ this.finalized = true;
213
+ throw err;
214
+ } finally {
215
+ this.finalize();
216
+ }
217
+ }
218
+
219
+ private processChunk(chunk: StreamChunk): void {
220
+ if (chunk.responseId) this.responseId = chunk.responseId;
221
+ if (chunk.modelVersion) this.modelVersion = chunk.modelVersion;
222
+ if (chunk.usageMetadata) this.usage = chunk.usageMetadata;
223
+ for (const cand of chunk.candidates ?? []) {
224
+ const idx = cand.index ?? 0;
225
+ const existing = this.aggregated.get(idx);
226
+ if (!existing) {
227
+ this.aggregated.set(idx, {
228
+ index: idx,
229
+ finishReason: cand.finishReason,
230
+ content: {
231
+ role: cand.content?.role,
232
+ parts: [...(cand.content?.parts ?? [])],
233
+ },
234
+ });
235
+ continue;
236
+ }
237
+ if (cand.finishReason) existing.finishReason = cand.finishReason;
238
+ if (cand.content?.role && !existing.content?.role) {
239
+ existing.content!.role = cand.content.role;
240
+ }
241
+ this.mergeParts(
242
+ existing.content!.parts as GeminiPart[],
243
+ cand.content?.parts ?? [],
244
+ );
245
+ }
246
+ }
247
+
248
+ /**
249
+ * Merge streamed parts into the aggregated parts list.
250
+ *
251
+ * Gemini streams text incrementally as separate `text`-only parts; thought
252
+ * signatures and function calls arrive as their own parts. Consecutive
253
+ * plain-text parts are coalesced into a single accumulating text part so the
254
+ * final thought signature on a block survives on its trailing part.
255
+ */
256
+ private mergeParts(target: GeminiPart[], incoming: GeminiPart[]): void {
257
+ for (const part of incoming) {
258
+ const last = target[target.length - 1];
259
+ if (isPlainTextPart(part) && last && isPlainTextPart(last)) {
260
+ last.text = (last.text || "") + (part.text || "");
261
+ continue;
262
+ }
263
+ target.push({ ...part });
264
+ }
265
+ }
266
+
267
+ private finalize(): void {
268
+ if (this.finalized) return;
269
+ this.finalized = true;
270
+ setResponseAttrs(this.span, {
271
+ candidates: Array.from(this.aggregated.values()),
272
+ usageMetadata: this.usage,
273
+ responseId: this.responseId,
274
+ modelVersion: this.modelVersion,
275
+ });
276
+ this.span.end();
277
+ }
278
+ }
279
+
280
+ // ---------------------------------------------------------------------------
281
+ // Public API
282
+ // ---------------------------------------------------------------------------
283
+
284
+ // The instrumentor patches `client.models.generateContent[Stream]` in place.
285
+ // We accept the client as `any` (matching AnthropicInstrumentor) so the typed
286
+ // SDK shape from `@google/genai` is compatible without consumers needing
287
+ // to cast at the call site.
288
+ interface GeminiModelsApi {
289
+ generateContent: (...args: unknown[]) => Promise<unknown>;
290
+ generateContentStream?: (...args: unknown[]) => Promise<unknown>;
291
+ }
292
+
293
+ /**
294
+ * Auto-instrumentor that wraps a `@google/genai` client instance to add
295
+ * Introspection tracing with full thought-signature capture.
296
+ *
297
+ * Captures all content parts including thought summaries and signed
298
+ * `thoughtSignature` payloads required for multi-turn replay.
299
+ */
300
+ /**
301
+ * Build the traced replacement for a non-streaming `generateContent`-style
302
+ * method. Shared by {@link GeminiInstrumentor.instrument} (patches a client's
303
+ * public `models.generateContent`) and {@link GeminiInstrumentor.instrumentClass}
304
+ * (patches `Models.prototype.generateContentInternal` so every client is
305
+ * auto-traced). Preserves the call-site `this`.
306
+ */
307
+ function buildTracedGenerate(
308
+ origGenerate: (...args: unknown[]) => Promise<unknown>,
309
+ tracer: Tracer,
310
+ conversationId: string,
311
+ ): (...args: unknown[]) => Promise<unknown> {
312
+ return async function tracedGenerate(this: unknown, ...args: unknown[]) {
313
+ const kwargs = (args[0] as Record<string, unknown>) || {};
314
+ const span = startSpan(
315
+ tracer,
316
+ (kwargs.model as string) || "unknown",
317
+ conversationId,
318
+ );
319
+ setRequestAttrs(span, kwargs);
320
+ try {
321
+ const response = (await origGenerate.apply(this, args)) as Record<
322
+ string,
323
+ unknown
324
+ >;
325
+ setResponseAttrs(span, response);
326
+ return response;
327
+ } catch (err) {
328
+ span.setStatus({ code: SpanStatusCode.ERROR, message: String(err) });
329
+ throw err;
330
+ } finally {
331
+ span.end();
332
+ }
333
+ };
334
+ }
335
+
336
+ /** Build the traced replacement for a streaming `generateContentStream`-style method. */
337
+ function buildTracedGenerateStream(
338
+ origStream: (...args: unknown[]) => Promise<unknown>,
339
+ tracer: Tracer,
340
+ conversationId: string,
341
+ ): (...args: unknown[]) => Promise<unknown> {
342
+ return async function tracedGenerateStream(
343
+ this: unknown,
344
+ ...args: unknown[]
345
+ ) {
346
+ const kwargs = (args[0] as Record<string, unknown>) || {};
347
+ const span = startSpan(
348
+ tracer,
349
+ (kwargs.model as string) || "unknown",
350
+ conversationId,
351
+ );
352
+ setRequestAttrs(span, kwargs);
353
+ try {
354
+ const stream = (await origStream.apply(
355
+ this,
356
+ args,
357
+ )) as AsyncIterable<StreamChunk>;
358
+ return new TracedStream(stream, span);
359
+ } catch (err) {
360
+ span.setStatus({ code: SpanStatusCode.ERROR, message: String(err) });
361
+ span.end();
362
+ throw err;
363
+ }
364
+ };
365
+ }
366
+
367
+ /**
368
+ * Marker placed on a patched `Models.prototype` method so repeated
369
+ * `instrumentClass()` calls (e.g. a second `introspection.init()`) are no-ops.
370
+ */
371
+ const PATCHED = Symbol.for("introspection.gemini.patched");
372
+
373
+ export class GeminiInstrumentor {
374
+ private tracer: Tracer | null = null;
375
+ private restores: Array<() => void> = [];
376
+ private conversationId: string | undefined;
377
+
378
+ instrument(opts: {
379
+ tracerProvider?: BasicTracerProvider;
380
+ /** A `@google/genai` `GoogleGenAI` client instance. */
381
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
382
+ client: any;
383
+ /**
384
+ * Conversation ID shared across all spans produced by this instrumentor.
385
+ * Defaults to a random UUID generated at `instrument()` time.
386
+ */
387
+ conversationId?: string;
388
+ }): void {
389
+ const { client } = opts;
390
+ if (!client?.models?.generateContent) {
391
+ throw new Error(
392
+ "Invalid client — pass a GoogleGenAI client instance (new GoogleGenAI({...}))",
393
+ );
394
+ }
395
+
396
+ this.conversationId = opts.conversationId ?? crypto.randomUUID();
397
+
398
+ const provider = opts.tracerProvider ?? trace.getTracerProvider();
399
+ this.tracer = (provider as BasicTracerProvider).getTracer(
400
+ "introspection-gemini",
401
+ );
402
+ const tracer = this.tracer;
403
+ const conversationId = this.conversationId;
404
+
405
+ const api = client.models as GeminiModelsApi;
406
+ const origGenerate = api.generateContent.bind(api);
407
+ const origGenerateStream = api.generateContentStream?.bind(api);
408
+ this.restores.push(() => {
409
+ api.generateContent = origGenerate;
410
+ if (origGenerateStream) api.generateContentStream = origGenerateStream;
411
+ });
412
+
413
+ api.generateContent = buildTracedGenerate(
414
+ origGenerate,
415
+ tracer,
416
+ conversationId,
417
+ ) as GeminiModelsApi["generateContent"];
418
+
419
+ if (origGenerateStream) {
420
+ api.generateContentStream = buildTracedGenerateStream(
421
+ origGenerateStream,
422
+ tracer,
423
+ conversationId,
424
+ ) as GeminiModelsApi["generateContentStream"];
425
+ }
426
+ }
427
+
428
+ /**
429
+ * Patch `Models.prototype.generateContentInternal` / `…StreamInternal` so
430
+ * **every** `GoogleGenAI` client is traced — the one-liner path used by
431
+ * `introspection.init()`. The public `generateContent` /
432
+ * `generateContentStream` are per-instance bound class fields that delegate
433
+ * to these prototype methods, so patching the prototype covers all clients.
434
+ * Idempotent: a second call is a no-op.
435
+ *
436
+ * @param opts.genai The `@google/genai` module (must expose `Models`).
437
+ */
438
+ instrumentClass(opts: {
439
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
440
+ genai: any;
441
+ tracerProvider?: BasicTracerProvider;
442
+ conversationId?: string;
443
+ }): void {
444
+ const proto = opts.genai?.Models?.prototype;
445
+ if (typeof proto?.generateContentInternal !== "function") {
446
+ throw new Error(
447
+ "Invalid @google/genai module — expected `Models.prototype.generateContentInternal`",
448
+ );
449
+ }
450
+ if (proto.generateContentInternal[PATCHED]) return;
451
+
452
+ this.conversationId = opts.conversationId ?? crypto.randomUUID();
453
+ const provider = opts.tracerProvider ?? trace.getTracerProvider();
454
+ this.tracer = (provider as BasicTracerProvider).getTracer(
455
+ "introspection-gemini",
456
+ );
457
+ const conversationId = this.conversationId;
458
+
459
+ const origGenerate = proto.generateContentInternal;
460
+ const patchedGenerate = buildTracedGenerate(
461
+ origGenerate,
462
+ this.tracer,
463
+ conversationId,
464
+ ) as ((...args: unknown[]) => Promise<unknown>) & { [PATCHED]?: boolean };
465
+ patchedGenerate[PATCHED] = true;
466
+ proto.generateContentInternal = patchedGenerate;
467
+ this.restores.push(() => {
468
+ proto.generateContentInternal = origGenerate;
469
+ });
470
+
471
+ if (typeof proto.generateContentStreamInternal === "function") {
472
+ const origStream = proto.generateContentStreamInternal;
473
+ const patchedStream = buildTracedGenerateStream(
474
+ origStream,
475
+ this.tracer,
476
+ conversationId,
477
+ ) as ((...args: unknown[]) => Promise<unknown>) & { [PATCHED]?: boolean };
478
+ patchedStream[PATCHED] = true;
479
+ proto.generateContentStreamInternal = patchedStream;
480
+ this.restores.push(() => {
481
+ proto.generateContentStreamInternal = origStream;
482
+ });
483
+ }
484
+ }
485
+
486
+ uninstrument(): void {
487
+ for (const restore of this.restores) restore();
488
+ this.restores = [];
489
+ this.tracer = null;
490
+ }
491
+ }
@@ -0,0 +1,121 @@
1
+ /**
2
+ * OpenTelemetry surface for the Introspection Node SDK.
3
+ *
4
+ * Subpath entry point: `@introspection-sdk/introspection-node/otel`.
5
+ *
6
+ * Importing from here pulls in OTel SDK packages (peer deps). The
7
+ * REST-only `IntrospectionClient` is available from the package root
8
+ * and does not require these to be installed.
9
+ */
10
+
11
+ // IntrospectionLogs — OTel logs exporter with track/feedback/identify
12
+ // and baggage context helpers (extracted from the old IntrospectionClient).
13
+ export { IntrospectionLogs } from "./logs.js";
14
+ export type { IntrospectionLogsOptions } from "./logs.js";
15
+
16
+ // One-call tracing bootstrap (NodeTracerProvider + AsyncLocalStorage +
17
+ // W3C baggage propagator + IntrospectionSpanProcessor).
18
+ export { setupTracing } from "./setup.js";
19
+ export type { SetupTracingOptions, ConflictBehavior } from "./setup.js";
20
+
21
+ // Span processor — attach to your own TracerProvider.
22
+ export { IntrospectionSpanProcessor } from "./span-processor.js";
23
+ export type { IntrospectionSpanProcessorOptions } from "./span-processor.js";
24
+
25
+ // OpenAI Agents SDK tracing processor.
26
+ export { IntrospectionTracingProcessor } from "./tracing-processor.js";
27
+ export type {
28
+ IntrospectionTracingProcessorOptions,
29
+ TracingProcessorAdvancedOptions,
30
+ } from "./tracing-processor.js";
31
+
32
+ // Claude Agent SDK hooks.
33
+ export { IntrospectionClaudeHooks } from "./claude-hooks.js";
34
+ export type {
35
+ IntrospectionClaudeHooksOptions,
36
+ ClaudeHooksAdvancedOptions,
37
+ ClaudeHooksConfig,
38
+ ClaudeHookCallbackMatcher,
39
+ ClaudeHookEvent,
40
+ ClaudeHookInput,
41
+ ClaudeHookOutput,
42
+ ClaudeHookCallback,
43
+ ClaudeUsage,
44
+ ClaudeModelUsage,
45
+ ClaudeResultMessage,
46
+ ClaudeAssistantMessage,
47
+ ClaudeSDKMessage,
48
+ } from "./claude-hooks.js";
49
+
50
+ // Claude Agent SDK wrapper.
51
+ export { withIntrospection } from "./claude-wrapper.js";
52
+ export type {
53
+ WithIntrospectionOptions,
54
+ InstrumentedClaudeAgentSDK,
55
+ ClaudeAgentSDKModule,
56
+ } from "./claude-wrapper.js";
57
+
58
+ // Anthropic SDK instrumentor.
59
+ export {
60
+ AnthropicInstrumentor,
61
+ tracedMessagesCreate,
62
+ REDACTED_THINKING_CONTENT,
63
+ } from "./anthropic.js";
64
+
65
+ // Pi Agent SDK instrumentor.
66
+ export { IntrospectionPiInstrumentor } from "./pi.js";
67
+ export type {
68
+ IntrospectionPiInstrumentorOptions,
69
+ AgentMeta as PiAgentMeta,
70
+ } from "./pi.js";
71
+
72
+ // Gemini SDK instrumentor.
73
+ export { GeminiInstrumentor } from "./gemini.js";
74
+
75
+ // OpenInference span exporter (drops Arize/OpenInference attrs onto a
76
+ // downstream OTel SpanExporter).
77
+ export {
78
+ addOpenInferenceAttributes,
79
+ OpenInferenceSpanExporter,
80
+ } from "../converters/openinference.js";
81
+
82
+ // One-liner bootstrap (`introspection.init()`) + analytics proxies and the
83
+ // per-framework handle accessors it binds. Auto-detects installed frameworks
84
+ // and wires them into one shared provider.
85
+ export {
86
+ init,
87
+ shutdown,
88
+ track,
89
+ feedback,
90
+ identify,
91
+ conversation,
92
+ withAgent,
93
+ withConversation,
94
+ withUserId,
95
+ withAnonymousId,
96
+ newConversationId,
97
+ getClient,
98
+ getTracerProvider,
99
+ getLangchainHandler,
100
+ getMastraExporter,
101
+ instrumentPi,
102
+ instrumentClaudeAgent,
103
+ _resetForTests,
104
+ } from "./init.js";
105
+ export type { InitOptions } from "./init.js";
106
+
107
+ // Low-level OTel registration helper (also used by `init`).
108
+ export { registerOTelGlobals } from "./setup.js";
109
+
110
+ // Integration registry — for custom integrations passed to `init`.
111
+ export {
112
+ DidNotEnable,
113
+ discoverIntegrations,
114
+ setupIntegrations,
115
+ resetInstalledForTests,
116
+ } from "./integrations/index.js";
117
+ export type {
118
+ Integration,
119
+ IntegrationSetupContext,
120
+ IntegrationHandles,
121
+ } from "./integrations/index.js";