@introspection-sdk/introspection-node 0.4.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.
Files changed (89) hide show
  1. package/.turbo/turbo-build.log +4 -0
  2. package/.turbo/turbo-check-types.log +5 -0
  3. package/.turbo/turbo-lint.log +5 -0
  4. package/dist/ai-sdk-integration.d.ts +123 -0
  5. package/dist/ai-sdk-integration.d.ts.map +1 -0
  6. package/dist/ai-sdk-integration.js +475 -0
  7. package/dist/anthropic.d.ts +54 -0
  8. package/dist/anthropic.d.ts.map +1 -0
  9. package/dist/anthropic.js +375 -0
  10. package/dist/claude-hooks.d.ts +328 -0
  11. package/dist/claude-hooks.d.ts.map +1 -0
  12. package/dist/claude-hooks.js +571 -0
  13. package/dist/claude-wrapper.d.ts +93 -0
  14. package/dist/claude-wrapper.d.ts.map +1 -0
  15. package/dist/claude-wrapper.js +154 -0
  16. package/dist/client.d.ts +157 -0
  17. package/dist/client.d.ts.map +1 -0
  18. package/dist/client.js +394 -0
  19. package/dist/converters/ai-sdk.d.ts +65 -0
  20. package/dist/converters/ai-sdk.d.ts.map +1 -0
  21. package/dist/converters/ai-sdk.js +238 -0
  22. package/dist/converters/claude.d.ts +146 -0
  23. package/dist/converters/claude.d.ts.map +1 -0
  24. package/dist/converters/claude.js +202 -0
  25. package/dist/converters/index.d.ts +9 -0
  26. package/dist/converters/index.d.ts.map +1 -0
  27. package/dist/converters/index.js +8 -0
  28. package/dist/converters/openai.d.ts +51 -0
  29. package/dist/converters/openai.d.ts.map +1 -0
  30. package/dist/converters/openai.js +268 -0
  31. package/dist/converters/openclaw.d.ts +16 -0
  32. package/dist/converters/openclaw.d.ts.map +1 -0
  33. package/dist/converters/openclaw.js +49 -0
  34. package/dist/converters/openinference.d.ts +107 -0
  35. package/dist/converters/openinference.d.ts.map +1 -0
  36. package/dist/converters/openinference.js +552 -0
  37. package/dist/converters/vercel.d.ts +21 -0
  38. package/dist/converters/vercel.d.ts.map +1 -0
  39. package/dist/converters/vercel.js +208 -0
  40. package/dist/index.d.ts +38 -0
  41. package/dist/index.d.ts.map +1 -0
  42. package/dist/index.js +39 -0
  43. package/dist/langchain-handler.d.ts +101 -0
  44. package/dist/langchain-handler.d.ts.map +1 -0
  45. package/dist/langchain-handler.js +489 -0
  46. package/dist/mastra-exporter.d.ts +85 -0
  47. package/dist/mastra-exporter.d.ts.map +1 -0
  48. package/dist/mastra-exporter.js +471 -0
  49. package/dist/span-processor.d.ts +62 -0
  50. package/dist/span-processor.d.ts.map +1 -0
  51. package/dist/span-processor.js +310 -0
  52. package/dist/tracing-processor.d.ts +136 -0
  53. package/dist/tracing-processor.d.ts.map +1 -0
  54. package/dist/tracing-processor.js +368 -0
  55. package/dist/types/genai.d.ts +165 -0
  56. package/dist/types/genai.d.ts.map +1 -0
  57. package/dist/types/genai.js +82 -0
  58. package/dist/types.d.ts +7 -0
  59. package/dist/types.d.ts.map +1 -0
  60. package/dist/types.js +1 -0
  61. package/dist/utils.d.ts +19 -0
  62. package/dist/utils.d.ts.map +1 -0
  63. package/dist/utils.js +57 -0
  64. package/dist/version.d.ts +3 -0
  65. package/dist/version.d.ts.map +1 -0
  66. package/dist/version.js +2 -0
  67. package/eslint.config.mjs +4 -0
  68. package/package.json +78 -0
  69. package/src/ai-sdk-integration.ts +689 -0
  70. package/src/anthropic.ts +465 -0
  71. package/src/claude-hooks.ts +1010 -0
  72. package/src/claude-wrapper.ts +240 -0
  73. package/src/client.ts +513 -0
  74. package/src/converters/ai-sdk.ts +298 -0
  75. package/src/converters/claude.ts +334 -0
  76. package/src/converters/index.ts +44 -0
  77. package/src/converters/openai.ts +302 -0
  78. package/src/converters/openinference.ts +673 -0
  79. package/src/converters/vercel.ts +264 -0
  80. package/src/index.ts +121 -0
  81. package/src/langchain-handler.ts +722 -0
  82. package/src/mastra-exporter.ts +650 -0
  83. package/src/span-processor.ts +418 -0
  84. package/src/tracing-processor.ts +548 -0
  85. package/src/types/genai.ts +264 -0
  86. package/src/types.ts +13 -0
  87. package/src/utils.ts +69 -0
  88. package/src/version.ts +2 -0
  89. package/tsconfig.json +8 -0
@@ -0,0 +1 @@
1
+ {"version":3,"file":"claude-hooks.d.ts","sourceRoot":"","sources":["../src/claude-hooks.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AASH,OAAO,EAIL,KAAK,YAAY,EACjB,KAAK,WAAW,EACjB,MAAM,+BAA+B,CAAC;AAoBvC,yDAAyD;AACzD,MAAM,WAAW,aAAa;IAC5B,iCAAiC;IACjC,UAAU,EAAE,MAAM,CAAC;IACnB,2CAA2C;IAC3C,eAAe,EAAE,MAAM,CAAC;IACxB,8CAA8C;IAC9C,GAAG,EAAE,MAAM,CAAC;IACZ,iDAAiD;IACjD,eAAe,CAAC,EAAE,MAAM,CAAC;CAC1B;AAED,iDAAiD;AACjD,MAAM,WAAW,qBAAsB,SAAQ,aAAa;IAC1D,eAAe,EAAE,cAAc,CAAC;IAChC,qCAAqC;IACrC,MAAM,EAAE,SAAS,GAAG,QAAQ,GAAG,OAAO,GAAG,SAAS,CAAC;IACnD,gDAAgD;IAChD,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,mCAAmC;IACnC,KAAK,CAAC,EAAE,MAAM,CAAC;CAChB;AAED,+CAA+C;AAC/C,MAAM,WAAW,mBAAoB,SAAQ,aAAa;IACxD,eAAe,EAAE,YAAY,CAAC;IAC9B,gCAAgC;IAChC,MAAM,EAAE,MAAM,CAAC;CAChB;AAED,+CAA+C;AAC/C,MAAM,WAAW,mBAAoB,SAAQ,aAAa;IACxD,eAAe,EAAE,YAAY,CAAC;IAC9B,4CAA4C;IAC5C,SAAS,EAAE,MAAM,CAAC;IAClB,qCAAqC;IACrC,UAAU,EAAE,OAAO,CAAC;IACpB,kDAAkD;IAClD,WAAW,EAAE,MAAM,CAAC;CACrB;AAED,gDAAgD;AAChD,MAAM,WAAW,oBAAqB,SAAQ,aAAa;IACzD,eAAe,EAAE,aAAa,CAAC;IAC/B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2
+ * Claude Agent SDK Instrumentation Hooks
3
+ *
4
+ * Provides OpenTelemetry instrumentation for the Claude Agent SDK via its hooks system.
5
+ * Creates spans for sessions, tool uses, and subagent executions with gen_ai.* attributes.
6
+ *
7
+ * @see https://platform.claude.com/docs/en/agent-sdk/typescript
8
+ */
9
+ import { context as otelContext, trace as otelTrace, SpanKind, SpanStatusCode, } from "@opentelemetry/api";
10
+ import { BasicTracerProvider, BatchSpanProcessor, SimpleSpanProcessor, } from "@opentelemetry/sdk-trace-base";
11
+ import { OTLPTraceExporter } from "@opentelemetry/exporter-trace-otlp-proto";
12
+ import { resourceFromAttributes, defaultResource, } from "@opentelemetry/resources";
13
+ import { ATTR_SERVICE_NAME } from "@opentelemetry/semantic-conventions";
14
+ import { logger } from "./utils.js";
15
+ import { VERSION } from "./version.js";
16
+ import { convertClaudeSessionToOtelAttributes, } from "./converters/claude.js";
17
+ /**
18
+ * Provides instrumented hooks for Claude Agent SDK.
19
+ *
20
+ * Creates OpenTelemetry spans with gen_ai.* semantic convention attributes:
21
+ * - Session spans: gen_ai.system, gen_ai.request.model
22
+ * - Tool spans: gen_ai.tool.name, gen_ai.tool.input, gen_ai.tool.output
23
+ * - Subagent spans: gen_ai.agent.name
24
+ *
25
+ * Usage tracking is captured from streamed messages via recordUsage().
26
+ *
27
+ * @example
28
+ * ```typescript
29
+ * import { query } from "@anthropic-ai/claude-agent-sdk";
30
+ * import { IntrospectionClaudeHooks } from "@introspection-sdk/introspection-node";
31
+ *
32
+ * const hooks = new IntrospectionClaudeHooks();
33
+ *
34
+ * const stream = query({
35
+ * prompt: "Hello",
36
+ * options: {
37
+ * hooks: hooks.getHooks(),
38
+ * },
39
+ * });
40
+ *
41
+ * for await (const message of stream) {
42
+ * hooks.recordUsage(message);
43
+ * // handle message...
44
+ * }
45
+ *
46
+ * await hooks.shutdown();
47
+ * ```
48
+ */
49
+ export class IntrospectionClaudeHooks {
50
+ _tracerProvider;
51
+ _tracer;
52
+ _agentName;
53
+ _sessionSpans = new Map();
54
+ _toolSpans = new Map();
55
+ _subagentSpans = new Map();
56
+ _sessionUsage = new Map();
57
+ constructor(options = {}) {
58
+ const advanced = options.advanced;
59
+ const serviceName = options.serviceName || "claude-agent";
60
+ this._agentName = options.agentName || serviceName;
61
+ const resource = defaultResource().merge(resourceFromAttributes({ [ATTR_SERVICE_NAME]: serviceName }));
62
+ if (!advanced?.spanExporter) {
63
+ const token = options.token || process.env.INTROSPECTION_TOKEN;
64
+ if (!token) {
65
+ throw new Error("INTROSPECTION_TOKEN is required");
66
+ }
67
+ const baseUrl = options.baseUrl ||
68
+ process.env.INTROSPECTION_BASE_URL ||
69
+ "https://otel.introspection.dev";
70
+ const headers = {
71
+ "User-Agent": `introspection-sdk/${VERSION}`,
72
+ Authorization: `Bearer ${token}`,
73
+ ...options.additionalHeaders,
74
+ };
75
+ const endpoint = baseUrl.endsWith("/v1/traces")
76
+ ? baseUrl
77
+ : `${baseUrl.replace(/\/$/, "")}/v1/traces`;
78
+ logger.info(`IntrospectionClaudeHooks initialized: service=${serviceName}, endpoint=${endpoint}`);
79
+ const spanExporter = new OTLPTraceExporter({
80
+ url: endpoint,
81
+ headers,
82
+ });
83
+ // Default to sequential export for dev/staging tokens.
84
+ const useSimple = advanced?.useSimpleSpanProcessor ||
85
+ token.startsWith("intro_dev") ||
86
+ token.startsWith("intro_staging");
87
+ const spanProcessor = useSimple
88
+ ? new SimpleSpanProcessor(spanExporter)
89
+ : new BatchSpanProcessor(spanExporter, { scheduledDelayMillis: 1000 });
90
+ this._tracerProvider = new BasicTracerProvider({
91
+ resource,
92
+ idGenerator: advanced?.idGenerator,
93
+ spanProcessors: [spanProcessor],
94
+ });
95
+ }
96
+ else {
97
+ logger.info(`IntrospectionClaudeHooks initialized in test mode with custom exporter`);
98
+ const spanProcessor = advanced.useSimpleSpanProcessor
99
+ ? new SimpleSpanProcessor(advanced.spanExporter)
100
+ : new BatchSpanProcessor(advanced.spanExporter, {
101
+ scheduledDelayMillis: 100,
102
+ });
103
+ this._tracerProvider = new BasicTracerProvider({
104
+ resource,
105
+ idGenerator: advanced.idGenerator,
106
+ spanProcessors: [spanProcessor],
107
+ });
108
+ }
109
+ this._tracer = this._tracerProvider.getTracer("claude-agent-sdk", VERSION);
110
+ }
111
+ /**
112
+ * Build the hooks configuration object to pass to Claude Agent SDK
113
+ * `query()` options.
114
+ *
115
+ * @returns A {@link ClaudeHooksConfig} wired to this instance's tracing.
116
+ */
117
+ getHooks() {
118
+ return {
119
+ SessionStart: [
120
+ {
121
+ hooks: [this._onSessionStart.bind(this)],
122
+ },
123
+ ],
124
+ SessionEnd: [
125
+ {
126
+ hooks: [this._onSessionEnd.bind(this)],
127
+ },
128
+ ],
129
+ PreToolUse: [
130
+ {
131
+ hooks: [this._onPreToolUse.bind(this)],
132
+ },
133
+ ],
134
+ PostToolUse: [
135
+ {
136
+ hooks: [this._onPostToolUse.bind(this)],
137
+ },
138
+ ],
139
+ SubagentStart: [
140
+ {
141
+ hooks: [this._onSubagentStart.bind(this)],
142
+ },
143
+ ],
144
+ SubagentStop: [
145
+ {
146
+ hooks: [this._onSubagentStop.bind(this)],
147
+ },
148
+ ],
149
+ };
150
+ }
151
+ /**
152
+ * Set the input prompt for a session so it appears as
153
+ * `gen_ai.input.messages` on the session span.
154
+ *
155
+ * If `sessionId` is not provided the prompt is buffered and associated
156
+ * with the next session that starts via an `init` message.
157
+ *
158
+ * @param prompt - The user prompt string passed to `query()`.
159
+ * @param sessionId - Optional session ID if already known.
160
+ */
161
+ setInputPrompt(prompt, sessionId) {
162
+ if (sessionId) {
163
+ const existing = this._sessionUsage.get(sessionId) || {
164
+ input: 0,
165
+ output: 0,
166
+ };
167
+ existing.inputPrompt = prompt;
168
+ this._sessionUsage.set(sessionId, existing);
169
+ }
170
+ else {
171
+ // Store for when session starts
172
+ this._pendingInputPrompt = prompt;
173
+ }
174
+ }
175
+ _pendingInputPrompt;
176
+ /**
177
+ * Set system instructions for a session so they appear as
178
+ * `gen_ai.system_instructions` on the session span.
179
+ *
180
+ * If `sessionId` is not provided the value is buffered and associated
181
+ * with the next session that starts via an `init` message.
182
+ *
183
+ * @param instructions - The system prompt / instructions string.
184
+ * @param sessionId - Optional session ID if already known.
185
+ */
186
+ setSystemInstructions(instructions, sessionId) {
187
+ if (sessionId) {
188
+ const existing = this._sessionUsage.get(sessionId) || {
189
+ input: 0,
190
+ output: 0,
191
+ };
192
+ existing.systemInstructions = instructions;
193
+ this._sessionUsage.set(sessionId, existing);
194
+ }
195
+ else {
196
+ this._pendingSystemInstructions = instructions;
197
+ }
198
+ }
199
+ _pendingSystemInstructions;
200
+ /**
201
+ * Record usage from a streamed SDK message.
202
+ *
203
+ * Call this for **every** message yielded by `query()` to capture token
204
+ * usage. Session spans are automatically created on `init` messages and
205
+ * ended on `result` messages.
206
+ *
207
+ * @param message - A {@link ClaudeSDKMessage} yielded by the `query()` stream.
208
+ */
209
+ recordUsage(message) {
210
+ const sessionId = message.session_id || "default";
211
+ const msg = message;
212
+ // Handle system init message - start session span
213
+ if (message.type === "system" && msg.subtype === "init") {
214
+ this._startSessionFromMessage(sessionId, msg);
215
+ return;
216
+ }
217
+ if (message.type === "assistant") {
218
+ const assistantMsg = message;
219
+ const existing = this._sessionUsage.get(sessionId) || {
220
+ input: 0,
221
+ output: 0,
222
+ };
223
+ // Track usage
224
+ const usage = assistantMsg.message?.usage;
225
+ if (usage) {
226
+ existing.input += usage.input_tokens || 0;
227
+ existing.output += usage.output_tokens || 0;
228
+ if (assistantMsg.message?.model) {
229
+ existing.model = assistantMsg.message.model;
230
+ }
231
+ logger.debug(`Recorded usage for session ${sessionId}: +${usage.input_tokens || 0} input, +${usage.output_tokens || 0} output`);
232
+ }
233
+ // Capture response ID from assistant message
234
+ if (assistantMsg.message?.id) {
235
+ existing.responseId = assistantMsg.message.id;
236
+ }
237
+ // Extract response content from assistant message
238
+ const content = assistantMsg.message?.content;
239
+ if (content && Array.isArray(content)) {
240
+ // Store content blocks for proper conversion
241
+ existing.responseBlocks = [
242
+ ...(existing.responseBlocks || []),
243
+ ...content,
244
+ ];
245
+ // Also extract text for backwards compatibility
246
+ const textContent = content
247
+ .filter((block) => block.type === "text" && block.text)
248
+ .map((block) => block.text)
249
+ .join("");
250
+ if (textContent) {
251
+ existing.responseContent =
252
+ (existing.responseContent || "") + textContent;
253
+ }
254
+ }
255
+ this._sessionUsage.set(sessionId, existing);
256
+ }
257
+ else if (message.type === "result") {
258
+ const resultMsg = message;
259
+ const existing = this._sessionUsage.get(sessionId) || {
260
+ input: 0,
261
+ output: 0,
262
+ };
263
+ if (resultMsg.usage) {
264
+ // Result message has final totals
265
+ existing.input = resultMsg.usage.input_tokens || existing.input;
266
+ existing.output = resultMsg.usage.output_tokens || existing.output;
267
+ }
268
+ if (resultMsg.total_cost_usd !== undefined) {
269
+ existing.cost = resultMsg.total_cost_usd;
270
+ }
271
+ // Capture stop reason from result subtype
272
+ const subtype = msg.subtype;
273
+ if (subtype) {
274
+ existing.stopReason = subtype;
275
+ }
276
+ this._sessionUsage.set(sessionId, existing);
277
+ logger.debug(`Recorded final usage for session ${sessionId}: ${existing.input} input, ${existing.output} output, $${existing.cost || 0}`);
278
+ // End session span on result message
279
+ this._endSessionFromMessage(sessionId, msg);
280
+ }
281
+ }
282
+ /**
283
+ * Start a session span from an init system message.
284
+ * This provides an alternative to the SessionStart hook which has timing issues.
285
+ */
286
+ _startSessionFromMessage(sessionId, msg) {
287
+ // Don't create duplicate spans if hook already created one
288
+ if (this._sessionSpans.has(sessionId)) {
289
+ logger.debug(`Session span already exists for ${sessionId}, skipping`);
290
+ return;
291
+ }
292
+ logger.debug(`Starting session span from init message: ${sessionId}`);
293
+ const span = this._tracer.startSpan("claude.session", {
294
+ kind: SpanKind.CLIENT,
295
+ attributes: {
296
+ "gen_ai.system": "anthropic",
297
+ "gen_ai.operation.name": "chat",
298
+ "gen_ai.agent.name": this._agentName,
299
+ "claude.session_id": sessionId,
300
+ "claude.source": "message",
301
+ },
302
+ });
303
+ // Add model if present in init message
304
+ const model = msg.model;
305
+ if (model) {
306
+ span.setAttribute("gen_ai.request.model", model);
307
+ }
308
+ // Add tools if present
309
+ const tools = msg.tools;
310
+ if (tools && tools.length > 0) {
311
+ span.setAttribute("claude.tools", tools.join(","));
312
+ span.setAttribute("gen_ai.tool.definitions", JSON.stringify(tools.map((name) => ({ name }))));
313
+ }
314
+ this._sessionSpans.set(sessionId, span);
315
+ // Initialize session usage, including any pending input prompt and system instructions
316
+ const sessionData = { input: 0, output: 0, model };
317
+ if (tools && tools.length > 0) {
318
+ sessionData.toolNames = tools;
319
+ }
320
+ if (this._pendingInputPrompt) {
321
+ sessionData.inputPrompt = this._pendingInputPrompt;
322
+ this._pendingInputPrompt = undefined;
323
+ }
324
+ if (this._pendingSystemInstructions) {
325
+ sessionData.systemInstructions = this._pendingSystemInstructions;
326
+ this._pendingSystemInstructions = undefined;
327
+ }
328
+ this._sessionUsage.set(sessionId, sessionData);
329
+ logger.info(`Created session span for ${sessionId}`);
330
+ }
331
+ /**
332
+ * End a session span from a result message.
333
+ * This provides an alternative to the SessionEnd hook which has timing issues.
334
+ */
335
+ _endSessionFromMessage(sessionId, msg) {
336
+ const span = this._sessionSpans.get(sessionId);
337
+ if (!span) {
338
+ logger.debug(`No session span found for ${sessionId}, nothing to end`);
339
+ return;
340
+ }
341
+ const usage = this._sessionUsage.get(sessionId);
342
+ // Use converter to set GenAI semantic convention attributes
343
+ const otelAttrs = convertClaudeSessionToOtelAttributes({
344
+ sessionId,
345
+ inputPrompt: usage?.inputPrompt,
346
+ responseContent: usage?.responseContent,
347
+ responseBlocks: usage?.responseBlocks,
348
+ model: usage?.model,
349
+ inputTokens: usage?.input,
350
+ outputTokens: usage?.output,
351
+ costUsd: usage?.cost,
352
+ stopReason: usage?.stopReason,
353
+ responseId: usage?.responseId,
354
+ toolNames: usage?.toolNames,
355
+ systemInstructions: usage?.systemInstructions,
356
+ });
357
+ // Apply all converted attributes to the span
358
+ for (const [key, value] of Object.entries(otelAttrs)) {
359
+ span.setAttribute(key, value);
360
+ }
361
+ // Set subtype/reason from result message
362
+ const subtype = msg.subtype;
363
+ if (subtype) {
364
+ span.setAttribute("claude.result_subtype", subtype);
365
+ if (subtype === "success") {
366
+ span.setStatus({ code: SpanStatusCode.OK });
367
+ }
368
+ else {
369
+ span.setStatus({
370
+ code: SpanStatusCode.ERROR,
371
+ message: subtype,
372
+ });
373
+ }
374
+ }
375
+ else {
376
+ span.setStatus({ code: SpanStatusCode.OK });
377
+ }
378
+ span.end();
379
+ this._sessionSpans.delete(sessionId);
380
+ this._sessionUsage.delete(sessionId);
381
+ logger.info(`Ended session span for ${sessionId}: ${usage?.input || 0} input, ${usage?.output || 0} output tokens`);
382
+ }
383
+ async _onSessionStart(input, _toolUseID, _options) {
384
+ void _toolUseID;
385
+ void _options;
386
+ const sessionInput = input;
387
+ logger.debug(`SessionStart hook: ${sessionInput.session_id}`);
388
+ const span = this._tracer.startSpan("claude.session", {
389
+ kind: SpanKind.CLIENT,
390
+ attributes: {
391
+ "gen_ai.system": "anthropic",
392
+ "gen_ai.operation.name": "chat",
393
+ "gen_ai.agent.name": this._agentName,
394
+ "claude.session_id": sessionInput.session_id,
395
+ "claude.source": sessionInput.source,
396
+ },
397
+ });
398
+ if (sessionInput.model) {
399
+ span.setAttribute("gen_ai.request.model", sessionInput.model);
400
+ }
401
+ if (sessionInput.agent_type) {
402
+ span.setAttribute("claude.agent_type", sessionInput.agent_type);
403
+ }
404
+ this._sessionSpans.set(sessionInput.session_id, span);
405
+ // Initialize session usage, consuming any pending prompts/instructions
406
+ const sessionUsage = {
407
+ input: 0,
408
+ output: 0,
409
+ };
410
+ if (this._pendingInputPrompt) {
411
+ sessionUsage.inputPrompt = this._pendingInputPrompt;
412
+ this._pendingInputPrompt = undefined;
413
+ }
414
+ if (this._pendingSystemInstructions) {
415
+ sessionUsage.systemInstructions = this._pendingSystemInstructions;
416
+ this._pendingSystemInstructions = undefined;
417
+ }
418
+ this._sessionUsage.set(sessionInput.session_id, sessionUsage);
419
+ return { continue: true };
420
+ }
421
+ async _onSessionEnd(input, _toolUseID, _options) {
422
+ void _toolUseID;
423
+ void _options;
424
+ const sessionInput = input;
425
+ logger.debug(`SessionEnd hook: ${sessionInput.session_id}`);
426
+ const span = this._sessionSpans.get(sessionInput.session_id);
427
+ if (span) {
428
+ const usage = this._sessionUsage.get(sessionInput.session_id);
429
+ if (usage) {
430
+ // Use converter for consistent gen_ai attribute mapping
431
+ const otelAttrs = convertClaudeSessionToOtelAttributes({
432
+ sessionId: sessionInput.session_id,
433
+ inputPrompt: usage.inputPrompt,
434
+ responseContent: usage.responseContent,
435
+ responseBlocks: usage.responseBlocks,
436
+ model: usage.model,
437
+ inputTokens: usage.input,
438
+ outputTokens: usage.output,
439
+ costUsd: usage.cost,
440
+ stopReason: usage.stopReason,
441
+ responseId: usage.responseId,
442
+ toolNames: usage.toolNames,
443
+ systemInstructions: usage.systemInstructions,
444
+ });
445
+ for (const [key, value] of Object.entries(otelAttrs)) {
446
+ span.setAttribute(key, value);
447
+ }
448
+ }
449
+ span.setAttribute("claude.exit_reason", sessionInput.reason);
450
+ span.setStatus({ code: SpanStatusCode.OK });
451
+ span.end();
452
+ this._sessionSpans.delete(sessionInput.session_id);
453
+ this._sessionUsage.delete(sessionInput.session_id);
454
+ logger.debug(`Ended session span for ${sessionInput.session_id}`);
455
+ }
456
+ return { continue: true };
457
+ }
458
+ async _onPreToolUse(input, _toolUseID, _options) {
459
+ void _toolUseID;
460
+ void _options;
461
+ const toolInput = input;
462
+ logger.debug(`PreToolUse: ${toolInput.tool_name} (${toolInput.tool_use_id})`);
463
+ const parentSpan = this._sessionSpans.get(toolInput.session_id);
464
+ const ctx = parentSpan
465
+ ? otelTrace.setSpan(otelContext.active(), parentSpan)
466
+ : undefined;
467
+ const span = this._tracer.startSpan(`tool.${toolInput.tool_name}`, {
468
+ kind: SpanKind.INTERNAL,
469
+ attributes: {
470
+ "gen_ai.tool.name": toolInput.tool_name,
471
+ "claude.session_id": toolInput.session_id,
472
+ "claude.tool_use_id": toolInput.tool_use_id,
473
+ },
474
+ }, ctx);
475
+ if (toolInput.tool_input) {
476
+ try {
477
+ span.setAttribute("gen_ai.tool.input", JSON.stringify(toolInput.tool_input));
478
+ }
479
+ catch {
480
+ span.setAttribute("gen_ai.tool.input", String(toolInput.tool_input));
481
+ }
482
+ }
483
+ this._toolSpans.set(toolInput.tool_use_id, span);
484
+ return { continue: true };
485
+ }
486
+ async _onPostToolUse(input, _toolUseID, _options) {
487
+ void _toolUseID;
488
+ void _options;
489
+ const toolInput = input;
490
+ logger.debug(`PostToolUse: ${toolInput.tool_name} (${toolInput.tool_use_id})`);
491
+ const span = this._toolSpans.get(toolInput.tool_use_id);
492
+ if (span) {
493
+ if (toolInput.tool_response !== undefined) {
494
+ try {
495
+ span.setAttribute("gen_ai.tool.output", JSON.stringify(toolInput.tool_response));
496
+ }
497
+ catch {
498
+ span.setAttribute("gen_ai.tool.output", String(toolInput.tool_response));
499
+ }
500
+ }
501
+ span.setStatus({ code: SpanStatusCode.OK });
502
+ span.end();
503
+ this._toolSpans.delete(toolInput.tool_use_id);
504
+ }
505
+ return { continue: true };
506
+ }
507
+ async _onSubagentStart(input, _toolUseID, _options) {
508
+ void _toolUseID;
509
+ void _options;
510
+ const subagentInput = input;
511
+ logger.debug(`SubagentStart: ${subagentInput.agent_type} (${subagentInput.agent_id})`);
512
+ const parentSpan = this._sessionSpans.get(subagentInput.session_id);
513
+ const ctx = parentSpan
514
+ ? otelTrace.setSpan(otelContext.active(), parentSpan)
515
+ : undefined;
516
+ const span = this._tracer.startSpan(`subagent.${subagentInput.agent_type}`, {
517
+ kind: SpanKind.INTERNAL,
518
+ attributes: {
519
+ "gen_ai.agent.name": subagentInput.agent_type,
520
+ "claude.session_id": subagentInput.session_id,
521
+ "claude.agent_id": subagentInput.agent_id,
522
+ },
523
+ }, ctx);
524
+ this._subagentSpans.set(subagentInput.agent_id, span);
525
+ return { continue: true };
526
+ }
527
+ async _onSubagentStop(input, _toolUseID, _options) {
528
+ void _toolUseID;
529
+ void _options;
530
+ const subagentInput = input;
531
+ logger.debug(`SubagentStop: ${subagentInput.agent_type} (${subagentInput.agent_id})`);
532
+ const span = this._subagentSpans.get(subagentInput.agent_id);
533
+ if (span) {
534
+ span.setStatus({ code: SpanStatusCode.OK });
535
+ span.end();
536
+ this._subagentSpans.delete(subagentInput.agent_id);
537
+ }
538
+ return { continue: true };
539
+ }
540
+ /**
541
+ * Force-flush any buffered spans to the Introspection backend.
542
+ *
543
+ * @returns A promise that resolves once the flush completes.
544
+ */
545
+ async forceFlush() {
546
+ await this._tracerProvider.forceFlush();
547
+ }
548
+ /**
549
+ * Shut down the hooks, ending any in-flight spans and flushing all
550
+ * pending data.
551
+ *
552
+ * @returns A promise that resolves once shutdown is complete.
553
+ */
554
+ async shutdown() {
555
+ // End any remaining spans
556
+ for (const [, span] of this._sessionSpans) {
557
+ span.end();
558
+ }
559
+ for (const [, span] of this._toolSpans) {
560
+ span.end();
561
+ }
562
+ for (const [, span] of this._subagentSpans) {
563
+ span.end();
564
+ }
565
+ this._sessionSpans.clear();
566
+ this._toolSpans.clear();
567
+ this._subagentSpans.clear();
568
+ this._sessionUsage.clear();
569
+ await this._tracerProvider.shutdown();
570
+ }
571
+ }
@@ -0,0 +1,93 @@
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, type IntrospectionClaudeHooksOptions } from "./claude-hooks.js";
23
+ /**
24
+ * Configuration for {@link withIntrospection}.
25
+ *
26
+ * Alias of {@link IntrospectionClaudeHooksOptions}.
27
+ */
28
+ export type WithIntrospectionOptions = IntrospectionClaudeHooksOptions;
29
+ /**
30
+ * Minimal interface for the Claude Agent SDK module.
31
+ * Accepts `import * as sdk from "@anthropic-ai/claude-agent-sdk"`.
32
+ *
33
+ * Uses `any` for the query signature to accept any SDK version's types
34
+ * without requiring the SDK as a compile-time dependency.
35
+ */
36
+ export interface ClaudeAgentSDKModule {
37
+ query: (...args: any[]) => any;
38
+ [key: string]: unknown;
39
+ }
40
+ /**
41
+ * The instrumented SDK returned by {@link withIntrospection}.
42
+ *
43
+ * Exposes the same surface as the original SDK module plus tracing helpers.
44
+ */
45
+ export interface InstrumentedClaudeAgentSDK {
46
+ /** Instrumented `query()` — auto-captures prompt, hooks, and usage. */
47
+ query: (...args: any[]) => any;
48
+ /**
49
+ * Flush pending spans without shutting down.
50
+ *
51
+ * @returns A promise that resolves once the flush completes.
52
+ */
53
+ forceFlush(): Promise<void>;
54
+ /**
55
+ * Shut down tracing and flush all pending spans.
56
+ *
57
+ * @returns A promise that resolves once shutdown is complete.
58
+ */
59
+ shutdown(): Promise<void>;
60
+ /** The underlying {@link IntrospectionClaudeHooks} instance for advanced usage. */
61
+ readonly hooks: IntrospectionClaudeHooks;
62
+ /** All other SDK exports pass through unchanged. */
63
+ [key: string]: unknown;
64
+ }
65
+ /**
66
+ * Wrap the Claude Agent SDK module to automatically instrument every
67
+ * `query()` call with OpenTelemetry tracing.
68
+ *
69
+ * The returned SDK:
70
+ * - Auto-captures `prompt` and `systemPrompt` from query params
71
+ * - Injects instrumentation hooks (merged with any user-provided hooks)
72
+ * - Calls {@link IntrospectionClaudeHooks.recordUsage | recordUsage()} on
73
+ * every streamed message automatically
74
+ * - Flushes spans when each query stream completes
75
+ *
76
+ * @param sdk - The Claude Agent SDK module
77
+ * (`import * as sdk from "@anthropic-ai/claude-agent-sdk"`).
78
+ * @param options - Introspection configuration (token, serviceName, baseUrl, etc.).
79
+ * @returns An {@link InstrumentedClaudeAgentSDK} with the same API plus
80
+ * `forceFlush()`, `shutdown()`, and `hooks`.
81
+ *
82
+ * @example
83
+ * ```ts
84
+ * import * as sdk from "@anthropic-ai/claude-agent-sdk";
85
+ * import { withIntrospection } from "@introspection-sdk/introspection-node";
86
+ *
87
+ * const traced = withIntrospection(sdk, { serviceName: "my-agent" });
88
+ * for await (const msg of traced.query({ prompt: "Hello" })) { /* … *\/ }
89
+ * await traced.shutdown();
90
+ * ```
91
+ */
92
+ export declare function withIntrospection(sdk: ClaudeAgentSDKModule, options?: WithIntrospectionOptions): InstrumentedClaudeAgentSDK;
93
+ //# sourceMappingURL=claude-wrapper.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"claude-wrapper.d.ts","sourceRoot":"","sources":["../src/claude-wrapper.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;GAoBG;AAEH,OAAO,EACL,wBAAwB,EACxB,KAAK,+BAA+B,EAGrC,MAAM,mBAAmB,CAAC;AAK3B;;;;GAIG;AACH,MAAM,MAAM,wBAAwB,GAAG,+BAA+B,CAAC;AAEvE;;;;;;GAMG;AACH,MAAM,WAAW,oBAAoB;IAEnC,KAAK,EAAE,CAAC,GAAG,IAAI,EAAE,GAAG,EAAE,KAAK,GAAG,CAAC;IAC/B,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC;CACxB;AAED;;;;GAIG;AACH,MAAM,WAAW,0BAA0B;IACzC,uEAAuE;IAEvE,KAAK,EAAE,CAAC,GAAG,IAAI,EAAE,GAAG,EAAE,KAAK,GAAG,CAAC;IAC/B;;;;OAIG;IACH,UAAU,IAAI,OAAO,CAAC,IAAI,CAAC,CAAC;IAC5B;;;;OAIG;IACH,QAAQ,IAAI,OAAO,CAAC,IAAI,CAAC,CAAC;IAC1B,mFAAmF;IACnF,QAAQ,CAAC,KAAK,EAAE,wBAAwB,CAAC;IACzC,oDAAoD;IACpD,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC;CACxB;AAID;;;;;;;;;;;;;;;;;;;;;;;;;;GA0BG;AACH,wBAAgB,iBAAiB,CAC/B,GAAG,EAAE,oBAAoB,EACzB,OAAO,CAAC,EAAE,wBAAwB,GACjC,0BAA0B,CAyC5B"}