@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,240 @@
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
+
23
+ import {
24
+ IntrospectionClaudeHooks,
25
+ type IntrospectionClaudeHooksOptions,
26
+ type ClaudeHooksConfig,
27
+ type ClaudeSDKMessage,
28
+ } from "./claude-hooks.js";
29
+ import { logger } from "./utils.js";
30
+
31
+ // --- Public types ---
32
+
33
+ /**
34
+ * Configuration for {@link withIntrospection}.
35
+ *
36
+ * Alias of {@link IntrospectionClaudeHooksOptions}.
37
+ */
38
+ export type WithIntrospectionOptions = IntrospectionClaudeHooksOptions;
39
+
40
+ /**
41
+ * Minimal interface for the Claude Agent SDK module.
42
+ * Accepts `import * as sdk from "@anthropic-ai/claude-agent-sdk"`.
43
+ *
44
+ * Uses `any` for the query signature to accept any SDK version's types
45
+ * without requiring the SDK as a compile-time dependency.
46
+ */
47
+ export interface ClaudeAgentSDKModule {
48
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
49
+ query: (...args: any[]) => any;
50
+ [key: string]: unknown;
51
+ }
52
+
53
+ /**
54
+ * The instrumented SDK returned by {@link withIntrospection}.
55
+ *
56
+ * Exposes the same surface as the original SDK module plus tracing helpers.
57
+ */
58
+ export interface InstrumentedClaudeAgentSDK {
59
+ /** Instrumented `query()` — auto-captures prompt, hooks, and usage. */
60
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
61
+ query: (...args: any[]) => any;
62
+ /**
63
+ * Flush pending spans without shutting down.
64
+ *
65
+ * @returns A promise that resolves once the flush completes.
66
+ */
67
+ forceFlush(): Promise<void>;
68
+ /**
69
+ * Shut down tracing and flush all pending spans.
70
+ *
71
+ * @returns A promise that resolves once shutdown is complete.
72
+ */
73
+ shutdown(): Promise<void>;
74
+ /** The underlying {@link IntrospectionClaudeHooks} instance for advanced usage. */
75
+ readonly hooks: IntrospectionClaudeHooks;
76
+ /** All other SDK exports pass through unchanged. */
77
+ [key: string]: unknown;
78
+ }
79
+
80
+ // --- Implementation ---
81
+
82
+ /**
83
+ * Wrap the Claude Agent SDK module to automatically instrument every
84
+ * `query()` call with OpenTelemetry tracing.
85
+ *
86
+ * The returned SDK:
87
+ * - Auto-captures `prompt` and `systemPrompt` from query params
88
+ * - Injects instrumentation hooks (merged with any user-provided hooks)
89
+ * - Calls {@link IntrospectionClaudeHooks.recordUsage | recordUsage()} on
90
+ * every streamed message automatically
91
+ * - Flushes spans when each query stream completes
92
+ *
93
+ * @param sdk - The Claude Agent SDK module
94
+ * (`import * as sdk from "@anthropic-ai/claude-agent-sdk"`).
95
+ * @param options - Introspection configuration (token, serviceName, baseUrl, etc.).
96
+ * @returns An {@link InstrumentedClaudeAgentSDK} with the same API plus
97
+ * `forceFlush()`, `shutdown()`, and `hooks`.
98
+ *
99
+ * @example
100
+ * ```ts
101
+ * import * as sdk from "@anthropic-ai/claude-agent-sdk";
102
+ * import { withIntrospection } from "@introspection-sdk/introspection-node";
103
+ *
104
+ * const traced = withIntrospection(sdk, { serviceName: "my-agent" });
105
+ * for await (const msg of traced.query({ prompt: "Hello" })) { /* … *\/ }
106
+ * await traced.shutdown();
107
+ * ```
108
+ */
109
+ export function withIntrospection(
110
+ sdk: ClaudeAgentSDKModule,
111
+ options?: WithIntrospectionOptions,
112
+ ): InstrumentedClaudeAgentSDK {
113
+ const hooks = new IntrospectionClaudeHooks(options);
114
+
115
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
116
+ function wrappedQuery(params: any): any {
117
+ // Auto-capture prompt
118
+ if (typeof params?.prompt === "string") {
119
+ hooks.setInputPrompt(params.prompt);
120
+ }
121
+
122
+ // Auto-capture systemPrompt from options
123
+ const opts = (params?.options || {}) as Record<string, unknown>;
124
+ if (typeof opts.systemPrompt === "string") {
125
+ hooks.setSystemInstructions(opts.systemPrompt);
126
+ }
127
+
128
+ // Merge instrumentation hooks with any user-provided hooks
129
+ const introspectionHooks = hooks.getHooks();
130
+ const userHooks = opts.hooks as
131
+ | Partial<Record<string, unknown[]>>
132
+ | undefined;
133
+ const mergedHooks = mergeHooks(introspectionHooks, userHooks);
134
+
135
+ // Call original query with merged hooks
136
+ const modifiedOptions = { ...opts, hooks: mergedHooks };
137
+ const originalQuery = sdk.query({
138
+ ...params,
139
+ options: modifiedOptions,
140
+ });
141
+
142
+ // Wrap the async generator to intercept messages
143
+ return wrapQueryResult(originalQuery, hooks);
144
+ }
145
+
146
+ return {
147
+ ...sdk,
148
+ query: wrappedQuery,
149
+ hooks,
150
+ forceFlush: () => hooks.forceFlush(),
151
+ shutdown: () => hooks.shutdown(),
152
+ };
153
+ }
154
+
155
+ /**
156
+ * Merges introspection hooks with user-provided hooks.
157
+ * Introspection hooks fire first, then user hooks.
158
+ * User hooks on events we don't handle pass through untouched.
159
+ */
160
+ function mergeHooks(
161
+ introspectionHooks: ClaudeHooksConfig,
162
+ userHooks?: Partial<Record<string, unknown[]>>,
163
+ ): Record<string, unknown[]> {
164
+ if (!userHooks) {
165
+ return introspectionHooks as Record<string, unknown[]>;
166
+ }
167
+
168
+ const merged: Record<string, unknown[]> = {};
169
+ const allEvents = new Set([
170
+ ...Object.keys(introspectionHooks),
171
+ ...Object.keys(userHooks),
172
+ ]);
173
+
174
+ for (const event of allEvents) {
175
+ const ours = (introspectionHooks as Record<string, unknown[]>)[event] || [];
176
+ const theirs = userHooks[event] || [];
177
+ merged[event] = [...ours, ...theirs];
178
+ }
179
+
180
+ return merged;
181
+ }
182
+
183
+ /**
184
+ * Wraps a Query async generator to intercept messages for usage recording.
185
+ * Uses a Proxy to transparently forward all non-iterator properties
186
+ * (interrupt, close, setModel, etc.) to the original Query object.
187
+ */
188
+ function wrapQueryResult(
189
+ originalQuery: unknown,
190
+ hooks: IntrospectionClaudeHooks,
191
+ ): unknown {
192
+ const query = originalQuery as AsyncGenerator<ClaudeSDKMessage, void> &
193
+ Record<string, unknown>;
194
+
195
+ async function* instrumentedIterator(): AsyncGenerator<
196
+ ClaudeSDKMessage,
197
+ void
198
+ > {
199
+ try {
200
+ for await (const message of query) {
201
+ hooks.recordUsage(message);
202
+ yield message;
203
+ }
204
+ } finally {
205
+ try {
206
+ await hooks.forceFlush();
207
+ } catch (flushError) {
208
+ logger.warn("Failed to flush spans after query completed", flushError);
209
+ }
210
+ }
211
+ }
212
+
213
+ const wrapped = instrumentedIterator();
214
+
215
+ // Use Proxy to transparently delegate non-iterator properties to original query.
216
+ // Iterator protocol methods come from our wrapper (bound to the actual generator
217
+ // to avoid "incompatible receiver" errors); everything else (interrupt, close,
218
+ // setModel, setPermissionMode, etc.) delegates to the original Query.
219
+ return new Proxy(wrapped, {
220
+ get(target, prop) {
221
+ if (
222
+ prop === Symbol.asyncIterator ||
223
+ prop === "next" ||
224
+ prop === "return" ||
225
+ prop === "throw"
226
+ ) {
227
+ const value = Reflect.get(target, prop);
228
+ if (typeof value === "function") {
229
+ return value.bind(target);
230
+ }
231
+ return value;
232
+ }
233
+ const original = query[prop as string];
234
+ if (typeof original === "function") {
235
+ return original.bind(query);
236
+ }
237
+ return original;
238
+ },
239
+ });
240
+ }