@fabricorg/experiments 0.13.0 → 0.14.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/bin/fx.js CHANGED
@@ -22,7 +22,7 @@ var __export = (target, all) => {
22
22
 
23
23
  // package.json
24
24
  var package_default = {
25
- version: "0.13.0"};
25
+ version: "0.14.0"};
26
26
 
27
27
  // ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/external.js
28
28
  var external_exports = {};
@@ -6157,12 +6157,14 @@ var LocalWarehouse = class {
6157
6157
  }
6158
6158
  dir;
6159
6159
  kind = "local";
6160
- state = { exposures: [], conversions: [] };
6160
+ state = { exposures: [], conversions: [], evalScores: [], spans: [] };
6161
6161
  async init() {
6162
6162
  const fs = await import('fs/promises');
6163
6163
  await fs.mkdir(this.dir, { recursive: true });
6164
6164
  this.state.exposures = await readNdjson(`${this.dir}/exposures.ndjson`);
6165
6165
  this.state.conversions = await readNdjson(`${this.dir}/conversions.ndjson`);
6166
+ this.state.evalScores = await readNdjson(`${this.dir}/eval_scores.ndjson`);
6167
+ this.state.spans = await readNdjson(`${this.dir}/spans.ndjson`);
6166
6168
  }
6167
6169
  async recordExposures(events) {
6168
6170
  if (events.length === 0) return;
@@ -6174,6 +6176,96 @@ var LocalWarehouse = class {
6174
6176
  this.state.conversions.push(...events);
6175
6177
  await appendNdjson(`${this.dir}/conversions.ndjson`, events);
6176
6178
  }
6179
+ async recordEvalScores(rows) {
6180
+ if (rows.length === 0) return;
6181
+ const path = `${this.dir}/eval_scores.ndjson`;
6182
+ await withLocalWriteLock(path, async () => {
6183
+ this.state.evalScores = await readNdjson(path);
6184
+ const seen = new Set(this.state.evalScores.map(evalScoreKey));
6185
+ const accepted = rows.filter((row) => {
6186
+ const key = evalScoreKey(row);
6187
+ if (seen.has(key)) return false;
6188
+ seen.add(key);
6189
+ return true;
6190
+ });
6191
+ if (accepted.length === 0) return;
6192
+ await appendNdjson(path, accepted);
6193
+ this.state.evalScores.push(...accepted);
6194
+ });
6195
+ }
6196
+ async recordSpans(rows) {
6197
+ if (rows.length === 0) return;
6198
+ const path = `${this.dir}/spans.ndjson`;
6199
+ await withLocalWriteLock(path, async () => {
6200
+ this.state.spans = await readNdjson(path);
6201
+ const seen = new Set(this.state.spans.map(spanKey));
6202
+ const accepted = rows.filter((row) => {
6203
+ const key = spanKey(row);
6204
+ if (seen.has(key)) return false;
6205
+ seen.add(key);
6206
+ return true;
6207
+ });
6208
+ if (accepted.length === 0) return;
6209
+ await appendNdjson(path, accepted);
6210
+ this.state.spans.push(...accepted);
6211
+ });
6212
+ }
6213
+ async spanAnalytics(query) {
6214
+ const filtered = this.state.spans.filter(
6215
+ (r) => r.tenantId === query.tenantId && (!query.experimentId || r.experimentId === query.experimentId) && (!query.variantKey || r.variantKey === query.variantKey) && (!query.fromIso || r.atIso >= query.fromIso) && (!query.untilIso || r.atIso < query.untilIso)
6216
+ );
6217
+ const byModel = (query.groupBy ?? "kind") === "model";
6218
+ const grouped = byModel ? filtered.filter((r) => r.modelName !== null) : filtered;
6219
+ const groups = [
6220
+ ...groupBy(grouped, (r) => byModel ? r.modelName : r.kind).values()
6221
+ ].map(
6222
+ (group) => aggregateSpans(byModel ? group[0].modelName : group[0].kind, group)
6223
+ );
6224
+ groups.sort((a, b) => a.groupKey.localeCompare(b.groupKey));
6225
+ return {
6226
+ groups,
6227
+ traceCount: new Set(filtered.map((r) => r.traceId)).size,
6228
+ // Overall cost is over the full filtered set, like traceCount — NOT the
6229
+ // model-grouped subset. Pre-cost NDJSON rows read as undefined → 0.
6230
+ totalCostUsd: filtered.reduce((sum, r) => sum + (r.costUsd ?? 0), 0)
6231
+ };
6232
+ }
6233
+ async evalRunAnalytics(query) {
6234
+ const rows = this.state.evalScores.filter(
6235
+ (r) => r.tenantId === query.tenantId && r.runId === query.runId
6236
+ );
6237
+ const groups = groupBy(rows, (r) => `${r.evaluatorName}\0${r.evaluatorVersion}`);
6238
+ const evaluators = [...groups.values()].map((group) => ({
6239
+ evaluatorName: group[0].evaluatorName,
6240
+ evaluatorVersion: group[0].evaluatorVersion,
6241
+ ...aggregateScores(group),
6242
+ totalTokens: group.reduce((sum, r) => sum + r.inputTokens + r.outputTokens, 0),
6243
+ meanLatencyMs: group.length > 0 ? group.reduce((sum, r) => sum + r.latencyMs, 0) / group.length : null
6244
+ }));
6245
+ evaluators.sort(
6246
+ (a, b) => a.evaluatorName.localeCompare(b.evaluatorName) || a.evaluatorVersion.localeCompare(b.evaluatorVersion)
6247
+ );
6248
+ return { evaluators, totalItems: new Set(rows.map((r) => r.itemId)).size };
6249
+ }
6250
+ async evalsByVariant(query) {
6251
+ const rows = this.state.evalScores.filter(
6252
+ (r) => r.tenantId === query.tenantId && r.experimentId === query.experimentId && r.variantKey !== null && (!query.evaluatorName || r.evaluatorName === query.evaluatorName) && (!query.fromIso || r.atIso >= query.fromIso) && (!query.untilIso || r.atIso < query.untilIso)
6253
+ );
6254
+ const groups = groupBy(
6255
+ rows,
6256
+ (r) => `${r.variantKey}\0${r.evaluatorName}\0${r.evaluatorVersion}`
6257
+ );
6258
+ const result = [...groups.values()].map((group) => ({
6259
+ variantKey: group[0].variantKey,
6260
+ evaluatorName: group[0].evaluatorName,
6261
+ evaluatorVersion: group[0].evaluatorVersion,
6262
+ ...aggregateScores(group)
6263
+ }));
6264
+ result.sort(
6265
+ (a, b) => a.variantKey.localeCompare(b.variantKey) || a.evaluatorName.localeCompare(b.evaluatorName) || a.evaluatorVersion.localeCompare(b.evaluatorVersion)
6266
+ );
6267
+ return result;
6268
+ }
6177
6269
  async aggregate(query) {
6178
6270
  const exps = this.state.exposures.filter(
6179
6271
  (e) => e.tenantId === query.tenantId && e.experimentId === query.experimentId && (!query.fromIso || e.at >= query.fromIso) && (!query.untilIso || e.at < query.untilIso)
@@ -6277,6 +6369,71 @@ var LocalWarehouse = class {
6277
6369
  return first;
6278
6370
  }
6279
6371
  };
6372
+ function evalScoreKey(row) {
6373
+ return [row.tenantId, row.runId, row.itemId, row.evaluatorName, row.evaluatorVersion].join(
6374
+ "\0"
6375
+ );
6376
+ }
6377
+ function spanKey(row) {
6378
+ return `${row.tenantId}|${row.traceId}|${row.spanId}`;
6379
+ }
6380
+ var localWriteLocks = /* @__PURE__ */ new Map();
6381
+ async function withLocalWriteLock(path, action) {
6382
+ const previous = localWriteLocks.get(path) ?? Promise.resolve();
6383
+ let release = () => {
6384
+ };
6385
+ const current = new Promise((resolve11) => {
6386
+ release = resolve11;
6387
+ });
6388
+ const queued = previous.then(() => current);
6389
+ localWriteLocks.set(path, queued);
6390
+ await previous;
6391
+ try {
6392
+ return await action();
6393
+ } finally {
6394
+ release();
6395
+ if (localWriteLocks.get(path) === queued) localWriteLocks.delete(path);
6396
+ }
6397
+ }
6398
+ function spanDurationMs(row) {
6399
+ return Number(BigInt(row.endTimeUnixNano) - BigInt(row.startTimeUnixNano)) / 1e6;
6400
+ }
6401
+ function aggregateSpans(groupKey, group) {
6402
+ const durations = group.map(spanDurationMs).sort((a, b) => a - b);
6403
+ return {
6404
+ groupKey,
6405
+ spanCount: group.length,
6406
+ errorCount: group.filter((r) => r.status === "ERROR").length,
6407
+ meanDurationMs: durations.length > 0 ? durations.reduce((sum, d) => sum + d, 0) / durations.length : null,
6408
+ p95DurationMs: durations.length > 0 ? durations[Math.ceil(0.95 * durations.length) - 1] ?? null : null,
6409
+ totalInputTokens: group.reduce((sum, r) => sum + (r.inputTokens ?? 0), 0),
6410
+ totalOutputTokens: group.reduce((sum, r) => sum + (r.outputTokens ?? 0), 0),
6411
+ totalCostUsd: group.reduce((sum, r) => sum + (r.costUsd ?? 0), 0)
6412
+ };
6413
+ }
6414
+ function groupBy(rows, key) {
6415
+ const groups = /* @__PURE__ */ new Map();
6416
+ for (const row of rows) {
6417
+ const k = key(row);
6418
+ let group = groups.get(k);
6419
+ if (!group) {
6420
+ group = [];
6421
+ groups.set(k, group);
6422
+ }
6423
+ group.push(row);
6424
+ }
6425
+ return groups;
6426
+ }
6427
+ function aggregateScores(group) {
6428
+ const nonNull = group.map((r) => r.score).filter((s) => s !== null);
6429
+ return {
6430
+ scored: nonNull.length,
6431
+ unscored: group.length - nonNull.length,
6432
+ meanScore: nonNull.length > 0 ? nonNull.reduce((sum, s) => sum + s, 0) / nonNull.length : null,
6433
+ passCount: nonNull.filter((s) => s === 1).length,
6434
+ binary: nonNull.length > 0 && nonNull.every((s) => s === 0 || s === 1)
6435
+ };
6436
+ }
6280
6437
  async function readNdjson(path) {
6281
6438
  const fs = await import('fs/promises');
6282
6439
  try {
@@ -7704,7 +7861,9 @@ var TestRunArtifact = external_exports.object({
7704
7861
  });
7705
7862
  var CreateTestRunInput = external_exports.object({
7706
7863
  externalId: external_exports.string().min(1).max(300).optional(),
7707
- source: external_exports.enum(["bdd", "live-suite", "junit", "cli", "other"]),
7864
+ // 'eval-run' rows are written by the API itself when an eval run concludes
7865
+ // (Quality Center evidence for the evals suite) — never via testRuns.create.
7866
+ source: external_exports.enum(["bdd", "live-suite", "junit", "cli", "other", "eval-run", "databricks-mlflow"]),
7708
7867
  suite: external_exports.string().min(1).max(240),
7709
7868
  status: TestRunStatus,
7710
7869
  startedAt: external_exports.string().datetime().nullable().optional(),
@@ -7743,6 +7902,346 @@ var HarnessOperatorDefinition = external_exports.object({
7743
7902
  var HarnessOperatorListResponse = external_exports.array(HarnessOperatorDefinition);
7744
7903
  var HarnessJobInput = external_exports.record(external_exports.unknown()).default({});
7745
7904
  var HarnessJobResponse = external_exports.record(external_exports.unknown());
7905
+ var DatasetSummary = external_exports.object({
7906
+ id: external_exports.string(),
7907
+ name: external_exports.string(),
7908
+ description: external_exports.string().optional(),
7909
+ latestVersion: external_exports.number().int(),
7910
+ exampleCount: external_exports.number().int(),
7911
+ createdAtIso: external_exports.string().datetime(),
7912
+ updatedAtIso: external_exports.string().datetime()
7913
+ });
7914
+ var DatasetListResponse = external_exports.object({ datasets: external_exports.array(DatasetSummary) });
7915
+ var CreateDatasetInput = external_exports.object({
7916
+ id: external_exports.string().min(2).max(64).regex(/^[a-z][a-z0-9-]*$/),
7917
+ name: external_exports.string().min(1).max(120),
7918
+ description: external_exports.string().max(2e3).optional()
7919
+ });
7920
+ var DatasetExampleWire = external_exports.object({
7921
+ exampleId: external_exports.string().uuid(),
7922
+ input: external_exports.unknown(),
7923
+ expectedOutput: external_exports.unknown().optional(),
7924
+ metadata: external_exports.record(external_exports.unknown()).default({}),
7925
+ split: external_exports.enum(["train", "test", "validation"]).default("test")
7926
+ });
7927
+ var AddExamplesInput = external_exports.object({
7928
+ examples: external_exports.array(DatasetExampleWire).min(1).max(1e3)
7929
+ });
7930
+ var AddExamplesResponse = external_exports.object({ added: external_exports.number().int() });
7931
+ var ListExamplesInput = external_exports.object({
7932
+ version: external_exports.coerce.number().int().min(1).optional(),
7933
+ split: external_exports.enum(["train", "test", "validation"]).optional(),
7934
+ limit: external_exports.coerce.number().int().min(1).max(500).default(100),
7935
+ offset: external_exports.coerce.number().int().min(0).default(0)
7936
+ });
7937
+ var ListExamplesResponse = external_exports.object({
7938
+ examples: external_exports.array(DatasetExampleWire),
7939
+ total: external_exports.number().int()
7940
+ });
7941
+ var CreateDatasetVersionInput = external_exports.object({ note: external_exports.string().max(500).optional() });
7942
+ var DatasetVersionWire = external_exports.object({
7943
+ datasetId: external_exports.string(),
7944
+ version: external_exports.number().int(),
7945
+ exampleCount: external_exports.number().int(),
7946
+ contentHash: external_exports.string(),
7947
+ createdAtIso: external_exports.string().datetime(),
7948
+ note: external_exports.string().optional()
7949
+ });
7950
+ var DatasetVersionListResponse = external_exports.object({
7951
+ versions: external_exports.array(DatasetVersionWire)
7952
+ });
7953
+ var EvalRunTargetWire = external_exports.discriminatedUnion("kind", [
7954
+ external_exports.object({ kind: external_exports.literal("dataset"), datasetId: external_exports.string(), version: external_exports.number().int().min(1) }),
7955
+ external_exports.object({
7956
+ kind: external_exports.literal("experiment"),
7957
+ experimentId: external_exports.string(),
7958
+ metricEventName: external_exports.string().optional()
7959
+ })
7960
+ ]);
7961
+ var CreateEvalRunInput = external_exports.object({
7962
+ target: EvalRunTargetWire,
7963
+ evaluatorNames: external_exports.array(external_exports.string().min(1)).min(1).max(10),
7964
+ maxJudgeTokens: external_exports.number().int().min(0).optional(),
7965
+ /**
7966
+ * Quality Center policy for binary evaluators: the run's companion
7967
+ * fx.test_runs evidence row is `failed` when any binary evaluator's pass
7968
+ * rate lands below this threshold, even if the run itself succeeded.
7969
+ * Defaults server-side to 0.9.
7970
+ */
7971
+ passThreshold: external_exports.number().min(0).max(1).optional()
7972
+ });
7973
+ var EvalRunGenerationWire = external_exports.object({
7974
+ promptId: external_exports.string(),
7975
+ promptVersion: external_exports.number().int().min(1),
7976
+ datasetId: external_exports.string(),
7977
+ datasetVersion: external_exports.number().int().min(1),
7978
+ maxExamples: external_exports.number().int().min(1)
7979
+ });
7980
+ var EvalRunSummary = external_exports.object({
7981
+ runId: external_exports.string(),
7982
+ target: EvalRunTargetWire,
7983
+ generation: EvalRunGenerationWire.optional(),
7984
+ evaluatorNames: external_exports.array(external_exports.string()),
7985
+ status: external_exports.enum(["pending", "running", "succeeded", "failed", "cancelled"]),
7986
+ scoredExamples: external_exports.number().int(),
7987
+ totalExamples: external_exports.number().int(),
7988
+ tokensSpent: external_exports.number().int(),
7989
+ costUsd: external_exports.number().nullable(),
7990
+ passThreshold: external_exports.number(),
7991
+ createdAtIso: external_exports.string().datetime(),
7992
+ startedAtIso: external_exports.string().datetime().optional(),
7993
+ finishedAtIso: external_exports.string().datetime().optional(),
7994
+ error: external_exports.string().optional()
7995
+ });
7996
+ var EvalRunListInput = external_exports.object({
7997
+ limit: external_exports.coerce.number().int().min(1).max(200).default(50),
7998
+ offset: external_exports.coerce.number().int().min(0).default(0),
7999
+ status: external_exports.enum(["pending", "running", "succeeded", "failed", "cancelled"]).optional()
8000
+ });
8001
+ var EvalRunListResponse = external_exports.object({ runs: external_exports.array(EvalRunSummary) });
8002
+ var EvaluatorAggregateWire = external_exports.object({
8003
+ evaluatorName: external_exports.string(),
8004
+ evaluatorVersion: external_exports.string(),
8005
+ scored: external_exports.number().int(),
8006
+ unscored: external_exports.number().int(),
8007
+ meanScore: external_exports.number().nullable(),
8008
+ passRate: external_exports.object({ rate: external_exports.number(), low: external_exports.number(), high: external_exports.number() }).nullable(),
8009
+ labelCounts: external_exports.record(external_exports.number().int()),
8010
+ totalTokens: external_exports.number().int(),
8011
+ meanLatencyMs: external_exports.number().nullable()
8012
+ });
8013
+ var EvalRunDetail = external_exports.object({
8014
+ run: EvalRunSummary,
8015
+ aggregates: external_exports.array(EvaluatorAggregateWire)
8016
+ });
8017
+ var EvalScoreWire = external_exports.object({
8018
+ itemId: external_exports.string(),
8019
+ evaluatorName: external_exports.string(),
8020
+ evaluatorVersion: external_exports.string(),
8021
+ label: external_exports.string().nullable(),
8022
+ score: external_exports.number().nullable(),
8023
+ explanation: external_exports.string().nullable(),
8024
+ latencyMs: external_exports.number()
8025
+ });
8026
+ var EvalScoreListInput = external_exports.object({
8027
+ evaluatorName: external_exports.string().optional(),
8028
+ limit: external_exports.coerce.number().int().min(1).max(500).default(100),
8029
+ offset: external_exports.coerce.number().int().min(0).default(0)
8030
+ });
8031
+ var EvalScoreListResponse = external_exports.object({
8032
+ scores: external_exports.array(EvalScoreWire),
8033
+ total: external_exports.number().int()
8034
+ });
8035
+ var PromptMessageWire = external_exports.object({
8036
+ role: external_exports.enum(["system", "user", "assistant"]),
8037
+ content: external_exports.string().min(1).max(1e5)
8038
+ });
8039
+ var PromptTemplateWire = external_exports.object({
8040
+ messages: external_exports.array(PromptMessageWire).min(1).max(50),
8041
+ params: external_exports.object({
8042
+ model: external_exports.string().max(256).optional(),
8043
+ temperature: external_exports.number().min(0).max(2).optional(),
8044
+ maxTokens: external_exports.number().int().min(1).max(2e5).optional(),
8045
+ topP: external_exports.number().min(0).max(1).optional()
8046
+ }).default({})
8047
+ });
8048
+ var PromptSummary = external_exports.object({
8049
+ id: external_exports.string(),
8050
+ name: external_exports.string(),
8051
+ description: external_exports.string().optional(),
8052
+ latestVersion: external_exports.number().int(),
8053
+ createdAtIso: external_exports.string().datetime(),
8054
+ updatedAtIso: external_exports.string().datetime()
8055
+ });
8056
+ var PromptListResponse = external_exports.object({ prompts: external_exports.array(PromptSummary) });
8057
+ var CreatePromptInput = external_exports.object({
8058
+ id: external_exports.string().min(2).max(64).regex(/^[a-z][a-z0-9-]*$/),
8059
+ name: external_exports.string().min(1).max(120),
8060
+ description: external_exports.string().max(2e3).optional()
8061
+ });
8062
+ var PromptVersionWire = external_exports.object({
8063
+ promptId: external_exports.string(),
8064
+ version: external_exports.number().int(),
8065
+ template: PromptTemplateWire,
8066
+ contentHash: external_exports.string(),
8067
+ variables: external_exports.array(external_exports.string()),
8068
+ createdAtIso: external_exports.string().datetime(),
8069
+ note: external_exports.string().optional()
8070
+ });
8071
+ var CreatePromptVersionInput = external_exports.object({
8072
+ template: PromptTemplateWire,
8073
+ note: external_exports.string().max(500).optional()
8074
+ });
8075
+ var PromptVersionListResponse = external_exports.object({
8076
+ versions: external_exports.array(PromptVersionWire)
8077
+ });
8078
+ var PlaygroundInvokeInput = external_exports.object({
8079
+ /** Registry reference (promptId + optional version, defaulting to latest)... */
8080
+ promptId: external_exports.string().optional(),
8081
+ version: external_exports.number().int().min(1).optional(),
8082
+ /** ...or an inline template (draft mode). Exactly one source is required. */
8083
+ template: PromptTemplateWire.optional(),
8084
+ variables: external_exports.record(external_exports.string()).default({})
8085
+ });
8086
+ var PlaygroundInvokeResponse = external_exports.object({
8087
+ messages: external_exports.array(PromptMessageWire),
8088
+ missingVariables: external_exports.array(external_exports.string()),
8089
+ text: external_exports.string(),
8090
+ inputTokens: external_exports.number().int(),
8091
+ outputTokens: external_exports.number().int(),
8092
+ latencyMs: external_exports.number(),
8093
+ modelEndpoint: external_exports.string(),
8094
+ /** Manifest cost of this invocation; null when the endpoint is unpriced. */
8095
+ costUsd: external_exports.number().nullable()
8096
+ });
8097
+ var PlaygroundReplayInput = external_exports.object({
8098
+ promptId: external_exports.string(),
8099
+ version: external_exports.number().int().min(1),
8100
+ datasetId: external_exports.string(),
8101
+ datasetVersion: external_exports.number().int().min(1),
8102
+ evaluatorNames: external_exports.array(external_exports.string().min(1)).min(1).max(10),
8103
+ /** Shared budget: generation AND judge tokens both count against it. */
8104
+ maxJudgeTokens: external_exports.number().int().min(0).optional(),
8105
+ /** Cap on examples replayed through the model. */
8106
+ maxExamples: external_exports.number().int().min(1).max(200).default(50)
8107
+ });
8108
+ var VariantEvalWire = external_exports.object({
8109
+ variantKey: external_exports.string(),
8110
+ evaluatorName: external_exports.string(),
8111
+ evaluatorVersion: external_exports.string(),
8112
+ scored: external_exports.number().int(),
8113
+ unscored: external_exports.number().int(),
8114
+ meanScore: external_exports.number().nullable(),
8115
+ passCount: external_exports.number().int(),
8116
+ binary: external_exports.boolean()
8117
+ });
8118
+ var VariantEvalListResponse = external_exports.object({ variants: external_exports.array(VariantEvalWire) });
8119
+ var SpanKindWire = external_exports.enum([
8120
+ "LLM",
8121
+ "CHAIN",
8122
+ "RETRIEVER",
8123
+ "EMBEDDING",
8124
+ "TOOL",
8125
+ "AGENT",
8126
+ "RERANKER",
8127
+ "GUARDRAIL",
8128
+ "EVALUATOR",
8129
+ "UNKNOWN"
8130
+ ]);
8131
+ var TraceSummaryWire = external_exports.object({
8132
+ traceId: external_exports.string(),
8133
+ rootSpanName: external_exports.string(),
8134
+ rootSpanKind: SpanKindWire,
8135
+ sessionId: external_exports.string().nullable(),
8136
+ experimentId: external_exports.string().nullable(),
8137
+ variantKey: external_exports.string().nullable(),
8138
+ startedAtIso: external_exports.string().datetime(),
8139
+ durationMs: external_exports.number(),
8140
+ spanCount: external_exports.number().int(),
8141
+ errorCount: external_exports.number().int(),
8142
+ totalInputTokens: external_exports.number().int(),
8143
+ totalOutputTokens: external_exports.number().int()
8144
+ });
8145
+ var TraceListInput = external_exports.object({
8146
+ experimentId: external_exports.string().optional(),
8147
+ variantKey: external_exports.string().optional(),
8148
+ sessionId: external_exports.string().optional(),
8149
+ kind: SpanKindWire.optional(),
8150
+ errorsOnly: external_exports.coerce.boolean().optional(),
8151
+ fromIso: external_exports.string().datetime().optional(),
8152
+ untilIso: external_exports.string().datetime().optional(),
8153
+ limit: external_exports.coerce.number().int().min(1).max(200).default(50),
8154
+ offset: external_exports.coerce.number().int().min(0).default(0)
8155
+ });
8156
+ var TraceListResponse = external_exports.object({
8157
+ traces: external_exports.array(TraceSummaryWire),
8158
+ total: external_exports.number().int()
8159
+ });
8160
+ var SessionTraceWire = TraceSummaryWire.extend({
8161
+ rootInputValue: external_exports.string().nullable(),
8162
+ rootOutputValue: external_exports.string().nullable()
8163
+ });
8164
+ var SessionDetailResponse = external_exports.object({
8165
+ sessionId: external_exports.string(),
8166
+ /** Conversation order: ascending by trace start time. */
8167
+ traces: external_exports.array(SessionTraceWire)
8168
+ });
8169
+ var SpanWire = external_exports.object({
8170
+ traceId: external_exports.string(),
8171
+ spanId: external_exports.string(),
8172
+ parentSpanId: external_exports.string().nullable(),
8173
+ name: external_exports.string(),
8174
+ kind: SpanKindWire,
8175
+ startedAtIso: external_exports.string().datetime(),
8176
+ durationMs: external_exports.number(),
8177
+ status: external_exports.enum(["UNSET", "OK", "ERROR"]),
8178
+ statusMessage: external_exports.string().nullable(),
8179
+ sessionId: external_exports.string().nullable(),
8180
+ experimentId: external_exports.string().nullable(),
8181
+ variantKey: external_exports.string().nullable(),
8182
+ inputValue: external_exports.string().nullable(),
8183
+ outputValue: external_exports.string().nullable(),
8184
+ inputTokens: external_exports.number().int().nullable(),
8185
+ outputTokens: external_exports.number().int().nullable(),
8186
+ modelName: external_exports.string().nullable(),
8187
+ /** Ingest-time dollar cost from the model-cost manifest; null when unpriceable. */
8188
+ costUsd: external_exports.number().nullable(),
8189
+ attributes: external_exports.record(external_exports.unknown())
8190
+ });
8191
+ var SpanAnnotationWire = external_exports.object({
8192
+ spanId: external_exports.string(),
8193
+ annotator: external_exports.enum(["human", "llm"]),
8194
+ /** Evaluator name for llm annotations; user id for human ones. */
8195
+ annotatorId: external_exports.string(),
8196
+ label: external_exports.string().nullable(),
8197
+ score: external_exports.number().nullable(),
8198
+ explanation: external_exports.string().nullable(),
8199
+ createdAtIso: external_exports.string().datetime()
8200
+ });
8201
+ var TraceDetail = external_exports.object({
8202
+ traceId: external_exports.string(),
8203
+ spans: external_exports.array(SpanWire),
8204
+ annotations: external_exports.array(SpanAnnotationWire)
8205
+ });
8206
+ var AnnotateSpanInput = external_exports.object({
8207
+ spanId: external_exports.string(),
8208
+ label: external_exports.string().max(64).optional(),
8209
+ score: external_exports.number().min(0).max(1).optional(),
8210
+ explanation: external_exports.string().max(1e4).optional()
8211
+ });
8212
+ var SpanAnalyticsInput = external_exports.object({
8213
+ experimentId: external_exports.string().optional(),
8214
+ variantKey: external_exports.string().optional(),
8215
+ groupBy: external_exports.enum(["kind", "model"]).default("kind"),
8216
+ fromIso: external_exports.string().datetime().optional(),
8217
+ untilIso: external_exports.string().datetime().optional()
8218
+ });
8219
+ var SpanAnalyticsResponse = external_exports.object({
8220
+ groups: external_exports.array(
8221
+ external_exports.object({
8222
+ groupKey: external_exports.string(),
8223
+ spanCount: external_exports.number().int(),
8224
+ errorCount: external_exports.number().int(),
8225
+ meanDurationMs: external_exports.number().nullable(),
8226
+ p95DurationMs: external_exports.number().nullable(),
8227
+ totalInputTokens: external_exports.number().int(),
8228
+ totalOutputTokens: external_exports.number().int(),
8229
+ totalCostUsd: external_exports.number()
8230
+ })
8231
+ ),
8232
+ traceCount: external_exports.number().int(),
8233
+ /** Cost over the full filtered span set — NOT restricted by groupBy model. */
8234
+ totalCostUsd: external_exports.number()
8235
+ });
8236
+ var IngestTokenSummary = external_exports.object({
8237
+ tokenId: external_exports.string(),
8238
+ label: external_exports.string(),
8239
+ createdAtIso: external_exports.string().datetime(),
8240
+ revokedAtIso: external_exports.string().datetime().nullable()
8241
+ });
8242
+ var IngestTokenListResponse = external_exports.object({ tokens: external_exports.array(IngestTokenSummary) });
8243
+ var CreateIngestTokenInput = external_exports.object({ label: external_exports.string().min(1).max(120) });
8244
+ var CreatedIngestToken = IngestTokenSummary.extend({ token: external_exports.string() });
7746
8245
  var endpoints = {
7747
8246
  "tenants.me": {
7748
8247
  method: "GET",
@@ -8056,6 +8555,232 @@ var endpoints = {
8056
8555
  mutates: false,
8057
8556
  requiresRole: "viewer"
8058
8557
  },
8558
+ "datasets.list": {
8559
+ method: "GET",
8560
+ path: "/v1/orgs/:orgId/datasets",
8561
+ params: Empty,
8562
+ response: DatasetListResponse,
8563
+ mutates: false,
8564
+ requiresRole: "viewer"
8565
+ },
8566
+ "datasets.create": {
8567
+ method: "POST",
8568
+ path: "/v1/orgs/:orgId/datasets",
8569
+ params: CreateDatasetInput,
8570
+ response: DatasetSummary,
8571
+ mutates: true,
8572
+ requiresRole: "experimenter"
8573
+ },
8574
+ "datasets.get": {
8575
+ method: "GET",
8576
+ path: "/v1/orgs/:orgId/datasets/:datasetId",
8577
+ params: Empty,
8578
+ response: DatasetSummary,
8579
+ mutates: false,
8580
+ requiresRole: "viewer"
8581
+ },
8582
+ "datasets.addExamples": {
8583
+ method: "POST",
8584
+ path: "/v1/orgs/:orgId/datasets/:datasetId/examples",
8585
+ params: AddExamplesInput,
8586
+ response: AddExamplesResponse,
8587
+ mutates: true,
8588
+ requiresRole: "experimenter"
8589
+ },
8590
+ "datasets.listExamples": {
8591
+ method: "GET",
8592
+ path: "/v1/orgs/:orgId/datasets/:datasetId/examples",
8593
+ params: ListExamplesInput,
8594
+ response: ListExamplesResponse,
8595
+ mutates: false,
8596
+ requiresRole: "viewer"
8597
+ },
8598
+ "datasets.createVersion": {
8599
+ method: "POST",
8600
+ path: "/v1/orgs/:orgId/datasets/:datasetId/versions",
8601
+ params: CreateDatasetVersionInput,
8602
+ response: DatasetVersionWire,
8603
+ mutates: true,
8604
+ requiresRole: "experimenter"
8605
+ },
8606
+ "datasets.listVersions": {
8607
+ method: "GET",
8608
+ path: "/v1/orgs/:orgId/datasets/:datasetId/versions",
8609
+ params: Empty,
8610
+ response: DatasetVersionListResponse,
8611
+ mutates: false,
8612
+ requiresRole: "viewer"
8613
+ },
8614
+ "traces.list": {
8615
+ method: "GET",
8616
+ path: "/v1/orgs/:orgId/traces",
8617
+ params: TraceListInput,
8618
+ response: TraceListResponse,
8619
+ mutates: false,
8620
+ requiresRole: "viewer"
8621
+ },
8622
+ "traces.get": {
8623
+ method: "GET",
8624
+ path: "/v1/orgs/:orgId/traces/:traceId",
8625
+ params: Empty,
8626
+ response: TraceDetail,
8627
+ mutates: false,
8628
+ requiresRole: "viewer"
8629
+ },
8630
+ "traces.annotate": {
8631
+ method: "POST",
8632
+ path: "/v1/orgs/:orgId/traces/:traceId/annotations",
8633
+ params: AnnotateSpanInput,
8634
+ response: SpanAnnotationWire,
8635
+ mutates: true,
8636
+ requiresRole: "experimenter"
8637
+ },
8638
+ "traces.analytics": {
8639
+ method: "GET",
8640
+ path: "/v1/orgs/:orgId/traces/analytics",
8641
+ params: SpanAnalyticsInput,
8642
+ response: SpanAnalyticsResponse,
8643
+ mutates: false,
8644
+ requiresRole: "viewer"
8645
+ },
8646
+ "traces.session": {
8647
+ method: "GET",
8648
+ path: "/v1/orgs/:orgId/traces/sessions/:sessionId",
8649
+ params: Empty,
8650
+ response: SessionDetailResponse,
8651
+ mutates: false,
8652
+ requiresRole: "viewer"
8653
+ },
8654
+ "evals.createRun": {
8655
+ method: "POST",
8656
+ path: "/v1/orgs/:orgId/evals/runs",
8657
+ params: CreateEvalRunInput,
8658
+ response: EvalRunSummary,
8659
+ mutates: true,
8660
+ requiresRole: "experimenter"
8661
+ },
8662
+ "evals.listRuns": {
8663
+ method: "GET",
8664
+ path: "/v1/orgs/:orgId/evals/runs",
8665
+ params: EvalRunListInput,
8666
+ response: EvalRunListResponse,
8667
+ mutates: false,
8668
+ requiresRole: "viewer"
8669
+ },
8670
+ "evals.getRun": {
8671
+ method: "GET",
8672
+ path: "/v1/orgs/:orgId/evals/runs/:runId",
8673
+ params: Empty,
8674
+ response: EvalRunDetail,
8675
+ mutates: false,
8676
+ requiresRole: "viewer"
8677
+ },
8678
+ "evals.listScores": {
8679
+ method: "GET",
8680
+ path: "/v1/orgs/:orgId/evals/runs/:runId/scores",
8681
+ params: EvalScoreListInput,
8682
+ response: EvalScoreListResponse,
8683
+ mutates: false,
8684
+ requiresRole: "viewer"
8685
+ },
8686
+ "evals.cancelRun": {
8687
+ method: "POST",
8688
+ path: "/v1/orgs/:orgId/evals/runs/:runId/cancel",
8689
+ params: Empty,
8690
+ response: EvalRunSummary,
8691
+ mutates: true,
8692
+ requiresRole: "experimenter"
8693
+ },
8694
+ "evals.byVariant": {
8695
+ method: "GET",
8696
+ path: "/v1/orgs/:orgId/experiments/:experimentId/evals",
8697
+ params: Empty,
8698
+ response: VariantEvalListResponse,
8699
+ mutates: false,
8700
+ requiresRole: "viewer"
8701
+ },
8702
+ "ingestTokens.list": {
8703
+ method: "GET",
8704
+ path: "/v1/orgs/:orgId/ingest-tokens",
8705
+ params: Empty,
8706
+ response: IngestTokenListResponse,
8707
+ mutates: false,
8708
+ requiresRole: "admin"
8709
+ },
8710
+ "ingestTokens.create": {
8711
+ method: "POST",
8712
+ path: "/v1/orgs/:orgId/ingest-tokens",
8713
+ params: CreateIngestTokenInput,
8714
+ response: CreatedIngestToken,
8715
+ mutates: true,
8716
+ requiresRole: "admin"
8717
+ },
8718
+ "ingestTokens.revoke": {
8719
+ method: "POST",
8720
+ path: "/v1/orgs/:orgId/ingest-tokens/:tokenId/revoke",
8721
+ params: Empty,
8722
+ response: IngestTokenSummary,
8723
+ mutates: true,
8724
+ requiresRole: "admin"
8725
+ },
8726
+ "prompts.list": {
8727
+ method: "GET",
8728
+ path: "/v1/orgs/:orgId/prompts",
8729
+ params: Empty,
8730
+ response: PromptListResponse,
8731
+ mutates: false,
8732
+ requiresRole: "viewer"
8733
+ },
8734
+ "prompts.create": {
8735
+ method: "POST",
8736
+ path: "/v1/orgs/:orgId/prompts",
8737
+ params: CreatePromptInput,
8738
+ response: PromptSummary,
8739
+ mutates: true,
8740
+ requiresRole: "experimenter"
8741
+ },
8742
+ "prompts.get": {
8743
+ method: "GET",
8744
+ path: "/v1/orgs/:orgId/prompts/:promptId",
8745
+ params: Empty,
8746
+ response: PromptSummary,
8747
+ mutates: false,
8748
+ requiresRole: "viewer"
8749
+ },
8750
+ "prompts.createVersion": {
8751
+ method: "POST",
8752
+ path: "/v1/orgs/:orgId/prompts/:promptId/versions",
8753
+ params: CreatePromptVersionInput,
8754
+ response: PromptVersionWire,
8755
+ mutates: true,
8756
+ requiresRole: "experimenter"
8757
+ },
8758
+ "prompts.listVersions": {
8759
+ method: "GET",
8760
+ path: "/v1/orgs/:orgId/prompts/:promptId/versions",
8761
+ params: Empty,
8762
+ response: PromptVersionListResponse,
8763
+ mutates: false,
8764
+ requiresRole: "viewer"
8765
+ },
8766
+ "playground.invoke": {
8767
+ method: "POST",
8768
+ path: "/v1/orgs/:orgId/playground/invoke",
8769
+ params: PlaygroundInvokeInput,
8770
+ response: PlaygroundInvokeResponse,
8771
+ mutates: false,
8772
+ requiresRole: "experimenter"
8773
+ },
8774
+ // 202-style: replay only creates a pending eval run (durable via the
8775
+ // outbox); generation + judging happen in the executor, off the request.
8776
+ "playground.replay": {
8777
+ method: "POST",
8778
+ path: "/v1/orgs/:orgId/playground/replay",
8779
+ params: PlaygroundReplayInput,
8780
+ response: EvalRunSummary,
8781
+ mutates: true,
8782
+ requiresRole: "experimenter"
8783
+ },
8059
8784
  "harness.definitions": {
8060
8785
  method: "GET",
8061
8786
  path: "/v1/orgs/:orgId/harness/admin/agents",
@@ -8252,6 +8977,46 @@ var ApiClient = class {
8252
8977
  get: (orgId) => this.call("saml.get", {}, orgId ? { orgId } : void 0),
8253
8978
  update: (params, orgId) => this.call("saml.update", params, orgId ? { orgId } : void 0)
8254
8979
  };
8980
+ datasets = {
8981
+ list: (orgId) => this.call("datasets.list", {}, orgId ? { orgId } : void 0),
8982
+ create: (params, orgId) => this.call("datasets.create", params, orgId ? { orgId } : void 0),
8983
+ get: (datasetId, orgId) => this.call("datasets.get", {}, orgId ? { orgId, datasetId } : { datasetId }),
8984
+ addExamples: (datasetId, params, orgId) => this.call("datasets.addExamples", params, orgId ? { orgId, datasetId } : { datasetId }),
8985
+ listExamples: (datasetId, params, orgId) => this.call("datasets.listExamples", params, orgId ? { orgId, datasetId } : { datasetId }),
8986
+ createVersion: (datasetId, params, orgId) => this.call("datasets.createVersion", params, orgId ? { orgId, datasetId } : { datasetId }),
8987
+ listVersions: (datasetId, orgId) => this.call("datasets.listVersions", {}, orgId ? { orgId, datasetId } : { datasetId })
8988
+ };
8989
+ evals = {
8990
+ createRun: (params, orgId) => this.call("evals.createRun", params, orgId ? { orgId } : void 0),
8991
+ listRuns: (params, orgId) => this.call("evals.listRuns", params, orgId ? { orgId } : void 0),
8992
+ getRun: (runId, orgId) => this.call("evals.getRun", {}, orgId ? { orgId, runId } : { runId }),
8993
+ listScores: (runId, params, orgId) => this.call("evals.listScores", params, orgId ? { orgId, runId } : { runId }),
8994
+ cancelRun: (runId, orgId) => this.call("evals.cancelRun", {}, orgId ? { orgId, runId } : { runId }),
8995
+ byVariant: (experimentId, orgId) => this.call("evals.byVariant", {}, orgId ? { orgId, experimentId } : { experimentId })
8996
+ };
8997
+ traces = {
8998
+ list: (params, orgId) => this.call("traces.list", params, orgId ? { orgId } : void 0),
8999
+ get: (traceId, orgId) => this.call("traces.get", {}, orgId ? { orgId, traceId } : { traceId }),
9000
+ annotate: (traceId, params, orgId) => this.call("traces.annotate", params, orgId ? { orgId, traceId } : { traceId }),
9001
+ analytics: (params, orgId) => this.call("traces.analytics", params, orgId ? { orgId } : void 0),
9002
+ session: (sessionId, orgId) => this.call("traces.session", {}, orgId ? { orgId, sessionId } : { sessionId })
9003
+ };
9004
+ ingestTokens = {
9005
+ list: (orgId) => this.call("ingestTokens.list", {}, orgId ? { orgId } : void 0),
9006
+ create: (params, orgId) => this.call("ingestTokens.create", params, orgId ? { orgId } : void 0),
9007
+ revoke: (tokenId, orgId) => this.call("ingestTokens.revoke", {}, orgId ? { orgId, tokenId } : { tokenId })
9008
+ };
9009
+ prompts = {
9010
+ list: (orgId) => this.call("prompts.list", {}, orgId ? { orgId } : void 0),
9011
+ create: (params, orgId) => this.call("prompts.create", params, orgId ? { orgId } : void 0),
9012
+ get: (promptId, orgId) => this.call("prompts.get", {}, orgId ? { orgId, promptId } : { promptId }),
9013
+ createVersion: (promptId, params, orgId) => this.call("prompts.createVersion", params, orgId ? { orgId, promptId } : { promptId }),
9014
+ listVersions: (promptId, orgId) => this.call("prompts.listVersions", {}, orgId ? { orgId, promptId } : { promptId })
9015
+ };
9016
+ playground = {
9017
+ invoke: (params, orgId) => this.call("playground.invoke", params, orgId ? { orgId } : void 0),
9018
+ replay: (params, orgId) => this.call("playground.replay", params, orgId ? { orgId } : void 0)
9019
+ };
8255
9020
  testRuns = {
8256
9021
  list: (params = {}, orgId) => this.call("testRuns.list", params, orgId ? { orgId } : void 0),
8257
9022
  get: (runId, orgId) => this.call("testRuns.get", {}, orgId ? { orgId, runId } : { runId }),
@@ -9658,6 +10423,295 @@ function parseInput(value) {
9658
10423
  return parsed;
9659
10424
  }
9660
10425
 
10426
+ // ../evals/dist/databricks.js
10427
+ var DatabricksBearerProvider = class {
10428
+ host;
10429
+ auth;
10430
+ fetchImpl;
10431
+ timeoutMs;
10432
+ oauthToken = null;
10433
+ constructor(config) {
10434
+ this.host = normalizeDatabricksHost(config.host);
10435
+ this.auth = config.auth;
10436
+ this.fetchImpl = config.fetchImpl ?? fetch;
10437
+ this.timeoutMs = config.timeoutMs ?? 6e4;
10438
+ if (!Number.isFinite(this.timeoutMs) || this.timeoutMs <= 0) {
10439
+ throw new Error("Databricks timeoutMs must be positive");
10440
+ }
10441
+ }
10442
+ async token() {
10443
+ if (this.auth.kind === "pat") return this.auth.token;
10444
+ if (this.oauthToken && this.oauthToken.expiresAt > Date.now() + 6e4) {
10445
+ return this.oauthToken.value;
10446
+ }
10447
+ const response = await this.fetchImpl(`${this.host}/oidc/v1/token`, {
10448
+ method: "POST",
10449
+ headers: {
10450
+ authorization: `Basic ${toBase64(`${this.auth.clientId}:${this.auth.clientSecret}`)}`,
10451
+ "content-type": "application/x-www-form-urlencoded"
10452
+ },
10453
+ body: new URLSearchParams({ grant_type: "client_credentials", scope: "all-apis" }),
10454
+ signal: AbortSignal.timeout(this.timeoutMs)
10455
+ });
10456
+ if (!response.ok) throw new Error(`Databricks OAuth exchange failed (${response.status})`);
10457
+ const body = await response.json();
10458
+ if (!body.access_token) throw new Error("Databricks OAuth exchange returned no access token");
10459
+ this.oauthToken = {
10460
+ value: body.access_token,
10461
+ expiresAt: Date.now() + (body.expires_in ?? 3600) * 1e3
10462
+ };
10463
+ return this.oauthToken.value;
10464
+ }
10465
+ };
10466
+ function normalizeDatabricksHost(host) {
10467
+ return host.startsWith("http://") || host.startsWith("https://") ? host.replace(/\/$/, "") : `https://${host.replace(/\/$/, "")}`;
10468
+ }
10469
+ function toBase64(value) {
10470
+ if (typeof Buffer !== "undefined") return Buffer.from(value).toString("base64");
10471
+ return btoa(value);
10472
+ }
10473
+ var MlflowMetric = external_exports.object({
10474
+ key: external_exports.string().min(1),
10475
+ value: external_exports.number(),
10476
+ timestamp: external_exports.number().optional(),
10477
+ step: external_exports.number().optional()
10478
+ });
10479
+ var MlflowRunResponse = external_exports.object({
10480
+ run: external_exports.object({
10481
+ info: external_exports.object({
10482
+ run_id: external_exports.string().min(1),
10483
+ experiment_id: external_exports.string().min(1),
10484
+ status: external_exports.string().min(1),
10485
+ start_time: external_exports.number().optional(),
10486
+ end_time: external_exports.number().optional(),
10487
+ artifact_uri: external_exports.string().optional(),
10488
+ run_name: external_exports.string().optional()
10489
+ }),
10490
+ data: external_exports.object({
10491
+ metrics: external_exports.array(MlflowMetric).default([]),
10492
+ params: external_exports.array(external_exports.object({ key: external_exports.string(), value: external_exports.string() })).default([]),
10493
+ tags: external_exports.array(external_exports.object({ key: external_exports.string(), value: external_exports.string() })).default([])
10494
+ }).default({ metrics: [], params: [], tags: [] })
10495
+ })
10496
+ });
10497
+ var DatabricksMlflowClient = class {
10498
+ host;
10499
+ authMode;
10500
+ fetchImpl;
10501
+ timeoutMs;
10502
+ bearer;
10503
+ constructor(config) {
10504
+ this.host = normalizeDatabricksHost(config.host);
10505
+ this.authMode = config.auth.kind;
10506
+ this.fetchImpl = config.fetchImpl ?? fetch;
10507
+ this.timeoutMs = config.timeoutMs ?? 6e4;
10508
+ if (!Number.isFinite(this.timeoutMs) || this.timeoutMs <= 0) {
10509
+ throw new Error("Databricks MLflow timeoutMs must be positive");
10510
+ }
10511
+ this.bearer = new DatabricksBearerProvider({
10512
+ host: this.host,
10513
+ auth: config.auth,
10514
+ fetchImpl: this.fetchImpl,
10515
+ timeoutMs: this.timeoutMs
10516
+ });
10517
+ }
10518
+ async getRun(runId) {
10519
+ if (!runId.trim()) throw new Error("MLflow runId is required");
10520
+ const url = new URL(`${this.host}/api/2.0/mlflow/runs/get`);
10521
+ url.searchParams.set("run_id", runId);
10522
+ const response = await this.fetchImpl(url, {
10523
+ headers: { authorization: `Bearer ${await this.bearer.token()}` },
10524
+ signal: AbortSignal.timeout(this.timeoutMs)
10525
+ });
10526
+ if (!response.ok) {
10527
+ const body = await response.text();
10528
+ throw new Error(
10529
+ `Databricks MLflow run lookup failed (${response.status}): ${body.slice(0, 500)}`
10530
+ );
10531
+ }
10532
+ const parsed = MlflowRunResponse.safeParse(await response.json());
10533
+ if (!parsed.success) {
10534
+ throw new Error(
10535
+ `Databricks MLflow returned an invalid run: ${parsed.error.issues[0]?.message ?? "schema mismatch"}`
10536
+ );
10537
+ }
10538
+ return parsed.data.run;
10539
+ }
10540
+ runUrl(run) {
10541
+ return `${this.host}/ml/experiments/${encodeURIComponent(run.info.experiment_id)}/runs/${encodeURIComponent(run.info.run_id)}`;
10542
+ }
10543
+ };
10544
+ function parseMlflowMetricGates(value) {
10545
+ const entries = value.split(",").map((entry) => entry.trim()).filter(Boolean);
10546
+ if (entries.length === 0) throw new Error("At least one MLflow metric gate is required");
10547
+ return entries.map((entry) => {
10548
+ const match = /^(.+?)(>=|<=|==|!=|>|<)(-?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?)$/i.exec(entry);
10549
+ if (!match) throw new Error(`Invalid MLflow metric gate '${entry}'`);
10550
+ const metric = match[1].trim();
10551
+ if (!metric) throw new Error(`Invalid MLflow metric gate '${entry}'`);
10552
+ return {
10553
+ metric,
10554
+ operator: match[2],
10555
+ threshold: Number(match[3])
10556
+ };
10557
+ });
10558
+ }
10559
+ function evaluateMlflowMetricGates(run, gates) {
10560
+ const metrics = new Map(run.data.metrics.map((metric) => [metric.key, metric.value]));
10561
+ return gates.map((gate) => {
10562
+ const actual = metrics.get(gate.metric) ?? null;
10563
+ return {
10564
+ ...gate,
10565
+ actual,
10566
+ passed: actual === null ? false : compare(actual, gate.operator, gate.threshold),
10567
+ ...actual === null ? { reason: "missing-metric" } : {}
10568
+ };
10569
+ });
10570
+ }
10571
+ function compare(actual, operator, threshold) {
10572
+ switch (operator) {
10573
+ case ">=":
10574
+ return actual >= threshold;
10575
+ case ">":
10576
+ return actual > threshold;
10577
+ case "<=":
10578
+ return actual <= threshold;
10579
+ case "<":
10580
+ return actual < threshold;
10581
+ case "==":
10582
+ return actual === threshold;
10583
+ case "!=":
10584
+ return actual !== threshold;
10585
+ }
10586
+ }
10587
+
10588
+ // src/commands/import-mlflow.ts
10589
+ async function cmdImportMlflow(runId, options = {}) {
10590
+ const env = options.env ?? process.env;
10591
+ const apiUrl = options.apiUrl ?? env.FX_API_URL;
10592
+ const apiKey = options.apiKey ?? env.FX_API_KEY;
10593
+ const tenantId = options.tenantId ?? env.FX_ORG_ID;
10594
+ const workspaceHost = options.workspaceHost ?? env.DATABRICKS_HOST;
10595
+ const gatesText = options.gates ?? env.FX_MLFLOW_GATES;
10596
+ if (!apiUrl || !apiKey || !tenantId || !workspaceHost || !gatesText) {
10597
+ process.stderr.write(
10598
+ 'Usage: fx test import-mlflow <run-id> --workspace-host <url> --gates "accuracy>=0.9" [hosted profile flags]\n'
10599
+ );
10600
+ return 1;
10601
+ }
10602
+ const auth = resolveDatabricksAuth(env);
10603
+ const client = new DatabricksMlflowClient({
10604
+ host: workspaceHost,
10605
+ auth,
10606
+ fetchImpl: options.fetchImpl
10607
+ });
10608
+ const run = await client.getRun(runId);
10609
+ if (run.info.run_id !== runId) {
10610
+ throw new Error(`Databricks returned MLflow run ${run.info.run_id}, expected ${runId}`);
10611
+ }
10612
+ const nativeRunUrl = client.runUrl(run);
10613
+ const input = mlflowRunToQualityEvidence(run, {
10614
+ gates: gatesText,
10615
+ workspaceHost: client.host,
10616
+ nativeRunUrl,
10617
+ suite: options.suite,
10618
+ externalId: options.externalId
10619
+ });
10620
+ const api = new ApiClient({
10621
+ baseUrl: apiUrl,
10622
+ apiKey,
10623
+ fetchImpl: options.fetchImpl,
10624
+ ...options.bearerToken ? { bearerToken: options.bearerToken } : {},
10625
+ defaultOrgId: tenantId
10626
+ });
10627
+ const created = await api.testRuns.create(input);
10628
+ process.stdout.write(
10629
+ `Linked Databricks MLflow run ${runId} to Quality Center: ${created.status} (${created.summary.passed}/${created.summary.total} gates passed)
10630
+ `
10631
+ );
10632
+ return created.status === "failed" ? 2 : 0;
10633
+ }
10634
+ function mlflowRunToQualityEvidence(run, options) {
10635
+ const gateResults = evaluateMlflowMetricGates(run, parseMlflowMetricGates(options.gates));
10636
+ const nativeStatus = run.info.status.toUpperCase();
10637
+ const terminalFailure = ["FAILED", "KILLED"].includes(nativeStatus);
10638
+ const stillRunning = ["RUNNING", "SCHEDULED"].includes(nativeStatus);
10639
+ const cases = gateResults.map(
10640
+ (gate) => ({
10641
+ id: `mlflow:${run.info.run_id}:${gate.metric}`,
10642
+ name: `${gate.metric} ${gate.operator} ${gate.threshold}`,
10643
+ status: gate.passed ? "passed" : "failed",
10644
+ durationMs: 0,
10645
+ tags: ["databricks", "mlflow", "native-evaluation"],
10646
+ resourceUrl: options.nativeRunUrl,
10647
+ ...gate.reason ? { error: `Native MLflow metric '${gate.metric}' was not recorded on this run` } : {},
10648
+ details: {
10649
+ metric: gate.metric,
10650
+ operator: gate.operator,
10651
+ threshold: gate.threshold,
10652
+ actual: gate.actual,
10653
+ mlflowRunId: run.info.run_id,
10654
+ mlflowExperimentId: run.info.experiment_id
10655
+ }
10656
+ })
10657
+ );
10658
+ const passed = cases.filter((item) => item.status === "passed").length;
10659
+ const failed = cases.length - passed;
10660
+ const startedAt = millisToIso(run.info.start_time);
10661
+ const finishedAt = millisToIso(run.info.end_time);
10662
+ return {
10663
+ externalId: options.externalId ?? `databricks-mlflow:${run.info.run_id}`,
10664
+ source: "databricks-mlflow",
10665
+ suite: options.suite ?? run.info.run_name ?? "Databricks MLflow evaluation",
10666
+ status: stillRunning ? "running" : terminalFailure || failed > 0 ? "failed" : "passed",
10667
+ startedAt,
10668
+ finishedAt,
10669
+ durationMs: startedAt && finishedAt ? Math.max(0, new Date(finishedAt).getTime() - new Date(startedAt).getTime()) : 0,
10670
+ summary: {
10671
+ total: cases.length,
10672
+ passed,
10673
+ failed,
10674
+ skipped: 0,
10675
+ pending: stillRunning ? cases.length : 0
10676
+ },
10677
+ environment: {
10678
+ platform: "databricks",
10679
+ nativeSystem: "managed-mlflow",
10680
+ workspace: options.workspaceHost,
10681
+ mlflowExperimentId: run.info.experiment_id,
10682
+ mlflowRunId: run.info.run_id,
10683
+ mlflowRunStatus: run.info.status,
10684
+ nativeRunUrl: options.nativeRunUrl,
10685
+ evidenceOwnership: "databricks"
10686
+ },
10687
+ revision: {},
10688
+ cases,
10689
+ artifacts: [
10690
+ {
10691
+ name: "Open native MLflow run in Databricks",
10692
+ url: options.nativeRunUrl,
10693
+ mediaType: "text/html"
10694
+ }
10695
+ ]
10696
+ };
10697
+ }
10698
+ function resolveDatabricksAuth(env) {
10699
+ if (env.DATABRICKS_TOKEN) return { kind: "pat", token: env.DATABRICKS_TOKEN };
10700
+ if (env.DATABRICKS_CLIENT_ID && env.DATABRICKS_CLIENT_SECRET) {
10701
+ return {
10702
+ kind: "oauth-m2m",
10703
+ clientId: env.DATABRICKS_CLIENT_ID,
10704
+ clientSecret: env.DATABRICKS_CLIENT_SECRET
10705
+ };
10706
+ }
10707
+ throw new Error(
10708
+ "Native MLflow import requires DATABRICKS_TOKEN or DATABRICKS_CLIENT_ID and DATABRICKS_CLIENT_SECRET"
10709
+ );
10710
+ }
10711
+ function millisToIso(value) {
10712
+ return typeof value === "number" && Number.isFinite(value) ? new Date(value).toISOString() : null;
10713
+ }
10714
+
9661
10715
  // src/bin/fx.ts
9662
10716
  var HELP = `fx \u2014 Fabric Experiments CLI
9663
10717
 
@@ -9677,6 +10731,7 @@ COMMANDS
9677
10731
  preview <experimentId> Mint a signed preview link for a variant. Requires --variant.
9678
10732
  test env <action> Create, destroy, list, or reap Databricks test environments.
9679
10733
  test publish <file> Publish BDD/live/JUnit/CLI evidence to Studio Quality.
10734
+ test import-mlflow <id> Link a native Databricks MLflow run to Studio Quality.
9680
10735
  init databricks-tests Scaffold a Databricks BDD test project.
9681
10736
  login Configure and verify a secure hosted profile.
9682
10737
  logout [profile] Remove a stored hosted profile.
@@ -9706,6 +10761,8 @@ GLOBAL FLAGS
9706
10761
  --profile <name> hosted profile (default: active profile)
9707
10762
  --studio-url <url> login: branded Studio URL
9708
10763
  --databricks-profile <p> Databricks CLI profile used for Apps OAuth
10764
+ --workspace-host <url> Databricks workspace URL for native MLflow evidence.
10765
+ --gates <rules> Native MLflow metric policy, e.g. "accuracy>=0.9,toxicity<=0.05".
9709
10766
  --no-publish push: apply actions without publishing manifest
9710
10767
  --name <name> test env: environment name (for example pr-1234)
9711
10768
  --seed <dir> test env create: JSON fixture directory
@@ -9960,6 +11017,31 @@ async function main() {
9960
11017
  });
9961
11018
  }
9962
11019
  case "test":
11020
+ if (args.positional[0] === "import-mlflow") {
11021
+ if (!args.positional[1]) {
11022
+ process.stderr.write(
11023
+ 'Usage: fx test import-mlflow <run-id> --workspace-host <url> --gates "accuracy>=0.9" [flags]\n'
11024
+ );
11025
+ return 1;
11026
+ }
11027
+ const hosted = await resolveHostedContext({
11028
+ profileName: args.flags.profile,
11029
+ databricksProfile: args.flags["databricks-profile"],
11030
+ apiUrl: args.flags["api-url"],
11031
+ apiKey: args.flags["api-key"],
11032
+ tenantId: explicitTenantId
11033
+ });
11034
+ return cmdImportMlflow(args.positional[1], {
11035
+ tenantId: hosted.tenantId,
11036
+ apiUrl: hosted.apiUrl,
11037
+ apiKey: hosted.apiKey,
11038
+ bearerToken: hosted.bearerToken,
11039
+ workspaceHost: args.flags["workspace-host"],
11040
+ gates: args.flags.gates,
11041
+ suite: args.flags.suite,
11042
+ externalId: args.flags["external-id"]
11043
+ });
11044
+ }
9963
11045
  if (args.positional[0] === "publish") {
9964
11046
  if (!args.positional[1]) {
9965
11047
  process.stderr.write("Usage: fx test publish <evidence.json|junit.xml> [flags]\n");
@@ -9982,7 +11064,7 @@ async function main() {
9982
11064
  });
9983
11065
  }
9984
11066
  if (args.positional[0] !== "env") {
9985
- process.stderr.write("Usage: fx test <env|publish> [args] [flags]\n");
11067
+ process.stderr.write("Usage: fx test <env|publish|import-mlflow> [args] [flags]\n");
9986
11068
  return 1;
9987
11069
  }
9988
11070
  return cmdTestEnv(args.positional[1] ?? "", {