retrace-sdk 0.1.6 → 0.2.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.
package/dist/sdk.test.js DELETED
@@ -1,132 +0,0 @@
1
- import { describe, it, expect, vi, beforeEach } from "vitest";
2
- import { configure, getConfig } from "./config.js";
3
- // Reset config between tests
4
- beforeEach(() => {
5
- configure({ apiKey: "", baseUrl: "http://localhost:3001", enabled: true, wsUrl: "" });
6
- });
7
- describe("Config", () => {
8
- it("has sensible defaults", () => {
9
- const c = getConfig();
10
- expect(c.baseUrl).toBe("http://localhost:3001");
11
- expect(c.enabled).toBe(true);
12
- });
13
- it("configures custom values", () => {
14
- configure({ apiKey: "rt_live_test", baseUrl: "https://api.example.com" });
15
- const c = getConfig();
16
- expect(c.apiKey).toBe("rt_live_test");
17
- expect(c.baseUrl).toBe("https://api.example.com");
18
- expect(c.wsUrl).toBe("wss://api.example.com");
19
- });
20
- it("auto-derives wsUrl from baseUrl", () => {
21
- configure({ baseUrl: "https://custom.io" });
22
- expect(getConfig().wsUrl).toBe("wss://custom.io");
23
- configure({ baseUrl: "http://localhost:3001" });
24
- expect(getConfig().wsUrl).toBe("ws://localhost:3001");
25
- });
26
- it("warns on invalid API key prefix", () => {
27
- const spy = vi.spyOn(console, "warn").mockImplementation(() => { });
28
- configure({ apiKey: "invalid_key" });
29
- expect(spy).toHaveBeenCalledWith(expect.stringContaining("rt_live_"));
30
- spy.mockRestore();
31
- });
32
- it("does not warn on valid API key", () => {
33
- const spy = vi.spyOn(console, "warn").mockImplementation(() => { });
34
- configure({ apiKey: "rt_live_valid123" });
35
- expect(spy).not.toHaveBeenCalled();
36
- spy.mockRestore();
37
- });
38
- });
39
- describe("Trace model", () => {
40
- it("SpanBuilder creates valid span data", async () => {
41
- const { SpanBuilder, SpanType } = await import("./trace.js");
42
- const sb = new SpanBuilder("test-span", SpanType.LLM_CALL).start();
43
- sb.setModel("gpt-4o");
44
- sb.setInput({ prompt: "hi" });
45
- const data = sb.end("hello");
46
- expect(data.name).toBe("test-span");
47
- expect(data.span_type).toBe("llm_call");
48
- expect(data.model).toBe("gpt-4o");
49
- expect(data.output).toBe("hello");
50
- expect(data.id).toHaveLength(36);
51
- expect(data.started_at).toBeDefined();
52
- expect(data.ended_at).toBeDefined();
53
- });
54
- it("TraceBuilder creates valid trace data", async () => {
55
- const { TraceBuilder, TraceStatus } = await import("./trace.js");
56
- const tb = new TraceBuilder();
57
- tb.start("my-trace", { prompt: "test" });
58
- const data = tb.end("result", TraceStatus.COMPLETED);
59
- expect(data.name).toBe("my-trace");
60
- expect(data.status).toBe("completed");
61
- expect(data.output).toBe("result");
62
- expect(data.id).toHaveLength(36);
63
- });
64
- it("SpanType enum values", async () => {
65
- const { SpanType } = await import("./trace.js");
66
- expect(SpanType.LLM_CALL).toBe("llm_call");
67
- expect(SpanType.TOOL_CALL).toBe("tool_call");
68
- expect(SpanType.ERROR).toBe("error");
69
- expect(SpanType.FORK_POINT).toBe("fork_point");
70
- });
71
- });
72
- describe("Recorder", () => {
73
- it("trace() wraps sync function", async () => {
74
- configure({ apiKey: "rt_live_t", baseUrl: "http://x:1", enabled: true });
75
- const { trace } = await import("./recorder.js");
76
- const fn = trace((x) => `result:${x}`, { name: "sync-fn" });
77
- expect(fn("hi")).toBe("result:hi");
78
- });
79
- it("trace() wraps async function", async () => {
80
- configure({ apiKey: "rt_live_t", baseUrl: "http://x:1", enabled: true });
81
- const { trace } = await import("./recorder.js");
82
- const fn = trace(async (x) => `async:${x}`, { name: "async-fn" });
83
- const result = await fn("hi");
84
- expect(result).toBe("async:hi");
85
- });
86
- it("trace() propagates exceptions", async () => {
87
- configure({ apiKey: "rt_live_t", baseUrl: "http://x:1", enabled: true });
88
- const { trace } = await import("./recorder.js");
89
- const fn = trace(() => { throw new Error("boom"); }, { name: "err-fn" });
90
- expect(() => fn()).toThrow("boom");
91
- });
92
- it("disabled SDK is no-op", async () => {
93
- configure({ apiKey: "rt_live_t", enabled: false });
94
- const { trace } = await import("./recorder.js");
95
- const fn = trace((x) => `r:${x}`, { name: "off" });
96
- expect(fn("hi")).toBe("r:hi");
97
- });
98
- });
99
- describe("Transport", () => {
100
- it("HTTPTransport accumulates and flushes", async () => {
101
- configure({ apiKey: "rt_live_t", baseUrl: "http://x:1" });
102
- const { HTTPTransport } = await import("./transport.js");
103
- const http = new HTTPTransport();
104
- const mockFetch = vi.fn().mockResolvedValue({ ok: true });
105
- vi.stubGlobal("fetch", mockFetch);
106
- http.send("trace_started", { id: "abc", name: "t", status: "running", started_at: "2026-01-01T00:00:00Z", total_tokens: 0, total_cost: 0, total_duration_ms: 0 });
107
- http.send("span_started", { id: "s1", trace_id: "abc", span_type: "llm_call", name: "s", started_at: "2026-01-01T00:00:00Z" });
108
- http.send("span_ended", { id: "s1", ended_at: "2026-01-01T00:00:01Z", output: "hi" });
109
- http.send("trace_ended", { id: "abc", ended_at: "2026-01-01T00:00:02Z", status: "completed" });
110
- expect(mockFetch).toHaveBeenCalled();
111
- const body = JSON.parse(mockFetch.mock.calls[0][1].body);
112
- expect(body.id).toBe("abc");
113
- expect(body.spans).toHaveLength(1);
114
- expect(body.spans[0].output).toBe("hi");
115
- vi.unstubAllGlobals();
116
- });
117
- it("createTransport returns correct type", async () => {
118
- const { createTransport, HTTPTransport } = await import("./transport.js");
119
- expect(createTransport("http")).toBeInstanceOf(HTTPTransport);
120
- });
121
- });
122
- describe("README examples", () => {
123
- it("TypeScript README example works", async () => {
124
- configure({ apiKey: "rt_live_test", enabled: false });
125
- const { trace } = await import("./recorder.js");
126
- const runAgent = trace(async (prompt) => {
127
- return `Response to: ${prompt}`;
128
- }, { name: "my-agent" });
129
- const result = await runAgent("What is quantum computing?");
130
- expect(result).toContain("quantum");
131
- });
132
- });
@@ -1 +0,0 @@
1
- export {};
@@ -1,67 +0,0 @@
1
- import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
2
- import { configure } from "./config.js";
3
- // Mock WebSocket to never connect (simulates unreachable WS endpoint)
4
- const mockWsInstances = [];
5
- vi.mock("ws", () => {
6
- const MockWebSocket = function () {
7
- this.readyState = 0;
8
- this._listeners = {};
9
- this.on = (event, cb) => { (this._listeners[event] ??= []).push(cb); return this; };
10
- this.send = vi.fn();
11
- this.close = vi.fn(() => {
12
- this.readyState = 3;
13
- for (const cb of (this._listeners["close"] ?? []))
14
- cb();
15
- });
16
- mockWsInstances.push(this);
17
- };
18
- MockWebSocket.OPEN = 1;
19
- return { default: MockWebSocket };
20
- });
21
- beforeEach(() => {
22
- configure({ apiKey: "rt_live_test", baseUrl: "http://localhost:3001", enabled: true });
23
- mockWsInstances.length = 0;
24
- });
25
- afterEach(() => {
26
- vi.unstubAllGlobals();
27
- });
28
- describe("Auto transport fallback on early close()", () => {
29
- it("flushes to HTTP when close() is called before WS connects", async () => {
30
- const mockFetch = vi.fn().mockResolvedValue({ ok: true });
31
- vi.stubGlobal("fetch", mockFetch);
32
- const { createTransport } = await import("./transport.js");
33
- const transport = createTransport("auto");
34
- // Send trace events immediately (before WS could connect)
35
- transport.send("trace_started", { id: "t1", name: "fast-trace", status: "running", started_at: "2026-01-01T00:00:00Z", total_tokens: 0, total_cost: 0, total_duration_ms: 0 });
36
- transport.send("span_started", { id: "s1", trace_id: "t1", span_type: "llm_call", name: "call", started_at: "2026-01-01T00:00:00Z" });
37
- transport.send("span_ended", { id: "s1", ended_at: "2026-01-01T00:00:01Z", output: "response" });
38
- transport.send("trace_ended", { id: "t1", ended_at: "2026-01-01T00:00:01Z", status: "completed" });
39
- // Close immediately — WS has NOT connected yet
40
- transport.close();
41
- // Should have fallen back to HTTP and flushed
42
- expect(mockFetch).toHaveBeenCalledTimes(1);
43
- const [url, opts] = mockFetch.mock.calls[0];
44
- expect(url).toBe("http://localhost:3001/api/v1/traces");
45
- const body = JSON.parse(opts.body);
46
- expect(body.id).toBe("t1");
47
- expect(body.name).toBe("fast-trace");
48
- expect(body.spans).toHaveLength(1);
49
- expect(body.spans[0].output).toBe("response");
50
- });
51
- it("does NOT reconnect after intentional close()", async () => {
52
- vi.stubGlobal("fetch", vi.fn().mockResolvedValue({ ok: true }));
53
- const { WSTransport } = await import("./transport.js");
54
- const ws = new WSTransport();
55
- ws.connect();
56
- // Should have created a WS instance
57
- expect(mockWsInstances.length).toBeGreaterThan(0);
58
- const instanceCount = mockWsInstances.length;
59
- // Close intentionally
60
- ws.close();
61
- // Trigger the "close" event that was registered — already fired by our mock's close()
62
- // Wait a tick for any setTimeout reconnect to fire
63
- await new Promise(r => setTimeout(r, 1100));
64
- // Should NOT have created new WS instances (no reconnect)
65
- expect(mockWsInstances.length).toBe(instanceCount);
66
- });
67
- });
@@ -1,16 +0,0 @@
1
- import { describe, it, expect } from "vitest";
2
- import { configure, getConfig } from "./config.js";
3
-
4
- describe("SDK config", () => {
5
- it("has defaults", () => {
6
- const c = getConfig();
7
- expect(c.baseUrl).toBe("http://localhost:3001");
8
- expect(c.enabled).toBe(true);
9
- });
10
- it("configures custom values", () => {
11
- configure({ apiKey: "rt_live_test", baseUrl: "http://custom:3001" });
12
- const c = getConfig();
13
- expect(c.apiKey).toBe("rt_live_test");
14
- expect(c.baseUrl).toBe("http://custom:3001");
15
- });
16
- });
package/src/config.ts DELETED
@@ -1,31 +0,0 @@
1
- export interface Config {
2
- apiKey: string;
3
- baseUrl: string;
4
- wsUrl: string;
5
- projectId: string | undefined;
6
- enabled: boolean;
7
- }
8
-
9
- const config: Config = {
10
- apiKey: process.env.RETRACE_API_KEY || "",
11
- baseUrl: process.env.RETRACE_BASE_URL || "http://localhost:3001",
12
- wsUrl: "",
13
- projectId: process.env.RETRACE_PROJECT_ID || undefined,
14
- enabled: !["false", "0"].includes((process.env.RETRACE_ENABLED || "true").toLowerCase()),
15
- };
16
- config.wsUrl = config.baseUrl.replace("https://", "wss://").replace("http://", "ws://");
17
-
18
- export function configure(opts: Partial<Config>): Config {
19
- if (opts.apiKey && !opts.apiKey.startsWith("rt_live_")) {
20
- console.warn("[retrace] API key does not start with 'rt_live_'. This may be invalid.");
21
- }
22
- Object.assign(config, opts);
23
- if (opts.baseUrl && !opts.wsUrl) {
24
- config.wsUrl = config.baseUrl.replace("https://", "wss://").replace("http://", "ws://");
25
- }
26
- return config;
27
- }
28
-
29
- export function getConfig(): Config {
30
- return config;
31
- }
package/src/index.ts DELETED
@@ -1,6 +0,0 @@
1
- export { configure, getConfig } from "./config.js";
2
- export { record, trace, TraceRecorder } from "./recorder.js";
3
- export { SpanBuilder, TraceBuilder } from "./trace.js";
4
- export type { SpanData, TraceData } from "./trace.js";
5
- export { SpanType, TraceStatus } from "./trace.js";
6
- export { installGeminiInterceptor, uninstallGeminiInterceptor } from "./interceptors/gemini.js";
@@ -1,86 +0,0 @@
1
- import { SpanData, SpanType } from "../trace.js";
2
- import { genId, nowIso, truncateJson } from "../utils.js";
3
-
4
- const PRICING: Record<string, [number, number]> = {
5
- "gemini-3.1-pro-preview": [2.0, 12.0],
6
- "gemini-2.5-pro": [1.25, 10.0],
7
- "gemini-2.5-flash": [0.15, 0.60],
8
- "gemini-2.0-flash": [0.10, 0.40],
9
- };
10
-
11
- function calcCost(model: string, inputTokens: number, outputTokens: number): number {
12
- const p = PRICING[model] || [0, 0];
13
- return (inputTokens * p[0] + outputTokens * p[1]) / 1_000_000;
14
- }
15
-
16
-
17
- let originalGenerateContent: ((...args: unknown[]) => unknown) | null = null;
18
- let installed = false;
19
- let onSpanCallback: ((span: SpanData) => void) | null = null;
20
-
21
- export function installGeminiInterceptor(onSpan: (span: SpanData) => void) {
22
- if (installed) { onSpanCallback = onSpan; return; }
23
- onSpanCallback = onSpan;
24
-
25
- import("@google/genai").then((genaiMod) => {
26
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
27
- const mod = genaiMod as Record<string, any>;
28
- const modelsProto = mod?.Models?.prototype || mod?.default?.Models?.prototype;
29
- if (!modelsProto?.generateContent) return;
30
-
31
- originalGenerateContent = modelsProto.generateContent;
32
-
33
- modelsProto.generateContent = async function (...args: unknown[]) {
34
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
35
- const opts = (args[0] as Record<string, any>) || {};
36
- const model = (opts.model as string) || "unknown";
37
- const contents = opts.contents;
38
- const spanId = genId();
39
- const startedAt = nowIso();
40
- const startMs = Date.now();
41
-
42
- try {
43
- const result = await originalGenerateContent!.apply(this, args);
44
- const durationMs = Date.now() - startMs;
45
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
46
- const res = result as any;
47
- const inputTokens = res?.usageMetadata?.promptTokenCount || 0;
48
- const outputTokens = res?.usageMetadata?.candidatesTokenCount || 0;
49
-
50
- const span: SpanData = {
51
- id: spanId, trace_id: "", parent_id: null,
52
- span_type: SpanType.LLM_CALL, name: "retrace.ai.generate", model,
53
- input: truncateJson(contents), output: truncateJson(res?.text || ""),
54
- input_tokens: inputTokens, output_tokens: outputTokens,
55
- cost: calcCost(model, inputTokens, outputTokens),
56
- duration_ms: durationMs, started_at: startedAt, ended_at: nowIso(),
57
- };
58
- onSpanCallback?.(span);
59
- return result;
60
- } catch (err) {
61
- const span: SpanData = {
62
- id: spanId, trace_id: "", parent_id: null,
63
- span_type: SpanType.LLM_CALL, name: "retrace.ai.generate", model,
64
- input: truncateJson(contents), started_at: startedAt, ended_at: nowIso(),
65
- duration_ms: Date.now() - startMs,
66
- error: err instanceof Error ? err.message : String(err),
67
- };
68
- onSpanCallback?.(span);
69
- throw err;
70
- }
71
- };
72
- installed = true;
73
- }).catch(() => { /* @google/genai not installed — skip */ });
74
- }
75
-
76
- export function uninstallGeminiInterceptor() {
77
- if (!installed || !originalGenerateContent) return;
78
- import("@google/genai").then((genaiMod) => {
79
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
80
- const mod = genaiMod as Record<string, any>;
81
- const modelsProto = mod?.Models?.prototype || mod?.default?.Models?.prototype;
82
- if (modelsProto) modelsProto.generateContent = originalGenerateContent;
83
- }).catch(() => {});
84
- installed = false;
85
- onSpanCallback = null;
86
- }
@@ -1 +0,0 @@
1
- export { installGeminiInterceptor, uninstallGeminiInterceptor } from "./gemini.js";
package/src/recorder.ts DELETED
@@ -1,136 +0,0 @@
1
- import { getConfig } from "./config.js";
2
- import { SpanBuilder, SpanData, SpanType, TraceBuilder, TraceStatus } from "./trace.js";
3
- import { createTransport, Transport } from "./transport.js";
4
- import { installGeminiInterceptor } from "./interceptors/gemini.js";
5
-
6
- export interface RecordOptions {
7
- name?: string;
8
- input?: unknown;
9
- metadata?: Record<string, unknown>;
10
- }
11
-
12
- export class TraceRecorder {
13
- private builder: TraceBuilder;
14
- private transport: Transport;
15
- private interceptorsInstalled = false;
16
- output: unknown = undefined;
17
-
18
- constructor(opts?: RecordOptions) {
19
- this.builder = new TraceBuilder();
20
- this.transport = createTransport();
21
- const cfg = getConfig();
22
- if (cfg.projectId) this.builder.setProjectId(cfg.projectId);
23
- if (opts?.metadata) this.builder.setMetadata(opts.metadata);
24
- if (opts?.name || opts?.input) {
25
- this.builder.start(opts.name, opts.input);
26
- }
27
- }
28
-
29
- get traceId() { return this.builder.id; }
30
-
31
- start(name?: string, input?: unknown): this {
32
- this.builder.start(name, input);
33
- this.installInterceptors();
34
- this.transport.send("trace_started", this.builder.toDict() as unknown as Record<string, unknown>);
35
- return this;
36
- }
37
-
38
- end(output?: unknown, status: TraceStatus = TraceStatus.COMPLETED) {
39
- if (output !== undefined) this.output = output;
40
- const data = this.builder.end(this.output, status);
41
- this.transport.send("trace_ended", {
42
- id: data.id,
43
- ended_at: data.ended_at!,
44
- output: data.output,
45
- status: data.status,
46
- total_tokens: data.total_tokens,
47
- total_cost: data.total_cost,
48
- });
49
- this.transport.close();
50
- }
51
-
52
- addSpan(span: SpanData) {
53
- span.trace_id = this.builder.id;
54
- this.builder.addSpan(span);
55
- this.transport.send("span_started", span as unknown as Record<string, unknown>);
56
- if (span.ended_at) {
57
- this.transport.send("span_ended", {
58
- id: span.id,
59
- ended_at: span.ended_at,
60
- output: span.output,
61
- output_tokens: span.output_tokens,
62
- cost: span.cost,
63
- error: span.error,
64
- });
65
- }
66
- }
67
-
68
- startSpan(name: string, spanType: SpanType = SpanType.LLM_CALL, input?: unknown, model?: string, parentId?: string): SpanBuilder {
69
- const sb = new SpanBuilder(name, spanType).start();
70
- sb.setTraceId(this.builder.id);
71
- if (input !== undefined) sb.setInput(input);
72
- if (model) sb.setModel(model);
73
- if (parentId) sb.setParentId(parentId);
74
- this.transport.send("span_started", sb.toData() as unknown as Record<string, unknown>);
75
- return sb;
76
- }
77
-
78
- endSpan(spanBuilder: SpanBuilder, output?: unknown, error?: string) {
79
- const span = spanBuilder.end(output, error);
80
- span.trace_id = this.builder.id;
81
- this.builder.addSpan(span);
82
- this.transport.send("span_ended", {
83
- id: span.id,
84
- ended_at: span.ended_at,
85
- output: span.output,
86
- output_tokens: span.output_tokens,
87
- cost: span.cost,
88
- error: span.error,
89
- });
90
- }
91
-
92
- private installInterceptors() {
93
- if (this.interceptorsInstalled) return;
94
- installGeminiInterceptor((span) => this.addSpan(span));
95
- this.interceptorsInstalled = true;
96
- }
97
- }
98
-
99
- export function record(opts?: RecordOptions): TraceRecorder {
100
- const cfg = getConfig();
101
- if (!cfg.enabled) {
102
- // Return a no-op recorder
103
- return new TraceRecorder(opts);
104
- }
105
- return new TraceRecorder(opts);
106
- }
107
-
108
- export function trace<T>(fn: (...args: unknown[]) => T, opts?: RecordOptions): (...args: unknown[]) => T {
109
- const cfg = getConfig();
110
- return (...args: unknown[]): T => {
111
- if (!cfg.enabled) return fn(...args);
112
-
113
- const recorder = new TraceRecorder({
114
- name: opts?.name || fn.name || "anonymous",
115
- input: opts?.input ?? args,
116
- metadata: opts?.metadata,
117
- });
118
- recorder.start(opts?.name || fn.name || "anonymous", opts?.input ?? args);
119
-
120
- try {
121
- const result = fn(...args);
122
- // Handle async functions
123
- if (result && typeof (result as { then?: unknown }).then === "function") {
124
- return (result as unknown as Promise<unknown>).then(
125
- (resolved) => { recorder.end(resolved, TraceStatus.COMPLETED); return resolved; },
126
- (err) => { recorder.end(undefined, TraceStatus.FAILED); throw err; }
127
- ) as unknown as T;
128
- }
129
- recorder.end(result, TraceStatus.COMPLETED);
130
- return result;
131
- } catch (err) {
132
- recorder.end(undefined, TraceStatus.FAILED);
133
- throw err;
134
- }
135
- };
136
- }
package/src/sdk.test.ts DELETED
@@ -1,152 +0,0 @@
1
- import { describe, it, expect, vi, beforeEach } from "vitest";
2
- import { configure, getConfig } from "./config.js";
3
-
4
- // Reset config between tests
5
- beforeEach(() => {
6
- configure({ apiKey: "", baseUrl: "http://localhost:3001", enabled: true, wsUrl: "" });
7
- });
8
-
9
- describe("Config", () => {
10
- it("has sensible defaults", () => {
11
- const c = getConfig();
12
- expect(c.baseUrl).toBe("http://localhost:3001");
13
- expect(c.enabled).toBe(true);
14
- });
15
-
16
- it("configures custom values", () => {
17
- configure({ apiKey: "rt_live_test", baseUrl: "https://api.example.com" });
18
- const c = getConfig();
19
- expect(c.apiKey).toBe("rt_live_test");
20
- expect(c.baseUrl).toBe("https://api.example.com");
21
- expect(c.wsUrl).toBe("wss://api.example.com");
22
- });
23
-
24
- it("auto-derives wsUrl from baseUrl", () => {
25
- configure({ baseUrl: "https://custom.io" });
26
- expect(getConfig().wsUrl).toBe("wss://custom.io");
27
- configure({ baseUrl: "http://localhost:3001" });
28
- expect(getConfig().wsUrl).toBe("ws://localhost:3001");
29
- });
30
-
31
- it("warns on invalid API key prefix", () => {
32
- const spy = vi.spyOn(console, "warn").mockImplementation(() => {});
33
- configure({ apiKey: "invalid_key" });
34
- expect(spy).toHaveBeenCalledWith(expect.stringContaining("rt_live_"));
35
- spy.mockRestore();
36
- });
37
-
38
- it("does not warn on valid API key", () => {
39
- const spy = vi.spyOn(console, "warn").mockImplementation(() => {});
40
- configure({ apiKey: "rt_live_valid123" });
41
- expect(spy).not.toHaveBeenCalled();
42
- spy.mockRestore();
43
- });
44
- });
45
-
46
- describe("Trace model", () => {
47
- it("SpanBuilder creates valid span data", async () => {
48
- const { SpanBuilder, SpanType } = await import("./trace.js");
49
- const sb = new SpanBuilder("test-span", SpanType.LLM_CALL).start();
50
- sb.setModel("gpt-4o");
51
- sb.setInput({ prompt: "hi" });
52
- const data = sb.end("hello");
53
- expect(data.name).toBe("test-span");
54
- expect(data.span_type).toBe("llm_call");
55
- expect(data.model).toBe("gpt-4o");
56
- expect(data.output).toBe("hello");
57
- expect(data.id).toHaveLength(36);
58
- expect(data.started_at).toBeDefined();
59
- expect(data.ended_at).toBeDefined();
60
- });
61
-
62
- it("TraceBuilder creates valid trace data", async () => {
63
- const { TraceBuilder, TraceStatus } = await import("./trace.js");
64
- const tb = new TraceBuilder();
65
- tb.start("my-trace", { prompt: "test" });
66
- const data = tb.end("result", TraceStatus.COMPLETED);
67
- expect(data.name).toBe("my-trace");
68
- expect(data.status).toBe("completed");
69
- expect(data.output).toBe("result");
70
- expect(data.id).toHaveLength(36);
71
- });
72
-
73
- it("SpanType enum values", async () => {
74
- const { SpanType } = await import("./trace.js");
75
- expect(SpanType.LLM_CALL).toBe("llm_call");
76
- expect(SpanType.TOOL_CALL).toBe("tool_call");
77
- expect(SpanType.ERROR).toBe("error");
78
- expect(SpanType.FORK_POINT).toBe("fork_point");
79
- });
80
- });
81
-
82
- describe("Recorder", () => {
83
- it("trace() wraps sync function", async () => {
84
- configure({ apiKey: "rt_live_t", baseUrl: "http://x:1", enabled: true });
85
- const { trace } = await import("./recorder.js");
86
- const fn = trace((x: unknown) => `result:${x}`, { name: "sync-fn" });
87
- expect(fn("hi")).toBe("result:hi");
88
- });
89
-
90
- it("trace() wraps async function", async () => {
91
- configure({ apiKey: "rt_live_t", baseUrl: "http://x:1", enabled: true });
92
- const { trace } = await import("./recorder.js");
93
- const fn = trace(async (x: unknown) => `async:${x}`, { name: "async-fn" });
94
- const result = await fn("hi");
95
- expect(result).toBe("async:hi");
96
- });
97
-
98
- it("trace() propagates exceptions", async () => {
99
- configure({ apiKey: "rt_live_t", baseUrl: "http://x:1", enabled: true });
100
- const { trace } = await import("./recorder.js");
101
- const fn = trace(() => { throw new Error("boom"); }, { name: "err-fn" });
102
- expect(() => fn()).toThrow("boom");
103
- });
104
-
105
- it("disabled SDK is no-op", async () => {
106
- configure({ apiKey: "rt_live_t", enabled: false });
107
- const { trace } = await import("./recorder.js");
108
- const fn = trace((x: unknown) => `r:${x}`, { name: "off" });
109
- expect(fn("hi")).toBe("r:hi");
110
- });
111
- });
112
-
113
- describe("Transport", () => {
114
- it("HTTPTransport accumulates and flushes", async () => {
115
- configure({ apiKey: "rt_live_t", baseUrl: "http://x:1" });
116
- const { HTTPTransport } = await import("./transport.js");
117
- const http = new HTTPTransport();
118
-
119
- const mockFetch = vi.fn().mockResolvedValue({ ok: true });
120
- vi.stubGlobal("fetch", mockFetch);
121
-
122
- http.send("trace_started", { id: "abc", name: "t", status: "running", started_at: "2026-01-01T00:00:00Z", total_tokens: 0, total_cost: 0, total_duration_ms: 0 });
123
- http.send("span_started", { id: "s1", trace_id: "abc", span_type: "llm_call", name: "s", started_at: "2026-01-01T00:00:00Z" });
124
- http.send("span_ended", { id: "s1", ended_at: "2026-01-01T00:00:01Z", output: "hi" });
125
- http.send("trace_ended", { id: "abc", ended_at: "2026-01-01T00:00:02Z", status: "completed" });
126
-
127
- expect(mockFetch).toHaveBeenCalled();
128
- const body = JSON.parse(mockFetch.mock.calls[0][1].body);
129
- expect(body.id).toBe("abc");
130
- expect(body.spans).toHaveLength(1);
131
- expect(body.spans[0].output).toBe("hi");
132
-
133
- vi.unstubAllGlobals();
134
- });
135
-
136
- it("createTransport returns correct type", async () => {
137
- const { createTransport, HTTPTransport } = await import("./transport.js");
138
- expect(createTransport("http")).toBeInstanceOf(HTTPTransport);
139
- });
140
- });
141
-
142
- describe("README examples", () => {
143
- it("TypeScript README example works", async () => {
144
- configure({ apiKey: "rt_live_test", enabled: false });
145
- const { trace } = await import("./recorder.js");
146
- const runAgent = trace(async (prompt: unknown) => {
147
- return `Response to: ${prompt}`;
148
- }, { name: "my-agent" });
149
- const result = await runAgent("What is quantum computing?");
150
- expect(result).toContain("quantum");
151
- });
152
- });