@goharvest/simforge 0.2.0 → 0.4.5

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 (44) hide show
  1. package/README.md +14 -0
  2. package/dist/baml.d.ts +16 -42
  3. package/dist/baml.d.ts.map +1 -1
  4. package/dist/baml.js +219 -87
  5. package/dist/baml.js.map +1 -1
  6. package/dist/baml.test.d.ts +2 -0
  7. package/dist/baml.test.d.ts.map +1 -0
  8. package/dist/baml.test.js +86 -0
  9. package/dist/baml.test.js.map +1 -0
  10. package/dist/client.d.ts +24 -0
  11. package/dist/client.d.ts.map +1 -1
  12. package/dist/client.js +101 -3
  13. package/dist/client.js.map +1 -1
  14. package/dist/client.test.js +137 -40
  15. package/dist/client.test.js.map +1 -1
  16. package/dist/constants.d.ts +17 -0
  17. package/dist/constants.d.ts.map +1 -0
  18. package/dist/constants.js +33 -0
  19. package/dist/constants.js.map +1 -0
  20. package/dist/constants.test.d.ts +2 -0
  21. package/dist/constants.test.d.ts.map +1 -0
  22. package/dist/constants.test.js +30 -0
  23. package/dist/constants.test.js.map +1 -0
  24. package/dist/index.d.ts +4 -1
  25. package/dist/index.d.ts.map +1 -1
  26. package/dist/index.js +2 -0
  27. package/dist/index.js.map +1 -1
  28. package/dist/openai-tracing.d.ts +91 -0
  29. package/dist/openai-tracing.d.ts.map +1 -0
  30. package/dist/openai-tracing.js +179 -0
  31. package/dist/openai-tracing.js.map +1 -0
  32. package/dist/tracing.d.ts +100 -0
  33. package/dist/tracing.d.ts.map +1 -0
  34. package/dist/tracing.js +300 -0
  35. package/dist/tracing.js.map +1 -0
  36. package/dist/tracing.test.d.ts +2 -0
  37. package/dist/tracing.test.d.ts.map +1 -0
  38. package/dist/tracing.test.js +399 -0
  39. package/dist/tracing.test.js.map +1 -0
  40. package/dist/version.d.ts +10 -0
  41. package/dist/version.d.ts.map +1 -0
  42. package/dist/version.js +22 -0
  43. package/dist/version.js.map +1 -0
  44. package/package.json +16 -5
@@ -0,0 +1,91 @@
1
+ /**
2
+ * OpenAI Agents SDK tracing processor for Simforge.
3
+ *
4
+ * This module provides a TracingProcessor implementation that integrates with
5
+ * the OpenAI Agents SDK to automatically capture and send traces to Simforge.
6
+ *
7
+ * See: https://openai.github.io/openai-agents-js/
8
+ */
9
+ import type { Span, Trace } from "@openai/agents";
10
+ /**
11
+ * TracingProcessor interface from OpenAI Agents SDK v0.3.7
12
+ */
13
+ export interface TracingProcessor {
14
+ onTraceStart(trace: Trace): Promise<void>;
15
+ onTraceEnd(trace: Trace): Promise<void>;
16
+ onSpanStart(span: Span<any>): Promise<void>;
17
+ onSpanEnd(span: Span<any>): Promise<void>;
18
+ forceFlush(): Promise<void>;
19
+ shutdown(timeout?: number): Promise<void>;
20
+ }
21
+ /**
22
+ * Tracing processor for OpenAI Agents SDK integration.
23
+ *
24
+ * Implements the TracingProcessor interface from the OpenAI Agents SDK to
25
+ * automatically capture traces and spans and send them to Simforge for
26
+ * monitoring and analysis.
27
+ *
28
+ * Example usage:
29
+ * ```typescript
30
+ * import { SimforgeOpenAITracingProcessor } from '@goharvest/simforge/openai-tracing';
31
+ * import { addTraceProcessor } from '@openai/agents';
32
+ *
33
+ * const processor = new SimforgeOpenAITracingProcessor({
34
+ * apiKey: 'your-api-key',
35
+ * serviceUrl: 'https://simforge.goharvest.ai'
36
+ * });
37
+ *
38
+ * addTraceProcessor(processor);
39
+ * ```
40
+ */
41
+ export declare class SimforgeOpenAITracingProcessor implements TracingProcessor {
42
+ private readonly apiKey;
43
+ private readonly serviceUrl;
44
+ private readonly timeout;
45
+ private readonly activeTraces;
46
+ /**
47
+ * Initialize the tracing processor.
48
+ *
49
+ * @param config - Configuration options
50
+ */
51
+ constructor(config: {
52
+ apiKey: string;
53
+ serviceUrl?: string;
54
+ timeout?: number;
55
+ });
56
+ /**
57
+ * Called when a trace is started.
58
+ */
59
+ onTraceStart(trace: Trace): Promise<void>;
60
+ /**
61
+ * Called when a trace is ended.
62
+ */
63
+ onTraceEnd(trace: Trace): Promise<void>;
64
+ /**
65
+ * Called when a span is started.
66
+ */
67
+ onSpanStart(_span: Span<any>): Promise<void>;
68
+ /**
69
+ * Called when a span is ended.
70
+ *
71
+ * For "response" spans (LLM calls), we send the trace data to Simforge.
72
+ */
73
+ onSpanEnd(span: Span<any>): Promise<void>;
74
+ /**
75
+ * Called when a trace is being flushed.
76
+ */
77
+ forceFlush(): Promise<void>;
78
+ /**
79
+ * Called when the trace processor is shutting down.
80
+ */
81
+ shutdown(_timeout?: number): Promise<void>;
82
+ /**
83
+ * Send a trace for a single LLM call (response span).
84
+ */
85
+ private sendTraceForLLMCall;
86
+ /**
87
+ * Send trace data to Simforge API.
88
+ */
89
+ private sendTrace;
90
+ }
91
+ //# sourceMappingURL=openai-tracing.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"openai-tracing.d.ts","sourceRoot":"","sources":["../src/openai-tracing.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAEH,OAAO,KAAK,EAAE,IAAI,EAAE,KAAK,EAAE,MAAM,gBAAgB,CAAA;AAEjD;;GAEG;AACH,MAAM,WAAW,gBAAgB;IAC/B,YAAY,CAAC,KAAK,EAAE,KAAK,GAAG,OAAO,CAAC,IAAI,CAAC,CAAA;IACzC,UAAU,CAAC,KAAK,EAAE,KAAK,GAAG,OAAO,CAAC,IAAI,CAAC,CAAA;IAEvC,WAAW,CAAC,IAAI,EAAE,IAAI,CAAC,GAAG,CAAC,GAAG,OAAO,CAAC,IAAI,CAAC,CAAA;IAE3C,SAAS,CAAC,IAAI,EAAE,IAAI,CAAC,GAAG,CAAC,GAAG,OAAO,CAAC,IAAI,CAAC,CAAA;IACzC,UAAU,IAAI,OAAO,CAAC,IAAI,CAAC,CAAA;IAC3B,QAAQ,CAAC,OAAO,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAAA;CAC1C;AAED;;;;;;;;;;;;;;;;;;;GAmBG;AACH,qBAAa,8BAA+B,YAAW,gBAAgB;IACrE,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAQ;IAC/B,OAAO,CAAC,QAAQ,CAAC,UAAU,CAAQ;IACnC,OAAO,CAAC,QAAQ,CAAC,OAAO,CAAQ;IAChC,OAAO,CAAC,QAAQ,CAAC,YAAY,CAAgC;IAE7D;;;;OAIG;gBACS,MAAM,EAAE;QAClB,MAAM,EAAE,MAAM,CAAA;QACd,UAAU,CAAC,EAAE,MAAM,CAAA;QACnB,OAAO,CAAC,EAAE,MAAM,CAAA;KACjB;IAMD;;OAEG;IACG,YAAY,CAAC,KAAK,EAAE,KAAK,GAAG,OAAO,CAAC,IAAI,CAAC;IAI/C;;OAEG;IACG,UAAU,CAAC,KAAK,EAAE,KAAK,GAAG,OAAO,CAAC,IAAI,CAAC;IAI7C;;OAEG;IAEG,WAAW,CAAC,KAAK,EAAE,IAAI,CAAC,GAAG,CAAC,GAAG,OAAO,CAAC,IAAI,CAAC;IAIlD;;;;OAIG;IAEG,SAAS,CAAC,IAAI,EAAE,IAAI,CAAC,GAAG,CAAC,GAAG,OAAO,CAAC,IAAI,CAAC;IA0B/C;;OAEG;IACG,UAAU,IAAI,OAAO,CAAC,IAAI,CAAC;IAIjC;;OAEG;IACG,QAAQ,CAAC,QAAQ,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IAIhD;;OAEG;YACW,mBAAmB;IAmDjC;;OAEG;YACW,SAAS;CA8CxB"}
@@ -0,0 +1,179 @@
1
+ /**
2
+ * OpenAI Agents SDK tracing processor for Simforge.
3
+ *
4
+ * This module provides a TracingProcessor implementation that integrates with
5
+ * the OpenAI Agents SDK to automatically capture and send traces to Simforge.
6
+ *
7
+ * See: https://openai.github.io/openai-agents-js/
8
+ */
9
+ /**
10
+ * Tracing processor for OpenAI Agents SDK integration.
11
+ *
12
+ * Implements the TracingProcessor interface from the OpenAI Agents SDK to
13
+ * automatically capture traces and spans and send them to Simforge for
14
+ * monitoring and analysis.
15
+ *
16
+ * Example usage:
17
+ * ```typescript
18
+ * import { SimforgeOpenAITracingProcessor } from '@goharvest/simforge/openai-tracing';
19
+ * import { addTraceProcessor } from '@openai/agents';
20
+ *
21
+ * const processor = new SimforgeOpenAITracingProcessor({
22
+ * apiKey: 'your-api-key',
23
+ * serviceUrl: 'https://simforge.goharvest.ai'
24
+ * });
25
+ *
26
+ * addTraceProcessor(processor);
27
+ * ```
28
+ */
29
+ export class SimforgeOpenAITracingProcessor {
30
+ /**
31
+ * Initialize the tracing processor.
32
+ *
33
+ * @param config - Configuration options
34
+ */
35
+ constructor(config) {
36
+ this.activeTraces = new Map();
37
+ this.apiKey = config.apiKey;
38
+ this.serviceUrl = config.serviceUrl ?? "https://simforge.goharvest.ai";
39
+ this.timeout = config.timeout ?? 10000;
40
+ }
41
+ /**
42
+ * Called when a trace is started.
43
+ */
44
+ async onTraceStart(trace) {
45
+ this.activeTraces.set(trace.traceId, trace);
46
+ }
47
+ /**
48
+ * Called when a trace is ended.
49
+ */
50
+ async onTraceEnd(trace) {
51
+ this.activeTraces.delete(trace.traceId);
52
+ }
53
+ /**
54
+ * Called when a span is started.
55
+ */
56
+ // biome-ignore lint/suspicious/noExplicitAny: OpenAI Agents SDK uses any for span data
57
+ async onSpanStart(_span) {
58
+ // No action needed on span start
59
+ }
60
+ /**
61
+ * Called when a span is ended.
62
+ *
63
+ * For "response" spans (LLM calls), we send the trace data to Simforge.
64
+ */
65
+ // biome-ignore lint/suspicious/noExplicitAny: OpenAI Agents SDK uses any for span data
66
+ async onSpanEnd(span) {
67
+ try {
68
+ // Only process "response" spans (LLM calls)
69
+ if (span.spanData?.type !== "response") {
70
+ return;
71
+ }
72
+ // Get the parent trace for context
73
+ const parentTrace = this.activeTraces.get(span.traceId);
74
+ if (!parentTrace) {
75
+ console.warn(`[SimforgeOpenAITracingProcessor] No parent trace found for span ${span.spanId}`);
76
+ return;
77
+ }
78
+ // Send the trace for this LLM call
79
+ await this.sendTraceForLLMCall(span, parentTrace);
80
+ }
81
+ catch (error) {
82
+ console.error("[SimforgeOpenAITracingProcessor] Error processing span end:", error);
83
+ }
84
+ }
85
+ /**
86
+ * Called when a trace is being flushed.
87
+ */
88
+ async forceFlush() {
89
+ // No buffering, so nothing to flush
90
+ }
91
+ /**
92
+ * Called when the trace processor is shutting down.
93
+ */
94
+ async shutdown(_timeout) {
95
+ this.activeTraces.clear();
96
+ }
97
+ /**
98
+ * Send a trace for a single LLM call (response span).
99
+ */
100
+ async sendTraceForLLMCall(
101
+ // biome-ignore lint/suspicious/noExplicitAny: OpenAI Agents SDK uses any for span data
102
+ span, parentTrace) {
103
+ try {
104
+ // Serialize the trace and span data
105
+ const rawTrace = {
106
+ id: parentTrace.traceId,
107
+ workflow_name: parentTrace.name,
108
+ group_id: parentTrace.groupId,
109
+ metadata: parentTrace.metadata,
110
+ };
111
+ const rawSpan = {
112
+ id: span.spanId,
113
+ trace_id: span.traceId,
114
+ parent_id: span.parentId,
115
+ started_at: typeof span.startedAt === "string"
116
+ ? span.startedAt
117
+ : span.startedAt
118
+ ? span.startedAt.toISOString()
119
+ : undefined,
120
+ ended_at: typeof span.endedAt === "string"
121
+ ? span.endedAt
122
+ : span.endedAt
123
+ ? span.endedAt.toISOString()
124
+ : undefined,
125
+ span_data: span.spanData,
126
+ error: span.error,
127
+ };
128
+ // Send raw trace and span data - let server extract everything
129
+ const traceData = {
130
+ type: "openai",
131
+ source: "typescript-sdk-openai-tracing",
132
+ rawTrace,
133
+ rawSpan,
134
+ };
135
+ await this.sendTrace(traceData);
136
+ }
137
+ catch (error) {
138
+ console.error("[SimforgeOpenAITracingProcessor] Error sending trace for LLM call:", error);
139
+ }
140
+ }
141
+ /**
142
+ * Send trace data to Simforge API.
143
+ */
144
+ async sendTrace(traceData) {
145
+ const url = `${this.serviceUrl}/api/sdk/traces/external`;
146
+ const controller = new AbortController();
147
+ const timeoutId = setTimeout(() => controller.abort(), this.timeout);
148
+ try {
149
+ const response = await fetch(url, {
150
+ method: "POST",
151
+ headers: {
152
+ "Content-Type": "application/json",
153
+ Authorization: `Bearer ${this.apiKey}`,
154
+ },
155
+ body: JSON.stringify(traceData),
156
+ signal: controller.signal,
157
+ });
158
+ if (!response.ok) {
159
+ const errorText = await response.text();
160
+ throw new Error(`Failed to send trace: HTTP ${response.status}: ${errorText.slice(0, 500)}`);
161
+ }
162
+ const result = await response.json();
163
+ console.debug(`[SimforgeOpenAITracingProcessor] Successfully sent trace to Simforge:`, result);
164
+ }
165
+ catch (error) {
166
+ if (error instanceof Error) {
167
+ if (error.name === "AbortError") {
168
+ throw new Error(`Request timed out after ${this.timeout}ms`);
169
+ }
170
+ throw error;
171
+ }
172
+ throw new Error("Unknown error occurred while sending trace");
173
+ }
174
+ finally {
175
+ clearTimeout(timeoutId);
176
+ }
177
+ }
178
+ }
179
+ //# sourceMappingURL=openai-tracing.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"openai-tracing.js","sourceRoot":"","sources":["../src/openai-tracing.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAkBH;;;;;;;;;;;;;;;;;;;GAmBG;AACH,MAAM,OAAO,8BAA8B;IAMzC;;;;OAIG;IACH,YAAY,MAIX;QAXgB,iBAAY,GAAuB,IAAI,GAAG,EAAE,CAAA;QAY3D,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC,MAAM,CAAA;QAC3B,IAAI,CAAC,UAAU,GAAG,MAAM,CAAC,UAAU,IAAI,+BAA+B,CAAA;QACtE,IAAI,CAAC,OAAO,GAAG,MAAM,CAAC,OAAO,IAAI,KAAK,CAAA;IACxC,CAAC;IAED;;OAEG;IACH,KAAK,CAAC,YAAY,CAAC,KAAY;QAC7B,IAAI,CAAC,YAAY,CAAC,GAAG,CAAC,KAAK,CAAC,OAAO,EAAE,KAAK,CAAC,CAAA;IAC7C,CAAC;IAED;;OAEG;IACH,KAAK,CAAC,UAAU,CAAC,KAAY;QAC3B,IAAI,CAAC,YAAY,CAAC,MAAM,CAAC,KAAK,CA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CAAC;YACH,MAAM,QAAQ,GAAG,MAAM,KAAK,CAAC,GAAG,EAAE;gBAChC,MAAM,EAAE,MAAM;gBACd,OAAO,EAAE;oBACP,cAAc,EAAE,kBAAkB;oBAClC,aAAa,EAAE,UAAU,IAAI,CAAC,MAAM,EAAE;iBACvC;gBACD,IAAI,EAAE,IAAI,CAAC,SAAS,CAAC,SAAS,CAAC;gBAC/B,MAAM,EAAE,UAAU,CAAC,MAAM;aAC1B,CAAC,CAAA;YAEF,IAAI,CAAC,QAAQ,CAAC,EAAE,EAAE,CAAC;gBACjB,MAAM,SAAS,GAAG,MAAM,QAAQ,CAAC,IAAI,EAAE,CAAA;gBACvC,MAAM,IAAI,KAAK,CACb,8BAA8B,QAAQ,CAAC,MAAM,KAAK,SAAS,CAAC,KAAK,CAAC,CAAC,EAAE,GAAG,CAAC,EAAE,CAC5E,CAAA;YACH,CAAC;YAED,MAAM,MAAM,GAAG,MAAM,QAAQ,CAAC,IAAI,EAAE,CAAA;YACpC,OAAO,CAAC,KAAK,CACX,uEAAuE,EACvE,MAAM,CACP,CAAA;QACH,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,IAAI,KAAK,YAAY,KAAK,EAAE,CAAC;gBAC3B,IAAI,KAAK,CAAC,IAAI,KAAK,YAAY,EAAE,CAAC;oBAChC,MAAM,IAAI,KAAK,CAAC,2BAA2B,IAAI,CAAC,OAAO,IAAI,CAAC,CAAA;gBAC9D,CAAC;gBACD,MAAM,KAAK,CAAA;YACb,CAAC;YACD,MAAM,IAAI,KAAK,CAAC,4CAA4C,CAAC,CAAA;QAC/D,CAAC;gBAAS,CAAC;YACT,YAAY,CAAC,SAAS,CAAC,CAAA;QACzB,CAAC;IACH,CAAC;CACF"}
@@ -0,0 +1,100 @@
1
+ /**
2
+ * Tracing utilities for external trace submission to Simforge.
3
+ *
4
+ * This module provides utilities for sending external traces (e.g., from OpenAI API calls)
5
+ * to Simforge for monitoring and analysis.
6
+ */
7
+ import type { Span, Trace } from "@openai/agents";
8
+ export interface TraceResponse {
9
+ traceId: string;
10
+ status: "success";
11
+ }
12
+ /**
13
+ * TracingProcessor interface from OpenAI Agents SDK v0.3.7
14
+ */
15
+ export interface TracingProcessor {
16
+ onTraceStart(trace: Trace): Promise<void>;
17
+ onTraceEnd(trace: Trace): Promise<void>;
18
+ onSpanStart(span: Span<any>): Promise<void>;
19
+ onSpanEnd(span: Span<any>): Promise<void>;
20
+ forceFlush(): Promise<void>;
21
+ shutdown(timeout?: number): Promise<void>;
22
+ }
23
+ /**
24
+ * Tracing processor for OpenAI Agents SDK integration.
25
+ *
26
+ * Implements the TracingProcessor interface from the OpenAI Agents SDK to
27
+ * automatically capture traces and spans and send them to Simforge for
28
+ * monitoring and analysis.
29
+ *
30
+ * Example usage:
31
+ * ```typescript
32
+ * import { Simforge } from '@goharvest/simforge';
33
+ * import { addTraceProcessor } from '@openai/agents';
34
+ *
35
+ * const client = new Simforge({ apiKey: 'your-api-key' });
36
+ * const processor = client.getOpenAiTracingProcessor();
37
+ * addTraceProcessor(processor);
38
+ * ```
39
+ */
40
+ export declare class SimforgeOpenAITracingProcessor implements TracingProcessor {
41
+ private readonly apiKey;
42
+ private readonly serviceUrl;
43
+ private readonly timeout;
44
+ private readonly activeTraces;
45
+ /**
46
+ * Initialize the tracing processor.
47
+ *
48
+ * @param config - Configuration options
49
+ * @throws {Error} If @openai/agents is not installed
50
+ */
51
+ constructor(config: {
52
+ apiKey: string;
53
+ serviceUrl?: string;
54
+ timeout?: number;
55
+ });
56
+ /**
57
+ * Called when a trace is started.
58
+ */
59
+ onTraceStart(trace: Trace): Promise<void>;
60
+ /**
61
+ * Called when a trace is ended.
62
+ */
63
+ onTraceEnd(trace: Trace): Promise<void>;
64
+ /**
65
+ * Called when a span is started.
66
+ */
67
+ onSpanStart(span: Span<any>): Promise<void>;
68
+ /**
69
+ * Called when a span is ended.
70
+ *
71
+ * Send all spans to Simforge for complete trace capture.
72
+ */
73
+ onSpanEnd(span: Span<any>): Promise<void>;
74
+ /**
75
+ * Called when a trace is being flushed.
76
+ */
77
+ forceFlush(): Promise<void>;
78
+ /**
79
+ * Called when the trace processor is shutting down.
80
+ */
81
+ shutdown(_timeout?: number): Promise<void>;
82
+ /**
83
+ * Send raw trace to Simforge API.
84
+ */
85
+ private sendRawTrace;
86
+ /**
87
+ * Export span to JSON object, collecting any errors.
88
+ */
89
+ private exportSpan;
90
+ /**
91
+ * Extract and add input/response to serialized span, updating errors list.
92
+ */
93
+ private extractSpanInputResponse;
94
+ /**
95
+ * Build span payload and handle JSON serialization, returning request body.
96
+ */
97
+ private buildSpanPayload;
98
+ private sendRawSpan;
99
+ }
100
+ //# sourceMappingURL=tracing.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"tracing.d.ts","sourceRoot":"","sources":["../src/tracing.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAYH,OAAO,KAAK,EAAE,IAAI,EAAE,KAAK,EAAE,MAAM,gBAAgB,CAAA;AAGjD,MAAM,WAAW,aAAa;IAC5B,OAAO,EAAE,MAAM,CAAA;IACf,MAAM,EAAE,SAAS,CAAA;CAClB;AAED;;GAEG;AACH,MAAM,WAAW,gBAAgB;IAC/B,YAAY,CAAC,KAAK,EAAE,KAAK,GAAG,OAAO,CAAC,IAAI,CAAC,CAAA;IACzC,UAAU,CAAC,KAAK,EAAE,KAAK,GAAG,OAAO,CAAC,IAAI,CAAC,CAAA;IAEvC,WAAW,CAAC,IAAI,EAAE,IAAI,CAAC,GAAG,CAAC,GAAG,OAAO,CAAC,IAAI,CAAC,CAAA;IAE3C,SAAS,CAAC,IAAI,EAAE,IAAI,CAAC,GAAG,CAAC,GAAG,OAAO,CAAC,IAAI,CAAC,CAAA;IACzC,UAAU,IAAI,OAAO,CAAC,IAAI,CAAC,CAAA;IAC3B,QAAQ,CAAC,OAAO,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAAA;CAC1C;AAED;;;;;;;;;;;;;;;;GAgBG;AACH,qBAAa,8BAA+B,YAAW,gBAAgB;IACrE,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAQ;IAC/B,OAAO,CAAC,QAAQ,CAAC,UAAU,CAAQ;IACnC,OAAO,CAAC,QAAQ,CAAC,OAAO,CAAQ;IAChC,OAAO,CAAC,QAAQ,CAAC,YAAY,CAAgC;IAE7D;;;;;OAKG;gBACS,MAAM,EAAE;QAClB,MAAM,EAAE,MAAM,CAAA;QACd,UAAU,CAAC,EAAE,MAAM,CAAA;QACnB,OAAO,CAAC,EAAE,MAAM,CAAA;KACjB;IAaD;;OAEG;IACG,YAAY,CAAC,KAAK,EAAE,KAAK,GAAG,OAAO,CAAC,IAAI,CAAC;IAc/C;;OAEG;IACG,UAAU,CAAC,KAAK,EAAE,KAAK,GAAG,OAAO,CAAC,IAAI,CAAC;IAc7C;;OAEG;IAEG,WAAW,CAAC,IAAI,EAAE,IAAI,CAAC,GAAG,CAAC,GAAG,OAAO,CAAC,IAAI,CAAC;IAYjD;;;;OAIG;IAEG,SAAS,CAAC,IAAI,EAAE,IAAI,CAAC,GAAG,CAAC,GAAG,OAAO,CAAC,IAAI,CAAC;IAY/C;;OAEG;IACG,UAAU,IAAI,OAAO,CAAC,IAAI,CAAC;IAIjC;;OAEG;IACG,QAAQ,CAAC,QAAQ,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IAIhD;;OAEG;YACW,YAAY;IAiD1B;;OAEG;IACH,OAAO,CAAC,UAAU;IAiClB;;OAEG;IACH,OAAO,CAAC,wBAAwB;IA2BhC;;OAEG;IACH,OAAO,CAAC,gBAAgB;YAwCV,WAAW;CAkD1B"}
@@ -0,0 +1,300 @@
1
+ /**
2
+ * Tracing utilities for external trace submission to Simforge.
3
+ *
4
+ * This module provides utilities for sending external traces (e.g., from OpenAI API calls)
5
+ * to Simforge for monitoring and analysis.
6
+ */
7
+ // Try to import OpenAI Agents SDK types - will fail at runtime if not installed
8
+ let OPENAI_AGENTS_AVAILABLE = false;
9
+ try {
10
+ // This will throw if @openai/agents is not installed
11
+ await import("@openai/agents");
12
+ OPENAI_AGENTS_AVAILABLE = true;
13
+ }
14
+ catch {
15
+ // @openai/agents not installed
16
+ }
17
+ import { __version__, DEFAULT_SERVICE_URL } from "./constants.js";
18
+ /**
19
+ * Tracing processor for OpenAI Agents SDK integration.
20
+ *
21
+ * Implements the TracingProcessor interface from the OpenAI Agents SDK to
22
+ * automatically capture traces and spans and send them to Simforge for
23
+ * monitoring and analysis.
24
+ *
25
+ * Example usage:
26
+ * ```typescript
27
+ * import { Simforge } from '@goharvest/simforge';
28
+ * import { addTraceProcessor } from '@openai/agents';
29
+ *
30
+ * const client = new Simforge({ apiKey: 'your-api-key' });
31
+ * const processor = client.getOpenAiTracingProcessor();
32
+ * addTraceProcessor(processor);
33
+ * ```
34
+ */
35
+ export class SimforgeOpenAITracingProcessor {
36
+ /**
37
+ * Initialize the tracing processor.
38
+ *
39
+ * @param config - Configuration options
40
+ * @throws {Error} If @openai/agents is not installed
41
+ */
42
+ constructor(config) {
43
+ this.activeTraces = new Map();
44
+ if (!OPENAI_AGENTS_AVAILABLE) {
45
+ throw new Error("@openai/agents is required for tracing functionality. " +
46
+ "Install it with: npm install @openai/agents");
47
+ }
48
+ this.apiKey = config.apiKey;
49
+ this.serviceUrl = config.serviceUrl ?? DEFAULT_SERVICE_URL;
50
+ this.timeout = config.timeout ?? 10000;
51
+ }
52
+ /**
53
+ * Called when a trace is started.
54
+ */
55
+ async onTraceStart(trace) {
56
+ this.activeTraces.set(trace.traceId, trace);
57
+ // Send the raw trace to Simforge immediately
58
+ try {
59
+ await this.sendRawTrace(trace);
60
+ }
61
+ catch (error) {
62
+ console.error("[SimforgeOpenAITracingProcessor] Error sending raw trace:", error);
63
+ }
64
+ }
65
+ /**
66
+ * Called when a trace is ended.
67
+ */
68
+ async onTraceEnd(trace) {
69
+ try {
70
+ // Send the raw trace again to capture any updates
71
+ await this.sendRawTrace(trace);
72
+ }
73
+ catch (error) {
74
+ console.error("[SimforgeOpenAITracingProcessor] Error sending raw trace on end:", error);
75
+ }
76
+ this.activeTraces.delete(trace.traceId);
77
+ }
78
+ /**
79
+ * Called when a span is started.
80
+ */
81
+ // biome-ignore lint/suspicious/noExplicitAny: OpenAI Agents SDK uses any for span data
82
+ async onSpanStart(span) {
83
+ try {
84
+ // Send the raw span to Simforge immediately
85
+ await this.sendRawSpan(span);
86
+ }
87
+ catch (error) {
88
+ console.error("[SimforgeOpenAITracingProcessor] Error sending raw span on start:", error);
89
+ }
90
+ }
91
+ /**
92
+ * Called when a span is ended.
93
+ *
94
+ * Send all spans to Simforge for complete trace capture.
95
+ */
96
+ // biome-ignore lint/suspicious/noExplicitAny: OpenAI Agents SDK uses any for span data
97
+ async onSpanEnd(span) {
98
+ try {
99
+ // Send the raw span to Simforge again to capture updates
100
+ await this.sendRawSpan(span);
101
+ }
102
+ catch (error) {
103
+ console.error("[SimforgeOpenAITracingProcessor] Error processing span end:", error);
104
+ }
105
+ }
106
+ /**
107
+ * Called when a trace is being flushed.
108
+ */
109
+ async forceFlush() {
110
+ // No buffering, so nothing to flush
111
+ }
112
+ /**
113
+ * Called when the trace processor is shutting down.
114
+ */
115
+ async shutdown(_timeout) {
116
+ this.activeTraces.clear();
117
+ }
118
+ /**
119
+ * Send raw trace to Simforge API.
120
+ */
121
+ async sendRawTrace(trace) {
122
+ const url = `${this.serviceUrl}/api/sdk/externalTraces`;
123
+ const controller = new AbortController();
124
+ const timeoutId = setTimeout(() => controller.abort(), this.timeout);
125
+ try {
126
+ const traceData = {
127
+ type: "openai",
128
+ source: "typescript-sdk-openai-tracing",
129
+ rawTrace: trace.toJSON(),
130
+ sdkVersion: __version__,
131
+ };
132
+ const response = await fetch(url, {
133
+ method: "POST",
134
+ headers: {
135
+ "Content-Type": "application/json",
136
+ Authorization: `Bearer ${this.apiKey}`,
137
+ },
138
+ body: JSON.stringify(traceData),
139
+ signal: controller.signal,
140
+ });
141
+ if (!response.ok) {
142
+ const errorText = await response.text();
143
+ throw new Error(`Failed to send raw trace: HTTP ${response.status}: ${errorText.slice(0, 500)}`);
144
+ }
145
+ const result = await response.json();
146
+ console.debug(`[SimforgeOpenAITracingProcessor] Successfully sent raw trace to Simforge:`, result);
147
+ }
148
+ catch (error) {
149
+ if (error instanceof Error) {
150
+ if (error.name === "AbortError") {
151
+ throw new Error(`Request timed out after ${this.timeout}ms`);
152
+ }
153
+ throw error;
154
+ }
155
+ throw new Error("Unknown error occurred while sending raw trace");
156
+ }
157
+ finally {
158
+ clearTimeout(timeoutId);
159
+ }
160
+ }
161
+ /**
162
+ * Export span to JSON object, collecting any errors.
163
+ */
164
+ exportSpan(
165
+ // biome-ignore lint/suspicious/noExplicitAny: OpenAI Agents SDK uses any for span data
166
+ span) {
167
+ const errors = [];
168
+ let serializedSpan;
169
+ try {
170
+ const jsonResult = span.toJSON();
171
+ if (typeof jsonResult !== "object" || jsonResult === null) {
172
+ errors.push({
173
+ step: "span.toJSON()",
174
+ error: `Returned unexpected type: ${typeof jsonResult}`,
175
+ });
176
+ serializedSpan = {};
177
+ }
178
+ else {
179
+ serializedSpan = jsonResult;
180
+ }
181
+ }
182
+ catch (error) {
183
+ errors.push({
184
+ step: "span.toJSON()",
185
+ error: error instanceof Error ? error.message : String(error),
186
+ });
187
+ serializedSpan = {};
188
+ }
189
+ if (!serializedSpan.span_data) {
190
+ serializedSpan.span_data = {};
191
+ }
192
+ return [serializedSpan, errors];
193
+ }
194
+ /**
195
+ * Extract and add input/response to serialized span, updating errors list.
196
+ */
197
+ extractSpanInputResponse(
198
+ // biome-ignore lint/suspicious/noExplicitAny: OpenAI Agents SDK uses any for span data
199
+ span, serializedSpan, errors) {
200
+ const spanData = serializedSpan.span_data;
201
+ try {
202
+ spanData.input = span.spanData?._input || [];
203
+ }
204
+ catch (error) {
205
+ errors.push({
206
+ step: "access_input",
207
+ error: error instanceof Error ? error.message : String(error),
208
+ });
209
+ }
210
+ try {
211
+ spanData.response = span.spanData?._response || null;
212
+ }
213
+ catch (error) {
214
+ errors.push({
215
+ step: "access_response",
216
+ error: error instanceof Error ? error.message : String(error),
217
+ });
218
+ }
219
+ }
220
+ /**
221
+ * Build span payload and handle JSON serialization, returning request body.
222
+ */
223
+ buildSpanPayload(
224
+ // biome-ignore lint/suspicious/noExplicitAny: OpenAI Agents SDK uses any for span data
225
+ span, serializedSpan, errors) {
226
+ let spanPayload = {
227
+ type: "openai",
228
+ source: "typescript-sdk-openai-tracing",
229
+ sourceTraceId: span.traceId || "unknown",
230
+ rawSpan: serializedSpan,
231
+ sdkVersion: __version__,
232
+ };
233
+ if (errors.length > 0) {
234
+ spanPayload.errors = errors;
235
+ }
236
+ try {
237
+ return JSON.stringify(spanPayload);
238
+ }
239
+ catch (error) {
240
+ errors.push({
241
+ step: "json_serialize",
242
+ error: error instanceof Error ? error.message : String(error),
243
+ });
244
+ // Try to send what we can with error info
245
+ spanPayload = {
246
+ type: "openai",
247
+ source: "typescript-sdk-openai-tracing",
248
+ sourceTraceId: span.traceId || "unknown",
249
+ rawSpan: {
250
+ id: span.spanId || "unknown",
251
+ trace_id: span.traceId || "unknown",
252
+ },
253
+ errors: errors,
254
+ };
255
+ return JSON.stringify(spanPayload);
256
+ }
257
+ }
258
+ async sendRawSpan(
259
+ // biome-ignore lint/suspicious/noExplicitAny: OpenAI Agents SDK uses any for span data
260
+ span) {
261
+ const errors = [];
262
+ const [serializedSpan, exportErrors] = this.exportSpan(span);
263
+ errors.push(...exportErrors);
264
+ this.extractSpanInputResponse(span, serializedSpan, errors);
265
+ const requestBody = this.buildSpanPayload(span, serializedSpan, errors);
266
+ const url = `${this.serviceUrl}/api/sdk/externalSpans`;
267
+ const controller = new AbortController();
268
+ const timeoutId = setTimeout(() => controller.abort(), this.timeout);
269
+ try {
270
+ const response = await fetch(url, {
271
+ method: "POST",
272
+ headers: {
273
+ "Content-Type": "application/json",
274
+ Authorization: `Bearer ${this.apiKey}`,
275
+ },
276
+ body: requestBody,
277
+ signal: controller.signal,
278
+ });
279
+ if (!response.ok) {
280
+ const errorText = await response.text();
281
+ throw new Error(`Failed to send raw span: HTTP ${response.status}: ${errorText.slice(0, 500)}`);
282
+ }
283
+ const result = await response.json();
284
+ console.debug(`[SimforgeOpenAITracingProcessor] Successfully sent raw span to Simforge:`, result);
285
+ }
286
+ catch (error) {
287
+ if (error instanceof Error) {
288
+ if (error.name === "AbortError") {
289
+ throw new Error(`Request timed out after ${this.timeout}ms`);
290
+ }
291
+ throw error;
292
+ }
293
+ throw new Error("Unknown error occurred while sending raw span");
294
+ }
295
+ finally {
296
+ clearTimeout(timeoutId);
297
+ }
298
+ }
299
+ }
300
+ //# sourceMappingURL=tracing.js.map