@cetra-ai/sdk 0.0.0-stage → 0.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js ADDED
@@ -0,0 +1,4056 @@
1
+ import { a as timeoutSignal, i as runtimeGlobals, n as gzip, o as utf8Decode, r as hasHttpAuthority, s as utf8Encode, t as getFetch } from "./web-C0F5sf2n.js";
2
+ import { ProxyTracerProvider, ROOT_CONTEXT, SpanStatusCode, TraceFlags, context, createContextKey, diag, isSpanContextValid, propagation, trace } from "@opentelemetry/api";
3
+ import { AsyncLocalStorageContextManager } from "@opentelemetry/context-async-hooks";
4
+ import { defaultResource, resourceFromAttributes } from "@opentelemetry/resources";
5
+ import { BatchSpanProcessor, ParentBasedSampler, TraceIdRatioBasedSampler, TracerProvider as TracerProvider$1 } from "@opentelemetry/sdk-trace";
6
+ import { ExportResultCode, hrTime, hrTimeDuration, hrTimeToNanoseconds } from "@opentelemetry/core";
7
+ import { ProtobufTraceSerializer } from "@opentelemetry/otlp-transformer";
8
+ // src/log.ts
9
+ /**
10
+ * Logging.
11
+ *
12
+ * `warnOnce` deduplicates by key so a repeated condition (a missing key on
13
+ * every `resolveConfig` call, a missing `fetch` on every export) warns once
14
+ * per process. Messages never contain values, keys or user ids (AGENTS.md
15
+ * § Privacy).
16
+ */
17
+ const warned = /* @__PURE__ */ new Set();
18
+ /** Warn `message` the first time `key` is seen in this process. */
19
+ function warnOnce(key, message) {
20
+ if (warned.has(key)) return;
21
+ warned.add(key);
22
+ runtimeGlobals().console?.warn(message);
23
+ }
24
+ /** Warn `message` on every call (no deduplication). */
25
+ function warn(message) {
26
+ runtimeGlobals().console?.warn(message);
27
+ }
28
+ /** Debug logging through the OTel diagnostics logger. */
29
+ function debug(message) {
30
+ diag.debug(message);
31
+ }
32
+ // src/config.ts
33
+ const ENV_PREFIX = "CETRA_";
34
+ const ENV_API_KEY = `${ENV_PREFIX}API_KEY`;
35
+ const ENV_BASE_URL = `${ENV_PREFIX}BASE_URL`;
36
+ const ENV_ENVIRONMENT = `${ENV_PREFIX}ENVIRONMENT`;
37
+ const ENV_RELEASE = `${ENV_PREFIX}RELEASE`;
38
+ const ENV_CAPTURE_CONTENT = `${ENV_PREFIX}CAPTURE_CONTENT`;
39
+ const ENV_SAMPLE_RATE = `${ENV_PREFIX}SAMPLE_RATE`;
40
+ const ENV_ENABLED = `${ENV_PREFIX}ENABLED`;
41
+ const ENV_SERVICE_NAME = "OTEL_SERVICE_NAME";
42
+ const KEY_PREFIX = "sk-cetra-";
43
+ const RESERVED_ENVIRONMENTS = /* @__PURE__ */ new Set([
44
+ "cetra-eval",
45
+ "cetra-playground",
46
+ "cetra-assistant"
47
+ ]);
48
+ const DEFAULT_BASE_URL = "http://localhost:8080";
49
+ const TRUE_WORDS = /* @__PURE__ */ new Set([
50
+ "true",
51
+ "1",
52
+ "yes",
53
+ "on"
54
+ ]);
55
+ const FALSE_WORDS = /* @__PURE__ */ new Set([
56
+ "false",
57
+ "0",
58
+ "no",
59
+ "off"
60
+ ]);
61
+ var ConfigError = class extends Error {
62
+ option;
63
+ constructor(option, problem) {
64
+ super(`${option}: ${problem}`);
65
+ this.name = "ConfigError";
66
+ this.option = option;
67
+ }
68
+ };
69
+ /** Resolve SDK options. An explicit argument wins, then the env var, then the default. */
70
+ function resolveConfig(options = {}, env) {
71
+ const raw = options;
72
+ const source = env ?? defaultEnv();
73
+ if (!resolveBool("enabled", ENV_ENABLED, raw.enabled, source, true)) return finish(disabled());
74
+ const apiKey = resolveApiKey(raw.apiKey, source);
75
+ if (apiKey === void 0) {
76
+ warnOnce("missing-api-key", "cetra: no API key; set CETRA_API_KEY, or CETRA_ENABLED=false to silence this; tracing is disabled");
77
+ return finish(disabled());
78
+ }
79
+ return finish({
80
+ enabled: true,
81
+ apiKey,
82
+ baseUrl: resolveBaseUrl(raw.baseUrl, source),
83
+ serviceName: readEnv(source, ENV_SERVICE_NAME),
84
+ environment: resolveEnvironment(raw.environment, source),
85
+ release: resolveRelease(raw.release, source),
86
+ captureContent: resolveBool("captureContent", ENV_CAPTURE_CONTENT, raw.captureContent, source, true),
87
+ sampleRate: resolveSampleRate(raw.sampleRate, source),
88
+ mask: resolveMask(raw.mask),
89
+ useGlobalProvider: resolveUseGlobalProvider(raw.useGlobalProvider),
90
+ exportFilter: resolveExportFilter(raw.exportFilter),
91
+ instrument: resolveInstrument(raw.instrument)
92
+ });
93
+ }
94
+ function defaultEnv() {
95
+ return runtimeGlobals().process?.env ?? {};
96
+ }
97
+ function disabled() {
98
+ return {
99
+ enabled: false,
100
+ apiKey: void 0,
101
+ baseUrl: DEFAULT_BASE_URL,
102
+ serviceName: void 0,
103
+ environment: void 0,
104
+ release: void 0,
105
+ captureContent: true,
106
+ sampleRate: 1,
107
+ mask: void 0,
108
+ useGlobalProvider: false,
109
+ exportFilter: void 0,
110
+ instrument: []
111
+ };
112
+ }
113
+ function finish(fields) {
114
+ const config = {
115
+ enabled: fields.enabled,
116
+ baseUrl: fields.baseUrl,
117
+ serviceName: fields.serviceName,
118
+ environment: fields.environment,
119
+ release: fields.release,
120
+ captureContent: fields.captureContent,
121
+ sampleRate: fields.sampleRate,
122
+ mask: fields.mask,
123
+ useGlobalProvider: fields.useGlobalProvider,
124
+ exportFilter: fields.exportFilter,
125
+ instrument: fields.instrument
126
+ };
127
+ Object.defineProperty(config, "apiKey", {
128
+ value: fields.apiKey,
129
+ enumerable: false,
130
+ writable: false
131
+ });
132
+ return Object.freeze(config);
133
+ }
134
+ function readEnv(source, name) {
135
+ const raw = source[name];
136
+ if (typeof raw !== "string") return;
137
+ const trimmed = raw.trim();
138
+ return trimmed === "" ? void 0 : trimmed;
139
+ }
140
+ function resolveBool(argument, envName, value, source, fallback) {
141
+ if (value !== void 0) {
142
+ if (typeof value !== "boolean") throw new ConfigError(argument, "must be a boolean");
143
+ return value;
144
+ }
145
+ const raw = readEnv(source, envName);
146
+ if (raw === void 0) return fallback;
147
+ const parsed = raw.toLowerCase();
148
+ if (TRUE_WORDS.has(parsed)) return true;
149
+ if (FALSE_WORDS.has(parsed)) return false;
150
+ throw new ConfigError(envName, "must be a boolean");
151
+ }
152
+ function resolveApiKey(value, source) {
153
+ if (value !== void 0) {
154
+ if (typeof value !== "string" || !value.startsWith(KEY_PREFIX)) throw new ConfigError("apiKey", `must start with ${KEY_PREFIX}`);
155
+ return value;
156
+ }
157
+ const raw = readEnv(source, ENV_API_KEY);
158
+ if (raw === void 0) return;
159
+ if (!raw.startsWith(KEY_PREFIX)) throw new ConfigError(ENV_API_KEY, `must start with ${KEY_PREFIX}`);
160
+ return raw;
161
+ }
162
+ function resolveBaseUrl(value, source) {
163
+ if (value !== void 0) return checkBaseUrl(value, "baseUrl");
164
+ const raw = readEnv(source, ENV_BASE_URL);
165
+ if (raw === void 0) return DEFAULT_BASE_URL;
166
+ return checkBaseUrl(raw, ENV_BASE_URL);
167
+ }
168
+ const SAMPLE_RATE_ENV = /^(?:[0-9]+(?:\.[0-9]*)?|\.[0-9]+)$/;
169
+ function checkBaseUrl(value, name) {
170
+ if (typeof value !== "string" || !hasHttpAuthority(value)) throw new ConfigError(name, "must be an absolute http or https URL");
171
+ const hash = value.indexOf("#");
172
+ const beforeHash = hash === -1 ? value : value.slice(0, hash);
173
+ const query = beforeHash.indexOf("?");
174
+ const queryValue = query === -1 ? "" : beforeHash.slice(query + 1);
175
+ const fragment = hash === -1 ? "" : value.slice(hash + 1);
176
+ if (queryValue !== "" || fragment !== "") throw new ConfigError(name, "must not include a query or fragment");
177
+ return value.replace(/\/+$/, "");
178
+ }
179
+ function resolveEnvironment(value, source) {
180
+ if (value !== void 0) return checkEnvironment(value, "environment");
181
+ const raw = readEnv(source, ENV_ENVIRONMENT);
182
+ if (raw === void 0) return;
183
+ return checkEnvironment(raw, ENV_ENVIRONMENT);
184
+ }
185
+ function checkEnvironment(value, name) {
186
+ if (typeof value !== "string") throw new ConfigError(name, "must be a string");
187
+ if (RESERVED_ENVIRONMENTS.has(value)) throw new ConfigError(name, "is reserved");
188
+ return value;
189
+ }
190
+ function resolveRelease(value, source) {
191
+ if (value !== void 0) {
192
+ if (typeof value !== "string") throw new ConfigError("release", "must be a string");
193
+ return value;
194
+ }
195
+ return readEnv(source, ENV_RELEASE);
196
+ }
197
+ function resolveSampleRate(value, source) {
198
+ if (value !== void 0) return checkSampleRate(value, "sampleRate");
199
+ const raw = readEnv(source, ENV_SAMPLE_RATE);
200
+ if (raw === void 0) return 1;
201
+ if (!SAMPLE_RATE_ENV.test(raw)) throw new ConfigError(ENV_SAMPLE_RATE, "must be a number between 0 and 1");
202
+ return checkSampleRate(Number(raw), ENV_SAMPLE_RATE);
203
+ }
204
+ function checkSampleRate(value, name) {
205
+ if (typeof value !== "number" || !Number.isFinite(value) || value < 0 || value > 1) throw new ConfigError(name, "must be a number between 0 and 1");
206
+ return value;
207
+ }
208
+ function resolveMask(value) {
209
+ if (value === void 0) return;
210
+ if (typeof value !== "function") throw new ConfigError("mask", "must be callable");
211
+ return value;
212
+ }
213
+ /** No env var: a provider registration is a code decision, not a setting. */
214
+ function resolveUseGlobalProvider(value) {
215
+ if (value === void 0) return false;
216
+ if (typeof value !== "boolean") throw new ConfigError("useGlobalProvider", "must be a boolean");
217
+ return value;
218
+ }
219
+ function resolveExportFilter(value) {
220
+ if (value === void 0) return;
221
+ if (typeof value !== "function") throw new ConfigError("exportFilter", "must be callable");
222
+ return value;
223
+ }
224
+ /** No env var: instrumentations are wired in code (D-F-7). */
225
+ function resolveInstrument(value) {
226
+ if (value === void 0) return [];
227
+ if (!(Array.isArray(value) && value.every((item) => typeof item === "object" && item !== null && isInstrumentation(item)))) throw new ConfigError("instrument", "must be a list of instrumentation objects");
228
+ return value;
229
+ }
230
+ function isInstrumentation(item) {
231
+ return typeof item.setTracerProvider === "function" && typeof item.enable === "function" && typeof item.disable === "function";
232
+ }
233
+ // src/quota.ts
234
+ /**
235
+ * The 402 pause shared by the trace exporter and the score queue (D-P-34).
236
+ *
237
+ * A `402` means the organization reached its monthly units cap. Both
238
+ * transports then drop data for `Retry-After` seconds, at most one hour at a
239
+ * time, and send again afterwards. One warning is logged per pause start.
240
+ */
241
+ const MAX_PAUSE_MILLIS = 36e5;
242
+ const DEFAULT_PAUSE_SECONDS = 3600;
243
+ const NON_NEGATIVE_INTEGER$1 = /^[0-9]+$/;
244
+ var QuotaState = class {
245
+ now;
246
+ until = Number.NEGATIVE_INFINITY;
247
+ /** Tests inject a clock; the default is `Date.now`. */
248
+ constructor(now = Date.now) {
249
+ this.now = now;
250
+ }
251
+ /** True while a pause set by `on402` has not yet ended. */
252
+ paused() {
253
+ return this.now() < this.until;
254
+ }
255
+ /**
256
+ * Pause for `Retry-After` seconds (at most one hour). A missing or unusable
257
+ * header pauses for one hour. Warns once when a pause starts.
258
+ */
259
+ on402(retryAfter) {
260
+ const seconds = parseSeconds(retryAfter) ?? DEFAULT_PAUSE_SECONDS;
261
+ const wasPaused = this.paused();
262
+ const start = this.now();
263
+ this.until = start + Math.min(seconds * 1e3, MAX_PAUSE_MILLIS);
264
+ if (!wasPaused) {
265
+ const resetAt = new Date(start + seconds * 1e3);
266
+ warn(`cetra: the organization reached its monthly units cap; telemetry is dropped until ${`${(Number.isNaN(resetAt.getTime()) ? new Date(start + MAX_PAUSE_MILLIS).toISOString() : resetAt.toISOString()).slice(0, 19)}Z`} (retrying at most every hour)`);
267
+ }
268
+ }
269
+ };
270
+ /** A non-negative integer `Retry-After` that is greater than zero, else undefined. */
271
+ function parseSeconds(retryAfter) {
272
+ const header = retryAfter === null ? "" : retryAfter.trim();
273
+ if (!NON_NEGATIVE_INTEGER$1.test(header)) return;
274
+ const seconds = Number(header);
275
+ return seconds > 0 ? seconds : void 0;
276
+ }
277
+ // src/retry.ts
278
+ /**
279
+ * Retry policy shared by the REST clients and the background senders (D-F-8,
280
+ * D-J-16): the backoff schedule, `Retry-After` handling and the sleep.
281
+ */
282
+ const RETRY_AFTER_MAX_MILLIS$1 = 3e4;
283
+ const NON_NEGATIVE_INTEGER = /^[0-9]+$/;
284
+ /** Backoff after the attempt with index `attempt` (0-based): 1 s, 2 s, 4 s. */
285
+ function backoffMillis(attempt) {
286
+ switch (attempt) {
287
+ case 0: return 1e3;
288
+ case 1: return 2e3;
289
+ default: return 4e3;
290
+ }
291
+ }
292
+ /** `Retry-After` seconds when a non-negative integer (capped at 30 s), else the backoff. */
293
+ function waitMillis(retryAfter, attempt) {
294
+ const header = retryAfter === null ? void 0 : retryAfter.trim();
295
+ if (header !== void 0 && NON_NEGATIVE_INTEGER.test(header)) return Math.min(Number(header) * 1e3, RETRY_AFTER_MAX_MILLIS$1);
296
+ return backoffMillis(attempt);
297
+ }
298
+ function defaultSleep(ms) {
299
+ const { setTimeout } = runtimeGlobals();
300
+ if (setTimeout === void 0) return Promise.resolve();
301
+ return new Promise((resolve) => {
302
+ setTimeout(resolve, ms);
303
+ });
304
+ }
305
+ // src/exporter.ts
306
+ /**
307
+ * OTLP/protobuf trace exporter over `fetch` (D-F-8).
308
+ *
309
+ * One transport on every runtime (Node, Bun, Deno, edge): the body is OTLP
310
+ * protobuf from `@opentelemetry/otlp-transformer`, gzipped through
311
+ * `CompressionStream` when the runtime has one. `export` never throws and
312
+ * calls its callback exactly once. Retries (429/502/503/504 and network
313
+ * errors, up to 4 attempts) stay inside a 30 s total deadline per export;
314
+ * `keepalive` is never set (bodies may exceed its 64 KiB limit).
315
+ */
316
+ const DEFAULT_TIMEOUT_MILLIS = 1e4;
317
+ /** Total budget per `export` call, retries included (D-F-8). */
318
+ const DEADLINE_MILLIS = 3e4;
319
+ const RETRYABLE_STATUSES = /* @__PURE__ */ new Set([
320
+ 429,
321
+ 502,
322
+ 503,
323
+ 504
324
+ ]);
325
+ var FetchTraceExporter = class {
326
+ url;
327
+ apiKey;
328
+ fetcher;
329
+ timeoutMillis;
330
+ sleep;
331
+ now;
332
+ quota;
333
+ inFlight = /* @__PURE__ */ new Set();
334
+ stopped = false;
335
+ constructor(options) {
336
+ this.url = options.url;
337
+ this.apiKey = options.apiKey;
338
+ this.fetcher = options.fetch ?? getFetch();
339
+ this.timeoutMillis = options.timeoutMillis ?? DEFAULT_TIMEOUT_MILLIS;
340
+ this.sleep = options.sleep ?? defaultSleep;
341
+ this.now = options.now ?? Date.now;
342
+ this.quota = options.quota ?? new QuotaState(this.now);
343
+ }
344
+ export(spans, resultCallback) {
345
+ const settled = this.runExport(spans).then((result) => {
346
+ resultCallback(result);
347
+ });
348
+ this.inFlight.add(settled);
349
+ settled.then(() => this.inFlight.delete(settled), () => this.inFlight.delete(settled));
350
+ }
351
+ /** Resolves when every export already in flight has settled. */
352
+ async forceFlush() {
353
+ await Promise.all([...this.inFlight]);
354
+ }
355
+ /** Waits for in-flight exports, then refuses new ones. */
356
+ async shutdown() {
357
+ await this.forceFlush();
358
+ this.stopped = true;
359
+ }
360
+ /** Runs one export to its single result; never rejects. */
361
+ async runExport(spans) {
362
+ if (this.stopped) return failure("shutdown");
363
+ if (this.quota.paused()) return { code: ExportResultCode.SUCCESS };
364
+ const fetch = this.fetcher;
365
+ if (fetch === void 0) {
366
+ warnOnce("no-fetch", "cetra: fetch is not available; spans are not exported");
367
+ return failure("no fetch");
368
+ }
369
+ try {
370
+ return await this.send(spans, fetch);
371
+ } catch {
372
+ return failure("export");
373
+ }
374
+ }
375
+ async send(spans, fetch) {
376
+ let body;
377
+ try {
378
+ body = ProtobufTraceSerializer.serializeRequest(spans);
379
+ } catch {
380
+ return failure("serialize");
381
+ }
382
+ if (body === void 0) return failure("serialize");
383
+ const headers = {
384
+ "Content-Type": "application/x-protobuf",
385
+ Authorization: `Bearer ${this.apiKey}`
386
+ };
387
+ let payload = body;
388
+ const compressed = await gzip(body).catch(() => void 0);
389
+ if (compressed !== void 0) {
390
+ payload = compressed;
391
+ headers["Content-Encoding"] = "gzip";
392
+ }
393
+ const deadline = this.now() + DEADLINE_MILLIS;
394
+ for (let attempt = 0;; attempt++) {
395
+ const remaining = deadline - this.now();
396
+ if (remaining <= 0) return failure("deadline");
397
+ let status;
398
+ let retryAfter = null;
399
+ try {
400
+ const response = await fetch(this.url, {
401
+ method: "POST",
402
+ headers,
403
+ body: payload,
404
+ signal: timeoutSignal(Math.min(this.timeoutMillis, remaining))
405
+ });
406
+ if (response.status >= 200 && response.status < 300) return { code: ExportResultCode.SUCCESS };
407
+ status = response.status;
408
+ retryAfter = response.headers.get("Retry-After");
409
+ } catch {
410
+ status = void 0;
411
+ }
412
+ if (status === 402) {
413
+ this.quota.on402(retryAfter);
414
+ return { code: ExportResultCode.SUCCESS };
415
+ }
416
+ const reason = status === void 0 ? "network" : `http ${String(status)}`;
417
+ if (status !== void 0 && !RETRYABLE_STATUSES.has(status)) return failure(reason);
418
+ if (attempt + 1 >= 4) return failure(reason);
419
+ const wait = waitMillis(retryAfter, attempt);
420
+ if (this.now() + wait > deadline) return failure(reason);
421
+ await this.sleep(wait);
422
+ }
423
+ }
424
+ };
425
+ function failure(reason) {
426
+ return {
427
+ code: ExportResultCode.FAILED,
428
+ error: new Error(reason)
429
+ };
430
+ }
431
+ // src/instrument.ts
432
+ /** The instrumentations the installed runtime enabled, so shutdown can disable them. */
433
+ let enabled = [];
434
+ /**
435
+ * Bind and enable the config's instrumentations: our tracer provider first,
436
+ * then `enable()`. A throwing item is logged and skipped; the rest proceed.
437
+ */
438
+ function enableInstrumentations(runtime) {
439
+ const items = [];
440
+ for (const item of runtime.config.instrument) try {
441
+ item.setTracerProvider(runtime.provider);
442
+ item.enable();
443
+ items.push(item);
444
+ } catch (error) {
445
+ debug(`cetra: instrumentation skipped after ${errorName$11(error)}`);
446
+ }
447
+ enabled = items;
448
+ }
449
+ /** Disable everything `enableInstrumentations` enabled, then forget the list. */
450
+ function disableInstrumentations() {
451
+ const items = enabled;
452
+ enabled = [];
453
+ for (const item of items) try {
454
+ item.disable();
455
+ } catch (error) {
456
+ debug(`cetra: instrumentation disable failed: ${errorName$11(error)}`);
457
+ }
458
+ }
459
+ function errorName$11(error) {
460
+ return error instanceof Error ? error.name : typeof error;
461
+ }
462
+ // src/serialize.ts
463
+ /**
464
+ * Tolerant payload serialization (§ Serialization of the F plan README).
465
+ *
466
+ * `serialize` never throws: any value, however exotic, becomes a text or
467
+ * compact-JSON payload. The branch order matters: byte views (and `DataView`)
468
+ * come before other typed arrays, which come before generic objects.
469
+ */
470
+ const MAX_PAYLOAD_BYTES = 1048576;
471
+ const DATA_URI_PREFIX = "data:application/octet-stream;base64,";
472
+ const BASE64_ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
473
+ const MAX_DEPTH_MARKER = "[cetra: max depth]";
474
+ const CYCLE_MARKER = "[cetra: cycle]";
475
+ /** § Serialization rules 2-4: convert `value` to a JSON-compatible value. */
476
+ function toJsonable(value) {
477
+ return convert(value, 1, /* @__PURE__ */ new Set());
478
+ }
479
+ /**
480
+ * § Serialization rules 1 and 6-7: `value` as `(text, format)`, truncated to
481
+ * `MAX_PAYLOAD_BYTES` UTF-8 bytes. Never throws.
482
+ */
483
+ function serialize(value) {
484
+ try {
485
+ if (typeof value === "string") return truncate(value, "text");
486
+ if (value === void 0) return ["null", "json"];
487
+ return truncate(JSON.stringify(toJsonable(value)), "json");
488
+ } catch {
489
+ return [`<unserializable ${typeName$1(value)}>`, "text"];
490
+ }
491
+ }
492
+ /**
493
+ * § Serialization rule 6: `text` unchanged when it fits `MAX_PAYLOAD_BYTES`
494
+ * UTF-8 bytes; else cut at the largest character boundary within the limit and
495
+ * appended with the server's truncation marker (format becomes `text`).
496
+ */
497
+ function truncate(text, format) {
498
+ const bytes = utf8Encode(text);
499
+ if (bytes.length <= 1048576) return [text, format];
500
+ let cut = MAX_PAYLOAD_BYTES;
501
+ while (cut > 0) {
502
+ const byte = bytes[cut];
503
+ if (byte === void 0 || (byte & 192) !== 128) break;
504
+ cut--;
505
+ }
506
+ return [`${utf8Decode(bytes.subarray(0, cut))}…[cetra: truncated, original ${bytes.length} bytes]`, "text"];
507
+ }
508
+ /** § Span attributes: a metadata value as an OTel attribute value. */
509
+ function attributeValue(value) {
510
+ if (typeof value === "string") return truncate(value, "text")[0];
511
+ if (typeof value === "boolean") return value;
512
+ if (typeof value === "number" && Number.isFinite(value) && (!Number.isInteger(value) || Number.isSafeInteger(value))) return value;
513
+ return serialize(value)[0];
514
+ }
515
+ /** The conversion proper. `depth` is the depth of `value` itself (top = 1). */
516
+ function convert(value, depth, path) {
517
+ if (value === null || value === void 0) return null;
518
+ if (typeof value === "boolean" || typeof value === "string") return value;
519
+ if (typeof value === "number") return numberToJson(value);
520
+ if (typeof value === "bigint") return value.toString();
521
+ if (typeof value === "function" || typeof value === "symbol") return String(value);
522
+ const object = value;
523
+ if (object instanceof Date) {
524
+ const time = object.getTime();
525
+ return Number.isNaN(time) ? null : object.toISOString();
526
+ }
527
+ if (ArrayBuffer.isView(object)) return viewToJson(object, depth, path);
528
+ if (object instanceof ArrayBuffer) return dataUri(new Uint8Array(object));
529
+ if (object instanceof Error) return {
530
+ type: object.name,
531
+ message: object.message
532
+ };
533
+ if (object instanceof Map) return convertContainer(object, depth, path, () => {
534
+ const record = newRecord();
535
+ for (const [key, item] of object) {
536
+ if (withoutJsonForm(item)) continue;
537
+ record[String(key)] = convertChild(item, depth + 1, path);
538
+ }
539
+ return record;
540
+ });
541
+ if (object instanceof Set) return convertContainer(object, depth, path, () => {
542
+ const items = [];
543
+ for (const item of object) items.push(withoutJsonForm(item) ? null : convertChild(item, depth + 1, path));
544
+ return items;
545
+ });
546
+ if (Array.isArray(object)) return convertContainer(object, depth, path, () => {
547
+ const items = [];
548
+ for (const item of object) items.push(withoutJsonForm(item) ? null : convertChild(item, depth + 1, path));
549
+ return items;
550
+ });
551
+ const method = object.toJSON;
552
+ if (typeof method === "function") {
553
+ const toJSON = method.bind(object);
554
+ return convertContainer(object, depth, path, () => convert(toJSON(), depth, path));
555
+ }
556
+ return convertContainer(object, depth, path, () => {
557
+ const record = newRecord();
558
+ const fields = object;
559
+ for (const key of Object.keys(object)) {
560
+ const item = fields[key];
561
+ if (withoutJsonForm(item)) continue;
562
+ record[key] = convertChild(item, depth + 1, path);
563
+ }
564
+ return record;
565
+ });
566
+ }
567
+ /**
568
+ * One contained value: converted, or the in-place `<unserializable …>` marker
569
+ * when its conversion fails (§ Serialization rule 2, last row). A failure of
570
+ * the top-level value itself is not caught here: it escapes to `serialize`,
571
+ * whose rule-7 tuple replaces the whole payload.
572
+ */
573
+ function convertChild(value, depth, path) {
574
+ try {
575
+ return convert(value, depth, path);
576
+ } catch {
577
+ return `<unserializable ${typeName$1(value)}>`;
578
+ }
579
+ }
580
+ /**
581
+ * Rules 3 and 4 for one container: the cycle or depth marker when it applies,
582
+ * else `body()` with `container` added to the current path.
583
+ */
584
+ function convertContainer(container, depth, path, body) {
585
+ if (path.has(container)) return CYCLE_MARKER;
586
+ if (depth > 32) return MAX_DEPTH_MARKER;
587
+ path.add(container);
588
+ try {
589
+ return body();
590
+ } finally {
591
+ path.delete(container);
592
+ }
593
+ }
594
+ /** Byte views and `DataView` become one data URI; wider typed arrays their elements. */
595
+ function viewToJson(view, depth, path) {
596
+ if (view instanceof DataView || bytesPerElement(view) === 1) return dataUri(new Uint8Array(view.buffer, view.byteOffset, view.byteLength));
597
+ const elements = Array.from(view);
598
+ return convertContainer(view, depth, path, () => elements.map((element) => convert(element, depth + 1, path)));
599
+ }
600
+ function numberToJson(value) {
601
+ if (Number.isFinite(value)) return value;
602
+ if (Number.isNaN(value)) return "NaN";
603
+ return value > 0 ? "Infinity" : "-Infinity";
604
+ }
605
+ /** `undefined`, functions and symbols have no JSON form; the caller decides per position. */
606
+ function withoutJsonForm(value) {
607
+ return value === void 0 || typeof value === "function" || typeof value === "symbol";
608
+ }
609
+ /** `Object.create(null)`: a `"__proto__"` key must not hijack the record's prototype. */
610
+ function newRecord() {
611
+ return Object.create(null);
612
+ }
613
+ function bytesPerElement(view) {
614
+ return view.BYTES_PER_ELEMENT;
615
+ }
616
+ function dataUri(bytes) {
617
+ return `${DATA_URI_PREFIX}${base64(bytes)}`;
618
+ }
619
+ /** Standard base64 with `=` padding; no `Buffer` (the SDK runs on any runtime). */
620
+ function base64(bytes) {
621
+ let out = "";
622
+ const length = bytes.length;
623
+ for (let i = 0; i < length; i += 3) {
624
+ const b0 = bytes[i] ?? 0;
625
+ const b1 = bytes[i + 1] ?? 0;
626
+ const b2 = bytes[i + 2] ?? 0;
627
+ out += BASE64_ALPHABET.charAt(b0 >> 2);
628
+ out += BASE64_ALPHABET.charAt((b0 & 3) << 4 | b1 >> 4);
629
+ out += i + 1 < length ? BASE64_ALPHABET.charAt((b1 & 15) << 2 | b2 >> 6) : "=";
630
+ out += i + 2 < length ? BASE64_ALPHABET.charAt(b2 & 63) : "=";
631
+ }
632
+ return out;
633
+ }
634
+ function typeName$1(value) {
635
+ try {
636
+ return value?.constructor?.name ?? typeof value;
637
+ } catch {
638
+ return typeof value;
639
+ }
640
+ }
641
+ // src/mask.ts
642
+ const MASK_FAILED = "[cetra: mask failed]";
643
+ /**
644
+ * § Payload keys: the exact attribute names every known schema uses for
645
+ * payload content, in span and event attributes alike.
646
+ */
647
+ const PAYLOAD_KEYS = /* @__PURE__ */ new Set([
648
+ "cetra.input",
649
+ "cetra.output",
650
+ "gen_ai.input.messages",
651
+ "gen_ai.output.messages",
652
+ "gen_ai.system_instructions",
653
+ "gen_ai.tool.call.arguments",
654
+ "gen_ai.tool.call.result",
655
+ "input.value",
656
+ "output.value",
657
+ "traceloop.entity.input",
658
+ "traceloop.entity.output",
659
+ "ai.prompt",
660
+ "ai.prompt.messages",
661
+ "ai.response.text",
662
+ "ai.response.object",
663
+ "ai.response.toolCalls",
664
+ "ai.toolCall.args",
665
+ "ai.toolCall.result",
666
+ "langfuse.observation.input",
667
+ "langfuse.observation.output",
668
+ "langfuse.trace.input",
669
+ "langfuse.trace.output",
670
+ "lmnr.span.input",
671
+ "lmnr.span.output"
672
+ ]);
673
+ /** Prefixes under which a schema spreads its payload over several keys. */
674
+ const PAYLOAD_PREFIXES = [
675
+ "llm.input_messages.",
676
+ "llm.output_messages.",
677
+ "gen_ai.prompt.",
678
+ "gen_ai.completion."
679
+ ];
680
+ function isPayloadKey(key) {
681
+ return PAYLOAD_KEYS.has(key) || PAYLOAD_PREFIXES.some((prefix) => key.startsWith(prefix));
682
+ }
683
+ /** Apply the running runtime's `mask` to `value`. Never throws. */
684
+ function applyMask(value) {
685
+ const mask = currentRuntime()?.config.mask;
686
+ if (mask === void 0) return value;
687
+ return applyWithFailClosed(mask, value);
688
+ }
689
+ /** Run `mask`; a raising mask fails closed to the marker (D-F-6). */
690
+ function applyWithFailClosed(mask, value) {
691
+ try {
692
+ return mask(value);
693
+ } catch (error) {
694
+ debug(`cetra: mask raised ${errorName$10(error)}`);
695
+ return MASK_FAILED;
696
+ }
697
+ }
698
+ /**
699
+ * The export-time masking pass (D-F-6), installed by `Runtime.create` only
700
+ * when a `mask` is configured or `captureContent` is false. Spans whose scope
701
+ * is `cetra` were already masked at capture and pass through untouched.
702
+ */
703
+ var MaskingExporter = class {
704
+ inner;
705
+ mask;
706
+ captureContent;
707
+ constructor(inner, options) {
708
+ this.inner = inner;
709
+ this.mask = options.mask;
710
+ this.captureContent = options.captureContent;
711
+ }
712
+ export(spans, resultCallback) {
713
+ let masked;
714
+ try {
715
+ masked = spans.map((span) => this.rewrite(span));
716
+ } catch {
717
+ runtimeGlobals().console?.warn(`cetra: masking failed; dropped ${spans.length} spans`);
718
+ resultCallback({
719
+ code: ExportResultCode.FAILED,
720
+ error: /* @__PURE__ */ new Error("masking failed")
721
+ });
722
+ return;
723
+ }
724
+ this.inner.export(masked, resultCallback);
725
+ }
726
+ async shutdown() {
727
+ await this.inner.shutdown();
728
+ }
729
+ async forceFlush() {
730
+ await this.inner.forceFlush?.();
731
+ }
732
+ /**
733
+ * A span with no payload key passes by reference; otherwise the rewrite is a
734
+ * new object literal implementing `ReadableSpan` field by field. Never
735
+ * spread the original: its `spanContext` lives on the prototype.
736
+ */
737
+ rewrite(span) {
738
+ if (span.instrumentationScope.name === "cetra" || !hasPayloadKeys(span)) return span;
739
+ return {
740
+ name: span.name,
741
+ kind: span.kind,
742
+ spanContext: () => span.spanContext(),
743
+ parentSpanContext: span.parentSpanContext,
744
+ startTime: span.startTime,
745
+ endTime: span.endTime,
746
+ status: span.status,
747
+ attributes: this.rewriteAttributes(span.attributes),
748
+ links: span.links,
749
+ events: span.events.map((event) => ({
750
+ time: event.time,
751
+ name: event.name,
752
+ attributes: event.attributes === void 0 ? void 0 : this.rewriteAttributes(event.attributes),
753
+ droppedAttributesCount: event.droppedAttributesCount
754
+ })),
755
+ duration: span.duration,
756
+ ended: span.ended,
757
+ resource: span.resource,
758
+ instrumentationScope: span.instrumentationScope,
759
+ droppedAttributesCount: span.droppedAttributesCount,
760
+ droppedEventsCount: span.droppedEventsCount,
761
+ droppedLinksCount: span.droppedLinksCount
762
+ };
763
+ }
764
+ /**
765
+ * Payload values: dropped when capture is off or (only strings are masked)
766
+ * when the value is not a string; otherwise decoded, masked, re-encoded.
767
+ * Every other key is copied unchanged.
768
+ */
769
+ rewriteAttributes(attributes) {
770
+ const mask = this.mask;
771
+ const next = {};
772
+ for (const [key, value] of Object.entries(attributes)) {
773
+ if (!isPayloadKey(key)) {
774
+ next[key] = value;
775
+ continue;
776
+ }
777
+ if (!this.captureContent || typeof value !== "string" || mask === void 0) continue;
778
+ next[key] = maskPayloadValue(mask, value);
779
+ }
780
+ return next;
781
+ }
782
+ };
783
+ function hasPayloadKeys(span) {
784
+ if (attributesHavePayloadKey(span.attributes)) return true;
785
+ return span.events.some((event) => attributesHavePayloadKey(event.attributes));
786
+ }
787
+ function attributesHavePayloadKey(attributes) {
788
+ return attributes !== void 0 && Object.keys(attributes).some(isPayloadKey);
789
+ }
790
+ /** Decode, mask, re-encode: a string result as is, anything else serialized. */
791
+ function maskPayloadValue(mask, text) {
792
+ const masked = applyWithFailClosed(mask, decodePayload(text));
793
+ return typeof masked === "string" ? masked : serialize(masked)[0];
794
+ }
795
+ /** The JSON value when the text is a JSON object or array, else the text. */
796
+ function decodePayload(text) {
797
+ const stripped = text.trim();
798
+ if (stripped.startsWith("{") || stripped.startsWith("[")) try {
799
+ return JSON.parse(stripped);
800
+ } catch {
801
+ return text;
802
+ }
803
+ return text;
804
+ }
805
+ function errorName$10(error) {
806
+ return error instanceof Error ? error.name : typeof error;
807
+ }
808
+ // src/template.ts
809
+ /**
810
+ * Plain `{{ name }}` prompt templates (D-V-3, D-V-5): the rules of
811
+ * `fixtures/prompts`, the same as `crates/eval/src/plain_template.rs` and the
812
+ * Python SDK's `_template.py`. Substitution only, no logic.
813
+ */
814
+ /** Names minijinja reads as literals or globals; a variable cannot use them (D-V-3). */
815
+ const RESERVED = /* @__PURE__ */ new Set([
816
+ "true",
817
+ "false",
818
+ "none",
819
+ "True",
820
+ "False",
821
+ "None",
822
+ "and",
823
+ "or",
824
+ "not",
825
+ "in",
826
+ "is",
827
+ "if",
828
+ "else",
829
+ "loop",
830
+ "self",
831
+ "range",
832
+ "dict",
833
+ "namespace",
834
+ "debug"
835
+ ]);
836
+ const NAME = /^[A-Za-z_][A-Za-z0-9_]*$/;
837
+ /**
838
+ * A template is invalid, or a variable or placeholder has no value.
839
+ *
840
+ * `kind` is `invalid`, `missing_variable` or `missing_placeholder`. `variable`
841
+ * is the missing name; `reason`, `line` and `column` describe an invalid
842
+ * template. The message never quotes the template.
843
+ */
844
+ var PromptCompileError = class extends Error {
845
+ kind;
846
+ variable;
847
+ reason;
848
+ line;
849
+ column;
850
+ /** The prompt's name, when the error came from `Prompt.compile` or a fallback. */
851
+ prompt;
852
+ constructor(kind, details) {
853
+ super(compileMessage(kind, details));
854
+ this.name = "PromptCompileError";
855
+ this.kind = kind;
856
+ this.variable = details.variable;
857
+ this.reason = details.reason;
858
+ this.line = details.line;
859
+ this.column = details.column;
860
+ this.prompt = details.prompt;
861
+ }
862
+ };
863
+ function compileMessage(kind, details) {
864
+ let detail;
865
+ if (kind === "missing_variable") detail = `missing variable ${details.variable}`;
866
+ else if (kind === "missing_placeholder") detail = `missing placeholder ${details.variable}`;
867
+ else if (details.line === void 0) detail = `invalid template: ${details.reason}`;
868
+ else detail = `invalid template at line ${details.line}, column ${details.column}: ${details.reason}`;
869
+ return details.prompt === void 0 ? detail : `prompt ${details.prompt}: ${detail}`;
870
+ }
871
+ function invalid(line, column, reason) {
872
+ return new PromptCompileError("invalid", {
873
+ line,
874
+ column,
875
+ reason
876
+ });
877
+ }
878
+ /** Removes leading and trailing spaces and tabs only (not a regex: linear on any input). */
879
+ function trimTags(text) {
880
+ let start = 0;
881
+ let end = text.length;
882
+ while (start < end && (text[start] === " " || text[start] === " ")) start += 1;
883
+ while (end > start && (text[end - 1] === " " || text[end - 1] === " ")) end -= 1;
884
+ return text.slice(start, end);
885
+ }
886
+ /**
887
+ * Splits `source` into text and variables. Adjacent text is one segment; empty
888
+ * text segments are not produced. Columns count code points.
889
+ */
890
+ function scan(source) {
891
+ const segments = [];
892
+ let textStart = 0;
893
+ let line = 1;
894
+ let column = 1;
895
+ let index = 0;
896
+ while (index < source.length) {
897
+ if (source[index] === "{") {
898
+ const next = source[index + 1];
899
+ if (next === "%" || next === "#") throw invalid(line, column, "block");
900
+ if (next === "{") {
901
+ const innerStart = index + 2;
902
+ const relativeEnd = source.indexOf("}}", innerStart);
903
+ if (relativeEnd < 0) throw invalid(line, column, "unclosed");
904
+ const name = trimTags(source.slice(innerStart, relativeEnd));
905
+ if (!NAME.test(name)) throw invalid(line, column, "not_a_name");
906
+ if (RESERVED.has(name)) throw invalid(line, column, "reserved");
907
+ if (textStart < index) segments.push({
908
+ kind: "text",
909
+ text: source.slice(textStart, index)
910
+ });
911
+ segments.push({
912
+ kind: "var",
913
+ name
914
+ });
915
+ const after = relativeEnd + 2;
916
+ column += after - index;
917
+ textStart = after;
918
+ index = after;
919
+ continue;
920
+ }
921
+ }
922
+ if (source[index] === "\n") {
923
+ line += 1;
924
+ column = 1;
925
+ index += 1;
926
+ } else {
927
+ const width = (source.codePointAt(index) ?? 0) > 65535 ? 2 : 1;
928
+ column += 1;
929
+ index += width;
930
+ }
931
+ }
932
+ if (textStart < source.length) segments.push({
933
+ kind: "text",
934
+ text: source.slice(textStart)
935
+ });
936
+ return segments;
937
+ }
938
+ /** The first variable of `segments` with no value, in template order, is an error. */
939
+ function checkVariables(segments, values) {
940
+ for (const segment of segments) if (segment.kind === "var" && !Object.hasOwn(values, segment.name)) throw new PromptCompileError("missing_variable", { variable: segment.name });
941
+ }
942
+ /** Joins the segments; values are inserted verbatim. Call `checkVariables` first. */
943
+ function fill(segments, values) {
944
+ let out = "";
945
+ for (const segment of segments) out += segment.kind === "text" ? segment.text : values[segment.name] ?? "";
946
+ return out;
947
+ }
948
+ /** The variable names, in order of first appearance, without duplicates. */
949
+ function variables(source) {
950
+ const seen = /* @__PURE__ */ new Set();
951
+ for (const segment of scan(source)) if (segment.kind === "var") seen.add(segment.name);
952
+ return [...seen];
953
+ }
954
+ /**
955
+ * Renders `source`: each variable is replaced by its value, inserted verbatim
956
+ * (never scanned again). Values not used by the template are ignored.
957
+ */
958
+ function render(source, values) {
959
+ const segments = scan(source);
960
+ checkVariables(segments, values);
961
+ return fill(segments, values);
962
+ }
963
+ /**
964
+ * Classifies one chat entry. An entry with `type === "placeholder"` is a
965
+ * placeholder and needs a string `name`; any other entry must have string
966
+ * `role` and `content`.
967
+ */
968
+ function classify(entry) {
969
+ if (typeof entry !== "object" || entry === null) throw new PromptCompileError("invalid", { reason: "not_a_message" });
970
+ const fields = entry;
971
+ if (fields.type === "placeholder") {
972
+ if (typeof fields.name !== "string") throw new PromptCompileError("invalid", { reason: "not_a_message" });
973
+ const name = trimTags(fields.name);
974
+ if (!NAME.test(name)) throw new PromptCompileError("invalid", { reason: "not_a_name" });
975
+ if (RESERVED.has(name)) throw new PromptCompileError("invalid", { reason: "reserved" });
976
+ return {
977
+ kind: "placeholder",
978
+ name
979
+ };
980
+ }
981
+ const role = fields.role;
982
+ const content = fields.content;
983
+ if (typeof role !== "string" || typeof content !== "string") throw new PromptCompileError("invalid", { reason: "not_a_message" });
984
+ return {
985
+ kind: "message",
986
+ role,
987
+ segments: scan(content)
988
+ };
989
+ }
990
+ /** The variable and placeholder names of a chat template, each in order of first use. */
991
+ function chatNames(template) {
992
+ const names = /* @__PURE__ */ new Set();
993
+ const placeholders = /* @__PURE__ */ new Set();
994
+ for (const entry of template.map(classify)) if (entry.kind === "placeholder") placeholders.add(entry.name);
995
+ else for (const segment of entry.segments) if (segment.kind === "var") names.add(segment.name);
996
+ return {
997
+ variables: [...names],
998
+ placeholders: [...placeholders]
999
+ };
1000
+ }
1001
+ /**
1002
+ * Renders a chat template. Checks run in this order, each raising the first
1003
+ * failure: every entry is valid; every variable of every message has a value;
1004
+ * every placeholder is given. Messages render to `{role, content}`; a
1005
+ * placeholder becomes copies of the given messages, which are not rendered.
1006
+ */
1007
+ function renderChat(template, values, placeholders) {
1008
+ const entries = template.map(classify);
1009
+ for (const entry of entries) if (entry.kind === "message") checkVariables(entry.segments, values);
1010
+ for (const entry of entries) if (entry.kind === "placeholder" && !Object.hasOwn(placeholders, entry.name)) throw new PromptCompileError("missing_placeholder", { variable: entry.name });
1011
+ const out = [];
1012
+ for (const entry of entries) if (entry.kind === "message") out.push({
1013
+ role: entry.role,
1014
+ content: fill(entry.segments, values)
1015
+ });
1016
+ else for (const message of placeholders[entry.name] ?? []) out.push({ ...message });
1017
+ return out;
1018
+ }
1019
+ // src/prompt.ts
1020
+ /**
1021
+ * `Prompt` and `PromptNotAvailable` (D-V-14, D-V-15), in a leaf module: it
1022
+ * imports the template renderer, the logger and OTel only, so `context.ts`
1023
+ * and `prompts.ts` can both import it without a cycle.
1024
+ */
1025
+ /** No prompt could be fetched, and the call gave no fallback (D-V-14). */
1026
+ var PromptNotAvailable = class extends Error {
1027
+ prompt;
1028
+ reason;
1029
+ constructor(prompt, reason) {
1030
+ super(`prompt ${prompt} is not available: ${reason}`);
1031
+ this.name = "PromptNotAvailable";
1032
+ this.prompt = prompt;
1033
+ this.reason = reason;
1034
+ }
1035
+ };
1036
+ /** A prompt version from the registry, or a fallback (D-V-14). */
1037
+ var Prompt = class {
1038
+ name;
1039
+ type;
1040
+ template;
1041
+ /** `undefined` for a fallback. */
1042
+ version;
1043
+ config;
1044
+ labels;
1045
+ variables;
1046
+ placeholders;
1047
+ isFallback;
1048
+ /**
1049
+ * Throws `PromptCompileError` when the template is invalid.
1050
+ * @internal
1051
+ */
1052
+ constructor(fields) {
1053
+ this.name = fields.name;
1054
+ this.version = fields.version;
1055
+ this.config = Object.freeze({ ...fields.config });
1056
+ this.labels = Object.freeze([...fields.labels]);
1057
+ this.isFallback = fields.isFallback;
1058
+ if (typeof fields.template === "string") {
1059
+ this.type = "text";
1060
+ this.template = fields.template;
1061
+ this.variables = variables(fields.template);
1062
+ this.placeholders = [];
1063
+ } else {
1064
+ const names = chatNames(fields.template);
1065
+ this.type = "chat";
1066
+ this.template = Object.freeze([...fields.template]);
1067
+ this.variables = names.variables;
1068
+ this.placeholders = names.placeholders;
1069
+ }
1070
+ }
1071
+ /**
1072
+ * Renders the template with `values`. A missing variable or placeholder, or
1073
+ * an invalid template, throws `PromptCompileError` carrying the prompt name;
1074
+ * a value of another type throws `TypeError`. On success the current span,
1075
+ * when it records, gets `cetra.prompt.name` and `cetra.prompt.version`.
1076
+ */
1077
+ compile(values = {}) {
1078
+ const strings = [];
1079
+ const lists = [];
1080
+ for (const [key, value] of Object.entries(values)) if (typeof value === "string") strings.push([key, value]);
1081
+ else if (typeof value === "number") {
1082
+ if (!Number.isFinite(value)) throw new TypeError(`prompt value ${key}: not a finite number`);
1083
+ strings.push([key, String(value)]);
1084
+ } else if (typeof value === "boolean") strings.push([key, value ? "true" : "false"]);
1085
+ else if (isMessageList(value)) lists.push([key, value]);
1086
+ else throw new TypeError(`prompt value ${key}: unsupported type`);
1087
+ const stringValues = Object.fromEntries(strings);
1088
+ const listValues = Object.fromEntries(lists);
1089
+ let rendered;
1090
+ try {
1091
+ rendered = typeof this.template === "string" ? render(this.template, stringValues) : renderChat(this.template, stringValues, listValues);
1092
+ } catch (error) {
1093
+ if (error instanceof PromptCompileError) throw new PromptCompileError(error.kind, {
1094
+ variable: error.variable,
1095
+ reason: error.reason,
1096
+ line: error.line,
1097
+ column: error.column,
1098
+ prompt: this.name
1099
+ });
1100
+ throw error;
1101
+ }
1102
+ this.#link();
1103
+ return rendered;
1104
+ }
1105
+ /** Stamps the prompt on the active span when it records. Never throws. */
1106
+ #link() {
1107
+ try {
1108
+ const span = trace.getSpan(context.active());
1109
+ if (span?.isRecording()) {
1110
+ span.setAttribute("cetra.prompt.name", this.name);
1111
+ if (this.version !== void 0) span.setAttribute("cetra.prompt.version", this.version);
1112
+ }
1113
+ } catch (error) {
1114
+ debug(`cetra: could not link the prompt (${errorName$9(error)})`);
1115
+ }
1116
+ }
1117
+ };
1118
+ /** A list of `{role, content}` string mappings: the value of a placeholder. */
1119
+ function isMessageList(value) {
1120
+ return Array.isArray(value) && value.every((item) => typeof item === "object" && item !== null && typeof item.role === "string" && typeof item.content === "string");
1121
+ }
1122
+ function errorName$9(error) {
1123
+ return error instanceof Error ? error.name : typeof error;
1124
+ }
1125
+ // src/context.ts
1126
+ /**
1127
+ * `withContext` and the context values it stores in the OTel context (D-F-12).
1128
+ *
1129
+ * The values live under one context key, so they follow the context manager
1130
+ * (`AsyncLocalStorage` on Node) into callbacks, promises and concurrent flows.
1131
+ * Nested blocks merge: inner session/user win, tags are the union (outer
1132
+ * first, no duplicates), metadata merges by key with the inner value winning.
1133
+ * Invalid options are dropped silently, with a debug log; user code runs
1134
+ * unchanged either way.
1135
+ */
1136
+ /** README § Names: one OTel context key for all context values. */
1137
+ const CONTEXT_KEY = createContextKey("cetra.context");
1138
+ const BAGGAGE_SESSION_KEY = "cetra.session.id";
1139
+ const BAGGAGE_USER_KEY = "cetra.user.id";
1140
+ /** § Span attributes: not empty, only `[A-Za-z0-9_.-]`. */
1141
+ const METADATA_KEY = /^[A-Za-z0-9_.-]+$/;
1142
+ const EMPTY_VALUES = Object.freeze({
1143
+ sessionId: void 0,
1144
+ userId: void 0,
1145
+ tags: Object.freeze([]),
1146
+ metadata: Object.freeze({}),
1147
+ experiment: void 0,
1148
+ prompt: void 0
1149
+ });
1150
+ /**
1151
+ * A context holding only the experiment link, built on `ROOT_CONTEXT`: no
1152
+ * active span, no baggage and none of the caller's values, so the run's root
1153
+ * span starts a new trace. Internal (`evaluate`).
1154
+ */
1155
+ function experimentContext(experimentId, datasetItemId) {
1156
+ const values = Object.freeze({
1157
+ ...EMPTY_VALUES,
1158
+ experiment: Object.freeze({
1159
+ experimentId,
1160
+ datasetItemId
1161
+ })
1162
+ });
1163
+ return ROOT_CONTEXT.setValue(CONTEXT_KEY, values);
1164
+ }
1165
+ /** The context values of `ctx` (the active context when omitted). Internal. */
1166
+ function currentValues(ctx) {
1167
+ return coerceValues((ctx ?? context.active()).getValue(CONTEXT_KEY));
1168
+ }
1169
+ /**
1170
+ * Run `fn` with the merged context values in scope. The return value (a
1171
+ * promise included) is returned unchanged; so are `fn`'s exceptions.
1172
+ */
1173
+ function withContext(options, fn) {
1174
+ return context.with(contextFor(options), fn);
1175
+ }
1176
+ /**
1177
+ * The context to enter: the active context plus the merged values under
1178
+ * `CONTEXT_KEY` and, with `propagate`, our two baggage entries merged into
1179
+ * any existing baggage. Never throws; on failure the active context.
1180
+ */
1181
+ function contextFor(options) {
1182
+ try {
1183
+ const raw = options;
1184
+ const outer = currentValues();
1185
+ const inner = validOptions(raw);
1186
+ const merged = Object.freeze({
1187
+ sessionId: inner.sessionId ?? outer.sessionId,
1188
+ userId: inner.userId ?? outer.userId,
1189
+ tags: Object.freeze(unionTags(outer.tags, inner.tags)),
1190
+ metadata: Object.freeze({
1191
+ ...outer.metadata,
1192
+ ...inner.metadata
1193
+ }),
1194
+ experiment: outer.experiment,
1195
+ prompt: inner.prompt ?? outer.prompt
1196
+ });
1197
+ let ctx = context.active().setValue(CONTEXT_KEY, merged);
1198
+ if (raw.propagate) {
1199
+ let baggage = propagation.getBaggage(ctx) ?? propagation.createBaggage();
1200
+ if (merged.sessionId !== void 0) baggage = baggage.setEntry(BAGGAGE_SESSION_KEY, { value: merged.sessionId });
1201
+ if (merged.userId !== void 0) baggage = baggage.setEntry(BAGGAGE_USER_KEY, { value: merged.userId });
1202
+ ctx = propagation.setBaggage(ctx, baggage);
1203
+ }
1204
+ return ctx;
1205
+ } catch (error) {
1206
+ debug(`cetra: withContext failed: ${errorName$8(error)}`);
1207
+ return context.active();
1208
+ }
1209
+ }
1210
+ /** The valid parts of user-given options; invalid values are dropped silently. */
1211
+ function validOptions(raw) {
1212
+ const sessionId = validString(raw.sessionId, "sessionId");
1213
+ const userId = validString(raw.userId, "userId");
1214
+ const tags = validTags(raw.tags);
1215
+ const metadata = {};
1216
+ const source = raw.metadata;
1217
+ if (typeof source === "object" && source !== null && !Array.isArray(source)) for (const [key, value] of Object.entries(source)) metadata[key] = applyMask(value);
1218
+ else if (source !== void 0) debug("cetra: withContext metadata option dropped");
1219
+ return {
1220
+ sessionId,
1221
+ userId,
1222
+ tags,
1223
+ metadata,
1224
+ prompt: validPrompt(raw.prompt)
1225
+ };
1226
+ }
1227
+ /** The link of a `Prompt`; anything else is dropped with a debug log. */
1228
+ function validPrompt(value) {
1229
+ if (value === void 0) return;
1230
+ if (value instanceof Prompt) return Object.freeze({
1231
+ name: value.name,
1232
+ version: value.version
1233
+ });
1234
+ debug("cetra: withContext prompt option dropped");
1235
+ }
1236
+ function validString(value, name) {
1237
+ if (typeof value === "string") return value;
1238
+ if (value !== void 0) debug(`cetra: withContext ${name} option dropped`);
1239
+ }
1240
+ /** A bare string is one tag; non-string items of an array are skipped. */
1241
+ function validTags(value) {
1242
+ if (typeof value === "string") return [value];
1243
+ if (!Array.isArray(value)) {
1244
+ if (value !== void 0) debug("cetra: withContext tags option dropped");
1245
+ return [];
1246
+ }
1247
+ return value.filter((tag) => typeof tag === "string");
1248
+ }
1249
+ /** The union of outer and inner tags: outer first, no duplicates. */
1250
+ function unionTags(outer, inner) {
1251
+ const seen = new Set(outer);
1252
+ const tags = [...outer];
1253
+ for (const tag of inner) if (!seen.has(tag)) {
1254
+ seen.add(tag);
1255
+ tags.push(tag);
1256
+ }
1257
+ return tags;
1258
+ }
1259
+ /** Only what this module stored passes as is; anything else under the key is garbage. */
1260
+ function coerceValues(raw) {
1261
+ if (typeof raw !== "object" || raw === null || Array.isArray(raw)) return EMPTY_VALUES;
1262
+ const record = raw;
1263
+ const tags = Array.isArray(record.tags) ? record.tags.filter((tag) => typeof tag === "string") : [];
1264
+ const metadata = typeof record.metadata === "object" && record.metadata !== null && !Array.isArray(record.metadata) ? record.metadata : {};
1265
+ return {
1266
+ sessionId: typeof record.sessionId === "string" ? record.sessionId : void 0,
1267
+ userId: typeof record.userId === "string" ? record.userId : void 0,
1268
+ tags,
1269
+ metadata,
1270
+ experiment: coerceLink(record.experiment),
1271
+ prompt: coercePrompt(record.prompt)
1272
+ };
1273
+ }
1274
+ /** A prompt link with a string name; anything else is no link. */
1275
+ function coercePrompt(raw) {
1276
+ if (typeof raw !== "object" || raw === null) return;
1277
+ const record = raw;
1278
+ if (typeof record.name !== "string") return;
1279
+ return {
1280
+ name: record.name,
1281
+ version: typeof record.version === "number" ? record.version : void 0
1282
+ };
1283
+ }
1284
+ /** An experiment link with two string ids; anything else is no link. */
1285
+ function coerceLink(raw) {
1286
+ if (typeof raw !== "object" || raw === null) return;
1287
+ const record = raw;
1288
+ if (typeof record.experimentId !== "string" || typeof record.datasetItemId !== "string") return;
1289
+ return {
1290
+ experimentId: record.experimentId,
1291
+ datasetItemId: record.datasetItemId
1292
+ };
1293
+ }
1294
+ const skippedMetadataKeys = /* @__PURE__ */ new Set();
1295
+ /**
1296
+ * The attribute name a metadata key maps to (`cetra.metadata.<key>`), or
1297
+ * `undefined` when the key fails the rule (§ Span attributes). A failing key
1298
+ * is logged once at debug level, with its length only, never the key.
1299
+ */
1300
+ function metadataAttributeName(key) {
1301
+ if (METADATA_KEY.test(key)) return `cetra.metadata.${key}`;
1302
+ if (!skippedMetadataKeys.has(key)) {
1303
+ skippedMetadataKeys.add(key);
1304
+ debug(`cetra: metadata key of length ${key.length} skipped`);
1305
+ }
1306
+ }
1307
+ function errorName$8(error) {
1308
+ return error instanceof Error ? error.name : typeof error;
1309
+ }
1310
+ // src/filter.ts
1311
+ /** Scope names whose spans are always ours to export. */
1312
+ const EXPORTED_SCOPES = /* @__PURE__ */ new Set(["cetra", "ai"]);
1313
+ const ATTRIBUTE_PREFIXES = [
1314
+ "cetra.",
1315
+ "gen_ai.",
1316
+ "llm.",
1317
+ "openinference.",
1318
+ "ai.",
1319
+ "traceloop.",
1320
+ "langfuse.",
1321
+ "lmnr.",
1322
+ "gcp.vertex.agent."
1323
+ ];
1324
+ /** Keys the schemas use for top-level payloads without a namespace. */
1325
+ const EXACT_ATTRIBUTE_KEYS = /* @__PURE__ */ new Set(["input.value", "output.value"]);
1326
+ /** D-F-5: export a span of our (global) provider or drop it as foreign noise. */
1327
+ function defaultFilter(span) {
1328
+ if (EXPORTED_SCOPES.has(span.instrumentationScope.name)) return true;
1329
+ for (const key of Object.keys(span.attributes)) if (EXACT_ATTRIBUTE_KEYS.has(key) || ATTRIBUTE_PREFIXES.some((prefix) => key.startsWith(prefix))) return true;
1330
+ return false;
1331
+ }
1332
+ // src/processor.ts
1333
+ /**
1334
+ * The cetra span processor.
1335
+ *
1336
+ * Owns an OTel `BatchSpanProcessor` (1 s scheduled delay, 45 s export
1337
+ * timeout — above the exporter's 30 s retry deadline, so `flush()` waits for
1338
+ * retries), stamps the context values (D-F-12) plus
1339
+ * `cetra.environment` / `cetra.release` on every span our provider
1340
+ * starts, whatever tracer created it, and decides each ended span's export
1341
+ * fate (D-F-5). Nothing here raises into the app: every method catches and
1342
+ * logs the error name at debug level.
1343
+ */
1344
+ var CetraSpanProcessor = class {
1345
+ batch;
1346
+ environment;
1347
+ release;
1348
+ exportFilter;
1349
+ /** Whether the D-F-5 default rule applies (global mode). */
1350
+ defaultFilterMode;
1351
+ constructor(exporter, options) {
1352
+ this.batch = new BatchSpanProcessor({
1353
+ exporter,
1354
+ scheduledDelayMillis: 1e3,
1355
+ exportTimeoutMillis: 45e3
1356
+ });
1357
+ this.environment = options.environment;
1358
+ this.release = options.release;
1359
+ this.exportFilter = options.exportFilter;
1360
+ this.defaultFilterMode = options.defaultFilter;
1361
+ }
1362
+ onStart(span, parentContext) {
1363
+ try {
1364
+ stampContext(span, parentContext);
1365
+ const experiment = currentValues(parentContext).experiment;
1366
+ if (experiment !== void 0) {
1367
+ span.setAttribute("cetra.experiment.id", experiment.experimentId);
1368
+ span.setAttribute("cetra.dataset_item.id", experiment.datasetItemId);
1369
+ span.setAttribute("cetra.environment", "experiment");
1370
+ } else if (this.environment !== void 0) span.setAttribute("cetra.environment", this.environment);
1371
+ if (this.release !== void 0) span.setAttribute("cetra.release", this.release);
1372
+ } catch (error) {
1373
+ debug(`cetra: span processor onStart failed: ${errorName$7(error)}`);
1374
+ }
1375
+ }
1376
+ onEnd(span) {
1377
+ try {
1378
+ if (this.exports(span)) this.batch.onEnd(span);
1379
+ } catch (error) {
1380
+ debug(`cetra: span processor onEnd failed: ${errorName$7(error)}`);
1381
+ }
1382
+ }
1383
+ /**
1384
+ * D-F-5: a configured `exportFilter` replaces the rule in both modes (a
1385
+ * raising filter exports the span); without one, the default rule applies
1386
+ * only in global mode; in own mode everything is exported.
1387
+ */
1388
+ exports(span) {
1389
+ if (this.exportFilter !== void 0) try {
1390
+ return this.exportFilter(span);
1391
+ } catch (error) {
1392
+ debug(`cetra: exportFilter raised ${errorName$7(error)}; span exported`);
1393
+ return true;
1394
+ }
1395
+ return this.defaultFilterMode ? defaultFilter(span) : true;
1396
+ }
1397
+ async forceFlush() {
1398
+ try {
1399
+ await this.batch.forceFlush();
1400
+ } catch (error) {
1401
+ debug(`cetra: span processor forceFlush failed: ${errorName$7(error)}`);
1402
+ }
1403
+ }
1404
+ async shutdown() {
1405
+ try {
1406
+ await this.batch.shutdown();
1407
+ } catch (error) {
1408
+ debug(`cetra: span processor shutdown failed: ${errorName$7(error)}`);
1409
+ }
1410
+ }
1411
+ };
1412
+ /**
1413
+ * § Span attributes: session/user from the context values, else from baggage;
1414
+ * tags when non-empty; each metadata entry under its own key. Runs for every
1415
+ * span of our provider, instrumentor spans included.
1416
+ */
1417
+ function stampContext(span, parentContext) {
1418
+ const values = currentValues(parentContext);
1419
+ stampSessionOrUser(span, "cetra.session.id", values.sessionId, parentContext);
1420
+ stampSessionOrUser(span, "cetra.user.id", values.userId, parentContext);
1421
+ if (values.tags.length > 0) span.setAttribute("cetra.tags", [...values.tags]);
1422
+ for (const [key, value] of Object.entries(values.metadata)) {
1423
+ const name = metadataAttributeName(key);
1424
+ if (name !== void 0) span.setAttribute(name, attributeValue(value));
1425
+ }
1426
+ if (values.prompt !== void 0) {
1427
+ span.setAttribute("cetra.prompt.name", values.prompt.name);
1428
+ if (values.prompt.version !== void 0) span.setAttribute("cetra.prompt.version", values.prompt.version);
1429
+ }
1430
+ }
1431
+ function stampSessionOrUser(span, name, fromContext, parentContext) {
1432
+ if (fromContext !== void 0) {
1433
+ span.setAttribute(name, fromContext);
1434
+ return;
1435
+ }
1436
+ const entry = propagation.getBaggage(parentContext ?? ROOT_CONTEXT)?.getEntry(name)?.value;
1437
+ if (typeof entry === "string") span.setAttribute(name, entry);
1438
+ }
1439
+ function errorName$7(error) {
1440
+ return error instanceof Error ? error.name : typeof error;
1441
+ }
1442
+ // src/datasets.ts
1443
+ /** Page size of the list and item routes. */
1444
+ const PAGE_SIZE = 1e3;
1445
+ /** Items per `POST /datasets/{dataset}/items` request. */
1446
+ const ADD_BATCH_SIZE$1 = 1e3;
1447
+ const ITEM_KEYS = /* @__PURE__ */ new Set([
1448
+ "input",
1449
+ "expectedOutput",
1450
+ "metadata"
1451
+ ]);
1452
+ /** One version of a dataset with all its items. */
1453
+ var Dataset = class {
1454
+ id;
1455
+ name;
1456
+ description;
1457
+ /** The version these items belong to. */
1458
+ version;
1459
+ items;
1460
+ #client;
1461
+ /** @internal */
1462
+ constructor(fields, client) {
1463
+ this.id = fields.id;
1464
+ this.name = fields.name;
1465
+ this.description = fields.description;
1466
+ this.version = fields.version;
1467
+ this.items = fields.items;
1468
+ this.#client = client;
1469
+ }
1470
+ /**
1471
+ * Add items; each batch of up to 1,000 makes one new version (D-J-3).
1472
+ * Rejects with `TypeError` before any request when an item is malformed.
1473
+ * Resolves to the latest version; an empty iterable resolves to `this`.
1474
+ * Batches are sent in order: if a later batch fails, the earlier batches are
1475
+ * already stored (each made a version), and the promise rejects.
1476
+ */
1477
+ async addItems(items) {
1478
+ const all = [...items];
1479
+ all.forEach(checkItem);
1480
+ if (all.length === 0) return this;
1481
+ for (let start = 0; start < all.length; start += ADD_BATCH_SIZE$1) {
1482
+ const batch = all.slice(start, start + ADD_BATCH_SIZE$1).map(itemToWire);
1483
+ await this.#client.request("POST", "/datasets/{dataset}/items", `/datasets/${segment(this.id)}/items`, {
1484
+ body: { items: batch },
1485
+ retry: false
1486
+ });
1487
+ }
1488
+ return this.#client.datasets.get(this.id);
1489
+ }
1490
+ };
1491
+ /** `client.datasets`. */
1492
+ var Datasets = class {
1493
+ #client;
1494
+ /** @internal */
1495
+ constructor(client) {
1496
+ this.#client = client;
1497
+ }
1498
+ /** Create a dataset (version 0, no items). Sent once: a retry could create a second one. */
1499
+ async create(name, options = {}) {
1500
+ const body = { name };
1501
+ if (options.description !== void 0) body.description = options.description;
1502
+ if (options.inputSchema !== void 0) body.input_schema = options.inputSchema;
1503
+ if (options.expectedSchema !== void 0) body.expected_schema = options.expectedSchema;
1504
+ const wire = await this.#client.request("POST", "/datasets", "/datasets", {
1505
+ body,
1506
+ retry: false
1507
+ });
1508
+ return new Dataset({
1509
+ id: wire.id,
1510
+ name: wire.name,
1511
+ description: wire.description,
1512
+ version: 0,
1513
+ items: []
1514
+ }, this.#client);
1515
+ }
1516
+ /** A dataset with the items of `options.version` (default: the current version). */
1517
+ async get(nameOrId, options = {}) {
1518
+ const wire = await this.#client.request("GET", "/datasets/{dataset}", `/datasets/${segment(nameOrId)}`);
1519
+ const version = options.version ?? wire.current_version;
1520
+ const items = await collect((cursor) => this.#client.request("GET", "/datasets/{dataset}/items", `/datasets/${segment(wire.id)}/items`, { query: pageQuery({ version }, cursor) }), itemFromWire);
1521
+ return new Dataset({
1522
+ id: wire.id,
1523
+ name: wire.name,
1524
+ description: wire.description,
1525
+ version,
1526
+ items
1527
+ }, this.#client);
1528
+ }
1529
+ /** Every dataset, without items. */
1530
+ async list() {
1531
+ return collect((cursor) => this.#client.request("GET", "/datasets", "/datasets", { query: pageQuery({}, cursor) }), infoFromWire);
1532
+ }
1533
+ /** Delete a dataset by name or id. */
1534
+ async delete(nameOrId) {
1535
+ await this.#client.request("DELETE", "/datasets/{dataset}", `/datasets/${segment(nameOrId)}`);
1536
+ }
1537
+ };
1538
+ /** Query of one page: the given fields, then `limit`, then `cursor` when there is one. */
1539
+ function pageQuery(fields, cursor) {
1540
+ const query = {
1541
+ ...fields,
1542
+ limit: PAGE_SIZE
1543
+ };
1544
+ if (cursor !== void 0) query.cursor = cursor;
1545
+ return query;
1546
+ }
1547
+ /** Fetch pages until `next_cursor` is null, mapping every item in order. */
1548
+ async function collect(fetchPage, map) {
1549
+ const out = [];
1550
+ let cursor;
1551
+ for (;;) {
1552
+ const page = await fetchPage(cursor);
1553
+ out.push(...page.data.map(map));
1554
+ if (page.next_cursor === null) return out;
1555
+ cursor = page.next_cursor;
1556
+ }
1557
+ }
1558
+ function infoFromWire(wire) {
1559
+ return {
1560
+ id: wire.id,
1561
+ name: wire.name,
1562
+ description: wire.description,
1563
+ currentVersion: wire.current_version,
1564
+ itemCount: wire.item_count
1565
+ };
1566
+ }
1567
+ /** A wire item as a `DatasetItem`. Internal, shared with `evaluate`. */
1568
+ function itemFromWire(wire) {
1569
+ return {
1570
+ id: wire.id,
1571
+ input: wire.input,
1572
+ expectedOutput: wire.expected_output ?? void 0,
1573
+ metadata: wire.metadata ?? {},
1574
+ version: wire.version,
1575
+ sourceTraceId: wire.source_trace_id,
1576
+ sourceSpanId: wire.source_span_id
1577
+ };
1578
+ }
1579
+ /** Throws `TypeError` naming the item's index and the problem, never the value. */
1580
+ function checkItem(item, index) {
1581
+ if (typeof item !== "object" || item === null || Array.isArray(item)) throw new TypeError(`items[${String(index)}]: must be an object`);
1582
+ for (const key of Object.keys(item)) if (!ITEM_KEYS.has(key)) throw new TypeError(`items[${String(index)}]: unknown key ${key}`);
1583
+ const record = item;
1584
+ if (!("input" in record) || record.input === void 0) throw new TypeError(`items[${String(index)}].input: required`);
1585
+ const metadata = record.metadata;
1586
+ if (metadata !== void 0 && (typeof metadata !== "object" || metadata === null || Array.isArray(metadata))) throw new TypeError(`items[${String(index)}].metadata: must be an object`);
1587
+ }
1588
+ function itemToWire(item) {
1589
+ const wire = { input: toJsonable(item.input) };
1590
+ if (item.expectedOutput !== void 0) wire.expected_output = toJsonable(item.expectedOutput);
1591
+ if (item.metadata !== void 0) wire.metadata = toJsonable(item.metadata);
1592
+ return wire;
1593
+ }
1594
+ // src/annotation-queues.ts
1595
+ /** Targets per `POST /annotation-queues/{queue}/items` request. */
1596
+ const ADD_BATCH_SIZE = 1e3;
1597
+ const TARGET_KINDS = [
1598
+ "traceIds",
1599
+ "spans",
1600
+ "sessionIds"
1601
+ ];
1602
+ const TARGET_NAMES = /* @__PURE__ */ new Set([
1603
+ "trace",
1604
+ "span",
1605
+ "session"
1606
+ ]);
1607
+ const KIND_MESSAGE = "give exactly one of traceIds, spans or sessionIds";
1608
+ /** `client.annotationQueues`. */
1609
+ var AnnotationQueues = class {
1610
+ #client;
1611
+ /** @internal */
1612
+ constructor(client) {
1613
+ this.#client = client;
1614
+ }
1615
+ /** Every queue of the key's project. */
1616
+ async list() {
1617
+ return collect((cursor) => this.#client.request("GET", "/annotation-queues", "/annotation-queues", { query: pageQuery({}, cursor) }), queueFromWire);
1618
+ }
1619
+ /** One queue by id. */
1620
+ async get(queueId) {
1621
+ return queueFromWire(await this.#client.request("GET", "/annotation-queues/{queue}", `/annotation-queues/${segment(queueId)}`));
1622
+ }
1623
+ /** Create a queue. Sent once: a retry could create a second one. */
1624
+ async create(name, options) {
1625
+ if (!TARGET_NAMES.has(options.target)) throw new TypeError("target must be trace, span or session");
1626
+ if (options.definitionIds.length === 0) throw new TypeError("definitionIds: give at least one score definition");
1627
+ const body = {
1628
+ name,
1629
+ target: options.target,
1630
+ definition_ids: [...options.definitionIds]
1631
+ };
1632
+ if (options.description !== void 0) body.description = options.description;
1633
+ if (options.instructions !== void 0) body.instructions = options.instructions;
1634
+ return queueFromWire(await this.#client.request("POST", "/annotation-queues", "/annotation-queues", {
1635
+ body,
1636
+ retry: false
1637
+ }));
1638
+ }
1639
+ /**
1640
+ * Change a queue. `version` is the version the caller read; the server
1641
+ * answers `409` when it is stale. `""` clears a text field.
1642
+ */
1643
+ async update(queueId, options) {
1644
+ const body = { version: options.version };
1645
+ if (options.name !== void 0) body.name = options.name;
1646
+ if (options.description !== void 0) body.description = options.description;
1647
+ if (options.instructions !== void 0) body.instructions = options.instructions;
1648
+ if (options.definitionIds !== void 0) body.definition_ids = [...options.definitionIds];
1649
+ return queueFromWire(await this.#client.request("PATCH", "/annotation-queues/{queue}", `/annotation-queues/${segment(queueId)}`, {
1650
+ body,
1651
+ retry: false
1652
+ }));
1653
+ }
1654
+ /** Delete a queue and its items. */
1655
+ async delete(queueId) {
1656
+ await this.#client.request("DELETE", "/annotation-queues/{queue}", `/annotation-queues/${segment(queueId)}`);
1657
+ }
1658
+ /**
1659
+ * Add traces, spans or sessions to a queue, in batches of 1,000 (D-AQ-8).
1660
+ * Rejects with `TypeError` before any request when the targets are malformed.
1661
+ * `skipped` indexes are positions in the list the caller passed. An empty
1662
+ * list resolves to zero counts without a request.
1663
+ */
1664
+ async addItems(queueId, targets) {
1665
+ const items = targetsToWire(targets);
1666
+ let added = 0;
1667
+ let existing = 0;
1668
+ const skipped = [];
1669
+ for (let start = 0; start < items.length; start += ADD_BATCH_SIZE) {
1670
+ const answer = await this.#client.request("POST", "/annotation-queues/{queue}/items", `/annotation-queues/${segment(queueId)}/items`, {
1671
+ body: { items: items.slice(start, start + ADD_BATCH_SIZE) },
1672
+ retry: true
1673
+ });
1674
+ added += answer.added;
1675
+ existing += answer.existing;
1676
+ for (const entry of answer.skipped) skipped.push({
1677
+ index: entry.index + start,
1678
+ message: entry.message
1679
+ });
1680
+ }
1681
+ return {
1682
+ added,
1683
+ existing,
1684
+ skipped
1685
+ };
1686
+ }
1687
+ /** The items of a queue, optionally only one status. Every page is read. */
1688
+ async items(queueId, options = {}) {
1689
+ const status = options.status;
1690
+ return collect((cursor) => this.#client.request("GET", "/annotation-queues/{queue}/items", `/annotation-queues/${segment(queueId)}/items`, { query: {
1691
+ ...status === void 0 ? {} : { status },
1692
+ ...pageQuery({}, cursor)
1693
+ } }), queueItemFromWire);
1694
+ }
1695
+ };
1696
+ function queueFromWire(wire) {
1697
+ return {
1698
+ id: wire.id,
1699
+ name: wire.name,
1700
+ description: wire.description,
1701
+ instructions: wire.instructions,
1702
+ target: wire.target,
1703
+ definitionIds: wire.definition_ids,
1704
+ version: wire.version,
1705
+ createdBy: wire.created_by,
1706
+ createdAt: wire.created_at,
1707
+ updatedAt: wire.updated_at,
1708
+ counts: {
1709
+ pending: wire.counts.pending,
1710
+ completed: wire.counts.completed,
1711
+ skipped: wire.counts.skipped
1712
+ }
1713
+ };
1714
+ }
1715
+ function queueItemFromWire(wire) {
1716
+ return {
1717
+ id: wire.id,
1718
+ queueId: wire.queue_id,
1719
+ traceId: wire.trace_id,
1720
+ spanId: wire.span_id,
1721
+ sessionId: wire.session_id,
1722
+ targetTime: wire.target_time,
1723
+ status: wire.status,
1724
+ skipReason: wire.skip_reason,
1725
+ leasedByUserId: wire.leased_by_user_id,
1726
+ leaseExpiresAt: wire.lease_expires_at,
1727
+ doneByUserId: wire.done_by_user_id,
1728
+ doneAt: wire.done_at,
1729
+ addedBy: wire.added_by,
1730
+ addedById: wire.added_by_id,
1731
+ createdAt: wire.created_at
1732
+ };
1733
+ }
1734
+ /**
1735
+ * The wire targets of `addItems`. Throws `TypeError` naming the problem, never
1736
+ * a value, before any request is sent.
1737
+ */
1738
+ function targetsToWire(targets) {
1739
+ if (typeof targets !== "object" || targets === null || Array.isArray(targets)) throw new TypeError(KIND_MESSAGE);
1740
+ const record = targets;
1741
+ for (const key of Object.keys(record)) if (!TARGET_KINDS.includes(key)) throw new TypeError(`unknown key ${key}`);
1742
+ const given = TARGET_KINDS.filter((key) => record[key] !== void 0);
1743
+ const only = given[0];
1744
+ if (given.length !== 1 || only === void 0) throw new TypeError(KIND_MESSAGE);
1745
+ switch (only) {
1746
+ case "traceIds": return idList(record.traceIds, "traceIds").map((id) => ({ trace_id: id }));
1747
+ case "sessionIds": return idList(record.sessionIds, "sessionIds").map((id) => ({ session_id: id }));
1748
+ case "spans": return spanList(record.spans);
1749
+ }
1750
+ }
1751
+ /** The ids of a `traceIds` or `sessionIds` list; a bare string is refused. */
1752
+ function idList(value, name) {
1753
+ if (typeof value === "string") throw new TypeError(`${name} must be an array of ids, not a string`);
1754
+ if (!Array.isArray(value)) throw new TypeError(`${name} must be an array of ids`);
1755
+ return value.map((id, index) => {
1756
+ if (typeof id !== "string") throw new TypeError(`${name}[${String(index)}]: must be a string`);
1757
+ return id;
1758
+ });
1759
+ }
1760
+ /** The wire items of a `spans` list: each entry a `[traceId, spanId]` pair. */
1761
+ function spanList(value) {
1762
+ if (!Array.isArray(value)) throw new TypeError("spans must be an array of [traceId, spanId] pairs");
1763
+ return value.map((pair, index) => spanWire(pair, index));
1764
+ }
1765
+ function spanWire(pair, index) {
1766
+ if (Array.isArray(pair) && pair.length === 2) {
1767
+ const [traceId, spanId] = pair;
1768
+ if (typeof traceId === "string" && typeof spanId === "string") return {
1769
+ trace_id: traceId,
1770
+ span_id: spanId
1771
+ };
1772
+ }
1773
+ throw new TypeError(`spans[${String(index)}]: must be a [traceId, spanId] pair of strings`);
1774
+ }
1775
+ // src/client.ts
1776
+ /**
1777
+ * REST client for datasets, experiments and annotation queues (spec 10).
1778
+ *
1779
+ * `Client` raises on failure: `ConfigError` for a missing key or runtime, and
1780
+ * `ApiError` for an error answer after retries (D-J-16). Only idempotent calls
1781
+ * are retried; the callers pass `retry` for the rest.
1782
+ */
1783
+ const REQUEST_TIMEOUT_MILLIS = 3e4;
1784
+ /** An error answer from the cetra API, or a network failure (`status` 0). */
1785
+ var ApiError = class extends Error {
1786
+ status;
1787
+ code;
1788
+ detail;
1789
+ errors;
1790
+ constructor(init) {
1791
+ let message = `${init.method} ${init.template}: ${String(init.status)}`;
1792
+ if (init.code !== void 0) message += ` ${init.code}`;
1793
+ if (init.detail !== void 0) message += `: ${init.detail}`;
1794
+ super(message);
1795
+ this.name = "ApiError";
1796
+ this.status = init.status;
1797
+ this.code = init.code;
1798
+ this.detail = init.detail;
1799
+ this.errors = init.errors;
1800
+ }
1801
+ };
1802
+ var Client = class {
1803
+ datasets;
1804
+ prompts;
1805
+ annotationQueues;
1806
+ #apiKey;
1807
+ #baseUrl;
1808
+ #fetch;
1809
+ #sleep;
1810
+ /** Resolves the key and base URL as `init()` does; throws `ConfigError` without a key. */
1811
+ constructor(options = {}) {
1812
+ const config = resolveConfig({
1813
+ apiKey: options.apiKey,
1814
+ baseUrl: options.baseUrl,
1815
+ enabled: true
1816
+ });
1817
+ if (!config.enabled || config.apiKey === void 0) throw new ConfigError("apiKey", "required");
1818
+ const fetcher = options.fetch ?? defaultFetch$1();
1819
+ if (fetcher === void 0) throw new ConfigError("fetch", "not available in this runtime");
1820
+ this.#apiKey = config.apiKey;
1821
+ this.#baseUrl = config.baseUrl;
1822
+ this.#fetch = fetcher;
1823
+ this.#sleep = options.sleep ?? defaultSleep;
1824
+ this.datasets = new Datasets(this);
1825
+ this.prompts = new Prompts(this);
1826
+ this.annotationQueues = new AnnotationQueues(this);
1827
+ }
1828
+ /**
1829
+ * One API call with the retry policy of D-J-16. `template` names the route
1830
+ * in errors (`/datasets/{dataset}/items`); `path` is the filled path with
1831
+ * its segments already encoded. Resolves to the decoded JSON, or
1832
+ * `undefined` for `204`.
1833
+ * @internal
1834
+ */
1835
+ async request(method, template, path, options = {}) {
1836
+ const url = this.#url(path, options.query);
1837
+ const attempts = options.retry ?? (method === "GET" || method === "DELETE") ? 4 : 1;
1838
+ const headers = { Authorization: `Bearer ${this.#apiKey}` };
1839
+ let body;
1840
+ if (options.body !== void 0) {
1841
+ headers["Content-Type"] = "application/json";
1842
+ body = JSON.stringify(options.body);
1843
+ }
1844
+ for (let attempt = 0;; attempt++) {
1845
+ const last = attempt + 1 >= attempts;
1846
+ let status;
1847
+ let text;
1848
+ let retryAfter;
1849
+ let contentType;
1850
+ try {
1851
+ const response = await this.#fetch(url, {
1852
+ method,
1853
+ headers,
1854
+ body,
1855
+ signal: timeoutSignal(REQUEST_TIMEOUT_MILLIS)
1856
+ });
1857
+ status = response.status;
1858
+ retryAfter = response.headers.get("Retry-After");
1859
+ contentType = response.headers.get("Content-Type");
1860
+ text = await response.text();
1861
+ } catch (error) {
1862
+ if (!last) {
1863
+ await this.#sleep(waitMillis(null, attempt));
1864
+ continue;
1865
+ }
1866
+ throw new ApiError({
1867
+ method,
1868
+ template,
1869
+ status: 0,
1870
+ code: "network",
1871
+ detail: errorName$6(error),
1872
+ errors: []
1873
+ });
1874
+ }
1875
+ if (status >= 200 && status < 300) return decodeBody(text, method, template, status);
1876
+ if ((status === 429 || status >= 500) && !last) {
1877
+ await this.#sleep(waitMillis(retryAfter, attempt));
1878
+ continue;
1879
+ }
1880
+ const problem = parseProblem(text, contentType);
1881
+ throw new ApiError({
1882
+ method,
1883
+ template,
1884
+ status,
1885
+ code: problem.code,
1886
+ detail: problem.detail,
1887
+ errors: problem.errors
1888
+ });
1889
+ }
1890
+ }
1891
+ #url(path, query) {
1892
+ const base = `${this.#baseUrl}/api/v1/projects/current${path}`;
1893
+ if (query === void 0) return base;
1894
+ const pairs = Object.entries(query).map(([key, value]) => `${encodeURIComponent(key)}=${encodeURIComponent(String(value))}`);
1895
+ return pairs.length === 0 ? base : `${base}?${pairs.join("&")}`;
1896
+ }
1897
+ };
1898
+ /** A path segment: an id, or a name with no safe characters left unencoded. */
1899
+ function segment(value) {
1900
+ return encodeURIComponent(value);
1901
+ }
1902
+ /**
1903
+ * The runtime's `fetch`. It accepts a request without a body, which the
1904
+ * `FetchLike` type of `web.ts` (written for the score queue) does not say.
1905
+ */
1906
+ function defaultFetch$1() {
1907
+ const fetch = getFetch();
1908
+ return fetch === void 0 ? void 0 : fetch;
1909
+ }
1910
+ function decodeBody(text, method, template, status) {
1911
+ if (text === "") return;
1912
+ try {
1913
+ return JSON.parse(text);
1914
+ } catch {
1915
+ throw new ApiError({
1916
+ method,
1917
+ template,
1918
+ status,
1919
+ code: void 0,
1920
+ detail: "response is not JSON",
1921
+ errors: []
1922
+ });
1923
+ }
1924
+ }
1925
+ /** The problem body of an error answer; anything unreadable gives no fields. */
1926
+ function parseProblem(text, contentType) {
1927
+ const empty = {
1928
+ code: void 0,
1929
+ detail: void 0,
1930
+ errors: []
1931
+ };
1932
+ if (contentType === null || !(contentType.includes("application/problem+json") || contentType.includes("application/json"))) return empty;
1933
+ let parsed;
1934
+ try {
1935
+ parsed = JSON.parse(text);
1936
+ } catch {
1937
+ return empty;
1938
+ }
1939
+ if (typeof parsed !== "object" || parsed === null) return empty;
1940
+ const record = parsed;
1941
+ const errors = [];
1942
+ if (Array.isArray(record.errors)) {
1943
+ for (const item of record.errors) if (typeof item === "object" && item !== null) {
1944
+ const { field, message } = item;
1945
+ if (typeof field === "string" && typeof message === "string") errors.push({
1946
+ field,
1947
+ message
1948
+ });
1949
+ }
1950
+ }
1951
+ return {
1952
+ code: typeof record.code === "string" ? record.code : void 0,
1953
+ detail: typeof record.detail === "string" ? record.detail : void 0,
1954
+ errors
1955
+ };
1956
+ }
1957
+ function errorName$6(error) {
1958
+ return error instanceof Error ? error.name : "Error";
1959
+ }
1960
+ // src/prompts.ts
1961
+ /**
1962
+ * Prompts over REST and the in-process prompt cache (spec 10, D-V-12, D-V-14,
1963
+ * D-V-15).
1964
+ *
1965
+ * `getPrompt` answers from one cache per process, keyed by base URL, name and
1966
+ * label or version. A version never expires; a label is fresh for
1967
+ * `cacheTtlS` seconds, then served stale while one background refresh runs.
1968
+ * A failed fetch falls back to the stale entry, else to the call's fallback,
1969
+ * else raises `PromptNotAvailable`. `client.prompts` is the REST sub-client
1970
+ * for scripts and CI: it is not cached and raises `ApiError`.
1971
+ */
1972
+ const DEFAULT_LABEL = "production";
1973
+ const DEFAULT_TTL_S = 60;
1974
+ const FETCH_TIMEOUT_MILLIS = 5e3;
1975
+ /** One attempt plus two retries (D-V-14). */
1976
+ const ATTEMPTS = 3;
1977
+ const RETRY_AFTER_MAX_MILLIS = 5e3;
1978
+ const CACHE_LIMIT = 1e3;
1979
+ const WARN_INTERVAL_MILLIS = 6e4;
1980
+ const LIST_PAGE_SIZE = 1e3;
1981
+ /** Checks the arguments of a fetch; a programming error throws `TypeError`. */
1982
+ function target(name, label, version) {
1983
+ if (name === "") throw new TypeError("prompt name is empty");
1984
+ if (label !== void 0 && version !== void 0) throw new TypeError("give a label or a version, not both");
1985
+ if (version !== void 0) {
1986
+ if (!Number.isInteger(version) || version < 1) throw new TypeError("prompt version must be an integer of at least 1");
1987
+ return {
1988
+ label: void 0,
1989
+ version
1990
+ };
1991
+ }
1992
+ return {
1993
+ label: label || DEFAULT_LABEL,
1994
+ version: void 0
1995
+ };
1996
+ }
1997
+ /**
1998
+ * The prompt cache (D-V-14): an LRU of at most 1 000 entries, one background
1999
+ * refresh per key, and the fetch with its retries. The seams are for tests;
2000
+ * the defaults are the real clock and the runtime's `fetch`.
2001
+ */
2002
+ var PromptCache = class {
2003
+ #now;
2004
+ #fetch;
2005
+ #sleep;
2006
+ /** Insertion order is the LRU order: the first key is the oldest. */
2007
+ #entries = /* @__PURE__ */ new Map();
2008
+ #refreshing = /* @__PURE__ */ new Map();
2009
+ #warnedAt;
2010
+ constructor(seams = {}) {
2011
+ this.#now = seams.now ?? (() => Date.now());
2012
+ this.#fetch = seams.fetch ?? defaultFetch();
2013
+ this.#sleep = seams.sleep ?? defaultSleep;
2014
+ }
2015
+ now() {
2016
+ return this.#now();
2017
+ }
2018
+ /** The entry for `key`, moved to the newest position. */
2019
+ get(key) {
2020
+ const entry = this.#entries.get(key);
2021
+ if (entry !== void 0) {
2022
+ this.#entries.delete(key);
2023
+ this.#entries.set(key, entry);
2024
+ }
2025
+ return entry;
2026
+ }
2027
+ store(key, entry) {
2028
+ this.#entries.delete(key);
2029
+ this.#entries.set(key, entry);
2030
+ if (this.#entries.size > CACHE_LIMIT) {
2031
+ const oldest = this.#entries.keys().next().value;
2032
+ if (oldest !== void 0) this.#entries.delete(oldest);
2033
+ }
2034
+ }
2035
+ /** Starts `task` unless one is already running for `key`. Never rejects. */
2036
+ refreshLater(key, task) {
2037
+ if (this.#refreshing.has(key)) return;
2038
+ const running = task().catch((error) => {
2039
+ debug(`cetra: prompt refresh failed (${errorName$5(error)})`);
2040
+ }).finally(() => {
2041
+ this.#refreshing.delete(key);
2042
+ });
2043
+ this.#refreshing.set(key, running);
2044
+ }
2045
+ /** Resolves when the background refreshes running now have finished. For tests. */
2046
+ async settle() {
2047
+ await Promise.all([...this.#refreshing.values()]);
2048
+ }
2049
+ /** One warning a minute for the whole cache, naming the prompt and the reason. */
2050
+ warnFailure(name, reason) {
2051
+ const now = this.#now();
2052
+ if (this.#warnedAt === void 0 || now - this.#warnedAt >= WARN_INTERVAL_MILLIS) {
2053
+ this.#warnedAt = now;
2054
+ warn(`cetra: prompt ${name} fetch failed (${reason})`);
2055
+ }
2056
+ }
2057
+ /**
2058
+ * GET the resolve route with up to three attempts: network errors, 429 and
2059
+ * 5xx are retried, with `Retry-After` (digits only, at most 5 s) or 0.5 s,
2060
+ * then 1 s. A 404 is "not found"; any other failure is `status <n>`.
2061
+ */
2062
+ async fetchResolve(config, name, t, etag) {
2063
+ const fetcher = this.#fetch;
2064
+ if (fetcher === void 0) return {
2065
+ kind: "failed",
2066
+ reason: "network"
2067
+ };
2068
+ const selector = t.version !== void 0 ? `version=${t.version}` : `label=${encodeURIComponent(t.label)}`;
2069
+ const url = `${config.baseUrl}/api/v1/projects/current/prompts/${segment(name)}/resolve?${selector}`;
2070
+ const headers = { Authorization: `Bearer ${config.apiKey ?? ""}` };
2071
+ if (etag !== void 0) headers["If-None-Match"] = etag;
2072
+ for (let attempt = 0;; attempt += 1) {
2073
+ const last = attempt + 1 >= ATTEMPTS;
2074
+ let status;
2075
+ let retryAfter;
2076
+ let etagHeader;
2077
+ let text = "";
2078
+ try {
2079
+ const response = await fetcher(url, {
2080
+ method: "GET",
2081
+ headers,
2082
+ signal: timeoutSignal(FETCH_TIMEOUT_MILLIS)
2083
+ });
2084
+ status = response.status;
2085
+ retryAfter = response.headers.get("Retry-After");
2086
+ etagHeader = response.headers.get("ETag");
2087
+ if (status === 200) text = await response.text();
2088
+ } catch {
2089
+ if (!last) {
2090
+ await this.#sleep(retryWaitMillis(null, attempt));
2091
+ continue;
2092
+ }
2093
+ return {
2094
+ kind: "failed",
2095
+ reason: "network"
2096
+ };
2097
+ }
2098
+ if (status === 200) {
2099
+ let body;
2100
+ try {
2101
+ body = JSON.parse(text);
2102
+ } catch {
2103
+ return {
2104
+ kind: "failed",
2105
+ reason: "invalid response"
2106
+ };
2107
+ }
2108
+ const prompt = parsePrompt(body);
2109
+ if (prompt === void 0) return {
2110
+ kind: "failed",
2111
+ reason: "invalid response"
2112
+ };
2113
+ return {
2114
+ kind: "fetched",
2115
+ prompt,
2116
+ etag: etagHeader ?? void 0
2117
+ };
2118
+ }
2119
+ if (status === 304 && etag !== void 0) return { kind: "not_modified" };
2120
+ if ((status === 429 || status >= 500) && !last) {
2121
+ await this.#sleep(retryWaitMillis(retryAfter, attempt));
2122
+ continue;
2123
+ }
2124
+ return {
2125
+ kind: "failed",
2126
+ reason: status === 404 ? "not found" : `status ${String(status)}`
2127
+ };
2128
+ }
2129
+ }
2130
+ };
2131
+ /** `Retry-After` seconds (digits only, at most 5 s), else 0.5 s after the first attempt and 1 s after the second. */
2132
+ function retryWaitMillis(retryAfter, attempt) {
2133
+ const header = retryAfter?.trim();
2134
+ if (header !== void 0 && NON_NEGATIVE_INTEGER.test(header)) return Math.min(Number(header) * 1e3, RETRY_AFTER_MAX_MILLIS);
2135
+ return attempt === 0 ? 500 : 1e3;
2136
+ }
2137
+ /** The one process-wide cache, created on first use. */
2138
+ let cache;
2139
+ function promptCache() {
2140
+ if (cache === void 0) cache = new PromptCache();
2141
+ return cache;
2142
+ }
2143
+ /**
2144
+ * The prompt `name` at its label (default `production`) or version. Answers
2145
+ * from the cache when it can (D-V-14); throws `TypeError` for bad arguments
2146
+ * and `PromptNotAvailable` when nothing can answer and there is no fallback.
2147
+ * Before `init()`, or with the SDK disabled, it behaves like a failed fetch.
2148
+ */
2149
+ async function getPrompt(name, options = {}) {
2150
+ const t = target(name, options.label, options.version);
2151
+ const ttl = options.cacheTtlS ?? DEFAULT_TTL_S;
2152
+ if (typeof ttl !== "number" || !Number.isFinite(ttl) || ttl < 0) throw new TypeError("cacheTtlS must be a finite number of at least 0");
2153
+ const config = currentRuntime()?.config;
2154
+ if (config === void 0 || config.apiKey === void 0) return unavailable(name, options.fallback, "sdk disabled");
2155
+ const store = promptCache();
2156
+ const key = JSON.stringify([
2157
+ config.baseUrl,
2158
+ name,
2159
+ t.version === void 0 ? "label" : "version",
2160
+ t.version ?? t.label
2161
+ ]);
2162
+ const entry = store.get(key);
2163
+ const fresh = entry !== void 0 && (t.version !== void 0 || ttl > 0 && store.now() - entry.fetchedAt < ttl * 1e3);
2164
+ if (entry !== void 0 && fresh) return entry.prompt;
2165
+ if (entry !== void 0 && ttl > 0) {
2166
+ store.refreshLater(key, () => revalidate(store, key, config, name, t, entry));
2167
+ return entry.prompt;
2168
+ }
2169
+ const outcome = await store.fetchResolve(config, name, t, void 0);
2170
+ if (outcome.kind === "fetched") {
2171
+ if (ttl > 0) store.store(key, {
2172
+ prompt: outcome.prompt,
2173
+ etag: outcome.etag,
2174
+ fetchedAt: store.now()
2175
+ });
2176
+ return outcome.prompt;
2177
+ }
2178
+ const reason = outcome.kind === "failed" ? outcome.reason : "invalid response";
2179
+ if (entry !== void 0) {
2180
+ store.warnFailure(name, reason);
2181
+ return entry.prompt;
2182
+ }
2183
+ return unavailable(name, options.fallback, reason);
2184
+ }
2185
+ /** The background refresh of a stale label entry (D-V-14). */
2186
+ async function revalidate(store, key, config, name, t, entry) {
2187
+ const outcome = await store.fetchResolve(config, name, t, entry.etag);
2188
+ if (outcome.kind === "fetched") store.store(key, {
2189
+ prompt: outcome.prompt,
2190
+ etag: outcome.etag,
2191
+ fetchedAt: store.now()
2192
+ });
2193
+ else if (outcome.kind === "not_modified") store.store(key, {
2194
+ ...entry,
2195
+ fetchedAt: store.now()
2196
+ });
2197
+ else {
2198
+ store.store(key, {
2199
+ ...entry,
2200
+ fetchedAt: store.now()
2201
+ });
2202
+ store.warnFailure(name, outcome.reason);
2203
+ }
2204
+ }
2205
+ /** The fallback as a prompt, or `PromptNotAvailable` when there is none. */
2206
+ function unavailable(name, fallback, reason) {
2207
+ if (fallback === void 0) throw new PromptNotAvailable(name, reason);
2208
+ debug(`cetra: prompt ${name} not available (${reason}); using the fallback`);
2209
+ try {
2210
+ return new Prompt({
2211
+ name,
2212
+ version: void 0,
2213
+ config: {},
2214
+ labels: [],
2215
+ isFallback: true,
2216
+ template: fallback
2217
+ });
2218
+ } catch (error) {
2219
+ if (error instanceof PromptCompileError) throw new PromptCompileError(error.kind, {
2220
+ variable: error.variable,
2221
+ reason: error.reason,
2222
+ line: error.line,
2223
+ column: error.column,
2224
+ prompt: name
2225
+ });
2226
+ throw error;
2227
+ }
2228
+ }
2229
+ /**
2230
+ * A prompt from a resolve or create answer, or `undefined` when the body does
2231
+ * not have the shape of a prompt (or its template does not render).
2232
+ */
2233
+ function parsePrompt(body) {
2234
+ if (!isRecord(body)) return;
2235
+ const { name, type, version, template, config, labels } = body;
2236
+ if (typeof name !== "string" || name === "" || typeof version !== "number" || !Number.isInteger(version) || version < 1 || !isRecord(config) || !isStringArray(labels)) return;
2237
+ let shape;
2238
+ if (type === "text" && typeof template === "string") shape = template;
2239
+ else if (type === "chat" && Array.isArray(template) && template.every(isFlatEntry)) shape = template;
2240
+ else return;
2241
+ try {
2242
+ return new Prompt({
2243
+ name,
2244
+ version,
2245
+ config,
2246
+ labels,
2247
+ isFallback: false,
2248
+ template: shape
2249
+ });
2250
+ } catch (error) {
2251
+ if (error instanceof PromptCompileError) return;
2252
+ throw error;
2253
+ }
2254
+ }
2255
+ /** `client.prompts`: the REST operations on prompts (spec 10, D-V-12). */
2256
+ var Prompts = class {
2257
+ #client;
2258
+ /** @internal */
2259
+ constructor(client) {
2260
+ this.#client = client;
2261
+ }
2262
+ /** The prompt at its label (default `production`) or version. Not cached. */
2263
+ async get(name, options = {}) {
2264
+ const t = target(name, options.label, options.version);
2265
+ return promptFrom("GET", "/prompts/{prompt}/resolve", await this.#client.request("GET", "/prompts/{prompt}/resolve", `/prompts/${segment(name)}/resolve`, { query: t.version !== void 0 ? { version: t.version } : { label: t.label } }));
2266
+ }
2267
+ /** The names of every prompt in the project. */
2268
+ async list() {
2269
+ const names = [];
2270
+ let cursor;
2271
+ for (;;) {
2272
+ const query = { limit: LIST_PAGE_SIZE };
2273
+ if (cursor !== void 0) query.cursor = cursor;
2274
+ const page = await this.#client.request("GET", "/prompts", "/prompts", { query });
2275
+ if (!isRecord(page) || !Array.isArray(page.data)) throw invalidResponse("GET", "/prompts");
2276
+ for (const item of page.data) {
2277
+ if (!isRecord(item) || typeof item.name !== "string") throw invalidResponse("GET", "/prompts");
2278
+ names.push(item.name);
2279
+ }
2280
+ if (page.next_cursor === null || page.next_cursor === void 0) return names;
2281
+ if (typeof page.next_cursor !== "string") throw invalidResponse("GET", "/prompts");
2282
+ cursor = page.next_cursor;
2283
+ }
2284
+ }
2285
+ /** Create a prompt with its version 1. Sent once: a retry could create a second one. */
2286
+ async create(input) {
2287
+ if (input.name === "") throw new TypeError("prompt name is empty");
2288
+ const body = {
2289
+ name: input.name,
2290
+ type: input.type,
2291
+ ...versionFields(input)
2292
+ };
2293
+ if (input.description !== void 0) body.description = input.description;
2294
+ if (input.tags !== void 0) body.tags = [...input.tags];
2295
+ return promptFrom("POST", "/prompts", await this.#client.request("POST", "/prompts", "/prompts", {
2296
+ body,
2297
+ retry: false
2298
+ }));
2299
+ }
2300
+ /** Add a version to a prompt. Sent once, for the same reason as `create`. */
2301
+ async createVersion(name, input) {
2302
+ if (name === "") throw new TypeError("prompt name is empty");
2303
+ const route = "/prompts/{prompt}/versions";
2304
+ return promptFrom("POST", route, await this.#client.request("POST", route, `/prompts/${segment(name)}/versions`, {
2305
+ body: versionFields(input),
2306
+ retry: false
2307
+ }));
2308
+ }
2309
+ /** Move `label` to `version`. Sent once. */
2310
+ async setLabel(name, label, version) {
2311
+ if (name === "" || label === "") throw new TypeError("prompt name and label must not be empty");
2312
+ await this.#client.request("PUT", "/prompts/{prompt}/labels/{label}", `/prompts/${segment(name)}/labels/${segment(label)}`, {
2313
+ body: { version },
2314
+ retry: false
2315
+ });
2316
+ }
2317
+ };
2318
+ /** The request fields of a version, with the optional ones left out when not given. */
2319
+ function versionFields(input) {
2320
+ const body = { template: input.template };
2321
+ if (input.config !== void 0) body.config = input.config;
2322
+ if (input.labels !== void 0) body.labels = [...input.labels];
2323
+ if (input.commitMessage !== void 0) body.commit_message = input.commitMessage;
2324
+ return body;
2325
+ }
2326
+ function promptFrom(method, template, body) {
2327
+ const prompt = parsePrompt(body);
2328
+ if (prompt === void 0) throw invalidResponse(method, template);
2329
+ return prompt;
2330
+ }
2331
+ function invalidResponse(method, template) {
2332
+ return new ApiError({
2333
+ method,
2334
+ template,
2335
+ status: 200,
2336
+ code: "invalid_response",
2337
+ detail: "invalid response",
2338
+ errors: []
2339
+ });
2340
+ }
2341
+ /**
2342
+ * A chat entry as the wire has it: a message with exactly string `role` and
2343
+ * `content`, or a placeholder with exactly `type: "placeholder"` and a string
2344
+ * `name`. Anything else (a non-string value, an extra key) is not a prompt.
2345
+ */
2346
+ function isFlatEntry(entry) {
2347
+ if (!isRecord(entry)) return false;
2348
+ const keys = Object.keys(entry).sort().join(",");
2349
+ if (entry.type === "placeholder") return keys === "name,type" && typeof entry.name === "string";
2350
+ return keys === "content,role" && typeof entry.role === "string" && typeof entry.content === "string";
2351
+ }
2352
+ function isRecord(value) {
2353
+ return typeof value === "object" && value !== null && !Array.isArray(value);
2354
+ }
2355
+ function isStringArray(value) {
2356
+ return Array.isArray(value) && value.every((item) => typeof item === "string");
2357
+ }
2358
+ /** The runtime's `fetch` as the REST client types it; the same as `client.ts`' default. */
2359
+ function defaultFetch() {
2360
+ const fetch = getFetch();
2361
+ return fetch === void 0 ? void 0 : fetch;
2362
+ }
2363
+ function errorName$5(error) {
2364
+ return error instanceof Error ? error.name : typeof error;
2365
+ }
2366
+ // src/uuid.ts
2367
+ /**
2368
+ * UUIDv7 (RFC 9562 §5.7).
2369
+ *
2370
+ * 48 big-endian bits of Unix milliseconds from `Date.now()`, version `0b0111`,
2371
+ * 12 random bits (`rand_a`), variant `0b10`, 62 random bits (`rand_b`); every
2372
+ * random bit comes from `crypto.getRandomValues` of the running runtime.
2373
+ */
2374
+ /**
2375
+ * A new UUIDv7 as a lowercase string. Throws when the runtime has no
2376
+ * `crypto.getRandomValues`; `score()` checks for that case first and warns
2377
+ * once instead (§ Score request).
2378
+ */
2379
+ function uuid7() {
2380
+ const { crypto } = runtimeGlobals();
2381
+ if (crypto === void 0) throw new Error("crypto is not available");
2382
+ const bytes = crypto.getRandomValues(/* @__PURE__ */ new Uint8Array(16));
2383
+ const ms = Date.now();
2384
+ bytes[0] = Math.floor(ms / 2 ** 40) & 255;
2385
+ bytes[1] = Math.floor(ms / 2 ** 32) & 255;
2386
+ bytes[2] = Math.floor(ms / 2 ** 24) & 255;
2387
+ bytes[3] = Math.floor(ms / 2 ** 16) & 255;
2388
+ bytes[4] = Math.floor(ms / 256) & 255;
2389
+ bytes[5] = ms & 255;
2390
+ bytes[6] = (bytes[6] ?? 0) & 15 | 112;
2391
+ bytes[8] = (bytes[8] ?? 0) & 63 | 128;
2392
+ const hex = Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join("");
2393
+ return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
2394
+ }
2395
+ // src/scores.ts
2396
+ /**
2397
+ * Scores over REST with a background queue (D-F-1, D-F-2, § Score request).
2398
+ *
2399
+ * `score()` validates its input (one warning per rejected call, values never
2400
+ * logged), mints a UUIDv7 unless `scoreId` is given, and queues the
2401
+ * snake_case body; it never throws. The `ScoreQueue` owned by the runtime
2402
+ * buffers up to 10 000 items and posts batches of up to 1000 to
2403
+ * `<baseUrl>/api/v1/scores` every second, retrying 429/5xx and network
2404
+ * batches up to 3 more times before dropping them with one warning.
2405
+ */
2406
+ const TRACE_ID = /^[0-9a-f]{32}$/;
2407
+ const SPAN_ID = /^[0-9a-f]{16}$/;
2408
+ const SCORE_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
2409
+ const MAX_BUFFER = 1e4;
2410
+ const BATCH_SIZE = 1e3;
2411
+ const TICK_MILLIS = 1e3;
2412
+ const ATTEMPT_TIMEOUT_MILLIS = 1e4;
2413
+ const DROP_WARN_INTERVAL_MILLIS = 6e4;
2414
+ /**
2415
+ * Queue one experiment score (D-J-12): a `score()` item plus the experiment
2416
+ * and dataset item ids. Returns its id, or `undefined` when nothing was queued
2417
+ * (invalid input, with one warning, or a full buffer). Internal.
2418
+ */
2419
+ function queueExperimentScore(runtime, options) {
2420
+ const failure = invalidReason(options);
2421
+ if (failure !== void 0) {
2422
+ warn(`cetra: score not queued: ${failure}`);
2423
+ return;
2424
+ }
2425
+ const scoreId = mintScoreId();
2426
+ if (scoreId === void 0) return;
2427
+ const body = {
2428
+ ...buildBody(options, scoreId),
2429
+ experiment_id: options.experimentId,
2430
+ dataset_item_id: options.datasetItemId
2431
+ };
2432
+ return runtime.scores.put(body) ? scoreId : void 0;
2433
+ }
2434
+ /**
2435
+ * Queue one score and return its id, or `undefined` when nothing was queued:
2436
+ * before `init()`, after `shutdown()`, without `crypto`, on invalid input
2437
+ * (one warning), or when the buffer is full (one warning per minute).
2438
+ */
2439
+ function score(options) {
2440
+ const runtime = currentRuntime();
2441
+ if (runtime === void 0) return;
2442
+ const failure = invalidReason(options);
2443
+ if (failure !== void 0) {
2444
+ warn(`cetra: score not queued: ${failure}`);
2445
+ return;
2446
+ }
2447
+ const scoreId = options.scoreId !== void 0 ? options.scoreId.toLowerCase() : mintScoreId();
2448
+ if (scoreId === void 0) return;
2449
+ return runtime.scores.put(buildBody(options, scoreId)) ? scoreId : void 0;
2450
+ }
2451
+ /** § Score request: the first failing reason, in the documented order. */
2452
+ function invalidReason(options) {
2453
+ if (!options.name) return "empty name";
2454
+ if (options.traceId === void 0 && options.spanId === void 0 && options.sessionId === void 0) return "no target";
2455
+ if (options.spanId !== void 0 && options.traceId === void 0) return "span_id without trace_id";
2456
+ if (options.traceId !== void 0 && !TRACE_ID.test(options.traceId)) return "invalid trace_id";
2457
+ if (options.spanId !== void 0 && !SPAN_ID.test(options.spanId)) return "invalid span_id";
2458
+ if (options.sessionId === "") return "invalid session_id";
2459
+ if (options.scoreId !== void 0 && !SCORE_ID.test(options.scoreId)) return "invalid score_id";
2460
+ return valueReason(options.value, options.dataType);
2461
+ }
2462
+ /** Why a value cannot be scored: a non-finite number, or a forced `dataType` that does not match. */
2463
+ function valueReason(value, dataType) {
2464
+ if (typeof value === "number" && !Number.isFinite(value)) return "non-finite value";
2465
+ if (dataTypeMismatch(value, dataType)) return "data_type mismatch";
2466
+ }
2467
+ /** A forced `dataType` must match the value's type; inference needs no match. */
2468
+ function dataTypeMismatch(value, dataType) {
2469
+ switch (dataType) {
2470
+ case "numeric": return typeof value !== "number";
2471
+ case "boolean": return typeof value !== "boolean";
2472
+ case "categorical":
2473
+ case "text": return typeof value !== "string";
2474
+ default: return false;
2475
+ }
2476
+ }
2477
+ function buildBody(options, scoreId) {
2478
+ const target = options.spanId !== void 0 && options.traceId !== void 0 ? {
2479
+ type: "span",
2480
+ trace_id: options.traceId,
2481
+ span_id: options.spanId
2482
+ } : options.traceId !== void 0 ? {
2483
+ type: "trace",
2484
+ trace_id: options.traceId
2485
+ } : {
2486
+ type: "session",
2487
+ session_id: options.sessionId ?? ""
2488
+ };
2489
+ const userId = options.userId ?? currentValues().userId;
2490
+ const body = {
2491
+ score_id: scoreId,
2492
+ target,
2493
+ name: options.name,
2494
+ value: scoreValue(options),
2495
+ source: "sdk"
2496
+ };
2497
+ if (options.reason !== void 0) {
2498
+ const masked = applyMask(options.reason);
2499
+ body.reason = typeof masked === "string" ? masked : serialize(masked)[0];
2500
+ }
2501
+ if (userId !== void 0) body.user_id = userId;
2502
+ const metadata = scoreMetadata(options.metadata);
2503
+ if (metadata !== void 0) body.metadata = metadata;
2504
+ return body;
2505
+ }
2506
+ function scoreValue(options) {
2507
+ const value = options.value;
2508
+ if (typeof value === "boolean") return {
2509
+ data_type: "boolean",
2510
+ value
2511
+ };
2512
+ if (typeof value === "number") return {
2513
+ data_type: "numeric",
2514
+ value
2515
+ };
2516
+ if (options.dataType === "text") return {
2517
+ data_type: "text",
2518
+ value
2519
+ };
2520
+ return {
2521
+ data_type: "categorical",
2522
+ value: { label: value }
2523
+ };
2524
+ }
2525
+ /** Metadata values are masked, then strings kept and the rest serialized. */
2526
+ function scoreMetadata(source) {
2527
+ if (source === void 0) return;
2528
+ const metadata = {};
2529
+ for (const [key, raw] of Object.entries(source)) {
2530
+ const value = applyMask(raw);
2531
+ metadata[key] = typeof value === "string" ? value : serialize(value)[0];
2532
+ }
2533
+ return metadata;
2534
+ }
2535
+ function mintScoreId() {
2536
+ if (runtimeGlobals().crypto === void 0) {
2537
+ warnOnce("no-crypto", "cetra: crypto is not available; scores are not queued");
2538
+ return;
2539
+ }
2540
+ return uuid7();
2541
+ }
2542
+ /**
2543
+ * The background score queue (§ Score request): a lazily started, unref'd
2544
+ * 1 s timer sends one batch of up to 1000 items per tick; `flush()` sends
2545
+ * batches until the buffer is empty.
2546
+ */
2547
+ var ScoreQueue = class {
2548
+ items = [];
2549
+ url;
2550
+ apiKey;
2551
+ fetcher;
2552
+ sleep;
2553
+ now;
2554
+ quota;
2555
+ sending;
2556
+ timer;
2557
+ stopped = false;
2558
+ dropped = 0;
2559
+ droppedWarnedAt = Number.NEGATIVE_INFINITY;
2560
+ constructor(options) {
2561
+ this.url = options.url;
2562
+ this.apiKey = options.apiKey;
2563
+ this.fetcher = options.fetch ?? getFetch();
2564
+ this.sleep = options.sleep ?? defaultSleep;
2565
+ this.now = options.now ?? Date.now;
2566
+ this.quota = options.quota ?? new QuotaState(this.now);
2567
+ }
2568
+ /** True while a 402 pause (D-P-34) drops the score batches. */
2569
+ paused() {
2570
+ return this.quota.paused();
2571
+ }
2572
+ /** Queue one score; `false` when it was dropped (buffer full, or stopped). */
2573
+ put(body) {
2574
+ if (this.stopped) return false;
2575
+ if (this.items.length >= MAX_BUFFER) {
2576
+ this.countDrop();
2577
+ return false;
2578
+ }
2579
+ this.items.push(body);
2580
+ this.ensureTimer();
2581
+ return true;
2582
+ }
2583
+ /** Send batches until the buffer is empty, awaiting each one. */
2584
+ async flush() {
2585
+ for (;;) {
2586
+ const inFlight = this.sending;
2587
+ if (inFlight !== void 0) {
2588
+ await inFlight;
2589
+ continue;
2590
+ }
2591
+ if (this.items.length === 0) return;
2592
+ await this.sendOne();
2593
+ }
2594
+ }
2595
+ /** Flush, then clear the timer and refuse further items. Idempotent. */
2596
+ async shutdown() {
2597
+ if (this.stopped) return;
2598
+ await this.flush();
2599
+ this.stopped = true;
2600
+ this.clearTimer();
2601
+ }
2602
+ /** Count one dropped item; warn at most once a minute, with the count only. */
2603
+ countDrop() {
2604
+ this.dropped += 1;
2605
+ const now = this.now();
2606
+ if (now - this.droppedWarnedAt >= DROP_WARN_INTERVAL_MILLIS) {
2607
+ warn(`cetra: score buffer full; dropped ${String(this.dropped)} scores in the last minute`);
2608
+ this.droppedWarnedAt = now;
2609
+ this.dropped = 0;
2610
+ }
2611
+ }
2612
+ /** Start the 1 s tick timer on the first queued item; unref it when we can. */
2613
+ ensureTimer() {
2614
+ if (this.timer !== void 0) return;
2615
+ const { setInterval } = runtimeGlobals();
2616
+ if (setInterval === void 0) return;
2617
+ const handle = setInterval(() => this.tick(), TICK_MILLIS);
2618
+ this.timer = handle;
2619
+ if (typeof handle.unref === "function") handle.unref();
2620
+ }
2621
+ clearTimer() {
2622
+ const handle = this.timer;
2623
+ if (handle === void 0) return;
2624
+ this.timer = void 0;
2625
+ runtimeGlobals().clearInterval?.(handle);
2626
+ }
2627
+ /** One interval tick: one batch, and only when no send is in flight. */
2628
+ tick() {
2629
+ if (this.stopped || this.sending !== void 0 || this.items.length === 0) return;
2630
+ this.sendOne();
2631
+ }
2632
+ /** Take one batch and send it; it is `this.sending` until it settles. */
2633
+ async sendOne() {
2634
+ const batch = this.items.splice(0, BATCH_SIZE);
2635
+ const send = this.sendBatch(batch);
2636
+ this.sending = send;
2637
+ try {
2638
+ await send;
2639
+ } finally {
2640
+ if (this.sending === send) this.sending = void 0;
2641
+ }
2642
+ }
2643
+ /** § Score request response handling; never rejects. */
2644
+ async sendBatch(batch) {
2645
+ const count = batch.length;
2646
+ try {
2647
+ for (let attempt = 0;; attempt++) {
2648
+ if (this.quota.paused()) return;
2649
+ let status;
2650
+ let retryAfter = null;
2651
+ const fetch = this.fetcher;
2652
+ if (fetch !== void 0) try {
2653
+ const response = await fetch(this.url, {
2654
+ method: "POST",
2655
+ headers: {
2656
+ "Content-Type": "application/json",
2657
+ Authorization: `Bearer ${this.apiKey}`
2658
+ },
2659
+ body: JSON.stringify({ scores: batch }),
2660
+ signal: timeoutSignal(ATTEMPT_TIMEOUT_MILLIS)
2661
+ });
2662
+ if (response.status >= 200 && response.status < 300) return;
2663
+ status = response.status;
2664
+ retryAfter = response.headers.get("Retry-After");
2665
+ } catch {
2666
+ status = void 0;
2667
+ }
2668
+ if (status === 402) {
2669
+ this.quota.on402(retryAfter);
2670
+ return;
2671
+ }
2672
+ if (status !== void 0 && status !== 429 && status < 500) {
2673
+ warn(`cetra: score batch rejected with status ${String(status)}; dropped ${String(count)} scores`);
2674
+ return;
2675
+ }
2676
+ if (attempt + 1 >= 4) {
2677
+ warn(`cetra: score batch failed after retries; dropped ${String(count)} scores`);
2678
+ return;
2679
+ }
2680
+ await this.sleep(waitMillis(retryAfter, attempt));
2681
+ }
2682
+ } catch (error) {
2683
+ debug(`cetra: score batch dropped: ${error instanceof Error ? error.name : typeof error}`);
2684
+ }
2685
+ }
2686
+ };
2687
+ // src/runtime.ts
2688
+ /**
2689
+ * The runtime: our own TracerProvider, its processor and the SDK lifecycle.
2690
+ *
2691
+ * `init()` resolves the config and installs one runtime per process (D-F-15);
2692
+ * by default the provider stays private. `useGlobalProvider` (D-F-4) registers
2693
+ * it as the global one when no app provider is set; OTel JS providers cannot
2694
+ * take processors after construction, so with an app provider we warn once and
2695
+ * stay private. The OTel *context* is always the global one, so instrumentor
2696
+ * spans nest under ours: every `Runtime.create` tries to register an
2697
+ * `AsyncLocalStorageContextManager` and keeps whatever manager was already
2698
+ * registered (D-F-4).
2699
+ */
2700
+ var Runtime = class Runtime {
2701
+ config;
2702
+ provider;
2703
+ ownsProvider;
2704
+ processor;
2705
+ /** The background score queue (§ Score request). */
2706
+ scores;
2707
+ tracer;
2708
+ shutDown = false;
2709
+ constructor(config, provider, processor, scores) {
2710
+ this.config = config;
2711
+ this.provider = provider;
2712
+ this.ownsProvider = true;
2713
+ this.processor = processor;
2714
+ this.scores = scores;
2715
+ this.tracer = provider.getTracer("cetra", VERSION);
2716
+ }
2717
+ static create(config, seams) {
2718
+ const registerGlobal = config.useGlobalProvider && !appProviderRegistered(trace.getTracerProvider());
2719
+ if (config.useGlobalProvider && !registerGlobal) warnOnce("global-provider-exists", "cetra: a global tracer provider is already registered; cetra keeps its own provider. Add spanProcessor() to your provider to send its spans to cetra");
2720
+ const quota = new QuotaState();
2721
+ const innerExporter = seams?.exporter ?? new FetchTraceExporter({
2722
+ url: `${config.baseUrl}/v1/traces`,
2723
+ apiKey: requireApiKey(config),
2724
+ fetch: seams?.fetch,
2725
+ quota
2726
+ });
2727
+ const scores = new ScoreQueue({
2728
+ url: `${config.baseUrl}/api/v1/scores`,
2729
+ apiKey: requireApiKey(config),
2730
+ fetch: seams?.fetch,
2731
+ sleep: seams?.scoreSleep,
2732
+ now: seams?.scoreNow,
2733
+ quota
2734
+ });
2735
+ const processor = new CetraSpanProcessor(config.mask === void 0 && config.captureContent ? innerExporter : new MaskingExporter(innerExporter, {
2736
+ mask: config.mask,
2737
+ captureContent: config.captureContent
2738
+ }), {
2739
+ environment: config.environment,
2740
+ release: config.release,
2741
+ exportFilter: config.exportFilter,
2742
+ defaultFilter: registerGlobal
2743
+ });
2744
+ const provider = new TracerProvider$1({
2745
+ resource: defaultResource().merge(resourceFromAttributes({
2746
+ "telemetry.distro.name": "cetra",
2747
+ "telemetry.distro.version": VERSION,
2748
+ ...config.serviceName ? { "service.name": config.serviceName } : {}
2749
+ })),
2750
+ sampler: new ParentBasedSampler({ root: new TraceIdRatioBasedSampler(config.sampleRate) }),
2751
+ spanLimits: { attributeCountLimit: 1e4 },
2752
+ idGenerator: seams?.idGenerator,
2753
+ spanProcessors: [processor]
2754
+ });
2755
+ if (registerGlobal) trace.setGlobalTracerProvider(provider);
2756
+ registerContextManager();
2757
+ return new Runtime(config, provider, processor, scores);
2758
+ }
2759
+ /** Resolves when pending spans and scores are exported. */
2760
+ async flush() {
2761
+ await Promise.all([this.processor.forceFlush(), this.scores.flush()]);
2762
+ }
2763
+ /** Idempotent; spans and scores after it are dropped. */
2764
+ async shutdown() {
2765
+ if (this.shutDown) return;
2766
+ this.shutDown = true;
2767
+ disableInstrumentations();
2768
+ try {
2769
+ await this.flush();
2770
+ await this.processor.shutdown();
2771
+ await this.scores.shutdown();
2772
+ if (this.ownsProvider) await this.provider.shutdown();
2773
+ } catch (error) {
2774
+ debug(`cetra: shutdown failed: ${errorName$4(error)}`);
2775
+ }
2776
+ }
2777
+ };
2778
+ let activeRuntime;
2779
+ let initCalled = false;
2780
+ let beforeExitRegistered = false;
2781
+ function init(options) {
2782
+ if (initCalled) {
2783
+ warnOnce("init-twice", "cetra: init() was already called; this call is ignored");
2784
+ return;
2785
+ }
2786
+ initCalled = true;
2787
+ const config = resolveConfig(options);
2788
+ if (!config.enabled) return;
2789
+ try {
2790
+ const runtime = Runtime.create(config);
2791
+ installRuntime(runtime);
2792
+ enableInstrumentations(runtime);
2793
+ } catch (error) {
2794
+ debug(`cetra: runtime startup failed: ${errorName$4(error)}`);
2795
+ return;
2796
+ }
2797
+ const process = runtimeGlobals().process;
2798
+ if (!beforeExitRegistered && process?.once !== void 0) {
2799
+ beforeExitRegistered = true;
2800
+ process.once("beforeExit", () => void shutdown());
2801
+ }
2802
+ }
2803
+ function flush() {
2804
+ const runtime = activeRuntime;
2805
+ if (runtime === void 0) return Promise.resolve();
2806
+ return runtime.flush();
2807
+ }
2808
+ function shutdown() {
2809
+ const current = activeRuntime;
2810
+ if (current === void 0) return Promise.resolve();
2811
+ return current.shutdown().then(() => {
2812
+ if (activeRuntime === current) activeRuntime = void 0;
2813
+ });
2814
+ }
2815
+ /** The provider in use; a no-op proxy when not running (spec 10 rule 1). */
2816
+ function tracerProvider() {
2817
+ const runtime = activeRuntime;
2818
+ if (runtime === void 0) return new ProxyTracerProvider();
2819
+ return runtime.provider;
2820
+ }
2821
+ /** Our span processor, for apps that build their own OTel pipeline. */
2822
+ function spanProcessor() {
2823
+ return activeRuntime?.processor;
2824
+ }
2825
+ /** The running runtime, when one is installed. Internal. */
2826
+ function currentRuntime() {
2827
+ return activeRuntime;
2828
+ }
2829
+ /** Install a runtime. Internal, and the test seam. */
2830
+ function installRuntime(runtime) {
2831
+ activeRuntime = runtime;
2832
+ }
2833
+ /**
2834
+ * D-F-4: does the global provider hold an app provider? The API returns its
2835
+ * singleton `ProxyTracerProvider` both before and after a registration, so the
2836
+ * test is by identity on the delegate — the shared no-op provider means
2837
+ * nothing is registered. Never compare constructor names: they break under
2838
+ * minification.
2839
+ */
2840
+ function appProviderRegistered(provider) {
2841
+ if (!(provider instanceof ProxyTracerProvider)) return true;
2842
+ return provider.getDelegate() !== new ProxyTracerProvider().getDelegate();
2843
+ }
2844
+ function registerContextManager() {
2845
+ const manager = new AsyncLocalStorageContextManager();
2846
+ if (context.setGlobalContextManager(manager.enable())) return;
2847
+ manager.disable();
2848
+ }
2849
+ function requireApiKey(config) {
2850
+ if (config.apiKey === void 0) throw new Error("Runtime.create requires a config with an API key");
2851
+ return config.apiKey;
2852
+ }
2853
+ function errorName$4(error) {
2854
+ return error instanceof Error ? error.name : typeof error;
2855
+ }
2856
+ // src/ai.ts
2857
+ /** Telemetry settings for the Vercel AI SDK's `experimental_telemetry`. */
2858
+ function aiTelemetry(options = {}) {
2859
+ const runtime = currentRuntime();
2860
+ if (runtime === void 0) return { isEnabled: false };
2861
+ const metadata = { ...options.metadata };
2862
+ if (options.sessionId !== void 0) metadata.sessionId = options.sessionId;
2863
+ if (options.userId !== void 0) metadata.userId = options.userId;
2864
+ if (options.tags !== void 0) metadata.tags = [...options.tags];
2865
+ const telemetry = {
2866
+ isEnabled: true,
2867
+ tracer: runtime.provider.getTracer("ai"),
2868
+ metadata
2869
+ };
2870
+ if (options.functionId !== void 0) telemetry.functionId = options.functionId;
2871
+ return telemetry;
2872
+ }
2873
+ // src/generators.ts
2874
+ /**
2875
+ * Traced generators and async generators (T7, D-F-11).
2876
+ *
2877
+ * `observe` detects generator functions at wrap time and, in generator mode,
2878
+ * creates no span at call time: it returns `traceGenerator` /
2879
+ * `traceAsyncGenerator` around the inner generator. The span starts when the
2880
+ * body starts (the first `next()`), with the context active then as parent,
2881
+ * and is current only while the body runs: every step runs inside
2882
+ * `context.with(spanContext, …)`. Exhaustion ends the span with the status
2883
+ * unset and the yielded items as the output; an early `return()` from the
2884
+ * consumer ends it with status ok and the items so far (an early `return()`
2885
+ * is not an error, § Span attributes "Errors"); an exception from the body, or
2886
+ * from a `throw()` the consumer delivers and the body does not catch, records
2887
+ * the error per § Span attributes "Errors" and is re-thrown. A `throw()` the
2888
+ * body catches keeps the loop going.
2889
+ *
2890
+ * A generator abandoned half-consumed — never exhausted, never `return()`ed —
2891
+ * is never exported: TypeScript has no reliable finalizer, so its span stays
2892
+ * unended. Consume generators fully, `break` out of the loop (which calls
2893
+ * `return()`), or call `return()` yourself.
2894
+ */
2895
+ const START = {
2896
+ kind: "next",
2897
+ value: void 0
2898
+ };
2899
+ /**
2900
+ * Wrap `inner` so the generator runs inside one of our spans (see the module
2901
+ * doc). The wrapper starts the span on the first `next()`, forwards sent
2902
+ * values and consumer `throw()`s, and ends the span on exhaustion (status
2903
+ * unset, the output), on an early `return()` (status ok, the items so far) or
2904
+ * on an exception (the error, then re-throw). An abandoned wrapper never ends
2905
+ * its span, so it is never exported.
2906
+ */
2907
+ function* traceGenerator(inner, plan) {
2908
+ const span = startTracedSpan(plan.runtime, plan);
2909
+ if (span === void 0) return yield* inner;
2910
+ const spanContext = trace.setSpan(context.active(), span);
2911
+ const items = [];
2912
+ const keeping = plan.runtime.config.captureContent && plan.captureOutput;
2913
+ let ended = false;
2914
+ let delivery = START;
2915
+ try {
2916
+ for (;;) {
2917
+ let result;
2918
+ try {
2919
+ result = context.with(spanContext, () => deliver(inner, delivery));
2920
+ } catch (error) {
2921
+ ended = true;
2922
+ recordError(span, error);
2923
+ span.end();
2924
+ throw error;
2925
+ }
2926
+ if (result.done === true) {
2927
+ ended = true;
2928
+ recordOutput(span, plan, items);
2929
+ span.end();
2930
+ return result.value;
2931
+ }
2932
+ if (keeping) items.push(result.value);
2933
+ try {
2934
+ delivery = {
2935
+ kind: "next",
2936
+ value: yield result.value
2937
+ };
2938
+ } catch (error) {
2939
+ delivery = {
2940
+ kind: "throw",
2941
+ error
2942
+ };
2943
+ }
2944
+ }
2945
+ } finally {
2946
+ if (!ended) {
2947
+ ended = true;
2948
+ try {
2949
+ context.with(spanContext, () => inner.return(void 0));
2950
+ span.setStatus({ code: SpanStatusCode.OK });
2951
+ recordOutput(span, plan, items);
2952
+ } catch (error) {
2953
+ recordError(span, error);
2954
+ }
2955
+ span.end();
2956
+ }
2957
+ }
2958
+ }
2959
+ /**
2960
+ * The `async function*` equivalent of `traceGenerator`: the span starts on the
2961
+ * first `next()`, each step's continuations run inside the span context, and
2962
+ * the span ends on exhaustion, early `return()` or exception as its sync twin.
2963
+ * An abandoned async generator never ends its span, so it is never exported.
2964
+ */
2965
+ async function* traceAsyncGenerator(inner, plan) {
2966
+ const span = startTracedSpan(plan.runtime, plan);
2967
+ if (span === void 0) return yield* inner;
2968
+ const spanContext = trace.setSpan(context.active(), span);
2969
+ const items = [];
2970
+ const keeping = plan.runtime.config.captureContent && plan.captureOutput;
2971
+ let ended = false;
2972
+ let delivery = START;
2973
+ try {
2974
+ for (;;) {
2975
+ let result;
2976
+ try {
2977
+ result = await context.with(spanContext, () => deliverAsync(inner, delivery));
2978
+ } catch (error) {
2979
+ ended = true;
2980
+ recordError(span, error);
2981
+ span.end();
2982
+ throw error;
2983
+ }
2984
+ if (result.done === true) {
2985
+ ended = true;
2986
+ recordOutput(span, plan, items);
2987
+ span.end();
2988
+ return result.value;
2989
+ }
2990
+ if (keeping) items.push(result.value);
2991
+ try {
2992
+ delivery = {
2993
+ kind: "next",
2994
+ value: yield result.value
2995
+ };
2996
+ } catch (error) {
2997
+ delivery = {
2998
+ kind: "throw",
2999
+ error
3000
+ };
3001
+ }
3002
+ }
3003
+ } finally {
3004
+ if (!ended) {
3005
+ ended = true;
3006
+ try {
3007
+ await context.with(spanContext, () => inner.return(void 0));
3008
+ span.setStatus({ code: SpanStatusCode.OK });
3009
+ recordOutput(span, plan, items);
3010
+ } catch (error) {
3011
+ recordError(span, error);
3012
+ }
3013
+ span.end();
3014
+ }
3015
+ }
3016
+ }
3017
+ /** One inner step of a generator, with a consumer `throw()` forwarded. */
3018
+ function deliver(inner, delivery) {
3019
+ return delivery.kind === "next" ? inner.next(delivery.value) : inner.throw(delivery.error);
3020
+ }
3021
+ /** One inner step of an async generator, with a consumer `throw()` forwarded. */
3022
+ function deliverAsync(inner, delivery) {
3023
+ return delivery.kind === "next" ? inner.next(delivery.value) : inner.throw(delivery.error);
3024
+ }
3025
+ /**
3026
+ * The generator output rule: no items → no output; every item a string →
3027
+ * their concatenation (text); otherwise the items as a JSON list.
3028
+ * `plan.reduceOutput`, when given, records `fn(items)` instead; a throw falls
3029
+ * back to the default rule with a debug log. Never throws.
3030
+ */
3031
+ function recordOutput(span, plan, items) {
3032
+ if (items.length === 0) return;
3033
+ if (plan.reduceOutput !== void 0) try {
3034
+ setPayload(span, "cetra.output", plan.reduceOutput(items), plan.runtime);
3035
+ return;
3036
+ } catch (error) {
3037
+ debug(`cetra: reduceOutput failed (${errorName$3(error)}); recording the items instead`);
3038
+ }
3039
+ if (items.every((item) => typeof item === "string")) {
3040
+ setPayload(span, "cetra.output", items.join(""), plan.runtime);
3041
+ return;
3042
+ }
3043
+ setPayload(span, "cetra.output", items, plan.runtime);
3044
+ }
3045
+ function errorName$3(error) {
3046
+ return error instanceof Error ? error.name : typeof error;
3047
+ }
3048
+ // src/span.ts
3049
+ /**
3050
+ * Manual spans: `withSpan`, the `observe` wrapper and the current ids (T6).
3051
+ *
3052
+ * One runner starts the span on our tracer with the active context as parent,
3053
+ * runs the body with the span current, and ends it when the body settles: a
3054
+ * thenable result ends the span from `.then` callbacks (a promise of the same
3055
+ * value comes back), a synchronous throw is recorded and re-thrown unchanged
3056
+ * (§ Span attributes "Errors"). Without a running runtime the body runs
3057
+ * untouched: `withSpan` with a no-op handle, `observe`'s wrapper straight
3058
+ * through. The check happens at call time, so functions wrapped before
3059
+ * `init()` are traced after it.
3060
+ *
3061
+ * Generator functions take another path (T7): `observe` detects them at wrap
3062
+ * time and traces the *generator*, not the call, through `./generators.js`.
3063
+ */
3064
+ const KINDS = [
3065
+ "llm",
3066
+ "embedding",
3067
+ "tool",
3068
+ "agent",
3069
+ "chain",
3070
+ "retriever",
3071
+ "reranker",
3072
+ "guardrail",
3073
+ "evaluator",
3074
+ "span"
3075
+ ];
3076
+ /**
3077
+ * § Span attributes "Programming errors raise": an invalid `kind` is the one
3078
+ * error the SDK raises after `init()`, before the user function runs. It is
3079
+ * checked when `observe`/`withSpan` is called (wrap time for `observe`).
3080
+ */
3081
+ function checkKind(kind) {
3082
+ if (kind === void 0) return "chain";
3083
+ if (typeof kind === "string" && KINDS.includes(kind)) return kind;
3084
+ throw new TypeError(`kind: must be one of ${KINDS.join(", ")}`);
3085
+ }
3086
+ /**
3087
+ * The shared runner (T6, T8). The body's return value is never recorded as
3088
+ * the output here; `observe` records it through `plan.captureResultAsOutput`,
3089
+ * `withSpan` and `withLlmSpan` only through the handle's `setOutput`.
3090
+ */
3091
+ function tracedSpan(plan, handles, body) {
3092
+ const runtime = currentRuntime();
3093
+ if (runtime === void 0) return body(handles.noop);
3094
+ const span = startTracedSpan(runtime, plan);
3095
+ if (span === void 0) return body(handles.noop);
3096
+ const handle = handles.create(span, runtime);
3097
+ try {
3098
+ const result = context.with(trace.setSpan(context.active(), span), () => body(handle));
3099
+ if (isThenable(result)) return result.then((value) => {
3100
+ captureResult(plan, span, runtime, value);
3101
+ span.end();
3102
+ return value;
3103
+ }, (error) => {
3104
+ recordError(span, error);
3105
+ span.end();
3106
+ throw error;
3107
+ });
3108
+ captureResult(plan, span, runtime, result);
3109
+ span.end();
3110
+ return result;
3111
+ } catch (error) {
3112
+ recordError(span, error);
3113
+ span.end();
3114
+ throw error;
3115
+ }
3116
+ }
3117
+ /** Start the span on our tracer, stamp kind, input and metadata. Never throws. */
3118
+ function startTracedSpan(runtime, plan) {
3119
+ try {
3120
+ const span = runtime.tracer.startSpan(plan.name, void 0, context.active());
3121
+ span.setAttribute("cetra.span.kind", plan.kind);
3122
+ if (plan.hasInput) setPayload(span, "cetra.input", plan.inputValue, runtime);
3123
+ if (plan.metadata !== void 0) stampMetadata(span, plan.metadata);
3124
+ return span;
3125
+ } catch (error) {
3126
+ debug(`cetra: starting a span failed: ${errorName$2(error)}`);
3127
+ return;
3128
+ }
3129
+ }
3130
+ /** `observe`: the settled result as the output, when it is one to record. */
3131
+ function captureResult(plan, span, runtime, value) {
3132
+ if (plan.captureResultAsOutput && value !== void 0 && !isGeneratorObject(value)) setPayload(span, "cetra.output", value, runtime);
3133
+ }
3134
+ /** § Span attributes "Errors": the event ourselves (not `recordException`), the error status, then re-raise. */
3135
+ function recordError(span, error) {
3136
+ try {
3137
+ const isError = error instanceof Error;
3138
+ const type = isError ? error.name : "Error";
3139
+ const message = isError ? error.message : String(error);
3140
+ span.addEvent("exception", {
3141
+ "exception.type": type,
3142
+ "exception.message": message,
3143
+ "exception.stacktrace": isError ? error.stack ?? "" : ""
3144
+ });
3145
+ span.setStatus({
3146
+ code: SpanStatusCode.ERROR,
3147
+ message: `${type}: ${message}`
3148
+ });
3149
+ } catch (failure) {
3150
+ debug(`cetra: recording an exception failed: ${errorName$2(failure)}`);
3151
+ }
3152
+ }
3153
+ /** The masked, serialized payload under `key` plus its format, when content capture is on. Never throws. */
3154
+ function setPayload(span, key, value, runtime) {
3155
+ try {
3156
+ if (!runtime.config.captureContent) return;
3157
+ const [text, format] = serialize(applyMask(value));
3158
+ span.setAttribute(key, text);
3159
+ span.setAttribute(`${key}.format`, format);
3160
+ } catch (error) {
3161
+ debug(`cetra: setting a payload attribute failed: ${errorName$2(error)}`);
3162
+ }
3163
+ }
3164
+ /** Each metadata value as its `cetra.metadata.<key>` attribute, masked per value (D-F-6).
3165
+ * Never throws. Shared with the LLM span (T8). */
3166
+ function stampMetadata(span, values) {
3167
+ try {
3168
+ for (const [key, value] of Object.entries(values)) {
3169
+ const name = metadataAttributeName(key);
3170
+ if (name !== void 0) span.setAttribute(name, attributeValue(applyMask(value)));
3171
+ }
3172
+ } catch (error) {
3173
+ debug(`cetra: setting a metadata attribute failed: ${errorName$2(error)}`);
3174
+ }
3175
+ }
3176
+ /** The live handle; every method is a no-op after the span ended and never raises. */
3177
+ var LiveSpanHandle = class {
3178
+ span;
3179
+ runtime;
3180
+ constructor(span, runtime) {
3181
+ this.span = span;
3182
+ this.runtime = runtime;
3183
+ }
3184
+ get traceId() {
3185
+ const spanContext = this.span.spanContext();
3186
+ return isSpanContextValid(spanContext) ? spanContext.traceId : void 0;
3187
+ }
3188
+ get spanId() {
3189
+ const spanContext = this.span.spanContext();
3190
+ return isSpanContextValid(spanContext) ? spanContext.spanId : void 0;
3191
+ }
3192
+ setInput(value) {
3193
+ if (this.span.isRecording()) setPayload(this.span, "cetra.input", value, this.runtime);
3194
+ }
3195
+ setOutput(value) {
3196
+ if (this.span.isRecording()) setPayload(this.span, "cetra.output", value, this.runtime);
3197
+ }
3198
+ setMetadata(values) {
3199
+ if (this.span.isRecording()) stampMetadata(this.span, values);
3200
+ }
3201
+ };
3202
+ const SPAN_HANDLES = {
3203
+ create: (span, runtime) => new LiveSpanHandle(span, runtime),
3204
+ noop: {
3205
+ traceId: void 0,
3206
+ spanId: void 0,
3207
+ setInput: () => {},
3208
+ setOutput: () => {},
3209
+ setMetadata: () => {}
3210
+ }
3211
+ };
3212
+ /** A body result with a `then` method ends the span when it settles. */
3213
+ function isThenable(value) {
3214
+ return typeof value === "object" && value !== null && typeof value.then === "function";
3215
+ }
3216
+ /** D-F-11: generator and async generator objects (functions are detected in T7). */
3217
+ function isGeneratorObject(value) {
3218
+ const tag = Object.prototype.toString.call(value);
3219
+ return tag === "[object Generator]" || tag === "[object AsyncGenerator]";
3220
+ }
3221
+ function withSpan(name, fnOrOptions, maybeFn) {
3222
+ const raw = typeof fnOrOptions === "function" ? {} : fnOrOptions;
3223
+ const kind = checkKind(raw.kind);
3224
+ const fn = typeof fnOrOptions === "function" ? fnOrOptions : maybeFn;
3225
+ return tracedSpan({
3226
+ name,
3227
+ kind,
3228
+ hasInput: "input" in raw,
3229
+ inputValue: raw.input,
3230
+ metadata: raw.metadata,
3231
+ captureResultAsOutput: false
3232
+ }, SPAN_HANDLES, fn);
3233
+ }
3234
+ /**
3235
+ * Wrap `fn` so each call runs inside one of our spans. `this` is preserved;
3236
+ * the input follows D-F-11 (no arguments → none, one → that value, more → the
3237
+ * array of them) and the output is the return value or resolved value
3238
+ * (`undefined` and generator objects are not recorded).
3239
+ *
3240
+ * Generator and async generator functions (detected at wrap time) are traced
3241
+ * as generators instead: no span at call time, the span starts at the first
3242
+ * `next()`, the output is the yielded items (or `reduceOutput(items)`), an
3243
+ * early `return()` ends with status ok. See `./generators.js`. The kind is
3244
+ * checked at wrap time; the runtime at call time, so a function wrapped
3245
+ * before `init()` is traced after it.
3246
+ */
3247
+ function observe(fn, options) {
3248
+ const raw = options ?? {};
3249
+ const kind = checkKind(raw.kind);
3250
+ const name = raw.name ?? (fn.name || "anonymous");
3251
+ const captureInput = raw.captureInput ?? true;
3252
+ const captureOutput = raw.captureOutput ?? true;
3253
+ const tag = Object.prototype.toString.call(fn);
3254
+ const generatorTag = tag === "[object GeneratorFunction]" || tag === "[object AsyncGeneratorFunction]";
3255
+ return function(...args) {
3256
+ if (!generatorTag) return tracedSpan({
3257
+ name,
3258
+ kind,
3259
+ hasInput: captureInput && args.length > 0,
3260
+ inputValue: args.length === 1 ? args[0] : args,
3261
+ metadata: void 0,
3262
+ captureResultAsOutput: captureOutput
3263
+ }, SPAN_HANDLES, () => fn.apply(this, args));
3264
+ const runtime = currentRuntime();
3265
+ const gen = fn.apply(this, args);
3266
+ if (runtime === void 0) return gen;
3267
+ const plan = {
3268
+ name,
3269
+ kind,
3270
+ hasInput: captureInput && args.length > 0,
3271
+ inputValue: args.length === 1 ? args[0] : args,
3272
+ metadata: void 0,
3273
+ runtime,
3274
+ captureOutput,
3275
+ reduceOutput: raw.reduceOutput
3276
+ };
3277
+ return tag === "[object GeneratorFunction]" ? traceGenerator(gen, plan) : traceAsyncGenerator(gen, plan);
3278
+ };
3279
+ }
3280
+ /** The trace id of the current span (ours or an instrumentor's), when valid. */
3281
+ function currentTraceId() {
3282
+ return currentSpanContext()?.traceId;
3283
+ }
3284
+ /** The span id of the current span (ours or an instrumentor's), when valid. */
3285
+ function currentSpanId() {
3286
+ return currentSpanContext()?.spanId;
3287
+ }
3288
+ function currentSpanContext() {
3289
+ const spanContext = trace.getSpan(context.active())?.spanContext();
3290
+ return spanContext !== void 0 && isSpanContextValid(spanContext) ? spanContext : void 0;
3291
+ }
3292
+ function errorName$2(error) {
3293
+ return error instanceof Error ? error.name : typeof error;
3294
+ }
3295
+ // src/experiments.ts
3296
+ /**
3297
+ * Experiments: `evaluate` runs a task over every item of a dataset version,
3298
+ * traces each run, scores it on this machine and stores the results on the
3299
+ * server (spec 06 § Protocol as amended; D-J-10, D-J-12, D-J-16).
3300
+ *
3301
+ * Task and scorer exceptions are recorded per run and do not abort the
3302
+ * experiment. Configuration, argument and API failures raise.
3303
+ */
3304
+ const DEFAULT_CONCURRENCY = 8;
3305
+ const MAX_CONCURRENCY = 64;
3306
+ const MAX_REPETITIONS = 20;
3307
+ const MAX_NAME_CHARS = 200;
3308
+ const ITEM_PAGE_SIZE = 1e3;
3309
+ const UPLOAD_BATCH_ROWS = 500;
3310
+ const UPLOAD_BATCH_BYTES = 33554432;
3311
+ /** An output over this many UTF-8 bytes of JSON text is cut (§ Output). */
3312
+ const OUTPUT_LIMIT_BYTES = 262144;
3313
+ const OUTPUT_KEEP_BYTES = 26e4;
3314
+ const ERROR_LIMIT_CHARS = 4096;
3315
+ const UPLOAD_FAILED = "results upload failed";
3316
+ /** The outcome of `evaluate`, built from the local runs and scores. */
3317
+ var ExperimentResult = class {
3318
+ experimentId;
3319
+ experimentName;
3320
+ datasetId;
3321
+ /** The pinned dataset version. */
3322
+ datasetVersion;
3323
+ /** In item order, repetitions inner. */
3324
+ runs;
3325
+ /** Scorer name to the number of runs it failed on (only scorers that failed). */
3326
+ scorerErrors;
3327
+ #scorerNames;
3328
+ /** @internal */
3329
+ constructor(fields) {
3330
+ this.experimentId = fields.experimentId;
3331
+ this.experimentName = fields.experimentName;
3332
+ this.datasetId = fields.datasetId;
3333
+ this.datasetVersion = fields.datasetVersion;
3334
+ this.runs = fields.runs;
3335
+ this.scorerErrors = fields.scorerErrors;
3336
+ this.#scorerNames = fields.scorerNames;
3337
+ }
3338
+ /** Runs with a task error. */
3339
+ get errorCount() {
3340
+ return this.runs.filter((run) => run.error !== void 0).length;
3341
+ }
3342
+ /** A short text report, one line per scorer, in the order the scorers were given. */
3343
+ summary() {
3344
+ const lines = [`Experiment ${this.experimentName} (${this.experimentId}) on dataset ${this.datasetId} v${String(this.datasetVersion)}: ${String(this.runs.length)} runs, ${String(this.errorCount)} errors`];
3345
+ for (const name of this.#scorerNames) {
3346
+ const values = this.#values(name);
3347
+ const numbers = values.flatMap((value) => typeof value === "string" ? [] : [Number(value)]);
3348
+ const labels = values.filter((value) => typeof value === "string");
3349
+ if (numbers.length === 0 && labels.length === 0) lines.push(` ${name}: no values`);
3350
+ if (numbers.length > 0) lines.push(` ${name}: mean ${mean(numbers).toFixed(3)} (${String(numbers.length)} values)`);
3351
+ if (labels.length > 0) lines.push(` ${name}: ${labelCounts(labels)}`);
3352
+ const errors = this.#errorsOf(name);
3353
+ if (errors > 0) lines.push(` ${name}: ${String(errors)} errors`);
3354
+ }
3355
+ return lines.join("\n");
3356
+ }
3357
+ /**
3358
+ * Throws `Error` when the mean of the numeric and boolean values of `name`
3359
+ * (over every run) is below `threshold`, or when there are none.
3360
+ */
3361
+ assertMin(name, threshold) {
3362
+ const numbers = this.#values(name).flatMap((value) => typeof value === "string" ? [] : [Number(value)]);
3363
+ if (numbers.length === 0) throw new Error(`${name}: no numeric or boolean values`);
3364
+ const average = mean(numbers);
3365
+ if (average < threshold) throw new Error(`${name}: mean ${average.toFixed(3)} is below ${String(threshold)}`);
3366
+ }
3367
+ /** The score values of scorer `name`, one per run that has one. */
3368
+ #values(name) {
3369
+ const values = [];
3370
+ for (const run of this.runs) {
3371
+ const score = scoreOf(run, name);
3372
+ if (score !== void 0) values.push(score.value);
3373
+ }
3374
+ return values;
3375
+ }
3376
+ #errorsOf(name) {
3377
+ return Object.hasOwn(this.scorerErrors, name) ? this.scorerErrors[name] ?? 0 : 0;
3378
+ }
3379
+ };
3380
+ /**
3381
+ * Run `task` on every item of a dataset version, score each run with
3382
+ * `scorers` and store the results on the server. Raises `ConfigError` before
3383
+ * `init()`, `RangeError`/`TypeError` for bad arguments, `ApiError` when the API
3384
+ * refuses a call (the create, or a finish that fails).
3385
+ */
3386
+ async function evaluate(options) {
3387
+ const runtime = currentRuntime();
3388
+ if (runtime === void 0) throw new ConfigError("evaluate", "needs cetra.init() with an API key");
3389
+ const checked = checkOptions(options);
3390
+ const client = options.client ?? new Client({
3391
+ apiKey: runtime.config.apiKey,
3392
+ baseUrl: runtime.config.baseUrl
3393
+ });
3394
+ if (runtime.config.sampleRate < 1) warnOnce("evaluate-sample-rate", "cetra: sample_rate is below 1; some experiment runs will have no trace and no score");
3395
+ const created = await createExperiment(client, options, checked.repetitions, await defaultNameSource(client, options));
3396
+ const experiment = created.experiment;
3397
+ let finishing = false;
3398
+ try {
3399
+ const executed = await execute({
3400
+ runtime,
3401
+ client,
3402
+ experiment,
3403
+ items: await readItems(client, created),
3404
+ repetitions: checked.repetitions,
3405
+ concurrency: checked.concurrency,
3406
+ task: options.task,
3407
+ scorers: checked.scorers
3408
+ });
3409
+ finishing = true;
3410
+ if (executed.uploadFailure !== void 0) {
3411
+ await finishWithError(client, experiment, UPLOAD_FAILED);
3412
+ throw executed.uploadFailure;
3413
+ }
3414
+ await client.request("POST", "/experiments/{experiment}/finish", finishPath(experiment), {
3415
+ body: {},
3416
+ retry: true
3417
+ });
3418
+ return new ExperimentResult({
3419
+ experimentId: experiment.id,
3420
+ experimentName: experiment.name,
3421
+ datasetId: experiment.dataset_id,
3422
+ datasetVersion: experiment.dataset_version,
3423
+ runs: executed.runs.filter((run) => run !== void 0),
3424
+ scorerErrors: Object.fromEntries(executed.scorerErrors),
3425
+ scorerNames: checked.scorers.map((scorer) => scorer.name)
3426
+ });
3427
+ } catch (error) {
3428
+ if (!finishing) await finishWithError(client, experiment, errorName$1(error));
3429
+ throw error;
3430
+ }
3431
+ }
3432
+ /** The argument checks of § `evaluate` flow step 1. Throws; never calls the API. */
3433
+ function checkOptions(options) {
3434
+ const { dataset, task, experimentName, datasetVersion } = options;
3435
+ if (typeof dataset !== "string" && !(dataset instanceof Dataset)) throw new TypeError("dataset: must be a name or a Dataset");
3436
+ if (typeof task !== "function") throw new TypeError("task: must be a function");
3437
+ const concurrency = options.concurrency ?? DEFAULT_CONCURRENCY;
3438
+ if (!Number.isInteger(concurrency) || concurrency < 1 || concurrency > MAX_CONCURRENCY) throw new RangeError(`concurrency: must be 1 to ${String(MAX_CONCURRENCY)}`);
3439
+ const repetitions = options.repetitions ?? 1;
3440
+ if (!Number.isInteger(repetitions) || repetitions < 1 || repetitions > MAX_REPETITIONS) throw new RangeError(`repetitions: must be 1 to ${String(MAX_REPETITIONS)}`);
3441
+ if (experimentName !== void 0) {
3442
+ const length = [...experimentName].length;
3443
+ if (length < 1 || length > MAX_NAME_CHARS) throw new RangeError(`experimentName: must be 1 to ${String(MAX_NAME_CHARS)} characters`);
3444
+ }
3445
+ if (datasetVersion !== void 0 && (!Number.isInteger(datasetVersion) || datasetVersion < 0)) throw new RangeError("datasetVersion: must be a non-negative integer");
3446
+ const scorers = [];
3447
+ const names = /* @__PURE__ */ new Set();
3448
+ (options.scorers ?? []).forEach((fn, index) => {
3449
+ if (typeof fn !== "function") throw new TypeError(`scorers[${String(index)}]: must be a function`);
3450
+ if (fn.name === "") throw new TypeError(`scorers[${String(index)}]: needs a name`);
3451
+ if (names.has(fn.name)) throw new TypeError(`scorers[${String(index)}]: name is used by another scorer`);
3452
+ names.add(fn.name);
3453
+ scorers.push({
3454
+ name: fn.name,
3455
+ index,
3456
+ fn
3457
+ });
3458
+ });
3459
+ return {
3460
+ concurrency,
3461
+ repetitions,
3462
+ scorers
3463
+ };
3464
+ }
3465
+ /**
3466
+ * The dataset name the default experiment name needs: a `Dataset` has it; a
3467
+ * name given as a string is read with one `GET` (only when no experiment name
3468
+ * is given). A string id is read the same way.
3469
+ */
3470
+ async function defaultNameSource(client, options) {
3471
+ if (options.experimentName !== void 0) return;
3472
+ const { dataset } = options;
3473
+ if (typeof dataset !== "string") return dataset.name;
3474
+ return (await client.request("GET", "/datasets/{dataset}", `/datasets/${segment(dataset)}`)).name;
3475
+ }
3476
+ /** Create the experiment. Sent once: a retry could create a second one. */
3477
+ async function createExperiment(client, options, repetitions, datasetName) {
3478
+ const { dataset } = options;
3479
+ const datasetRef = typeof dataset === "string" ? dataset : dataset.id;
3480
+ const body = {
3481
+ name: options.experimentName ?? defaultName(datasetName ?? ""),
3482
+ dataset: datasetRef,
3483
+ repetitions
3484
+ };
3485
+ let version = options.datasetVersion;
3486
+ if (version === void 0 && typeof dataset !== "string" && dataset.version !== 0) version = dataset.version;
3487
+ if (version !== void 0) body.dataset_version = version;
3488
+ if (options.description !== void 0) body.description = options.description;
3489
+ if (options.metadata !== void 0) body.metadata = toJsonable(options.metadata);
3490
+ return client.request("POST", "/experiments", "/experiments", {
3491
+ body,
3492
+ retry: false
3493
+ });
3494
+ }
3495
+ /** The first page from the create answer, then the rest of the pinned version (D-J-10). */
3496
+ async function readItems(client, created) {
3497
+ const items = created.items.map(itemFromWire);
3498
+ const { dataset_id: datasetId, dataset_version: version } = created.experiment;
3499
+ let cursor = created.next_cursor;
3500
+ while (cursor !== null) {
3501
+ const page = await client.request("GET", "/datasets/{dataset}/items", `/datasets/${segment(datasetId)}/items`, { query: {
3502
+ version,
3503
+ limit: ITEM_PAGE_SIZE,
3504
+ cursor
3505
+ } });
3506
+ items.push(...page.data.map(itemFromWire));
3507
+ cursor = page.next_cursor;
3508
+ }
3509
+ return items;
3510
+ }
3511
+ /**
3512
+ * Runs the (item, repetition) pairs, at most `concurrency` at once, and drains
3513
+ * the uploads. A worker that throws stops new runs; the rest in flight are
3514
+ * awaited, then the error is raised.
3515
+ */
3516
+ async function execute(plan) {
3517
+ const { runtime, client, experiment, items, repetitions } = plan;
3518
+ const total = items.length * repetitions;
3519
+ const runs = new Array(total);
3520
+ const uploader = new Uploader(client, experiment.id);
3521
+ const scorerErrors = /* @__PURE__ */ new Map();
3522
+ const warned = /* @__PURE__ */ new Set();
3523
+ let next = 0;
3524
+ let stopped = false;
3525
+ const worker = async () => {
3526
+ while (!stopped && uploader.failure === void 0 && next < total) {
3527
+ const index = next;
3528
+ next += 1;
3529
+ const item = items[Math.floor(index / repetitions)];
3530
+ if (item === void 0) return;
3531
+ try {
3532
+ const outcome = await runOne(plan, item, index % repetitions, scorerErrors, warned);
3533
+ runs[index] = outcome.run;
3534
+ await uploader.add(outcome.row, outcome.bytes);
3535
+ } catch (error) {
3536
+ stopped = true;
3537
+ throw error;
3538
+ }
3539
+ }
3540
+ };
3541
+ const settled = await Promise.allSettled(Array.from({ length: Math.min(plan.concurrency, total) }, () => worker()));
3542
+ await uploader.drain();
3543
+ await runtime.flush();
3544
+ const failed = settled.find((result) => {
3545
+ return result.status === "rejected";
3546
+ });
3547
+ if (failed !== void 0) throw failed.reason;
3548
+ return {
3549
+ runs,
3550
+ scorerErrors,
3551
+ uploadFailure: uploader.failure
3552
+ };
3553
+ }
3554
+ /** Finish the experiment with `error`, best effort: a failure is logged at debug level only. */
3555
+ async function finishWithError(client, experiment, error) {
3556
+ try {
3557
+ await client.request("POST", "/experiments/{experiment}/finish", finishPath(experiment), {
3558
+ body: { error },
3559
+ retry: true
3560
+ });
3561
+ } catch (finishError) {
3562
+ debug(`cetra: finishing a failed experiment failed: ${errorName$1(finishError)}`);
3563
+ }
3564
+ }
3565
+ function finishPath(experiment) {
3566
+ return `/experiments/${segment(experiment.id)}/finish`;
3567
+ }
3568
+ /** One run: the task in the experiment scope, then the scorers (§ evaluate flow, step 5). */
3569
+ async function runOne(plan, item, repetition, scorerErrors, warned) {
3570
+ const { experiment, task } = plan;
3571
+ let traceId;
3572
+ let latencyNs = 0;
3573
+ let output;
3574
+ let error;
3575
+ const callTask = async (span) => {
3576
+ traceId = sampledTraceId(span);
3577
+ const started = clockNs();
3578
+ let value;
3579
+ try {
3580
+ value = await task(item.input, item);
3581
+ } finally {
3582
+ latencyNs = Math.round(clockNs() - started);
3583
+ }
3584
+ if (value !== void 0) span.setOutput(value);
3585
+ return value;
3586
+ };
3587
+ try {
3588
+ output = await context.with(experimentContext(experiment.id, item.id), () => withSpan(experiment.name, {
3589
+ kind: "chain",
3590
+ input: item.input
3591
+ }, callTask));
3592
+ } catch (caught) {
3593
+ error = errorText(caught);
3594
+ }
3595
+ const row = {
3596
+ dataset_item_id: item.id,
3597
+ repetition,
3598
+ latency_ns: latencyNs
3599
+ };
3600
+ if (traceId !== void 0) row.trace_id = traceId;
3601
+ let bytes = 0;
3602
+ let scores = {};
3603
+ if (error !== void 0) row.error = error;
3604
+ else {
3605
+ const converted = outputForRow(output);
3606
+ if (converted !== void 0) {
3607
+ row.output = converted.output;
3608
+ bytes = converted.bytes;
3609
+ }
3610
+ scores = await context.with(experimentContext(experiment.id, item.id), () => scoreRun(plan, item, output, traceId, scorerErrors, warned));
3611
+ }
3612
+ return {
3613
+ run: {
3614
+ datasetItemId: item.id,
3615
+ repetition,
3616
+ input: item.input,
3617
+ expectedOutput: item.expectedOutput,
3618
+ output: error === void 0 ? output : void 0,
3619
+ error,
3620
+ traceId,
3621
+ latencyNs,
3622
+ scores
3623
+ },
3624
+ row,
3625
+ bytes
3626
+ };
3627
+ }
3628
+ /** Run the scorers in order, queue their scores when the run has a trace, and return the run's scores. */
3629
+ async function scoreRun(plan, item, output, traceId, scorerErrors, warned) {
3630
+ const entries = [];
3631
+ for (const scorer of plan.scorers) {
3632
+ const args = {
3633
+ input: item.input,
3634
+ output,
3635
+ expected: item.expectedOutput,
3636
+ metadata: item.metadata,
3637
+ traceId,
3638
+ item
3639
+ };
3640
+ const outcome = await callScorer(scorer.fn, args);
3641
+ if (outcome.kind === "error") {
3642
+ scorerErrors.set(scorer.name, (scorerErrors.get(scorer.name) ?? 0) + 1);
3643
+ if (!warned.has(scorer.index)) {
3644
+ warned.add(scorer.index);
3645
+ warn(`cetra: scorer ${String(scorer.index)} failed (${outcome.name})`);
3646
+ }
3647
+ continue;
3648
+ }
3649
+ if (outcome.kind === "none") continue;
3650
+ entries.push([scorer.name, outcome.score]);
3651
+ if (traceId !== void 0) {
3652
+ if (plan.runtime.scores.paused()) warnOnce("evaluate-score-pause", "cetra: the monthly units cap paused score uploads; experiment scores are being dropped");
3653
+ queueExperimentScore(plan.runtime, {
3654
+ name: scorer.name,
3655
+ value: outcome.score.value,
3656
+ traceId,
3657
+ experimentId: plan.experiment.id,
3658
+ datasetItemId: item.id,
3659
+ reason: outcome.score.reason,
3660
+ dataType: outcome.score.dataType,
3661
+ metadata: outcome.score.metadata
3662
+ });
3663
+ }
3664
+ }
3665
+ return Object.fromEntries(entries);
3666
+ }
3667
+ /** Call one scorer; a throw or an invalid return value is an error with the type name only. */
3668
+ async function callScorer(scorer, args) {
3669
+ let raw;
3670
+ try {
3671
+ raw = await scorer(args);
3672
+ } catch (caught) {
3673
+ return {
3674
+ kind: "error",
3675
+ name: errorName$1(caught)
3676
+ };
3677
+ }
3678
+ return normalizeScore(raw);
3679
+ }
3680
+ const INVALID_SCORE = {
3681
+ kind: "error",
3682
+ name: "TypeError"
3683
+ };
3684
+ /** § Scorers, return value: a bare value, a `Score`, nothing, or an error. */
3685
+ function normalizeScore(raw) {
3686
+ if (raw === void 0 || raw === null) return { kind: "none" };
3687
+ if (typeof raw === "boolean" || typeof raw === "string") return {
3688
+ kind: "score",
3689
+ score: { value: raw }
3690
+ };
3691
+ if (typeof raw === "number") return Number.isFinite(raw) ? {
3692
+ kind: "score",
3693
+ score: { value: raw }
3694
+ } : INVALID_SCORE;
3695
+ if (typeof raw !== "object" || !("value" in raw)) return INVALID_SCORE;
3696
+ const fields = raw;
3697
+ const value = fields.value;
3698
+ if (typeof value !== "boolean" && typeof value !== "string" && typeof value !== "number") return INVALID_SCORE;
3699
+ const dataType = typeof fields.dataType === "string" ? fields.dataType : void 0;
3700
+ if (valueReason(value, dataType) !== void 0) return INVALID_SCORE;
3701
+ const score = { value };
3702
+ if (typeof fields.reason === "string") score.reason = fields.reason;
3703
+ if (dataType !== void 0) score.dataType = dataType;
3704
+ if (typeof fields.metadata === "object" && fields.metadata !== null && !Array.isArray(fields.metadata)) score.metadata = fields.metadata;
3705
+ return {
3706
+ kind: "score",
3707
+ score
3708
+ };
3709
+ }
3710
+ /**
3711
+ * The trace id of a run's root span, or `undefined` when the span is not
3712
+ * sampled (its trace has no spans and gets no score).
3713
+ */
3714
+ function sampledTraceId(span) {
3715
+ const active = trace.getActiveSpan()?.spanContext();
3716
+ return active !== void 0 && (active.traceFlags & TraceFlags.SAMPLED) !== 0 ? span.traceId : void 0;
3717
+ }
3718
+ /**
3719
+ * The row's output (§ Output): the converted value, or its text cut to
3720
+ * 260,000 bytes and marked when the text is over 256 KiB. `bytes` is the UTF-8
3721
+ * size of the JSON form, the upload budget's unit.
3722
+ */
3723
+ function outputForRow(value) {
3724
+ if (value === void 0) return;
3725
+ try {
3726
+ const converted = toJsonable(value);
3727
+ const text = JSON.stringify(converted);
3728
+ const size = utf8Encode(text).length;
3729
+ if (size <= OUTPUT_LIMIT_BYTES) return {
3730
+ output: converted,
3731
+ bytes: size
3732
+ };
3733
+ const truncated = `${cutUtf8(text, OUTPUT_KEEP_BYTES)}…[cetra: truncated, original ${String(size)} bytes]`;
3734
+ return {
3735
+ output: truncated,
3736
+ bytes: utf8Encode(JSON.stringify(truncated)).length
3737
+ };
3738
+ } catch {
3739
+ const marker = `<unserializable ${typeName(value)}>`;
3740
+ return {
3741
+ output: marker,
3742
+ bytes: utf8Encode(JSON.stringify(marker)).length
3743
+ };
3744
+ }
3745
+ }
3746
+ /** The longest prefix of `text` within `limit` UTF-8 bytes, on a character boundary. */
3747
+ function cutUtf8(text, limit) {
3748
+ const bytes = utf8Encode(text);
3749
+ let cut = limit;
3750
+ while (cut > 0 && ((bytes[cut] ?? 0) & 192) === 128) cut -= 1;
3751
+ return utf8Decode(bytes.subarray(0, cut));
3752
+ }
3753
+ /**
3754
+ * Batches the result rows (§ evaluate flow, step 6). A batch is posted when
3755
+ * 500 rows or 32 MiB of outputs are waiting, and at the end. Posts are upserts
3756
+ * (retried) and run one at a time. The first failure is kept; later posts are
3757
+ * skipped.
3758
+ */
3759
+ var Uploader = class {
3760
+ #client;
3761
+ #path;
3762
+ #rows = [];
3763
+ #bytes = 0;
3764
+ #chain = Promise.resolve();
3765
+ #failure;
3766
+ constructor(client, experimentId) {
3767
+ this.#client = client;
3768
+ this.#path = `/experiments/${segment(experimentId)}/items`;
3769
+ }
3770
+ get failure() {
3771
+ return this.#failure;
3772
+ }
3773
+ /** Queue one row; resolves once every post sent so far has settled. */
3774
+ async add(row, bytes) {
3775
+ if (this.#rows.length > 0 && this.#bytes + bytes > UPLOAD_BATCH_BYTES) this.#post(this.#take());
3776
+ this.#rows.push(row);
3777
+ this.#bytes += bytes;
3778
+ if (this.#rows.length >= UPLOAD_BATCH_ROWS) this.#post(this.#take());
3779
+ await this.#chain;
3780
+ }
3781
+ /** Post the rows still waiting, then resolve once every post has settled. */
3782
+ async drain() {
3783
+ if (this.#rows.length > 0) this.#post(this.#take());
3784
+ await this.#chain;
3785
+ }
3786
+ #take() {
3787
+ const rows = this.#rows;
3788
+ this.#rows = [];
3789
+ this.#bytes = 0;
3790
+ return rows;
3791
+ }
3792
+ #post(rows) {
3793
+ this.#chain = this.#chain.then(async () => {
3794
+ if (this.#failure !== void 0) return;
3795
+ try {
3796
+ await this.#client.request("POST", "/experiments/{experiment}/items", this.#path, {
3797
+ body: { results: rows },
3798
+ retry: true
3799
+ });
3800
+ } catch (error) {
3801
+ if (error instanceof ApiError) this.#failure = error;
3802
+ }
3803
+ });
3804
+ }
3805
+ };
3806
+ /** The score of scorer `name` in a run; own properties only, so `constructor` finds nothing. */
3807
+ function scoreOf(run, name) {
3808
+ return Object.hasOwn(run.scores, name) ? run.scores[name] : void 0;
3809
+ }
3810
+ function mean(values) {
3811
+ return values.reduce((sum, value) => sum + value, 0) / values.length;
3812
+ }
3813
+ /**
3814
+ * "label count" pairs: counts descending, ties by label. Interpretation of
3815
+ * the spec's "labels sorted, counts descending".
3816
+ */
3817
+ function labelCounts(labels) {
3818
+ const counts = /* @__PURE__ */ new Map();
3819
+ for (const label of labels) counts.set(label, (counts.get(label) ?? 0) + 1);
3820
+ return [...counts.entries()].sort(([labelA, countA], [labelB, countB]) => countA !== countB ? countB - countA : labelA < labelB ? -1 : labelA > labelB ? 1 : 0).map(([label, count]) => `${label} ${String(count)}`).join(", ");
3821
+ }
3822
+ /** `YYYY-MM-DD HH:MM:SS` in UTC. */
3823
+ function defaultName(datasetName) {
3824
+ return `${datasetName} ${(/* @__PURE__ */ new Date()).toISOString().slice(0, 19).replace("T", " ")}`;
3825
+ }
3826
+ /** Monotonic nanoseconds (wall clock in milliseconds where there is no `performance`). */
3827
+ function clockNs() {
3828
+ const { performance } = runtimeGlobals();
3829
+ return (performance !== void 0 ? performance.now() : Date.now()) * 1e6;
3830
+ }
3831
+ /** `<ExceptionTypeName>: <message>`, cut to 4,096 UTF-16 code units. */
3832
+ function errorText(caught) {
3833
+ try {
3834
+ return (caught instanceof Error ? `${caught.name}: ${caught.message}` : `Error: ${String(caught)}`).slice(0, ERROR_LIMIT_CHARS);
3835
+ } catch {
3836
+ return typeName(caught);
3837
+ }
3838
+ }
3839
+ function typeName(value) {
3840
+ try {
3841
+ return value?.constructor?.name ?? typeof value;
3842
+ } catch {
3843
+ return typeof value;
3844
+ }
3845
+ }
3846
+ function errorName$1(error) {
3847
+ try {
3848
+ return error instanceof Error ? error.name : typeof error;
3849
+ } catch {
3850
+ return "Error";
3851
+ }
3852
+ }
3853
+ // src/llm.ts
3854
+ /**
3855
+ * The manual LLM span: `withLlmSpan` (T8, D-F-13).
3856
+ *
3857
+ * One chat span with GenAI attributes, started through the T6 runner's
3858
+ * building blocks (`startTracedSpan`, `recordError`, `setPayload`). Messages
3859
+ * may be given in the canonical format (an object with `parts`) or as the
3860
+ * short form `{role, content: "<text>"}`, which becomes one text part; the
3861
+ * list is masked first, then converted, then serialized (§ LLM span). With
3862
+ * `captureContent: false` none of the message attributes is written; the
3863
+ * model, params, usage, cost and TTFT stay. The body's return value is never
3864
+ * recorded; `setInput`/`setOutput` remain available for non-chat payloads.
3865
+ */
3866
+ /** `Usage` field to attribute name, in the setter's declaration order. */
3867
+ const USAGE_KEYS = [
3868
+ ["inputTokens", "gen_ai.usage.input_tokens"],
3869
+ ["outputTokens", "gen_ai.usage.output_tokens"],
3870
+ ["cacheReadTokens", "gen_ai.usage.cache_read.input_tokens"],
3871
+ ["cacheWriteTokens", "gen_ai.usage.cache_creation.input_tokens"],
3872
+ ["reasoningTokens", "gen_ai.usage.reasoning.output_tokens"]
3873
+ ];
3874
+ /** § "Programming errors raise": like `kind`, checked before the body runs. */
3875
+ function requireNonEmptyString(option, value) {
3876
+ if (typeof value === "string" && value.length > 0) return value;
3877
+ throw new TypeError(`${option}: must be a non-empty string`);
3878
+ }
3879
+ /** § LLM span "Messages JSON": one message to the canonical shape. */
3880
+ function toCanonicalMessage(message) {
3881
+ if (typeof message !== "object" || message === null) return message;
3882
+ if ("parts" in message) return message;
3883
+ if ("role" in message && "content" in message && typeof message.content === "string") {
3884
+ const converted = { role: message.role };
3885
+ if ("name" in message) converted.name = message.name;
3886
+ if ("finish_reason" in message) converted.finish_reason = message.finish_reason;
3887
+ converted.parts = [{
3888
+ type: "text",
3889
+ content: message.content
3890
+ }];
3891
+ return converted;
3892
+ }
3893
+ return message;
3894
+ }
3895
+ /** The masked, converted, serialized message list under `key`. Never throws. */
3896
+ function setMessages(span, key, messages, runtime) {
3897
+ try {
3898
+ if (!runtime.config.captureContent) return;
3899
+ const masked = applyMask(messages);
3900
+ const converted = Array.isArray(masked) ? masked.map(toCanonicalMessage) : masked;
3901
+ span.setAttribute(key, serialize(converted)[0]);
3902
+ } catch (error) {
3903
+ debug(`cetra: setting ${key} failed: ${errorName(error)}`);
3904
+ }
3905
+ }
3906
+ /** The masked system instructions as parts JSON. Never throws. */
3907
+ function setSystemInstructions(span, instructions, runtime) {
3908
+ try {
3909
+ if (!runtime.config.captureContent) return;
3910
+ const masked = applyMask(instructions);
3911
+ const parts = typeof masked === "string" ? [{
3912
+ type: "text",
3913
+ content: masked
3914
+ }] : masked;
3915
+ span.setAttribute("gen_ai.system_instructions", serialize(parts)[0]);
3916
+ } catch (error) {
3917
+ debug(`cetra: setting gen_ai.system_instructions failed: ${errorName(error)}`);
3918
+ }
3919
+ }
3920
+ /** `gen_ai.request.<key>` for every scalar param (§ LLM span). */
3921
+ function stampParams(span, params) {
3922
+ if (typeof params !== "object" || params === null) return;
3923
+ for (const [key, value] of Object.entries(params)) if (typeof value === "string" || typeof value === "boolean" || typeof value === "number" && Number.isFinite(value)) span.setAttribute(`gen_ai.request.${key}`, value);
3924
+ }
3925
+ /** The fixed attributes of the LLM span, before the body runs. Never throws. */
3926
+ function stampLlmStart(span, provider, model, options, runtime) {
3927
+ try {
3928
+ span.setAttribute("gen_ai.operation.name", "chat");
3929
+ span.setAttribute("gen_ai.provider.name", provider);
3930
+ span.setAttribute("gen_ai.request.model", model);
3931
+ stampParams(span, options.params);
3932
+ if (options.inputMessages !== void 0) setMessages(span, "gen_ai.input.messages", options.inputMessages, runtime);
3933
+ if (options.systemInstructions !== void 0) setSystemInstructions(span, options.systemInstructions, runtime);
3934
+ } catch (error) {
3935
+ debug(`cetra: starting the LLM span attributes failed: ${errorName(error)}`);
3936
+ }
3937
+ }
3938
+ /** The live handle; every method is a no-op after the span ended and never raises. */
3939
+ var LiveLlmSpanHandle = class {
3940
+ span;
3941
+ runtime;
3942
+ firstTokenRecorded = false;
3943
+ constructor(span, runtime) {
3944
+ this.span = span;
3945
+ this.runtime = runtime;
3946
+ }
3947
+ get traceId() {
3948
+ const spanContext = this.span.spanContext();
3949
+ return isSpanContextValid(spanContext) ? spanContext.traceId : void 0;
3950
+ }
3951
+ get spanId() {
3952
+ const spanContext = this.span.spanContext();
3953
+ return isSpanContextValid(spanContext) ? spanContext.spanId : void 0;
3954
+ }
3955
+ setInput(value) {
3956
+ if (this.span.isRecording()) setPayload(this.span, "cetra.input", value, this.runtime);
3957
+ }
3958
+ setOutput(value) {
3959
+ if (this.span.isRecording()) setPayload(this.span, "cetra.output", value, this.runtime);
3960
+ }
3961
+ setMetadata(values) {
3962
+ if (this.span.isRecording()) stampMetadata(this.span, values);
3963
+ }
3964
+ setInputMessages(messages) {
3965
+ if (this.span.isRecording()) setMessages(this.span, "gen_ai.input.messages", messages, this.runtime);
3966
+ }
3967
+ setOutputMessages(messages) {
3968
+ if (this.span.isRecording()) setMessages(this.span, "gen_ai.output.messages", messages, this.runtime);
3969
+ }
3970
+ setResponseModel(model) {
3971
+ if (!this.span.isRecording()) return;
3972
+ try {
3973
+ this.span.setAttribute("gen_ai.response.model", model);
3974
+ } catch (error) {
3975
+ debug(`cetra: setting gen_ai.response.model failed: ${errorName(error)}`);
3976
+ }
3977
+ }
3978
+ /** Safe integers ≥ 0 only; anything else is skipped with a debug line (no values). */
3979
+ setUsage(usage) {
3980
+ if (!this.span.isRecording()) return;
3981
+ try {
3982
+ for (const [field, attribute] of USAGE_KEYS) {
3983
+ const value = usage[field];
3984
+ if (value === void 0) continue;
3985
+ if (typeof value === "number" && Number.isSafeInteger(value) && value >= 0) this.span.setAttribute(attribute, value);
3986
+ else debug(`cetra: skipped ${attribute}`);
3987
+ }
3988
+ } catch (error) {
3989
+ debug(`cetra: setting a usage attribute failed: ${errorName(error)}`);
3990
+ }
3991
+ }
3992
+ setCost(totalUsd) {
3993
+ if (!this.span.isRecording()) return;
3994
+ if (typeof totalUsd === "number" && Number.isFinite(totalUsd) && totalUsd >= 0) try {
3995
+ this.span.setAttribute("cetra.cost.total", totalUsd);
3996
+ } catch (error) {
3997
+ debug(`cetra: setting cetra.cost.total failed: ${errorName(error)}`);
3998
+ }
3999
+ else debug("cetra: skipped cetra.cost.total");
4000
+ }
4001
+ /** `cetra.ttft_ns`: now − span start; only the first call counts. */
4002
+ recordFirstToken() {
4003
+ if (this.firstTokenRecorded || !this.span.isRecording()) return;
4004
+ this.firstTokenRecorded = true;
4005
+ try {
4006
+ const startTime = this.span.startTime;
4007
+ this.span.setAttribute("cetra.ttft_ns", hrTimeToNanoseconds(hrTimeDuration(startTime, hrTime())));
4008
+ } catch (error) {
4009
+ debug(`cetra: recording the first token failed: ${errorName(error)}`);
4010
+ }
4011
+ }
4012
+ };
4013
+ const NOOP_LLM_HANDLE = {
4014
+ traceId: void 0,
4015
+ spanId: void 0,
4016
+ setInput: () => {},
4017
+ setOutput: () => {},
4018
+ setMetadata: () => {},
4019
+ setInputMessages: () => {},
4020
+ setOutputMessages: () => {},
4021
+ setResponseModel: () => {},
4022
+ setUsage: () => {},
4023
+ setCost: () => {},
4024
+ recordFirstToken: () => {}
4025
+ };
4026
+ /**
4027
+ * Run `fn` inside one manual LLM span, through the T6 runner (`tracedSpan`)
4028
+ * so `withSpan` and `withLlmSpan` behave the same. `provider` and `model` are
4029
+ * checked before the body runs (a `TypeError` otherwise); the body's return
4030
+ * value is never recorded — only the handle's setters write attributes.
4031
+ */
4032
+ function withLlmSpan(name, options, fn) {
4033
+ const provider = requireNonEmptyString("provider", options.provider);
4034
+ const model = requireNonEmptyString("model", options.model);
4035
+ return tracedSpan({
4036
+ name,
4037
+ kind: "llm",
4038
+ hasInput: false,
4039
+ inputValue: void 0,
4040
+ metadata: options.metadata,
4041
+ captureResultAsOutput: false
4042
+ }, {
4043
+ create: (span, runtime) => {
4044
+ stampLlmStart(span, provider, model, options, runtime);
4045
+ return new LiveLlmSpanHandle(span, runtime);
4046
+ },
4047
+ noop: NOOP_LLM_HANDLE
4048
+ }, fn);
4049
+ }
4050
+ function errorName(error) {
4051
+ return error instanceof Error ? error.name : typeof error;
4052
+ }
4053
+ // src/index.ts
4054
+ /** Package version. Kept equal to package.json. */
4055
+ const VERSION = "0.0.0";
4056
+ export { ApiError, Client, ConfigError, Dataset, ExperimentResult, Prompt, PromptCompileError, PromptNotAvailable, VERSION, aiTelemetry, currentSpanId, currentTraceId, evaluate, flush, getPrompt, init, observe, score, shutdown, spanProcessor, tracerProvider, uuid7, withContext, withLlmSpan, withSpan };