raindrop-ai 1.1.1 → 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.
@@ -1,4799 +0,0 @@
1
- import {
2
- APP_BRANCH,
3
- APP_COMMIT_DIRTY,
4
- APP_COMMIT_SHA,
5
- DEFAULT_REQUEST_TIMEOUT_MS,
6
- DELIVERED,
7
- EVAL_CORRELATION_ID_ATTRIBUTE,
8
- EventShipper2,
9
- InFlightCutOff,
10
- POST_SHUTDOWN_TIMEOUT_MS,
11
- PiiFieldRedactor,
12
- asCompat,
13
- authHintForKey,
14
- awaitEarlierSends,
15
- capText,
16
- combineResults,
17
- createAppGitContext,
18
- currentEvalScope,
19
- currentReplayTraceDestination,
20
- currentRoutingBinding,
21
- describeUndelivered,
22
- evalScopeAttributes,
23
- fateOf,
24
- isMissingUserId,
25
- localDebuggerEnabled,
26
- maskPayload,
27
- normalizeFeatureFlags,
28
- normalizeProjectId,
29
- package_default,
30
- piiRedaction,
31
- piiRedactionNow,
32
- projectIdHeaders,
33
- raceWithTimeout,
34
- randomUUID,
35
- rateLimitedLog,
36
- redactUrlForLog,
37
- resolveFlushTimeoutMs,
38
- resolveLocalDebuggerBaseUrl,
39
- resolveMaxTextFieldChars,
40
- runWithTracingSuppressed,
41
- sendJson,
42
- setDefaultMaxTextFieldChars,
43
- snapshotPayload,
44
- summarize2,
45
- tracing,
46
- validAppCommitSha,
47
- withAppGitProperties,
48
- withEvalScope,
49
- withReplayTraceDestination,
50
- withRoutingContext,
51
- withTask
52
- } from "./chunk-7HPYMPNJ.mjs";
53
- import {
54
- AiTrackEventSchema,
55
- AttachmentSchema,
56
- CapturedTraceSnapshotSchema,
57
- EvalCaseExpectationSchema,
58
- EvalCaseTracePairSchema,
59
- EvalDatasetCaseIdSchema,
60
- EvalScoreSchema,
61
- IdentifySchema,
62
- JsonValueSchema,
63
- SignalEventSchema,
64
- TrackEventSchema,
65
- defineDataset,
66
- defineEvalSuite,
67
- defineEvaluatorProgram,
68
- evaluatorName,
69
- evaluatorOutput,
70
- importPortableEvaluator,
71
- isEvalDataset,
72
- isEvalSuiteDefinition,
73
- isPublishedEvalSuite,
74
- stringRecord,
75
- stringRecord2,
76
- traceOutput,
77
- traceToolCalls,
78
- validateEvaluatorOutput,
79
- verifyPortableEvalArtifact
80
- } from "./chunk-6575YF3B.mjs";
81
-
82
- // src/lib/env.ts
83
- var detectRuntime = () => {
84
- if (typeof process === "object" && process && typeof process.env === "object" && process.env && typeof process.version === "string") {
85
- return "node";
86
- }
87
- if (typeof window === "object") {
88
- return "browser";
89
- }
90
- if (typeof WebSocketPair !== "undefined") {
91
- return "cloudflare-worker";
92
- }
93
- if (typeof EdgeRuntime === "string") {
94
- return "vercel-edge";
95
- }
96
- if (
97
- // @ts-ignore
98
- typeof WorkerGlobalScope !== "undefined" && // @ts-ignore
99
- typeof importScripts === "function"
100
- ) {
101
- return "web-worker";
102
- }
103
- return "unknown";
104
- };
105
-
106
- // src/types.ts
107
- import { z } from "zod/v4";
108
- var ClientTrack = TrackEventSchema.extend({
109
- received_at: z.undefined().optional()
110
- // not sent from client
111
- });
112
- var ClientAiTrack = AiTrackEventSchema.extend({
113
- received_at: z.undefined().optional()
114
- // not sent from client
115
- });
116
- var PartialClientAiTrack = ClientAiTrack.extend({
117
- is_pending: z.boolean().optional(),
118
- ai_data: z.object({
119
- input: z.string().optional().nullable(),
120
- output: z.string().optional().nullable(),
121
- model: z.string().optional().nullable(),
122
- convo_id: z.string().optional().nullable()
123
- }).optional()
124
- });
125
- var AiTrackUsageSchema = z.object({
126
- provider: z.string().trim().min(1),
127
- inputTokens: z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER),
128
- outputTokens: z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER),
129
- cacheReadTokens: z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER).optional(),
130
- cacheWriteTokens: z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER).optional(),
131
- reasoningTokens: z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER).optional(),
132
- providerReportedCost: z.number().finite().nonnegative().optional()
133
- });
134
- var AttachmentTypeSchema = z.enum(["code", "text", "image", "iframe"]);
135
-
136
- // src/replay/index.ts
137
- import { context, trace } from "@opentelemetry/api";
138
- import { z as z4 } from "zod/v4";
139
-
140
- // src/evals/generated/dataset.ts
141
- import { z as z2 } from "zod/v4";
142
- var EVAL_DATASET_MAX_CASES = 1e3;
143
- var EVAL_DATASET_MAX_REQUEST_BYTES = 4 * 1024 * 1024;
144
- var EVAL_DATASET_MAX_REFERENCE_BYTES = 1024 * 1024;
145
- var EvalDatasetSlugSchema = z2.string().min(1).max(64).regex(/^[a-z0-9]+(-[a-z0-9]+)*$/);
146
- var EvalDatasetFingerprintSchema = z2.string().regex(/^[0-9a-f]{64}$/);
147
- var EvalDatasetEventSourceSchema = z2.object({
148
- sourceEventId: z2.string().trim().min(1).max(512),
149
- sourceEventTimestamp: z2.string().datetime({ offset: true }).optional()
150
- }).strict();
151
- var EvalDatasetCaptureRefSchema = EvalDatasetEventSourceSchema.extend({
152
- id: EvalDatasetFingerprintSchema
153
- }).strict();
154
- var EvalReferenceVerdictSchema = z2.union([
155
- z2.object({ pass: z2.boolean() }).strict(),
156
- z2.object({ score: z2.number().int().min(1).max(5) }).strict(),
157
- z2.object({ value: z2.number().finite() }).strict()
158
- ]);
159
- var EvalDatasetCaseInputSchema = z2.object({
160
- id: EvalDatasetCaseIdSchema,
161
- name: z2.string().trim().min(1).max(200),
162
- input: z2.string().nullable(),
163
- output: JsonValueSchema.optional(),
164
- properties: stringRecord2(z2.string()),
165
- referenceTrace: CapturedTraceSnapshotSchema.optional(),
166
- referenceCapture: EvalDatasetCaptureRefSchema.optional(),
167
- expectation: EvalCaseExpectationSchema.optional(),
168
- expectedVerdict: EvalReferenceVerdictSchema.optional()
169
- }).strict();
170
- var EvalDatasetVersionCaseSchema = EvalDatasetCaseInputSchema.extend({
171
- referenceTraceSha256: EvalDatasetFingerprintSchema.optional()
172
- });
173
- var EvalDatasetCaseInputsSchema = z2.array(EvalDatasetCaseInputSchema).min(1).max(EVAL_DATASET_MAX_CASES).superRefine((cases, context2) => {
174
- const seen = /* @__PURE__ */ new Set();
175
- for (const [index, entry] of cases.entries()) {
176
- if (seen.has(entry.id)) {
177
- context2.addIssue({
178
- code: z2.ZodIssueCode.custom,
179
- message: `Duplicate row id ${entry.id}`,
180
- path: [index, "id"]
181
- });
182
- }
183
- seen.add(entry.id);
184
- }
185
- });
186
- var PublishEvalDatasetVersionInputSchema = z2.object({
187
- name: z2.string().trim().min(1).max(100),
188
- requestKey: z2.string().uuid(),
189
- expectedCurrentVersionId: z2.string().uuid().nullable(),
190
- fingerprint: EvalDatasetFingerprintSchema,
191
- cases: EvalDatasetCaseInputsSchema
192
- }).strict();
193
- var CaptureEvalDatasetCaseSchema = EvalDatasetCaseInputSchema.pick({
194
- id: true,
195
- name: true,
196
- properties: true,
197
- expectation: true,
198
- expectedVerdict: true
199
- }).merge(EvalDatasetEventSourceSchema).strict();
200
- var CaptureEvalDatasetVersionInputSchema = PublishEvalDatasetVersionInputSchema.omit({
201
- cases: true,
202
- fingerprint: true
203
- }).extend({
204
- requestKey: z2.string().uuid().optional(),
205
- expectedCurrentVersionId: z2.string().uuid().nullable().optional(),
206
- cases: z2.array(CaptureEvalDatasetCaseSchema).min(1).max(EVAL_DATASET_MAX_CASES).refine((cases) => new Set(cases.map((entry) => entry.id)).size === cases.length, "Case IDs must be unique")
207
- }).strict();
208
- var EvalDatasetIdentitySchema = z2.object({
209
- id: z2.string().uuid(),
210
- slug: EvalDatasetSlugSchema,
211
- name: z2.string().min(1).max(100),
212
- currentVersionId: z2.string().uuid().nullable()
213
- });
214
- var EvalDatasetVersionSchema = z2.object({
215
- id: z2.string().uuid(),
216
- datasetId: z2.string().uuid(),
217
- parentVersionId: z2.string().uuid().nullable(),
218
- fingerprint: EvalDatasetFingerprintSchema,
219
- cases: z2.array(EvalDatasetVersionCaseSchema).min(1).max(EVAL_DATASET_MAX_CASES),
220
- createdAt: z2.string().datetime({ offset: true })
221
- });
222
- var EvalDatasetManifestSchema = z2.object({
223
- dataset: EvalDatasetIdentitySchema,
224
- version: EvalDatasetVersionSchema.omit({ cases: true }),
225
- cases: z2.array(EvalDatasetVersionCaseSchema.pick({
226
- id: true,
227
- name: true,
228
- input: true,
229
- output: true,
230
- properties: true
231
- }).extend({
232
- referenceTraceSha256: EvalDatasetFingerprintSchema.optional(),
233
- referenceCapture: EvalDatasetCaptureRefSchema.optional(),
234
- expectation: EvalCaseExpectationSchema.optional(),
235
- expectedVerdict: EvalReferenceVerdictSchema.optional()
236
- }))
237
- });
238
- function compareNanoseconds(left, right) {
239
- const leftValue = BigInt(left);
240
- const rightValue = BigInt(right);
241
- return leftValue < rightValue ? -1 : leftValue > rightValue ? 1 : 0;
242
- }
243
- function orderSnapshot(snapshot) {
244
- return {
245
- event: snapshot.event,
246
- spans: [...snapshot.spans].sort((left, right) => compareNanoseconds(left.start_unix_ns, right.start_unix_ns) || left.span_id.localeCompare(right.span_id))
247
- };
248
- }
249
- function normalizeCasesForFingerprint(cases) {
250
- return cases.map((entry) => entry.referenceTrace === void 0 ? entry : {
251
- ...entry,
252
- referenceTrace: orderSnapshot(entry.referenceTrace)
253
- });
254
- }
255
- function stableStringify(value) {
256
- if (value === null || typeof value !== "object") return JSON.stringify(value);
257
- if (Array.isArray(value)) return `[${value.map(stableStringify).join(",")}]`;
258
- return `{${Object.entries(value).sort(([left], [right]) => left < right ? -1 : left > right ? 1 : 0).map(([key, entry]) => `${JSON.stringify(key)}:${stableStringify(entry)}`).join(",")}}`;
259
- }
260
- function canonicalJson(value) {
261
- return stableStringify(JSON.parse(JSON.stringify(value)));
262
- }
263
- async function sha256(value) {
264
- var _a;
265
- if (!((_a = globalThis.crypto) == null ? void 0 : _a.subtle)) {
266
- throw new Error("Raindrop eval dataset publication requires Web Crypto SHA-256 support");
267
- }
268
- const digest = await globalThis.crypto.subtle.digest("SHA-256", new TextEncoder().encode(value));
269
- return [...new Uint8Array(digest)].map((byte) => byte.toString(16).padStart(2, "0")).join("");
270
- }
271
- async function evalDatasetVersionFingerprint(cases) {
272
- const parsed = EvalDatasetCaseInputsSchema.parse(cases);
273
- return sha256(canonicalJson(normalizeCasesForFingerprint(parsed)));
274
- }
275
-
276
- // src/evals/generated/simulation.ts
277
- import { z as z3 } from "zod/v4";
278
- var EvalOutputTypeSchema = z3.enum(["boolean", "score", "number", "preference"]);
279
- var PreferenceValueSchema = z3.enum(["A", "B", "tie"]);
280
- var TraceIdSchema = z3.string().min(1).max(200);
281
- var OutcomeNoteSchema = z3.string().trim().min(1).max(600);
282
- var FailureMessageSchema = z3.string().trim().min(1).max(600);
283
- var ScoreValueSchema = z3.union([
284
- z3.literal(1),
285
- z3.literal(2),
286
- z3.literal(3),
287
- z3.literal(4),
288
- z3.literal(5)
289
- ]);
290
- var ErroredOutcomeSchema = z3.object({
291
- state: z3.literal("errored"),
292
- traceId: TraceIdSchema,
293
- message: FailureMessageSchema
294
- });
295
- var UngradedOutcomeSchema = z3.object({
296
- state: z3.literal("ungraded"),
297
- traceId: TraceIdSchema,
298
- reason: z3.enum(["not sampled", "trace unavailable", "content unreadable"])
299
- });
300
- var GradedBaseSchema = z3.object({
301
- state: z3.literal("graded"),
302
- traceId: TraceIdSchema,
303
- note: OutcomeNoteSchema.optional()
304
- });
305
- var BooleanOutcomeSchema = z3.discriminatedUnion("state", [
306
- GradedBaseSchema.extend({ pass: z3.boolean() }),
307
- ErroredOutcomeSchema,
308
- UngradedOutcomeSchema
309
- ]);
310
- var ScoreOutcomeSchema = z3.discriminatedUnion("state", [
311
- GradedBaseSchema.extend({ score: ScoreValueSchema }),
312
- ErroredOutcomeSchema,
313
- UngradedOutcomeSchema
314
- ]);
315
- var NumberOutcomeSchema = z3.discriminatedUnion("state", [
316
- GradedBaseSchema.extend({ value: z3.number().finite() }),
317
- ErroredOutcomeSchema,
318
- UngradedOutcomeSchema
319
- ]);
320
- var PreferenceOutcomeSchema = z3.discriminatedUnion("state", [
321
- GradedBaseSchema.extend({ preference: PreferenceValueSchema }),
322
- ErroredOutcomeSchema,
323
- UngradedOutcomeSchema
324
- ]);
325
- var EvalOutcomeSchema = z3.union([
326
- BooleanOutcomeSchema,
327
- ScoreOutcomeSchema,
328
- NumberOutcomeSchema,
329
- PreferenceOutcomeSchema
330
- ]);
331
- var SIMULATION_RESULT_PAGE_SIZE = 100;
332
- var SimulationEvalResultsQuerySchema = z3.object({
333
- offset: z3.coerce.number().int().min(0).max(Number.MAX_SAFE_INTEGER).default(0)
334
- });
335
- var SimulationEvalResultPageSchema = z3.object({
336
- executionId: z3.string().uuid(),
337
- evalId: z3.string().uuid(),
338
- runId: z3.string().uuid(),
339
- offset: z3.number().int().nonnegative(),
340
- outcomes: z3.array(EvalOutcomeSchema).max(SIMULATION_RESULT_PAGE_SIZE),
341
- failures: z3.array(FailureMessageSchema).max(SIMULATION_RESULT_PAGE_SIZE),
342
- nextOffset: z3.number().int().nonnegative().nullable()
343
- });
344
- var EvalExecutionPinsSchema = z3.object({
345
- datasetVersionId: z3.string().uuid(),
346
- datasetFingerprint: z3.string().regex(/^[a-f0-9]{64}$/),
347
- evaluators: z3.array(z3.object({
348
- evalId: z3.string().uuid(),
349
- programVersion: z3.number().int().positive()
350
- }).strict()).min(1).max(20).refine((pins) => new Set(pins.map((pin) => pin.evalId)).size === pins.length, "Evaluator pins must be unique")
351
- }).strict();
352
- var SimulationRevisionSchema = z3.object({
353
- worldVersionId: z3.string().uuid().optional(),
354
- commitSha: z3.string().regex(/^[0-9a-f]{40}$/).optional(),
355
- requestKey: z3.string().trim().min(1).max(200).optional()
356
- });
357
- var SimulationEvalRequestSchema = z3.union([
358
- SimulationRevisionSchema.extend({
359
- datasetId: z3.string().uuid(),
360
- worldId: z3.string().uuid(),
361
- pins: EvalExecutionPinsSchema
362
- }).strict(),
363
- SimulationRevisionSchema.extend({
364
- evals: z3.array(z3.string().trim().min(1)).min(1).max(20),
365
- worldId: z3.string().uuid(),
366
- datasetId: z3.string().uuid().optional()
367
- }).strict(),
368
- SimulationRevisionSchema.extend({
369
- eval: z3.string().trim().min(1),
370
- worldId: z3.string().uuid(),
371
- datasetId: z3.string().uuid().optional(),
372
- programVersion: z3.number().int().positive().optional()
373
- }).strict(),
374
- SimulationRevisionSchema.pick({ commitSha: true, requestKey: true }).extend({
375
- baselineExecutionId: z3.string().uuid()
376
- }).strict()
377
- ]);
378
- var SimulationEvalExecutionSchema = z3.object({
379
- id: z3.string().uuid(),
380
- status: z3.enum(["queued", "executing", "grading", "completed", "failed"]),
381
- error: z3.string().nullable(),
382
- datasetId: z3.string().uuid(),
383
- datasetVersionId: z3.string().uuid(),
384
- datasetFingerprint: z3.string(),
385
- worldId: z3.string().uuid(),
386
- worldVersionId: z3.string().uuid(),
387
- commitSha: z3.string(),
388
- agent: z3.string(),
389
- cases: z3.array(z3.object({
390
- caseId: z3.string(),
391
- replayId: z3.string().uuid(),
392
- runId: z3.string().uuid().nullable()
393
- })),
394
- evaluations: z3.array(z3.object({
395
- evalId: z3.string().uuid(),
396
- slug: z3.string(),
397
- outputType: EvalOutputTypeSchema,
398
- programVersion: z3.number().int().positive(),
399
- runId: z3.string().uuid(),
400
- status: z3.enum(["queued", "running", "completed", "failed"]),
401
- error: z3.string().nullable(),
402
- outcomeCount: z3.number().int().nonnegative(),
403
- failureCount: z3.number().int().nonnegative()
404
- }))
405
- });
406
-
407
- // src/evals/trace-pair.ts
408
- var EvalCaseTracePairSchema2 = EvalCaseTracePairSchema.extend({
409
- reference: EvalCaseTracePairSchema.shape.reference.unwrap().extend({
410
- snapshot: CapturedTraceSnapshotSchema.optional()
411
- }).optional()
412
- });
413
-
414
- // src/replay/endpoint.ts
415
- function credentialEndpoint(value) {
416
- const url = new URL(value);
417
- const loopback = ["localhost", "127.0.0.1", "[::1]"].includes(url.hostname);
418
- if (url.protocol !== "https:" && !(url.protocol === "http:" && loopback)) {
419
- throw new Error("Raindrop endpoints require HTTPS, except on loopback hosts");
420
- }
421
- if (url.username || url.password || url.search || url.hash) {
422
- throw new Error("Raindrop endpoints cannot contain credentials, a query, or a fragment");
423
- }
424
- return url;
425
- }
426
- function replayIngestEndpoint(value, trustedUrl) {
427
- const url = credentialEndpoint(value);
428
- if (!trustedUrl && url.href.replace(/\/+$/, "") === "https://app.raindrop.ai/api/replays/ingest") {
429
- url.hostname = "backend.raindrop.ai";
430
- }
431
- const trusted = credentialEndpoint(trustedUrl != null ? trustedUrl : "https://backend.raindrop.ai/api/replays/ingest/");
432
- if (url.href.replace(/\/+$/, "") !== trusted.href.replace(/\/+$/, "")) {
433
- throw new Error("Raindrop replay ingest URL does not match the trusted replayIngestUrl");
434
- }
435
- return url.href;
436
- }
437
-
438
- // src/replay/index.ts
439
- var DEFAULT_QUERY_URL = "https://query.raindrop.ai";
440
- var DEFAULT_TRACE_WAIT_MS = 6e4;
441
- var DEFAULT_EVAL_WAIT_MS = 10 * 6e4;
442
- var DEFAULT_EVAL_POLL_INTERVAL_MS = 2e3;
443
- var MAX_EVAL_STATUS_RETRIES = 2;
444
- var TRACE_POLL_INTERVAL_MS = 500;
445
- var DEFAULT_CONCURRENCY = 4;
446
- var EVAL_RETRY_BASE_DELAY_MS = 50;
447
- var MAX_REPLAY_REPORT_RETRIES = 2;
448
- var QUERY_REQUEST_TIMEOUT_MS = 3e4;
449
- var LOCAL_EVALUATOR_SLUG_PATTERN = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
450
- function retryDelayMs(response, retry) {
451
- const retryAfter = response.headers.get("retry-after");
452
- if (retryAfter !== null) {
453
- const seconds = Number(retryAfter);
454
- if (Number.isFinite(seconds) && seconds >= 0) return seconds * 1e3;
455
- }
456
- return EVAL_RETRY_BASE_DELAY_MS * 2 ** retry;
457
- }
458
- var ReplayRowSchema = z4.object({
459
- id: z4.string(),
460
- name: z4.string(),
461
- input: z4.string().nullable(),
462
- output: JsonValueSchema,
463
- properties: stringRecord(z4.string())
464
- });
465
- var WireEvalManifestSchema = z4.object({
466
- dataset_id: z4.string().uuid(),
467
- dataset_version_id: z4.string().uuid().optional(),
468
- fingerprint: z4.string().regex(/^[a-f0-9]{64}$/),
469
- rows: z4.array(ReplayRowSchema.extend({ id: z4.string().min(1) }))
470
- });
471
- var EvalDatasetManifestReadSchema = EvalDatasetManifestSchema.extend({
472
- cases: z4.array(
473
- z4.object({
474
- ...EvalDatasetManifestSchema.shape.cases.element.shape,
475
- referenceCapture: z4.object(EvalDatasetCaptureRefSchema.shape).optional(),
476
- expectation: z4.object(EvalCaseExpectationSchema.shape).optional(),
477
- expectedVerdict: z4.union([
478
- z4.object({ pass: z4.boolean() }),
479
- z4.object({ score: z4.number().int().min(1).max(5) }),
480
- z4.object({ value: z4.number().finite() }),
481
- z4.object({ preference: PreferenceValueSchema })
482
- ]).optional().catch(void 0)
483
- })
484
- )
485
- });
486
- var ReplayCountsSchema = z4.object({
487
- total: z4.number(),
488
- pending: z4.number(),
489
- done: z4.number(),
490
- missing: z4.number()
491
- });
492
- var ReplayEvaluatorCountsSchema = z4.object({
493
- traces: z4.number(),
494
- graded: z4.number(),
495
- errored: z4.number(),
496
- ungraded: z4.number(),
497
- pending: z4.number()
498
- });
499
- var ReplayEvaluatorStatsSchema = z4.object({
500
- traceCount: z4.number(),
501
- hydratedCount: z4.number(),
502
- judgeCalls: z4.number(),
503
- durationMs: z4.number(),
504
- skippedRows: z4.number(),
505
- skippedReason: z4.literal("no trace").nullable()
506
- });
507
- var ReplayEvaluatorSummarySchema = z4.discriminatedUnion("outputType", [
508
- z4.object({
509
- outputType: z4.literal("preference"),
510
- counts: ReplayEvaluatorCountsSchema,
511
- stats: ReplayEvaluatorStatsSchema,
512
- preferences: z4.object({ A: z4.number(), B: z4.number(), tie: z4.number() })
513
- }),
514
- z4.object({
515
- outputType: z4.literal("boolean"),
516
- counts: ReplayEvaluatorCountsSchema,
517
- stats: ReplayEvaluatorStatsSchema,
518
- passed: z4.number(),
519
- failed: z4.number(),
520
- passRate: z4.number().nullable()
521
- }),
522
- z4.object({
523
- outputType: z4.literal("score"),
524
- counts: ReplayEvaluatorCountsSchema,
525
- stats: ReplayEvaluatorStatsSchema,
526
- mean: z4.number().nullable(),
527
- median: z4.number().nullable(),
528
- p10: z4.number().nullable(),
529
- p90: z4.number().nullable(),
530
- atLeast4Share: z4.number().nullable(),
531
- histogram: z4.tuple([z4.number(), z4.number(), z4.number(), z4.number(), z4.number()])
532
- }),
533
- z4.object({
534
- outputType: z4.literal("number"),
535
- counts: ReplayEvaluatorCountsSchema,
536
- stats: ReplayEvaluatorStatsSchema,
537
- median: z4.number().nullable(),
538
- p10: z4.number().nullable(),
539
- p90: z4.number().nullable()
540
- })
541
- ]);
542
- var ReplayVerdictIdentitySchema = z4.object({
543
- evaluator: z4.string(),
544
- runId: z4.string(),
545
- url: z4.string()
546
- });
547
- var ReplayVerdictGradedSchema = ReplayVerdictIdentitySchema.extend({
548
- state: z4.literal("graded"),
549
- note: z4.string().optional()
550
- });
551
- var ReplayVerdictSchema = z4.union([
552
- ReplayVerdictGradedSchema.extend({ pass: z4.boolean() }),
553
- ReplayVerdictGradedSchema.extend({ score: EvalScoreSchema }),
554
- ReplayVerdictGradedSchema.extend({ value: z4.number().finite() }),
555
- ReplayVerdictGradedSchema.extend({ preference: z4.enum(["A", "B", "tie"]) }),
556
- ReplayVerdictIdentitySchema.extend({
557
- state: z4.literal("errored"),
558
- message: z4.string()
559
- }),
560
- ReplayVerdictIdentitySchema.extend({
561
- state: z4.literal("ungraded"),
562
- reason: z4.enum(["not sampled", "trace unavailable", "content unreadable"])
563
- })
564
- ]);
565
- var ReplayResultRowSchema = ReplayRowSchema.extend({
566
- status: z4.enum(["pending", "done", "missing"]),
567
- traceId: z4.string().nullable(),
568
- error: z4.string().nullable(),
569
- verdicts: z4.array(ReplayVerdictSchema)
570
- });
571
- var ReplayTraceEvidenceEntrySchema = z4.object({
572
- rowId: z4.string().min(1).max(512),
573
- traceId: z4.string().regex(/^[a-f0-9]{32}$/),
574
- spanIds: z4.array(z4.string().regex(/^[a-f0-9]{16}$/)).min(1).max(500)
575
- }).superRefine((entry, context2) => {
576
- if (new Set(entry.spanIds).size !== entry.spanIds.length) {
577
- context2.addIssue({
578
- code: z4.ZodIssueCode.custom,
579
- message: "Replay trace evidence span ids must be unique",
580
- path: ["spanIds"]
581
- });
582
- }
583
- });
584
- var ReplayTraceEvidenceSchema = z4.array(ReplayTraceEvidenceEntrySchema).superRefine((entries, context2) => {
585
- const seen = /* @__PURE__ */ new Set();
586
- for (const [index, entry] of entries.entries()) {
587
- if (seen.has(entry.rowId)) {
588
- context2.addIssue({
589
- code: z4.ZodIssueCode.custom,
590
- message: "Replay trace evidence row ids must be unique",
591
- path: [index, "rowId"]
592
- });
593
- }
594
- seen.add(entry.rowId);
595
- }
596
- });
597
- var LocalBooleanVerdictSchema = z4.object({ pass: z4.boolean(), note: z4.string().trim().min(1).max(600).optional() }).strict();
598
- var LocalScoreVerdictSchema = z4.object({
599
- score: EvalScoreSchema,
600
- note: z4.string().trim().min(1).max(600).optional()
601
- }).strict();
602
- var LocalNumberVerdictSchema = z4.object({ value: z4.number().finite(), note: z4.string().trim().min(1).max(600).optional() }).strict();
603
- var LocalPreferenceVerdictSchema = z4.object({
604
- preference: z4.enum(["A", "B", "tie"]),
605
- note: z4.string().trim().min(1).max(600).optional()
606
- }).strict();
607
- var LocalVerdictSchema = z4.union([
608
- LocalBooleanVerdictSchema,
609
- LocalScoreVerdictSchema,
610
- LocalNumberVerdictSchema,
611
- LocalPreferenceVerdictSchema
612
- ]);
613
- async function queryApi(request) {
614
- var _a, _b;
615
- if (!((_a = request.client.connection.apiKey) == null ? void 0 : _a.trim())) {
616
- throw new Error("Raindrop evals and datasets require a Query SDK API key (apiKey)");
617
- }
618
- const headers = {
619
- Authorization: `Bearer ${request.client.connection.apiKey}`,
620
- "Content-Type": "application/json"
621
- };
622
- const projectId = request.client.connection.projectId;
623
- if (projectId !== void 0) headers["X-Raindrop-Project-Id"] = projectId;
624
- const url = `${credentialEndpoint(request.queryUrl).href.replace(/\/+$/, "")}${request.path}`;
625
- const maxRetries = (_b = request.maxRetries) != null ? _b : 0;
626
- const body = request.body === void 0 ? void 0 : JSON.stringify(request.body);
627
- for (let retry = 0; ; retry += 1) {
628
- let response;
629
- let text;
630
- const controller = new AbortController();
631
- const remainingMs = () => request.deadlineAt === void 0 ? QUERY_REQUEST_TIMEOUT_MS : Math.max(0, request.deadlineAt - Date.now());
632
- const timeout = setTimeout(
633
- () => controller.abort(),
634
- Math.max(1, Math.min(QUERY_REQUEST_TIMEOUT_MS, remainingMs()))
635
- );
636
- try {
637
- response = await runWithTracingSuppressed(
638
- () => fetch(url, {
639
- method: request.method,
640
- headers,
641
- body,
642
- signal: controller.signal,
643
- redirect: "error"
644
- })
645
- );
646
- text = await response.text();
647
- } catch (cause) {
648
- if (retry >= maxRetries || remainingMs() <= 0) throw cause;
649
- const retryMs = EVAL_RETRY_BASE_DELAY_MS * 2 ** retry;
650
- const budgetMs = remainingMs();
651
- await sleep(Math.min(retryMs, budgetMs));
652
- if (retryMs >= budgetMs || remainingMs() <= 0) throw cause;
653
- continue;
654
- } finally {
655
- clearTimeout(timeout);
656
- }
657
- if (!response.ok) {
658
- const error = new Error(
659
- `Raindrop API ${request.method} ${request.path}: ${response.status} ${text}`
660
- );
661
- if (retry >= maxRetries || !isRetryableStatus(response.status) || remainingMs() <= 0)
662
- throw error;
663
- const retryMs = retryDelayMs(response, retry);
664
- const budgetMs = remainingMs();
665
- await sleep(Math.min(retryMs, budgetMs));
666
- if (retryMs >= budgetMs || remainingMs() <= 0) throw error;
667
- continue;
668
- }
669
- let json;
670
- try {
671
- json = JSON.parse(text);
672
- } catch (e) {
673
- throw new Error(`Raindrop API ${request.method} ${request.path} returned invalid JSON`);
674
- }
675
- const parsed = request.schema.safeParse(json);
676
- if (!parsed.success) {
677
- throw new Error(
678
- `Raindrop API ${request.method} ${request.path} returned an invalid response: ${parsed.error.message}`
679
- );
680
- }
681
- return parsed.data;
682
- }
683
- }
684
- var ReplayStatusSchema = z4.enum(["queued", "running", "complete", "failed"]);
685
- var ReplayRowStatusSchema = z4.enum(["pending", "done", "missing"]);
686
- var WireReplaySchema = z4.object({
687
- id: z4.string(),
688
- status: ReplayStatusSchema,
689
- counts: ReplayCountsSchema,
690
- traces_expire_at: z4.string(),
691
- traces_expired: z4.boolean()
692
- });
693
- var WireRowSchema = z4.object({
694
- row_id: z4.string(),
695
- attempt: z4.number().int().nonnegative(),
696
- status: ReplayRowStatusSchema,
697
- trace_id: z4.string().nullable(),
698
- error: z4.string().nullable()
699
- });
700
- var WirePlanSchema = z4.object({
701
- replay: WireReplaySchema,
702
- ingest_url: z4.string().min(1).nullable(),
703
- rows: z4.array(
704
- ReplayRowSchema.omit({ id: true }).extend({
705
- row_id: z4.string(),
706
- attempt: z4.literal(0),
707
- correlation_id: z4.string()
708
- })
709
- )
710
- });
711
- var WireReplayDetailSchema = z4.object({
712
- replay: WireReplaySchema,
713
- rows: z4.array(WireRowSchema)
714
- });
715
- var EvalRunDetailSchema = WireReplayDetailSchema.extend({
716
- replay: WireReplaySchema.extend({
717
- dataset_id: z4.string().uuid(),
718
- dataset_version_id: z4.string().uuid().nullable()
719
- }),
720
- eval_runs: z4.array(
721
- z4.object({
722
- id: z4.string().uuid(),
723
- eval_id: z4.string().uuid(),
724
- program_version: z4.number().int().positive(),
725
- output_type: z4.enum(["boolean", "score", "number", "preference"]),
726
- executed_by: z4.enum(["hosted", "local"]),
727
- status: z4.enum(["running", "completed", "failed"])
728
- })
729
- )
730
- });
731
- async function readReplayDetails(client, runId, options = {}) {
732
- var _a;
733
- const detail = await queryApi({
734
- client,
735
- queryUrl: (_a = options.queryUrl) != null ? _a : DEFAULT_QUERY_URL,
736
- path: `/v1/replays/${encodeURIComponent(runId)}`,
737
- method: "GET",
738
- schema: EvalRunDetailSchema
739
- });
740
- if (detail.replay.id !== runId) throw new Error("Raindrop returned a different run");
741
- return detail;
742
- }
743
- var WireReportSchema = z4.object({ status: z4.string() });
744
- var WireAttemptStartedSchema = z4.object({
745
- status: z4.literal("pending"),
746
- row: z4.object({
747
- row_id: z4.string().min(1),
748
- attempt: z4.number().int().positive(),
749
- correlation_id: z4.string().min(1)
750
- })
751
- });
752
- var WireLocalEvaluatorSchema = z4.object({
753
- data: z4.object({
754
- id: z4.string().uuid(),
755
- slug: z4.string(),
756
- name: z4.string(),
757
- output: z4.enum(["boolean", "score", "number", "preference"]),
758
- kind: z4.literal("local"),
759
- programVersion: z4.number().int().positive()
760
- })
761
- });
762
- var WireStartedEvalRunSchema = z4.object({
763
- data: z4.object({
764
- runId: z4.string(),
765
- status: z4.literal("running"),
766
- url: z4.string(),
767
- evalId: z4.string().uuid().optional(),
768
- programVersion: z4.number().int().positive().optional()
769
- })
770
- });
771
- var WireEvalRunSchema = z4.object({
772
- data: z4.object({
773
- id: z4.string(),
774
- evalSlug: z4.string(),
775
- status: z4.enum(["running", "completed", "failed"]),
776
- summary: ReplayEvaluatorSummarySchema.nullable(),
777
- error: z4.string().nullable(),
778
- traces: z4.array(
779
- z4.union([
780
- z4.object({
781
- state: z4.literal("graded"),
782
- traceId: z4.string(),
783
- pass: z4.boolean(),
784
- note: z4.string().optional()
785
- }),
786
- z4.object({
787
- state: z4.literal("graded"),
788
- traceId: z4.string(),
789
- score: EvalScoreSchema,
790
- note: z4.string().optional()
791
- }),
792
- z4.object({
793
- state: z4.literal("graded"),
794
- traceId: z4.string(),
795
- value: z4.number().finite(),
796
- note: z4.string().optional()
797
- }),
798
- z4.object({
799
- state: z4.literal("graded"),
800
- traceId: z4.string(),
801
- preference: z4.enum(["A", "B", "tie"]),
802
- note: z4.string().optional()
803
- }),
804
- z4.object({ state: z4.literal("errored"), traceId: z4.string(), message: z4.string() }),
805
- z4.object({
806
- state: z4.literal("ungraded"),
807
- traceId: z4.string(),
808
- reason: z4.enum(["not sampled", "trace unavailable", "content unreadable"])
809
- })
810
- ])
811
- )
812
- })
813
- });
814
- var WireLocalEvalRunSchema = z4.object({
815
- data: WireEvalRunSchema.shape.data.extend({ status: z4.literal("completed"), url: z4.string() })
816
- });
817
- var WireLocalEvalRunStartedSchema = z4.object({
818
- data: WireEvalRunSchema.shape.data.omit({ traces: true }).extend({ status: z4.literal("running"), url: z4.string() })
819
- });
820
- var WireLocalEvalAttemptSchema = z4.object({
821
- data: z4.object({
822
- runId: z4.string().uuid(),
823
- requestId: z4.string().uuid(),
824
- rowId: z4.string().min(1),
825
- attempt: z4.number().int().nonnegative(),
826
- traceId: z4.string().regex(/^[a-f0-9]{32}$/),
827
- outcome: WireEvalRunSchema.shape.data.shape.traces.element
828
- })
829
- });
830
- var WireEvalCaseTracePairReadSchema = z4.discriminatedUnion("state", [
831
- EvalCaseTracePairSchema2.extend({
832
- state: z4.literal("ready"),
833
- attempt: z4.number().int().nonnegative(),
834
- datasetVersion: z4.object({
835
- id: z4.string().uuid(),
836
- fingerprint: EvalDatasetFingerprintSchema
837
- })
838
- }),
839
- z4.object({
840
- state: z4.literal("pending"),
841
- caseId: z4.string().min(1),
842
- attempt: z4.number().int().nonnegative()
843
- }),
844
- z4.object({
845
- state: z4.literal("missing"),
846
- caseId: z4.string().min(1),
847
- attempt: z4.number().int().nonnegative(),
848
- reason: z4.string()
849
- }),
850
- z4.object({
851
- state: z4.literal("expired"),
852
- caseId: z4.string().min(1),
853
- attempt: z4.number().int().nonnegative(),
854
- expiredAt: z4.string().datetime({ offset: true })
855
- }),
856
- z4.object({
857
- state: z4.literal("errored"),
858
- caseId: z4.string().min(1),
859
- attempt: z4.number().int().nonnegative(),
860
- reason: z4.string()
861
- })
862
- ]);
863
- var replayGitSnapshots = /* @__PURE__ */ new WeakMap();
864
- var replayPropertySnapshots = /* @__PURE__ */ new WeakMap();
865
- var replayOverrideSnapshots = /* @__PURE__ */ new WeakSet();
866
- function withReplayGit(snapshot, run) {
867
- var _a;
868
- return withRoutingContext({
869
- ...currentRoutingBinding(),
870
- appGit: (_a = replayPropertySnapshots.get(snapshot)) != null ? _a : snapshot,
871
- appGitSource: replayOverrideSnapshots.has(snapshot) ? "replay-override" : void 0
872
- }, run);
873
- }
874
- function captureReplayGit(client, options) {
875
- var _a, _b;
876
- try {
877
- if (options === void 0 && client.getAppGitSnapshot) {
878
- const properties = Object.freeze({ ...client.getAppGitSnapshot() });
879
- const snapshot2 = Object.freeze({ ...(_b = (_a = client.getReplayAppGitSnapshot) == null ? void 0 : _a.call(client)) != null ? _b : properties });
880
- replayPropertySnapshots.set(snapshot2, properties);
881
- return snapshot2;
882
- }
883
- const resolver = createAppGitContext(options, { allowLocalGit: false });
884
- const snapshot = resolver.snapshot();
885
- resolver.dispose();
886
- if (options && typeof options === "object") replayOverrideSnapshots.add(snapshot);
887
- return snapshot;
888
- } catch (e) {
889
- return {};
890
- }
891
- }
892
- function replayGitFields(snapshot) {
893
- const rawSha = snapshot[APP_COMMIT_SHA];
894
- const sha = typeof rawSha === "string" && validAppCommitSha(rawSha) ? rawSha.trim() : void 0;
895
- const dirty = snapshot[APP_COMMIT_DIRTY];
896
- const rawBranch = snapshot[APP_BRANCH];
897
- const branch = typeof rawBranch === "string" && rawBranch.length <= 1024 ? rawBranch.trim() : "";
898
- return {
899
- commit_sha: sha != null ? sha : null,
900
- commit_dirty: sha && typeof dirty === "boolean" ? dirty : null,
901
- commit_branch: branch.length > 0 && branch.length <= 400 ? branch : null
902
- };
903
- }
904
- function toReading(wire) {
905
- return {
906
- replayId: wire.replay.id,
907
- status: wire.replay.status,
908
- counts: wire.replay.counts,
909
- rows: wire.rows.map((row) => ({
910
- rowId: row.row_id,
911
- attempt: row.attempt,
912
- status: row.status,
913
- traceId: row.trace_id,
914
- error: row.error
915
- })),
916
- tracesExpireAt: wire.replay.traces_expire_at,
917
- tracesExpired: wire.replay.traces_expired
918
- };
919
- }
920
- async function createReplay(client, options) {
921
- var _a;
922
- const gitSnapshot = captureReplayGit(client, options.appGit);
923
- const queryUrl = (_a = options.queryUrl) != null ? _a : DEFAULT_QUERY_URL;
924
- const manifest = typeof options.dataset === "string" ? await readEvalDataset(client, options.dataset, { queryUrl }) : validateEvalDatasetManifest(options.dataset);
925
- const rowIds = selectEvalDatasetRows(manifest, options.rowIds);
926
- const created = await queryApi({
927
- client,
928
- queryUrl,
929
- path: "/v1/replays",
930
- method: "POST",
931
- schema: WirePlanSchema,
932
- maxRetries: MAX_REPLAY_REPORT_RETRIES,
933
- body: {
934
- dataset_slug: manifest.dataset.slug,
935
- dataset_version_id: manifest.version.id,
936
- dataset_fingerprint: manifest.version.fingerprint,
937
- request_key: randomUUID(),
938
- ...replayGitFields(gitSnapshot),
939
- row_ids: rowIds
940
- }
941
- });
942
- const handle = {
943
- ...toHandle(created),
944
- datasetVersion: {
945
- id: manifest.version.id,
946
- fingerprint: manifest.version.fingerprint
947
- }
948
- };
949
- assertSelectedRows(handle, rowIds);
950
- replayGitSnapshots.set(handle, gitSnapshot);
951
- return handle;
952
- }
953
- function selectEvalDatasetRows(manifest, requestedRowIds) {
954
- const rowIds = requestedRowIds != null ? requestedRowIds : manifest.cases.map((entry) => entry.id);
955
- if (rowIds.length === 0) throw new Error("Raindrop replay rowIds cannot be empty");
956
- if (rowIds.some((rowId) => rowId.length === 0)) {
957
- throw new Error("Raindrop replay rowIds cannot contain an empty id");
958
- }
959
- if (new Set(rowIds).size !== rowIds.length) {
960
- throw new Error("Raindrop replay rowIds must be unique");
961
- }
962
- const selected = new Set(rowIds);
963
- const ordered = manifest.cases.flatMap((entry) => selected.has(entry.id) ? [entry.id] : []);
964
- if (ordered.length !== selected.size) {
965
- const available = new Set(manifest.cases.map((entry) => entry.id));
966
- const unknown = rowIds.find((rowId) => !available.has(rowId));
967
- throw new Error(`Raindrop replay rowIds contains unknown row ${unknown != null ? unknown : "unknown"}`);
968
- }
969
- return ordered;
970
- }
971
- function assertSelectedRows(handle, requestedRowIds) {
972
- const returnedRowIds = handle.rows.map((row) => row.id);
973
- const requested = new Set(requestedRowIds);
974
- const returned = new Set(returnedRowIds);
975
- const matches = returned.size === returnedRowIds.length && requested.size === returned.size && requestedRowIds.every((rowId, index) => returnedRowIds[index] === rowId);
976
- if (!matches) {
977
- throw new Error(
978
- `Raindrop replay ${handle.replayId} returned rows that do not match the manifest selection`
979
- );
980
- }
981
- }
982
- function toHandle(wire) {
983
- return {
984
- replayId: wire.replay.id,
985
- ingestUrl: wire.ingest_url,
986
- rows: wire.rows.map((row) => ({
987
- id: row.row_id,
988
- attempt: row.attempt,
989
- correlationId: row.correlation_id,
990
- name: row.name,
991
- input: row.input,
992
- output: row.output,
993
- properties: row.properties
994
- }))
995
- };
996
- }
997
- async function claimReplay(client, replayId, options) {
998
- var _a;
999
- const gitSnapshot = captureReplayGit(client, options == null ? void 0 : options.appGit);
1000
- const handle = toHandle(
1001
- await queryApi({
1002
- client,
1003
- queryUrl: (_a = options == null ? void 0 : options.queryUrl) != null ? _a : DEFAULT_QUERY_URL,
1004
- path: `/v1/replays/${encodeURIComponent(replayId)}/claim`,
1005
- method: "POST",
1006
- schema: WirePlanSchema,
1007
- body: replayGitFields(gitSnapshot)
1008
- })
1009
- );
1010
- replayGitSnapshots.set(handle, gitSnapshot);
1011
- return handle;
1012
- }
1013
- async function readReplay(client, replayId, options) {
1014
- var _a;
1015
- return toReading(
1016
- await queryApi({
1017
- client,
1018
- queryUrl: (_a = options == null ? void 0 : options.queryUrl) != null ? _a : DEFAULT_QUERY_URL,
1019
- path: `/v1/replays/${encodeURIComponent(replayId)}`,
1020
- deadlineAt: options == null ? void 0 : options.deadlineAt,
1021
- method: "GET",
1022
- schema: WireReplayDetailSchema
1023
- })
1024
- );
1025
- }
1026
- async function readEvalManifest(client, dataset, options) {
1027
- var _a;
1028
- const normalized = dataset.trim();
1029
- if (normalized.length === 0) throw new Error("Raindrop eval manifest dataset cannot be empty");
1030
- const manifest = await queryApi({
1031
- client,
1032
- queryUrl: (_a = options == null ? void 0 : options.queryUrl) != null ? _a : DEFAULT_QUERY_URL,
1033
- path: `/v1/replays/manifest?dataset=${encodeURIComponent(normalized)}`,
1034
- method: "GET",
1035
- schema: WireEvalManifestSchema
1036
- });
1037
- const caseIds = manifest.rows.map((row) => row.id);
1038
- if (new Set(caseIds).size !== caseIds.length) {
1039
- throw new Error(`Raindrop eval manifest for ${normalized} contains duplicate row ids`);
1040
- }
1041
- return {
1042
- datasetId: manifest.dataset_id,
1043
- datasetVersionId: manifest.dataset_version_id,
1044
- fingerprint: manifest.fingerprint,
1045
- cases: manifest.rows
1046
- };
1047
- }
1048
- async function readEvalDataset(client, dataset, options) {
1049
- var _a;
1050
- const slug = EvalDatasetSlugSchema.parse(dataset.trim());
1051
- const versionId = options == null ? void 0 : options.versionId;
1052
- if (versionId !== void 0 && !z4.string().uuid().safeParse(versionId).success) {
1053
- throw new Error("Raindrop eval dataset versionId must be a UUID");
1054
- }
1055
- const path = versionId ? `/v1/eval-datasets/${encodeURIComponent(slug)}/versions/${encodeURIComponent(versionId)}` : `/v1/eval-datasets/${encodeURIComponent(slug)}`;
1056
- const manifest = validateEvalDatasetManifest(
1057
- await queryApi({
1058
- client,
1059
- queryUrl: (_a = options == null ? void 0 : options.queryUrl) != null ? _a : DEFAULT_QUERY_URL,
1060
- path,
1061
- method: "GET",
1062
- schema: EvalDatasetManifestReadSchema
1063
- })
1064
- );
1065
- if (manifest.dataset.slug !== slug && manifest.dataset.id !== slug) {
1066
- throw new Error(`Raindrop eval dataset ${slug} returned mismatched dataset identity`);
1067
- }
1068
- if (versionId !== void 0 && manifest.version.id !== versionId) {
1069
- throw new Error(`Raindrop eval dataset ${slug} returned mismatched version identity`);
1070
- }
1071
- return manifest;
1072
- }
1073
- function validateEvalDatasetManifest(value) {
1074
- const manifest = EvalDatasetManifestReadSchema.parse(value);
1075
- if (manifest.dataset.id !== manifest.version.datasetId) {
1076
- throw new Error("Raindrop eval dataset and version identities do not match");
1077
- }
1078
- const caseIds = manifest.cases.map((entry) => entry.id);
1079
- if (new Set(caseIds).size !== caseIds.length) {
1080
- throw new Error(`Raindrop eval dataset ${manifest.dataset.slug} contains duplicate row ids`);
1081
- }
1082
- return manifest;
1083
- }
1084
- async function runReplay(client, handle, options) {
1085
- return (await runReplayRows(client, handle, options)).reading;
1086
- }
1087
- async function runEvalReplay(client, handle, options) {
1088
- return runReplayRows(client, handle, options);
1089
- }
1090
- async function runReplayRows(client, handle, options) {
1091
- var _a, _b, _c, _d, _e, _f, _g, _h;
1092
- if (!Number.isSafeInteger((_a = options.concurrency) != null ? _a : DEFAULT_CONCURRENCY) || ((_b = options.concurrency) != null ? _b : DEFAULT_CONCURRENCY) < 1) {
1093
- throw new Error("Raindrop replay concurrency must be a positive safe integer");
1094
- }
1095
- validateWait("traceWaitMs", (_c = options.traceWaitMs) != null ? _c : DEFAULT_TRACE_WAIT_MS, true);
1096
- const ingestUrl = handle.ingestUrl && replayIngestEndpoint(handle.ingestUrl, options.replayIngestUrl);
1097
- if (!ingestUrl) {
1098
- throw new Error(
1099
- `Raindrop replay ${handle.replayId} has no ingest URL; create or claim it with this runner before running it`
1100
- );
1101
- }
1102
- const queryUrl = (_d = options.queryUrl) != null ? _d : DEFAULT_QUERY_URL;
1103
- const report = (body) => queryApi({
1104
- client,
1105
- queryUrl,
1106
- path: `/v1/replays/${encodeURIComponent(handle.replayId)}/report`,
1107
- method: "POST",
1108
- schema: WireReportSchema,
1109
- body,
1110
- maxRetries: MAX_REPLAY_REPORT_RETRIES
1111
- });
1112
- const gitSnapshot = (_e = replayGitSnapshots.get(handle)) != null ? _e : captureReplayGit(client);
1113
- replayGitSnapshots.set(handle, gitSnapshot);
1114
- await report({ type: "started", ...replayGitFields(gitSnapshot) });
1115
- const rows = [...handle.rows];
1116
- const results = /* @__PURE__ */ new Map();
1117
- const captures = /* @__PURE__ */ new Map();
1118
- let next = 0;
1119
- const worker = async () => {
1120
- var _a2, _b2;
1121
- while (next < rows.length) {
1122
- const row = rows[next++];
1123
- if (!row) return;
1124
- const spanIds = /* @__PURE__ */ new Set();
1125
- const traceIds = /* @__PURE__ */ new Set();
1126
- captures.set(row.id, { spanIds, traceIds });
1127
- try {
1128
- const { correlationId: _attribution, attempt: _attempt, ...visible } = row;
1129
- const replayDestination = {
1130
- kind: "raindrop",
1131
- url: ingestUrl,
1132
- replayId: handle.replayId,
1133
- apiKey: (_a2 = client.connection.apiKey) != null ? _a2 : "",
1134
- projectId: client.connection.projectId,
1135
- exportedSpanIds: spanIds,
1136
- exportedTraceIds: traceIds
1137
- };
1138
- const result = await withReplayGit(gitSnapshot, () => context.with(
1139
- trace.deleteSpan(context.active()),
1140
- () => withReplayTraceDestination(
1141
- replayDestination,
1142
- () => withEvalScope(
1143
- { correlationId: row.correlationId },
1144
- () => withTask(
1145
- { name: "raindrop.replay.row", inputParameters: [visible], traceContent: true },
1146
- async () => {
1147
- var _a3;
1148
- const parent = (_a3 = trace.getSpan(context.active())) == null ? void 0 : _a3.spanContext();
1149
- if (!parent) return options.run(visible);
1150
- return withReplayTraceDestination(
1151
- {
1152
- ...replayDestination,
1153
- parentSpanContext: {
1154
- traceIdB64: Buffer.from(parent.traceId, "hex").toString("base64"),
1155
- spanIdB64: Buffer.from(parent.spanId, "hex").toString("base64"),
1156
- eventId: parent.traceId
1157
- }
1158
- },
1159
- () => options.run(visible)
1160
- );
1161
- }
1162
- )
1163
- )
1164
- )
1165
- ));
1166
- results.set(row.id, { value: result });
1167
- } catch (cause) {
1168
- const error = describeError(cause);
1169
- await report({
1170
- type: "row_missing",
1171
- row_id: row.id,
1172
- attempt: row.attempt,
1173
- error
1174
- });
1175
- await client.forceFlush();
1176
- try {
1177
- await waitForFailedTraceAssociation({
1178
- client,
1179
- queryUrl,
1180
- replayId: handle.replayId,
1181
- rowId: row.id,
1182
- attempt: row.attempt,
1183
- traceIds,
1184
- spanIds,
1185
- waitMs: (_b2 = options.traceWaitMs) != null ? _b2 : DEFAULT_TRACE_WAIT_MS
1186
- });
1187
- } catch (retentionCause) {
1188
- throw failedTraceRetentionError(cause, retentionCause, row.id);
1189
- }
1190
- captures.delete(row.id);
1191
- }
1192
- }
1193
- };
1194
- const workers = await Promise.allSettled(
1195
- Array.from(
1196
- { length: Math.min((_f = options.concurrency) != null ? _f : DEFAULT_CONCURRENCY, rows.length) },
1197
- () => worker()
1198
- )
1199
- );
1200
- const failures = workers.flatMap(
1201
- (result) => result.status === "rejected" ? [result.reason] : []
1202
- );
1203
- if (failures.length === 1) throw failures[0];
1204
- if (failures.length > 1) throw new AggregateError(failures, "Replay row execution failed");
1205
- await client.forceFlush();
1206
- const traceEvidence = [];
1207
- for (const row of rows) {
1208
- const capture = captures.get(row.id);
1209
- if (!capture) continue;
1210
- const traceIds = [...capture.traceIds];
1211
- const spanIds = [...capture.spanIds];
1212
- if (traceIds.length !== 1 || spanIds.length === 0 || spanIds.length > 500) {
1213
- const detail = traceIds.length !== 1 ? `expected one trace, captured ${traceIds.length}` : spanIds.length === 0 ? "captured no ended spans" : `captured ${spanIds.length} spans, exceeding the 500 span limit`;
1214
- await report({ type: "row_missing", row_id: row.id, attempt: row.attempt, error: detail });
1215
- continue;
1216
- }
1217
- const traceId = traceIds[0];
1218
- if (traceId === void 0) {
1219
- throw new Error(`Raindrop replay ${handle.replayId} lost trace evidence for ${row.id}`);
1220
- }
1221
- traceEvidence.push({ rowId: row.id, traceId, spanIds });
1222
- }
1223
- const settled = await waitForTraces({
1224
- client,
1225
- queryUrl,
1226
- replayId: handle.replayId,
1227
- deadlineAt: Date.now() + ((_g = options.traceWaitMs) != null ? _g : DEFAULT_TRACE_WAIT_MS)
1228
- });
1229
- for (const row of settled.rows) {
1230
- if (row.status !== "pending") continue;
1231
- await report({
1232
- type: "row_missing",
1233
- row_id: row.rowId,
1234
- attempt: row.attempt,
1235
- error: `no trace arrived for this row within ${Math.round(
1236
- ((_h = options.traceWaitMs) != null ? _h : DEFAULT_TRACE_WAIT_MS) / 1e3
1237
- )}s`
1238
- });
1239
- }
1240
- await report({ type: "finished" });
1241
- return {
1242
- reading: await readReplay(client, handle.replayId, { queryUrl }),
1243
- results,
1244
- traceEvidence: ReplayTraceEvidenceSchema.parse(traceEvidence)
1245
- };
1246
- }
1247
- async function readEvalCaseTracePairs(input) {
1248
- const deadlineAt = Date.now() + input.waitMs;
1249
- const entries = await Promise.all(
1250
- input.evidence.map(async (evidence) => {
1251
- var _a, _b, _c;
1252
- let reading = await readEvalCaseTracePair(
1253
- { ...input, deadlineAt },
1254
- evidence,
1255
- (_a = input.attempt) != null ? _a : 0
1256
- );
1257
- while (reading.state === "pending" && Date.now() < deadlineAt) {
1258
- await sleep(Math.min(TRACE_POLL_INTERVAL_MS, Math.max(0, deadlineAt - Date.now())));
1259
- if (Date.now() >= deadlineAt) break;
1260
- reading = await readEvalCaseTracePair(
1261
- { ...input, deadlineAt },
1262
- evidence,
1263
- (_b = input.attempt) != null ? _b : 0
1264
- );
1265
- }
1266
- if (reading.state !== "ready") {
1267
- const detail = reading.state === "pending" ? `did not become complete within ${input.waitMs}ms` : reading.state === "expired" ? `expired at ${reading.expiredAt}` : reading.reason;
1268
- throw new Error(
1269
- `Raindrop replay ${input.replayId} trace pair for ${evidence.rowId} ${detail}`
1270
- );
1271
- }
1272
- if (reading.caseId !== evidence.rowId) {
1273
- throw new Error(
1274
- `Raindrop replay ${input.replayId} returned a trace pair for the wrong case`
1275
- );
1276
- }
1277
- if (reading.attempt !== ((_c = input.attempt) != null ? _c : 0)) {
1278
- throw new Error(
1279
- `Raindrop replay ${input.replayId} returned a trace pair for the wrong attempt`
1280
- );
1281
- }
1282
- if (input.datasetVersion && (reading.datasetVersion.id !== input.datasetVersion.id || reading.datasetVersion.fingerprint !== input.datasetVersion.fingerprint)) {
1283
- throw new Error(
1284
- `Raindrop replay ${input.replayId} returned a trace pair from the wrong dataset version`
1285
- );
1286
- }
1287
- return [evidence.rowId, reading];
1288
- })
1289
- );
1290
- return new Map(entries);
1291
- }
1292
- async function readEvalCaseTracePair(input, evidence, attempt) {
1293
- const query = new URLSearchParams({
1294
- row_id: evidence.rowId,
1295
- attempt: String(attempt),
1296
- expected_trace_id: evidence.traceId
1297
- });
1298
- for (const spanId of evidence.spanIds) query.append("expected_span_id", spanId);
1299
- return queryApi({
1300
- client: input.client,
1301
- queryUrl: input.queryUrl,
1302
- path: `/v1/replays/${encodeURIComponent(input.replayId)}/trace?${query.toString()}`,
1303
- method: "GET",
1304
- schema: WireEvalCaseTracePairReadSchema,
1305
- deadlineAt: input.deadlineAt,
1306
- maxRetries: MAX_EVAL_STATUS_RETRIES
1307
- });
1308
- }
1309
- async function createLocalEvalReplaySession(client, options) {
1310
- var _a, _b, _c;
1311
- if (options.evaluators.length === 0) {
1312
- throw new Error("Raindrop local eval replay requires at least one evaluator");
1313
- }
1314
- const queryUrl = (_a = options.queryUrl) != null ? _a : DEFAULT_QUERY_URL;
1315
- await validateReferenceRequirements(
1316
- client,
1317
- options.dataset,
1318
- options.rowIds,
1319
- options.evaluators,
1320
- queryUrl
1321
- );
1322
- const handle = await createReplay(client, {
1323
- dataset: options.dataset,
1324
- rowIds: options.rowIds,
1325
- queryUrl
1326
- });
1327
- const validatedHandle = {
1328
- ...handle,
1329
- ingestUrl: replayIngestEndpoint(requireReplayIngestUrl(handle), options.replayIngestUrl)
1330
- };
1331
- replayGitSnapshots.set(validatedHandle, (_b = replayGitSnapshots.get(handle)) != null ? _b : {});
1332
- await reportReplay(client, queryUrl, handle.replayId, { type: "started", ...replayGitFields((_c = replayGitSnapshots.get(handle)) != null ? _c : {}) });
1333
- const parents = await Promise.all(
1334
- options.evaluators.map(async (evaluator) => {
1335
- const registered = await registerLocalEvaluator(client, evaluator, queryUrl);
1336
- const runId = randomUUID();
1337
- const started = await queryApi({
1338
- client,
1339
- queryUrl,
1340
- path: `/v1/evals/${encodeURIComponent(evaluator.slug)}/runs/local`,
1341
- method: "POST",
1342
- schema: WireLocalEvalRunStartedSchema,
1343
- maxRetries: MAX_REPLAY_REPORT_RETRIES,
1344
- body: {
1345
- type: "started",
1346
- runId,
1347
- expectedEvalId: registered.data.id,
1348
- expectedProgramVersion: registered.data.programVersion,
1349
- source: { replay: handle.replayId }
1350
- }
1351
- });
1352
- if (started.data.id !== runId) {
1353
- throw new Error(`Raindrop local evaluator ${evaluator.slug} returned the wrong run id`);
1354
- }
1355
- return {
1356
- evaluator,
1357
- runId,
1358
- url: started.data.url
1359
- };
1360
- })
1361
- );
1362
- return new LocalEvalReplaySessionImpl(client, validatedHandle, parents, queryUrl);
1363
- }
1364
- var LocalEvalReplaySessionImpl = class {
1365
- constructor(client, handle, parents, queryUrl) {
1366
- this.client = client;
1367
- this.handle = handle;
1368
- this.parents = parents;
1369
- this.queryUrl = queryUrl;
1370
- this.state = "open";
1371
- this.replayId = handle.replayId;
1372
- this.rows = handle.rows.map(
1373
- ({ correlationId: _correlationId, attempt: _attempt, ...row }) => row
1374
- );
1375
- }
1376
- async run(input) {
1377
- var _a, _b, _c, _d, _e;
1378
- validateWait("traceWaitMs", (_a = input.traceWaitMs) != null ? _a : DEFAULT_TRACE_WAIT_MS, true);
1379
- if (this.state !== "open") {
1380
- throw new Error(`Raindrop replay ${this.replayId} is already finishing`);
1381
- }
1382
- if (!Number.isInteger(input.attempt) || input.attempt < 0) {
1383
- throw new Error("Raindrop replay attempt must be a non-negative integer");
1384
- }
1385
- const planned = this.handle.rows.find((row2) => row2.id === input.rowId);
1386
- if (!planned) throw new Error(`Raindrop replay ${this.replayId} has no row ${input.rowId}`);
1387
- const correlationId = input.attempt === 0 ? planned.correlationId : await this.allocateRetry(input.rowId, input.attempt);
1388
- const { correlationId: _correlationId, attempt: _attempt, ...row } = planned;
1389
- const spanIds = /* @__PURE__ */ new Set();
1390
- const traceIds = /* @__PURE__ */ new Set();
1391
- let result;
1392
- const startedAt = Date.now();
1393
- const replayDestination = {
1394
- kind: "raindrop",
1395
- url: requireReplayIngestUrl(this.handle),
1396
- replayId: this.replayId,
1397
- apiKey: (_b = this.client.connection.apiKey) != null ? _b : "",
1398
- projectId: this.client.connection.projectId,
1399
- exportedSpanIds: spanIds,
1400
- exportedTraceIds: traceIds
1401
- };
1402
- try {
1403
- result = await withReplayGit(
1404
- (_c = replayGitSnapshots.get(this.handle)) != null ? _c : {},
1405
- () => context.with(
1406
- trace.deleteSpan(context.active()),
1407
- () => withReplayTraceDestination(
1408
- replayDestination,
1409
- () => withEvalScope(
1410
- { correlationId },
1411
- () => withTask(
1412
- { name: "raindrop.replay.row", inputParameters: [row], traceContent: true },
1413
- () => {
1414
- var _a2;
1415
- const parent = (_a2 = trace.getSpan(context.active())) == null ? void 0 : _a2.spanContext();
1416
- if (!parent) return input.run(row);
1417
- return withReplayTraceDestination(
1418
- {
1419
- ...replayDestination,
1420
- parentSpanContext: {
1421
- traceIdB64: Buffer.from(parent.traceId, "hex").toString("base64"),
1422
- spanIdB64: Buffer.from(parent.spanId, "hex").toString("base64"),
1423
- eventId: parent.traceId
1424
- }
1425
- },
1426
- () => input.run(row)
1427
- );
1428
- }
1429
- )
1430
- )
1431
- )
1432
- )
1433
- );
1434
- } catch (cause) {
1435
- const error = describeError(cause);
1436
- await reportReplay(this.client, this.queryUrl, this.replayId, {
1437
- type: "row_missing",
1438
- row_id: row.id,
1439
- attempt: input.attempt,
1440
- error
1441
- });
1442
- await this.client.forceFlush();
1443
- let retainedTraceId;
1444
- try {
1445
- retainedTraceId = await waitForFailedTraceAssociation({
1446
- client: this.client,
1447
- queryUrl: this.queryUrl,
1448
- replayId: this.replayId,
1449
- rowId: row.id,
1450
- attempt: input.attempt,
1451
- traceIds,
1452
- spanIds,
1453
- waitMs: (_d = input.traceWaitMs) != null ? _d : DEFAULT_TRACE_WAIT_MS
1454
- });
1455
- } catch (retentionCause) {
1456
- throw failedTraceRetentionError(cause, retentionCause, row.id);
1457
- }
1458
- return {
1459
- row,
1460
- attempt: input.attempt,
1461
- status: "missing",
1462
- traceId: retainedTraceId,
1463
- error,
1464
- verdicts: []
1465
- };
1466
- }
1467
- await this.client.forceFlush();
1468
- let pair;
1469
- let evidence;
1470
- try {
1471
- evidence = capturedEvidence(row.id, traceIds, spanIds);
1472
- const pairs = await readEvalCaseTracePairs({
1473
- client: this.client,
1474
- queryUrl: this.queryUrl,
1475
- replayId: this.replayId,
1476
- datasetVersion: this.handle.datasetVersion,
1477
- evidence: [evidence],
1478
- waitMs: (_e = input.traceWaitMs) != null ? _e : DEFAULT_TRACE_WAIT_MS,
1479
- attempt: input.attempt
1480
- });
1481
- const captured = pairs.get(row.id);
1482
- if (!captured)
1483
- throw new Error(`Raindrop replay ${this.replayId} omitted trace pair ${row.id}`);
1484
- pair = captured;
1485
- } catch (cause) {
1486
- const error = describeError(cause);
1487
- await reportReplay(this.client, this.queryUrl, this.replayId, {
1488
- type: "row_missing",
1489
- row_id: row.id,
1490
- attempt: input.attempt,
1491
- error
1492
- });
1493
- return { row, attempt: input.attempt, status: "missing", traceId: null, error, verdicts: [] };
1494
- }
1495
- const verdicts = await Promise.all(
1496
- this.parents.map(async (parent) => {
1497
- var _a2;
1498
- const judgeStartedAt = Date.now();
1499
- let verdict;
1500
- try {
1501
- verdict = parseLocalVerdict(
1502
- parent.evaluator,
1503
- await parent.evaluator.judge({
1504
- trace: pair.candidate.trace,
1505
- expectedOutput: pair.output,
1506
- rowMetadata: row.properties,
1507
- referenceTrace: (_a2 = pair.reference) == null ? void 0 : _a2.trace,
1508
- case: pair,
1509
- row,
1510
- result
1511
- })
1512
- );
1513
- } catch (cause) {
1514
- verdict = { error: localEvaluatorError(cause) };
1515
- }
1516
- const requestId = randomUUID();
1517
- let receipt;
1518
- try {
1519
- receipt = await queryApi({
1520
- client: this.client,
1521
- queryUrl: this.queryUrl,
1522
- path: `/v1/evals/${encodeURIComponent(parent.evaluator.slug)}/runs/local`,
1523
- method: "POST",
1524
- schema: WireLocalEvalAttemptSchema,
1525
- maxRetries: MAX_REPLAY_REPORT_RETRIES,
1526
- body: {
1527
- type: "attempt",
1528
- runId: parent.runId,
1529
- requestId,
1530
- source: {
1531
- replay: this.replayId,
1532
- rowId: row.id,
1533
- attempt: input.attempt,
1534
- traceEvidence: [evidence]
1535
- },
1536
- verdict,
1537
- durationMs: Date.now() - judgeStartedAt
1538
- }
1539
- });
1540
- } catch (cause) {
1541
- throw new Error(
1542
- `Raindrop local evaluator ${parent.evaluator.slug} could not record attempt at ${parent.url}: ${describeError(cause)}`
1543
- );
1544
- }
1545
- const data = receipt.data;
1546
- if (data.runId !== parent.runId || data.requestId !== requestId || data.rowId !== row.id || data.attempt !== input.attempt || data.traceId !== evidence.traceId) {
1547
- throw new Error(
1548
- `Raindrop local evaluator ${parent.evaluator.slug} returned a mismatched attempt receipt`
1549
- );
1550
- }
1551
- return replayVerdict(
1552
- {
1553
- evaluator: parent.evaluator.slug,
1554
- runId: parent.runId,
1555
- status: "completed",
1556
- url: parent.url,
1557
- summary: null,
1558
- error: null
1559
- },
1560
- data.outcome
1561
- );
1562
- })
1563
- );
1564
- return {
1565
- row,
1566
- attempt: input.attempt,
1567
- status: "done",
1568
- traceId: evidence.traceId,
1569
- error: null,
1570
- result,
1571
- verdicts
1572
- };
1573
- }
1574
- finish() {
1575
- if (this.finishPromise) return this.finishPromise;
1576
- this.state = "finishing";
1577
- this.finishPromise = this.finishOnce();
1578
- return this.finishPromise;
1579
- }
1580
- async finishOnce() {
1581
- await reportReplay(this.client, this.queryUrl, this.replayId, { type: "finished" });
1582
- const completed = await Promise.all(
1583
- this.parents.map(async (parent) => {
1584
- const response = await queryApi({
1585
- client: this.client,
1586
- queryUrl: this.queryUrl,
1587
- path: `/v1/evals/${encodeURIComponent(parent.evaluator.slug)}/runs/local`,
1588
- method: "POST",
1589
- schema: WireLocalEvalRunSchema,
1590
- maxRetries: MAX_REPLAY_REPORT_RETRIES,
1591
- body: { type: "finished", runId: parent.runId, source: { replay: this.replayId } }
1592
- });
1593
- if (response.data.id !== parent.runId) {
1594
- throw new Error(
1595
- `Raindrop local evaluator ${parent.evaluator.slug} returned the wrong run id`
1596
- );
1597
- }
1598
- return {
1599
- evaluator: parent.evaluator.slug,
1600
- runId: response.data.id,
1601
- status: response.data.status,
1602
- url: response.data.url,
1603
- summary: response.data.summary,
1604
- error: response.data.error
1605
- };
1606
- })
1607
- );
1608
- const reading = await readReplay(this.client, this.replayId, { queryUrl: this.queryUrl });
1609
- this.state = "finished";
1610
- return { reading, evaluators: completed };
1611
- }
1612
- async allocateRetry(rowId, attempt) {
1613
- const response = await queryApi({
1614
- client: this.client,
1615
- queryUrl: this.queryUrl,
1616
- path: `/v1/replays/${encodeURIComponent(this.replayId)}/report`,
1617
- method: "POST",
1618
- schema: WireAttemptStartedSchema,
1619
- body: { type: "attempt_started", row_id: rowId, attempt, request_key: randomUUID() },
1620
- maxRetries: MAX_REPLAY_REPORT_RETRIES
1621
- });
1622
- if (response.row.row_id !== rowId || response.row.attempt !== attempt) {
1623
- throw new Error(`Raindrop replay ${this.replayId} returned the wrong retry attempt`);
1624
- }
1625
- return response.row.correlation_id;
1626
- }
1627
- };
1628
- function requireReplayIngestUrl(handle) {
1629
- if (!handle.ingestUrl) {
1630
- throw new Error(`Raindrop replay ${handle.replayId} has no ingest URL`);
1631
- }
1632
- return handle.ingestUrl;
1633
- }
1634
- function capturedEvidence(rowId, traceIds, spanIds) {
1635
- const traces = [...traceIds];
1636
- const spans = [...spanIds];
1637
- if (traces.length !== 1 || spans.length === 0 || spans.length > 500) {
1638
- const detail = traces.length !== 1 ? `expected one trace, captured ${traces.length}` : spans.length === 0 ? "captured no ended spans" : `captured ${spans.length} spans, exceeding the 500 span limit`;
1639
- throw new Error(`Raindrop replay row ${rowId} ${detail}`);
1640
- }
1641
- const traceId = traces[0];
1642
- if (traceId === void 0) throw new Error(`Raindrop replay row ${rowId} lost its trace id`);
1643
- return ReplayTraceEvidenceEntrySchema.parse({ rowId, traceId, spanIds: spans });
1644
- }
1645
- function reportReplay(client, queryUrl, replayId, body) {
1646
- return queryApi({
1647
- client,
1648
- queryUrl,
1649
- path: `/v1/replays/${encodeURIComponent(replayId)}/report`,
1650
- method: "POST",
1651
- schema: WireReportSchema,
1652
- body,
1653
- maxRetries: MAX_REPLAY_REPORT_RETRIES
1654
- });
1655
- }
1656
- async function validateReferenceRequirements(client, dataset, rowIds, evaluators, queryUrl) {
1657
- const selected = new Set(selectEvalDatasetRows(dataset, rowIds));
1658
- const missing = dataset.cases.filter(
1659
- (entry) => selected.has(entry.id) && entry.referenceTraceSha256 === void 0
1660
- );
1661
- if (missing.length === 0) return;
1662
- for (const evaluator of evaluators) {
1663
- const requiresReference = typeof evaluator === "string" ? (await queryApi({
1664
- client,
1665
- queryUrl,
1666
- path: `/v1/evals/${encodeURIComponent(evaluator)}`,
1667
- method: "GET",
1668
- schema: z4.object({ data: z4.object({ requiresReference: z4.boolean() }) })
1669
- })).data.requiresReference : evaluator.requiresReference === true;
1670
- if (requiresReference) {
1671
- const name = typeof evaluator === "string" ? evaluator : evaluator.slug;
1672
- throw new Error(
1673
- `Raindrop evaluator ${name} requires a reference trace. Missing references for rows: ${missing.map((entry) => entry.id).join(", ")}`
1674
- );
1675
- }
1676
- }
1677
- }
1678
- async function replay(client, options) {
1679
- var _a, _b, _c;
1680
- const evaluators = normalizeEvaluators(options.evaluators);
1681
- const queryUrl = (_a = options.queryUrl) != null ? _a : DEFAULT_QUERY_URL;
1682
- const dataset = typeof options.dataset === "string" ? await readEvalDataset(client, options.dataset, { queryUrl }) : options.dataset;
1683
- const rowIds = options.runId === void 0 ? options.rowIds : await queuedSuiteRows(client, options.runId, dataset, options.rowIds, queryUrl);
1684
- await validateReferenceRequirements(client, dataset, rowIds, evaluators, queryUrl);
1685
- const local = evaluators.flatMap(
1686
- (evaluator) => typeof evaluator === "string" ? [] : [{ evaluator, verdicts: [], durationMs: 0 }]
1687
- );
1688
- await Promise.all(
1689
- local.map(
1690
- (state) => {
1691
- var _a2;
1692
- return registerLocalEvaluator(client, state.evaluator, (_a2 = options.queryUrl) != null ? _a2 : DEFAULT_QUERY_URL);
1693
- }
1694
- )
1695
- );
1696
- const handle = options.runId === void 0 ? await createReplay(client, { ...options, dataset, rowIds }) : await claimSuiteRun(client, options.runId, dataset, rowIds != null ? rowIds : [], queryUrl);
1697
- const execution = await runReplayRows(client, handle, options);
1698
- const { reading } = execution;
1699
- const doneRowIds = new Set(
1700
- reading.rows.flatMap((row) => row.status === "done" ? [row.rowId] : [])
1701
- );
1702
- const traceEvidence = execution.traceEvidence.filter((entry) => doneRowIds.has(entry.rowId));
1703
- if (traceEvidence.length !== doneRowIds.size) {
1704
- throw new Error(`Raindrop replay ${reading.replayId} completed without full trace evidence`);
1705
- }
1706
- if (local.length > 0) {
1707
- const pairs = await readEvalCaseTracePairs({
1708
- client,
1709
- queryUrl: (_b = options.queryUrl) != null ? _b : DEFAULT_QUERY_URL,
1710
- replayId: reading.replayId,
1711
- datasetVersion: handle.datasetVersion,
1712
- evidence: traceEvidence,
1713
- waitMs: (_c = options.traceWaitMs) != null ? _c : DEFAULT_TRACE_WAIT_MS
1714
- });
1715
- const rowsById = new Map(
1716
- handle.rows.map(({ correlationId: _correlationId, ...row }) => [row.id, row])
1717
- );
1718
- for (const [rowId, pair] of pairs) {
1719
- const row = rowsById.get(rowId);
1720
- const result = execution.results.get(rowId);
1721
- if (!row || !result) {
1722
- throw new Error(`Raindrop replay ${reading.replayId} omitted result for ${rowId}`);
1723
- }
1724
- await runLocalEvaluators(local, pair, row, result.value);
1725
- }
1726
- }
1727
- const hosted = evaluators.flatMap(
1728
- (evaluator) => typeof evaluator === "string" ? [evaluator] : []
1729
- );
1730
- const [hostedResults, localResults] = await Promise.all([
1731
- hosted.length === 0 ? Promise.resolve([]) : runReplayEvaluators(client, reading.replayId, {
1732
- evaluators: hosted,
1733
- evaluatorPins: options.evaluatorPins,
1734
- queryUrl: options.queryUrl,
1735
- waitMs: options.evalWaitMs,
1736
- pollIntervalMs: options.evalPollIntervalMs,
1737
- traceEvidence
1738
- }),
1739
- Promise.all(
1740
- local.map(
1741
- (state) => {
1742
- var _a2;
1743
- return submitLocalEvaluator(
1744
- client,
1745
- reading.replayId,
1746
- state,
1747
- (_a2 = options.queryUrl) != null ? _a2 : DEFAULT_QUERY_URL,
1748
- traceEvidence
1749
- );
1750
- }
1751
- )
1752
- )
1753
- ]);
1754
- const resultsByEvaluator = new Map(
1755
- [...hostedResults, ...localResults].map((result) => [result.evaluator, result])
1756
- );
1757
- const evaluatorResults = evaluators.map((evaluator) => {
1758
- const name = typeof evaluator === "string" ? evaluator : evaluator.slug;
1759
- const result = resultsByEvaluator.get(name);
1760
- if (!result) throw new Error(`Raindrop replay omitted evaluator ${name}`);
1761
- return result;
1762
- });
1763
- return {
1764
- ...reading,
1765
- rows: replayResultRows(handle, reading, evaluatorResults),
1766
- evaluators: evaluatorResults.map(({ outcomes: _outcomes, ...evaluator }) => evaluator)
1767
- };
1768
- }
1769
- async function queuedSuiteRows(client, runId, dataset, requestedRows, queryUrl) {
1770
- const detail = await readReplayDetails(client, runId, { queryUrl });
1771
- if (detail.replay.dataset_id !== dataset.dataset.id || detail.replay.dataset_version_id !== dataset.version.id) {
1772
- throw new Error("Queued run dataset version does not match the suite");
1773
- }
1774
- if (detail.replay.status !== "queued") throw new Error("Only queued runs can be claimed");
1775
- if (detail.replay.traces_expired) throw new Error("Queued run has expired");
1776
- const rowIds = selectEvalDatasetRows(
1777
- dataset,
1778
- detail.rows.map((row) => row.row_id)
1779
- );
1780
- const requested = requestedRows && selectEvalDatasetRows(dataset, requestedRows);
1781
- if (requested && (requested.length !== rowIds.length || requested.some((id, index) => id !== rowIds[index]))) {
1782
- throw new Error("Queued run rows do not match the requested selection");
1783
- }
1784
- return rowIds;
1785
- }
1786
- async function claimSuiteRun(client, runId, dataset, rowIds, queryUrl) {
1787
- const handle = await claimReplay(client, runId, { queryUrl });
1788
- if (handle.replayId !== runId) throw new Error("Raindrop claimed a different run");
1789
- if (!handle.ingestUrl) throw new Error("Run has already been claimed by another runner");
1790
- assertSelectedRows(handle, rowIds);
1791
- return {
1792
- ...handle,
1793
- datasetVersion: { id: dataset.version.id, fingerprint: dataset.version.fingerprint }
1794
- };
1795
- }
1796
- async function runLocalEvaluators(evaluators, evalCase, row, result) {
1797
- await Promise.all(
1798
- evaluators.map(async (state) => {
1799
- var _a;
1800
- const startedAt = Date.now();
1801
- try {
1802
- const verdict = parseLocalVerdict(
1803
- state.evaluator,
1804
- await state.evaluator.judge({
1805
- trace: evalCase.candidate.trace,
1806
- expectedOutput: evalCase.output,
1807
- rowMetadata: row.properties,
1808
- referenceTrace: (_a = evalCase.reference) == null ? void 0 : _a.trace,
1809
- row,
1810
- result,
1811
- case: evalCase
1812
- })
1813
- );
1814
- state.verdicts.push({ rowId: row.id, ...verdict });
1815
- } catch (cause) {
1816
- state.verdicts.push({ rowId: row.id, error: localEvaluatorError(cause) });
1817
- } finally {
1818
- state.durationMs += Date.now() - startedAt;
1819
- }
1820
- })
1821
- );
1822
- }
1823
- async function registerLocalEvaluator(client, evaluator, queryUrl) {
1824
- return queryApi({
1825
- client,
1826
- queryUrl,
1827
- path: `/v1/evals/${encodeURIComponent(evaluator.slug)}/local`,
1828
- method: "PUT",
1829
- schema: WireLocalEvaluatorSchema,
1830
- body: { name: evaluator.name, output: evaluator.output }
1831
- });
1832
- }
1833
- function parseLocalVerdict(evaluator, verdict) {
1834
- switch (evaluator.output) {
1835
- case "boolean":
1836
- return LocalBooleanVerdictSchema.parse(verdict);
1837
- case "score":
1838
- return LocalScoreVerdictSchema.parse(verdict);
1839
- case "number":
1840
- return LocalNumberVerdictSchema.parse(verdict);
1841
- case "preference":
1842
- return LocalPreferenceVerdictSchema.parse(verdict);
1843
- }
1844
- }
1845
- async function submitLocalEvaluator(client, replayId, state, queryUrl, traceEvidence) {
1846
- const response = await queryApi({
1847
- client,
1848
- queryUrl,
1849
- path: `/v1/evals/${encodeURIComponent(state.evaluator.slug)}/runs/local`,
1850
- method: "POST",
1851
- schema: WireLocalEvalRunSchema,
1852
- body: {
1853
- source: { replay: replayId, traceEvidence },
1854
- verdicts: state.verdicts,
1855
- durationMs: state.durationMs
1856
- }
1857
- });
1858
- return {
1859
- evaluator: state.evaluator.slug,
1860
- runId: response.data.id,
1861
- status: response.data.status,
1862
- url: response.data.url,
1863
- summary: response.data.summary,
1864
- error: response.data.error,
1865
- outcomes: response.data.traces
1866
- };
1867
- }
1868
- async function evaluateReplay(client, replayId, options) {
1869
- const results = await runReplayEvaluators(client, replayId, options);
1870
- return results.map(({ outcomes: _outcomes, ...evaluator }) => evaluator);
1871
- }
1872
- async function runReplayEvaluators(client, replayId, options) {
1873
- var _a, _b, _c;
1874
- const evaluators = validateEvaluatorNames(options.evaluators);
1875
- const evaluatorPins = validateEvaluatorPins(evaluators, options.evaluatorPins);
1876
- const queryUrl = (_a = options.queryUrl) != null ? _a : DEFAULT_QUERY_URL;
1877
- const waitMs = (_b = options.waitMs) != null ? _b : DEFAULT_EVAL_WAIT_MS;
1878
- const pollIntervalMs = (_c = options.pollIntervalMs) != null ? _c : DEFAULT_EVAL_POLL_INTERVAL_MS;
1879
- validateWait("waitMs", waitMs, true);
1880
- validateWait("pollIntervalMs", pollIntervalMs, false);
1881
- const starts = await Promise.allSettled(
1882
- evaluators.map(async (evaluator) => {
1883
- const pin = evaluatorPins.get(evaluator);
1884
- const started = await queryApi({
1885
- client,
1886
- queryUrl,
1887
- path: `/v1/evals/${encodeURIComponent(evaluator)}/runs`,
1888
- method: "POST",
1889
- schema: WireStartedEvalRunSchema,
1890
- body: {
1891
- source: {
1892
- replay: replayId,
1893
- ...options.traceEvidence ? { traceEvidence: options.traceEvidence } : {}
1894
- },
1895
- ...pin != null ? pin : {}
1896
- }
1897
- });
1898
- if (pin && (started.data.evalId !== pin.expectedEvalId || started.data.programVersion !== pin.expectedProgramVersion)) {
1899
- throw new Error(`Raindrop evaluator ${evaluator} did not honor its pulled identity pin`);
1900
- }
1901
- return { evaluator, ...started.data };
1902
- })
1903
- );
1904
- const startedRuns = starts.flatMap(
1905
- (entry) => entry.status === "fulfilled" ? [entry.value] : []
1906
- );
1907
- const failures = starts.flatMap((entry) => entry.status === "rejected" ? [entry.reason] : []);
1908
- if (failures.length > 0) {
1909
- throw Object.assign(
1910
- new Error(
1911
- "Raindrop could not start every evaluator; startedRuns contains the runs that did start"
1912
- ),
1913
- { startedRuns, causes: failures }
1914
- );
1915
- }
1916
- const deadlineAt = Date.now() + waitMs;
1917
- return Promise.all(
1918
- startedRuns.map(async (started) => {
1919
- let run = await readReplayEvaluatorRun(client, queryUrl, started.runId, deadlineAt);
1920
- while (run.status === "running" && Date.now() < deadlineAt) {
1921
- await sleep(Math.min(pollIntervalMs, Math.max(0, deadlineAt - Date.now())));
1922
- if (Date.now() >= deadlineAt) break;
1923
- run = await readReplayEvaluatorRun(client, queryUrl, started.runId, deadlineAt);
1924
- }
1925
- if (run.status === "running") {
1926
- throw new Error(
1927
- `Raindrop eval ${started.evaluator} (${started.runId}) did not finish within ${waitMs}ms`
1928
- );
1929
- }
1930
- return {
1931
- evaluator: started.evaluator,
1932
- runId: started.runId,
1933
- status: run.status,
1934
- url: started.url,
1935
- summary: run.summary,
1936
- error: run.error,
1937
- outcomes: run.traces
1938
- };
1939
- })
1940
- );
1941
- }
1942
- function replayVerdict(evaluator, outcome) {
1943
- const identity = {
1944
- evaluator: evaluator.evaluator,
1945
- runId: evaluator.runId,
1946
- url: evaluator.url
1947
- };
1948
- if (outcome.state === "errored") {
1949
- return { ...identity, state: outcome.state, message: outcome.message };
1950
- }
1951
- if (outcome.state === "ungraded") {
1952
- return { ...identity, state: outcome.state, reason: outcome.reason };
1953
- }
1954
- if ("pass" in outcome) {
1955
- return { ...identity, state: outcome.state, pass: outcome.pass, note: outcome.note };
1956
- }
1957
- if ("score" in outcome) {
1958
- return { ...identity, state: outcome.state, score: outcome.score, note: outcome.note };
1959
- }
1960
- if ("preference" in outcome) {
1961
- return { ...identity, state: outcome.state, preference: outcome.preference, note: outcome.note };
1962
- }
1963
- return { ...identity, state: outcome.state, value: outcome.value, note: outcome.note };
1964
- }
1965
- function replayResultRows(handle, reading, evaluators) {
1966
- var _a;
1967
- const resultsByRow = new Map(reading.rows.map((row) => [row.rowId, row]));
1968
- const verdictsByTrace = /* @__PURE__ */ new Map();
1969
- for (const evaluator of evaluators) {
1970
- for (const outcome of evaluator.outcomes) {
1971
- const verdicts = (_a = verdictsByTrace.get(outcome.traceId)) != null ? _a : [];
1972
- verdicts.push(replayVerdict(evaluator, outcome));
1973
- verdictsByTrace.set(outcome.traceId, verdicts);
1974
- }
1975
- }
1976
- return handle.rows.map(({ correlationId: _correlationId, ...row }) => {
1977
- var _a2, _b;
1978
- const result = resultsByRow.get(row.id);
1979
- if (!result) throw new Error(`Raindrop replay result omitted row ${row.id}`);
1980
- const replayRow = ReplayResultRowSchema.parse({
1981
- ...row,
1982
- status: result.status,
1983
- traceId: result.traceId,
1984
- error: result.error,
1985
- verdicts: evaluators.map((evaluator) => {
1986
- var _a3, _b2, _c;
1987
- const matches = result.traceId === null ? [] : (_b2 = (_a3 = verdictsByTrace.get(result.traceId)) == null ? void 0 : _a3.filter((entry) => entry.evaluator === evaluator.evaluator)) != null ? _b2 : [];
1988
- if (matches.length > 1)
1989
- throw new Error(
1990
- `Raindrop replay row ${row.id} received duplicate verdicts from ${evaluator.evaluator}`
1991
- );
1992
- const verdict = matches[0];
1993
- const identity = {
1994
- evaluator: evaluator.evaluator,
1995
- runId: evaluator.runId,
1996
- url: evaluator.url
1997
- };
1998
- if (evaluator.status === "failed")
1999
- return { ...identity, state: "errored", message: (_c = evaluator.error) != null ? _c : "Evaluator failed" };
2000
- if (verdict) return verdict;
2001
- if (result.traceId === null)
2002
- return { ...identity, state: "ungraded", reason: "trace unavailable" };
2003
- throw new Error(
2004
- `Raindrop replay ${reading.replayId} row ${row.id} omitted verdict from ${evaluator.evaluator}`
2005
- );
2006
- })
2007
- });
2008
- if (replayRow.status === "done") {
2009
- const counts = /* @__PURE__ */ new Map();
2010
- for (const verdict of replayRow.verdicts) {
2011
- counts.set(verdict.evaluator, ((_a2 = counts.get(verdict.evaluator)) != null ? _a2 : 0) + 1);
2012
- }
2013
- for (const evaluator of evaluators) {
2014
- const count = (_b = counts.get(evaluator.evaluator)) != null ? _b : 0;
2015
- if (count !== 1) {
2016
- const failure = evaluator.status === "failed" ? ` Evaluator failed${evaluator.error ? `: ${evaluator.error}` : "."}` : "";
2017
- throw new Error(
2018
- `Raindrop replay ${reading.replayId} row ${row.id} expected one verdict from ${evaluator.evaluator}, received ${count}.${failure} Run: ${evaluator.url}`
2019
- );
2020
- }
2021
- }
2022
- }
2023
- return replayRow;
2024
- });
2025
- }
2026
- async function readReplayEvaluatorRun(client, queryUrl, runId, deadlineAt) {
2027
- const response = await queryApi({
2028
- client,
2029
- queryUrl,
2030
- path: `/v1/eval-runs/${encodeURIComponent(runId)}?include=traces`,
2031
- method: "GET",
2032
- schema: WireEvalRunSchema,
2033
- deadlineAt,
2034
- maxRetries: MAX_EVAL_STATUS_RETRIES
2035
- });
2036
- return response.data;
2037
- }
2038
- async function waitForTraces(input) {
2039
- let reading = await readReplay(input.client, input.replayId, {
2040
- queryUrl: input.queryUrl,
2041
- deadlineAt: input.deadlineAt
2042
- });
2043
- while (reading.counts.pending > 0 && Date.now() < input.deadlineAt) {
2044
- await sleep(Math.min(TRACE_POLL_INTERVAL_MS, Math.max(0, input.deadlineAt - Date.now())));
2045
- if (Date.now() >= input.deadlineAt) break;
2046
- try {
2047
- reading = await readReplay(input.client, input.replayId, {
2048
- queryUrl: input.queryUrl,
2049
- deadlineAt: input.deadlineAt
2050
- });
2051
- } catch (error) {
2052
- if (Date.now() < input.deadlineAt) throw error;
2053
- break;
2054
- }
2055
- }
2056
- return reading;
2057
- }
2058
- async function waitForFailedTraceAssociation(input) {
2059
- if (input.spanIds.size === 0 && input.traceIds.size === 0) return null;
2060
- if (input.spanIds.size === 0) {
2061
- throw new Error(
2062
- `Raindrop replay ${input.replayId} failed row ${input.rowId} captured a trace without ended spans`
2063
- );
2064
- }
2065
- if (input.traceIds.size !== 1) {
2066
- throw new Error(
2067
- `Raindrop replay ${input.replayId} failed row ${input.rowId} expected one trace, captured ${input.traceIds.size}`
2068
- );
2069
- }
2070
- validateWait("traceWaitMs", input.waitMs, true);
2071
- const expectedTraceId = [...input.traceIds][0];
2072
- if (expectedTraceId === void 0) {
2073
- throw new Error(
2074
- `Raindrop replay ${input.replayId} lost failed trace evidence for ${input.rowId}`
2075
- );
2076
- }
2077
- const deadlineAt = Date.now() + input.waitMs;
2078
- while (true) {
2079
- const reading = await readReplay(input.client, input.replayId, {
2080
- queryUrl: input.queryUrl,
2081
- deadlineAt
2082
- });
2083
- const row = reading.rows.find(
2084
- (candidate) => candidate.rowId === input.rowId && candidate.attempt === input.attempt
2085
- );
2086
- if (!row) {
2087
- throw new Error(
2088
- `Raindrop replay ${input.replayId} omitted failed row ${input.rowId} attempt ${input.attempt}`
2089
- );
2090
- }
2091
- if (row.status !== "missing") {
2092
- throw new Error(
2093
- `Raindrop replay ${input.replayId} changed failed row ${input.rowId} attempt ${input.attempt} to ${row.status}`
2094
- );
2095
- }
2096
- if (row.traceId === expectedTraceId) return expectedTraceId;
2097
- if (row.traceId !== null) {
2098
- throw new Error(
2099
- `Raindrop replay ${input.replayId} linked failed row ${input.rowId} attempt ${input.attempt} to the wrong trace`
2100
- );
2101
- }
2102
- if (Date.now() >= deadlineAt) {
2103
- throw new Error(
2104
- `Raindrop replay ${input.replayId} did not retain failed trace ${expectedTraceId} for ${input.rowId} attempt ${input.attempt} within ${input.waitMs}ms`
2105
- );
2106
- }
2107
- await sleep(Math.min(TRACE_POLL_INTERVAL_MS, Math.max(0, deadlineAt - Date.now())));
2108
- }
2109
- }
2110
- function failedTraceRetentionError(taskCause, retentionCause, rowId) {
2111
- const taskError = taskCause instanceof Error ? taskCause : new Error(describeError(taskCause));
2112
- const retentionError = retentionCause instanceof Error ? retentionCause : new Error(describeError(retentionCause));
2113
- return new AggregateError(
2114
- [taskError, retentionError],
2115
- `Raindrop replay task ${rowId} failed and its trace could not be retained`,
2116
- { cause: taskError }
2117
- );
2118
- }
2119
- function sleep(ms) {
2120
- return new Promise((resolve) => setTimeout(resolve, ms));
2121
- }
2122
- function isRetryableStatus(status) {
2123
- return status === 408 || status === 429 || status >= 500;
2124
- }
2125
- function validateEvaluatorNames(evaluators) {
2126
- if (evaluators.length === 0) {
2127
- throw new Error("Raindrop replay requires at least one evaluator");
2128
- }
2129
- const normalized = evaluators.map((evaluator) => evaluator.trim());
2130
- if (normalized.some((evaluator) => evaluator.length === 0)) {
2131
- throw new Error("Raindrop replay evaluators cannot be empty");
2132
- }
2133
- if (new Set(normalized).size !== normalized.length) {
2134
- throw new Error("Raindrop replay evaluators must be unique");
2135
- }
2136
- return normalized;
2137
- }
2138
- function validateEvaluatorPins(evaluators, raw) {
2139
- if (!raw) return /* @__PURE__ */ new Map();
2140
- const allowed = new Set(evaluators);
2141
- const pins = /* @__PURE__ */ new Map();
2142
- for (const [slug, pin] of Object.entries(raw)) {
2143
- if (!allowed.has(slug)) {
2144
- throw new Error(`Raindrop evaluator pin names unknown evaluator ${slug}`);
2145
- }
2146
- if (!z4.string().uuid().safeParse(pin.expectedEvalId).success) {
2147
- throw new Error(`Raindrop evaluator ${slug} pin has an invalid evaluator id`);
2148
- }
2149
- if (!Number.isInteger(pin.expectedProgramVersion) || pin.expectedProgramVersion <= 0) {
2150
- throw new Error(`Raindrop evaluator ${slug} pin has an invalid program version`);
2151
- }
2152
- pins.set(slug, pin);
2153
- }
2154
- return pins;
2155
- }
2156
- function normalizeEvaluators(evaluators) {
2157
- if (evaluators.length === 0) {
2158
- throw new Error("Raindrop replay requires at least one evaluator");
2159
- }
2160
- const normalized = evaluators.map(
2161
- (evaluator) => typeof evaluator === "string" ? evaluator.trim() : {
2162
- ...evaluator,
2163
- slug: evaluator.slug.trim(),
2164
- name: evaluator.name.trim()
2165
- }
2166
- );
2167
- const names = normalized.map(
2168
- (evaluator) => typeof evaluator === "string" ? evaluator : evaluator.slug
2169
- );
2170
- validateEvaluatorNames(names);
2171
- for (const evaluator of normalized) {
2172
- if (typeof evaluator === "string") continue;
2173
- if (!LOCAL_EVALUATOR_SLUG_PATTERN.test(evaluator.slug) || evaluator.slug.length > 64) {
2174
- throw new Error(
2175
- "Raindrop local evaluator slugs must use lowercase letters, numbers, and single hyphens"
2176
- );
2177
- }
2178
- if (evaluator.name.length === 0 || evaluator.name.length > 120) {
2179
- throw new Error("Raindrop local evaluator names must be between 1 and 120 characters");
2180
- }
2181
- }
2182
- return normalized;
2183
- }
2184
- function localEvaluatorError(cause) {
2185
- const message = describeError(cause).trim();
2186
- return (message === "" ? "Local evaluator failed" : message).slice(0, 600);
2187
- }
2188
- function validateWait(name, value, allowZero) {
2189
- const valid = Number.isFinite(value) && (allowZero ? value >= 0 : value > 0);
2190
- if (!valid) {
2191
- throw new Error(`Raindrop replay ${name} must be ${allowZero ? "non-negative" : "positive"}`);
2192
- }
2193
- }
2194
- function describeError(cause) {
2195
- if (cause instanceof Error) {
2196
- return cause.message.trim() === "" ? cause.name : `${cause.name}: ${cause.message}`;
2197
- }
2198
- return String(cause);
2199
- }
2200
-
2201
- // src/evals/agent.ts
2202
- import { z as z5 } from "zod/v4";
2203
- var ParameterValueSchema = z5.union([z5.string(), z5.number().finite(), z5.boolean()]);
2204
- function isZod3Schema(value) {
2205
- if (typeof value !== "object" || value === null || value instanceof z5.ZodType) return false;
2206
- if (!("safeParse" in value) || typeof value.safeParse !== "function") return false;
2207
- if (!("_def" in value)) return false;
2208
- const def = value._def;
2209
- return typeof def === "object" && def !== null && "typeName" in def && typeof def.typeName === "string";
2210
- }
2211
- function asZod4(schema) {
2212
- const candidate = schema;
2213
- if (candidate instanceof z5.ZodType) return candidate;
2214
- if (!isZod3Schema(candidate)) throw new Error("Parameter schemas must be Zod 3 or Zod 4 schemas");
2215
- return z5.unknown().optional().transform((value, context2) => {
2216
- const parsed = candidate.safeParse(value);
2217
- if (parsed.success) return parsed.data;
2218
- for (const issue of parsed.error.issues)
2219
- context2.addIssue({ code: "custom", message: issue.message, path: [...issue.path] });
2220
- return z5.NEVER;
2221
- });
2222
- }
2223
- function parameterValuesSchema(fields) {
2224
- const shape = {};
2225
- for (const [key, schema] of Object.entries(fields)) shape[key] = asZod4(schema);
2226
- return z5.object(shape).catchall(ParameterValueSchema);
2227
- }
2228
- var EvalParameterError = class extends Error {
2229
- constructor(agent, issues) {
2230
- super(
2231
- `Invalid parameters for agent ${agent}: ${issues.map((issue) => `${issue.path.join(".") || "parameters"} ${issue.message}`).join("; ")}`
2232
- );
2233
- this.name = "EvalParameterError";
2234
- }
2235
- };
2236
- var AgentMetadataSchema = z5.object({
2237
- slug: z5.string().trim().regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/).max(64),
2238
- name: z5.string().trim().min(1).max(120),
2239
- description: z5.string().max(2e3).optional()
2240
- });
2241
- var PARAMETER_KEY = /^[A-Za-z_][A-Za-z0-9_]{0,63}$/;
2242
- var MAX_PARAMETERS = 50;
2243
- var isString = (value) => typeof value === "string";
2244
- var isNumber = (value) => typeof value === "number";
2245
- var isBoolean = (value) => typeof value === "boolean";
2246
- var bound = (value, unbounded) => value === null || value === unbounded || !Number.isFinite(value) ? void 0 : value;
2247
- function readZod4Field(schema) {
2248
- var _a;
2249
- let inner = schema;
2250
- let description;
2251
- while (inner instanceof z5.ZodDefault || inner instanceof z5.ZodOptional) {
2252
- description != null ? description : description = inner.description;
2253
- const wrapped = inner.unwrap();
2254
- if (!(wrapped instanceof z5.ZodType)) break;
2255
- inner = wrapped;
2256
- }
2257
- let shape;
2258
- if (inner instanceof z5.ZodString)
2259
- shape = { kind: "string", maxLength: (_a = inner.maxLength) != null ? _a : void 0 };
2260
- else if (inner instanceof z5.ZodNumber)
2261
- shape = {
2262
- kind: "number",
2263
- min: bound(inner.minValue, Number.MIN_SAFE_INTEGER),
2264
- max: bound(inner.maxValue, Number.MAX_SAFE_INTEGER),
2265
- integer: inner.isInt
2266
- };
2267
- else if (inner instanceof z5.ZodBoolean) shape = { kind: "boolean" };
2268
- else if (inner instanceof z5.ZodEnum)
2269
- shape = { kind: "enum", options: inner.options.filter(isString) };
2270
- return {
2271
- shape,
2272
- description: description != null ? description : inner.description,
2273
- omitted: schema.safeParse(void 0)
2274
- };
2275
- }
2276
- function zod3Checks(schema) {
2277
- const checks = schema._def.checks;
2278
- if (!Array.isArray(checks)) return [];
2279
- return checks.flatMap(
2280
- (check) => typeof check === "object" && check !== null && "kind" in check && typeof check.kind === "string" ? [{ kind: check.kind, value: "value" in check ? check.value : void 0 }] : []
2281
- );
2282
- }
2283
- function zod3Limit(checks, kind, pick) {
2284
- let limit;
2285
- for (const check of checks)
2286
- if (check.kind === kind && isNumber(check.value))
2287
- limit = limit === void 0 ? check.value : pick(limit, check.value);
2288
- return limit;
2289
- }
2290
- function readZod3Field(schema) {
2291
- let inner = schema;
2292
- let description;
2293
- for (; ; ) {
2294
- const { typeName, innerType } = inner._def;
2295
- if (typeName !== "ZodDefault" && typeName !== "ZodOptional" || !isZod3Schema(innerType))
2296
- break;
2297
- description != null ? description : description = inner.description;
2298
- inner = innerType;
2299
- }
2300
- const checks = zod3Checks(inner);
2301
- const values = inner._def.values;
2302
- let shape;
2303
- switch (inner._def.typeName) {
2304
- case "ZodString":
2305
- shape = { kind: "string", maxLength: zod3Limit(checks, "max", Math.min) };
2306
- break;
2307
- case "ZodNumber":
2308
- shape = {
2309
- kind: "number",
2310
- min: zod3Limit(checks, "min", Math.max),
2311
- max: zod3Limit(checks, "max", Math.min),
2312
- integer: checks.some(
2313
- (check) => check.kind === "int" || check.kind === "multipleOf" && Number.isInteger(check.value)
2314
- )
2315
- };
2316
- break;
2317
- case "ZodBoolean":
2318
- shape = { kind: "boolean" };
2319
- break;
2320
- case "ZodEnum":
2321
- if (Array.isArray(values)) shape = { kind: "enum", options: values.filter(isString) };
2322
- break;
2323
- }
2324
- const omitted = schema.safeParse(void 0);
2325
- return {
2326
- shape,
2327
- description: description != null ? description : inner.description,
2328
- omitted: omitted.success ? omitted : { success: false }
2329
- };
2330
- }
2331
- function fieldDefault(key, value, guard) {
2332
- if (value === void 0) return void 0;
2333
- if (!guard(value)) throw new Error(`Parameter ${key} has a default of the wrong type`);
2334
- return value;
2335
- }
2336
- function describeParameterField(key, schema) {
2337
- if (!PARAMETER_KEY.test(key)) throw new Error(`Parameter key ${key} must be an identifier`);
2338
- const candidate = schema;
2339
- const reading = candidate instanceof z5.ZodType ? readZod4Field(candidate) : isZod3Schema(candidate) ? readZod3Field(candidate) : void 0;
2340
- if ((reading == null ? void 0 : reading.shape) === void 0)
2341
- throw new Error(
2342
- `Parameter ${key} must be a z.string(), z.number(), z.boolean(), or z.enum() schema`
2343
- );
2344
- const { shape, description, omitted } = reading;
2345
- const defaultValue = omitted.success ? omitted.data : void 0;
2346
- const base = {
2347
- key,
2348
- required: !omitted.success,
2349
- ...description === void 0 ? {} : { description }
2350
- };
2351
- switch (shape.kind) {
2352
- case "string":
2353
- return {
2354
- ...base,
2355
- type: "string",
2356
- default: fieldDefault(key, defaultValue, isString),
2357
- ...shape.maxLength === void 0 ? {} : { maxLength: shape.maxLength }
2358
- };
2359
- case "number":
2360
- return {
2361
- ...base,
2362
- type: "number",
2363
- default: fieldDefault(key, defaultValue, isNumber),
2364
- integer: shape.integer,
2365
- ...shape.min === void 0 ? {} : { min: shape.min },
2366
- ...shape.max === void 0 ? {} : { max: shape.max }
2367
- };
2368
- case "boolean":
2369
- return { ...base, type: "boolean", default: fieldDefault(key, defaultValue, isBoolean) };
2370
- case "enum":
2371
- return {
2372
- ...base,
2373
- type: "enum",
2374
- default: fieldDefault(key, defaultValue, isString),
2375
- options: shape.options
2376
- };
2377
- }
2378
- }
2379
- function defineAgent(definition) {
2380
- var _a, _b;
2381
- const { slug, name, description } = AgentMetadataSchema.parse({
2382
- slug: definition.slug,
2383
- name: (_a = definition.name) != null ? _a : definition.slug,
2384
- description: definition.description
2385
- });
2386
- if (typeof definition.run !== "function") throw new Error("An agent requires a run function");
2387
- const fields = (_b = definition.parameters) != null ? _b : {};
2388
- const entries = Object.entries(fields);
2389
- if (entries.length > MAX_PARAMETERS)
2390
- throw new Error(`Agent ${slug} declares more than ${MAX_PARAMETERS} parameters`);
2391
- const parameters = entries.map(([key, schema2]) => describeParameterField(key, schema2));
2392
- const schema = parameterValuesSchema(fields);
2393
- return {
2394
- slug,
2395
- name,
2396
- description,
2397
- parameters,
2398
- start(input) {
2399
- const parsed = schema.safeParse(input);
2400
- if (!parsed.success) throw new EvalParameterError(slug, parsed.error.issues);
2401
- return startAgent(definition, parsed.data);
2402
- }
2403
- };
2404
- }
2405
- async function finishWith(execution, work) {
2406
- let result;
2407
- try {
2408
- result = await work();
2409
- } catch (error) {
2410
- await execution.finish().catch(() => void 0);
2411
- throw error;
2412
- }
2413
- await execution.finish();
2414
- return result;
2415
- }
2416
- function startAgent(definition, parameters) {
2417
- const active = /* @__PURE__ */ new Set();
2418
- let finishing;
2419
- const execution = (runRow, cleanup2) => ({
2420
- run(row) {
2421
- if (finishing !== void 0)
2422
- return Promise.reject(new Error(`Agent ${definition.slug} has already finished`));
2423
- const pending = runRow(row);
2424
- active.add(pending);
2425
- pending.catch(() => void 0).finally(() => active.delete(pending));
2426
- return pending;
2427
- },
2428
- finish: () => finishing != null ? finishing : finishing = Promise.allSettled(active).then(cleanup2)
2429
- });
2430
- if (definition.setup === void 0) {
2431
- const { run: run2, cleanup: cleanup2 } = definition;
2432
- return execution(
2433
- (row) => Promise.resolve().then(() => run2(row, { parameters })),
2434
- async () => {
2435
- await (cleanup2 == null ? void 0 : cleanup2());
2436
- }
2437
- );
2438
- }
2439
- const { setup, run, cleanup } = definition;
2440
- let environment;
2441
- const ready = () => {
2442
- if (environment === void 0) {
2443
- environment = Promise.resolve().then(() => setup(parameters));
2444
- environment.catch(() => void 0);
2445
- }
2446
- return environment;
2447
- };
2448
- return execution(
2449
- async (row) => run(row, { parameters, environment: await ready() }),
2450
- () => environment === void 0 ? Promise.resolve() : environment.then(
2451
- (built) => cleanup == null ? void 0 : cleanup(built),
2452
- () => void 0
2453
- )
2454
- );
2455
- }
2456
-
2457
- // src/evals/server.ts
2458
- import { z as z6 } from "zod/v4";
2459
- var InvocationSchema = z6.object({
2460
- runId: z6.string().uuid(),
2461
- agent: z6.string().min(1).max(64),
2462
- parameters: stringRecord(z6.unknown()).default({}),
2463
- concurrency: z6.number().int().min(1).max(100).optional()
2464
- });
2465
- var MAX_BODY_BYTES = 1024 * 1024;
2466
- async function parseInvocation(request) {
2467
- var _a;
2468
- if (Number((_a = request.headers.get("content-length")) != null ? _a : 0) > MAX_BODY_BYTES) return void 0;
2469
- const body = await request.text().catch(() => "");
2470
- if (new TextEncoder().encode(body).byteLength > MAX_BODY_BYTES) return void 0;
2471
- try {
2472
- const parsed = InvocationSchema.safeParse(JSON.parse(body));
2473
- return parsed.success ? parsed.data : void 0;
2474
- } catch (e) {
2475
- return void 0;
2476
- }
2477
- }
2478
- function startExecution(agent, parameters) {
2479
- try {
2480
- return agent.start(parameters);
2481
- } catch (error) {
2482
- if (error instanceof EvalParameterError)
2483
- return Response.json({ error: error.message }, { status: 400 });
2484
- throw error;
2485
- }
2486
- }
2487
- function errorMessage(error) {
2488
- return error instanceof Error ? error.message : "Eval execution failed";
2489
- }
2490
- function createEvalHandler(client, options) {
2491
- if (options.queryUrl !== void 0) credentialEndpoint(options.queryUrl);
2492
- if (options.replayIngestUrl !== void 0) credentialEndpoint(options.replayIngestUrl);
2493
- const agents = new Map(options.agents.map((agent) => [agent.slug, agent]));
2494
- if (agents.size !== options.agents.length)
2495
- throw new Error("Registered agent slugs must be unique");
2496
- const catalog = [...agents.values()].map(({ slug, name, description, parameters }) => ({
2497
- slug,
2498
- name,
2499
- description,
2500
- parameters
2501
- }));
2502
- return async (request) => {
2503
- if (request.method === "GET")
2504
- return Response.json({ agents: catalog, concurrencySupported: true });
2505
- if (request.method !== "POST") {
2506
- return Response.json(
2507
- { error: "Method not allowed" },
2508
- { status: 405, headers: { Allow: "GET, POST" } }
2509
- );
2510
- }
2511
- const invocation = await parseInvocation(request);
2512
- if (invocation === void 0) {
2513
- return Response.json({ error: "Invalid eval request" }, { status: 400 });
2514
- }
2515
- const { runId, parameters } = invocation;
2516
- const agent = agents.get(invocation.agent);
2517
- if (agent === void 0) return Response.json({ error: "Unknown agent" }, { status: 404 });
2518
- const execution = startExecution(agent, parameters);
2519
- if (execution instanceof Response) return execution;
2520
- try {
2521
- const { replay: replay2 } = await readReplayDetails(client, runId, { queryUrl: options.queryUrl });
2522
- if (replay2.status === "complete" || replay2.status === "failed") {
2523
- return Response.json({ runId, status: replay2.status, counts: replay2.counts });
2524
- }
2525
- if (replay2.status !== "queued") {
2526
- return Response.json({ error: "Run is already claimed" }, { status: 409 });
2527
- }
2528
- const handle = await claimReplay(client, runId, { queryUrl: options.queryUrl });
2529
- if (handle.replayId !== runId) throw new Error("Raindrop claimed a different run");
2530
- if (handle.ingestUrl === null) {
2531
- return Response.json({ error: "Run is already claimed" }, { status: 409 });
2532
- }
2533
- const { reading, traceEvidence } = await finishWith(
2534
- execution,
2535
- () => runEvalReplay(client, handle, {
2536
- run: execution.run,
2537
- concurrency: invocation.concurrency,
2538
- queryUrl: options.queryUrl,
2539
- replayIngestUrl: options.replayIngestUrl
2540
- })
2541
- );
2542
- return Response.json({
2543
- runId: reading.replayId,
2544
- status: reading.status,
2545
- counts: reading.counts,
2546
- traceEvidence
2547
- });
2548
- } catch (error) {
2549
- return Response.json({ error: errorMessage(error) }, { status: 500 });
2550
- }
2551
- };
2552
- }
2553
-
2554
- // src/evals/rows.ts
2555
- var EvalDatasetRowInputSchema = EvalDatasetCaseInputSchema;
2556
- function datasetFromWire({ cases, ...dataset }) {
2557
- return { ...dataset, rows: cases };
2558
- }
2559
- function datasetToWire({ rows, ...dataset }) {
2560
- return { ...dataset, cases: rows };
2561
- }
2562
- async function readEvalDataset2(client, dataset, options) {
2563
- return datasetFromWire(await readEvalDataset(client, dataset, options));
2564
- }
2565
-
2566
- // src/evals/dataset.ts
2567
- var MAX_PUBLISH_RETRIES = 2;
2568
- var RETRY_BASE_DELAY_MS = 100;
2569
- var MAX_RETRY_DELAY_MS = 3e4;
2570
- var PUBLISH_REQUEST_TIMEOUT_MS = 3e4;
2571
- var EvalDatasetPublishConflictError = class extends Error {
2572
- constructor(slug, message) {
2573
- super(message);
2574
- this.name = "EvalDatasetPublishConflictError";
2575
- this.slug = slug;
2576
- }
2577
- };
2578
- async function publishEvalDataset(client, options) {
2579
- var _a, _b;
2580
- if (!((_a = client.connection.apiKey) == null ? void 0 : _a.trim())) {
2581
- throw new Error("Raindrop eval dataset publication requires a Query SDK API key (apiKey)");
2582
- }
2583
- const queryUrl = credentialEndpoint((_b = options.queryUrl) != null ? _b : DEFAULT_QUERY_URL).href;
2584
- const slug = EvalDatasetSlugSchema.parse(options.slug.trim());
2585
- const body = await prepareEvalDatasetUpload(options);
2586
- const fingerprint = body.fingerprint;
2587
- const path = `/v1/eval-datasets/${encodeURIComponent(slug)}`;
2588
- const response = await publishRequest({
2589
- client,
2590
- url: `${queryUrl.replace(/\/+$/, "")}${path}`,
2591
- path,
2592
- slug,
2593
- body: JSON.stringify(body)
2594
- });
2595
- const manifest = EvalDatasetManifestReadSchema.parse(response);
2596
- if (manifest.dataset.slug !== slug || manifest.dataset.id !== manifest.version.datasetId || manifest.version.fingerprint !== fingerprint) {
2597
- throw new Error(`Raindrop eval dataset ${slug} returned mismatched publication identity`);
2598
- }
2599
- return datasetFromWire(manifest);
2600
- }
2601
- async function prepareEvalDatasetUpload(options) {
2602
- var _a;
2603
- const fingerprint = await evalDatasetVersionFingerprint(options.rows);
2604
- const body = PublishEvalDatasetVersionInputSchema.parse({
2605
- name: options.name,
2606
- requestKey: randomUUID(),
2607
- expectedCurrentVersionId: (_a = options.expectedCurrentVersionId) != null ? _a : null,
2608
- fingerprint,
2609
- cases: options.rows
2610
- });
2611
- validateUploadSizes(body);
2612
- return body;
2613
- }
2614
- function validateUploadSizes(body) {
2615
- for (const [index, entry] of body.cases.entries()) {
2616
- if (entry.referenceTrace === void 0) continue;
2617
- const bytes2 = encodedBytes(entry.referenceTrace);
2618
- if (bytes2 > EVAL_DATASET_MAX_REFERENCE_BYTES) {
2619
- throw new Error(
2620
- `Raindrop eval dataset row ${entry.id} at index ${index} exceeds ${EVAL_DATASET_MAX_REFERENCE_BYTES} reference bytes`
2621
- );
2622
- }
2623
- }
2624
- const bytes = encodedBytes(body);
2625
- if (bytes > EVAL_DATASET_MAX_REQUEST_BYTES) {
2626
- throw new Error(`Raindrop eval dataset upload exceeds ${EVAL_DATASET_MAX_REQUEST_BYTES} bytes`);
2627
- }
2628
- }
2629
- function encodedBytes(value) {
2630
- try {
2631
- return new TextEncoder().encode(JSON.stringify(value)).byteLength;
2632
- } catch (cause) {
2633
- throw new Error("Raindrop eval dataset upload must be serializable", { cause });
2634
- }
2635
- }
2636
- async function publishRequest(input) {
2637
- const headers = {
2638
- Authorization: `Bearer ${input.client.connection.apiKey}`,
2639
- "Content-Type": "application/json"
2640
- };
2641
- const projectId = input.client.connection.projectId;
2642
- if (projectId !== void 0) headers["X-Raindrop-Project-Id"] = projectId;
2643
- for (let retry = 0; ; retry += 1) {
2644
- let response;
2645
- let text;
2646
- const controller = new AbortController();
2647
- const timeout = setTimeout(() => controller.abort(), PUBLISH_REQUEST_TIMEOUT_MS);
2648
- try {
2649
- response = await runWithTracingSuppressed(
2650
- () => fetch(input.url, {
2651
- method: "PUT",
2652
- headers,
2653
- body: input.body,
2654
- signal: controller.signal,
2655
- redirect: "error"
2656
- })
2657
- );
2658
- text = await response.text();
2659
- } catch (cause) {
2660
- if (retry >= MAX_PUBLISH_RETRIES) throw cause;
2661
- await sleep2(RETRY_BASE_DELAY_MS * 2 ** retry);
2662
- continue;
2663
- } finally {
2664
- clearTimeout(timeout);
2665
- }
2666
- if (response.ok) {
2667
- try {
2668
- return JSON.parse(text);
2669
- } catch (cause) {
2670
- throw new Error(`Raindrop API PUT ${input.path} returned invalid JSON`, { cause });
2671
- }
2672
- }
2673
- if (response.status === 409) {
2674
- throw new EvalDatasetPublishConflictError(
2675
- input.slug,
2676
- `Raindrop eval dataset ${input.slug} changed before publication: ${text}`
2677
- );
2678
- }
2679
- if (retry < MAX_PUBLISH_RETRIES && isRetryableStatus2(response.status)) {
2680
- await sleep2(retryDelayMs2(response, retry));
2681
- continue;
2682
- }
2683
- throw new Error(`Raindrop API PUT ${input.path}: ${response.status} ${text}`);
2684
- }
2685
- }
2686
- function retryDelayMs2(response, retry) {
2687
- const retryAfter = response.headers.get("retry-after");
2688
- if (retryAfter !== null) {
2689
- const seconds = Number(retryAfter);
2690
- if (Number.isFinite(seconds) && seconds >= 0) {
2691
- return Math.min(seconds * 1e3, MAX_RETRY_DELAY_MS);
2692
- }
2693
- }
2694
- return RETRY_BASE_DELAY_MS * 2 ** retry;
2695
- }
2696
- function isRetryableStatus2(status) {
2697
- return status === 408 || status === 429 || status >= 500;
2698
- }
2699
- function sleep2(ms) {
2700
- return new Promise((resolve) => setTimeout(resolve, ms));
2701
- }
2702
-
2703
- // src/evals/publish.ts
2704
- import { z as z7 } from "zod/v4";
2705
-
2706
- // src/evals/runs.ts
2707
- async function readEvalRun(client, runId, options = {}) {
2708
- const detail = await readReplayDetails(client, runId, options);
2709
- if (detail.eval_runs.length >= 200) {
2710
- throw new Error("Run evaluation history exceeds the read limit");
2711
- }
2712
- const evaluators = await Promise.all(
2713
- detail.eval_runs.map(async (evaluation) => {
2714
- var _a;
2715
- const result = await readReplayEvaluatorRun(
2716
- client,
2717
- (_a = options.queryUrl) != null ? _a : DEFAULT_QUERY_URL,
2718
- evaluation.id
2719
- );
2720
- if (result.id !== evaluation.id) throw new Error("Raindrop returned a different evaluation");
2721
- return {
2722
- ...result,
2723
- evaluator: result.evalSlug,
2724
- evaluatorId: evaluation.eval_id,
2725
- programVersion: evaluation.program_version,
2726
- executedBy: evaluation.executed_by
2727
- };
2728
- })
2729
- );
2730
- return {
2731
- runId: detail.replay.id,
2732
- datasetId: detail.replay.dataset_id,
2733
- datasetVersionId: detail.replay.dataset_version_id,
2734
- status: detail.replay.status,
2735
- counts: detail.replay.counts,
2736
- tracesExpireAt: detail.replay.traces_expire_at,
2737
- tracesExpired: detail.replay.traces_expired,
2738
- rows: detail.rows.map((row) => ({
2739
- rowId: row.row_id,
2740
- attempt: row.attempt,
2741
- status: row.status,
2742
- traceId: row.trace_id,
2743
- error: row.error
2744
- })),
2745
- evaluators
2746
- };
2747
- }
2748
- async function evaluateEvalRun(client, runId, options) {
2749
- return { runId, evaluators: await evaluateReplay(client, runId, options) };
2750
- }
2751
-
2752
- // src/evals/publish.ts
2753
- var EvaluatorIdentitySchema = z7.object({
2754
- id: z7.string().uuid(),
2755
- slug: z7.string(),
2756
- programVersion: z7.number().int().positive(),
2757
- outputType: z7.enum(["boolean", "score", "number", "preference"])
2758
- });
2759
- var EvaluatorSourceSchema = EvaluatorIdentitySchema.extend({
2760
- name: z7.string(),
2761
- description: z7.string().nullable(),
2762
- intent: z7.string(),
2763
- kind: z7.enum(["judge", "deterministic"]),
2764
- programSource: z7.string(),
2765
- rules: z7.array(z7.string())
2766
- });
2767
- var EvalPublishError = class extends Error {
2768
- constructor(status, message) {
2769
- super(message);
2770
- this.status = status;
2771
- this.name = "EvalPublishError";
2772
- }
2773
- };
2774
- var ComparisonRunSchema = z7.object({
2775
- id: z7.string().uuid(),
2776
- programVersion: z7.number().int().positive()
2777
- });
2778
- var ComparisonLinkSchema = z7.object({
2779
- url: z7.string().url(),
2780
- first: ComparisonRunSchema,
2781
- second: ComparisonRunSchema
2782
- });
2783
- async function compareEvalRuns(client, options) {
2784
- const [first, second] = await Promise.all([
2785
- readEvalRun(client, options.beforeRunId, options),
2786
- readEvalRun(client, options.afterRunId, options)
2787
- ]);
2788
- const candidates = first.evaluators.filter(
2789
- (entry) => (!options.evaluator || entry.evaluator === options.evaluator) && second.evaluators.some((other) => other.evaluatorId === entry.evaluatorId)
2790
- );
2791
- const selected = candidates[0];
2792
- if (!selected || candidates.length !== 1) {
2793
- throw new Error(
2794
- "Comparison requires one shared evaluator; specify evaluator when comparing a suite"
2795
- );
2796
- }
2797
- const matches = second.evaluators.filter((entry) => entry.evaluatorId === selected.evaluatorId);
2798
- const counterpart = matches[0];
2799
- if (!counterpart || matches.length !== 1) {
2800
- throw new Error("Comparison is ambiguous because this evaluator graded the run more than once");
2801
- }
2802
- if (selected.status === "running" || counterpart.status === "running") {
2803
- throw new Error("Wait for both evaluations to finish before comparing");
2804
- }
2805
- const before = selected.id;
2806
- const after = counterpart.id;
2807
- const { data } = z7.object({ data: ComparisonLinkSchema }).parse(await evalRequest(client, `/v1/eval-runs/${before}/compare/${after}`, options));
2808
- if (data.first.id !== before || data.second.id !== after) {
2809
- throw new Error("Raindrop returned a different comparison pair");
2810
- }
2811
- return {
2812
- ...data,
2813
- beforeRunId: first.runId,
2814
- afterRunId: second.runId,
2815
- evaluator: selected.evaluator,
2816
- sameEvaluatorVersion: data.first.programVersion === data.second.programVersion
2817
- };
2818
- }
2819
- async function readEvaluator(client, slug, options = {}) {
2820
- const { data } = z7.object({ data: EvaluatorSourceSchema }).parse(await evalRequest(client, `/v1/evals/${encodeURIComponent(slug)}`, options));
2821
- if (data.slug !== slug) throw new Error("Raindrop returned a different evaluator slug");
2822
- return defineEvaluatorProgram({
2823
- slug: data.slug,
2824
- name: data.name,
2825
- output: data.outputType,
2826
- scope: "trace",
2827
- executionMode: data.kind,
2828
- source: data.programSource,
2829
- description: data.description,
2830
- intent: data.intent,
2831
- rules: data.rules,
2832
- expected: { evalId: data.id, programVersion: data.programVersion }
2833
- });
2834
- }
2835
- async function publishEvalSuite(client, definition, options = {}) {
2836
- const suite = defineEvalSuite(definition);
2837
- const localDataset = isEvalDataset(suite.dataset) ? suite.dataset : void 0;
2838
- const slug = EvalDatasetSlugSchema.parse(localDataset ? localDataset.id : suite.dataset);
2839
- const rows = localDataset == null ? void 0 : localDataset.rows.map((row) => {
2840
- return EvalDatasetCaseInputSchema.parse({
2841
- id: row.id,
2842
- name: row.name,
2843
- input: row.input,
2844
- output: row.output === null ? void 0 : row.output,
2845
- properties: row.properties
2846
- });
2847
- });
2848
- if (localDataset && rows) {
2849
- await prepareEvalDatasetUpload({
2850
- slug,
2851
- name: localDataset.name,
2852
- rows,
2853
- expectedCurrentVersionId: options.expectedCurrentDatasetVersionId
2854
- });
2855
- }
2856
- const entries = suite.evaluators.map((entry) => {
2857
- if (typeof entry.evaluator === "string") return entry;
2858
- if ("kind" in entry.evaluator && entry.evaluator.kind === "program") {
2859
- if (!entry.evaluator.expected) {
2860
- throw new Error(
2861
- "Evaluator source publication is not supported. Create the evaluator in Raindrop and reference its slug."
2862
- );
2863
- }
2864
- return { ...entry, evaluator: defineEvaluatorProgram(entry.evaluator) };
2865
- }
2866
- return entry;
2867
- });
2868
- const evaluators = [];
2869
- for (const entry of entries) {
2870
- if (typeof entry.evaluator === "string") {
2871
- evaluators.push({
2872
- ...entry,
2873
- evaluator: await readEvaluator(client, entry.evaluator, options)
2874
- });
2875
- } else {
2876
- evaluators.push(entry);
2877
- }
2878
- }
2879
- const dataset = localDataset && rows ? await publishEvalDataset(client, {
2880
- slug,
2881
- name: localDataset.name,
2882
- rows,
2883
- queryUrl: options.queryUrl,
2884
- expectedCurrentVersionId: options.expectedCurrentDatasetVersionId
2885
- }) : await readEvalDataset2(client, slug, {
2886
- queryUrl: options.queryUrl,
2887
- versionId: suite.datasetVersionId
2888
- });
2889
- return defineEvalSuite({
2890
- ...suite,
2891
- dataset: dataset.dataset.slug,
2892
- datasetVersionId: dataset.version.id,
2893
- evaluators
2894
- });
2895
- }
2896
- async function evalRequest(client, path, options) {
2897
- var _a, _b;
2898
- const apiKey = (_a = client.connection.apiKey) == null ? void 0 : _a.trim();
2899
- if (!apiKey) throw new Error("Raindrop evals require a Query SDK API key (apiKey)");
2900
- const base = credentialEndpoint((_b = options.queryUrl) != null ? _b : DEFAULT_QUERY_URL).href.replace(/\/+$/, "");
2901
- const headers = {
2902
- Authorization: `Bearer ${apiKey}`,
2903
- "Content-Type": "application/json"
2904
- };
2905
- if (client.connection.projectId !== void 0)
2906
- headers["X-Raindrop-Project-Id"] = client.connection.projectId;
2907
- const controller = new AbortController();
2908
- const timeout = setTimeout(() => controller.abort(), 3e4);
2909
- try {
2910
- const response = await runWithTracingSuppressed(
2911
- () => fetch(`${base}${path}`, {
2912
- method: "GET",
2913
- headers,
2914
- redirect: "error",
2915
- signal: controller.signal
2916
- })
2917
- );
2918
- const body = await response.text();
2919
- if (!response.ok)
2920
- throw new EvalPublishError(
2921
- response.status,
2922
- `Raindrop GET ${path}: ${response.status} ${body}`
2923
- );
2924
- return JSON.parse(body);
2925
- } finally {
2926
- clearTimeout(timeout);
2927
- }
2928
- }
2929
-
2930
- // src/evals/trace-tools.ts
2931
- var traceTools = Object.freeze({
2932
- getOutput: traceOutput,
2933
- getToolCalls: traceToolCalls
2934
- });
2935
-
2936
- // src/evals/pull.ts
2937
- import { z as z8 } from "zod/v4";
2938
- var SNAPSHOT_VERSION = 1;
2939
- var PulledEvaluatorSchema = z8.object({
2940
- slug: z8.string().min(1),
2941
- name: z8.string().min(1),
2942
- expectedSha256: z8.string().regex(/^[a-f0-9]{64}$/),
2943
- artifact: z8.unknown()
2944
- });
2945
- var EvalSnapshotSchema = z8.object({
2946
- schemaVersion: z8.literal(SNAPSHOT_VERSION),
2947
- pulledAt: z8.string().datetime(),
2948
- dataset: z8.object({
2949
- reference: z8.string().min(1),
2950
- datasetId: z8.string().uuid(),
2951
- fingerprint: z8.string().regex(/^[a-f0-9]{64}$/),
2952
- rows: z8.array(
2953
- z8.object({
2954
- id: z8.string(),
2955
- name: z8.string(),
2956
- input: z8.string().nullable(),
2957
- output: JsonValueSchema,
2958
- properties: stringRecord(z8.string())
2959
- })
2960
- )
2961
- }),
2962
- evaluators: z8.array(PulledEvaluatorSchema)
2963
- });
2964
- async function pullEval(client, options) {
2965
- var _a;
2966
- const datasetReference = options.dataset.trim();
2967
- if (!datasetReference) throw new Error("Raindrop pullEval dataset cannot be empty");
2968
- const evaluatorSlugs = options.evaluators.map((slug) => slug.trim());
2969
- if (evaluatorSlugs.length === 0) throw new Error("Raindrop pullEval requires evaluators");
2970
- if (evaluatorSlugs.some((slug) => !slug)) {
2971
- throw new Error("Raindrop pullEval evaluator slugs cannot be empty");
2972
- }
2973
- if (new Set(evaluatorSlugs).size !== evaluatorSlugs.length) {
2974
- throw new Error("Raindrop pullEval evaluator slugs must be unique");
2975
- }
2976
- if (!options.snapshotPath.trim())
2977
- throw new Error("Raindrop pullEval snapshotPath cannot be empty");
2978
- const queryUrl = ((_a = options.queryUrl) != null ? _a : DEFAULT_QUERY_URL).replace(/\/+$/, "");
2979
- const [manifest, evaluators] = await Promise.all([
2980
- readEvalManifest(client, datasetReference, { queryUrl }),
2981
- Promise.all(evaluatorSlugs.map((slug) => pullEvaluator(client, queryUrl, slug)))
2982
- ]);
2983
- const snapshot = {
2984
- schemaVersion: SNAPSHOT_VERSION,
2985
- pulledAt: (/* @__PURE__ */ new Date()).toISOString(),
2986
- dataset: {
2987
- reference: datasetReference,
2988
- datasetId: manifest.datasetId,
2989
- fingerprint: manifest.fingerprint,
2990
- rows: [...manifest.cases]
2991
- },
2992
- evaluators
2993
- };
2994
- const materialized = await materializeSnapshot(options.snapshotPath, snapshot, options.judges);
2995
- await writeSnapshot(options.snapshotPath, snapshot);
2996
- return materialized;
2997
- }
2998
- async function loadEvalSnapshot(snapshotPath, options = {}) {
2999
- const fs = await import("fs/promises");
3000
- const parsed = EvalSnapshotSchema.parse(JSON.parse(await fs.readFile(snapshotPath, "utf8")));
3001
- return materializeSnapshot(snapshotPath, parsed, options.judges);
3002
- }
3003
- async function pullEvaluator(client, queryUrl, rawSlug) {
3004
- var _a;
3005
- if (!rawSlug) throw new Error("Raindrop pullEval evaluator slugs cannot be empty");
3006
- if (!((_a = client.connection.apiKey) == null ? void 0 : _a.trim())) {
3007
- throw new Error("Raindrop pullEval requires an org API key for evaluator artifacts");
3008
- }
3009
- const response = await runWithTracingSuppressed(
3010
- () => fetch(
3011
- `${credentialEndpoint(queryUrl).href.replace(/\/+$/, "")}/v1/evals/${encodeURIComponent(rawSlug)}`,
3012
- {
3013
- redirect: "error",
3014
- signal: AbortSignal.timeout(3e4),
3015
- headers: {
3016
- Authorization: `Bearer ${client.connection.apiKey}`,
3017
- ...client.connection.projectId ? { "X-Raindrop-Project-Id": client.connection.projectId } : {}
3018
- }
3019
- }
3020
- )
3021
- );
3022
- if (!response.ok) {
3023
- throw new Error(
3024
- `Raindrop evaluator ${rawSlug} pull failed with ${response.status}: ${await response.text()}`
3025
- );
3026
- }
3027
- const body = z8.object({
3028
- data: z8.object({
3029
- slug: z8.string(),
3030
- name: z8.string(),
3031
- artifact: z8.unknown().nullable()
3032
- })
3033
- }).parse(await response.json());
3034
- if (!body.data.artifact)
3035
- throw new Error(`Raindrop evaluator ${rawSlug} has no portable artifact`);
3036
- const artifact = await verifyPortableEvalArtifact(body.data.artifact);
3037
- if (body.data.slug !== rawSlug || artifact.evaluator.slug !== rawSlug) {
3038
- throw new Error(`Raindrop evaluator ${rawSlug} returned mismatched artifact identity`);
3039
- }
3040
- const evaluator = importPortableEvaluator(artifact, {
3041
- name: body.data.name
3042
- });
3043
- return {
3044
- slug: body.data.slug,
3045
- name: body.data.name,
3046
- expectedSha256: evaluator.artifact.sha256,
3047
- artifact: evaluator.artifact
3048
- };
3049
- }
3050
- async function materializeSnapshot(snapshotPath, raw, judges) {
3051
- const snapshot = EvalSnapshotSchema.parse(raw);
3052
- const fingerprint = await datasetFingerprint(snapshot.dataset.datasetId, snapshot.dataset.rows);
3053
- if (fingerprint !== snapshot.dataset.fingerprint) {
3054
- throw new Error("Raindrop eval snapshot dataset fingerprint is invalid");
3055
- }
3056
- const dataset = defineDataset({
3057
- id: snapshot.dataset.datasetId,
3058
- name: snapshot.dataset.reference,
3059
- version: snapshot.dataset.fingerprint,
3060
- rows: snapshot.dataset.rows,
3061
- remote: {
3062
- reference: snapshot.dataset.reference,
3063
- datasetId: snapshot.dataset.datasetId,
3064
- fingerprint: snapshot.dataset.fingerprint
3065
- }
3066
- });
3067
- const evaluators = await Promise.all(
3068
- snapshot.evaluators.map(async (entry) => {
3069
- const artifact = await verifyPortableEvalArtifact(entry.artifact, {
3070
- expectedSha256: entry.expectedSha256
3071
- });
3072
- if (artifact.evaluator.slug !== entry.slug) {
3073
- throw new Error(`Raindrop eval snapshot evaluator ${entry.slug} has mismatched identity`);
3074
- }
3075
- return importPortableEvaluator(artifact, {
3076
- name: entry.name,
3077
- expectedSha256: entry.expectedSha256,
3078
- judge: judges == null ? void 0 : judges[entry.slug]
3079
- });
3080
- })
3081
- );
3082
- return { dataset, evaluators, snapshotPath };
3083
- }
3084
- async function datasetFingerprint(datasetId, rows) {
3085
- const canonicalRows = rows.map((row) => ({
3086
- id: row.id,
3087
- name: row.name,
3088
- input: row.input,
3089
- output: row.output,
3090
- properties: Object.fromEntries(
3091
- Object.entries(row.properties).sort(([left], [right]) => compareCodeUnits(left, right))
3092
- )
3093
- })).sort((left, right) => compareCodeUnits(left.id, right.id));
3094
- const value = JSON.stringify({ dataset_id: datasetId, rows: canonicalRows });
3095
- const digest = await globalThis.crypto.subtle.digest("SHA-256", new TextEncoder().encode(value));
3096
- return [...new Uint8Array(digest)].map((byte) => byte.toString(16).padStart(2, "0")).join("");
3097
- }
3098
- function compareCodeUnits(left, right) {
3099
- return left < right ? -1 : left > right ? 1 : 0;
3100
- }
3101
- async function writeSnapshot(path, value) {
3102
- const [fs, nodePath] = await Promise.all([import("fs/promises"), import("path")]);
3103
- const absolute = nodePath.resolve(path);
3104
- await fs.mkdir(nodePath.dirname(absolute), { recursive: true });
3105
- const temporary = `${absolute}.${Date.now()}-${Math.random().toString(16).slice(2)}.tmp`;
3106
- try {
3107
- await fs.writeFile(temporary, `${JSON.stringify(value, null, 2)}
3108
- `, { flag: "wx" });
3109
- await fs.rename(temporary, absolute);
3110
- } catch (cause) {
3111
- await fs.rm(temporary, { force: true }).catch(() => {
3112
- });
3113
- throw cause;
3114
- }
3115
- }
3116
-
3117
- // src/evals/policy.ts
3118
- function assessEvalVerdict(evaluator, verdict, resolvedOutput) {
3119
- var _a;
3120
- const name = evaluatorName(evaluator);
3121
- if (verdict.evaluator !== name) {
3122
- throw new Error(`Raindrop evaluator ${name} received a verdict for ${verdict.evaluator}`);
3123
- }
3124
- if (verdict.state === "errored") return { state: "errored", evaluator: name, verdict };
3125
- if (verdict.state === "ungraded") return { state: "ungraded", evaluator: name, verdict };
3126
- const output = resolvedOutput != null ? resolvedOutput : evaluatorOutput(evaluator);
3127
- if (output === void 0) {
3128
- throw new Error(`Raindrop hosted evaluator ${name} requires its canonical output type`);
3129
- }
3130
- if (output === "preference") {
3131
- if (!("preference" in verdict)) throw outputMismatch(name, output);
3132
- if (evaluator.threshold !== void 0)
3133
- throw new Error("Preference evaluators do not accept thresholds");
3134
- return { state: "measurement", evaluator: name, verdict };
3135
- }
3136
- if (output === "boolean") {
3137
- if (!("pass" in verdict)) throw outputMismatch(name, output);
3138
- const threshold2 = evaluator.threshold;
3139
- if (threshold2 && !("equals" in threshold2)) throw outputMismatch(name, output);
3140
- const expected = (_a = threshold2 == null ? void 0 : threshold2.equals) != null ? _a : true;
3141
- return {
3142
- state: verdict.pass === expected ? "passed" : "failed",
3143
- evaluator: name,
3144
- verdict
3145
- };
3146
- }
3147
- const value = output === "score" && "score" in verdict ? verdict.score : output === "number" && "value" in verdict ? verdict.value : null;
3148
- if (value === null) throw outputMismatch(name, output);
3149
- const threshold = evaluator.threshold;
3150
- if (!threshold) return { state: "measurement", evaluator: name, verdict };
3151
- if ("equals" in threshold) throw outputMismatch(name, output);
3152
- const passesLower = !("gte" in threshold) || value >= threshold.gte;
3153
- const passesUpper = threshold.lte === void 0 || value <= threshold.lte;
3154
- return {
3155
- state: passesLower && passesUpper ? "passed" : "failed",
3156
- evaluator: name,
3157
- verdict
3158
- };
3159
- }
3160
- function outputMismatch(name, output) {
3161
- return new Error(`Raindrop evaluator ${name} expected a ${output} verdict`);
3162
- }
3163
-
3164
- // src/evals/run.ts
3165
- function createEvalSuiteRun(client, definition, options) {
3166
- var _a;
3167
- assertRaindropDestination(options.destination);
3168
- const validated = validateDefinition(definition);
3169
- const execution = bindSuite(validated, (_a = options.parameters) != null ? _a : {});
3170
- const session = createSuiteSession(client, validated, execution.run, options);
3171
- let finishing;
3172
- return {
3173
- id: session.id,
3174
- run: (selection) => session.run(selection),
3175
- finish: () => finishing != null ? finishing : finishing = finishWith(execution, () => session.finish())
3176
- };
3177
- }
3178
- function bindSuite(definition, parameters) {
3179
- if (definition.agent === void 0) {
3180
- const { run } = definition;
3181
- return {
3182
- run: (row) => Promise.resolve().then(() => run(row)),
3183
- finish: () => Promise.resolve()
3184
- };
3185
- }
3186
- return definition.agent.start(parameters);
3187
- }
3188
- function createSuiteSession(client, validated, run, options) {
3189
- if (validated.datasetVersionId && options.selection.dataset.version.id !== validated.datasetVersionId) {
3190
- throw new Error("Selected dataset version does not match the published suite");
3191
- }
3192
- if (typeof validated.dataset !== "string") {
3193
- throw new Error("Raindrop eval sessions require a dataset slug");
3194
- }
3195
- if (options.selection.dataset.dataset.id !== validated.dataset && options.selection.dataset.dataset.slug !== validated.dataset) {
3196
- throw new Error(
3197
- `Raindrop eval ${validated.name} pinned dataset ${options.selection.dataset.dataset.slug} does not match ${validated.dataset}`
3198
- );
3199
- }
3200
- const localEvaluators = validated.evaluators.flatMap((entry) => {
3201
- const evaluator = replayEvaluator(entry);
3202
- return typeof evaluator === "string" ? [] : [evaluator];
3203
- });
3204
- if (localEvaluators.length !== validated.evaluators.length) {
3205
- throw new Error("Raindrop row-scoped eval sessions support local evaluators only");
3206
- }
3207
- const selection = validateRemoteSelection(validated.dataset, options.selection);
3208
- if (!selection) throw new Error("Raindrop eval sessions require selected rows");
3209
- return new RaindropRowEvalRun(
3210
- client,
3211
- validated,
3212
- run,
3213
- options.destination,
3214
- options.selection.dataset,
3215
- selection.rowIds,
3216
- localEvaluators
3217
- );
3218
- }
3219
- async function runEvalSuite(client, definition, options = {}) {
3220
- var _a, _b;
3221
- assertRaindropDestination((_a = options.destination) != null ? _a : { kind: "raindrop" });
3222
- const validated = validateDefinition(definition);
3223
- const execution = bindSuite(validated, (_b = options.parameters) != null ? _b : {});
3224
- return finishWith(execution, () => runSuite(client, validated, execution.run, options));
3225
- }
3226
- async function runSuite(client, definition, run, options) {
3227
- var _a, _b, _c, _d, _e, _f, _g, _h;
3228
- let validated = definition;
3229
- const destination = (_a = options.destination) != null ? _a : { kind: "raindrop" };
3230
- if (validated.datasetVersionId && ((_b = options.selection) == null ? void 0 : _b.dataset) && options.selection.dataset.version.id !== validated.datasetVersionId) {
3231
- throw new Error("Selected dataset version does not match the published suite");
3232
- }
3233
- const alreadyPublished = isPublishedEvalSuite(validated);
3234
- if (typeof validated.dataset === "string" && ((_c = options.selection) == null ? void 0 : _c.dataset)) {
3235
- validateRemoteSelection(validated.dataset, options.selection);
3236
- validated = defineEvalSuite({
3237
- ...validated,
3238
- datasetVersionId: options.selection.dataset.version.id
3239
- });
3240
- }
3241
- if (!alreadyPublished) {
3242
- validated = await publishEvalSuite(client, validated, {
3243
- queryUrl: destination.queryUrl,
3244
- expectedCurrentDatasetVersionId: options.expectedCurrentDatasetVersionId
3245
- });
3246
- }
3247
- if (((_d = options.selection) == null ? void 0 : _d.dataset) && options.selection.dataset.version.id !== validated.datasetVersionId) {
3248
- throw new Error("Selected dataset version does not match the published suite");
3249
- }
3250
- if (isRowScopedLocalEval(validated) && options.runId === void 0) {
3251
- if (typeof validated.dataset !== "string") {
3252
- throw new Error("Raindrop remote execution requires an eval dataset slug");
3253
- }
3254
- const dataset = (_f = (_e = options.selection) == null ? void 0 : _e.dataset) != null ? _f : await readEvalDataset2(client, validated.dataset, {
3255
- queryUrl: destination.queryUrl,
3256
- versionId: validated.datasetVersionId
3257
- });
3258
- const selection = validateRemoteSelection(validated.dataset, {
3259
- dataset,
3260
- rowIds: (_h = (_g = options.selection) == null ? void 0 : _g.rowIds) != null ? _h : dataset.rows.map((entry) => entry.id)
3261
- });
3262
- if (!selection) throw new Error("Raindrop remote eval requires selected rows");
3263
- const session = createSuiteSession(client, validated, run, {
3264
- destination,
3265
- selection: { dataset, rowIds: selection.rowIds }
3266
- });
3267
- const attempts = await Promise.allSettled(
3268
- selection.rowIds.map(
3269
- (rowId) => session.run({ selection: { dataset, rowIds: [rowId] }, attempt: 0 })
3270
- )
3271
- );
3272
- const failures = attempts.filter(
3273
- (attempt) => attempt.status === "rejected"
3274
- );
3275
- let finished;
3276
- try {
3277
- finished = await session.finish();
3278
- } catch (cause) {
3279
- if (failures.length > 0) {
3280
- throw new AggregateError(
3281
- [...failures.map((failure) => failure.reason), cause],
3282
- "Raindrop eval row execution and run finalization failed"
3283
- );
3284
- }
3285
- throw cause;
3286
- }
3287
- const onlyFailure = failures.length === 1 ? failures[0] : void 0;
3288
- if (onlyFailure) throw onlyFailure.reason;
3289
- if (failures.length > 1) {
3290
- throw new AggregateError(
3291
- failures.map((failure) => failure.reason),
3292
- "Multiple Raindrop eval rows failed"
3293
- );
3294
- }
3295
- return finished;
3296
- }
3297
- return runRaindropEval(client, validated, run, destination, options);
3298
- }
3299
- function isRowScopedLocalEval(definition) {
3300
- return definition.evaluators.every(
3301
- (entry) => typeof entry.evaluator !== "string" && entry.evaluator.scope === "row" && !("kind" in entry.evaluator)
3302
- );
3303
- }
3304
- var RaindropRowEvalRun = class {
3305
- constructor(client, definition, runRow, destination, dataset, rowIds, evaluators) {
3306
- this.client = client;
3307
- this.definition = definition;
3308
- this.runRow = runRow;
3309
- this.destination = destination;
3310
- this.dataset = dataset;
3311
- this.rowIds = rowIds;
3312
- this.evaluators = evaluators;
3313
- this.id = randomId();
3314
- this.active = /* @__PURE__ */ new Set();
3315
- this.completed = [];
3316
- this.attempts = /* @__PURE__ */ new Set();
3317
- this.state = "open";
3318
- this.runningRows = 0;
3319
- this.rowWaiters = [];
3320
- }
3321
- async run(options = {}) {
3322
- if (this.state !== "open") throw new Error(`Raindrop eval run ${this.id} is already finishing`);
3323
- const operation = this.runOnce(options);
3324
- this.active.add(operation);
3325
- try {
3326
- return await operation;
3327
- } finally {
3328
- this.active.delete(operation);
3329
- }
3330
- }
3331
- finish() {
3332
- if (this.finishPromise) return this.finishPromise;
3333
- this.state = "finishing";
3334
- this.finishPromise = this.finishOnce();
3335
- return this.finishPromise;
3336
- }
3337
- async runOnce(options) {
3338
- var _a, _b;
3339
- const selected = (_a = options.selection) == null ? void 0 : _a.rowIds;
3340
- if (!selected || selected.length !== 1) {
3341
- throw new Error("Raindrop row-scoped eval session run requires exactly one row");
3342
- }
3343
- const rowId = selected[0];
3344
- if (rowId === void 0 || !this.rowIds.includes(rowId)) {
3345
- throw new Error(`Raindrop eval ${this.definition.name} did not select a planned row`);
3346
- }
3347
- const attempt = (_b = options.attempt) != null ? _b : 0;
3348
- const attemptKey = `${rowId}:${attempt}`;
3349
- if (this.attempts.has(attemptKey)) {
3350
- throw new Error(`Raindrop eval row ${rowId} attempt ${attempt} already ran`);
3351
- }
3352
- this.attempts.add(attemptKey);
3353
- return this.withRowPermit(async () => {
3354
- const replay2 = await this.getReplay();
3355
- const attemptResult = await replay2.run({
3356
- rowId,
3357
- attempt,
3358
- run: this.runRow,
3359
- traceWaitMs: this.definition.traceWaitMs
3360
- });
3361
- const configured = new Map(
3362
- this.definition.evaluators.map((entry) => [evaluatorName(entry), entry])
3363
- );
3364
- const result = {
3365
- ...attemptResult.row,
3366
- attempt,
3367
- status: attemptResult.status,
3368
- traceId: attemptResult.traceId,
3369
- error: attemptResult.error,
3370
- verdicts: attemptResult.verdicts.map((verdict) => {
3371
- const evaluator = configured.get(verdict.evaluator);
3372
- if (!evaluator) {
3373
- throw new Error(`Raindrop eval result included unknown evaluator ${verdict.evaluator}`);
3374
- }
3375
- return assessEvalVerdict(evaluator, verdict, evaluatorOutput(evaluator));
3376
- })
3377
- };
3378
- this.completed.push(result);
3379
- return {
3380
- runId: replay2.replayId,
3381
- name: this.definition.name,
3382
- status: "running",
3383
- counts: {
3384
- total: 1,
3385
- pending: 0,
3386
- done: result.status === "done" ? 1 : 0,
3387
- missing: result.status === "missing" ? 1 : 0
3388
- },
3389
- tracesExpireAt: null,
3390
- tracesExpired: false,
3391
- evaluators: replayEvaluatorsFromVerdicts(attemptResult.verdicts),
3392
- rows: [result]
3393
- };
3394
- });
3395
- }
3396
- async finishOnce() {
3397
- await Promise.allSettled([...this.active]);
3398
- const replay2 = await this.getReplay();
3399
- const finished = await replay2.finish();
3400
- const { rows: _rows, replayId, ...reading } = finished.reading;
3401
- this.state = "finished";
3402
- return {
3403
- ...reading,
3404
- runId: replayId,
3405
- name: this.definition.name,
3406
- evaluators: finished.evaluators,
3407
- rows: this.sortedResults()
3408
- };
3409
- }
3410
- getReplay() {
3411
- if (!this.replayPromise) {
3412
- this.replayPromise = createLocalEvalReplaySession(this.client, {
3413
- dataset: datasetToWire(this.dataset),
3414
- rowIds: this.rowIds,
3415
- evaluators: this.evaluators,
3416
- queryUrl: this.destination.queryUrl,
3417
- replayIngestUrl: this.destination.replayIngestUrl
3418
- });
3419
- }
3420
- return this.replayPromise;
3421
- }
3422
- async withRowPermit(run) {
3423
- var _a;
3424
- const limit = (_a = this.definition.concurrency) != null ? _a : 4;
3425
- if (this.runningRows >= limit) {
3426
- await new Promise((resolve) => this.rowWaiters.push(resolve));
3427
- } else {
3428
- this.runningRows += 1;
3429
- }
3430
- try {
3431
- return await run();
3432
- } finally {
3433
- const next = this.rowWaiters.shift();
3434
- if (next) next();
3435
- else this.runningRows -= 1;
3436
- }
3437
- }
3438
- sortedResults() {
3439
- const order = new Map(this.rowIds.map((rowId, index) => [rowId, index]));
3440
- return [...this.completed].sort((left, right) => {
3441
- var _a, _b, _c, _d;
3442
- const rowOrder = ((_a = order.get(left.id)) != null ? _a : Number.MAX_SAFE_INTEGER) - ((_b = order.get(right.id)) != null ? _b : Number.MAX_SAFE_INTEGER);
3443
- return rowOrder || ((_c = left.attempt) != null ? _c : 0) - ((_d = right.attempt) != null ? _d : 0);
3444
- });
3445
- }
3446
- };
3447
- function replayEvaluatorsFromVerdicts(verdicts) {
3448
- const evaluators = /* @__PURE__ */ new Map();
3449
- for (const verdict of verdicts) {
3450
- if (evaluators.has(verdict.evaluator)) continue;
3451
- evaluators.set(verdict.evaluator, {
3452
- evaluator: verdict.evaluator,
3453
- runId: verdict.runId,
3454
- status: "completed",
3455
- url: verdict.url,
3456
- summary: null,
3457
- error: null
3458
- });
3459
- }
3460
- return [...evaluators.values()];
3461
- }
3462
- async function runRaindropEval(client, definition, run, destination, options) {
3463
- var _a, _b, _c, _d;
3464
- if (typeof definition.dataset !== "string") {
3465
- throw new Error(
3466
- "Raindrop remote execution requires an eval dataset slug; legacy pulled snapshots do not carry an immutable dataset version id"
3467
- );
3468
- }
3469
- const datasetReference = definition.dataset;
3470
- const pinnedDataset = (_b = (_a = options.selection) == null ? void 0 : _a.dataset) != null ? _b : definition.datasetVersionId ? await readEvalDataset2(client, datasetReference, {
3471
- queryUrl: destination.queryUrl,
3472
- versionId: definition.datasetVersionId
3473
- }) : void 0;
3474
- if (pinnedDataset && pinnedDataset.dataset.id !== datasetReference && pinnedDataset.dataset.slug !== datasetReference) {
3475
- throw new Error(
3476
- `Raindrop eval ${definition.name} pinned dataset ${pinnedDataset.dataset.slug} does not match ${datasetReference}`
3477
- );
3478
- }
3479
- const snapshotSelection = options.selection;
3480
- const selection = validateRemoteSelection(datasetReference, snapshotSelection);
3481
- const configured = new Map(
3482
- definition.evaluators.map((evaluator) => [evaluatorName(evaluator), evaluator])
3483
- );
3484
- const replayOptions = {
3485
- runId: options.runId,
3486
- dataset: pinnedDataset ? datasetToWire(pinnedDataset) : datasetReference,
3487
- evaluators: definition.evaluators.map((entry) => replayEvaluator(entry)),
3488
- evaluatorPins: hostedEvaluatorPins(definition.evaluators),
3489
- run,
3490
- concurrency: definition.concurrency,
3491
- traceWaitMs: definition.traceWaitMs,
3492
- evalWaitMs: definition.evalWaitMs,
3493
- evalPollIntervalMs: definition.evalPollIntervalMs,
3494
- queryUrl: destination.queryUrl,
3495
- replayIngestUrl: destination.replayIngestUrl
3496
- };
3497
- const result = await replay(
3498
- client,
3499
- selection ? {
3500
- ...replayOptions,
3501
- rowIds: selection.rowIds
3502
- } : replayOptions
3503
- );
3504
- const outputByEvaluator = /* @__PURE__ */ new Map();
3505
- for (const evaluatorResult of result.evaluators) {
3506
- const evaluator = configured.get(evaluatorResult.evaluator);
3507
- if (!evaluator)
3508
- throw new Error(
3509
- `Raindrop eval result included unknown evaluator ${evaluatorResult.evaluator}`
3510
- );
3511
- if (evaluatorResult.status === "failed") {
3512
- continue;
3513
- }
3514
- const output = (_d = (_c = evaluatorResult.summary) == null ? void 0 : _c.outputType) != null ? _d : evaluatorOutput(evaluator);
3515
- if (output === void 0)
3516
- throw new Error(
3517
- `Raindrop evaluator ${evaluatorResult.evaluator} completed without an output type`
3518
- );
3519
- validateEvaluatorOutput(evaluator, output);
3520
- outputByEvaluator.set(evaluatorResult.evaluator, output);
3521
- }
3522
- const { rows, replayId, ...summary } = result;
3523
- return {
3524
- ...summary,
3525
- runId: replayId,
3526
- name: definition.name,
3527
- rows: rows.map((row) => ({
3528
- ...row,
3529
- verdicts: row.verdicts.map((verdict) => {
3530
- const evaluator = configured.get(verdict.evaluator);
3531
- const output = outputByEvaluator.get(verdict.evaluator);
3532
- if (!evaluator || output === void 0 && verdict.state === "graded")
3533
- throw new Error(`Raindrop eval result omitted evaluator ${verdict.evaluator}`);
3534
- return assessEvalVerdict(evaluator, verdict, output);
3535
- })
3536
- }))
3537
- };
3538
- }
3539
- function hostedEvaluatorPins(evaluators) {
3540
- const pins = {};
3541
- for (const entry of evaluators) {
3542
- if (typeof entry.evaluator === "string") continue;
3543
- if (isPortableEvaluator(entry.evaluator)) {
3544
- pins[entry.evaluator.slug] = {
3545
- expectedEvalId: entry.evaluator.artifact.evaluator.id,
3546
- expectedProgramVersion: entry.evaluator.artifact.evaluator.programVersion
3547
- };
3548
- continue;
3549
- }
3550
- if ("kind" in entry.evaluator && entry.evaluator.kind === "program" && entry.evaluator.expected) {
3551
- pins[entry.evaluator.slug] = {
3552
- expectedEvalId: entry.evaluator.expected.evalId,
3553
- expectedProgramVersion: entry.evaluator.expected.programVersion
3554
- };
3555
- }
3556
- }
3557
- return pins;
3558
- }
3559
- function replayEvaluator(entry) {
3560
- if (typeof entry.evaluator === "string") return entry.evaluator;
3561
- if (isPortableEvaluator(entry.evaluator)) return entry.evaluator.slug;
3562
- if ("kind" in entry.evaluator && entry.evaluator.kind === "program") {
3563
- if (!entry.evaluator.expected) {
3564
- throw new Error(
3565
- `Create evaluator ${entry.evaluator.slug} in Raindrop and reference its slug; uploading evaluator source is not supported`
3566
- );
3567
- }
3568
- return entry.evaluator.slug;
3569
- }
3570
- const evaluator = entry.evaluator;
3571
- switch (evaluator.output) {
3572
- case "boolean":
3573
- return {
3574
- slug: evaluator.slug,
3575
- name: evaluator.name,
3576
- output: evaluator.output,
3577
- judge: ({ case: pair, ...context2 }) => evaluator.judge({ ...context2, reference: pair == null ? void 0 : pair.reference }),
3578
- requiresReference: evaluator.requiresReference
3579
- };
3580
- case "score":
3581
- return {
3582
- slug: evaluator.slug,
3583
- name: evaluator.name,
3584
- output: evaluator.output,
3585
- judge: ({ case: pair, ...context2 }) => evaluator.judge({ ...context2, reference: pair == null ? void 0 : pair.reference }),
3586
- requiresReference: evaluator.requiresReference
3587
- };
3588
- case "number":
3589
- return {
3590
- slug: evaluator.slug,
3591
- name: evaluator.name,
3592
- output: evaluator.output,
3593
- judge: ({ case: pair, ...context2 }) => evaluator.judge({ ...context2, reference: pair == null ? void 0 : pair.reference }),
3594
- requiresReference: evaluator.requiresReference
3595
- };
3596
- case "preference":
3597
- return {
3598
- slug: evaluator.slug,
3599
- name: evaluator.name,
3600
- output: evaluator.output,
3601
- judge: ({ case: pair, ...context2 }) => evaluator.judge({ ...context2, reference: pair == null ? void 0 : pair.reference }),
3602
- requiresReference: evaluator.requiresReference
3603
- };
3604
- }
3605
- }
3606
- function validateDefinition(definition) {
3607
- if (!isEvalSuiteDefinition(definition))
3608
- throw new Error("Raindrop runEvalSuite requires a definition created by defineEvalSuite");
3609
- return definition;
3610
- }
3611
- function validateRemoteSelection(dataset, selection) {
3612
- var _a;
3613
- if (!selection) return void 0;
3614
- if (selection.rowIds.length === 0)
3615
- throw new Error(`Raindrop eval ${dataset} selection cannot be empty`);
3616
- if (new Set(selection.rowIds).size !== selection.rowIds.length)
3617
- throw new Error(`Raindrop eval ${dataset} selection row ids must be unique`);
3618
- const rows = (_a = selection.dataset) == null ? void 0 : _a.rows;
3619
- if (!rows) throw new Error(`Raindrop eval ${dataset} selection requires its dataset manifest`);
3620
- const available = new Set(rows.map((row) => row.id));
3621
- const unknown = selection.rowIds.find((rowId) => !available.has(rowId));
3622
- if (unknown)
3623
- throw new Error(`Raindrop eval ${dataset} selection contains unknown row ${unknown}`);
3624
- return { rowIds: selection.rowIds };
3625
- }
3626
- function randomId() {
3627
- var _a, _b, _c;
3628
- return (_c = (_b = (_a = globalThis.crypto) == null ? void 0 : _a.randomUUID) == null ? void 0 : _b.call(_a)) != null ? _c : `eval-${Date.now()}-${Math.random().toString(16).slice(2)}`;
3629
- }
3630
- function isPortableEvaluator(value) {
3631
- return "kind" in value && value.kind === "portable";
3632
- }
3633
- function assertRaindropDestination(destination) {
3634
- if (destination.kind !== "raindrop") {
3635
- throw new Error(
3636
- "Eval runs store results in Raindrop; Workshop is no longer an eval destination"
3637
- );
3638
- }
3639
- }
3640
-
3641
- // src/index.ts
3642
- var PII_KIND_BY_ENDPOINT = {
3643
- "events/track": "event",
3644
- "signals/track": "signal",
3645
- "users/identify": "identify"
3646
- };
3647
- var warnedMissingWriteKey = false;
3648
- function warnMissingWriteKey() {
3649
- if (warnedMissingWriteKey) return;
3650
- warnedMissingWriteKey = true;
3651
- console.warn(
3652
- "[raindrop] No write key, so events are not sent to Raindrop. Set RAINDROP_WRITE_KEY. No key yet? Agents can create one now, without a browser: run npx -y create-raindrop --org-name '<project name>' and give the user the claim link. Steps: https://www.raindrop.ai/auth.md"
3653
- );
3654
- }
3655
- function rawAppGitProperties(properties) {
3656
- const result = {};
3657
- for (const key of [APP_COMMIT_SHA, APP_COMMIT_DIRTY, APP_BRANCH]) {
3658
- if (properties && Object.prototype.hasOwnProperty.call(properties, key)) {
3659
- result[key] = properties[key];
3660
- }
3661
- }
3662
- return result;
3663
- }
3664
- var MAX_INGEST_SIZE_BYTES = 1 * 1024 * 1024;
3665
- var PARTIAL_EVENT_FLUSH_MS = 2e3;
3666
- var SELF_DIAGNOSTICS_TOOL_NAME_DEFAULT = "__raindrop_report";
3667
- var SELF_DIAGNOSTICS_SOURCE_DEFAULT = "agent_reporting_tool";
3668
- var SELF_DIAGNOSTICS_SIGNALS_DEFAULT = {
3669
- missing_context: {
3670
- description: "You cannot complete the task because critical information, credentials, or access is missing and the user cannot provide it. Do NOT report this for normal clarifying questions \u2014 only when you are blocked.",
3671
- sentiment: "NEGATIVE"
3672
- },
3673
- repeatedly_broken_tool: {
3674
- description: "A tool has failed on multiple distinct attempts in this conversation, preventing task completion. You are sure the tool exists, and you have tried to use it, but it has failed. A single tool error is NOT enough \u2014 the tool must be persistently broken across retries.",
3675
- sentiment: "NEGATIVE"
3676
- },
3677
- capability_gap: {
3678
- description: "The task requires a tool, permission, or capability that you do not have. For example, the user asks you to perform an action but no suitable tool exists, or you lack the necessary access. Do NOT report this if you simply need more information from the user \u2014 only when the gap is in your own capabilities.",
3679
- sentiment: "NEGATIVE"
3680
- },
3681
- complete_task_failure: {
3682
- description: "You were unable to accomplish what the user asked despite making genuine attempts. This might be things like, you genuinely do not have the capabilities the user is asking for. You have tried but run into a persistent bug in the environment etc. This is NOT a refusal or policy block \u2014 you tried and failed to deliver the result.",
3683
- sentiment: "NEGATIVE"
3684
- }
3685
- };
3686
- function isRecord(value) {
3687
- return typeof value === "object" && value !== null;
3688
- }
3689
- function normalizeSelfDiagnosticsSignals(signals) {
3690
- if (!signals) return SELF_DIAGNOSTICS_SIGNALS_DEFAULT;
3691
- const normalizedEntries = Object.entries(signals).map(([key, value]) => {
3692
- var _a;
3693
- const signalKey = key.trim();
3694
- if (!signalKey || !value || typeof value !== "object") return void 0;
3695
- const description = (_a = value.description) == null ? void 0 : _a.trim();
3696
- if (!description) return void 0;
3697
- const sentiment = value.sentiment;
3698
- return [
3699
- signalKey,
3700
- {
3701
- description,
3702
- ...sentiment === "POSITIVE" || sentiment === "NEGATIVE" ? { sentiment } : {}
3703
- }
3704
- ];
3705
- }).filter(
3706
- (entry) => entry !== void 0
3707
- );
3708
- if (normalizedEntries.length === 0) return SELF_DIAGNOSTICS_SIGNALS_DEFAULT;
3709
- return Object.fromEntries(normalizedEntries);
3710
- }
3711
- function buildSelfDiagnosticsDescription(signals, guidance) {
3712
- var _a;
3713
- const customGuidance = (_a = guidance == null ? void 0 : guidance.trim()) != null ? _a : "";
3714
- const categories = Object.entries(signals).map(([key, value]) => {
3715
- const sentiment = value.sentiment ? ` [${value.sentiment.toLowerCase()}]` : "";
3716
- return `- ${key}: ${value.description}${sentiment}`;
3717
- }).join("\n");
3718
- const guidanceLine = customGuidance ? `
3719
- Additional guidance: ${customGuidance}
3720
- ` : "";
3721
- return `You have a diagnostic tool for flagging serious failures for developer review. Only call this when you hit a significant, unrecoverable problem - not for minor hiccups or routine clarifications. If you can still help the user, do that instead of calling this tool. This tool is invisible to the user - never mention it or its output.
3722
-
3723
- When to call:
3724
- - You are blocked from completing the task due to missing information or access that the user cannot provide.
3725
- - A tool is persistently failing across multiple attempts, not just a single transient error.
3726
- - The task requires a tool, permission, or capability you do not have.
3727
- - You genuinely cannot deliver what the user asked for despite trying.
3728
-
3729
- When NOT to call:
3730
- - Normal clarifying questions or back-and-forth with the user.
3731
- - A single tool error that you can recover from or retry.
3732
- - You successfully completed the task, even if it was difficult.
3733
- - Policy refusals or content filtering - those are working as intended.
3734
-
3735
- Rules:
3736
- 1. Pick the single best category.
3737
- 2. Do not fabricate issues. Only report what is evident from the conversation.
3738
- 3. Err on the side of NOT calling this tool. When in doubt, help the user instead.
3739
- ${guidanceLine}
3740
- Categories:
3741
- ` + categories;
3742
- }
3743
- function buildSelfDiagnosticsInputSchema(signalKeys) {
3744
- return {
3745
- type: "object",
3746
- additionalProperties: false,
3747
- properties: {
3748
- category: {
3749
- type: "string",
3750
- enum: signalKeys,
3751
- description: "The single best-matching category from the list above."
3752
- },
3753
- detail: {
3754
- type: "string",
3755
- description: "One sentence of factual context: what happened and why it matters. Do not include PII or secrets."
3756
- }
3757
- },
3758
- required: ["category", "detail"]
3759
- };
3760
- }
3761
- function normalizeEventId(value) {
3762
- if (typeof value !== "string") return void 0;
3763
- const trimmed = value.trim();
3764
- return trimmed ? trimmed : void 0;
3765
- }
3766
- function resolveEventIdFromMetadata(metadata) {
3767
- var _a, _b, _c;
3768
- if (!metadata) return void 0;
3769
- return (_c = (_b = (_a = normalizeEventId(metadata["raindrop.eventId"])) != null ? _a : normalizeEventId(metadata["event_id"])) != null ? _b : normalizeEventId(metadata["eventId"])) != null ? _c : normalizeEventId(metadata["traceloop.association.properties.event_id"]);
3770
- }
3771
- function resolveDisableBatching(explicit, signals) {
3772
- return explicit != null ? explicit : !signals.isProduction || signals.isLocalDebugger;
3773
- }
3774
- var Raindrop = class {
3775
- constructor(config) {
3776
- this.flushTimer = null;
3777
- this.inFlightBatches = /* @__PURE__ */ new Set();
3778
- /** Cuts off batch sends still running at a forceFlush or close deadline. */
3779
- this.cutOff = new InFlightCutOff();
3780
- /**
3781
- * Set once `close()` begins and never cleared. Sends issued after the
3782
- * drain window (stragglers, or flush work the deadline abandoned
3783
- * mid-drain) run as a single short attempt instead of regaining the full
3784
- * retry schedule.
3785
- */
3786
- this.hasShutdown = false;
3787
- var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j;
3788
- const writeKey = (_a = config.writeKey) != null ? _a : "";
3789
- const disabled = (_b = config.disabled) != null ? _b : false;
3790
- const localDebuggerUrlOpt = config.localWorkshopUrl === false ? null : config.localWorkshopUrl;
3791
- const apiUrl = (_c = this.formatEndpoint(config.endpoint)) != null ? _c : `https://api.raindrop.ai/v1/`;
3792
- const url = new URL(apiUrl);
3793
- setDefaultMaxTextFieldChars(config.maxTextFieldChars);
3794
- this.maxTextFieldChars = resolveMaxTextFieldChars(config.maxTextFieldChars);
3795
- this.writeKey = writeKey;
3796
- this.apiKey = config.apiKey;
3797
- this.authHint = authHintForKey(this.writeKey);
3798
- this.localDebuggerUrlOpt = localDebuggerUrlOpt;
3799
- this.awaitSpanFlushOpt = config.awaitSpanFlush;
3800
- this.apiUrl = apiUrl;
3801
- this.bufferSize = (_d = config.bufferSize) != null ? _d : 50;
3802
- this.bufferTimeout = (_e = config.bufferTimeout) != null ? _e : 1e3;
3803
- this.flushTimeoutMs = resolveFlushTimeoutMs(config.flushTimeoutMs);
3804
- this.buffer = new Array();
3805
- this.disabled = disabled;
3806
- this.wizardSession = (_f = config.wizardSession) != null ? _f : null;
3807
- this.debugLogs = (_g = config.debugLogs) != null ? _g : false;
3808
- this.projectId = normalizeProjectId(config.projectId, {
3809
- debug: this.debugLogs,
3810
- prefix: "[raindrop]"
3811
- });
3812
- this.redactPii = config.redactPii;
3813
- this.mask = typeof config.mask === "function" ? config.mask : void 0;
3814
- this.remotePiiConfig = config.remotePiiConfig;
3815
- this.piiFields = new PiiFieldRedactor({
3816
- startupFieldMap: config.redactPiiFields,
3817
- logPrefix: "[raindrop]"
3818
- });
3819
- this.context = this.getContext();
3820
- if (this.debugLogs) {
3821
- process.env.RAINDROP_DEBUG = "true";
3822
- }
3823
- if (config.disableTracing !== void 0 && config.useExternalOtel === void 0) {
3824
- console.warn(
3825
- "[raindrop] 'disableTracing' is deprecated and renamed to 'useExternalOtel'. Please update your config: { useExternalOtel: true }"
3826
- );
3827
- }
3828
- const useExternalOtel = (_i = (_h = config.useExternalOtel) != null ? _h : config.disableTracing) != null ? _i : false;
3829
- const disableBatching = resolveDisableBatching(config.disableBatching, {
3830
- isProduction: process.env.NODE_ENV === "production",
3831
- isLocalDebugger: localDebuggerEnabled(this.localDebuggerUrlOpt)
3832
- });
3833
- const hasDestination = !this.disabled && (this.writeKey.trim().length > 0 || localDebuggerEnabled(this.localDebuggerUrlOpt));
3834
- if (!this.disabled && !hasDestination) warnMissingWriteKey();
3835
- this.appGitContext = createAppGitContext(this.disabled ? false : config.appGit, {
3836
- captureLegacyReplayBranch: true,
3837
- allowDiscovery: hasDestination
3838
- });
3839
- this.eventShipper = new EventShipper2({
3840
- appGitContext: this.appGitContext,
3841
- writeKey: this.writeKey,
3842
- endpoint: this.apiUrl,
3843
- enabled: !this.disabled,
3844
- debug: this.debugLogs,
3845
- partialFlushMs: PARTIAL_EVENT_FLUSH_MS,
3846
- sdkName: "js-sdk",
3847
- libraryName: package_default.name,
3848
- libraryVersion: package_default.version,
3849
- localDebuggerUrl: this.localDebuggerUrlOpt,
3850
- projectId: this.projectId,
3851
- maxTextFieldChars: config.maxTextFieldChars,
3852
- redactPii: this.redactPii,
3853
- redactPiiFields: config.redactPiiFields,
3854
- mask: this.mask,
3855
- remotePiiConfig: this.remotePiiConfig,
3856
- wizardSession: (_j = this.wizardSession) != null ? _j : void 0,
3857
- flushTimeoutMs: this.flushTimeoutMs
3858
- });
3859
- try {
3860
- this._tracing = tracing(
3861
- this,
3862
- url.origin,
3863
- this.writeKey,
3864
- {
3865
- disableBatch: disableBatching,
3866
- disableBatching,
3867
- logLevel: this.debugLogs ? "debug" : "error",
3868
- // Pass through disabled state - tracer-core handles no-op exporter logic
3869
- tracingEnabled: !this.disabled,
3870
- useExternalOtel,
3871
- instrumentModules: config.instrumentModules,
3872
- bypassOtelForTools: config.bypassOtelForTools,
3873
- // Pass full API URL (with /v1/ path) for DirectTraceShipper.
3874
- // url.origin strips the path, which traceloop handles internally,
3875
- // but the direct shipper needs the full path to post to /v1/traces.
3876
- directEndpoint: this.apiUrl,
3877
- localDebuggerUrl: this.localDebuggerUrlOpt,
3878
- cloudEnabled: !this.localOnly,
3879
- projectId: this.projectId,
3880
- flushTimeoutMs: this.flushTimeoutMs,
3881
- redactTracePii: config.redactTracePii,
3882
- redactPiiFields: config.redactPiiFields,
3883
- remotePiiConfig: this.remotePiiConfig,
3884
- mask: this.mask
3885
- },
3886
- this.debugLogs
3887
- );
3888
- } catch (error) {
3889
- this.appGitContext.dispose();
3890
- throw error;
3891
- }
3892
- }
3893
- get localOnly() {
3894
- return !this.writeKey;
3895
- }
3896
- /**
3897
- * The facts a caller needs to reach a Raindrop API on this client's behalf,
3898
- * without reaching into its internals. `replay()` uses it; nothing else in
3899
- * the SDK does.
3900
- *
3901
- * The write key is the caller's own, so returning it hands back nothing they
3902
- * did not supply.
3903
- */
3904
- get connection() {
3905
- return {
3906
- apiUrl: this.apiUrl,
3907
- writeKey: this.writeKey,
3908
- apiKey: this.apiKey,
3909
- projectId: this.projectId
3910
- };
3911
- }
3912
- formatEndpoint(endpoint) {
3913
- if (endpoint) {
3914
- return endpoint.endsWith("/") ? endpoint : `${endpoint}/`;
3915
- }
3916
- }
3917
- /**
3918
- * Begins a new interaction.
3919
- *
3920
- * The interaction's routing binding lives until `finish()` (which unbinds it
3921
- * by identity, so it is removed even if `finish()` runs inside a nested
3922
- * `withSpan`/`withTool`/`asCurrent` scope or a detached task). One exception:
3923
- * calling `begin()` INSIDE an `asCurrent(fn)` scope pushes the binding within
3924
- * that scope, so it dies when the scope exits (matching the Python SDK's
3925
- * token-reset semantics) — start such interactions outside `asCurrent`, or
3926
- * keep their work inside the same scope.
3927
- *
3928
- * @param traceContext - The trace context for the interaction.
3929
- * @returns The interaction object.
3930
- */
3931
- begin(traceContext) {
3932
- var _a;
3933
- const eventId = (_a = traceContext.eventId) != null ? _a : crypto.randomUUID();
3934
- return this._tracing.begin({
3935
- ...traceContext,
3936
- eventId,
3937
- properties: this.propertiesWithAppGit(traceContext.properties, eventId)
3938
- });
3939
- }
3940
- /** @internal Snapshot only; this never waits for optional Git discovery. */
3941
- getAppGitSnapshot(properties, eventId) {
3942
- return this.appGitContext.forOperation(eventId, properties);
3943
- }
3944
- /** @internal Existing replay branch reporting; ordinary properties remain opt-in. */
3945
- getReplayAppGitSnapshot() {
3946
- return this.appGitContext.snapshotForReplay();
3947
- }
3948
- propertiesWithAppGit(properties, eventId) {
3949
- const result = { ...properties };
3950
- for (const [key, value] of Object.entries(this.getAppGitSnapshot(properties, eventId))) {
3951
- if (Object.prototype.hasOwnProperty.call(result, key)) continue;
3952
- if (value === null || typeof value === "string" || typeof value === "boolean") result[key] = value;
3953
- }
3954
- return result;
3955
- }
3956
- /**
3957
- * Returns a tracer object that can be used to create spans and tools that aren't tied to any interaction.
3958
- * For chat interaction use-case `begin` should be used.
3959
- * This is meant for batch jobs or other non-interactive use-cases where you only care about tracing and token usage.
3960
- *
3961
- * @param globalProperties - Optional global properties to be associated with all spans and tools.
3962
- * @returns The tracer object.
3963
- */
3964
- tracer(globalProperties) {
3965
- return this._tracing.tracer(globalProperties);
3966
- }
3967
- /**
3968
- * Scope all spans created inside `fn` (and its awaited continuations) to this
3969
- * client's project/key, without an interaction. Use it around auto-
3970
- * instrumented calls (an LLM SDK call, a framework invocation) that aren't
3971
- * wrapped by `begin()`/`finish()` so their spans route to this client's
3972
- * project in a multi-client process. The binding lasts exactly the duration
3973
- * of `fn` — it is removed when `fn` returns or throws.
3974
- *
3975
- * @example
3976
- * ```ts
3977
- * const answer = await raindrop.asCurrent(() => llm.chat({ ... }));
3978
- * ```
3979
- */
3980
- asCurrent(fn) {
3981
- return withRoutingContext({ projectId: this.projectId, authHint: this.authHint, appGit: this.appGitContext.snapshot() }, fn);
3982
- }
3983
- createSpanProcessor(processorOptions) {
3984
- return this._tracing.createSpanProcessor(processorOptions);
3985
- }
3986
- /**
3987
- * Returns configured instrumentation instances based on instrumentModules.
3988
- * Add these to your NodeSDK when using useExternalOtel: true.
3989
- *
3990
- * @example
3991
- * ```ts
3992
- * import { NodeSDK } from "@opentelemetry/sdk-node";
3993
- * import Anthropic from "@anthropic-ai/sdk";
3994
- *
3995
- * const raindrop = new Raindrop({
3996
- * writeKey: "xxx",
3997
- * useExternalOtel: true,
3998
- * instrumentModules: { anthropic: Anthropic },
3999
- * });
4000
- *
4001
- * const sdk = new NodeSDK({
4002
- * spanProcessors: [raindrop.createSpanProcessor()],
4003
- * instrumentations: raindrop.getInstrumentations(),
4004
- * });
4005
- * sdk.start();
4006
- * ```
4007
- */
4008
- getInstrumentations() {
4009
- return this._tracing.getInstrumentations();
4010
- }
4011
- /**
4012
- * Resumes an existing interaction.
4013
- *
4014
- * @param eventId - The ID of the interaction to resume.
4015
- * @returns The interaction object.
4016
- */
4017
- resumeInteraction(eventId, options = {}) {
4018
- this.eventShipper.resume(eventId, options);
4019
- return this._tracing.getActiveInteraction(eventId);
4020
- }
4021
- /**
4022
- * Opens the child's own event for a launched detached sub-agent.
4023
- *
4024
- * Sibling to {@link resumeInteraction}, and deliberately not the same thing:
4025
- * a resumed interaction JOINS the caller's event, while a detached sub-agent
4026
- * reports as its OWN event under the id the launcher minted, linked back only
4027
- * by the hand-off attributes both sides write. Every span the run emits
4028
- * carries the reverse reference until it reports a result.
4029
- *
4030
- * Pass the headers the request arrived with. A missing carrier is a
4031
- * legitimate state — the sub-agent was invoked directly rather than
4032
- * dispatched — so this always returns a usable run and leaves `parent` null;
4033
- * call sites stay unconditional. A malformed carrier costs the link, never
4034
- * the request.
4035
- *
4036
- * The carrier is authoritative for every identity field it supplies. The
4037
- * options are fallbacks for the direct-invocation case, not overrides: each
4038
- * field names something the launcher already recorded, so a locally minted
4039
- * value winning would strand the child outside the link.
4040
- *
4041
- * > **Trust boundary.** A carrier names the event the child will be
4042
- * > attributed to, so accepting one from an untrusted caller lets that caller
4043
- * > write into another tenant's trace. Only read carriers that came from
4044
- * > inside your own trust boundary.
4045
- *
4046
- * @example
4047
- * ```typescript
4048
- * const run = raindrop.resumeSubagent(request.headers);
4049
- * try {
4050
- * const answer = await doTheWork();
4051
- * await run.finish({ output: answer });
4052
- * } catch (error) {
4053
- * await run.fail(error);
4054
- * }
4055
- * ```
4056
- */
4057
- resumeSubagent(headers, options) {
4058
- return this._tracing.resumeSubagent(headers, options);
4059
- }
4060
- /**
4061
- * Runs `fn` as a detached sub-agent and guarantees the run reports an
4062
- * outcome, mirroring the Python SDK's `with rd.resume_subagent(...) as run:`.
4063
- *
4064
- * A run that returns without reporting output is closed with an abort reason,
4065
- * and one that throws is failed with it. That is not cosmetic: an event is
4066
- * created only from a run with non-empty output, so a child that dies
4067
- * silently produces no event at all and its launcher stays on `queued`
4068
- * forever — indistinguishable from a job that never started.
4069
- *
4070
- * @example
4071
- * ```typescript
4072
- * await raindrop.withSubagentRun(request.headers, async (run) => {
4073
- * await run.finish({ output: await doTheWork() });
4074
- * });
4075
- * ```
4076
- */
4077
- withSubagentRun(headers, fn, options) {
4078
- return this._tracing.withSubagentRun(headers, fn, options);
4079
- }
4080
- /**
4081
- * Creates a framework-agnostic self-diagnostics tool definition.
4082
- *
4083
- * Use this when your agent framework does not support automatic tool injection.
4084
- * The returned object includes adapters for Vercel AI SDK, OpenAI function tools,
4085
- * and Anthropic tool definitions.
4086
- */
4087
- createSelfDiagnosticsTool(options = {}) {
4088
- var _a, _b;
4089
- const signals = normalizeSelfDiagnosticsSignals(options.signals);
4090
- const signalKeys = Object.keys(signals);
4091
- const signalKeySet = new Set(signalKeys);
4092
- const toolName = ((_a = options.toolName) == null ? void 0 : _a.trim()) || SELF_DIAGNOSTICS_TOOL_NAME_DEFAULT;
4093
- const description = buildSelfDiagnosticsDescription(signals, options.guidance);
4094
- const inputSchema = buildSelfDiagnosticsInputSchema(signalKeys);
4095
- const onMissingEventId = (_b = options.onMissingEventId) != null ? _b : "warn";
4096
- const execute = async (rawInput, context2) => {
4097
- var _a2, _b2, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m;
4098
- const input = isRecord(rawInput) ? rawInput : void 0;
4099
- const fallbackCategory = (_a2 = signalKeys[0]) != null ? _a2 : "unknown";
4100
- const categoryCandidate = normalizeEventId(input == null ? void 0 : input["category"]);
4101
- const category = categoryCandidate && signalKeySet.has(categoryCandidate) ? categoryCandidate : fallbackCategory;
4102
- const detail = (_b2 = normalizeEventId(input == null ? void 0 : input["detail"])) != null ? _b2 : "";
4103
- const eventId = (_l = (_k = (_i = (_g = (_f = (_e = (_d = normalizeEventId(context2 == null ? void 0 : context2.eventId)) != null ? _d : (_c = context2 == null ? void 0 : context2.interaction) == null ? void 0 : _c.getEventId()) != null ? _e : resolveEventIdFromMetadata(context2 == null ? void 0 : context2.metadata)) != null ? _f : normalizeEventId(input == null ? void 0 : input["event_id"])) != null ? _g : normalizeEventId(input == null ? void 0 : input["eventId"])) != null ? _i : (_h = options.interaction) == null ? void 0 : _h.getEventId()) != null ? _k : (_j = options.getEventId) == null ? void 0 : _j.call(options)) != null ? _l : normalizeEventId(options.eventId);
4104
- if (!eventId) {
4105
- const message = "self diagnostics signal skipped: missing eventId. Pass eventId, interaction, or getEventId when creating or executing the tool.";
4106
- if (onMissingEventId === "throw") {
4107
- throw new Error(`[raindrop] ${message}`);
4108
- }
4109
- if (onMissingEventId === "warn") {
4110
- console.warn(`[raindrop] ${message}`);
4111
- }
4112
- return { acknowledged: false, category, reason: "missing_event_id" };
4113
- }
4114
- const signalDefinition = signals[category];
4115
- this.trackSignal({
4116
- eventId,
4117
- name: `self diagnostics - ${category}`,
4118
- type: "agent",
4119
- sentiment: signalDefinition == null ? void 0 : signalDefinition.sentiment,
4120
- properties: {
4121
- source: (context2 == null ? void 0 : context2.source) || options.source || SELF_DIAGNOSTICS_SOURCE_DEFAULT,
4122
- category,
4123
- signal_description: signalDefinition == null ? void 0 : signalDefinition.description,
4124
- ...detail ? { detail } : {},
4125
- ...(_m = context2 == null ? void 0 : context2.properties) != null ? _m : {}
4126
- }
4127
- });
4128
- return { acknowledged: true, category, eventId };
4129
- };
4130
- return {
4131
- name: toolName,
4132
- description,
4133
- inputSchema,
4134
- signalKeys,
4135
- execute,
4136
- forVercelAI() {
4137
- return {
4138
- description,
4139
- parameters: inputSchema,
4140
- inputSchema,
4141
- execute
4142
- };
4143
- },
4144
- forOpenAI() {
4145
- return {
4146
- type: "function",
4147
- function: {
4148
- name: toolName,
4149
- description,
4150
- parameters: inputSchema
4151
- }
4152
- };
4153
- },
4154
- forAnthropic() {
4155
- return {
4156
- name: toolName,
4157
- description,
4158
- input_schema: inputSchema
4159
- };
4160
- }
4161
- };
4162
- }
4163
- /**
4164
- * Track AI events. In addiiton to normal event properties, you can provide an "input", "output", or "model" parameter.
4165
- * It takes an AiTrackEvent as input and sends it to the /track-ai endpoint of the raindrop api.
4166
- *
4167
- * @param event - The AiTrackEvent (you must specify at least one of input/output properties)
4168
- * @returns A Promise that resolves when the event has been successfully sent.
4169
- *
4170
- * Example usage:
4171
- * ```typescript
4172
- * raindrop.track_ai({
4173
- * event: "chat", //name of the event
4174
- * model: "claude", //optional
4175
- * input: "what's up?", // input or output is required
4176
- * output: "not much human, how are you?", //input or output is required
4177
- * userId: "cn123456789",
4178
- * });
4179
- * ```
4180
- */
4181
- trackAi(event) {
4182
- if (this.disabled) {
4183
- return void 0;
4184
- }
4185
- const destination = currentReplayTraceDestination();
4186
- const cloudReplay = destination !== void 0 && destination.kind !== "workshop";
4187
- const addEvent = (e) => {
4188
- const {
4189
- eventId,
4190
- userId,
4191
- model,
4192
- input: rawInput,
4193
- output: rawOutput,
4194
- convoId,
4195
- attachments,
4196
- properties,
4197
- featureFlags,
4198
- usage,
4199
- timestamp,
4200
- ...rest
4201
- } = e;
4202
- const input = capText(rawInput, this.maxTextFieldChars);
4203
- const output = capText(rawOutput, this.maxTextFieldChars);
4204
- if (isMissingUserId(userId)) {
4205
- rateLimitedLog(
4206
- "js-sdk.track_ai_missing_user",
4207
- () => console.warn("[raindrop] trackAi() called without a userId; event not sent")
4208
- );
4209
- return;
4210
- }
4211
- const customEventId = eventId != null ? eventId : crypto.randomUUID();
4212
- const parsedAttachments = AttachmentSchema.array().safeParse(attachments != null ? attachments : []);
4213
- if (!parsedAttachments.success) {
4214
- console.warn(
4215
- `[raindrop] Invalid attachments provided to .track_ai(): ${this.formatZodError(parsedAttachments.error)}`
4216
- );
4217
- return;
4218
- }
4219
- const normalizedFlags = featureFlags ? normalizeFeatureFlags(featureFlags) : void 0;
4220
- const parsed = ClientAiTrack.safeParse({
4221
- event_id: customEventId,
4222
- // Only custom event id can sent to server
4223
- user_id: userId,
4224
- timestamp: timestamp || /* @__PURE__ */ new Date(),
4225
- ai_data: { model, input, output, convo_id: convoId },
4226
- properties: {
4227
- ...properties
4228
- },
4229
- ...normalizedFlags && Object.keys(normalizedFlags).length > 0 ? { feature_flags: normalizedFlags } : {},
4230
- attachments: parsedAttachments.data,
4231
- ...rest
4232
- });
4233
- if (!parsed.success) {
4234
- console.warn(
4235
- `[raindrop] Invalid data provided to .track_ai(): ${this.formatZodError(parsed.error)}`
4236
- );
4237
- return;
4238
- }
4239
- const toSave = parsed.data;
4240
- const appGitSnapshot = this.getAppGitSnapshot(toSave.properties, customEventId);
4241
- const eventProperties = withAppGitProperties(toSave.properties, appGitSnapshot);
4242
- const usageProperties = withAppGitProperties(
4243
- rawAppGitProperties(toSave.properties),
4244
- appGitSnapshot
4245
- );
4246
- try {
4247
- toSave.properties = {
4248
- ...eventProperties,
4249
- ...this.wizardSession ? { "raindrop.wizardSession": this.wizardSession } : {},
4250
- // Last, so a caller-supplied property cannot shadow the replay row the
4251
- // event belongs to.
4252
- ...evalScopeAttributes(),
4253
- $context: this.context
4254
- };
4255
- if (!cloudReplay) {
4256
- this.saveToBuffer({
4257
- type: "ai",
4258
- ...toSave
4259
- });
4260
- }
4261
- this._recordModelUsage(customEventId, model, usage, usageProperties, appGitSnapshot);
4262
- return customEventId;
4263
- } finally {
4264
- this.appGitContext.finishOperation(customEventId);
4265
- }
4266
- };
4267
- if (Array.isArray(event)) {
4268
- return event.map(addEvent);
4269
- } else {
4270
- return addEvent(event);
4271
- }
4272
- }
4273
- setUserDetails(event) {
4274
- if (this.disabled) {
4275
- return;
4276
- }
4277
- const parsed = IdentifySchema.safeParse({
4278
- user_id: event.userId,
4279
- traits: event.traits || {}
4280
- });
4281
- if (!parsed.success) {
4282
- console.warn(
4283
- `[raindrop] Invalid data provided to .setUserDetails(): ${this.formatZodError(parsed.error)}`
4284
- );
4285
- return;
4286
- }
4287
- this.saveToBuffer({
4288
- type: "identify",
4289
- ...parsed.data
4290
- });
4291
- }
4292
- /**
4293
- * Report a self-diagnostic signal. This is a convenient shorthand for sending
4294
- * signals that appear in the Self Diagnostics tab of the Raindrop dashboard.
4295
- *
4296
- * @param options - The diagnostic details.
4297
- * @param options.eventId - The interaction/event ID this diagnostic belongs to.
4298
- * @param options.description - A human-readable description of the issue.
4299
- * @param options.category - Optional category (e.g. "missing_context"). Defaults to "general".
4300
- * @param options.source - Optional source identifier. Defaults to "selfDiagnose".
4301
- * @param options.sentiment - Signal sentiment. Defaults to "NEGATIVE".
4302
- * @param options.properties - Additional custom properties.
4303
- *
4304
- * @example
4305
- * ```typescript
4306
- * raindrop.selfDiagnose({
4307
- * eventId: "evt_123",
4308
- * description: "User asked for production DB access but no credentials were provided.",
4309
- * category: "missing_context",
4310
- * });
4311
- * ```
4312
- */
4313
- selfDiagnose(options) {
4314
- var _a, _b, _c;
4315
- if (this.disabled) {
4316
- return;
4317
- }
4318
- const category = ((_a = options.category) == null ? void 0 : _a.trim()) || "general";
4319
- const source = ((_b = options.source) == null ? void 0 : _b.trim()) || "selfDiagnose";
4320
- const sentiment = (_c = options.sentiment) != null ? _c : "NEGATIVE";
4321
- this.trackSignal({
4322
- eventId: options.eventId,
4323
- name: `self diagnostics - ${category}`,
4324
- type: "agent",
4325
- sentiment,
4326
- properties: {
4327
- ...options.properties,
4328
- source,
4329
- category,
4330
- detail: options.description,
4331
- signal_description: options.description
4332
- }
4333
- });
4334
- }
4335
- trackSignal(signal) {
4336
- if (this.disabled) {
4337
- return;
4338
- }
4339
- const addSignal = (s) => {
4340
- const parsed = SignalEventSchema.safeParse({
4341
- event_id: s.eventId,
4342
- signal_name: s.name,
4343
- timestamp: s.timestamp,
4344
- sentiment: s.sentiment,
4345
- properties: {
4346
- ...s.properties,
4347
- ..."comment" in s ? { comment: s.comment } : {},
4348
- ..."after" in s ? { after: s.after } : {}
4349
- },
4350
- attachment_id: s.attachmentId,
4351
- signal_type: s.type || "default"
4352
- });
4353
- if (!parsed.success) {
4354
- console.warn(
4355
- `[raindrop] Invalid data provided to .trackSignal(): ${this.formatZodError(parsed.error)}`
4356
- );
4357
- return;
4358
- }
4359
- this.saveToBuffer({
4360
- type: "signal",
4361
- ...parsed.data
4362
- });
4363
- };
4364
- if (Array.isArray(signal)) {
4365
- return signal.map(addSignal);
4366
- } else {
4367
- return addSignal(signal);
4368
- }
4369
- }
4370
- saveToBuffer(event) {
4371
- if (this.disabled) {
4372
- return;
4373
- }
4374
- if (this.debugLogs) {
4375
- console.log("[raindrop] Added to queue: " + JSON.stringify({ event }));
4376
- }
4377
- this.buffer.push(event);
4378
- if (this.buffer.length >= this.bufferSize) {
4379
- this.flush();
4380
- } else if (!this.flushTimer) {
4381
- this.flushTimer = setTimeout(() => {
4382
- this.flush();
4383
- }, this.bufferTimeout);
4384
- }
4385
- }
4386
- /**
4387
- * Send the buffered track/identify/signal batches. With a deadline (a
4388
- * forceFlush or close), a batch not sent before it is put back at the front
4389
- * of the buffer for a later send (outside close).
4390
- */
4391
- flush(deadlineAt) {
4392
- if (this.flushTimer) {
4393
- clearTimeout(this.flushTimer);
4394
- this.flushTimer = null;
4395
- }
4396
- if (this.buffer.length === 0) {
4397
- return Promise.resolve([]);
4398
- }
4399
- const currentBuffer = this.buffer;
4400
- this.buffer = new Array();
4401
- const events = currentBuffer.filter((e) => e.type === "event");
4402
- const aiEvents = currentBuffer.filter((e) => e.type === "ai");
4403
- const identify = currentBuffer.filter((e) => e.type === "identify");
4404
- const signals = currentBuffer.filter((e) => e.type === "signal");
4405
- const flushPromises = [
4406
- events.length ? this.sendBatchToApi(events, "events/track", deadlineAt) : Promise.resolve(void 0),
4407
- aiEvents.length ? this.sendBatchToApi(aiEvents, "events/track", deadlineAt) : Promise.resolve(void 0),
4408
- identify.length ? this.sendBatchToApi(identify, "users/identify", deadlineAt) : Promise.resolve(void 0),
4409
- signals.length ? this.sendBatchToApi(signals, "signals/track", deadlineAt) : Promise.resolve(void 0)
4410
- ];
4411
- const sending = Promise.all(flushPromises).then(
4412
- (fates) => fates.filter((fate) => fate !== void 0)
4413
- );
4414
- this.inFlightBatches.add(sending);
4415
- void sending.finally(() => this.inFlightBatches.delete(sending)).catch(() => {
4416
- });
4417
- return sending;
4418
- }
4419
- /** Put a batch a deadline deferred back at the front of the buffer and send it later. */
4420
- requeueBatch(events, retryAtMs) {
4421
- var _a, _b;
4422
- this.buffer = [...events, ...this.buffer];
4423
- if (this.flushTimer) clearTimeout(this.flushTimer);
4424
- const delay = Math.max(this.bufferTimeout, (retryAtMs != null ? retryAtMs : 0) - Date.now());
4425
- this.flushTimer = setTimeout(() => {
4426
- this.flush();
4427
- }, delay);
4428
- (_b = (_a = this.flushTimer).unref) == null ? void 0 : _b.call(_a);
4429
- }
4430
- // Symmetric with mirrorPartialEventToLocalDebugger: fan batch posts out to a
4431
- // resolved Workshop daemon so calls like trackAi() that never go through the
4432
- // partial-event path still land in the local debugger. Fire-and-forget; cloud
4433
- // shipping is independent.
4434
- mirrorBatchToLocalDebugger(endpoint, body) {
4435
- const localUrl = resolveLocalDebuggerBaseUrl(this.localDebuggerUrlOpt);
4436
- if (!localUrl) return;
4437
- const headers = { "Content-Type": "application/json" };
4438
- if (this.writeKey) headers.Authorization = `Bearer ${this.writeKey}`;
4439
- try {
4440
- void runWithTracingSuppressed(
4441
- () => fetch(`${localUrl}${endpoint}`, {
4442
- method: "POST",
4443
- headers,
4444
- body: JSON.stringify(body),
4445
- // Bounded like the cloud paths: a black-holed Workshop URL must not
4446
- // pin connections indefinitely (fire-and-forget still holds sockets).
4447
- signal: AbortSignal.timeout(DEFAULT_REQUEST_TIMEOUT_MS)
4448
- })
4449
- ).catch(() => {
4450
- });
4451
- } catch (e) {
4452
- }
4453
- }
4454
- /**
4455
- * Retry/timeout options for one POST. During close(), sends retry within its
4456
- * window; a forceFlush passes its own deadline. `null` once the close()
4457
- * window is spent (the caller drops the payload). After close() returns,
4458
- * stragglers get a single short attempt.
4459
- */
4460
- requestOpts(deadlineAt) {
4461
- const opts = this.scheduleFor(deadlineAt);
4462
- return opts && { ...opts, cutOff: this.cutOff.signal };
4463
- }
4464
- scheduleFor(deadlineAt) {
4465
- if (this.shutdownDeadlineAt !== void 0) {
4466
- if (this.shutdownDeadlineAt - Date.now() <= 0) return null;
4467
- return {
4468
- maxAttempts: 3,
4469
- debug: this.debugLogs,
4470
- deadlineAt: Math.min(this.shutdownDeadlineAt, deadlineAt != null ? deadlineAt : Infinity)
4471
- };
4472
- }
4473
- if (this.hasShutdown) {
4474
- return { maxAttempts: 1, debug: this.debugLogs, timeoutMs: POST_SHUTDOWN_TIMEOUT_MS };
4475
- }
4476
- return { maxAttempts: 3, debug: this.debugLogs, deadlineAt };
4477
- }
4478
- warnShutdownDrop(what) {
4479
- rateLimitedLog(
4480
- "js-sdk.shutdown_deadline",
4481
- () => console.warn(`[raindrop] shutdown flush deadline exceeded; dropping ${what}`)
4482
- );
4483
- }
4484
- async sendBatchToApi(events, endpoint, deadlineAt) {
4485
- const kind = PII_KIND_BY_ENDPOINT[endpoint];
4486
- const writeKey = this.localOnly ? void 0 : this.writeKey;
4487
- let rows = events.map(({ type, ...event }) => event);
4488
- let redact = kind !== void 0 && piiRedactionNow(this.redactPii, this.remotePiiConfig, this.apiUrl, writeKey);
4489
- if (redact === void 0) {
4490
- rows = rows.map(snapshotPayload);
4491
- redact = await piiRedaction(this.redactPii, this.remotePiiConfig, this.apiUrl, writeKey, deadlineAt);
4492
- }
4493
- const body = rows.map((event) => {
4494
- const redacted = redact && kind ? this.piiFields.redact(kind, event) : event;
4495
- return kind && isRecord(redacted) ? maskPayload(kind, redacted, this.mask, "[raindrop]") : redacted;
4496
- });
4497
- this.mirrorBatchToLocalDebugger(endpoint, body);
4498
- if (this.localOnly) {
4499
- return void 0;
4500
- }
4501
- const opts = this.requestOpts(deadlineAt);
4502
- if (!opts) {
4503
- this.warnShutdownDrop(`${events.length} event(s) for ${endpoint}`);
4504
- return "dropped";
4505
- }
4506
- const outcome = await sendJson(
4507
- this.apiUrl + endpoint,
4508
- body,
4509
- { Authorization: `Bearer ${this.writeKey}`, ...projectIdHeaders(this.projectId) },
4510
- { ...opts, sdkName: void 0 }
4511
- );
4512
- const shuttingDown = this.shutdownDeadlineAt !== void 0 || this.hasShutdown;
4513
- const fate = fateOf(outcome, shuttingDown);
4514
- if (fate === "queued") {
4515
- this.requeueBatch(events, outcome.status === "deferred" ? outcome.retryAtMs : void 0);
4516
- } else if (fate === "dropped" || outcome.status === "rejected") {
4517
- const reason = outcome.status === "cut_off" ? "cut off at the flush deadline (not resent: it may have reached ingest)" : outcome.status === "deferred" ? "not sent before the shutdown deadline" : "error" in outcome && outcome.error ? outcome.error.message : outcome.status;
4518
- rateLimitedLog(
4519
- `js-sdk.batch_failed.${endpoint}`,
4520
- () => console.error(`[raindrop] Error (POST ${redactUrlForLog(this.apiUrl + endpoint)}): ${reason}`)
4521
- );
4522
- } else if (this.debugLogs) {
4523
- console.log(`[raindrop] Success (POST ${redactUrlForLog(this.apiUrl + endpoint)})`);
4524
- }
4525
- return fate;
4526
- }
4527
- getContext() {
4528
- const runtime = detectRuntime();
4529
- const context2 = {
4530
- library: {
4531
- name: package_default.name,
4532
- version: package_default.version
4533
- },
4534
- metadata: {
4535
- jsRuntime: runtime
4536
- }
4537
- };
4538
- if (runtime === "node") {
4539
- context2.metadata.nodeVersion = process.version;
4540
- }
4541
- return context2;
4542
- }
4543
- formatZodError(error) {
4544
- return error.issues.map((issue) => `(path: ${issue.path.join(".")}): ${issue.message}`).join(", ");
4545
- }
4546
- /**
4547
- * Internal method for tracking partial AI events. use .begin() to start an interaction instead.
4548
- *
4549
- * Partial events are buffered, merged and sent by the shared core
4550
- * `EventShipper` (one implementation for every JS SDK): updates for an event
4551
- * are merged for up to 2 s, sent in order, and the event's start time is
4552
- * sent as its timestamp. Usage is not sent here; it goes out as a model span.
4553
- *
4554
- * @param event - The PartialAiTrackEvent, requires eventId.
4555
- */
4556
- _trackAiPartial(event) {
4557
- if (this.disabled) {
4558
- return Promise.resolve();
4559
- }
4560
- const { eventId, isPending, usage: _usage, ...fields } = event;
4561
- if (!eventId) {
4562
- console.warn("[raindrop] trackAiPartial requires an eventId.");
4563
- return Promise.resolve();
4564
- }
4565
- return this.eventShipper.patch(eventId, {
4566
- eventName: fields.event,
4567
- userId: fields.userId,
4568
- convoId: fields.convoId,
4569
- input: fields.input,
4570
- output: fields.output,
4571
- model: fields.model,
4572
- properties: fields.properties,
4573
- featureFlags: fields.featureFlags ? normalizeFeatureFlags(fields.featureFlags) : void 0,
4574
- attachments: fields.attachments,
4575
- timestamp: fields.timestamp,
4576
- isPending
4577
- });
4578
- }
4579
- /**
4580
- * Best-effort flush of in-flight OTel spans and pending partial-event POSTs.
4581
- * Safe to call multiple times; never throws.
4582
- */
4583
- async forceFlush() {
4584
- const deadlineAt = Date.now() + this.flushTimeoutMs;
4585
- const [batchFates, spans, partials] = await Promise.all([
4586
- this.flush(deadlineAt),
4587
- this._tracing.forceFlush().catch(() => ({ ...DELIVERED })),
4588
- this.eventShipper.flush()
4589
- ]);
4590
- const running = [...this.inFlightBatches];
4591
- const { settled, stillRunning } = await awaitEarlierSends(
4592
- running,
4593
- deadlineAt,
4594
- this.cutOff,
4595
- (p) => this.inFlightBatches.has(p)
4596
- );
4597
- const result = combineResults(
4598
- summarize2(batchFates, stillRunning, !settled),
4599
- spans != null ? spans : { ...DELIVERED },
4600
- partials
4601
- );
4602
- if (!result.delivered) {
4603
- rateLimitedLog(
4604
- "js-sdk.flush_undelivered",
4605
- () => console.warn(`[raindrop] ${describeUndelivered("forceFlush()", result)}`)
4606
- );
4607
- }
4608
- return asCompat(result);
4609
- }
4610
- /**
4611
- * Best-effort drain of buffered OTel/tool spans (traceloop + direct shipper).
4612
- * This is the round-trip-heavy part of `forceFlush()` (e.g. the `/v1/traces`
4613
- * POST with retries); kept separate so `finish()` can background it.
4614
- * @internal
4615
- */
4616
- async _flushTracingSpans() {
4617
- try {
4618
- await this._tracing.forceFlush();
4619
- } catch (e) {
4620
- }
4621
- }
4622
- /**
4623
- * Emit one model span carrying raw provider usage facts.
4624
- * @internal
4625
- */
4626
- _recordModelUsage(eventId, model, usage, properties = {}, appGitSnapshot = this.getAppGitSnapshot(properties)) {
4627
- if (usage === void 0) return;
4628
- const parsed = AiTrackUsageSchema.safeParse(usage);
4629
- if (!parsed.success) {
4630
- console.warn(
4631
- `[raindrop] Invalid usage provided to .track_ai(): ${this.formatZodError(parsed.error)}`
4632
- );
4633
- return;
4634
- }
4635
- if (typeof model !== "string" || model.trim() === "") {
4636
- console.warn("[raindrop] .track_ai() usage requires a non-empty model.");
4637
- return;
4638
- }
4639
- this._tracing.recordModelUsage({
4640
- eventId,
4641
- model,
4642
- usage: parsed.data,
4643
- appGitProperties: rawAppGitProperties(properties),
4644
- appGitSnapshot
4645
- });
4646
- }
4647
- /**
4648
- * Kept for callers of the internal API. Sends for one event are already
4649
- * ordered by the core EventShipper, so a per-event drain is a no-op; with no
4650
- * `eventId` it sends everything buffered.
4651
- * @internal
4652
- */
4653
- async _drainInFlightPartials(eventId) {
4654
- if (eventId === void 0) await this.eventShipper.flush();
4655
- }
4656
- /**
4657
- * Whether `interaction.finish()` should await the in-flight span/trace flush
4658
- * before resolving. Blocks by default (preserving the historical behavior);
4659
- * callers opt out with `awaitSpanFlush: false`. A local Workshop/debugger
4660
- * always forces the await (its read-after-write guarantee depends on it),
4661
- * even when `awaitSpanFlush: false`. The terminal partial-event POST is
4662
- * always awaited by `finish()`, independent of this.
4663
- * @internal
4664
- */
4665
- _shouldBlockFinishFlush() {
4666
- if (resolveLocalDebuggerBaseUrl(this.localDebuggerUrlOpt) !== null) {
4667
- return true;
4668
- }
4669
- return this.awaitSpanFlushOpt !== false;
4670
- }
4671
- /**
4672
- * Flush everything within `flushTimeoutMs` and stop. Resolves, never
4673
- * rejects, to the combined delivery result of batches, spans and partial
4674
- * events (CONTRACT 1.2.1); leftovers at the deadline are dropped with a
4675
- * warning. Ignoring the result is fine.
4676
- */
4677
- async close() {
4678
- this.appGitContext.dispose();
4679
- this.hasShutdown = true;
4680
- this.shutdownDeadlineAt = Date.now() + this.flushTimeoutMs;
4681
- try {
4682
- return asCompat(await this.closeWithinDeadline());
4683
- } catch (e) {
4684
- return asCompat({ ...DELIVERED, delivered: false });
4685
- } finally {
4686
- this.shutdownDeadlineAt = void 0;
4687
- }
4688
- }
4689
- async closeWithinDeadline() {
4690
- var _a;
4691
- const deadlineAt = (_a = this.shutdownDeadlineAt) != null ? _a : Date.now();
4692
- const remainingMs = () => Math.max(0, deadlineAt - Date.now());
4693
- const partialsShutdown = this.eventShipper.shutdown();
4694
- const TIMED_OUT = { ...DELIVERED, delivered: false, timedOut: true, inFlight: 1 };
4695
- let tracingResult = TIMED_OUT;
4696
- const tracing2 = raceWithTimeout(
4697
- this._tracing.close().then((r) => {
4698
- tracingResult = r;
4699
- }),
4700
- remainingMs()
4701
- ).then((settled) => {
4702
- if (!settled) {
4703
- tracingResult = TIMED_OUT;
4704
- this.warnShutdownDrop("in-flight trace flush");
4705
- }
4706
- });
4707
- const batches = (async () => {
4708
- let fates = [];
4709
- try {
4710
- fates = await this.flush(deadlineAt);
4711
- } catch (error) {
4712
- console.error(
4713
- "[raindrop] Error flushing standard buffer during close:",
4714
- error instanceof Error ? error : String(error)
4715
- );
4716
- }
4717
- const { settled, stillRunning } = await awaitEarlierSends(
4718
- [...this.inFlightBatches],
4719
- deadlineAt,
4720
- this.cutOff,
4721
- (p) => this.inFlightBatches.has(p)
4722
- );
4723
- if (stillRunning > 0) this.warnShutdownDrop(`${stillRunning} in-flight batch(es)`);
4724
- return summarize2(fates, stillRunning, !settled);
4725
- })();
4726
- let partialsResult = TIMED_OUT;
4727
- const partials = raceWithTimeout(
4728
- partialsShutdown.then((r) => {
4729
- partialsResult = r;
4730
- }),
4731
- remainingMs()
4732
- ).then((settled) => {
4733
- if (!settled) {
4734
- partialsResult = TIMED_OUT;
4735
- this.warnShutdownDrop("partial event request(s)");
4736
- }
4737
- });
4738
- const [, batchResult] = await Promise.all([tracing2, batches, partials]);
4739
- if (this.debugLogs) {
4740
- console.log("[raindrop] Closing Raindrop Analytics");
4741
- }
4742
- return combineResults(batchResult, tracingResult, partialsResult);
4743
- }
4744
- };
4745
- var index_default = Raindrop;
4746
- var EVAL_CORRELATION_ID_ATTRIBUTE2 = EVAL_CORRELATION_ID_ATTRIBUTE;
4747
- var currentEvalScope2 = currentEvalScope;
4748
- var withEvalScope2 = withEvalScope;
4749
-
4750
- export {
4751
- DEFAULT_QUERY_URL,
4752
- DEFAULT_TRACE_WAIT_MS,
4753
- DEFAULT_EVAL_WAIT_MS,
4754
- DEFAULT_EVAL_POLL_INTERVAL_MS,
4755
- MAX_EVAL_STATUS_RETRIES,
4756
- ReplayCountsSchema,
4757
- ReplayEvaluatorCountsSchema,
4758
- ReplayEvaluatorStatsSchema,
4759
- ReplayEvaluatorSummarySchema,
4760
- ReplayVerdictSchema,
4761
- ReplayResultRowSchema,
4762
- LocalBooleanVerdictSchema,
4763
- LocalScoreVerdictSchema,
4764
- LocalNumberVerdictSchema,
4765
- LocalPreferenceVerdictSchema,
4766
- LocalVerdictSchema,
4767
- createReplay,
4768
- claimReplay,
4769
- readReplay,
4770
- readEvalManifest,
4771
- runReplay,
4772
- replay,
4773
- evaluateReplay,
4774
- EvalParameterError,
4775
- defineAgent,
4776
- createEvalHandler,
4777
- EvalDatasetRowInputSchema,
4778
- readEvalDataset2 as readEvalDataset,
4779
- EvalDatasetPublishConflictError,
4780
- publishEvalDataset,
4781
- readEvalRun,
4782
- evaluateEvalRun,
4783
- EvalPublishError,
4784
- compareEvalRuns,
4785
- readEvaluator,
4786
- publishEvalSuite,
4787
- traceTools,
4788
- pullEval,
4789
- loadEvalSnapshot,
4790
- createEvalSuiteRun,
4791
- runEvalSuite,
4792
- MAX_INGEST_SIZE_BYTES,
4793
- resolveDisableBatching,
4794
- Raindrop,
4795
- index_default,
4796
- EVAL_CORRELATION_ID_ATTRIBUTE2 as EVAL_CORRELATION_ID_ATTRIBUTE,
4797
- currentEvalScope2 as currentEvalScope,
4798
- withEvalScope2 as withEvalScope
4799
- };