@fabricorg/experiments 0.13.0 → 0.14.1

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.1"};
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 {
@@ -7633,6 +7790,31 @@ var CreateAuditExportInput = external_exports.object({
7633
7790
  /** Free-form config; encrypted at rest. Schema enforced by destination kind. */
7634
7791
  config: external_exports.record(external_exports.unknown())
7635
7792
  });
7793
+ var BillingHealthResponse = external_exports.object({
7794
+ configured: external_exports.boolean(),
7795
+ livemode: external_exports.boolean().nullable(),
7796
+ meter: external_exports.object({
7797
+ id: external_exports.string(),
7798
+ eventName: external_exports.string(),
7799
+ status: external_exports.string()
7800
+ }).nullable(),
7801
+ subscription: external_exports.object({
7802
+ status: external_exports.string(),
7803
+ billingMode: external_exports.string(),
7804
+ priceId: external_exports.string().nullable(),
7805
+ meterId: external_exports.string().nullable(),
7806
+ currentPeriodEnd: external_exports.string().datetime().nullable()
7807
+ }).nullable()
7808
+ });
7809
+ var CreateBillingCheckoutInput = external_exports.object({
7810
+ mode: external_exports.enum(["subscription", "setup"]).default("subscription")
7811
+ });
7812
+ var BillingCheckoutResponse = external_exports.object({
7813
+ id: external_exports.string(),
7814
+ url: external_exports.string().url(),
7815
+ mode: external_exports.enum(["subscription", "setup"]),
7816
+ livemode: external_exports.boolean()
7817
+ });
7636
7818
  var ApiKeySummary = external_exports.object({
7637
7819
  id: external_exports.string(),
7638
7820
  name: external_exports.string(),
@@ -7704,7 +7886,9 @@ var TestRunArtifact = external_exports.object({
7704
7886
  });
7705
7887
  var CreateTestRunInput = external_exports.object({
7706
7888
  externalId: external_exports.string().min(1).max(300).optional(),
7707
- source: external_exports.enum(["bdd", "live-suite", "junit", "cli", "other"]),
7889
+ // 'eval-run' rows are written by the API itself when an eval run concludes
7890
+ // (Quality Center evidence for the evals suite) — never via testRuns.create.
7891
+ source: external_exports.enum(["bdd", "live-suite", "junit", "cli", "other", "eval-run", "databricks-mlflow"]),
7708
7892
  suite: external_exports.string().min(1).max(240),
7709
7893
  status: TestRunStatus,
7710
7894
  startedAt: external_exports.string().datetime().nullable().optional(),
@@ -7743,6 +7927,346 @@ var HarnessOperatorDefinition = external_exports.object({
7743
7927
  var HarnessOperatorListResponse = external_exports.array(HarnessOperatorDefinition);
7744
7928
  var HarnessJobInput = external_exports.record(external_exports.unknown()).default({});
7745
7929
  var HarnessJobResponse = external_exports.record(external_exports.unknown());
7930
+ var DatasetSummary = external_exports.object({
7931
+ id: external_exports.string(),
7932
+ name: external_exports.string(),
7933
+ description: external_exports.string().optional(),
7934
+ latestVersion: external_exports.number().int(),
7935
+ exampleCount: external_exports.number().int(),
7936
+ createdAtIso: external_exports.string().datetime(),
7937
+ updatedAtIso: external_exports.string().datetime()
7938
+ });
7939
+ var DatasetListResponse = external_exports.object({ datasets: external_exports.array(DatasetSummary) });
7940
+ var CreateDatasetInput = external_exports.object({
7941
+ id: external_exports.string().min(2).max(64).regex(/^[a-z][a-z0-9-]*$/),
7942
+ name: external_exports.string().min(1).max(120),
7943
+ description: external_exports.string().max(2e3).optional()
7944
+ });
7945
+ var DatasetExampleWire = external_exports.object({
7946
+ exampleId: external_exports.string().uuid(),
7947
+ input: external_exports.unknown(),
7948
+ expectedOutput: external_exports.unknown().optional(),
7949
+ metadata: external_exports.record(external_exports.unknown()).default({}),
7950
+ split: external_exports.enum(["train", "test", "validation"]).default("test")
7951
+ });
7952
+ var AddExamplesInput = external_exports.object({
7953
+ examples: external_exports.array(DatasetExampleWire).min(1).max(1e3)
7954
+ });
7955
+ var AddExamplesResponse = external_exports.object({ added: external_exports.number().int() });
7956
+ var ListExamplesInput = external_exports.object({
7957
+ version: external_exports.coerce.number().int().min(1).optional(),
7958
+ split: external_exports.enum(["train", "test", "validation"]).optional(),
7959
+ limit: external_exports.coerce.number().int().min(1).max(500).default(100),
7960
+ offset: external_exports.coerce.number().int().min(0).default(0)
7961
+ });
7962
+ var ListExamplesResponse = external_exports.object({
7963
+ examples: external_exports.array(DatasetExampleWire),
7964
+ total: external_exports.number().int()
7965
+ });
7966
+ var CreateDatasetVersionInput = external_exports.object({ note: external_exports.string().max(500).optional() });
7967
+ var DatasetVersionWire = external_exports.object({
7968
+ datasetId: external_exports.string(),
7969
+ version: external_exports.number().int(),
7970
+ exampleCount: external_exports.number().int(),
7971
+ contentHash: external_exports.string(),
7972
+ createdAtIso: external_exports.string().datetime(),
7973
+ note: external_exports.string().optional()
7974
+ });
7975
+ var DatasetVersionListResponse = external_exports.object({
7976
+ versions: external_exports.array(DatasetVersionWire)
7977
+ });
7978
+ var EvalRunTargetWire = external_exports.discriminatedUnion("kind", [
7979
+ external_exports.object({ kind: external_exports.literal("dataset"), datasetId: external_exports.string(), version: external_exports.number().int().min(1) }),
7980
+ external_exports.object({
7981
+ kind: external_exports.literal("experiment"),
7982
+ experimentId: external_exports.string(),
7983
+ metricEventName: external_exports.string().optional()
7984
+ })
7985
+ ]);
7986
+ var CreateEvalRunInput = external_exports.object({
7987
+ target: EvalRunTargetWire,
7988
+ evaluatorNames: external_exports.array(external_exports.string().min(1)).min(1).max(10),
7989
+ maxJudgeTokens: external_exports.number().int().min(0).optional(),
7990
+ /**
7991
+ * Quality Center policy for binary evaluators: the run's companion
7992
+ * fx.test_runs evidence row is `failed` when any binary evaluator's pass
7993
+ * rate lands below this threshold, even if the run itself succeeded.
7994
+ * Defaults server-side to 0.9.
7995
+ */
7996
+ passThreshold: external_exports.number().min(0).max(1).optional()
7997
+ });
7998
+ var EvalRunGenerationWire = external_exports.object({
7999
+ promptId: external_exports.string(),
8000
+ promptVersion: external_exports.number().int().min(1),
8001
+ datasetId: external_exports.string(),
8002
+ datasetVersion: external_exports.number().int().min(1),
8003
+ maxExamples: external_exports.number().int().min(1)
8004
+ });
8005
+ var EvalRunSummary = external_exports.object({
8006
+ runId: external_exports.string(),
8007
+ target: EvalRunTargetWire,
8008
+ generation: EvalRunGenerationWire.optional(),
8009
+ evaluatorNames: external_exports.array(external_exports.string()),
8010
+ status: external_exports.enum(["pending", "running", "succeeded", "failed", "cancelled"]),
8011
+ scoredExamples: external_exports.number().int(),
8012
+ totalExamples: external_exports.number().int(),
8013
+ tokensSpent: external_exports.number().int(),
8014
+ costUsd: external_exports.number().nullable(),
8015
+ passThreshold: external_exports.number(),
8016
+ createdAtIso: external_exports.string().datetime(),
8017
+ startedAtIso: external_exports.string().datetime().optional(),
8018
+ finishedAtIso: external_exports.string().datetime().optional(),
8019
+ error: external_exports.string().optional()
8020
+ });
8021
+ var EvalRunListInput = external_exports.object({
8022
+ limit: external_exports.coerce.number().int().min(1).max(200).default(50),
8023
+ offset: external_exports.coerce.number().int().min(0).default(0),
8024
+ status: external_exports.enum(["pending", "running", "succeeded", "failed", "cancelled"]).optional()
8025
+ });
8026
+ var EvalRunListResponse = external_exports.object({ runs: external_exports.array(EvalRunSummary) });
8027
+ var EvaluatorAggregateWire = external_exports.object({
8028
+ evaluatorName: external_exports.string(),
8029
+ evaluatorVersion: external_exports.string(),
8030
+ scored: external_exports.number().int(),
8031
+ unscored: external_exports.number().int(),
8032
+ meanScore: external_exports.number().nullable(),
8033
+ passRate: external_exports.object({ rate: external_exports.number(), low: external_exports.number(), high: external_exports.number() }).nullable(),
8034
+ labelCounts: external_exports.record(external_exports.number().int()),
8035
+ totalTokens: external_exports.number().int(),
8036
+ meanLatencyMs: external_exports.number().nullable()
8037
+ });
8038
+ var EvalRunDetail = external_exports.object({
8039
+ run: EvalRunSummary,
8040
+ aggregates: external_exports.array(EvaluatorAggregateWire)
8041
+ });
8042
+ var EvalScoreWire = external_exports.object({
8043
+ itemId: external_exports.string(),
8044
+ evaluatorName: external_exports.string(),
8045
+ evaluatorVersion: external_exports.string(),
8046
+ label: external_exports.string().nullable(),
8047
+ score: external_exports.number().nullable(),
8048
+ explanation: external_exports.string().nullable(),
8049
+ latencyMs: external_exports.number()
8050
+ });
8051
+ var EvalScoreListInput = external_exports.object({
8052
+ evaluatorName: external_exports.string().optional(),
8053
+ limit: external_exports.coerce.number().int().min(1).max(500).default(100),
8054
+ offset: external_exports.coerce.number().int().min(0).default(0)
8055
+ });
8056
+ var EvalScoreListResponse = external_exports.object({
8057
+ scores: external_exports.array(EvalScoreWire),
8058
+ total: external_exports.number().int()
8059
+ });
8060
+ var PromptMessageWire = external_exports.object({
8061
+ role: external_exports.enum(["system", "user", "assistant"]),
8062
+ content: external_exports.string().min(1).max(1e5)
8063
+ });
8064
+ var PromptTemplateWire = external_exports.object({
8065
+ messages: external_exports.array(PromptMessageWire).min(1).max(50),
8066
+ params: external_exports.object({
8067
+ model: external_exports.string().max(256).optional(),
8068
+ temperature: external_exports.number().min(0).max(2).optional(),
8069
+ maxTokens: external_exports.number().int().min(1).max(2e5).optional(),
8070
+ topP: external_exports.number().min(0).max(1).optional()
8071
+ }).default({})
8072
+ });
8073
+ var PromptSummary = external_exports.object({
8074
+ id: external_exports.string(),
8075
+ name: external_exports.string(),
8076
+ description: external_exports.string().optional(),
8077
+ latestVersion: external_exports.number().int(),
8078
+ createdAtIso: external_exports.string().datetime(),
8079
+ updatedAtIso: external_exports.string().datetime()
8080
+ });
8081
+ var PromptListResponse = external_exports.object({ prompts: external_exports.array(PromptSummary) });
8082
+ var CreatePromptInput = external_exports.object({
8083
+ id: external_exports.string().min(2).max(64).regex(/^[a-z][a-z0-9-]*$/),
8084
+ name: external_exports.string().min(1).max(120),
8085
+ description: external_exports.string().max(2e3).optional()
8086
+ });
8087
+ var PromptVersionWire = external_exports.object({
8088
+ promptId: external_exports.string(),
8089
+ version: external_exports.number().int(),
8090
+ template: PromptTemplateWire,
8091
+ contentHash: external_exports.string(),
8092
+ variables: external_exports.array(external_exports.string()),
8093
+ createdAtIso: external_exports.string().datetime(),
8094
+ note: external_exports.string().optional()
8095
+ });
8096
+ var CreatePromptVersionInput = external_exports.object({
8097
+ template: PromptTemplateWire,
8098
+ note: external_exports.string().max(500).optional()
8099
+ });
8100
+ var PromptVersionListResponse = external_exports.object({
8101
+ versions: external_exports.array(PromptVersionWire)
8102
+ });
8103
+ var PlaygroundInvokeInput = external_exports.object({
8104
+ /** Registry reference (promptId + optional version, defaulting to latest)... */
8105
+ promptId: external_exports.string().optional(),
8106
+ version: external_exports.number().int().min(1).optional(),
8107
+ /** ...or an inline template (draft mode). Exactly one source is required. */
8108
+ template: PromptTemplateWire.optional(),
8109
+ variables: external_exports.record(external_exports.string()).default({})
8110
+ });
8111
+ var PlaygroundInvokeResponse = external_exports.object({
8112
+ messages: external_exports.array(PromptMessageWire),
8113
+ missingVariables: external_exports.array(external_exports.string()),
8114
+ text: external_exports.string(),
8115
+ inputTokens: external_exports.number().int(),
8116
+ outputTokens: external_exports.number().int(),
8117
+ latencyMs: external_exports.number(),
8118
+ modelEndpoint: external_exports.string(),
8119
+ /** Manifest cost of this invocation; null when the endpoint is unpriced. */
8120
+ costUsd: external_exports.number().nullable()
8121
+ });
8122
+ var PlaygroundReplayInput = external_exports.object({
8123
+ promptId: external_exports.string(),
8124
+ version: external_exports.number().int().min(1),
8125
+ datasetId: external_exports.string(),
8126
+ datasetVersion: external_exports.number().int().min(1),
8127
+ evaluatorNames: external_exports.array(external_exports.string().min(1)).min(1).max(10),
8128
+ /** Shared budget: generation AND judge tokens both count against it. */
8129
+ maxJudgeTokens: external_exports.number().int().min(0).optional(),
8130
+ /** Cap on examples replayed through the model. */
8131
+ maxExamples: external_exports.number().int().min(1).max(200).default(50)
8132
+ });
8133
+ var VariantEvalWire = external_exports.object({
8134
+ variantKey: external_exports.string(),
8135
+ evaluatorName: external_exports.string(),
8136
+ evaluatorVersion: external_exports.string(),
8137
+ scored: external_exports.number().int(),
8138
+ unscored: external_exports.number().int(),
8139
+ meanScore: external_exports.number().nullable(),
8140
+ passCount: external_exports.number().int(),
8141
+ binary: external_exports.boolean()
8142
+ });
8143
+ var VariantEvalListResponse = external_exports.object({ variants: external_exports.array(VariantEvalWire) });
8144
+ var SpanKindWire = external_exports.enum([
8145
+ "LLM",
8146
+ "CHAIN",
8147
+ "RETRIEVER",
8148
+ "EMBEDDING",
8149
+ "TOOL",
8150
+ "AGENT",
8151
+ "RERANKER",
8152
+ "GUARDRAIL",
8153
+ "EVALUATOR",
8154
+ "UNKNOWN"
8155
+ ]);
8156
+ var TraceSummaryWire = external_exports.object({
8157
+ traceId: external_exports.string(),
8158
+ rootSpanName: external_exports.string(),
8159
+ rootSpanKind: SpanKindWire,
8160
+ sessionId: external_exports.string().nullable(),
8161
+ experimentId: external_exports.string().nullable(),
8162
+ variantKey: external_exports.string().nullable(),
8163
+ startedAtIso: external_exports.string().datetime(),
8164
+ durationMs: external_exports.number(),
8165
+ spanCount: external_exports.number().int(),
8166
+ errorCount: external_exports.number().int(),
8167
+ totalInputTokens: external_exports.number().int(),
8168
+ totalOutputTokens: external_exports.number().int()
8169
+ });
8170
+ var TraceListInput = external_exports.object({
8171
+ experimentId: external_exports.string().optional(),
8172
+ variantKey: external_exports.string().optional(),
8173
+ sessionId: external_exports.string().optional(),
8174
+ kind: SpanKindWire.optional(),
8175
+ errorsOnly: external_exports.coerce.boolean().optional(),
8176
+ fromIso: external_exports.string().datetime().optional(),
8177
+ untilIso: external_exports.string().datetime().optional(),
8178
+ limit: external_exports.coerce.number().int().min(1).max(200).default(50),
8179
+ offset: external_exports.coerce.number().int().min(0).default(0)
8180
+ });
8181
+ var TraceListResponse = external_exports.object({
8182
+ traces: external_exports.array(TraceSummaryWire),
8183
+ total: external_exports.number().int()
8184
+ });
8185
+ var SessionTraceWire = TraceSummaryWire.extend({
8186
+ rootInputValue: external_exports.string().nullable(),
8187
+ rootOutputValue: external_exports.string().nullable()
8188
+ });
8189
+ var SessionDetailResponse = external_exports.object({
8190
+ sessionId: external_exports.string(),
8191
+ /** Conversation order: ascending by trace start time. */
8192
+ traces: external_exports.array(SessionTraceWire)
8193
+ });
8194
+ var SpanWire = external_exports.object({
8195
+ traceId: external_exports.string(),
8196
+ spanId: external_exports.string(),
8197
+ parentSpanId: external_exports.string().nullable(),
8198
+ name: external_exports.string(),
8199
+ kind: SpanKindWire,
8200
+ startedAtIso: external_exports.string().datetime(),
8201
+ durationMs: external_exports.number(),
8202
+ status: external_exports.enum(["UNSET", "OK", "ERROR"]),
8203
+ statusMessage: external_exports.string().nullable(),
8204
+ sessionId: external_exports.string().nullable(),
8205
+ experimentId: external_exports.string().nullable(),
8206
+ variantKey: external_exports.string().nullable(),
8207
+ inputValue: external_exports.string().nullable(),
8208
+ outputValue: external_exports.string().nullable(),
8209
+ inputTokens: external_exports.number().int().nullable(),
8210
+ outputTokens: external_exports.number().int().nullable(),
8211
+ modelName: external_exports.string().nullable(),
8212
+ /** Ingest-time dollar cost from the model-cost manifest; null when unpriceable. */
8213
+ costUsd: external_exports.number().nullable(),
8214
+ attributes: external_exports.record(external_exports.unknown())
8215
+ });
8216
+ var SpanAnnotationWire = external_exports.object({
8217
+ spanId: external_exports.string(),
8218
+ annotator: external_exports.enum(["human", "llm"]),
8219
+ /** Evaluator name for llm annotations; user id for human ones. */
8220
+ annotatorId: external_exports.string(),
8221
+ label: external_exports.string().nullable(),
8222
+ score: external_exports.number().nullable(),
8223
+ explanation: external_exports.string().nullable(),
8224
+ createdAtIso: external_exports.string().datetime()
8225
+ });
8226
+ var TraceDetail = external_exports.object({
8227
+ traceId: external_exports.string(),
8228
+ spans: external_exports.array(SpanWire),
8229
+ annotations: external_exports.array(SpanAnnotationWire)
8230
+ });
8231
+ var AnnotateSpanInput = external_exports.object({
8232
+ spanId: external_exports.string(),
8233
+ label: external_exports.string().max(64).optional(),
8234
+ score: external_exports.number().min(0).max(1).optional(),
8235
+ explanation: external_exports.string().max(1e4).optional()
8236
+ });
8237
+ var SpanAnalyticsInput = external_exports.object({
8238
+ experimentId: external_exports.string().optional(),
8239
+ variantKey: external_exports.string().optional(),
8240
+ groupBy: external_exports.enum(["kind", "model"]).default("kind"),
8241
+ fromIso: external_exports.string().datetime().optional(),
8242
+ untilIso: external_exports.string().datetime().optional()
8243
+ });
8244
+ var SpanAnalyticsResponse = external_exports.object({
8245
+ groups: external_exports.array(
8246
+ external_exports.object({
8247
+ groupKey: external_exports.string(),
8248
+ spanCount: external_exports.number().int(),
8249
+ errorCount: external_exports.number().int(),
8250
+ meanDurationMs: external_exports.number().nullable(),
8251
+ p95DurationMs: external_exports.number().nullable(),
8252
+ totalInputTokens: external_exports.number().int(),
8253
+ totalOutputTokens: external_exports.number().int(),
8254
+ totalCostUsd: external_exports.number()
8255
+ })
8256
+ ),
8257
+ traceCount: external_exports.number().int(),
8258
+ /** Cost over the full filtered span set — NOT restricted by groupBy model. */
8259
+ totalCostUsd: external_exports.number()
8260
+ });
8261
+ var IngestTokenSummary = external_exports.object({
8262
+ tokenId: external_exports.string(),
8263
+ label: external_exports.string(),
8264
+ createdAtIso: external_exports.string().datetime(),
8265
+ revokedAtIso: external_exports.string().datetime().nullable()
8266
+ });
8267
+ var IngestTokenListResponse = external_exports.object({ tokens: external_exports.array(IngestTokenSummary) });
8268
+ var CreateIngestTokenInput = external_exports.object({ label: external_exports.string().min(1).max(120) });
8269
+ var CreatedIngestToken = IngestTokenSummary.extend({ token: external_exports.string() });
7746
8270
  var endpoints = {
7747
8271
  "tenants.me": {
7748
8272
  method: "GET",
@@ -7968,6 +8492,22 @@ var endpoints = {
7968
8492
  mutates: true,
7969
8493
  requiresRole: "admin"
7970
8494
  },
8495
+ "billing.health": {
8496
+ method: "GET",
8497
+ path: "/v1/orgs/:orgId/billing/health",
8498
+ params: Empty,
8499
+ response: BillingHealthResponse,
8500
+ mutates: false,
8501
+ requiresRole: "owner"
8502
+ },
8503
+ "billing.checkout": {
8504
+ method: "POST",
8505
+ path: "/v1/orgs/:orgId/billing/checkout",
8506
+ params: CreateBillingCheckoutInput,
8507
+ response: BillingCheckoutResponse,
8508
+ mutates: true,
8509
+ requiresRole: "owner"
8510
+ },
7971
8511
  "audit.exports.list": {
7972
8512
  method: "GET",
7973
8513
  path: "/v1/orgs/:orgId/audit/exports",
@@ -8056,6 +8596,232 @@ var endpoints = {
8056
8596
  mutates: false,
8057
8597
  requiresRole: "viewer"
8058
8598
  },
8599
+ "datasets.list": {
8600
+ method: "GET",
8601
+ path: "/v1/orgs/:orgId/datasets",
8602
+ params: Empty,
8603
+ response: DatasetListResponse,
8604
+ mutates: false,
8605
+ requiresRole: "viewer"
8606
+ },
8607
+ "datasets.create": {
8608
+ method: "POST",
8609
+ path: "/v1/orgs/:orgId/datasets",
8610
+ params: CreateDatasetInput,
8611
+ response: DatasetSummary,
8612
+ mutates: true,
8613
+ requiresRole: "experimenter"
8614
+ },
8615
+ "datasets.get": {
8616
+ method: "GET",
8617
+ path: "/v1/orgs/:orgId/datasets/:datasetId",
8618
+ params: Empty,
8619
+ response: DatasetSummary,
8620
+ mutates: false,
8621
+ requiresRole: "viewer"
8622
+ },
8623
+ "datasets.addExamples": {
8624
+ method: "POST",
8625
+ path: "/v1/orgs/:orgId/datasets/:datasetId/examples",
8626
+ params: AddExamplesInput,
8627
+ response: AddExamplesResponse,
8628
+ mutates: true,
8629
+ requiresRole: "experimenter"
8630
+ },
8631
+ "datasets.listExamples": {
8632
+ method: "GET",
8633
+ path: "/v1/orgs/:orgId/datasets/:datasetId/examples",
8634
+ params: ListExamplesInput,
8635
+ response: ListExamplesResponse,
8636
+ mutates: false,
8637
+ requiresRole: "viewer"
8638
+ },
8639
+ "datasets.createVersion": {
8640
+ method: "POST",
8641
+ path: "/v1/orgs/:orgId/datasets/:datasetId/versions",
8642
+ params: CreateDatasetVersionInput,
8643
+ response: DatasetVersionWire,
8644
+ mutates: true,
8645
+ requiresRole: "experimenter"
8646
+ },
8647
+ "datasets.listVersions": {
8648
+ method: "GET",
8649
+ path: "/v1/orgs/:orgId/datasets/:datasetId/versions",
8650
+ params: Empty,
8651
+ response: DatasetVersionListResponse,
8652
+ mutates: false,
8653
+ requiresRole: "viewer"
8654
+ },
8655
+ "traces.list": {
8656
+ method: "GET",
8657
+ path: "/v1/orgs/:orgId/traces",
8658
+ params: TraceListInput,
8659
+ response: TraceListResponse,
8660
+ mutates: false,
8661
+ requiresRole: "viewer"
8662
+ },
8663
+ "traces.get": {
8664
+ method: "GET",
8665
+ path: "/v1/orgs/:orgId/traces/:traceId",
8666
+ params: Empty,
8667
+ response: TraceDetail,
8668
+ mutates: false,
8669
+ requiresRole: "viewer"
8670
+ },
8671
+ "traces.annotate": {
8672
+ method: "POST",
8673
+ path: "/v1/orgs/:orgId/traces/:traceId/annotations",
8674
+ params: AnnotateSpanInput,
8675
+ response: SpanAnnotationWire,
8676
+ mutates: true,
8677
+ requiresRole: "experimenter"
8678
+ },
8679
+ "traces.analytics": {
8680
+ method: "GET",
8681
+ path: "/v1/orgs/:orgId/traces/analytics",
8682
+ params: SpanAnalyticsInput,
8683
+ response: SpanAnalyticsResponse,
8684
+ mutates: false,
8685
+ requiresRole: "viewer"
8686
+ },
8687
+ "traces.session": {
8688
+ method: "GET",
8689
+ path: "/v1/orgs/:orgId/traces/sessions/:sessionId",
8690
+ params: Empty,
8691
+ response: SessionDetailResponse,
8692
+ mutates: false,
8693
+ requiresRole: "viewer"
8694
+ },
8695
+ "evals.createRun": {
8696
+ method: "POST",
8697
+ path: "/v1/orgs/:orgId/evals/runs",
8698
+ params: CreateEvalRunInput,
8699
+ response: EvalRunSummary,
8700
+ mutates: true,
8701
+ requiresRole: "experimenter"
8702
+ },
8703
+ "evals.listRuns": {
8704
+ method: "GET",
8705
+ path: "/v1/orgs/:orgId/evals/runs",
8706
+ params: EvalRunListInput,
8707
+ response: EvalRunListResponse,
8708
+ mutates: false,
8709
+ requiresRole: "viewer"
8710
+ },
8711
+ "evals.getRun": {
8712
+ method: "GET",
8713
+ path: "/v1/orgs/:orgId/evals/runs/:runId",
8714
+ params: Empty,
8715
+ response: EvalRunDetail,
8716
+ mutates: false,
8717
+ requiresRole: "viewer"
8718
+ },
8719
+ "evals.listScores": {
8720
+ method: "GET",
8721
+ path: "/v1/orgs/:orgId/evals/runs/:runId/scores",
8722
+ params: EvalScoreListInput,
8723
+ response: EvalScoreListResponse,
8724
+ mutates: false,
8725
+ requiresRole: "viewer"
8726
+ },
8727
+ "evals.cancelRun": {
8728
+ method: "POST",
8729
+ path: "/v1/orgs/:orgId/evals/runs/:runId/cancel",
8730
+ params: Empty,
8731
+ response: EvalRunSummary,
8732
+ mutates: true,
8733
+ requiresRole: "experimenter"
8734
+ },
8735
+ "evals.byVariant": {
8736
+ method: "GET",
8737
+ path: "/v1/orgs/:orgId/experiments/:experimentId/evals",
8738
+ params: Empty,
8739
+ response: VariantEvalListResponse,
8740
+ mutates: false,
8741
+ requiresRole: "viewer"
8742
+ },
8743
+ "ingestTokens.list": {
8744
+ method: "GET",
8745
+ path: "/v1/orgs/:orgId/ingest-tokens",
8746
+ params: Empty,
8747
+ response: IngestTokenListResponse,
8748
+ mutates: false,
8749
+ requiresRole: "admin"
8750
+ },
8751
+ "ingestTokens.create": {
8752
+ method: "POST",
8753
+ path: "/v1/orgs/:orgId/ingest-tokens",
8754
+ params: CreateIngestTokenInput,
8755
+ response: CreatedIngestToken,
8756
+ mutates: true,
8757
+ requiresRole: "admin"
8758
+ },
8759
+ "ingestTokens.revoke": {
8760
+ method: "POST",
8761
+ path: "/v1/orgs/:orgId/ingest-tokens/:tokenId/revoke",
8762
+ params: Empty,
8763
+ response: IngestTokenSummary,
8764
+ mutates: true,
8765
+ requiresRole: "admin"
8766
+ },
8767
+ "prompts.list": {
8768
+ method: "GET",
8769
+ path: "/v1/orgs/:orgId/prompts",
8770
+ params: Empty,
8771
+ response: PromptListResponse,
8772
+ mutates: false,
8773
+ requiresRole: "viewer"
8774
+ },
8775
+ "prompts.create": {
8776
+ method: "POST",
8777
+ path: "/v1/orgs/:orgId/prompts",
8778
+ params: CreatePromptInput,
8779
+ response: PromptSummary,
8780
+ mutates: true,
8781
+ requiresRole: "experimenter"
8782
+ },
8783
+ "prompts.get": {
8784
+ method: "GET",
8785
+ path: "/v1/orgs/:orgId/prompts/:promptId",
8786
+ params: Empty,
8787
+ response: PromptSummary,
8788
+ mutates: false,
8789
+ requiresRole: "viewer"
8790
+ },
8791
+ "prompts.createVersion": {
8792
+ method: "POST",
8793
+ path: "/v1/orgs/:orgId/prompts/:promptId/versions",
8794
+ params: CreatePromptVersionInput,
8795
+ response: PromptVersionWire,
8796
+ mutates: true,
8797
+ requiresRole: "experimenter"
8798
+ },
8799
+ "prompts.listVersions": {
8800
+ method: "GET",
8801
+ path: "/v1/orgs/:orgId/prompts/:promptId/versions",
8802
+ params: Empty,
8803
+ response: PromptVersionListResponse,
8804
+ mutates: false,
8805
+ requiresRole: "viewer"
8806
+ },
8807
+ "playground.invoke": {
8808
+ method: "POST",
8809
+ path: "/v1/orgs/:orgId/playground/invoke",
8810
+ params: PlaygroundInvokeInput,
8811
+ response: PlaygroundInvokeResponse,
8812
+ mutates: false,
8813
+ requiresRole: "experimenter"
8814
+ },
8815
+ // 202-style: replay only creates a pending eval run (durable via the
8816
+ // outbox); generation + judging happen in the executor, off the request.
8817
+ "playground.replay": {
8818
+ method: "POST",
8819
+ path: "/v1/orgs/:orgId/playground/replay",
8820
+ params: PlaygroundReplayInput,
8821
+ response: EvalRunSummary,
8822
+ mutates: true,
8823
+ requiresRole: "experimenter"
8824
+ },
8059
8825
  "harness.definitions": {
8060
8826
  method: "GET",
8061
8827
  path: "/v1/orgs/:orgId/harness/admin/agents",
@@ -8252,6 +9018,46 @@ var ApiClient = class {
8252
9018
  get: (orgId) => this.call("saml.get", {}, orgId ? { orgId } : void 0),
8253
9019
  update: (params, orgId) => this.call("saml.update", params, orgId ? { orgId } : void 0)
8254
9020
  };
9021
+ datasets = {
9022
+ list: (orgId) => this.call("datasets.list", {}, orgId ? { orgId } : void 0),
9023
+ create: (params, orgId) => this.call("datasets.create", params, orgId ? { orgId } : void 0),
9024
+ get: (datasetId, orgId) => this.call("datasets.get", {}, orgId ? { orgId, datasetId } : { datasetId }),
9025
+ addExamples: (datasetId, params, orgId) => this.call("datasets.addExamples", params, orgId ? { orgId, datasetId } : { datasetId }),
9026
+ listExamples: (datasetId, params, orgId) => this.call("datasets.listExamples", params, orgId ? { orgId, datasetId } : { datasetId }),
9027
+ createVersion: (datasetId, params, orgId) => this.call("datasets.createVersion", params, orgId ? { orgId, datasetId } : { datasetId }),
9028
+ listVersions: (datasetId, orgId) => this.call("datasets.listVersions", {}, orgId ? { orgId, datasetId } : { datasetId })
9029
+ };
9030
+ evals = {
9031
+ createRun: (params, orgId) => this.call("evals.createRun", params, orgId ? { orgId } : void 0),
9032
+ listRuns: (params, orgId) => this.call("evals.listRuns", params, orgId ? { orgId } : void 0),
9033
+ getRun: (runId, orgId) => this.call("evals.getRun", {}, orgId ? { orgId, runId } : { runId }),
9034
+ listScores: (runId, params, orgId) => this.call("evals.listScores", params, orgId ? { orgId, runId } : { runId }),
9035
+ cancelRun: (runId, orgId) => this.call("evals.cancelRun", {}, orgId ? { orgId, runId } : { runId }),
9036
+ byVariant: (experimentId, orgId) => this.call("evals.byVariant", {}, orgId ? { orgId, experimentId } : { experimentId })
9037
+ };
9038
+ traces = {
9039
+ list: (params, orgId) => this.call("traces.list", params, orgId ? { orgId } : void 0),
9040
+ get: (traceId, orgId) => this.call("traces.get", {}, orgId ? { orgId, traceId } : { traceId }),
9041
+ annotate: (traceId, params, orgId) => this.call("traces.annotate", params, orgId ? { orgId, traceId } : { traceId }),
9042
+ analytics: (params, orgId) => this.call("traces.analytics", params, orgId ? { orgId } : void 0),
9043
+ session: (sessionId, orgId) => this.call("traces.session", {}, orgId ? { orgId, sessionId } : { sessionId })
9044
+ };
9045
+ ingestTokens = {
9046
+ list: (orgId) => this.call("ingestTokens.list", {}, orgId ? { orgId } : void 0),
9047
+ create: (params, orgId) => this.call("ingestTokens.create", params, orgId ? { orgId } : void 0),
9048
+ revoke: (tokenId, orgId) => this.call("ingestTokens.revoke", {}, orgId ? { orgId, tokenId } : { tokenId })
9049
+ };
9050
+ prompts = {
9051
+ list: (orgId) => this.call("prompts.list", {}, orgId ? { orgId } : void 0),
9052
+ create: (params, orgId) => this.call("prompts.create", params, orgId ? { orgId } : void 0),
9053
+ get: (promptId, orgId) => this.call("prompts.get", {}, orgId ? { orgId, promptId } : { promptId }),
9054
+ createVersion: (promptId, params, orgId) => this.call("prompts.createVersion", params, orgId ? { orgId, promptId } : { promptId }),
9055
+ listVersions: (promptId, orgId) => this.call("prompts.listVersions", {}, orgId ? { orgId, promptId } : { promptId })
9056
+ };
9057
+ playground = {
9058
+ invoke: (params, orgId) => this.call("playground.invoke", params, orgId ? { orgId } : void 0),
9059
+ replay: (params, orgId) => this.call("playground.replay", params, orgId ? { orgId } : void 0)
9060
+ };
8255
9061
  testRuns = {
8256
9062
  list: (params = {}, orgId) => this.call("testRuns.list", params, orgId ? { orgId } : void 0),
8257
9063
  get: (runId, orgId) => this.call("testRuns.get", {}, orgId ? { orgId, runId } : { runId }),
@@ -9658,6 +10464,295 @@ function parseInput(value) {
9658
10464
  return parsed;
9659
10465
  }
9660
10466
 
10467
+ // ../evals/dist/databricks.js
10468
+ var DatabricksBearerProvider = class {
10469
+ host;
10470
+ auth;
10471
+ fetchImpl;
10472
+ timeoutMs;
10473
+ oauthToken = null;
10474
+ constructor(config) {
10475
+ this.host = normalizeDatabricksHost(config.host);
10476
+ this.auth = config.auth;
10477
+ this.fetchImpl = config.fetchImpl ?? fetch;
10478
+ this.timeoutMs = config.timeoutMs ?? 6e4;
10479
+ if (!Number.isFinite(this.timeoutMs) || this.timeoutMs <= 0) {
10480
+ throw new Error("Databricks timeoutMs must be positive");
10481
+ }
10482
+ }
10483
+ async token() {
10484
+ if (this.auth.kind === "pat") return this.auth.token;
10485
+ if (this.oauthToken && this.oauthToken.expiresAt > Date.now() + 6e4) {
10486
+ return this.oauthToken.value;
10487
+ }
10488
+ const response = await this.fetchImpl(`${this.host}/oidc/v1/token`, {
10489
+ method: "POST",
10490
+ headers: {
10491
+ authorization: `Basic ${toBase64(`${this.auth.clientId}:${this.auth.clientSecret}`)}`,
10492
+ "content-type": "application/x-www-form-urlencoded"
10493
+ },
10494
+ body: new URLSearchParams({ grant_type: "client_credentials", scope: "all-apis" }),
10495
+ signal: AbortSignal.timeout(this.timeoutMs)
10496
+ });
10497
+ if (!response.ok) throw new Error(`Databricks OAuth exchange failed (${response.status})`);
10498
+ const body = await response.json();
10499
+ if (!body.access_token) throw new Error("Databricks OAuth exchange returned no access token");
10500
+ this.oauthToken = {
10501
+ value: body.access_token,
10502
+ expiresAt: Date.now() + (body.expires_in ?? 3600) * 1e3
10503
+ };
10504
+ return this.oauthToken.value;
10505
+ }
10506
+ };
10507
+ function normalizeDatabricksHost(host) {
10508
+ return host.startsWith("http://") || host.startsWith("https://") ? host.replace(/\/$/, "") : `https://${host.replace(/\/$/, "")}`;
10509
+ }
10510
+ function toBase64(value) {
10511
+ if (typeof Buffer !== "undefined") return Buffer.from(value).toString("base64");
10512
+ return btoa(value);
10513
+ }
10514
+ var MlflowMetric = external_exports.object({
10515
+ key: external_exports.string().min(1),
10516
+ value: external_exports.number(),
10517
+ timestamp: external_exports.number().optional(),
10518
+ step: external_exports.number().optional()
10519
+ });
10520
+ var MlflowRunResponse = external_exports.object({
10521
+ run: external_exports.object({
10522
+ info: external_exports.object({
10523
+ run_id: external_exports.string().min(1),
10524
+ experiment_id: external_exports.string().min(1),
10525
+ status: external_exports.string().min(1),
10526
+ start_time: external_exports.number().optional(),
10527
+ end_time: external_exports.number().optional(),
10528
+ artifact_uri: external_exports.string().optional(),
10529
+ run_name: external_exports.string().optional()
10530
+ }),
10531
+ data: external_exports.object({
10532
+ metrics: external_exports.array(MlflowMetric).default([]),
10533
+ params: external_exports.array(external_exports.object({ key: external_exports.string(), value: external_exports.string() })).default([]),
10534
+ tags: external_exports.array(external_exports.object({ key: external_exports.string(), value: external_exports.string() })).default([])
10535
+ }).default({ metrics: [], params: [], tags: [] })
10536
+ })
10537
+ });
10538
+ var DatabricksMlflowClient = class {
10539
+ host;
10540
+ authMode;
10541
+ fetchImpl;
10542
+ timeoutMs;
10543
+ bearer;
10544
+ constructor(config) {
10545
+ this.host = normalizeDatabricksHost(config.host);
10546
+ this.authMode = config.auth.kind;
10547
+ this.fetchImpl = config.fetchImpl ?? fetch;
10548
+ this.timeoutMs = config.timeoutMs ?? 6e4;
10549
+ if (!Number.isFinite(this.timeoutMs) || this.timeoutMs <= 0) {
10550
+ throw new Error("Databricks MLflow timeoutMs must be positive");
10551
+ }
10552
+ this.bearer = new DatabricksBearerProvider({
10553
+ host: this.host,
10554
+ auth: config.auth,
10555
+ fetchImpl: this.fetchImpl,
10556
+ timeoutMs: this.timeoutMs
10557
+ });
10558
+ }
10559
+ async getRun(runId) {
10560
+ if (!runId.trim()) throw new Error("MLflow runId is required");
10561
+ const url = new URL(`${this.host}/api/2.0/mlflow/runs/get`);
10562
+ url.searchParams.set("run_id", runId);
10563
+ const response = await this.fetchImpl(url, {
10564
+ headers: { authorization: `Bearer ${await this.bearer.token()}` },
10565
+ signal: AbortSignal.timeout(this.timeoutMs)
10566
+ });
10567
+ if (!response.ok) {
10568
+ const body = await response.text();
10569
+ throw new Error(
10570
+ `Databricks MLflow run lookup failed (${response.status}): ${body.slice(0, 500)}`
10571
+ );
10572
+ }
10573
+ const parsed = MlflowRunResponse.safeParse(await response.json());
10574
+ if (!parsed.success) {
10575
+ throw new Error(
10576
+ `Databricks MLflow returned an invalid run: ${parsed.error.issues[0]?.message ?? "schema mismatch"}`
10577
+ );
10578
+ }
10579
+ return parsed.data.run;
10580
+ }
10581
+ runUrl(run) {
10582
+ return `${this.host}/ml/experiments/${encodeURIComponent(run.info.experiment_id)}/runs/${encodeURIComponent(run.info.run_id)}`;
10583
+ }
10584
+ };
10585
+ function parseMlflowMetricGates(value) {
10586
+ const entries = value.split(",").map((entry) => entry.trim()).filter(Boolean);
10587
+ if (entries.length === 0) throw new Error("At least one MLflow metric gate is required");
10588
+ return entries.map((entry) => {
10589
+ const match = /^(.+?)(>=|<=|==|!=|>|<)(-?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?)$/i.exec(entry);
10590
+ if (!match) throw new Error(`Invalid MLflow metric gate '${entry}'`);
10591
+ const metric = match[1].trim();
10592
+ if (!metric) throw new Error(`Invalid MLflow metric gate '${entry}'`);
10593
+ return {
10594
+ metric,
10595
+ operator: match[2],
10596
+ threshold: Number(match[3])
10597
+ };
10598
+ });
10599
+ }
10600
+ function evaluateMlflowMetricGates(run, gates) {
10601
+ const metrics = new Map(run.data.metrics.map((metric) => [metric.key, metric.value]));
10602
+ return gates.map((gate) => {
10603
+ const actual = metrics.get(gate.metric) ?? null;
10604
+ return {
10605
+ ...gate,
10606
+ actual,
10607
+ passed: actual === null ? false : compare(actual, gate.operator, gate.threshold),
10608
+ ...actual === null ? { reason: "missing-metric" } : {}
10609
+ };
10610
+ });
10611
+ }
10612
+ function compare(actual, operator, threshold) {
10613
+ switch (operator) {
10614
+ case ">=":
10615
+ return actual >= threshold;
10616
+ case ">":
10617
+ return actual > threshold;
10618
+ case "<=":
10619
+ return actual <= threshold;
10620
+ case "<":
10621
+ return actual < threshold;
10622
+ case "==":
10623
+ return actual === threshold;
10624
+ case "!=":
10625
+ return actual !== threshold;
10626
+ }
10627
+ }
10628
+
10629
+ // src/commands/import-mlflow.ts
10630
+ async function cmdImportMlflow(runId, options = {}) {
10631
+ const env = options.env ?? process.env;
10632
+ const apiUrl = options.apiUrl ?? env.FX_API_URL;
10633
+ const apiKey = options.apiKey ?? env.FX_API_KEY;
10634
+ const tenantId = options.tenantId ?? env.FX_ORG_ID;
10635
+ const workspaceHost = options.workspaceHost ?? env.DATABRICKS_HOST;
10636
+ const gatesText = options.gates ?? env.FX_MLFLOW_GATES;
10637
+ if (!apiUrl || !apiKey || !tenantId || !workspaceHost || !gatesText) {
10638
+ process.stderr.write(
10639
+ 'Usage: fx test import-mlflow <run-id> --workspace-host <url> --gates "accuracy>=0.9" [hosted profile flags]\n'
10640
+ );
10641
+ return 1;
10642
+ }
10643
+ const auth = resolveDatabricksAuth(env);
10644
+ const client = new DatabricksMlflowClient({
10645
+ host: workspaceHost,
10646
+ auth,
10647
+ fetchImpl: options.fetchImpl
10648
+ });
10649
+ const run = await client.getRun(runId);
10650
+ if (run.info.run_id !== runId) {
10651
+ throw new Error(`Databricks returned MLflow run ${run.info.run_id}, expected ${runId}`);
10652
+ }
10653
+ const nativeRunUrl = client.runUrl(run);
10654
+ const input = mlflowRunToQualityEvidence(run, {
10655
+ gates: gatesText,
10656
+ workspaceHost: client.host,
10657
+ nativeRunUrl,
10658
+ suite: options.suite,
10659
+ externalId: options.externalId
10660
+ });
10661
+ const api = new ApiClient({
10662
+ baseUrl: apiUrl,
10663
+ apiKey,
10664
+ fetchImpl: options.fetchImpl,
10665
+ ...options.bearerToken ? { bearerToken: options.bearerToken } : {},
10666
+ defaultOrgId: tenantId
10667
+ });
10668
+ const created = await api.testRuns.create(input);
10669
+ process.stdout.write(
10670
+ `Linked Databricks MLflow run ${runId} to Quality Center: ${created.status} (${created.summary.passed}/${created.summary.total} gates passed)
10671
+ `
10672
+ );
10673
+ return created.status === "failed" ? 2 : 0;
10674
+ }
10675
+ function mlflowRunToQualityEvidence(run, options) {
10676
+ const gateResults = evaluateMlflowMetricGates(run, parseMlflowMetricGates(options.gates));
10677
+ const nativeStatus = run.info.status.toUpperCase();
10678
+ const terminalFailure = ["FAILED", "KILLED"].includes(nativeStatus);
10679
+ const stillRunning = ["RUNNING", "SCHEDULED"].includes(nativeStatus);
10680
+ const cases = gateResults.map(
10681
+ (gate) => ({
10682
+ id: `mlflow:${run.info.run_id}:${gate.metric}`,
10683
+ name: `${gate.metric} ${gate.operator} ${gate.threshold}`,
10684
+ status: gate.passed ? "passed" : "failed",
10685
+ durationMs: 0,
10686
+ tags: ["databricks", "mlflow", "native-evaluation"],
10687
+ resourceUrl: options.nativeRunUrl,
10688
+ ...gate.reason ? { error: `Native MLflow metric '${gate.metric}' was not recorded on this run` } : {},
10689
+ details: {
10690
+ metric: gate.metric,
10691
+ operator: gate.operator,
10692
+ threshold: gate.threshold,
10693
+ actual: gate.actual,
10694
+ mlflowRunId: run.info.run_id,
10695
+ mlflowExperimentId: run.info.experiment_id
10696
+ }
10697
+ })
10698
+ );
10699
+ const passed = cases.filter((item) => item.status === "passed").length;
10700
+ const failed = cases.length - passed;
10701
+ const startedAt = millisToIso(run.info.start_time);
10702
+ const finishedAt = millisToIso(run.info.end_time);
10703
+ return {
10704
+ externalId: options.externalId ?? `databricks-mlflow:${run.info.run_id}`,
10705
+ source: "databricks-mlflow",
10706
+ suite: options.suite ?? run.info.run_name ?? "Databricks MLflow evaluation",
10707
+ status: stillRunning ? "running" : terminalFailure || failed > 0 ? "failed" : "passed",
10708
+ startedAt,
10709
+ finishedAt,
10710
+ durationMs: startedAt && finishedAt ? Math.max(0, new Date(finishedAt).getTime() - new Date(startedAt).getTime()) : 0,
10711
+ summary: {
10712
+ total: cases.length,
10713
+ passed,
10714
+ failed,
10715
+ skipped: 0,
10716
+ pending: stillRunning ? cases.length : 0
10717
+ },
10718
+ environment: {
10719
+ platform: "databricks",
10720
+ nativeSystem: "managed-mlflow",
10721
+ workspace: options.workspaceHost,
10722
+ mlflowExperimentId: run.info.experiment_id,
10723
+ mlflowRunId: run.info.run_id,
10724
+ mlflowRunStatus: run.info.status,
10725
+ nativeRunUrl: options.nativeRunUrl,
10726
+ evidenceOwnership: "databricks"
10727
+ },
10728
+ revision: {},
10729
+ cases,
10730
+ artifacts: [
10731
+ {
10732
+ name: "Open native MLflow run in Databricks",
10733
+ url: options.nativeRunUrl,
10734
+ mediaType: "text/html"
10735
+ }
10736
+ ]
10737
+ };
10738
+ }
10739
+ function resolveDatabricksAuth(env) {
10740
+ if (env.DATABRICKS_TOKEN) return { kind: "pat", token: env.DATABRICKS_TOKEN };
10741
+ if (env.DATABRICKS_CLIENT_ID && env.DATABRICKS_CLIENT_SECRET) {
10742
+ return {
10743
+ kind: "oauth-m2m",
10744
+ clientId: env.DATABRICKS_CLIENT_ID,
10745
+ clientSecret: env.DATABRICKS_CLIENT_SECRET
10746
+ };
10747
+ }
10748
+ throw new Error(
10749
+ "Native MLflow import requires DATABRICKS_TOKEN or DATABRICKS_CLIENT_ID and DATABRICKS_CLIENT_SECRET"
10750
+ );
10751
+ }
10752
+ function millisToIso(value) {
10753
+ return typeof value === "number" && Number.isFinite(value) ? new Date(value).toISOString() : null;
10754
+ }
10755
+
9661
10756
  // src/bin/fx.ts
9662
10757
  var HELP = `fx \u2014 Fabric Experiments CLI
9663
10758
 
@@ -9677,6 +10772,7 @@ COMMANDS
9677
10772
  preview <experimentId> Mint a signed preview link for a variant. Requires --variant.
9678
10773
  test env <action> Create, destroy, list, or reap Databricks test environments.
9679
10774
  test publish <file> Publish BDD/live/JUnit/CLI evidence to Studio Quality.
10775
+ test import-mlflow <id> Link a native Databricks MLflow run to Studio Quality.
9680
10776
  init databricks-tests Scaffold a Databricks BDD test project.
9681
10777
  login Configure and verify a secure hosted profile.
9682
10778
  logout [profile] Remove a stored hosted profile.
@@ -9706,6 +10802,8 @@ GLOBAL FLAGS
9706
10802
  --profile <name> hosted profile (default: active profile)
9707
10803
  --studio-url <url> login: branded Studio URL
9708
10804
  --databricks-profile <p> Databricks CLI profile used for Apps OAuth
10805
+ --workspace-host <url> Databricks workspace URL for native MLflow evidence.
10806
+ --gates <rules> Native MLflow metric policy, e.g. "accuracy>=0.9,toxicity<=0.05".
9709
10807
  --no-publish push: apply actions without publishing manifest
9710
10808
  --name <name> test env: environment name (for example pr-1234)
9711
10809
  --seed <dir> test env create: JSON fixture directory
@@ -9960,6 +11058,31 @@ async function main() {
9960
11058
  });
9961
11059
  }
9962
11060
  case "test":
11061
+ if (args.positional[0] === "import-mlflow") {
11062
+ if (!args.positional[1]) {
11063
+ process.stderr.write(
11064
+ 'Usage: fx test import-mlflow <run-id> --workspace-host <url> --gates "accuracy>=0.9" [flags]\n'
11065
+ );
11066
+ return 1;
11067
+ }
11068
+ const hosted = await resolveHostedContext({
11069
+ profileName: args.flags.profile,
11070
+ databricksProfile: args.flags["databricks-profile"],
11071
+ apiUrl: args.flags["api-url"],
11072
+ apiKey: args.flags["api-key"],
11073
+ tenantId: explicitTenantId
11074
+ });
11075
+ return cmdImportMlflow(args.positional[1], {
11076
+ tenantId: hosted.tenantId,
11077
+ apiUrl: hosted.apiUrl,
11078
+ apiKey: hosted.apiKey,
11079
+ bearerToken: hosted.bearerToken,
11080
+ workspaceHost: args.flags["workspace-host"],
11081
+ gates: args.flags.gates,
11082
+ suite: args.flags.suite,
11083
+ externalId: args.flags["external-id"]
11084
+ });
11085
+ }
9963
11086
  if (args.positional[0] === "publish") {
9964
11087
  if (!args.positional[1]) {
9965
11088
  process.stderr.write("Usage: fx test publish <evidence.json|junit.xml> [flags]\n");
@@ -9982,7 +11105,7 @@ async function main() {
9982
11105
  });
9983
11106
  }
9984
11107
  if (args.positional[0] !== "env") {
9985
- process.stderr.write("Usage: fx test <env|publish> [args] [flags]\n");
11108
+ process.stderr.write("Usage: fx test <env|publish|import-mlflow> [args] [flags]\n");
9986
11109
  return 1;
9987
11110
  }
9988
11111
  return cmdTestEnv(args.positional[1] ?? "", {