@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,1010 @@
1
+ /**
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
+
10
+ import {
11
+ context as otelContext,
12
+ trace as otelTrace,
13
+ Span as OtelSpan,
14
+ SpanKind,
15
+ SpanStatusCode,
16
+ } from "@opentelemetry/api";
17
+ import {
18
+ BasicTracerProvider,
19
+ BatchSpanProcessor,
20
+ SimpleSpanProcessor,
21
+ type SpanExporter,
22
+ type IdGenerator,
23
+ } from "@opentelemetry/sdk-trace-base";
24
+ import { OTLPTraceExporter } from "@opentelemetry/exporter-trace-otlp-proto";
25
+ import {
26
+ resourceFromAttributes,
27
+ defaultResource,
28
+ } from "@opentelemetry/resources";
29
+ import { ATTR_SERVICE_NAME } from "@opentelemetry/semantic-conventions";
30
+
31
+ import { logger } from "./utils.js";
32
+ import { VERSION } from "./version.js";
33
+ import {
34
+ convertClaudeSessionToOtelAttributes,
35
+ type ClaudeContentBlock,
36
+ } from "./converters/claude.js";
37
+
38
+ // ---------------------------------------------------------------------------
39
+ // Claude Agent SDK Hook types
40
+ // Defined locally to avoid requiring the SDK as a compile-time dependency.
41
+ // ---------------------------------------------------------------------------
42
+
43
+ /** Common fields present on every hook input payload. */
44
+ export interface BaseHookInput {
45
+ /** Active session identifier. */
46
+ session_id: string;
47
+ /** Path to the session transcript file. */
48
+ transcript_path: string;
49
+ /** Working directory of the agent process. */
50
+ cwd: string;
51
+ /** Permission mode the session is running in. */
52
+ permission_mode?: string;
53
+ }
54
+
55
+ /** Input payload for the `SessionStart` hook. */
56
+ export interface SessionStartHookInput extends BaseHookInput {
57
+ hook_event_name: "SessionStart";
58
+ /** How the session was initiated. */
59
+ source: "startup" | "resume" | "clear" | "compact";
60
+ /** Agent type (e.g. `"main"`, `"subagent"`). */
61
+ agent_type?: string;
62
+ /** Model used for this session. */
63
+ model?: string;
64
+ }
65
+
66
+ /** Input payload for the `SessionEnd` hook. */
67
+ export interface SessionEndHookInput extends BaseHookInput {
68
+ hook_event_name: "SessionEnd";
69
+ /** Reason the session ended. */
70
+ reason: string;
71
+ }
72
+
73
+ /** Input payload for the `PreToolUse` hook. */
74
+ export interface PreToolUseHookInput extends BaseHookInput {
75
+ hook_event_name: "PreToolUse";
76
+ /** Name of the tool about to be invoked. */
77
+ tool_name: string;
78
+ /** Input data passed to the tool. */
79
+ tool_input: unknown;
80
+ /** Unique identifier for this tool invocation. */
81
+ tool_use_id: string;
82
+ }
83
+
84
+ /** Input payload for the `PostToolUse` hook. */
85
+ export interface PostToolUseHookInput extends BaseHookInput {
86
+ hook_event_name: "PostToolUse";
87
+ /** Name of the tool that was invoked. */
88
+ tool_name: string;
89
+ /** Input data that was passed to the tool. */
90
+ tool_input: unknown;
91
+ /** Response returned by the tool. */
92
+ tool_response: unknown;
93
+ /** Unique identifier for this tool invocation. */
94
+ tool_use_id: string;
95
+ }
96
+
97
+ /** Input payload for the `SubagentStart` hook. */
98
+ export interface SubagentStartHookInput extends BaseHookInput {
99
+ hook_event_name: "SubagentStart";
100
+ /** Identifier of the sub-agent. */
101
+ agent_id: string;
102
+ /** Type / name of the sub-agent. */
103
+ agent_type: string;
104
+ }
105
+
106
+ /** Input payload for the `SubagentStop` hook. */
107
+ export interface SubagentStopHookInput extends BaseHookInput {
108
+ hook_event_name: "SubagentStop";
109
+ /** Identifier of the sub-agent. */
110
+ agent_id: string;
111
+ /** Type / name of the sub-agent. */
112
+ agent_type: string;
113
+ /** Path to the sub-agent's transcript. */
114
+ agent_transcript_path: string;
115
+ }
116
+
117
+ /** Discriminated union of all possible hook input payloads. */
118
+ export type ClaudeHookInput =
119
+ | SessionStartHookInput
120
+ | SessionEndHookInput
121
+ | PreToolUseHookInput
122
+ | PostToolUseHookInput
123
+ | SubagentStartHookInput
124
+ | SubagentStopHookInput;
125
+
126
+ /**
127
+ * JSON-serialisable output returned by a hook callback
128
+ * (`SyncHookJSONOutput` in the SDK).
129
+ */
130
+ export type ClaudeHookOutput = {
131
+ /** Whether the SDK should continue processing. */
132
+ continue?: boolean;
133
+ /** Suppress the default output for this hook event. */
134
+ suppressOutput?: boolean;
135
+ /** Reason to stop the session. */
136
+ stopReason?: string;
137
+ /** Approval decision for `PreToolUse` hooks. */
138
+ decision?: "approve" | "block";
139
+ /** System message to inject into the conversation. */
140
+ systemMessage?: string;
141
+ /** Human-readable reason for the decision. */
142
+ reason?: string;
143
+ };
144
+
145
+ /**
146
+ * Async callback signature for a Claude Agent SDK hook.
147
+ *
148
+ * @param input - The hook input payload.
149
+ * @param toolUseID - The tool-use ID (set for `PreToolUse` / `PostToolUse`).
150
+ * @param options - Abort signal for cancellation.
151
+ * @returns A {@link ClaudeHookOutput} controlling the SDK's behaviour.
152
+ */
153
+ export type ClaudeHookCallback = (
154
+ input: ClaudeHookInput,
155
+ toolUseID: string | undefined,
156
+ options: { signal: AbortSignal },
157
+ ) => Promise<ClaudeHookOutput>;
158
+
159
+ /** Pairs an optional glob matcher with one or more hook callbacks. */
160
+ export interface ClaudeHookCallbackMatcher {
161
+ /** Glob pattern to match tool names (only relevant for tool hooks). */
162
+ matcher?: string;
163
+ /** Callbacks to invoke when the matcher (or all events) match. */
164
+ hooks: ClaudeHookCallback[];
165
+ /** Timeout in milliseconds for hook execution. */
166
+ timeout?: number;
167
+ }
168
+
169
+ /** String literal union of all Claude Agent SDK hook event names. */
170
+ export type ClaudeHookEvent =
171
+ | "PreToolUse"
172
+ | "PostToolUse"
173
+ | "SessionStart"
174
+ | "SessionEnd"
175
+ | "SubagentStart"
176
+ | "SubagentStop";
177
+
178
+ /**
179
+ * Full hooks configuration object accepted by the Claude Agent SDK
180
+ * `query()` options. Maps each event name to an array of
181
+ * {@link ClaudeHookCallbackMatcher} entries.
182
+ */
183
+ export type ClaudeHooksConfig = Partial<
184
+ Record<ClaudeHookEvent, ClaudeHookCallbackMatcher[]>
185
+ >;
186
+
187
+ // ---------------------------------------------------------------------------
188
+ // Claude Agent SDK message types (for extracting usage info)
189
+ // ---------------------------------------------------------------------------
190
+
191
+ /** Token-level usage counters reported by the Claude API. */
192
+ export interface ClaudeUsage {
193
+ /** Number of input tokens consumed. */
194
+ input_tokens: number;
195
+ /** Number of output tokens generated. */
196
+ output_tokens: number;
197
+ /** Tokens used to create new cache entries. */
198
+ cache_creation_input_tokens?: number;
199
+ /** Tokens read from cache. */
200
+ cache_read_input_tokens?: number;
201
+ }
202
+
203
+ /** Per-model usage breakdown reported in a result message. */
204
+ export interface ClaudeModelUsage {
205
+ /** Input tokens for this model. */
206
+ inputTokens: number;
207
+ /** Output tokens for this model. */
208
+ outputTokens: number;
209
+ /** Tokens read from cache for this model. */
210
+ cacheReadInputTokens: number;
211
+ /** Tokens used to create cache for this model. */
212
+ cacheCreationInputTokens: number;
213
+ /** Estimated cost in USD for this model. */
214
+ costUSD: number;
215
+ }
216
+
217
+ /** A `"result"` message yielded at the end of a `query()` stream. */
218
+ export interface ClaudeResultMessage {
219
+ type: "result";
220
+ /** Aggregate token usage for the session. */
221
+ usage?: ClaudeUsage;
222
+ /** Total estimated cost in USD. */
223
+ total_cost_usd?: number;
224
+ /** Per-model usage breakdown. */
225
+ modelUsage?: Record<string, ClaudeModelUsage>;
226
+ /** Final text result (if any). */
227
+ result?: string;
228
+ /** Whether the session ended with an error. */
229
+ is_error?: boolean;
230
+ /** Session identifier. */
231
+ session_id: string;
232
+ }
233
+
234
+ /** An `"assistant"` message yielded during a `query()` stream. */
235
+ export interface ClaudeAssistantMessage {
236
+ type: "assistant";
237
+ /** The underlying API message with optional usage and content. */
238
+ message?: {
239
+ id?: string;
240
+ model?: string;
241
+ usage?: {
242
+ input_tokens?: number;
243
+ output_tokens?: number;
244
+ };
245
+ content?: Array<{ type: string; text?: string }>;
246
+ };
247
+ /** Session identifier. */
248
+ session_id: string;
249
+ }
250
+
251
+ /**
252
+ * Discriminated union of all messages that can be yielded by a Claude Agent
253
+ * SDK `query()` stream.
254
+ */
255
+ export type ClaudeSDKMessage =
256
+ | ClaudeResultMessage
257
+ | ClaudeAssistantMessage
258
+ | { type: string; session_id?: string };
259
+
260
+ /** Advanced options for testing and customization of {@link IntrospectionClaudeHooks}. */
261
+ export interface ClaudeHooksAdvancedOptions {
262
+ /** Custom span exporter (for testing) */
263
+ spanExporter?: SpanExporter;
264
+ /** Custom ID generator (for testing) */
265
+ idGenerator?: IdGenerator;
266
+ /** Use SimpleSpanProcessor instead of BatchSpanProcessor (for testing) */
267
+ useSimpleSpanProcessor?: boolean;
268
+ }
269
+
270
+ /** Configuration for {@link IntrospectionClaudeHooks}. */
271
+ export interface IntrospectionClaudeHooksOptions {
272
+ /** Authentication token (env: INTROSPECTION_TOKEN) */
273
+ token?: string;
274
+ /** Base URL for the API (env: INTROSPECTION_BASE_URL) */
275
+ baseUrl?: string;
276
+ /** Service name for the OTel resource (defaults to "claude-agent") */
277
+ serviceName?: string;
278
+ /** Agent name set on session spans as gen_ai.agent.name (defaults to serviceName) */
279
+ agentName?: string;
280
+ /** Additional headers to include in requests */
281
+ additionalHeaders?: Record<string, string>;
282
+ /** Advanced options for testing and customization */
283
+ advanced?: ClaudeHooksAdvancedOptions;
284
+ }
285
+
286
+ /**
287
+ * Provides instrumented hooks for Claude Agent SDK.
288
+ *
289
+ * Creates OpenTelemetry spans with gen_ai.* semantic convention attributes:
290
+ * - Session spans: gen_ai.system, gen_ai.request.model
291
+ * - Tool spans: gen_ai.tool.name, gen_ai.tool.input, gen_ai.tool.output
292
+ * - Subagent spans: gen_ai.agent.name
293
+ *
294
+ * Usage tracking is captured from streamed messages via recordUsage().
295
+ *
296
+ * @example
297
+ * ```typescript
298
+ * import { query } from "@anthropic-ai/claude-agent-sdk";
299
+ * import { IntrospectionClaudeHooks } from "@introspection-sdk/introspection-node";
300
+ *
301
+ * const hooks = new IntrospectionClaudeHooks();
302
+ *
303
+ * const stream = query({
304
+ * prompt: "Hello",
305
+ * options: {
306
+ * hooks: hooks.getHooks(),
307
+ * },
308
+ * });
309
+ *
310
+ * for await (const message of stream) {
311
+ * hooks.recordUsage(message);
312
+ * // handle message...
313
+ * }
314
+ *
315
+ * await hooks.shutdown();
316
+ * ```
317
+ */
318
+ export class IntrospectionClaudeHooks {
319
+ private _tracerProvider: BasicTracerProvider;
320
+ private _tracer: ReturnType<BasicTracerProvider["getTracer"]>;
321
+ private _agentName: string;
322
+ private _sessionSpans: Map<string, OtelSpan> = new Map();
323
+ private _toolSpans: Map<string, OtelSpan> = new Map();
324
+ private _subagentSpans: Map<string, OtelSpan> = new Map();
325
+ private _sessionUsage: Map<
326
+ string,
327
+ {
328
+ input: number;
329
+ output: number;
330
+ cost?: number;
331
+ model?: string;
332
+ inputPrompt?: string;
333
+ responseContent?: string;
334
+ responseBlocks?: ClaudeContentBlock[];
335
+ stopReason?: string;
336
+ responseId?: string;
337
+ toolNames?: string[];
338
+ systemInstructions?: string;
339
+ }
340
+ > = new Map();
341
+
342
+ constructor(options: IntrospectionClaudeHooksOptions = {}) {
343
+ const advanced = options.advanced;
344
+ const serviceName = options.serviceName || "claude-agent";
345
+ this._agentName = options.agentName || serviceName;
346
+ const resource = defaultResource().merge(
347
+ resourceFromAttributes({ [ATTR_SERVICE_NAME]: serviceName }),
348
+ );
349
+
350
+ if (!advanced?.spanExporter) {
351
+ const token = options.token || process.env.INTROSPECTION_TOKEN;
352
+ if (!token) {
353
+ throw new Error("INTROSPECTION_TOKEN is required");
354
+ }
355
+
356
+ const baseUrl =
357
+ options.baseUrl ||
358
+ process.env.INTROSPECTION_BASE_URL ||
359
+ "https://otel.introspection.dev";
360
+
361
+ const headers: Record<string, string> = {
362
+ "User-Agent": `introspection-sdk/${VERSION}`,
363
+ Authorization: `Bearer ${token}`,
364
+ ...options.additionalHeaders,
365
+ };
366
+
367
+ const endpoint = baseUrl.endsWith("/v1/traces")
368
+ ? baseUrl
369
+ : `${baseUrl.replace(/\/$/, "")}/v1/traces`;
370
+
371
+ logger.info(
372
+ `IntrospectionClaudeHooks initialized: service=${serviceName}, endpoint=${endpoint}`,
373
+ );
374
+
375
+ const spanExporter = new OTLPTraceExporter({
376
+ url: endpoint,
377
+ headers,
378
+ });
379
+
380
+ // Default to sequential export for dev/staging tokens.
381
+ const useSimple =
382
+ advanced?.useSimpleSpanProcessor ||
383
+ token.startsWith("intro_dev") ||
384
+ token.startsWith("intro_staging");
385
+ const spanProcessor = useSimple
386
+ ? new SimpleSpanProcessor(spanExporter)
387
+ : new BatchSpanProcessor(spanExporter, { scheduledDelayMillis: 1000 });
388
+
389
+ this._tracerProvider = new BasicTracerProvider({
390
+ resource,
391
+ idGenerator: advanced?.idGenerator,
392
+ spanProcessors: [spanProcessor],
393
+ });
394
+ } else {
395
+ logger.info(
396
+ `IntrospectionClaudeHooks initialized in test mode with custom exporter`,
397
+ );
398
+
399
+ const spanProcessor = advanced.useSimpleSpanProcessor
400
+ ? new SimpleSpanProcessor(advanced.spanExporter)
401
+ : new BatchSpanProcessor(advanced.spanExporter, {
402
+ scheduledDelayMillis: 100,
403
+ });
404
+
405
+ this._tracerProvider = new BasicTracerProvider({
406
+ resource,
407
+ idGenerator: advanced.idGenerator,
408
+ spanProcessors: [spanProcessor],
409
+ });
410
+ }
411
+
412
+ this._tracer = this._tracerProvider.getTracer("claude-agent-sdk", VERSION);
413
+ }
414
+
415
+ /**
416
+ * Build the hooks configuration object to pass to Claude Agent SDK
417
+ * `query()` options.
418
+ *
419
+ * @returns A {@link ClaudeHooksConfig} wired to this instance's tracing.
420
+ */
421
+ getHooks(): ClaudeHooksConfig {
422
+ return {
423
+ SessionStart: [
424
+ {
425
+ hooks: [this._onSessionStart.bind(this)],
426
+ },
427
+ ],
428
+ SessionEnd: [
429
+ {
430
+ hooks: [this._onSessionEnd.bind(this)],
431
+ },
432
+ ],
433
+ PreToolUse: [
434
+ {
435
+ hooks: [this._onPreToolUse.bind(this)],
436
+ },
437
+ ],
438
+ PostToolUse: [
439
+ {
440
+ hooks: [this._onPostToolUse.bind(this)],
441
+ },
442
+ ],
443
+ SubagentStart: [
444
+ {
445
+ hooks: [this._onSubagentStart.bind(this)],
446
+ },
447
+ ],
448
+ SubagentStop: [
449
+ {
450
+ hooks: [this._onSubagentStop.bind(this)],
451
+ },
452
+ ],
453
+ };
454
+ }
455
+
456
+ /**
457
+ * Set the input prompt for a session so it appears as
458
+ * `gen_ai.input.messages` on the session span.
459
+ *
460
+ * If `sessionId` is not provided the prompt is buffered and associated
461
+ * with the next session that starts via an `init` message.
462
+ *
463
+ * @param prompt - The user prompt string passed to `query()`.
464
+ * @param sessionId - Optional session ID if already known.
465
+ */
466
+ setInputPrompt(prompt: string, sessionId?: string): void {
467
+ if (sessionId) {
468
+ const existing = this._sessionUsage.get(sessionId) || {
469
+ input: 0,
470
+ output: 0,
471
+ };
472
+ existing.inputPrompt = prompt;
473
+ this._sessionUsage.set(sessionId, existing);
474
+ } else {
475
+ // Store for when session starts
476
+ this._pendingInputPrompt = prompt;
477
+ }
478
+ }
479
+
480
+ private _pendingInputPrompt?: string;
481
+
482
+ /**
483
+ * Set system instructions for a session so they appear as
484
+ * `gen_ai.system_instructions` on the session span.
485
+ *
486
+ * If `sessionId` is not provided the value is buffered and associated
487
+ * with the next session that starts via an `init` message.
488
+ *
489
+ * @param instructions - The system prompt / instructions string.
490
+ * @param sessionId - Optional session ID if already known.
491
+ */
492
+ setSystemInstructions(instructions: string, sessionId?: string): void {
493
+ if (sessionId) {
494
+ const existing = this._sessionUsage.get(sessionId) || {
495
+ input: 0,
496
+ output: 0,
497
+ };
498
+ existing.systemInstructions = instructions;
499
+ this._sessionUsage.set(sessionId, existing);
500
+ } else {
501
+ this._pendingSystemInstructions = instructions;
502
+ }
503
+ }
504
+
505
+ private _pendingSystemInstructions?: string;
506
+
507
+ /**
508
+ * Record usage from a streamed SDK message.
509
+ *
510
+ * Call this for **every** message yielded by `query()` to capture token
511
+ * usage. Session spans are automatically created on `init` messages and
512
+ * ended on `result` messages.
513
+ *
514
+ * @param message - A {@link ClaudeSDKMessage} yielded by the `query()` stream.
515
+ */
516
+ recordUsage(message: ClaudeSDKMessage): void {
517
+ const sessionId = message.session_id || "default";
518
+ const msg = message as Record<string, unknown>;
519
+
520
+ // Handle system init message - start session span
521
+ if (message.type === "system" && msg.subtype === "init") {
522
+ this._startSessionFromMessage(sessionId, msg);
523
+ return;
524
+ }
525
+
526
+ if (message.type === "assistant") {
527
+ const assistantMsg = message as ClaudeAssistantMessage;
528
+ const existing = this._sessionUsage.get(sessionId) || {
529
+ input: 0,
530
+ output: 0,
531
+ };
532
+
533
+ // Track usage
534
+ const usage = assistantMsg.message?.usage;
535
+ if (usage) {
536
+ existing.input += usage.input_tokens || 0;
537
+ existing.output += usage.output_tokens || 0;
538
+ if (assistantMsg.message?.model) {
539
+ existing.model = assistantMsg.message.model;
540
+ }
541
+ logger.debug(
542
+ `Recorded usage for session ${sessionId}: +${usage.input_tokens || 0} input, +${usage.output_tokens || 0} output`,
543
+ );
544
+ }
545
+
546
+ // Capture response ID from assistant message
547
+ if (assistantMsg.message?.id) {
548
+ existing.responseId = assistantMsg.message.id;
549
+ }
550
+
551
+ // Extract response content from assistant message
552
+ const content = assistantMsg.message?.content;
553
+ if (content && Array.isArray(content)) {
554
+ // Store content blocks for proper conversion
555
+ existing.responseBlocks = [
556
+ ...(existing.responseBlocks || []),
557
+ ...(content as ClaudeContentBlock[]),
558
+ ];
559
+ // Also extract text for backwards compatibility
560
+ const textContent = content
561
+ .filter((block) => block.type === "text" && block.text)
562
+ .map((block) => block.text)
563
+ .join("");
564
+ if (textContent) {
565
+ existing.responseContent =
566
+ (existing.responseContent || "") + textContent;
567
+ }
568
+ }
569
+
570
+ this._sessionUsage.set(sessionId, existing);
571
+ } else if (message.type === "result") {
572
+ const resultMsg = message as ClaudeResultMessage;
573
+ const existing = this._sessionUsage.get(sessionId) || {
574
+ input: 0,
575
+ output: 0,
576
+ };
577
+
578
+ if (resultMsg.usage) {
579
+ // Result message has final totals
580
+ existing.input = resultMsg.usage.input_tokens || existing.input;
581
+ existing.output = resultMsg.usage.output_tokens || existing.output;
582
+ }
583
+ if (resultMsg.total_cost_usd !== undefined) {
584
+ existing.cost = resultMsg.total_cost_usd;
585
+ }
586
+
587
+ // Capture stop reason from result subtype
588
+ const subtype = msg.subtype as string | undefined;
589
+ if (subtype) {
590
+ existing.stopReason = subtype;
591
+ }
592
+
593
+ this._sessionUsage.set(sessionId, existing);
594
+ logger.debug(
595
+ `Recorded final usage for session ${sessionId}: ${existing.input} input, ${existing.output} output, $${existing.cost || 0}`,
596
+ );
597
+
598
+ // End session span on result message
599
+ this._endSessionFromMessage(sessionId, msg);
600
+ }
601
+ }
602
+
603
+ /**
604
+ * Start a session span from an init system message.
605
+ * This provides an alternative to the SessionStart hook which has timing issues.
606
+ */
607
+ private _startSessionFromMessage(
608
+ sessionId: string,
609
+ msg: Record<string, unknown>,
610
+ ): void {
611
+ // Don't create duplicate spans if hook already created one
612
+ if (this._sessionSpans.has(sessionId)) {
613
+ logger.debug(`Session span already exists for ${sessionId}, skipping`);
614
+ return;
615
+ }
616
+
617
+ logger.debug(`Starting session span from init message: ${sessionId}`);
618
+
619
+ const span = this._tracer.startSpan("claude.session", {
620
+ kind: SpanKind.CLIENT,
621
+ attributes: {
622
+ "gen_ai.system": "anthropic",
623
+ "gen_ai.operation.name": "chat",
624
+ "gen_ai.agent.name": this._agentName,
625
+ "claude.session_id": sessionId,
626
+ "claude.source": "message",
627
+ },
628
+ });
629
+
630
+ // Add model if present in init message
631
+ const model = msg.model as string | undefined;
632
+ if (model) {
633
+ span.setAttribute("gen_ai.request.model", model);
634
+ }
635
+
636
+ // Add tools if present
637
+ const tools = msg.tools as string[] | undefined;
638
+ if (tools && tools.length > 0) {
639
+ span.setAttribute("claude.tools", tools.join(","));
640
+ span.setAttribute(
641
+ "gen_ai.tool.definitions",
642
+ JSON.stringify(tools.map((name) => ({ name }))),
643
+ );
644
+ }
645
+
646
+ this._sessionSpans.set(sessionId, span);
647
+
648
+ // Initialize session usage, including any pending input prompt and system instructions
649
+ const sessionData: {
650
+ input: number;
651
+ output: number;
652
+ model?: string;
653
+ inputPrompt?: string;
654
+ responseContent?: string;
655
+ toolNames?: string[];
656
+ systemInstructions?: string;
657
+ } = { input: 0, output: 0, model };
658
+
659
+ if (tools && tools.length > 0) {
660
+ sessionData.toolNames = tools;
661
+ }
662
+
663
+ if (this._pendingInputPrompt) {
664
+ sessionData.inputPrompt = this._pendingInputPrompt;
665
+ this._pendingInputPrompt = undefined;
666
+ }
667
+
668
+ if (this._pendingSystemInstructions) {
669
+ sessionData.systemInstructions = this._pendingSystemInstructions;
670
+ this._pendingSystemInstructions = undefined;
671
+ }
672
+
673
+ this._sessionUsage.set(sessionId, sessionData);
674
+ logger.info(`Created session span for ${sessionId}`);
675
+ }
676
+
677
+ /**
678
+ * End a session span from a result message.
679
+ * This provides an alternative to the SessionEnd hook which has timing issues.
680
+ */
681
+ private _endSessionFromMessage(
682
+ sessionId: string,
683
+ msg: Record<string, unknown>,
684
+ ): void {
685
+ const span = this._sessionSpans.get(sessionId);
686
+ if (!span) {
687
+ logger.debug(`No session span found for ${sessionId}, nothing to end`);
688
+ return;
689
+ }
690
+
691
+ const usage = this._sessionUsage.get(sessionId);
692
+
693
+ // Use converter to set GenAI semantic convention attributes
694
+ const otelAttrs = convertClaudeSessionToOtelAttributes({
695
+ sessionId,
696
+ inputPrompt: usage?.inputPrompt,
697
+ responseContent: usage?.responseContent,
698
+ responseBlocks: usage?.responseBlocks,
699
+ model: usage?.model,
700
+ inputTokens: usage?.input,
701
+ outputTokens: usage?.output,
702
+ costUsd: usage?.cost,
703
+ stopReason: usage?.stopReason,
704
+ responseId: usage?.responseId,
705
+ toolNames: usage?.toolNames,
706
+ systemInstructions: usage?.systemInstructions,
707
+ });
708
+
709
+ // Apply all converted attributes to the span
710
+ for (const [key, value] of Object.entries(otelAttrs)) {
711
+ span.setAttribute(key, value);
712
+ }
713
+
714
+ // Set subtype/reason from result message
715
+ const subtype = msg.subtype as string | undefined;
716
+ if (subtype) {
717
+ span.setAttribute("claude.result_subtype", subtype);
718
+ if (subtype === "success") {
719
+ span.setStatus({ code: SpanStatusCode.OK });
720
+ } else {
721
+ span.setStatus({
722
+ code: SpanStatusCode.ERROR,
723
+ message: subtype,
724
+ });
725
+ }
726
+ } else {
727
+ span.setStatus({ code: SpanStatusCode.OK });
728
+ }
729
+
730
+ span.end();
731
+ this._sessionSpans.delete(sessionId);
732
+ this._sessionUsage.delete(sessionId);
733
+ logger.info(
734
+ `Ended session span for ${sessionId}: ${usage?.input || 0} input, ${usage?.output || 0} output tokens`,
735
+ );
736
+ }
737
+
738
+ private async _onSessionStart(
739
+ input: ClaudeHookInput,
740
+ _toolUseID?: string,
741
+ _options?: { signal: AbortSignal },
742
+ ): Promise<ClaudeHookOutput> {
743
+ void _toolUseID;
744
+ void _options;
745
+ const sessionInput = input as SessionStartHookInput;
746
+ logger.debug(`SessionStart hook: ${sessionInput.session_id}`);
747
+
748
+ const span = this._tracer.startSpan("claude.session", {
749
+ kind: SpanKind.CLIENT,
750
+ attributes: {
751
+ "gen_ai.system": "anthropic",
752
+ "gen_ai.operation.name": "chat",
753
+ "gen_ai.agent.name": this._agentName,
754
+ "claude.session_id": sessionInput.session_id,
755
+ "claude.source": sessionInput.source,
756
+ },
757
+ });
758
+
759
+ if (sessionInput.model) {
760
+ span.setAttribute("gen_ai.request.model", sessionInput.model);
761
+ }
762
+ if (sessionInput.agent_type) {
763
+ span.setAttribute("claude.agent_type", sessionInput.agent_type);
764
+ }
765
+
766
+ this._sessionSpans.set(sessionInput.session_id, span);
767
+
768
+ // Initialize session usage, consuming any pending prompts/instructions
769
+ const sessionUsage: {
770
+ input: number;
771
+ output: number;
772
+ inputPrompt?: string;
773
+ systemInstructions?: string;
774
+ } = {
775
+ input: 0,
776
+ output: 0,
777
+ };
778
+ if (this._pendingInputPrompt) {
779
+ sessionUsage.inputPrompt = this._pendingInputPrompt;
780
+ this._pendingInputPrompt = undefined;
781
+ }
782
+ if (this._pendingSystemInstructions) {
783
+ sessionUsage.systemInstructions = this._pendingSystemInstructions;
784
+ this._pendingSystemInstructions = undefined;
785
+ }
786
+ this._sessionUsage.set(sessionInput.session_id, sessionUsage);
787
+
788
+ return { continue: true };
789
+ }
790
+
791
+ private async _onSessionEnd(
792
+ input: ClaudeHookInput,
793
+ _toolUseID?: string,
794
+ _options?: { signal: AbortSignal },
795
+ ): Promise<ClaudeHookOutput> {
796
+ void _toolUseID;
797
+ void _options;
798
+ const sessionInput = input as SessionEndHookInput;
799
+ logger.debug(`SessionEnd hook: ${sessionInput.session_id}`);
800
+
801
+ const span = this._sessionSpans.get(sessionInput.session_id);
802
+ if (span) {
803
+ const usage = this._sessionUsage.get(sessionInput.session_id);
804
+ if (usage) {
805
+ // Use converter for consistent gen_ai attribute mapping
806
+ const otelAttrs = convertClaudeSessionToOtelAttributes({
807
+ sessionId: sessionInput.session_id,
808
+ inputPrompt: usage.inputPrompt,
809
+ responseContent: usage.responseContent,
810
+ responseBlocks: usage.responseBlocks,
811
+ model: usage.model,
812
+ inputTokens: usage.input,
813
+ outputTokens: usage.output,
814
+ costUsd: usage.cost,
815
+ stopReason: usage.stopReason,
816
+ responseId: usage.responseId,
817
+ toolNames: usage.toolNames,
818
+ systemInstructions: usage.systemInstructions,
819
+ });
820
+ for (const [key, value] of Object.entries(otelAttrs)) {
821
+ span.setAttribute(key, value);
822
+ }
823
+ }
824
+
825
+ span.setAttribute("claude.exit_reason", sessionInput.reason);
826
+ span.setStatus({ code: SpanStatusCode.OK });
827
+ span.end();
828
+ this._sessionSpans.delete(sessionInput.session_id);
829
+ this._sessionUsage.delete(sessionInput.session_id);
830
+ logger.debug(`Ended session span for ${sessionInput.session_id}`);
831
+ }
832
+
833
+ return { continue: true };
834
+ }
835
+
836
+ private async _onPreToolUse(
837
+ input: ClaudeHookInput,
838
+ _toolUseID?: string,
839
+ _options?: { signal: AbortSignal },
840
+ ): Promise<ClaudeHookOutput> {
841
+ void _toolUseID;
842
+ void _options;
843
+ const toolInput = input as PreToolUseHookInput;
844
+ logger.debug(
845
+ `PreToolUse: ${toolInput.tool_name} (${toolInput.tool_use_id})`,
846
+ );
847
+
848
+ const parentSpan = this._sessionSpans.get(toolInput.session_id);
849
+ const ctx = parentSpan
850
+ ? otelTrace.setSpan(otelContext.active(), parentSpan)
851
+ : undefined;
852
+
853
+ const span = this._tracer.startSpan(
854
+ `tool.${toolInput.tool_name}`,
855
+ {
856
+ kind: SpanKind.INTERNAL,
857
+ attributes: {
858
+ "gen_ai.tool.name": toolInput.tool_name,
859
+ "claude.session_id": toolInput.session_id,
860
+ "claude.tool_use_id": toolInput.tool_use_id,
861
+ },
862
+ },
863
+ ctx,
864
+ );
865
+
866
+ if (toolInput.tool_input) {
867
+ try {
868
+ span.setAttribute(
869
+ "gen_ai.tool.input",
870
+ JSON.stringify(toolInput.tool_input),
871
+ );
872
+ } catch {
873
+ span.setAttribute("gen_ai.tool.input", String(toolInput.tool_input));
874
+ }
875
+ }
876
+
877
+ this._toolSpans.set(toolInput.tool_use_id, span);
878
+
879
+ return { continue: true };
880
+ }
881
+
882
+ private async _onPostToolUse(
883
+ input: ClaudeHookInput,
884
+ _toolUseID?: string,
885
+ _options?: { signal: AbortSignal },
886
+ ): Promise<ClaudeHookOutput> {
887
+ void _toolUseID;
888
+ void _options;
889
+ const toolInput = input as PostToolUseHookInput;
890
+ logger.debug(
891
+ `PostToolUse: ${toolInput.tool_name} (${toolInput.tool_use_id})`,
892
+ );
893
+
894
+ const span = this._toolSpans.get(toolInput.tool_use_id);
895
+
896
+ if (span) {
897
+ if (toolInput.tool_response !== undefined) {
898
+ try {
899
+ span.setAttribute(
900
+ "gen_ai.tool.output",
901
+ JSON.stringify(toolInput.tool_response),
902
+ );
903
+ } catch {
904
+ span.setAttribute(
905
+ "gen_ai.tool.output",
906
+ String(toolInput.tool_response),
907
+ );
908
+ }
909
+ }
910
+ span.setStatus({ code: SpanStatusCode.OK });
911
+ span.end();
912
+ this._toolSpans.delete(toolInput.tool_use_id);
913
+ }
914
+
915
+ return { continue: true };
916
+ }
917
+
918
+ private async _onSubagentStart(
919
+ input: ClaudeHookInput,
920
+ _toolUseID?: string,
921
+ _options?: { signal: AbortSignal },
922
+ ): Promise<ClaudeHookOutput> {
923
+ void _toolUseID;
924
+ void _options;
925
+ const subagentInput = input as SubagentStartHookInput;
926
+ logger.debug(
927
+ `SubagentStart: ${subagentInput.agent_type} (${subagentInput.agent_id})`,
928
+ );
929
+
930
+ const parentSpan = this._sessionSpans.get(subagentInput.session_id);
931
+ const ctx = parentSpan
932
+ ? otelTrace.setSpan(otelContext.active(), parentSpan)
933
+ : undefined;
934
+
935
+ const span = this._tracer.startSpan(
936
+ `subagent.${subagentInput.agent_type}`,
937
+ {
938
+ kind: SpanKind.INTERNAL,
939
+ attributes: {
940
+ "gen_ai.agent.name": subagentInput.agent_type,
941
+ "claude.session_id": subagentInput.session_id,
942
+ "claude.agent_id": subagentInput.agent_id,
943
+ },
944
+ },
945
+ ctx,
946
+ );
947
+
948
+ this._subagentSpans.set(subagentInput.agent_id, span);
949
+
950
+ return { continue: true };
951
+ }
952
+
953
+ private async _onSubagentStop(
954
+ input: ClaudeHookInput,
955
+ _toolUseID?: string,
956
+ _options?: { signal: AbortSignal },
957
+ ): Promise<ClaudeHookOutput> {
958
+ void _toolUseID;
959
+ void _options;
960
+ const subagentInput = input as SubagentStopHookInput;
961
+ logger.debug(
962
+ `SubagentStop: ${subagentInput.agent_type} (${subagentInput.agent_id})`,
963
+ );
964
+
965
+ const span = this._subagentSpans.get(subagentInput.agent_id);
966
+
967
+ if (span) {
968
+ span.setStatus({ code: SpanStatusCode.OK });
969
+ span.end();
970
+ this._subagentSpans.delete(subagentInput.agent_id);
971
+ }
972
+
973
+ return { continue: true };
974
+ }
975
+
976
+ /**
977
+ * Force-flush any buffered spans to the Introspection backend.
978
+ *
979
+ * @returns A promise that resolves once the flush completes.
980
+ */
981
+ async forceFlush(): Promise<void> {
982
+ await this._tracerProvider.forceFlush();
983
+ }
984
+
985
+ /**
986
+ * Shut down the hooks, ending any in-flight spans and flushing all
987
+ * pending data.
988
+ *
989
+ * @returns A promise that resolves once shutdown is complete.
990
+ */
991
+ async shutdown(): Promise<void> {
992
+ // End any remaining spans
993
+ for (const [, span] of this._sessionSpans) {
994
+ span.end();
995
+ }
996
+ for (const [, span] of this._toolSpans) {
997
+ span.end();
998
+ }
999
+ for (const [, span] of this._subagentSpans) {
1000
+ span.end();
1001
+ }
1002
+
1003
+ this._sessionSpans.clear();
1004
+ this._toolSpans.clear();
1005
+ this._subagentSpans.clear();
1006
+ this._sessionUsage.clear();
1007
+
1008
+ await this._tracerProvider.shutdown();
1009
+ }
1010
+ }