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