raindrop-ai 1.1.1-otelv2 → 2.0.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/chunk-BU322D7Q.mjs +1953 -0
- package/dist/{chunk-7HPYMPNJ.mjs → chunk-CSH7U5JZ.mjs} +72 -4140
- package/dist/chunk-F5TJSGNA.mjs +4204 -0
- package/dist/{chunk-6575YF3B.mjs → chunk-PYMV6B3M.mjs} +4326 -1246
- package/dist/evals/cli.js +25704 -25358
- package/dist/evals/cli.mjs +13 -13
- package/dist/{index-mM4Ls3Kv.d.ts → index-BJJ273dz.d.mts} +8434 -4087
- package/dist/{index-mM4Ls3Kv.d.mts → index-BJJ273dz.d.ts} +8434 -4087
- package/dist/index.d.mts +2 -1
- package/dist/index.d.ts +2 -1
- package/dist/index.js +26461 -26184
- package/dist/index.mjs +24 -21
- package/dist/{portable-runtime-M4PGODCX.mjs → portable-runtime-G27RYK6P.mjs} +7 -11
- package/dist/tracing/index.d.mts +2 -1
- package/dist/tracing/index.d.ts +2 -1
- package/dist/tracing/index.js +1 -1
- package/dist/tracing/index.mjs +2 -1
- package/package.json +20 -20
- package/dist/chunk-HEJQOFNN.mjs +0 -4799
|
@@ -0,0 +1,1953 @@
|
|
|
1
|
+
import {
|
|
2
|
+
runWithTracingSuppressed
|
|
3
|
+
} from "./chunk-CSH7U5JZ.mjs";
|
|
4
|
+
|
|
5
|
+
// src/evals/generated/trace.ts
|
|
6
|
+
import z from "zod/v4";
|
|
7
|
+
function isPlainJsonObject(value) {
|
|
8
|
+
if (typeof value !== "object" || value === null) return false;
|
|
9
|
+
const prototype = Object.getPrototypeOf(value);
|
|
10
|
+
return prototype === null || Object.getPrototypeOf(prototype) === null;
|
|
11
|
+
}
|
|
12
|
+
function stringRecord(value) {
|
|
13
|
+
return z.custom(isPlainJsonObject, { message: "Expected a plain object" }).transform((record) => Object.hasOwn(record, "__proto__") ? Object.fromEntries(Object.entries(record).filter(([key]) => key !== "__proto__")) : record).pipe(z.object({}).catchall(value));
|
|
14
|
+
}
|
|
15
|
+
function jsonTreeKind(value, ancestors) {
|
|
16
|
+
switch (typeof value) {
|
|
17
|
+
case "string":
|
|
18
|
+
case "boolean":
|
|
19
|
+
return "plain";
|
|
20
|
+
case "number":
|
|
21
|
+
return Number.isNaN(value) ? "other" : "plain";
|
|
22
|
+
case "object":
|
|
23
|
+
break;
|
|
24
|
+
default:
|
|
25
|
+
return "other";
|
|
26
|
+
}
|
|
27
|
+
if (value === null)
|
|
28
|
+
return "plain";
|
|
29
|
+
if (ancestors.has(value))
|
|
30
|
+
return "cycle";
|
|
31
|
+
const prototype = Object.getPrototypeOf(value);
|
|
32
|
+
const plain = Array.isArray(value) ? prototype === Array.prototype && Object.keys(value).length === value.length : (prototype === Object.prototype || prototype === null) && !Object.hasOwn(value, "__proto__");
|
|
33
|
+
const children = Array.isArray(value) ? value : isRecordInput(value) ? recordEntries(value).map(([, entry]) => entry) : [];
|
|
34
|
+
ancestors.add(value);
|
|
35
|
+
let kind = plain ? "plain" : "other";
|
|
36
|
+
for (const child of children) {
|
|
37
|
+
const childKind = jsonTreeKind(child, ancestors);
|
|
38
|
+
if (childKind === "cycle") {
|
|
39
|
+
kind = "cycle";
|
|
40
|
+
break;
|
|
41
|
+
}
|
|
42
|
+
if (childKind === "other")
|
|
43
|
+
kind = "other";
|
|
44
|
+
}
|
|
45
|
+
ancestors.delete(value);
|
|
46
|
+
return kind;
|
|
47
|
+
}
|
|
48
|
+
function isRecordInput(value) {
|
|
49
|
+
return value !== null && typeof value === "object" && !Array.isArray(value) && !(value instanceof Date) && !(value instanceof Map) && !(value instanceof Set) && !("then" in value && typeof value.then === "function" && "catch" in value && typeof value.catch === "function");
|
|
50
|
+
}
|
|
51
|
+
function recordEntries(value) {
|
|
52
|
+
const entries = [];
|
|
53
|
+
for (const key in value)
|
|
54
|
+
entries.push([key, value[key]]);
|
|
55
|
+
return entries;
|
|
56
|
+
}
|
|
57
|
+
function jsonRecordInput(value) {
|
|
58
|
+
return isRecordInput(value) ? Object.fromEntries(recordEntries(value)) : value;
|
|
59
|
+
}
|
|
60
|
+
var RecursiveJsonValueSchema = z.lazy(() => z.union([
|
|
61
|
+
z.string(),
|
|
62
|
+
z.number(),
|
|
63
|
+
z.boolean(),
|
|
64
|
+
z.null(),
|
|
65
|
+
z.array(RecursiveJsonValueSchema),
|
|
66
|
+
z.preprocess(jsonRecordInput, stringRecord(RecursiveJsonValueSchema))
|
|
67
|
+
]));
|
|
68
|
+
var JsonValueSchema = z.preprocess((value, context) => {
|
|
69
|
+
if (jsonTreeKind(value, /* @__PURE__ */ new Set()) === "cycle") {
|
|
70
|
+
context.addIssue({ code: "custom", message: "JSON values cannot contain cycles" });
|
|
71
|
+
return z.NEVER;
|
|
72
|
+
}
|
|
73
|
+
return value;
|
|
74
|
+
}, RecursiveJsonValueSchema).nonoptional();
|
|
75
|
+
var stringToJSONSchema = z.string().transform((str, ctx) => {
|
|
76
|
+
try {
|
|
77
|
+
return JSON.parse(str);
|
|
78
|
+
} catch (e) {
|
|
79
|
+
ctx.addIssue({ code: "custom", message: "Invalid JSON" });
|
|
80
|
+
return z.NEVER;
|
|
81
|
+
}
|
|
82
|
+
});
|
|
83
|
+
var SignalPropertiesSchema = z.union([stringToJSONSchema, stringRecord(z.unknown())]);
|
|
84
|
+
var AIEventMetadataSchema = z.object({
|
|
85
|
+
input: z.string().optional().nullable(),
|
|
86
|
+
output: z.string().optional().nullable(),
|
|
87
|
+
model: z.string().optional().nullable(),
|
|
88
|
+
convoId: z.string().optional().nullable()
|
|
89
|
+
});
|
|
90
|
+
var AnalyticsEventSchema = z.object({
|
|
91
|
+
name: z.string(),
|
|
92
|
+
timestamp: z.string(),
|
|
93
|
+
receivedAt: z.string(),
|
|
94
|
+
id: z.string(),
|
|
95
|
+
properties: stringRecord(z.unknown()).nullable(),
|
|
96
|
+
userId: z.string(),
|
|
97
|
+
isPending: z.boolean().optional()
|
|
98
|
+
});
|
|
99
|
+
var LensInfoSchema = z.object({
|
|
100
|
+
lensId: z.coerce.number(),
|
|
101
|
+
sourceId: z.string(),
|
|
102
|
+
source: z.string().optional(),
|
|
103
|
+
categoryId: z.coerce.number()
|
|
104
|
+
});
|
|
105
|
+
var AttachmentSchema = z.object({
|
|
106
|
+
attachment_id: z.string(),
|
|
107
|
+
attachment_type: z.enum(["text", "image", "iframe"]).prefault("text"),
|
|
108
|
+
value: z.string(),
|
|
109
|
+
name: z.string().prefault("")
|
|
110
|
+
});
|
|
111
|
+
var SignalSchema = z.object({
|
|
112
|
+
id: z.string().optional(),
|
|
113
|
+
name: z.string(),
|
|
114
|
+
timestamp: z.string(),
|
|
115
|
+
attachmentId: z.string().optional(),
|
|
116
|
+
properties: SignalPropertiesSchema,
|
|
117
|
+
signalType: z.string().optional(),
|
|
118
|
+
score: z.number().optional()
|
|
119
|
+
});
|
|
120
|
+
var RichTextContentSchema = z.object({
|
|
121
|
+
type: z.literal("text"),
|
|
122
|
+
text: z.string(),
|
|
123
|
+
annotations: z.array(z.object({
|
|
124
|
+
type: z.enum(["url", "file", "event", "user", "signal"]),
|
|
125
|
+
text: z.string().optional(),
|
|
126
|
+
id: z.string().optional(),
|
|
127
|
+
url: z.string().optional(),
|
|
128
|
+
startIndex: z.number().int().optional(),
|
|
129
|
+
endIndex: z.number().int().optional()
|
|
130
|
+
})).optional()
|
|
131
|
+
});
|
|
132
|
+
var RichJsonContentSchema = z.object({
|
|
133
|
+
type: z.literal("json"),
|
|
134
|
+
value: z.unknown().optional(),
|
|
135
|
+
raw: z.string().nullable()
|
|
136
|
+
});
|
|
137
|
+
var RichMediaContentSchema = z.object({
|
|
138
|
+
type: z.enum(["image", "file"]),
|
|
139
|
+
mimeType: z.string().optional(),
|
|
140
|
+
url: z.string().optional(),
|
|
141
|
+
fileId: z.string().optional(),
|
|
142
|
+
name: z.string().optional()
|
|
143
|
+
});
|
|
144
|
+
var RichReferenceContentSchema = z.object({
|
|
145
|
+
type: z.literal("reference"),
|
|
146
|
+
label: z.string(),
|
|
147
|
+
refType: z.enum(["stored_tool_result", "external"]),
|
|
148
|
+
href: z.string().optional(),
|
|
149
|
+
metadata: stringRecord(z.unknown()).optional()
|
|
150
|
+
});
|
|
151
|
+
var RichContentSchema = z.union([
|
|
152
|
+
RichTextContentSchema,
|
|
153
|
+
RichJsonContentSchema,
|
|
154
|
+
RichMediaContentSchema,
|
|
155
|
+
RichReferenceContentSchema
|
|
156
|
+
]);
|
|
157
|
+
var RichPayloadValueSchema = z.object({
|
|
158
|
+
kind: z.enum(["empty", "text", "json", "reference"]),
|
|
159
|
+
raw: z.string().nullable(),
|
|
160
|
+
truncated: z.boolean(),
|
|
161
|
+
sizeChars: z.number().int().nullable()
|
|
162
|
+
});
|
|
163
|
+
var RichEntrySourceSchema = z.object({
|
|
164
|
+
adapter: z.string(),
|
|
165
|
+
confidence: z.enum(["high", "medium", "low"]),
|
|
166
|
+
spanIds: z.array(z.string()),
|
|
167
|
+
parentSpanIds: z.array(z.string()),
|
|
168
|
+
attributeKeys: z.array(z.string())
|
|
169
|
+
});
|
|
170
|
+
var RichInteractionEntryBaseSchema = z.object({
|
|
171
|
+
id: z.string(),
|
|
172
|
+
order: z.number().int(),
|
|
173
|
+
startMs: z.number().int().nullable(),
|
|
174
|
+
endMs: z.number().int().nullable(),
|
|
175
|
+
source: RichEntrySourceSchema,
|
|
176
|
+
model: z.string().nullable().optional(),
|
|
177
|
+
provider: z.string().nullable().optional()
|
|
178
|
+
});
|
|
179
|
+
var RichSystemEntrySchema = RichInteractionEntryBaseSchema.extend({
|
|
180
|
+
type: z.literal("system"),
|
|
181
|
+
role: z.enum(["system", "developer"]),
|
|
182
|
+
content: RichTextContentSchema,
|
|
183
|
+
collapsed: z.literal(true),
|
|
184
|
+
tokenEstimate: z.number().int().nullable()
|
|
185
|
+
});
|
|
186
|
+
var RichUserMessageEntrySchema = RichInteractionEntryBaseSchema.extend({
|
|
187
|
+
type: z.literal("user_message"),
|
|
188
|
+
role: z.literal("user"),
|
|
189
|
+
content: z.array(RichContentSchema),
|
|
190
|
+
turnInput: z.literal(true).optional()
|
|
191
|
+
});
|
|
192
|
+
var RichAssistantTextEntrySchema = RichInteractionEntryBaseSchema.extend({
|
|
193
|
+
type: z.literal("assistant_text"),
|
|
194
|
+
role: z.literal("assistant"),
|
|
195
|
+
content: z.array(RichContentSchema),
|
|
196
|
+
format: z.enum(["markdown", "text"]),
|
|
197
|
+
final: z.boolean()
|
|
198
|
+
});
|
|
199
|
+
var RichReasoningEntrySchema = RichInteractionEntryBaseSchema.extend({
|
|
200
|
+
type: z.literal("reasoning"),
|
|
201
|
+
content: RichTextContentSchema,
|
|
202
|
+
format: z.literal("text"),
|
|
203
|
+
visibility: z.enum(["collapsed", "expanded"]),
|
|
204
|
+
capturedAs: z.enum(["provider_reasoning", "reasoning_summary", "thinking", "unknown"])
|
|
205
|
+
});
|
|
206
|
+
var RichToolCallEntrySchema = RichInteractionEntryBaseSchema.extend({
|
|
207
|
+
type: z.literal("tool_call"),
|
|
208
|
+
callId: z.string().nullable(),
|
|
209
|
+
name: z.string(),
|
|
210
|
+
status: z.enum(["pending", "completed", "error", "unknown"]),
|
|
211
|
+
durationMs: z.number().int().nullable(),
|
|
212
|
+
input: RichPayloadValueSchema,
|
|
213
|
+
output: RichPayloadValueSchema.nullable(),
|
|
214
|
+
error: RichPayloadValueSchema.nullable()
|
|
215
|
+
});
|
|
216
|
+
var RichUnknownSpanEntrySchema = RichInteractionEntryBaseSchema.extend({
|
|
217
|
+
type: z.literal("unknown_span"),
|
|
218
|
+
spanType: z.string().nullable(),
|
|
219
|
+
name: z.string(),
|
|
220
|
+
hiddenByDefault: z.literal(true)
|
|
221
|
+
});
|
|
222
|
+
var RichSubAgentEntrySchema = RichInteractionEntryBaseSchema.extend({
|
|
223
|
+
type: z.literal("sub_agent"),
|
|
224
|
+
rootSpanId: z.string(),
|
|
225
|
+
name: z.string(),
|
|
226
|
+
spanIds: z.array(z.string()),
|
|
227
|
+
toolCount: z.number().int(),
|
|
228
|
+
llmCount: z.number().int(),
|
|
229
|
+
durationMs: z.number().int().nullable(),
|
|
230
|
+
inputPreview: z.string().nullable(),
|
|
231
|
+
outputPreview: z.string().nullable(),
|
|
232
|
+
status: z.enum(["ok", "error", "unknown"]),
|
|
233
|
+
model: z.string().nullable(),
|
|
234
|
+
totalInputTokens: z.number().int().nullable(),
|
|
235
|
+
totalOutputTokens: z.number().int().nullable()
|
|
236
|
+
});
|
|
237
|
+
var RichDetachedSubAgentEntrySchema = RichInteractionEntryBaseSchema.extend({
|
|
238
|
+
type: z.literal("detached_sub_agent"),
|
|
239
|
+
rootSpanId: z.string(),
|
|
240
|
+
name: z.string(),
|
|
241
|
+
durationMs: z.number().int().nullable(),
|
|
242
|
+
inputPreview: z.string().nullable(),
|
|
243
|
+
outputPreview: z.string().nullable(),
|
|
244
|
+
status: z.enum(["ok", "error", "unknown"]),
|
|
245
|
+
childEventId: z.string()
|
|
246
|
+
});
|
|
247
|
+
var RichLlmCallEntrySchema = RichInteractionEntryBaseSchema.extend({
|
|
248
|
+
type: z.literal("llm_call"),
|
|
249
|
+
name: z.string(),
|
|
250
|
+
contentAvailable: z.literal(false)
|
|
251
|
+
});
|
|
252
|
+
var RichAgentHandoffEntrySchema = RichInteractionEntryBaseSchema.extend({
|
|
253
|
+
type: z.literal("agent_handoff"),
|
|
254
|
+
fromAgent: z.string(),
|
|
255
|
+
toAgent: z.string(),
|
|
256
|
+
reason: z.string().nullable()
|
|
257
|
+
});
|
|
258
|
+
var RichInteractionEntrySchema = z.discriminatedUnion("type", [
|
|
259
|
+
RichSystemEntrySchema,
|
|
260
|
+
RichUserMessageEntrySchema,
|
|
261
|
+
RichAssistantTextEntrySchema,
|
|
262
|
+
RichReasoningEntrySchema,
|
|
263
|
+
RichToolCallEntrySchema,
|
|
264
|
+
RichSubAgentEntrySchema,
|
|
265
|
+
RichDetachedSubAgentEntrySchema,
|
|
266
|
+
RichAgentHandoffEntrySchema,
|
|
267
|
+
RichLlmCallEntrySchema,
|
|
268
|
+
RichUnknownSpanEntrySchema
|
|
269
|
+
]);
|
|
270
|
+
var RichSpanSummarySchema = z.object({
|
|
271
|
+
spanId: z.string(),
|
|
272
|
+
parentSpanId: z.string().nullable(),
|
|
273
|
+
traceId: z.string(),
|
|
274
|
+
name: z.string(),
|
|
275
|
+
spanType: z.string().nullable(),
|
|
276
|
+
status: z.string().nullable(),
|
|
277
|
+
startMs: z.number().int().nullable(),
|
|
278
|
+
endMs: z.number().int().nullable(),
|
|
279
|
+
durationMs: z.number().int().nullable(),
|
|
280
|
+
model: z.string().nullable(),
|
|
281
|
+
provider: z.string().nullable(),
|
|
282
|
+
rendered: z.boolean()
|
|
283
|
+
});
|
|
284
|
+
var RichDiagnosticWarningSchema = z.object({
|
|
285
|
+
code: z.enum([
|
|
286
|
+
"no_spans",
|
|
287
|
+
"missing_llm_input",
|
|
288
|
+
"missing_llm_output",
|
|
289
|
+
"duplicate_output_suppressed",
|
|
290
|
+
"tool_call_unmatched",
|
|
291
|
+
"payload_truncated",
|
|
292
|
+
"trace_too_large",
|
|
293
|
+
"unknown_span_shape"
|
|
294
|
+
]),
|
|
295
|
+
message: z.string(),
|
|
296
|
+
spanIds: z.array(z.string()).optional()
|
|
297
|
+
});
|
|
298
|
+
var RichInteractionStatsSchema = z.object({
|
|
299
|
+
agentCount: z.number().int(),
|
|
300
|
+
llmCallCount: z.number().int(),
|
|
301
|
+
toolCallCount: z.number().int(),
|
|
302
|
+
errorCount: z.number().int(),
|
|
303
|
+
agentNames: z.array(z.string())
|
|
304
|
+
});
|
|
305
|
+
var RichEventInteractionSchema = z.object({
|
|
306
|
+
schemaVersion: z.literal("2026-05-20"),
|
|
307
|
+
eventId: z.string(),
|
|
308
|
+
traceIds: z.array(z.string()),
|
|
309
|
+
rootSpanIds: z.array(z.string()),
|
|
310
|
+
status: z.enum(["complete", "partial", "missing_spans"]),
|
|
311
|
+
startedAt: z.string().nullable(),
|
|
312
|
+
endedAt: z.string().nullable(),
|
|
313
|
+
durationMs: z.number().int().nullable(),
|
|
314
|
+
stats: RichInteractionStatsSchema,
|
|
315
|
+
entries: z.array(RichInteractionEntrySchema),
|
|
316
|
+
spans: z.array(RichSpanSummarySchema),
|
|
317
|
+
diagnostics: z.object({
|
|
318
|
+
extractionVersion: z.literal("rich-interaction/1"),
|
|
319
|
+
warnings: z.array(RichDiagnosticWarningSchema),
|
|
320
|
+
unrenderedSpanCount: z.number().int()
|
|
321
|
+
})
|
|
322
|
+
});
|
|
323
|
+
var CoreEventSchema = z.object({
|
|
324
|
+
id: z.string(),
|
|
325
|
+
_raindropDatabaseId: z.string(),
|
|
326
|
+
projectId: z.string().optional(),
|
|
327
|
+
name: z.string(),
|
|
328
|
+
timestamp: z.string(),
|
|
329
|
+
receivedAt: z.string(),
|
|
330
|
+
userId: z.string(),
|
|
331
|
+
aiData: AIEventMetadataSchema,
|
|
332
|
+
properties: stringRecord(z.unknown()).nullable()
|
|
333
|
+
});
|
|
334
|
+
var AIAnalyticsEventSchema = CoreEventSchema.extend({
|
|
335
|
+
customEventId: z.string().optional().nullable(),
|
|
336
|
+
occurrencesInWindow: z.number().optional(),
|
|
337
|
+
lensInfo: z.array(LensInfoSchema).optional(),
|
|
338
|
+
topics: z.array(z.string()).optional(),
|
|
339
|
+
categories: z.array(z.tuple([z.string(), z.string().nullable(), z.coerce.number().nullable()])).optional(),
|
|
340
|
+
categoryLog: z.array(z.object({
|
|
341
|
+
lensId: z.coerce.number(),
|
|
342
|
+
categoryId: z.coerce.string(),
|
|
343
|
+
action: z.enum(["add_category", "remove_category", "skip_category"])
|
|
344
|
+
})).optional(),
|
|
345
|
+
inputAttachments: z.array(z.union([z.string(), AttachmentSchema])).optional().transform((attachments) => (attachments == null ? void 0 : attachments.map((attachment) => {
|
|
346
|
+
if (typeof attachment === "string") {
|
|
347
|
+
try {
|
|
348
|
+
return AttachmentSchema.parse(JSON.parse(attachment));
|
|
349
|
+
} catch (e) {
|
|
350
|
+
return null;
|
|
351
|
+
}
|
|
352
|
+
}
|
|
353
|
+
return attachment;
|
|
354
|
+
}).filter((a) => a !== null)) || []),
|
|
355
|
+
outputAttachments: z.array(z.union([z.string(), AttachmentSchema])).optional().transform((attachments) => (attachments == null ? void 0 : attachments.map((attachment) => {
|
|
356
|
+
if (typeof attachment === "string") {
|
|
357
|
+
try {
|
|
358
|
+
return AttachmentSchema.parse(JSON.parse(attachment));
|
|
359
|
+
} catch (e) {
|
|
360
|
+
return null;
|
|
361
|
+
}
|
|
362
|
+
}
|
|
363
|
+
return attachment;
|
|
364
|
+
}).filter((a) => a !== null)) || []),
|
|
365
|
+
signals: z.array(SignalSchema).optional(),
|
|
366
|
+
errorSpans: z.array(z.object({
|
|
367
|
+
span_id: z.string().optional(),
|
|
368
|
+
started_at: z.string().optional(),
|
|
369
|
+
status: z.string().optional(),
|
|
370
|
+
duration_ms: z.coerce.number().optional(),
|
|
371
|
+
span_type: z.string().optional(),
|
|
372
|
+
span_name: z.string().optional(),
|
|
373
|
+
output_payload: z.any().optional(),
|
|
374
|
+
error_message: z.string().optional()
|
|
375
|
+
})).optional(),
|
|
376
|
+
regexSignals: z.array(z.string()).optional(),
|
|
377
|
+
toolCalls: z.array(z.any()).optional(),
|
|
378
|
+
toolCallNames: z.array(z.string()).optional(),
|
|
379
|
+
richInteraction: RichEventInteractionSchema.optional().nullable(),
|
|
380
|
+
_ai_output_words: z.number().optional(),
|
|
381
|
+
_ai_input_words: z.number().optional(),
|
|
382
|
+
userTraits: stringRecord(z.unknown()).optional().nullable(),
|
|
383
|
+
featureFlags: stringRecord(z.string()).optional().nullable(),
|
|
384
|
+
userCreatedAt: z.string().optional().nullable(),
|
|
385
|
+
userPlan: z.string().optional().nullable(),
|
|
386
|
+
userLastPlan: z.string().optional().nullable(),
|
|
387
|
+
userPlanChangeTs: z.string().optional().nullable(),
|
|
388
|
+
isPending: z.boolean().optional()
|
|
389
|
+
});
|
|
390
|
+
var SpanStatusSchema = z.enum(["UNSET", "OK", "ERROR"]);
|
|
391
|
+
var SpanTypeSchema = z.enum([
|
|
392
|
+
"INTERNAL",
|
|
393
|
+
"LLM_GENERATION",
|
|
394
|
+
"LLM_GENERATION_STREAM",
|
|
395
|
+
"TOOL_CALL"
|
|
396
|
+
]);
|
|
397
|
+
var TracesListPipe = {
|
|
398
|
+
name: "traces_list",
|
|
399
|
+
input: z.object({
|
|
400
|
+
event_id: z.string().optional(),
|
|
401
|
+
trace_id: z.string().optional(),
|
|
402
|
+
subagent_parent_event_ids: z.array(z.string()).optional(),
|
|
403
|
+
limit: z.number().int().optional(),
|
|
404
|
+
offset: z.number().int().optional(),
|
|
405
|
+
trunc_len: z.number().int().nonnegative().optional(),
|
|
406
|
+
span_type_filter: SpanTypeSchema.optional(),
|
|
407
|
+
span_status_filter: SpanStatusSchema.optional(),
|
|
408
|
+
span_id_filter: z.string().optional(),
|
|
409
|
+
span_ids_filter: z.array(z.string()).optional(),
|
|
410
|
+
include_payload_chars: z.literal(1).optional(),
|
|
411
|
+
start_unix_ns_min: z.string().optional(),
|
|
412
|
+
start_unix_ns_max: z.string().optional()
|
|
413
|
+
}),
|
|
414
|
+
output: z.object({
|
|
415
|
+
project_id: z.string().optional(),
|
|
416
|
+
convo_id: z.string(),
|
|
417
|
+
event_id: z.string(),
|
|
418
|
+
custom_event_id: z.string(),
|
|
419
|
+
trace_id: z.string(),
|
|
420
|
+
span_id: z.string(),
|
|
421
|
+
parent_span_id: z.string(),
|
|
422
|
+
span_type: SpanTypeSchema,
|
|
423
|
+
span_name: z.string(),
|
|
424
|
+
status: SpanStatusSchema,
|
|
425
|
+
input_payload: z.string(),
|
|
426
|
+
output_payload: z.string(),
|
|
427
|
+
start_unix_ns: z.number(),
|
|
428
|
+
end_unix_ns: z.number(),
|
|
429
|
+
duration_ns: z.number(),
|
|
430
|
+
input_tokens: z.number(),
|
|
431
|
+
output_tokens: z.number(),
|
|
432
|
+
model: z.string(),
|
|
433
|
+
provider: z.string(),
|
|
434
|
+
attributes_string: stringRecord(z.string()),
|
|
435
|
+
attributes_num: stringRecord(z.number()),
|
|
436
|
+
input_chars: z.number().optional(),
|
|
437
|
+
output_chars: z.number().optional(),
|
|
438
|
+
attributes_chars: z.number().optional()
|
|
439
|
+
})
|
|
440
|
+
};
|
|
441
|
+
var UINT64_MAX = BigInt("18446744073709551615");
|
|
442
|
+
var NANOSECONDS_PATTERN = /^\d{1,20}$/;
|
|
443
|
+
var NanosecondsStringSchema = z.string().refine((value) => {
|
|
444
|
+
if (!NANOSECONDS_PATTERN.test(value))
|
|
445
|
+
return false;
|
|
446
|
+
return BigInt(value) <= UINT64_MAX;
|
|
447
|
+
}, "Nanoseconds must be a UInt64 decimal string");
|
|
448
|
+
var ReplayTraceSnapshotSpanSchema = TracesListPipe.output.extend({
|
|
449
|
+
org_public_id: z.guid(),
|
|
450
|
+
project_id: z.string().min(1),
|
|
451
|
+
user_id: z.string(),
|
|
452
|
+
start_unix_ns: NanosecondsStringSchema,
|
|
453
|
+
timestamp: z.string().min(1),
|
|
454
|
+
end_unix_ns: NanosecondsStringSchema,
|
|
455
|
+
end_timestamp: z.string().min(1),
|
|
456
|
+
duration_ns: NanosecondsStringSchema,
|
|
457
|
+
_inserted_at: z.string().min(1)
|
|
458
|
+
}).strict();
|
|
459
|
+
var EvalDatasetRowIdSchema = z.string().min(1).max(512).refine((value) => value === value.trim(), "Row id cannot have surrounding whitespace");
|
|
460
|
+
var EvalCaseExpectationSchema = z.object({
|
|
461
|
+
description: z.string().trim().min(1).max(1e4),
|
|
462
|
+
basis: z.enum(["human", "policy", "code", "inferred"]).optional(),
|
|
463
|
+
reference: z.string().trim().min(1).max(2e3).optional()
|
|
464
|
+
}).strict();
|
|
465
|
+
var TraceSchema = z.object({
|
|
466
|
+
origin: z.enum(["production", "dataset", "simulation", "replay"]),
|
|
467
|
+
event: AIAnalyticsEventSchema,
|
|
468
|
+
entries: z.array(RichInteractionEntrySchema)
|
|
469
|
+
});
|
|
470
|
+
var EvalReferenceOutputSchema = z.object({
|
|
471
|
+
source: z.union([z.object({ column: z.string() }), z.object({ baselineRunId: z.string() })]),
|
|
472
|
+
kind: z.enum(["json", "trace"]),
|
|
473
|
+
value: JsonValueSchema,
|
|
474
|
+
trace: TraceSchema.extend({ origin: z.literal("dataset") })
|
|
475
|
+
});
|
|
476
|
+
var EvalContextSchema = z.strictObject({
|
|
477
|
+
trace: TraceSchema,
|
|
478
|
+
referenceOutput: EvalReferenceOutputSchema.optional(),
|
|
479
|
+
rowMetadata: stringRecord(z.string())
|
|
480
|
+
});
|
|
481
|
+
var CapturedTraceSpanSchema = ReplayTraceSnapshotSpanSchema;
|
|
482
|
+
var EVAL_DATASET_MAX_SPANS_PER_TRACE = 500;
|
|
483
|
+
var CapturedTraceSnapshotSchema = z.object({
|
|
484
|
+
event: AIAnalyticsEventSchema,
|
|
485
|
+
spans: z.array(CapturedTraceSpanSchema).max(EVAL_DATASET_MAX_SPANS_PER_TRACE)
|
|
486
|
+
}).strict().superRefine(({ event, spans }, context) => {
|
|
487
|
+
var _a, _b;
|
|
488
|
+
if (spans.length === 0) {
|
|
489
|
+
if (!((_a = event.aiData.output) == null ? void 0 : _a.trim()))
|
|
490
|
+
context.addIssue({
|
|
491
|
+
code: z.ZodIssueCode.custom,
|
|
492
|
+
message: "A captured event without spans needs an output",
|
|
493
|
+
path: ["event", "aiData", "output"]
|
|
494
|
+
});
|
|
495
|
+
return;
|
|
496
|
+
}
|
|
497
|
+
const spanIds = /* @__PURE__ */ new Set();
|
|
498
|
+
const traceIds = /* @__PURE__ */ new Set();
|
|
499
|
+
for (const [index, span] of spans.entries()) {
|
|
500
|
+
if (!/^[0-9a-f]{32}$/.test(span.trace_id)) {
|
|
501
|
+
context.addIssue({
|
|
502
|
+
code: z.ZodIssueCode.custom,
|
|
503
|
+
message: "Captured trace id must be a lowercase 32-character hexadecimal value",
|
|
504
|
+
path: ["spans", index, "trace_id"]
|
|
505
|
+
});
|
|
506
|
+
}
|
|
507
|
+
if (!/^[0-9a-f]{16}$/.test(span.span_id)) {
|
|
508
|
+
context.addIssue({
|
|
509
|
+
code: z.ZodIssueCode.custom,
|
|
510
|
+
message: "Captured span id must be a lowercase 16-character hexadecimal value",
|
|
511
|
+
path: ["spans", index, "span_id"]
|
|
512
|
+
});
|
|
513
|
+
}
|
|
514
|
+
if (span.parent_span_id !== "" && !/^[0-9a-f]{16}$/.test(span.parent_span_id)) {
|
|
515
|
+
context.addIssue({
|
|
516
|
+
code: z.ZodIssueCode.custom,
|
|
517
|
+
message: "Captured parent span id must be empty or lowercase hexadecimal",
|
|
518
|
+
path: ["spans", index, "parent_span_id"]
|
|
519
|
+
});
|
|
520
|
+
}
|
|
521
|
+
if (span.event_id.length === 0) {
|
|
522
|
+
context.addIssue({
|
|
523
|
+
code: z.ZodIssueCode.custom,
|
|
524
|
+
message: "Captured event id cannot be empty",
|
|
525
|
+
path: ["spans", index, "event_id"]
|
|
526
|
+
});
|
|
527
|
+
}
|
|
528
|
+
if (spanIds.has(span.span_id)) {
|
|
529
|
+
context.addIssue({
|
|
530
|
+
code: z.ZodIssueCode.custom,
|
|
531
|
+
message: `Duplicate span id ${span.span_id}`,
|
|
532
|
+
path: ["spans", index, "span_id"]
|
|
533
|
+
});
|
|
534
|
+
}
|
|
535
|
+
spanIds.add(span.span_id);
|
|
536
|
+
traceIds.add(span.trace_id);
|
|
537
|
+
if (span.event_id !== event._raindropDatabaseId) {
|
|
538
|
+
context.addIssue({
|
|
539
|
+
code: z.ZodIssueCode.custom,
|
|
540
|
+
message: "Span event identity does not match the captured event",
|
|
541
|
+
path: ["spans", index, "event_id"]
|
|
542
|
+
});
|
|
543
|
+
}
|
|
544
|
+
const validStart = /^\d{1,20}$/.test(span.start_unix_ns);
|
|
545
|
+
const validEnd = /^\d{1,20}$/.test(span.end_unix_ns);
|
|
546
|
+
if (validStart && validEnd && (BigInt(span.start_unix_ns) === BigInt(0) || BigInt(span.end_unix_ns) < BigInt(span.start_unix_ns))) {
|
|
547
|
+
context.addIssue({
|
|
548
|
+
code: z.ZodIssueCode.custom,
|
|
549
|
+
message: "A captured span must have an end time at or after its start time",
|
|
550
|
+
path: ["spans", index, "end_unix_ns"]
|
|
551
|
+
});
|
|
552
|
+
}
|
|
553
|
+
}
|
|
554
|
+
if (traceIds.size !== 1) {
|
|
555
|
+
context.addIssue({
|
|
556
|
+
code: z.ZodIssueCode.custom,
|
|
557
|
+
message: "A reference snapshot must contain exactly one trace id",
|
|
558
|
+
path: ["spans"]
|
|
559
|
+
});
|
|
560
|
+
}
|
|
561
|
+
const parentBySpanId = new Map(spans.map((span) => [span.span_id, span.parent_span_id]));
|
|
562
|
+
for (const [index, span] of spans.entries()) {
|
|
563
|
+
const path = /* @__PURE__ */ new Set();
|
|
564
|
+
let spanId = span.span_id;
|
|
565
|
+
while (spanId !== "") {
|
|
566
|
+
if (path.has(spanId)) {
|
|
567
|
+
context.addIssue({
|
|
568
|
+
code: z.ZodIssueCode.custom,
|
|
569
|
+
message: "Captured span parent relationships cannot contain a cycle",
|
|
570
|
+
path: ["spans", index, "parent_span_id"]
|
|
571
|
+
});
|
|
572
|
+
break;
|
|
573
|
+
}
|
|
574
|
+
path.add(spanId);
|
|
575
|
+
spanId = (_b = parentBySpanId.get(spanId)) != null ? _b : "";
|
|
576
|
+
}
|
|
577
|
+
}
|
|
578
|
+
});
|
|
579
|
+
var EvalRowTraceSchema = z.object({
|
|
580
|
+
snapshot: CapturedTraceSnapshotSchema,
|
|
581
|
+
trace: TraceSchema
|
|
582
|
+
});
|
|
583
|
+
var EvalRowTracePairSchema = z.object({
|
|
584
|
+
rowId: EvalDatasetRowIdSchema,
|
|
585
|
+
referenceOutput: EvalReferenceOutputSchema.optional(),
|
|
586
|
+
output: JsonValueSchema.optional(),
|
|
587
|
+
rowMetadata: stringRecord(z.string()).optional(),
|
|
588
|
+
candidate: EvalRowTraceSchema.extend({
|
|
589
|
+
trace: TraceSchema.extend({ origin: z.enum(["replay", "dataset"]) })
|
|
590
|
+
}),
|
|
591
|
+
reference: EvalRowTraceSchema.extend({
|
|
592
|
+
snapshot: CapturedTraceSnapshotSchema.optional(),
|
|
593
|
+
trace: TraceSchema.extend({ origin: z.literal("dataset") })
|
|
594
|
+
}).optional()
|
|
595
|
+
});
|
|
596
|
+
function compareNanoseconds(left, right) {
|
|
597
|
+
if (Number.isFinite(left) && Number.isFinite(right))
|
|
598
|
+
return Number(left) - Number(right);
|
|
599
|
+
const leftNs = BigInt(left != null ? left : 0);
|
|
600
|
+
const rightNs = BigInt(right != null ? right : 0);
|
|
601
|
+
return leftNs < rightNs ? -1 : leftNs > rightNs ? 1 : 0;
|
|
602
|
+
}
|
|
603
|
+
function nanosecondsToRoundedMilliseconds(value) {
|
|
604
|
+
if (Number.isFinite(value))
|
|
605
|
+
return Math.round(Number(value) / 1e6);
|
|
606
|
+
return Number((BigInt(value != null ? value : 0) + BigInt(5e5)) / BigInt(1e6));
|
|
607
|
+
}
|
|
608
|
+
var MAX_CUSTOM_ATTRIBUTES = 25;
|
|
609
|
+
var MAX_ATTRIBUTE_VALUE_CHARS = 500;
|
|
610
|
+
var KNOWN_ATTRIBUTE_PREFIXES = [
|
|
611
|
+
"ai.",
|
|
612
|
+
"gen_ai.",
|
|
613
|
+
"llm.",
|
|
614
|
+
"openinference.",
|
|
615
|
+
"traceloop.",
|
|
616
|
+
"raindrop.",
|
|
617
|
+
"otel.",
|
|
618
|
+
"telemetry.",
|
|
619
|
+
"service.",
|
|
620
|
+
"resource.",
|
|
621
|
+
"http.",
|
|
622
|
+
"net.",
|
|
623
|
+
"network.",
|
|
624
|
+
"server.",
|
|
625
|
+
"client.",
|
|
626
|
+
"url.",
|
|
627
|
+
"rpc.",
|
|
628
|
+
"db.",
|
|
629
|
+
"messaging.",
|
|
630
|
+
"code.",
|
|
631
|
+
"thread.",
|
|
632
|
+
"session.",
|
|
633
|
+
"user_agent.",
|
|
634
|
+
"process.",
|
|
635
|
+
"host.",
|
|
636
|
+
"os.",
|
|
637
|
+
"exception.",
|
|
638
|
+
"span."
|
|
639
|
+
];
|
|
640
|
+
var SENSITIVE_KEY_TOKENS = /* @__PURE__ */ new Set([
|
|
641
|
+
"secret",
|
|
642
|
+
"secrets",
|
|
643
|
+
"secretkey",
|
|
644
|
+
"password",
|
|
645
|
+
"passwd",
|
|
646
|
+
"pwd",
|
|
647
|
+
"token",
|
|
648
|
+
"tokens",
|
|
649
|
+
"auth",
|
|
650
|
+
"authorization",
|
|
651
|
+
"credential",
|
|
652
|
+
"credentials",
|
|
653
|
+
"bearer",
|
|
654
|
+
"cookie",
|
|
655
|
+
"cookies",
|
|
656
|
+
"apikey",
|
|
657
|
+
"accesskey",
|
|
658
|
+
"privatekey",
|
|
659
|
+
"sessionid"
|
|
660
|
+
]);
|
|
661
|
+
var SENSITIVE_KEY_TOKEN_PAIRS = /* @__PURE__ */ new Set([
|
|
662
|
+
"api key",
|
|
663
|
+
"access key",
|
|
664
|
+
"private key",
|
|
665
|
+
"secret key",
|
|
666
|
+
"session id",
|
|
667
|
+
"auth token",
|
|
668
|
+
"access token",
|
|
669
|
+
"refresh token"
|
|
670
|
+
]);
|
|
671
|
+
function isKnownAttributeKey(key) {
|
|
672
|
+
return KNOWN_ATTRIBUTE_PREFIXES.some((prefix) => key.startsWith(prefix));
|
|
673
|
+
}
|
|
674
|
+
function tokenizeKey(key) {
|
|
675
|
+
return key.replace(/([a-z0-9])([A-Z])/g, "$1 $2").split(/[^a-zA-Z0-9]+/).filter(Boolean).map((token) => token.toLowerCase());
|
|
676
|
+
}
|
|
677
|
+
function isSensitiveAttributeKey(key) {
|
|
678
|
+
const tokens = tokenizeKey(key);
|
|
679
|
+
if (tokens.some((token) => SENSITIVE_KEY_TOKENS.has(token)))
|
|
680
|
+
return true;
|
|
681
|
+
for (let index = 0; index < tokens.length - 1; index += 1) {
|
|
682
|
+
if (SENSITIVE_KEY_TOKEN_PAIRS.has(`${tokens[index]} ${tokens[index + 1]}`))
|
|
683
|
+
return true;
|
|
684
|
+
}
|
|
685
|
+
return false;
|
|
686
|
+
}
|
|
687
|
+
function extractCustomSpanAttributes(span) {
|
|
688
|
+
var _a, _b;
|
|
689
|
+
const attributes = {};
|
|
690
|
+
const strings = (_a = span.attributes_string) != null ? _a : {};
|
|
691
|
+
for (const [key, value] of Object.entries(strings)) {
|
|
692
|
+
if (Object.keys(attributes).length >= MAX_CUSTOM_ATTRIBUTES)
|
|
693
|
+
break;
|
|
694
|
+
if (isKnownAttributeKey(key) || isSensitiveAttributeKey(key)) {
|
|
695
|
+
continue;
|
|
696
|
+
}
|
|
697
|
+
attributes[key] = value.length > MAX_ATTRIBUTE_VALUE_CHARS ? `${value.slice(0, MAX_ATTRIBUTE_VALUE_CHARS)}\u2026` : value;
|
|
698
|
+
}
|
|
699
|
+
const numbers = (_b = span.attributes_num) != null ? _b : {};
|
|
700
|
+
for (const [key, value] of Object.entries(numbers)) {
|
|
701
|
+
if (Object.keys(attributes).length >= MAX_CUSTOM_ATTRIBUTES)
|
|
702
|
+
break;
|
|
703
|
+
if (isKnownAttributeKey(key) || isSensitiveAttributeKey(key)) {
|
|
704
|
+
continue;
|
|
705
|
+
}
|
|
706
|
+
attributes[key] = value;
|
|
707
|
+
}
|
|
708
|
+
return Object.keys(attributes).length > 0 ? attributes : void 0;
|
|
709
|
+
}
|
|
710
|
+
function extractFinishReason(span) {
|
|
711
|
+
var _a, _b, _c;
|
|
712
|
+
const strings = (_a = span.attributes_string) != null ? _a : {};
|
|
713
|
+
const value = (_c = (_b = strings["ai.response.finishReason"]) != null ? _b : strings["gen_ai.response.finish_reasons"]) != null ? _c : strings["llm.response.finish_reason"];
|
|
714
|
+
return value && value.length > 0 ? value : void 0;
|
|
715
|
+
}
|
|
716
|
+
function normalizePayload(value) {
|
|
717
|
+
return value != null ? value : void 0;
|
|
718
|
+
}
|
|
719
|
+
function buildTraceSteps(rawSpans, options = {}) {
|
|
720
|
+
var _a;
|
|
721
|
+
const includePayloads = (_a = options.includePayloads) != null ? _a : false;
|
|
722
|
+
const sorted = [...rawSpans].sort((left, right) => compareNanoseconds(left.start_unix_ns, right.start_unix_ns));
|
|
723
|
+
return sorted.map((span, index) => {
|
|
724
|
+
var _a2, _b;
|
|
725
|
+
const status = span.status === "OK" || span.status === "ERROR" ? span.status : "UNSET";
|
|
726
|
+
const step = {
|
|
727
|
+
step: index + 1,
|
|
728
|
+
type: span.span_type || "INTERNAL",
|
|
729
|
+
name: span.span_name || "unknown",
|
|
730
|
+
status,
|
|
731
|
+
duration_ms: nanosecondsToRoundedMilliseconds(span.duration_ns)
|
|
732
|
+
};
|
|
733
|
+
if (span.span_id)
|
|
734
|
+
step.span_id = span.span_id;
|
|
735
|
+
if (span.status === "ERROR" && span.output_payload) {
|
|
736
|
+
step.error = span.output_payload.slice(0, 500);
|
|
737
|
+
}
|
|
738
|
+
if (span.model)
|
|
739
|
+
step.model = span.model;
|
|
740
|
+
const finishReason = extractFinishReason(span);
|
|
741
|
+
if (finishReason)
|
|
742
|
+
step.finish_reason = finishReason;
|
|
743
|
+
if (((_a2 = span.input_tokens) != null ? _a2 : 0) > 0)
|
|
744
|
+
step.input_tokens = span.input_tokens;
|
|
745
|
+
if (((_b = span.output_tokens) != null ? _b : 0) > 0)
|
|
746
|
+
step.output_tokens = span.output_tokens;
|
|
747
|
+
if (includePayloads && step.type === "TOOL_CALL") {
|
|
748
|
+
const inputPayload = normalizePayload(span.input_payload);
|
|
749
|
+
const outputPayload = normalizePayload(span.output_payload);
|
|
750
|
+
if (inputPayload)
|
|
751
|
+
step.input_payload = inputPayload;
|
|
752
|
+
if (outputPayload)
|
|
753
|
+
step.output_payload = outputPayload;
|
|
754
|
+
}
|
|
755
|
+
const attributes = extractCustomSpanAttributes(span);
|
|
756
|
+
if (attributes)
|
|
757
|
+
step.attributes = attributes;
|
|
758
|
+
return step;
|
|
759
|
+
});
|
|
760
|
+
}
|
|
761
|
+
var MAX_EVAL_PAYLOAD_RAW_CHARS = 16 * 1024;
|
|
762
|
+
function boundEvalPayload(payload) {
|
|
763
|
+
var _a;
|
|
764
|
+
if (payload.raw === null)
|
|
765
|
+
return payload;
|
|
766
|
+
const sizeChars = (_a = payload.sizeChars) != null ? _a : payload.raw.length;
|
|
767
|
+
return {
|
|
768
|
+
...payload,
|
|
769
|
+
raw: payload.raw.slice(0, MAX_EVAL_PAYLOAD_RAW_CHARS),
|
|
770
|
+
sizeChars,
|
|
771
|
+
truncated: payload.truncated || sizeChars > MAX_EVAL_PAYLOAD_RAW_CHARS
|
|
772
|
+
};
|
|
773
|
+
}
|
|
774
|
+
function boundEvalEntry(entry) {
|
|
775
|
+
switch (entry.type) {
|
|
776
|
+
case "system":
|
|
777
|
+
case "reasoning":
|
|
778
|
+
return {
|
|
779
|
+
...entry,
|
|
780
|
+
content: {
|
|
781
|
+
...entry.content,
|
|
782
|
+
text: entry.content.text.slice(0, MAX_EVAL_PAYLOAD_RAW_CHARS)
|
|
783
|
+
}
|
|
784
|
+
};
|
|
785
|
+
case "user_message":
|
|
786
|
+
case "assistant_text":
|
|
787
|
+
return {
|
|
788
|
+
...entry,
|
|
789
|
+
content: entry.content.map((content) => content.type === "text" ? { ...content, text: content.text.slice(0, MAX_EVAL_PAYLOAD_RAW_CHARS) } : content.type === "json" && content.raw !== null ? { ...content, raw: content.raw.slice(0, MAX_EVAL_PAYLOAD_RAW_CHARS) } : content)
|
|
790
|
+
};
|
|
791
|
+
case "tool_call":
|
|
792
|
+
return {
|
|
793
|
+
...entry,
|
|
794
|
+
input: boundEvalPayload(entry.input),
|
|
795
|
+
output: entry.output === null ? null : boundEvalPayload(entry.output),
|
|
796
|
+
error: entry.error === null ? null : boundEvalPayload(entry.error)
|
|
797
|
+
};
|
|
798
|
+
default:
|
|
799
|
+
return entry;
|
|
800
|
+
}
|
|
801
|
+
}
|
|
802
|
+
function createTrace(origin, event, entries) {
|
|
803
|
+
return TraceSchema.parse({ origin, event, entries });
|
|
804
|
+
}
|
|
805
|
+
function traceStepsToEntries(steps) {
|
|
806
|
+
return steps.map((step, index) => {
|
|
807
|
+
var _a;
|
|
808
|
+
const source = {
|
|
809
|
+
adapter: "raw_spans",
|
|
810
|
+
confidence: "medium",
|
|
811
|
+
spanIds: step.span_id ? [step.span_id] : [],
|
|
812
|
+
parentSpanIds: [],
|
|
813
|
+
attributeKeys: []
|
|
814
|
+
};
|
|
815
|
+
const common = {
|
|
816
|
+
id: (_a = step.span_id) != null ? _a : `raw-step-${index}`,
|
|
817
|
+
order: index,
|
|
818
|
+
startMs: null,
|
|
819
|
+
endMs: null,
|
|
820
|
+
source
|
|
821
|
+
};
|
|
822
|
+
if (step.type === "TOOL_CALL") {
|
|
823
|
+
const payload = (raw) => {
|
|
824
|
+
var _a2;
|
|
825
|
+
return boundEvalPayload({
|
|
826
|
+
kind: raw ? "text" : "empty",
|
|
827
|
+
raw: raw != null ? raw : null,
|
|
828
|
+
truncated: false,
|
|
829
|
+
sizeChars: (_a2 = raw == null ? void 0 : raw.length) != null ? _a2 : null
|
|
830
|
+
});
|
|
831
|
+
};
|
|
832
|
+
return {
|
|
833
|
+
...common,
|
|
834
|
+
type: "tool_call",
|
|
835
|
+
callId: null,
|
|
836
|
+
name: step.name,
|
|
837
|
+
status: step.status === "ERROR" ? "error" : step.status === "OK" ? "completed" : "unknown",
|
|
838
|
+
durationMs: step.duration_ms,
|
|
839
|
+
input: payload(step.input_payload),
|
|
840
|
+
output: step.output_payload ? payload(step.output_payload) : null,
|
|
841
|
+
error: step.error ? payload(step.error) : null
|
|
842
|
+
};
|
|
843
|
+
}
|
|
844
|
+
return {
|
|
845
|
+
...common,
|
|
846
|
+
type: "unknown_span",
|
|
847
|
+
spanType: step.type,
|
|
848
|
+
name: step.name,
|
|
849
|
+
hiddenByDefault: true
|
|
850
|
+
};
|
|
851
|
+
});
|
|
852
|
+
}
|
|
853
|
+
function eventEntries(event) {
|
|
854
|
+
const source = {
|
|
855
|
+
adapter: "event",
|
|
856
|
+
confidence: "high",
|
|
857
|
+
spanIds: [],
|
|
858
|
+
parentSpanIds: [],
|
|
859
|
+
attributeKeys: []
|
|
860
|
+
};
|
|
861
|
+
const timing = { startMs: null, endMs: null, source };
|
|
862
|
+
const entries = [];
|
|
863
|
+
const { input, output } = event.aiData;
|
|
864
|
+
if (input)
|
|
865
|
+
entries.push({
|
|
866
|
+
...timing,
|
|
867
|
+
id: `${event.id}:input`,
|
|
868
|
+
order: 0,
|
|
869
|
+
type: "user_message",
|
|
870
|
+
role: "user",
|
|
871
|
+
content: [{ type: "text", text: input }]
|
|
872
|
+
});
|
|
873
|
+
if (output)
|
|
874
|
+
entries.push({
|
|
875
|
+
...timing,
|
|
876
|
+
id: `${event.id}:output`,
|
|
877
|
+
order: 1,
|
|
878
|
+
type: "assistant_text",
|
|
879
|
+
role: "assistant",
|
|
880
|
+
content: [{ type: "text", text: output }],
|
|
881
|
+
format: "text",
|
|
882
|
+
final: true
|
|
883
|
+
});
|
|
884
|
+
return entries.map(boundEvalEntry);
|
|
885
|
+
}
|
|
886
|
+
function projectWorkshopTrace(input) {
|
|
887
|
+
if (input.spans.length === 0)
|
|
888
|
+
return createTrace(input.origin, input.event, eventEntries(input.event));
|
|
889
|
+
const projectedEntries = extractInteractionEntries(input.spans.map(normalizeStoredSpan), MAX_EVAL_PAYLOAD_RAW_CHARS).entries;
|
|
890
|
+
const entries = projectedEntries.length > 0 ? projectedEntries.map((entry) => RichInteractionEntrySchema.parse(entry)).map(boundEvalEntry) : traceStepsToEntries(buildTraceSteps([...input.spans], { includePayloads: true })).map(boundEvalEntry);
|
|
891
|
+
return createTrace(input.origin, input.event, entries);
|
|
892
|
+
}
|
|
893
|
+
function formatTrace(trace) {
|
|
894
|
+
return JSON.stringify(trace);
|
|
895
|
+
}
|
|
896
|
+
function traceOutput(trace) {
|
|
897
|
+
var _a;
|
|
898
|
+
return (_a = trace.event.aiData.output) != null ? _a : null;
|
|
899
|
+
}
|
|
900
|
+
function traceToolCalls(trace, name) {
|
|
901
|
+
return trace.entries.filter((entry) => entry.type === "tool_call" && (name === void 0 || entry.name === name));
|
|
902
|
+
}
|
|
903
|
+
|
|
904
|
+
// src/evals/dataset.ts
|
|
905
|
+
import { createHash } from "crypto";
|
|
906
|
+
import { z as z2 } from "zod/v4";
|
|
907
|
+
|
|
908
|
+
// src/replay/endpoint.ts
|
|
909
|
+
function credentialEndpoint(value) {
|
|
910
|
+
const url = new URL(value);
|
|
911
|
+
const loopback = ["localhost", "127.0.0.1", "[::1]"].includes(url.hostname);
|
|
912
|
+
if (url.protocol !== "https:" && !(url.protocol === "http:" && loopback)) {
|
|
913
|
+
throw new Error("Raindrop endpoints require HTTPS, except on loopback hosts");
|
|
914
|
+
}
|
|
915
|
+
if (url.username || url.password || url.search || url.hash) {
|
|
916
|
+
throw new Error("Raindrop endpoints cannot contain credentials, a query, or a fragment");
|
|
917
|
+
}
|
|
918
|
+
return url;
|
|
919
|
+
}
|
|
920
|
+
function replayIngestEndpoint(value, trustedUrl) {
|
|
921
|
+
const url = credentialEndpoint(value);
|
|
922
|
+
if (!trustedUrl && url.href.replace(/\/+$/, "") === "https://app.raindrop.ai/api/replays/ingest") {
|
|
923
|
+
url.hostname = "backend.raindrop.ai";
|
|
924
|
+
}
|
|
925
|
+
const trusted = credentialEndpoint(trustedUrl != null ? trustedUrl : "https://backend.raindrop.ai/api/replays/ingest/");
|
|
926
|
+
if (url.href.replace(/\/+$/, "") !== trusted.href.replace(/\/+$/, "")) {
|
|
927
|
+
throw new Error("Raindrop replay ingest URL does not match the trusted replayIngestUrl");
|
|
928
|
+
}
|
|
929
|
+
return url.href;
|
|
930
|
+
}
|
|
931
|
+
|
|
932
|
+
// src/evals/dataset.ts
|
|
933
|
+
var DEFAULT_QUERY_URL = "https://query.raindrop.ai";
|
|
934
|
+
var DATASET_REQUEST_TIMEOUT_MS = 3e4;
|
|
935
|
+
var UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
936
|
+
function stringRecord2(value) {
|
|
937
|
+
return z2.record(z2.string(), value);
|
|
938
|
+
}
|
|
939
|
+
var DatasetIdSchema = z2.string().trim().regex(
|
|
940
|
+
UUID_PATTERN,
|
|
941
|
+
"Raindrop eval dataset must be a dataset UUID (not a slug). Use the dataset id shown by list_datasets."
|
|
942
|
+
);
|
|
943
|
+
function isDatasetId(value) {
|
|
944
|
+
return UUID_PATTERN.test(value.trim());
|
|
945
|
+
}
|
|
946
|
+
function parseDatasetId(dataset) {
|
|
947
|
+
const trimmed = dataset.trim();
|
|
948
|
+
if (!UUID_PATTERN.test(trimmed)) {
|
|
949
|
+
throw new Error(
|
|
950
|
+
`Raindrop eval dataset must be a dataset UUID (got ${JSON.stringify(dataset)}). Use the dataset id shown by list_datasets.`
|
|
951
|
+
);
|
|
952
|
+
}
|
|
953
|
+
return trimmed;
|
|
954
|
+
}
|
|
955
|
+
var ReplayMessageToolCallSchema = z2.object({
|
|
956
|
+
id: z2.string(),
|
|
957
|
+
type: z2.literal("function"),
|
|
958
|
+
function: z2.object({
|
|
959
|
+
name: z2.string(),
|
|
960
|
+
arguments: z2.string()
|
|
961
|
+
})
|
|
962
|
+
});
|
|
963
|
+
var ReplayMessageContentPartSchema = z2.union([
|
|
964
|
+
z2.object({ type: z2.literal("text"), text: z2.string() }),
|
|
965
|
+
z2.object({
|
|
966
|
+
type: z2.literal("image_url"),
|
|
967
|
+
image_url: z2.object({ url: z2.string(), detail: z2.string().optional() })
|
|
968
|
+
}),
|
|
969
|
+
stringRecord2(JsonValueSchema)
|
|
970
|
+
]);
|
|
971
|
+
var ReplayMessageSchema = z2.object({
|
|
972
|
+
role: z2.string(),
|
|
973
|
+
content: z2.union([z2.string(), z2.array(ReplayMessageContentPartSchema)]).nullable().optional(),
|
|
974
|
+
name: z2.string().optional(),
|
|
975
|
+
tool_calls: z2.array(ReplayMessageToolCallSchema).optional(),
|
|
976
|
+
tool_call_id: z2.string().optional()
|
|
977
|
+
}).catchall(JsonValueSchema);
|
|
978
|
+
var InputDatasetColumnSchema = z2.object({
|
|
979
|
+
name: z2.string().min(1),
|
|
980
|
+
role: z2.literal("input"),
|
|
981
|
+
type: z2.enum(["json", "trace"]).default("json")
|
|
982
|
+
});
|
|
983
|
+
var HistoryDatasetColumnSchema = z2.object({
|
|
984
|
+
name: z2.string().min(1),
|
|
985
|
+
role: z2.literal("history"),
|
|
986
|
+
type: z2.literal("trace").default("trace")
|
|
987
|
+
});
|
|
988
|
+
var OutputDatasetColumnSchema = z2.object({
|
|
989
|
+
name: z2.string().min(1),
|
|
990
|
+
role: z2.literal("output"),
|
|
991
|
+
type: z2.enum(["json", "trace"]).default("json"),
|
|
992
|
+
is_reference: z2.boolean().optional()
|
|
993
|
+
});
|
|
994
|
+
var LabelDatasetColumnSchema = z2.object({
|
|
995
|
+
name: z2.string().min(1),
|
|
996
|
+
role: z2.literal("label"),
|
|
997
|
+
type: z2.string().optional(),
|
|
998
|
+
of: z2.array(z2.string()).optional(),
|
|
999
|
+
for: z2.string().optional()
|
|
1000
|
+
});
|
|
1001
|
+
var MetadataDatasetColumnSchema = z2.object({
|
|
1002
|
+
name: z2.string().min(1),
|
|
1003
|
+
role: z2.literal("metadata")
|
|
1004
|
+
});
|
|
1005
|
+
var UnknownDatasetColumnSchema = z2.object({
|
|
1006
|
+
name: z2.string().min(1),
|
|
1007
|
+
role: z2.string()
|
|
1008
|
+
});
|
|
1009
|
+
var DatasetColumnSchema = z2.union([
|
|
1010
|
+
InputDatasetColumnSchema,
|
|
1011
|
+
HistoryDatasetColumnSchema,
|
|
1012
|
+
OutputDatasetColumnSchema,
|
|
1013
|
+
LabelDatasetColumnSchema,
|
|
1014
|
+
MetadataDatasetColumnSchema,
|
|
1015
|
+
UnknownDatasetColumnSchema
|
|
1016
|
+
]);
|
|
1017
|
+
var SavedEventsCellSchema = z2.object({
|
|
1018
|
+
events: z2.array(z2.object({ messages: z2.array(ReplayMessageSchema) }))
|
|
1019
|
+
});
|
|
1020
|
+
var SavedEventsCursorCellSchema = z2.object({
|
|
1021
|
+
events_cursor: z2.string().min(1)
|
|
1022
|
+
});
|
|
1023
|
+
var InlineMessagesTraceCellSchema = z2.object({
|
|
1024
|
+
messages: z2.array(ReplayMessageSchema)
|
|
1025
|
+
});
|
|
1026
|
+
var SavedEventsPageSchema = z2.object({
|
|
1027
|
+
events: z2.array(
|
|
1028
|
+
z2.object({
|
|
1029
|
+
index: z2.number().int().nonnegative(),
|
|
1030
|
+
messages: z2.array(ReplayMessageSchema)
|
|
1031
|
+
})
|
|
1032
|
+
),
|
|
1033
|
+
next_cursor: z2.string().nullable().optional()
|
|
1034
|
+
});
|
|
1035
|
+
var WireDatasetRowSchema = z2.object({
|
|
1036
|
+
id: z2.string().min(1),
|
|
1037
|
+
values: stringRecord2(JsonValueSchema),
|
|
1038
|
+
tags: z2.array(z2.string()).default([])
|
|
1039
|
+
});
|
|
1040
|
+
var WireDatasetPageSchema = z2.object({
|
|
1041
|
+
dataset: z2.object({
|
|
1042
|
+
id: z2.string().min(1),
|
|
1043
|
+
slug: z2.string(),
|
|
1044
|
+
name: z2.string(),
|
|
1045
|
+
columns: z2.array(DatasetColumnSchema),
|
|
1046
|
+
version_id: z2.string().nullable(),
|
|
1047
|
+
version_number: z2.number().int().nullable()
|
|
1048
|
+
}),
|
|
1049
|
+
rows: z2.array(WireDatasetRowSchema),
|
|
1050
|
+
next_cursor: z2.string().nullable().optional()
|
|
1051
|
+
});
|
|
1052
|
+
var ReferenceOutputSourceSchema = z2.union([
|
|
1053
|
+
z2.object({ column: z2.string().min(1) }),
|
|
1054
|
+
z2.object({ baselineRunId: z2.string().min(1) })
|
|
1055
|
+
]);
|
|
1056
|
+
var ReferenceOutputSchema = EvalReferenceOutputSchema;
|
|
1057
|
+
var DatasetRowSchema = z2.object({
|
|
1058
|
+
id: z2.string(),
|
|
1059
|
+
input: JsonValueSchema.optional(),
|
|
1060
|
+
history: z2.array(ReplayMessageSchema).default([]),
|
|
1061
|
+
outputs: stringRecord2(JsonValueSchema).default({}),
|
|
1062
|
+
referenceOutput: ReferenceOutputSchema.optional(),
|
|
1063
|
+
labels: stringRecord2(JsonValueSchema).default({}),
|
|
1064
|
+
metadata: stringRecord2(z2.string()).default({})
|
|
1065
|
+
});
|
|
1066
|
+
function isInputColumn(column) {
|
|
1067
|
+
return column.role === "input" && "type" in column && (column.type === "json" || column.type === "trace");
|
|
1068
|
+
}
|
|
1069
|
+
function isHistoryColumn(column) {
|
|
1070
|
+
return column.role === "history" && "type" in column && column.type === "trace";
|
|
1071
|
+
}
|
|
1072
|
+
function isOutputColumn(column) {
|
|
1073
|
+
return column.role === "output" && "type" in column && (column.type === "json" || column.type === "trace");
|
|
1074
|
+
}
|
|
1075
|
+
function isLabelColumn(column) {
|
|
1076
|
+
return column.role === "label";
|
|
1077
|
+
}
|
|
1078
|
+
function isMetadataColumn(column) {
|
|
1079
|
+
return column.role === "metadata";
|
|
1080
|
+
}
|
|
1081
|
+
function extractMessageText(message) {
|
|
1082
|
+
if (message === void 0 || message.content === void 0 || message.content === null) {
|
|
1083
|
+
return null;
|
|
1084
|
+
}
|
|
1085
|
+
if (typeof message.content === "string") return message.content;
|
|
1086
|
+
const parts = [];
|
|
1087
|
+
for (const part of message.content) {
|
|
1088
|
+
if (part.type === "text" && typeof part.text === "string") {
|
|
1089
|
+
parts.push(part.text);
|
|
1090
|
+
}
|
|
1091
|
+
}
|
|
1092
|
+
return parts.length > 0 ? parts.join("\n") : null;
|
|
1093
|
+
}
|
|
1094
|
+
function formatJsonAsText(value) {
|
|
1095
|
+
return typeof value === "string" ? value : JSON.stringify(value);
|
|
1096
|
+
}
|
|
1097
|
+
function extractCellMessages(cell) {
|
|
1098
|
+
if (cell === void 0 || cell === null) return [];
|
|
1099
|
+
const saved = SavedEventsCellSchema.safeParse(cell);
|
|
1100
|
+
if (saved.success) {
|
|
1101
|
+
return saved.data.events.flatMap((event) => event.messages);
|
|
1102
|
+
}
|
|
1103
|
+
const inline = InlineMessagesTraceCellSchema.safeParse(cell);
|
|
1104
|
+
if (inline.success) {
|
|
1105
|
+
return inline.data.messages;
|
|
1106
|
+
}
|
|
1107
|
+
return [];
|
|
1108
|
+
}
|
|
1109
|
+
function extractInputTurn(inputColumn, cell) {
|
|
1110
|
+
var _a, _b, _c, _d;
|
|
1111
|
+
if (inputColumn === void 0 || cell === void 0 || cell === null) {
|
|
1112
|
+
return { input: void 0, history: [] };
|
|
1113
|
+
}
|
|
1114
|
+
if (inputColumn.type === "json") {
|
|
1115
|
+
return { input: cell, history: [] };
|
|
1116
|
+
}
|
|
1117
|
+
const saved = SavedEventsCellSchema.safeParse(cell);
|
|
1118
|
+
if (saved.success) {
|
|
1119
|
+
if (saved.data.events.length === 0) return { input: void 0, history: [] };
|
|
1120
|
+
const earlier = saved.data.events.slice(0, -1).flatMap((event) => event.messages);
|
|
1121
|
+
const lastMessages = (_b = (_a = saved.data.events[saved.data.events.length - 1]) == null ? void 0 : _a.messages) != null ? _b : [];
|
|
1122
|
+
const lastUserIndex = findLastUserIndex(lastMessages);
|
|
1123
|
+
return {
|
|
1124
|
+
input: lastUserIndex >= 0 ? (_c = extractMessageText(lastMessages[lastUserIndex])) != null ? _c : void 0 : void 0,
|
|
1125
|
+
history: earlier
|
|
1126
|
+
};
|
|
1127
|
+
}
|
|
1128
|
+
const inline = InlineMessagesTraceCellSchema.safeParse(cell);
|
|
1129
|
+
if (inline.success) {
|
|
1130
|
+
const messages = inline.data.messages;
|
|
1131
|
+
const lastUserIndex = findLastUserIndex(messages);
|
|
1132
|
+
if (lastUserIndex < 0) return { input: void 0, history: messages };
|
|
1133
|
+
return {
|
|
1134
|
+
input: (_d = extractMessageText(messages[lastUserIndex])) != null ? _d : void 0,
|
|
1135
|
+
history: messages.slice(0, lastUserIndex)
|
|
1136
|
+
};
|
|
1137
|
+
}
|
|
1138
|
+
return { input: void 0, history: [] };
|
|
1139
|
+
}
|
|
1140
|
+
function findLastUserIndex(messages) {
|
|
1141
|
+
var _a;
|
|
1142
|
+
for (let index = messages.length - 1; index >= 0; index -= 1) {
|
|
1143
|
+
if (((_a = messages[index]) == null ? void 0 : _a.role) === "user") return index;
|
|
1144
|
+
}
|
|
1145
|
+
return -1;
|
|
1146
|
+
}
|
|
1147
|
+
function findLastAssistantText(messages) {
|
|
1148
|
+
for (let index = messages.length - 1; index >= 0; index -= 1) {
|
|
1149
|
+
const message = messages[index];
|
|
1150
|
+
if ((message == null ? void 0 : message.role) === "assistant") {
|
|
1151
|
+
const text = extractMessageText(message);
|
|
1152
|
+
if (text !== null) return text;
|
|
1153
|
+
}
|
|
1154
|
+
}
|
|
1155
|
+
return null;
|
|
1156
|
+
}
|
|
1157
|
+
function preferredOutputName(columns, values) {
|
|
1158
|
+
var _a;
|
|
1159
|
+
for (const column of columns) {
|
|
1160
|
+
if (!isLabelColumn(column) || column.type !== "preference") continue;
|
|
1161
|
+
const candidates = (_a = column.of) != null ? _a : [];
|
|
1162
|
+
if (candidates.length === 0) continue;
|
|
1163
|
+
const cell = values[column.name];
|
|
1164
|
+
if (typeof cell === "string") {
|
|
1165
|
+
if (cell !== "tie" && candidates.includes(cell)) return cell;
|
|
1166
|
+
continue;
|
|
1167
|
+
}
|
|
1168
|
+
if (Array.isArray(cell) && cell.length > 0) {
|
|
1169
|
+
const firstTier = cell[0];
|
|
1170
|
+
if (Array.isArray(firstTier) && firstTier.length === 1 && typeof firstTier[0] === "string" && candidates.includes(firstTier[0])) {
|
|
1171
|
+
return firstTier[0];
|
|
1172
|
+
}
|
|
1173
|
+
}
|
|
1174
|
+
}
|
|
1175
|
+
return void 0;
|
|
1176
|
+
}
|
|
1177
|
+
function selectReferenceOutputColumn(columns, values) {
|
|
1178
|
+
const outputs = columns.filter(isOutputColumn);
|
|
1179
|
+
if (outputs.length === 0) return void 0;
|
|
1180
|
+
const marked = outputs.find((column) => column.is_reference === true);
|
|
1181
|
+
if (marked !== void 0) return marked;
|
|
1182
|
+
const preferred = preferredOutputName(columns, values);
|
|
1183
|
+
if (preferred !== void 0) {
|
|
1184
|
+
const match = outputs.find((column) => column.name === preferred);
|
|
1185
|
+
if (match !== void 0) return match;
|
|
1186
|
+
}
|
|
1187
|
+
return outputs[0];
|
|
1188
|
+
}
|
|
1189
|
+
function datasetTraceId(versionId, rowId, columnName) {
|
|
1190
|
+
return createHash("sha256").update(JSON.stringify([versionId != null ? versionId : "", rowId, columnName])).digest("hex").slice(0, 32);
|
|
1191
|
+
}
|
|
1192
|
+
function buildDatasetReferenceTrace(params) {
|
|
1193
|
+
return TraceSchema.parse({
|
|
1194
|
+
origin: "dataset",
|
|
1195
|
+
event: AIAnalyticsEventSchema.parse({
|
|
1196
|
+
id: datasetTraceId(params.versionId, params.rowId, params.columnName),
|
|
1197
|
+
_raindropDatabaseId: "",
|
|
1198
|
+
name: "Dataset reference",
|
|
1199
|
+
timestamp: "",
|
|
1200
|
+
receivedAt: "",
|
|
1201
|
+
userId: "",
|
|
1202
|
+
aiData: {
|
|
1203
|
+
input: params.input,
|
|
1204
|
+
output: params.outputText,
|
|
1205
|
+
model: null,
|
|
1206
|
+
convoId: null
|
|
1207
|
+
},
|
|
1208
|
+
properties: {}
|
|
1209
|
+
}),
|
|
1210
|
+
entries: [
|
|
1211
|
+
{
|
|
1212
|
+
id: `${params.rowId}:${params.columnName}`,
|
|
1213
|
+
order: 0,
|
|
1214
|
+
startMs: null,
|
|
1215
|
+
endMs: null,
|
|
1216
|
+
source: {
|
|
1217
|
+
adapter: "dataset-reply",
|
|
1218
|
+
confidence: "high",
|
|
1219
|
+
spanIds: [],
|
|
1220
|
+
parentSpanIds: [],
|
|
1221
|
+
attributeKeys: []
|
|
1222
|
+
},
|
|
1223
|
+
type: "assistant_text",
|
|
1224
|
+
role: "assistant",
|
|
1225
|
+
content: [{ type: "text", text: params.outputText }],
|
|
1226
|
+
format: "text",
|
|
1227
|
+
final: true
|
|
1228
|
+
}
|
|
1229
|
+
]
|
|
1230
|
+
});
|
|
1231
|
+
}
|
|
1232
|
+
function projectOutputCell(params) {
|
|
1233
|
+
const { column, cell } = params;
|
|
1234
|
+
if (cell === void 0 || cell === null) return void 0;
|
|
1235
|
+
if (column.type === "json") {
|
|
1236
|
+
return {
|
|
1237
|
+
source: { column: column.name },
|
|
1238
|
+
kind: "json",
|
|
1239
|
+
value: cell,
|
|
1240
|
+
trace: buildDatasetReferenceTrace({
|
|
1241
|
+
versionId: params.versionId,
|
|
1242
|
+
rowId: params.rowId,
|
|
1243
|
+
columnName: column.name,
|
|
1244
|
+
input: params.input,
|
|
1245
|
+
outputText: formatJsonAsText(cell)
|
|
1246
|
+
})
|
|
1247
|
+
};
|
|
1248
|
+
}
|
|
1249
|
+
const saved = SavedEventsCellSchema.safeParse(cell);
|
|
1250
|
+
if (saved.success) {
|
|
1251
|
+
if (saved.data.events.length === 0) return void 0;
|
|
1252
|
+
const messages = saved.data.events.flatMap((event) => event.messages);
|
|
1253
|
+
const value = findLastAssistantText(messages);
|
|
1254
|
+
return {
|
|
1255
|
+
source: { column: column.name },
|
|
1256
|
+
kind: "trace",
|
|
1257
|
+
value,
|
|
1258
|
+
trace: buildDatasetReferenceTrace({
|
|
1259
|
+
versionId: params.versionId,
|
|
1260
|
+
rowId: params.rowId,
|
|
1261
|
+
columnName: column.name,
|
|
1262
|
+
input: params.input,
|
|
1263
|
+
outputText: value != null ? value : ""
|
|
1264
|
+
})
|
|
1265
|
+
};
|
|
1266
|
+
}
|
|
1267
|
+
const inline = InlineMessagesTraceCellSchema.safeParse(cell);
|
|
1268
|
+
if (inline.success) {
|
|
1269
|
+
if (inline.data.messages.length === 0) return void 0;
|
|
1270
|
+
const value = findLastAssistantText(inline.data.messages);
|
|
1271
|
+
return {
|
|
1272
|
+
source: { column: column.name },
|
|
1273
|
+
kind: "trace",
|
|
1274
|
+
value,
|
|
1275
|
+
trace: buildDatasetReferenceTrace({
|
|
1276
|
+
versionId: params.versionId,
|
|
1277
|
+
rowId: params.rowId,
|
|
1278
|
+
columnName: column.name,
|
|
1279
|
+
input: params.input,
|
|
1280
|
+
outputText: value != null ? value : ""
|
|
1281
|
+
})
|
|
1282
|
+
};
|
|
1283
|
+
}
|
|
1284
|
+
return void 0;
|
|
1285
|
+
}
|
|
1286
|
+
function projectDatasetRow(columns, row, versionId = null) {
|
|
1287
|
+
const inputColumn = columns.find(isInputColumn);
|
|
1288
|
+
const historyColumns = columns.filter(isHistoryColumn);
|
|
1289
|
+
const outputColumns = columns.filter(isOutputColumn);
|
|
1290
|
+
const labelColumns = columns.filter(isLabelColumn);
|
|
1291
|
+
const metadataColumns = columns.filter(isMetadataColumn);
|
|
1292
|
+
const turn = extractInputTurn(inputColumn, inputColumn ? row.values[inputColumn.name] : void 0);
|
|
1293
|
+
const history = historyColumns.length > 0 ? historyColumns.flatMap((column) => extractCellMessages(row.values[column.name])) : turn.history;
|
|
1294
|
+
const outputs = {};
|
|
1295
|
+
for (const column of outputColumns) {
|
|
1296
|
+
const cell = row.values[column.name];
|
|
1297
|
+
if (cell !== void 0 && cell !== null) {
|
|
1298
|
+
outputs[column.name] = cell;
|
|
1299
|
+
}
|
|
1300
|
+
}
|
|
1301
|
+
const labels = {};
|
|
1302
|
+
for (const column of labelColumns) {
|
|
1303
|
+
const cell = row.values[column.name];
|
|
1304
|
+
if (cell !== void 0 && cell !== null) {
|
|
1305
|
+
labels[column.name] = cell;
|
|
1306
|
+
}
|
|
1307
|
+
}
|
|
1308
|
+
const metadata = {};
|
|
1309
|
+
for (const column of metadataColumns) {
|
|
1310
|
+
const cell = row.values[column.name];
|
|
1311
|
+
if (cell !== void 0 && cell !== null) {
|
|
1312
|
+
metadata[column.name] = formatJsonAsText(cell);
|
|
1313
|
+
}
|
|
1314
|
+
}
|
|
1315
|
+
const inputText = turn.input === void 0 || turn.input === null ? null : formatJsonAsText(turn.input);
|
|
1316
|
+
const referenceColumn = selectReferenceOutputColumn(columns, row.values);
|
|
1317
|
+
const referenceOutput = referenceColumn === void 0 ? void 0 : projectOutputCell({
|
|
1318
|
+
column: referenceColumn,
|
|
1319
|
+
cell: row.values[referenceColumn.name],
|
|
1320
|
+
versionId,
|
|
1321
|
+
rowId: row.id,
|
|
1322
|
+
input: inputText
|
|
1323
|
+
});
|
|
1324
|
+
return {
|
|
1325
|
+
id: row.id,
|
|
1326
|
+
input: turn.input,
|
|
1327
|
+
history,
|
|
1328
|
+
outputs,
|
|
1329
|
+
...referenceOutput === void 0 ? {} : { referenceOutput },
|
|
1330
|
+
labels,
|
|
1331
|
+
metadata
|
|
1332
|
+
};
|
|
1333
|
+
}
|
|
1334
|
+
async function fetchDatasetEndpoint(params) {
|
|
1335
|
+
var _a;
|
|
1336
|
+
if (!((_a = params.client.connection.apiKey) == null ? void 0 : _a.trim())) {
|
|
1337
|
+
throw new Error("Raindrop evals and datasets require a Query SDK API key (apiKey)");
|
|
1338
|
+
}
|
|
1339
|
+
const headers = {
|
|
1340
|
+
Authorization: `Bearer ${params.client.connection.apiKey}`,
|
|
1341
|
+
"Content-Type": "application/json"
|
|
1342
|
+
};
|
|
1343
|
+
if (params.client.connection.projectId !== void 0) {
|
|
1344
|
+
headers["X-Raindrop-Project-Id"] = params.client.connection.projectId;
|
|
1345
|
+
}
|
|
1346
|
+
const url = `${credentialEndpoint(params.queryUrl).href.replace(/\/+$/, "")}${params.path}`;
|
|
1347
|
+
const controller = new AbortController();
|
|
1348
|
+
const timeout = setTimeout(() => controller.abort(), DATASET_REQUEST_TIMEOUT_MS);
|
|
1349
|
+
let response;
|
|
1350
|
+
let text;
|
|
1351
|
+
try {
|
|
1352
|
+
response = await runWithTracingSuppressed(
|
|
1353
|
+
() => fetch(url, {
|
|
1354
|
+
method: "GET",
|
|
1355
|
+
headers,
|
|
1356
|
+
signal: controller.signal,
|
|
1357
|
+
redirect: "error"
|
|
1358
|
+
})
|
|
1359
|
+
);
|
|
1360
|
+
text = await response.text();
|
|
1361
|
+
} finally {
|
|
1362
|
+
clearTimeout(timeout);
|
|
1363
|
+
}
|
|
1364
|
+
if (!response.ok) {
|
|
1365
|
+
throw new Error(`Raindrop API GET ${params.path}: ${response.status} ${text}`);
|
|
1366
|
+
}
|
|
1367
|
+
let parsed;
|
|
1368
|
+
try {
|
|
1369
|
+
parsed = JSON.parse(text);
|
|
1370
|
+
} catch (cause) {
|
|
1371
|
+
const detail = cause instanceof Error ? cause.message : String(cause);
|
|
1372
|
+
throw new Error(`Raindrop API GET ${params.path} returned invalid JSON: ${detail}`);
|
|
1373
|
+
}
|
|
1374
|
+
return params.schema.parse(parsed);
|
|
1375
|
+
}
|
|
1376
|
+
async function readSavedEventsCell(params) {
|
|
1377
|
+
var _a;
|
|
1378
|
+
const byIndex = /* @__PURE__ */ new Map();
|
|
1379
|
+
const seenCursors = /* @__PURE__ */ new Set();
|
|
1380
|
+
let cursor = params.cursor;
|
|
1381
|
+
while (cursor !== null) {
|
|
1382
|
+
if (seenCursors.has(cursor)) {
|
|
1383
|
+
throw new Error(`Raindrop dataset ${params.datasetId} returned a repeated events cursor`);
|
|
1384
|
+
}
|
|
1385
|
+
seenCursors.add(cursor);
|
|
1386
|
+
const page = await fetchDatasetEndpoint({
|
|
1387
|
+
client: params.client,
|
|
1388
|
+
queryUrl: params.queryUrl,
|
|
1389
|
+
path: `/v1/datasets/${encodeURIComponent(params.datasetId)}/events?cursor=${encodeURIComponent(cursor)}`,
|
|
1390
|
+
schema: SavedEventsPageSchema
|
|
1391
|
+
});
|
|
1392
|
+
for (const chunk of page.events) {
|
|
1393
|
+
const existing = byIndex.get(chunk.index);
|
|
1394
|
+
if (existing === void 0) {
|
|
1395
|
+
byIndex.set(chunk.index, [...chunk.messages]);
|
|
1396
|
+
} else {
|
|
1397
|
+
existing.push(...chunk.messages);
|
|
1398
|
+
}
|
|
1399
|
+
}
|
|
1400
|
+
cursor = (_a = page.next_cursor) != null ? _a : null;
|
|
1401
|
+
}
|
|
1402
|
+
const events = [...byIndex.entries()].sort(([a], [b]) => a - b).map(([, messages]) => ({ messages }));
|
|
1403
|
+
return { events };
|
|
1404
|
+
}
|
|
1405
|
+
async function hydrateCursorCells(params) {
|
|
1406
|
+
const traceColumnNames = new Set(
|
|
1407
|
+
params.columns.filter(
|
|
1408
|
+
(column) => isHistoryColumn(column) || isInputColumn(column) && column.type === "trace" || isOutputColumn(column) && column.type === "trace"
|
|
1409
|
+
).map((column) => column.name)
|
|
1410
|
+
);
|
|
1411
|
+
if (traceColumnNames.size === 0) return [...params.rows];
|
|
1412
|
+
const hydrated = [];
|
|
1413
|
+
for (const row of params.rows) {
|
|
1414
|
+
let values;
|
|
1415
|
+
for (const columnName of traceColumnNames) {
|
|
1416
|
+
const cell = row.values[columnName];
|
|
1417
|
+
const cursorCell = SavedEventsCursorCellSchema.safeParse(cell);
|
|
1418
|
+
if (!cursorCell.success) continue;
|
|
1419
|
+
const resolved = await readSavedEventsCell({
|
|
1420
|
+
client: params.client,
|
|
1421
|
+
queryUrl: params.queryUrl,
|
|
1422
|
+
datasetId: params.datasetId,
|
|
1423
|
+
cursor: cursorCell.data.events_cursor
|
|
1424
|
+
});
|
|
1425
|
+
values != null ? values : values = { ...row.values };
|
|
1426
|
+
values[columnName] = resolved;
|
|
1427
|
+
}
|
|
1428
|
+
hydrated.push(values === void 0 ? row : { ...row, values });
|
|
1429
|
+
}
|
|
1430
|
+
return hydrated;
|
|
1431
|
+
}
|
|
1432
|
+
async function readDataset(client, datasetId, options) {
|
|
1433
|
+
var _a, _b, _c, _d, _e, _f;
|
|
1434
|
+
const id = parseDatasetId(datasetId);
|
|
1435
|
+
const versionId = (_a = options == null ? void 0 : options.versionId) == null ? void 0 : _a.trim();
|
|
1436
|
+
if (versionId !== void 0 && !UUID_PATTERN.test(versionId)) {
|
|
1437
|
+
throw new Error(
|
|
1438
|
+
`Raindrop dataset versionId must be a UUID (got ${JSON.stringify(options == null ? void 0 : options.versionId)})`
|
|
1439
|
+
);
|
|
1440
|
+
}
|
|
1441
|
+
const queryUrl = (_b = options == null ? void 0 : options.queryUrl) != null ? _b : DEFAULT_QUERY_URL;
|
|
1442
|
+
const basePath = versionId !== void 0 ? `/v1/datasets/${encodeURIComponent(id)}/versions/${encodeURIComponent(versionId)}` : `/v1/datasets/${encodeURIComponent(id)}`;
|
|
1443
|
+
const seenCursors = /* @__PURE__ */ new Set();
|
|
1444
|
+
let cursor = null;
|
|
1445
|
+
let header;
|
|
1446
|
+
const rawRows = [];
|
|
1447
|
+
const limit = (_c = options == null ? void 0 : options.limit) != null ? _c : 100;
|
|
1448
|
+
for (; ; ) {
|
|
1449
|
+
const query = new URLSearchParams();
|
|
1450
|
+
query.set("limit", String(limit));
|
|
1451
|
+
if (cursor !== null) query.set("cursor", cursor);
|
|
1452
|
+
const path = `${basePath}?${query.toString()}`;
|
|
1453
|
+
const page = await fetchDatasetEndpoint({
|
|
1454
|
+
client,
|
|
1455
|
+
queryUrl,
|
|
1456
|
+
path,
|
|
1457
|
+
schema: WireDatasetPageSchema
|
|
1458
|
+
});
|
|
1459
|
+
if (page.dataset.id !== id) {
|
|
1460
|
+
throw new Error(`Raindrop dataset ${id} returned mismatched dataset id ${page.dataset.id}`);
|
|
1461
|
+
}
|
|
1462
|
+
if (versionId !== void 0 && page.dataset.version_id !== versionId) {
|
|
1463
|
+
throw new Error(
|
|
1464
|
+
`Raindrop dataset ${id} returned mismatched version ${(_d = page.dataset.version_id) != null ? _d : "null"} for requested version ${versionId}`
|
|
1465
|
+
);
|
|
1466
|
+
}
|
|
1467
|
+
if (header === void 0) {
|
|
1468
|
+
header = page.dataset;
|
|
1469
|
+
} else if (page.dataset.version_id !== header.version_id) {
|
|
1470
|
+
throw new Error(
|
|
1471
|
+
`Raindrop dataset ${id} changed version mid-pagination (${(_e = header.version_id) != null ? _e : "null"} -> ${(_f = page.dataset.version_id) != null ? _f : "null"})`
|
|
1472
|
+
);
|
|
1473
|
+
}
|
|
1474
|
+
rawRows.push(...page.rows);
|
|
1475
|
+
if (page.next_cursor === null || page.next_cursor === void 0) break;
|
|
1476
|
+
if (seenCursors.has(page.next_cursor)) {
|
|
1477
|
+
throw new Error(`Raindrop dataset ${id} returned a repeated page cursor`);
|
|
1478
|
+
}
|
|
1479
|
+
seenCursors.add(page.next_cursor);
|
|
1480
|
+
cursor = page.next_cursor;
|
|
1481
|
+
}
|
|
1482
|
+
const hydratedRows = await hydrateCursorCells({
|
|
1483
|
+
client,
|
|
1484
|
+
queryUrl,
|
|
1485
|
+
datasetId: id,
|
|
1486
|
+
columns: header.columns,
|
|
1487
|
+
rows: rawRows
|
|
1488
|
+
});
|
|
1489
|
+
return {
|
|
1490
|
+
id: header.id,
|
|
1491
|
+
slug: header.slug,
|
|
1492
|
+
name: header.name,
|
|
1493
|
+
versionId: header.version_id,
|
|
1494
|
+
versionNumber: header.version_number,
|
|
1495
|
+
columns: header.columns,
|
|
1496
|
+
rows: hydratedRows.map((row) => projectDatasetRow(header.columns, row, header.version_id))
|
|
1497
|
+
};
|
|
1498
|
+
}
|
|
1499
|
+
|
|
1500
|
+
// src/evals/generated/manifest.ts
|
|
1501
|
+
import { z as z3 } from "zod/v4";
|
|
1502
|
+
var BooleanThresholdSchema = z3.object({ equals: z3.boolean() }).strict();
|
|
1503
|
+
var FiniteThresholdSchema = z3.number().finite();
|
|
1504
|
+
var NumericThresholdSchema = z3.union([
|
|
1505
|
+
z3.object({ gte: FiniteThresholdSchema, lte: FiniteThresholdSchema.optional() }).strict(),
|
|
1506
|
+
z3.object({ lte: FiniteThresholdSchema }).strict()
|
|
1507
|
+
]).refine(
|
|
1508
|
+
(threshold) => !("gte" in threshold) || threshold.lte === void 0 || threshold.gte <= threshold.lte,
|
|
1509
|
+
{ message: "Lower threshold cannot exceed upper threshold" }
|
|
1510
|
+
);
|
|
1511
|
+
var UUID_PATTERN2 = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
1512
|
+
var EvalSuiteManifestSchema = z3.object({
|
|
1513
|
+
name: z3.string().trim().min(1),
|
|
1514
|
+
dataset: z3.string().trim().regex(
|
|
1515
|
+
UUID_PATTERN2,
|
|
1516
|
+
"Raindrop eval suite dataset must be a dataset UUID (not a slug). Use the dataset id shown by list_datasets."
|
|
1517
|
+
),
|
|
1518
|
+
datasetVersionId: z3.string().trim().regex(UUID_PATTERN2).optional(),
|
|
1519
|
+
evaluators: z3.array(
|
|
1520
|
+
z3.object({
|
|
1521
|
+
evaluator: z3.string().trim().min(1),
|
|
1522
|
+
threshold: z3.union([BooleanThresholdSchema, NumericThresholdSchema]).optional()
|
|
1523
|
+
}).strict()
|
|
1524
|
+
).min(1),
|
|
1525
|
+
concurrency: z3.number().int().positive().optional(),
|
|
1526
|
+
traceWaitMs: z3.number().nonnegative().optional(),
|
|
1527
|
+
evalWaitMs: z3.number().nonnegative().optional(),
|
|
1528
|
+
evalPollIntervalMs: z3.number().positive().optional()
|
|
1529
|
+
}).strict();
|
|
1530
|
+
|
|
1531
|
+
// src/evals/definition.ts
|
|
1532
|
+
import { z as z4 } from "zod/v4";
|
|
1533
|
+
var EvalScoreSchema = z4.union([
|
|
1534
|
+
z4.literal(1),
|
|
1535
|
+
z4.literal(2),
|
|
1536
|
+
z4.literal(3),
|
|
1537
|
+
z4.literal(4),
|
|
1538
|
+
z4.literal(5)
|
|
1539
|
+
]);
|
|
1540
|
+
var EvalOutputSchema = z4.enum(["boolean", "score", "number", "preference"]);
|
|
1541
|
+
function defineEvaluatorProgram(program) {
|
|
1542
|
+
var _a, _b, _c, _d;
|
|
1543
|
+
const slug = program.slug.trim();
|
|
1544
|
+
const name = program.name.trim();
|
|
1545
|
+
const source = program.source.trim();
|
|
1546
|
+
const intent = program.intent.trim();
|
|
1547
|
+
if (!/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(slug) || slug.length > 64) {
|
|
1548
|
+
throw new Error(
|
|
1549
|
+
"Raindrop evaluator program slugs must use lowercase letters, numbers, and single hyphens"
|
|
1550
|
+
);
|
|
1551
|
+
}
|
|
1552
|
+
if (!name || name.length > 120) {
|
|
1553
|
+
throw new Error("Raindrop evaluator program names must be between 1 and 120 characters");
|
|
1554
|
+
}
|
|
1555
|
+
if (!source) throw new Error(`Raindrop evaluator program ${slug} source cannot be empty`);
|
|
1556
|
+
if (!intent || intent.length > 1e4) {
|
|
1557
|
+
throw new Error(
|
|
1558
|
+
`Raindrop evaluator program ${slug} intent must be between 1 and 10000 characters`
|
|
1559
|
+
);
|
|
1560
|
+
}
|
|
1561
|
+
if (program.description != null && program.description.trim().length > 2e3) {
|
|
1562
|
+
throw new Error(`Raindrop evaluator program ${slug} description exceeds 2000 characters`);
|
|
1563
|
+
}
|
|
1564
|
+
const rules = (_b = (_a = program.rules) == null ? void 0 : _a.map((rule) => rule.trim())) != null ? _b : [];
|
|
1565
|
+
if (rules.length > 12 || rules.some((rule) => !rule || rule.length > 2e3)) {
|
|
1566
|
+
throw new Error(`Raindrop evaluator program ${slug} rules are invalid`);
|
|
1567
|
+
}
|
|
1568
|
+
if (program.expected && (!z4.string().uuid().safeParse(program.expected.evalId).success || !Number.isInteger(program.expected.programVersion) || program.expected.programVersion <= 0)) {
|
|
1569
|
+
throw new Error(`Raindrop evaluator program ${slug} expected identity is invalid`);
|
|
1570
|
+
}
|
|
1571
|
+
return {
|
|
1572
|
+
...program,
|
|
1573
|
+
kind: "program",
|
|
1574
|
+
scope: z4.literal("trace").parse((_c = program.scope) != null ? _c : "trace"),
|
|
1575
|
+
slug,
|
|
1576
|
+
name,
|
|
1577
|
+
source,
|
|
1578
|
+
intent,
|
|
1579
|
+
description: ((_d = program.description) == null ? void 0 : _d.trim()) || null,
|
|
1580
|
+
rules
|
|
1581
|
+
};
|
|
1582
|
+
}
|
|
1583
|
+
function defineLocalEvaluator(evaluator) {
|
|
1584
|
+
var _a;
|
|
1585
|
+
return { ...evaluator, scope: z4.literal("row").parse((_a = evaluator.scope) != null ? _a : "row") };
|
|
1586
|
+
}
|
|
1587
|
+
var EVAL_DEFINITION = /* @__PURE__ */ Symbol.for("raindrop.evalDefinition");
|
|
1588
|
+
function defineEvalSuite(definition, binding) {
|
|
1589
|
+
if (binding) return createEvalSuite({ ...EvalSuiteManifestSchema.parse(definition), ...binding });
|
|
1590
|
+
if (!("run" in definition) && !("agent" in definition)) {
|
|
1591
|
+
throw new Error("Bind the eval manifest to your local run function or agent");
|
|
1592
|
+
}
|
|
1593
|
+
return createEvalSuite(definition);
|
|
1594
|
+
}
|
|
1595
|
+
function createEvalSuite(definition) {
|
|
1596
|
+
var _a;
|
|
1597
|
+
const name = definition.name.trim();
|
|
1598
|
+
if (name.length === 0) throw new Error("Raindrop eval suite names cannot be empty");
|
|
1599
|
+
const dataset = parseDatasetId(definition.dataset);
|
|
1600
|
+
const datasetVersionId = (_a = definition.datasetVersionId) == null ? void 0 : _a.trim();
|
|
1601
|
+
if (datasetVersionId !== void 0) {
|
|
1602
|
+
if (!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(datasetVersionId)) {
|
|
1603
|
+
throw new Error(
|
|
1604
|
+
`Raindrop eval suite datasetVersionId must be a UUID (got ${JSON.stringify(definition.datasetVersionId)})`
|
|
1605
|
+
);
|
|
1606
|
+
}
|
|
1607
|
+
}
|
|
1608
|
+
if (definition.agent !== void 0 && definition.run !== void 0) {
|
|
1609
|
+
throw new Error("An eval suite accepts either agent or run, not both");
|
|
1610
|
+
}
|
|
1611
|
+
if (definition.agent === void 0 && typeof definition.run !== "function") {
|
|
1612
|
+
throw new Error("Raindrop eval suite run must be a function");
|
|
1613
|
+
}
|
|
1614
|
+
if (!Array.isArray(definition.evaluators) || definition.evaluators.length === 0) {
|
|
1615
|
+
throw new Error("Raindrop eval suites require at least one evaluator");
|
|
1616
|
+
}
|
|
1617
|
+
validateOptionalNumber("concurrency", definition.concurrency, true, false);
|
|
1618
|
+
validateOptionalNumber("traceWaitMs", definition.traceWaitMs, false, true);
|
|
1619
|
+
validateOptionalNumber("evalWaitMs", definition.evalWaitMs, false, true);
|
|
1620
|
+
validateOptionalNumber("evalPollIntervalMs", definition.evalPollIntervalMs, false, false);
|
|
1621
|
+
const evaluators = definition.evaluators.map((evaluator) => validateEvaluator(evaluator));
|
|
1622
|
+
const evaluatorNames = evaluators.map((entry) => evaluatorName(entry));
|
|
1623
|
+
if (new Set(evaluatorNames).size !== evaluatorNames.length) {
|
|
1624
|
+
throw new Error("Raindrop eval suite evaluators must be unique");
|
|
1625
|
+
}
|
|
1626
|
+
const branded = {
|
|
1627
|
+
...definition,
|
|
1628
|
+
[EVAL_DEFINITION]: true,
|
|
1629
|
+
name,
|
|
1630
|
+
dataset,
|
|
1631
|
+
...datasetVersionId !== void 0 ? { datasetVersionId } : {},
|
|
1632
|
+
evaluators
|
|
1633
|
+
};
|
|
1634
|
+
Object.defineProperty(branded, EVAL_DEFINITION, { enumerable: false });
|
|
1635
|
+
return branded;
|
|
1636
|
+
}
|
|
1637
|
+
function isEvalSuiteDefinition(value) {
|
|
1638
|
+
return typeof value === "object" && value !== null && EVAL_DEFINITION in value && value[EVAL_DEFINITION] === true;
|
|
1639
|
+
}
|
|
1640
|
+
function isPublishedEvalSuite(definition) {
|
|
1641
|
+
return definition.datasetVersionId !== void 0 && definition.evaluators.every(
|
|
1642
|
+
({ evaluator }) => typeof evaluator !== "string" && (!("kind" in evaluator) || evaluator.kind !== "program" || evaluator.expected !== void 0)
|
|
1643
|
+
);
|
|
1644
|
+
}
|
|
1645
|
+
function evaluatorName(evaluator) {
|
|
1646
|
+
return typeof evaluator.evaluator === "string" ? evaluator.evaluator.trim() : evaluator.evaluator.slug.trim();
|
|
1647
|
+
}
|
|
1648
|
+
function evaluatorOutput(evaluator) {
|
|
1649
|
+
return typeof evaluator.evaluator === "string" ? void 0 : evaluator.evaluator.output;
|
|
1650
|
+
}
|
|
1651
|
+
function validateEvaluatorOutput(evaluator, rawOutput) {
|
|
1652
|
+
const name = evaluatorName(evaluator);
|
|
1653
|
+
const output = EvalOutputSchema.parse(rawOutput);
|
|
1654
|
+
const localOutput = evaluatorOutput(evaluator);
|
|
1655
|
+
if (localOutput !== void 0 && localOutput !== output) {
|
|
1656
|
+
throw new Error(`Raindrop local evaluator ${name} expected ${localOutput}, received ${output}`);
|
|
1657
|
+
}
|
|
1658
|
+
switch (output) {
|
|
1659
|
+
case "preference":
|
|
1660
|
+
if (evaluator.threshold !== void 0)
|
|
1661
|
+
throw new Error("Preference evaluators do not accept thresholds");
|
|
1662
|
+
break;
|
|
1663
|
+
case "boolean":
|
|
1664
|
+
parseBooleanThreshold(evaluator.threshold);
|
|
1665
|
+
break;
|
|
1666
|
+
case "score":
|
|
1667
|
+
parseNumericThreshold(name, "score", evaluator.threshold);
|
|
1668
|
+
break;
|
|
1669
|
+
case "number":
|
|
1670
|
+
parseNumericThreshold(name, "number", evaluator.threshold);
|
|
1671
|
+
break;
|
|
1672
|
+
}
|
|
1673
|
+
}
|
|
1674
|
+
function validateEvaluator(evaluator) {
|
|
1675
|
+
if (typeof evaluator !== "object" || evaluator === null || !("evaluator" in evaluator)) {
|
|
1676
|
+
throw new Error("Raindrop eval evaluator entries must name an evaluator");
|
|
1677
|
+
}
|
|
1678
|
+
if ("output" in evaluator) {
|
|
1679
|
+
throw new Error(
|
|
1680
|
+
"Raindrop eval evaluator entries do not accept output; the evaluator definition owns it"
|
|
1681
|
+
);
|
|
1682
|
+
}
|
|
1683
|
+
if (typeof evaluator.evaluator !== "string" && (typeof evaluator.evaluator !== "object" || evaluator.evaluator === null || typeof evaluator.evaluator.slug !== "string" || typeof evaluator.evaluator.name !== "string")) {
|
|
1684
|
+
throw new Error("Raindrop local eval evaluators require a slug, name, output, and judge");
|
|
1685
|
+
}
|
|
1686
|
+
const name = evaluatorName(evaluator);
|
|
1687
|
+
if (name.length === 0) throw new Error("Raindrop eval evaluator names cannot be empty");
|
|
1688
|
+
if (typeof evaluator.evaluator === "string") {
|
|
1689
|
+
const threshold = evaluator.threshold;
|
|
1690
|
+
if (threshold !== void 0) {
|
|
1691
|
+
const boolean = BooleanThresholdSchema.safeParse(threshold);
|
|
1692
|
+
const numeric = NumericThresholdSchema.safeParse(threshold);
|
|
1693
|
+
if (!boolean.success && !numeric.success) {
|
|
1694
|
+
throw new Error(`Raindrop hosted evaluator ${name} has an invalid threshold`);
|
|
1695
|
+
}
|
|
1696
|
+
}
|
|
1697
|
+
return { ...evaluator, evaluator: name };
|
|
1698
|
+
}
|
|
1699
|
+
if ("kind" in evaluator.evaluator && evaluator.evaluator.kind === "portable") {
|
|
1700
|
+
validateEvaluatorOutput(evaluator, evaluator.evaluator.output);
|
|
1701
|
+
return evaluator;
|
|
1702
|
+
}
|
|
1703
|
+
if ("kind" in evaluator.evaluator && evaluator.evaluator.kind === "program") {
|
|
1704
|
+
const program = defineEvaluatorProgram(evaluator.evaluator);
|
|
1705
|
+
validateEvaluatorOutput({ ...evaluator, evaluator: program }, program.output);
|
|
1706
|
+
return { ...evaluator, evaluator: program };
|
|
1707
|
+
}
|
|
1708
|
+
if (typeof evaluator.evaluator.judge !== "function") {
|
|
1709
|
+
throw new Error(`Raindrop local evaluator ${name} judge must be a function`);
|
|
1710
|
+
}
|
|
1711
|
+
if (evaluator.evaluator.scope !== "row") {
|
|
1712
|
+
throw new Error(`Raindrop local evaluator ${name} scope must be row`);
|
|
1713
|
+
}
|
|
1714
|
+
const output = EvalOutputSchema.parse(evaluator.evaluator.output);
|
|
1715
|
+
validateEvaluatorOutput(evaluator, output);
|
|
1716
|
+
return evaluator;
|
|
1717
|
+
}
|
|
1718
|
+
function validateOptionalNumber(name, value, integer, allowZero) {
|
|
1719
|
+
if (value === void 0) return;
|
|
1720
|
+
const valid = Number.isFinite(value) && (!integer || Number.isInteger(value)) && (allowZero ? value >= 0 : value > 0);
|
|
1721
|
+
if (!valid) {
|
|
1722
|
+
const kind = integer ? "a positive integer" : allowZero ? "non-negative" : "positive";
|
|
1723
|
+
throw new Error(`Raindrop eval ${name} must be ${kind}`);
|
|
1724
|
+
}
|
|
1725
|
+
}
|
|
1726
|
+
function parseBooleanThreshold(threshold) {
|
|
1727
|
+
return threshold === void 0 ? void 0 : BooleanThresholdSchema.parse(threshold);
|
|
1728
|
+
}
|
|
1729
|
+
function parseNumericThreshold(name, output, threshold) {
|
|
1730
|
+
const parsed = threshold === void 0 ? void 0 : NumericThresholdSchema.parse(threshold);
|
|
1731
|
+
if (output === "score" && parsed) {
|
|
1732
|
+
const lower = "gte" in parsed ? parsed.gte : void 0;
|
|
1733
|
+
const inRange = (lower === void 0 || lower >= 1 && lower <= 5) && (parsed.lte === void 0 || parsed.lte >= 1 && parsed.lte <= 5);
|
|
1734
|
+
if (!inRange)
|
|
1735
|
+
throw new Error(`Raindrop score evaluator ${name} thresholds must be from 1 to 5`);
|
|
1736
|
+
}
|
|
1737
|
+
return parsed;
|
|
1738
|
+
}
|
|
1739
|
+
|
|
1740
|
+
// src/evals/portable.ts
|
|
1741
|
+
import { z as z5 } from "zod/v4";
|
|
1742
|
+
var PortableEvalArtifactSchema = z5.object({
|
|
1743
|
+
format: z5.literal("raindrop.eval-program"),
|
|
1744
|
+
formatVersion: z5.literal(1),
|
|
1745
|
+
runtimeAbi: z5.literal("raindrop-eval-v3"),
|
|
1746
|
+
evaluator: z5.object({
|
|
1747
|
+
id: z5.string().uuid(),
|
|
1748
|
+
slug: z5.string().min(1),
|
|
1749
|
+
programVersion: z5.number().int().positive(),
|
|
1750
|
+
executionMode: z5.enum(["deterministic", "judge"]),
|
|
1751
|
+
outputType: z5.enum(["boolean", "score", "number", "preference"]),
|
|
1752
|
+
scope: z5.literal("trace")
|
|
1753
|
+
}).strict(),
|
|
1754
|
+
traceProjectionVersion: z5.literal(1),
|
|
1755
|
+
// Sent for SDKs before 2.0, which require it. Not read or checked here.
|
|
1756
|
+
traceProjectionSha256: z5.unknown().optional(),
|
|
1757
|
+
source: z5.string().min(1),
|
|
1758
|
+
sha256: z5.string().regex(/^[a-f0-9]{64}$/)
|
|
1759
|
+
}).strict();
|
|
1760
|
+
var PortableEvalLimitsSchema = z5.object({
|
|
1761
|
+
memoryBytes: z5.number().int().positive().optional(),
|
|
1762
|
+
stackBytes: z5.number().int().positive().optional(),
|
|
1763
|
+
timeoutMs: z5.number().int().positive().max(2147483647).optional(),
|
|
1764
|
+
maxInputBytes: z5.number().int().positive().optional(),
|
|
1765
|
+
maxOutputBytes: z5.number().int().positive().optional(),
|
|
1766
|
+
judgeTimeoutMs: z5.number().int().positive().max(2147483647).optional(),
|
|
1767
|
+
judgeConcurrency: z5.number().int().positive().optional()
|
|
1768
|
+
}).readonly();
|
|
1769
|
+
var PortableEvalResultSchema = z5.object({
|
|
1770
|
+
outcomes: z5.array(
|
|
1771
|
+
z5.union([
|
|
1772
|
+
z5.object({
|
|
1773
|
+
state: z5.literal("graded"),
|
|
1774
|
+
traceId: z5.string(),
|
|
1775
|
+
pass: z5.boolean(),
|
|
1776
|
+
note: z5.string().optional()
|
|
1777
|
+
}),
|
|
1778
|
+
z5.object({
|
|
1779
|
+
state: z5.literal("graded"),
|
|
1780
|
+
traceId: z5.string(),
|
|
1781
|
+
score: EvalScoreSchema,
|
|
1782
|
+
note: z5.string().optional()
|
|
1783
|
+
}),
|
|
1784
|
+
z5.object({
|
|
1785
|
+
state: z5.literal("graded"),
|
|
1786
|
+
traceId: z5.string(),
|
|
1787
|
+
value: z5.number().finite(),
|
|
1788
|
+
note: z5.string().optional()
|
|
1789
|
+
}),
|
|
1790
|
+
z5.object({
|
|
1791
|
+
state: z5.literal("graded"),
|
|
1792
|
+
traceId: z5.string(),
|
|
1793
|
+
preference: z5.enum(["A", "B", "tie"]),
|
|
1794
|
+
note: z5.string().optional()
|
|
1795
|
+
}),
|
|
1796
|
+
z5.object({ state: z5.literal("errored"), traceId: z5.string(), message: z5.string() }),
|
|
1797
|
+
z5.object({
|
|
1798
|
+
state: z5.literal("ungraded"),
|
|
1799
|
+
traceId: z5.string(),
|
|
1800
|
+
reason: z5.enum(["not sampled", "trace unavailable", "content unreadable"])
|
|
1801
|
+
})
|
|
1802
|
+
])
|
|
1803
|
+
),
|
|
1804
|
+
failures: z5.array(z5.string()),
|
|
1805
|
+
stats: z5.object({
|
|
1806
|
+
traceCount: z5.number().int().nonnegative(),
|
|
1807
|
+
hydratedCount: z5.number().int().nonnegative(),
|
|
1808
|
+
judgeCalls: z5.number().int().nonnegative(),
|
|
1809
|
+
durationMs: z5.number().nonnegative(),
|
|
1810
|
+
skippedRows: z5.number().int().nonnegative(),
|
|
1811
|
+
skippedReason: z5.literal("no trace").nullable()
|
|
1812
|
+
})
|
|
1813
|
+
});
|
|
1814
|
+
function parsePortableEvalResult(value) {
|
|
1815
|
+
return PortableEvalResultSchema.parse(value);
|
|
1816
|
+
}
|
|
1817
|
+
function importPortableEvaluator(rawArtifact, options = {}) {
|
|
1818
|
+
var _a;
|
|
1819
|
+
const artifact = PortableEvalArtifactSchema.parse(rawArtifact);
|
|
1820
|
+
if (options.expectedSha256 && !/^[a-f0-9]{64}$/.test(options.expectedSha256)) {
|
|
1821
|
+
throw new Error(
|
|
1822
|
+
"Raindrop portable evaluator expectedSha256 must be a lowercase SHA-256 digest"
|
|
1823
|
+
);
|
|
1824
|
+
}
|
|
1825
|
+
return {
|
|
1826
|
+
kind: "portable",
|
|
1827
|
+
artifact,
|
|
1828
|
+
expectedSha256: options.expectedSha256,
|
|
1829
|
+
judge: options.judge,
|
|
1830
|
+
limits: options.limits === void 0 ? void 0 : PortableEvalLimitsSchema.parse(options.limits),
|
|
1831
|
+
slug: artifact.evaluator.slug,
|
|
1832
|
+
name: ((_a = options.name) == null ? void 0 : _a.trim()) || artifact.evaluator.slug,
|
|
1833
|
+
output: artifact.evaluator.outputType,
|
|
1834
|
+
scope: artifact.evaluator.scope
|
|
1835
|
+
};
|
|
1836
|
+
}
|
|
1837
|
+
async function evaluatePortableEvaluator(evaluator, input) {
|
|
1838
|
+
var _a;
|
|
1839
|
+
const artifact = await verifyPortableEvalArtifact(evaluator.artifact, {
|
|
1840
|
+
expectedSha256: evaluator.expectedSha256
|
|
1841
|
+
});
|
|
1842
|
+
if (new Set(input.traces.map((trace) => trace.event.id)).size !== input.traces.length) {
|
|
1843
|
+
throw new Error("Raindrop portable evaluator input trace ids must be unique");
|
|
1844
|
+
}
|
|
1845
|
+
const { runPortableEvaluator } = await import("./portable-runtime-G27RYK6P.mjs");
|
|
1846
|
+
const rows = (_a = input.rows) != null ? _a : [];
|
|
1847
|
+
if (rows.length > 0 && (rows.length !== input.traces.length || rows.some(
|
|
1848
|
+
(entry, index) => {
|
|
1849
|
+
var _a2;
|
|
1850
|
+
return entry.candidate.trace.event.id !== ((_a2 = input.traces[index]) == null ? void 0 : _a2.event.id);
|
|
1851
|
+
}
|
|
1852
|
+
))) {
|
|
1853
|
+
throw new Error("Raindrop portable evaluator rows must match traces exactly, in slice order");
|
|
1854
|
+
}
|
|
1855
|
+
const result = await runPortableEvaluator(evaluator, { ...input, rows });
|
|
1856
|
+
validatePortableResult(artifact, input.traces, result);
|
|
1857
|
+
return result;
|
|
1858
|
+
}
|
|
1859
|
+
async function verifyPortableEvalArtifact(rawArtifact, options = {}) {
|
|
1860
|
+
const artifact = PortableEvalArtifactSchema.parse(rawArtifact);
|
|
1861
|
+
const digest = await artifactDigest(artifact);
|
|
1862
|
+
if (digest !== artifact.sha256) {
|
|
1863
|
+
throw new Error(
|
|
1864
|
+
`Raindrop portable evaluator ${artifact.evaluator.slug} content digest is invalid`
|
|
1865
|
+
);
|
|
1866
|
+
}
|
|
1867
|
+
if (options.expectedSha256 && digest !== options.expectedSha256) {
|
|
1868
|
+
throw new Error(
|
|
1869
|
+
`Raindrop portable evaluator ${artifact.evaluator.slug} does not match expectedSha256`
|
|
1870
|
+
);
|
|
1871
|
+
}
|
|
1872
|
+
return artifact;
|
|
1873
|
+
}
|
|
1874
|
+
function validatePortableResult(artifact, traces, result) {
|
|
1875
|
+
if (result.stats.traceCount !== traces.length) {
|
|
1876
|
+
throw new Error("Raindrop portable evaluator returned an inconsistent trace count");
|
|
1877
|
+
}
|
|
1878
|
+
const expected = new Set(traces.map((trace) => trace.event.id));
|
|
1879
|
+
const returned = /* @__PURE__ */ new Set();
|
|
1880
|
+
for (const outcome of result.outcomes) {
|
|
1881
|
+
if (!expected.has(outcome.traceId)) {
|
|
1882
|
+
throw new Error(`Raindrop portable evaluator returned foreign trace ${outcome.traceId}`);
|
|
1883
|
+
}
|
|
1884
|
+
if (returned.has(outcome.traceId)) {
|
|
1885
|
+
throw new Error(`Raindrop portable evaluator repeated trace ${outcome.traceId}`);
|
|
1886
|
+
}
|
|
1887
|
+
returned.add(outcome.traceId);
|
|
1888
|
+
if (outcome.state !== "graded") continue;
|
|
1889
|
+
const valid = artifact.evaluator.outputType === "boolean" ? "pass" in outcome : artifact.evaluator.outputType === "score" ? "score" in outcome : artifact.evaluator.outputType === "preference" ? "preference" in outcome : "value" in outcome;
|
|
1890
|
+
if (!valid) {
|
|
1891
|
+
throw new Error(
|
|
1892
|
+
`Raindrop portable evaluator ${artifact.evaluator.slug} returned the wrong graded value`
|
|
1893
|
+
);
|
|
1894
|
+
}
|
|
1895
|
+
}
|
|
1896
|
+
const missing = [...expected].find((traceId) => !returned.has(traceId));
|
|
1897
|
+
if (missing) throw new Error(`Raindrop portable evaluator omitted trace ${missing}`);
|
|
1898
|
+
}
|
|
1899
|
+
async function artifactDigest(artifact) {
|
|
1900
|
+
var _a;
|
|
1901
|
+
if (!((_a = globalThis.crypto) == null ? void 0 : _a.subtle)) {
|
|
1902
|
+
throw new Error("Raindrop portable evaluator requires Web Crypto SHA-256 support");
|
|
1903
|
+
}
|
|
1904
|
+
const { sha256: _digest, ...unsigned } = artifact;
|
|
1905
|
+
const encoded = new TextEncoder().encode(canonicalJson(unsigned));
|
|
1906
|
+
const digest = await globalThis.crypto.subtle.digest("SHA-256", encoded);
|
|
1907
|
+
return [...new Uint8Array(digest)].map((byte) => byte.toString(16).padStart(2, "0")).join("");
|
|
1908
|
+
}
|
|
1909
|
+
function canonicalJson(value) {
|
|
1910
|
+
if (value === null || typeof value !== "object") return JSON.stringify(value);
|
|
1911
|
+
if (Array.isArray(value)) return `[${value.map(canonicalJson).join(",")}]`;
|
|
1912
|
+
return `{${Object.entries(value).sort(([left], [right]) => left.localeCompare(right)).map(([key, entry]) => `${JSON.stringify(key)}:${canonicalJson(entry)}`).join(",")}}`;
|
|
1913
|
+
}
|
|
1914
|
+
|
|
1915
|
+
export {
|
|
1916
|
+
credentialEndpoint,
|
|
1917
|
+
replayIngestEndpoint,
|
|
1918
|
+
TraceSchema,
|
|
1919
|
+
EvalContextSchema,
|
|
1920
|
+
EvalRowTracePairSchema,
|
|
1921
|
+
projectWorkshopTrace,
|
|
1922
|
+
formatTrace,
|
|
1923
|
+
traceOutput,
|
|
1924
|
+
traceToolCalls,
|
|
1925
|
+
DatasetIdSchema,
|
|
1926
|
+
isDatasetId,
|
|
1927
|
+
parseDatasetId,
|
|
1928
|
+
ReplayMessageToolCallSchema,
|
|
1929
|
+
ReplayMessageContentPartSchema,
|
|
1930
|
+
ReplayMessageSchema,
|
|
1931
|
+
DatasetColumnSchema,
|
|
1932
|
+
ReferenceOutputSourceSchema,
|
|
1933
|
+
ReferenceOutputSchema,
|
|
1934
|
+
DatasetRowSchema,
|
|
1935
|
+
readDataset,
|
|
1936
|
+
BooleanThresholdSchema,
|
|
1937
|
+
NumericThresholdSchema,
|
|
1938
|
+
EvalSuiteManifestSchema,
|
|
1939
|
+
EvalScoreSchema,
|
|
1940
|
+
defineEvaluatorProgram,
|
|
1941
|
+
defineLocalEvaluator,
|
|
1942
|
+
defineEvalSuite,
|
|
1943
|
+
isEvalSuiteDefinition,
|
|
1944
|
+
isPublishedEvalSuite,
|
|
1945
|
+
evaluatorName,
|
|
1946
|
+
evaluatorOutput,
|
|
1947
|
+
validateEvaluatorOutput,
|
|
1948
|
+
PortableEvalLimitsSchema,
|
|
1949
|
+
parsePortableEvalResult,
|
|
1950
|
+
importPortableEvaluator,
|
|
1951
|
+
evaluatePortableEvaluator,
|
|
1952
|
+
verifyPortableEvalArtifact
|
|
1953
|
+
};
|