@fabricorg/experiments 0.12.0 → 0.14.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/bin/fx.js CHANGED
@@ -20,6 +20,10 @@ var __export = (target, all) => {
20
20
  __defProp(target, name, { get: all[name], enumerable: true });
21
21
  };
22
22
 
23
+ // package.json
24
+ var package_default = {
25
+ version: "0.14.0"};
26
+
23
27
  // ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/external.js
24
28
  var external_exports = {};
25
29
  __export(external_exports, {
@@ -4302,26 +4306,55 @@ var ExperimentSpecBase = external_exports.object({
4302
4306
  isGuardrail: external_exports.boolean().optional()
4303
4307
  })
4304
4308
  ).optional()
4305
- });
4306
- var ExperimentSpec = ExperimentSpecBase.refine(
4307
- (s) => s.holdback === void 0 || s.sampleRate === void 0,
4308
- { message: "Use either `sampleRate` or `holdback`, not both.", path: ["holdback"] }
4309
- ).refine((s) => s.divertTo === void 0 || s.variants.some((v) => v.key === s.divertTo), {
4310
- message: "`divertTo` must reference an existing variant key.",
4311
- path: ["divertTo"]
4312
- }).refine(
4313
- (s) => {
4314
- const withWeight = s.variants.filter((v) => v.weight !== void 0);
4315
- if (withWeight.length === 0) return true;
4316
- if (withWeight.length !== s.variants.length) return false;
4317
- const sum = withWeight.reduce((acc, v) => acc + (v.weight ?? 0), 0);
4318
- return sum === 1e4;
4319
- },
4320
- {
4321
- message: "When variant weights are set, all variants must have weights summing to 10000.",
4322
- path: ["variants"]
4309
+ }).strict();
4310
+ function validateExperimentSpec(spec, ctx) {
4311
+ if (spec.holdback !== void 0 && spec.sampleRate !== void 0) {
4312
+ ctx.addIssue({
4313
+ code: external_exports.ZodIssueCode.custom,
4314
+ message: "Use either `sampleRate` or `holdback`, not both.",
4315
+ path: ["holdback"]
4316
+ });
4323
4317
  }
4324
- );
4318
+ const variantKeys = spec.variants.map((variant) => variant.key);
4319
+ if (new Set(variantKeys).size !== variantKeys.length) {
4320
+ ctx.addIssue({
4321
+ code: external_exports.ZodIssueCode.custom,
4322
+ message: "Variant keys must be unique.",
4323
+ path: ["variants"]
4324
+ });
4325
+ }
4326
+ if (spec.divertTo !== void 0 && !variantKeys.includes(spec.divertTo)) {
4327
+ ctx.addIssue({
4328
+ code: external_exports.ZodIssueCode.custom,
4329
+ message: "divertTo must reference an existing variant key.",
4330
+ path: ["divertTo"]
4331
+ });
4332
+ }
4333
+ const withWeight = spec.variants.filter((variant) => variant.weight !== void 0);
4334
+ if (withWeight.length > 0 && (withWeight.length !== spec.variants.length || withWeight.reduce((sum, variant) => sum + (variant.weight ?? 0), 0) !== 1e4)) {
4335
+ ctx.addIssue({
4336
+ code: external_exports.ZodIssueCode.custom,
4337
+ message: "Variant weights must sum to 10000 and be declared for every variant.",
4338
+ path: ["variants"]
4339
+ });
4340
+ }
4341
+ const metricKeys = (spec.metrics ?? []).map((metric) => metric.key);
4342
+ if (new Set(metricKeys).size !== metricKeys.length) {
4343
+ ctx.addIssue({
4344
+ code: external_exports.ZodIssueCode.custom,
4345
+ message: "Metric keys must be unique.",
4346
+ path: ["metrics"]
4347
+ });
4348
+ }
4349
+ if (spec.environmentIds && new Set(spec.environmentIds).size !== spec.environmentIds.length) {
4350
+ ctx.addIssue({
4351
+ code: external_exports.ZodIssueCode.custom,
4352
+ message: "Environment IDs must be unique.",
4353
+ path: ["environmentIds"]
4354
+ });
4355
+ }
4356
+ }
4357
+ var ExperimentSpec = ExperimentSpecBase.superRefine(validateExperimentSpec);
4325
4358
  external_exports.object({
4326
4359
  experimentId: ExperimentId,
4327
4360
  subjectId: external_exports.string().min(1),
@@ -4503,6 +4536,7 @@ var ActionId = external_exports.enum([
4503
4536
  "experiment.resume",
4504
4537
  "experiment.kill",
4505
4538
  "experiment.declare_winner",
4539
+ "experiment.archive",
4506
4540
  "experiment.update",
4507
4541
  "experiment.guardrail_breach",
4508
4542
  "experiment.workspace_resource_upsert",
@@ -4512,7 +4546,7 @@ var ActionId = external_exports.enum([
4512
4546
  var CreateExperimentInput = ExperimentSpecBase.extend({
4513
4547
  ownerId: external_exports.string().min(1),
4514
4548
  tenantId: external_exports.string().min(1).default("default")
4515
- });
4549
+ }).superRefine(validateExperimentSpec);
4516
4550
  var ExperimentRef = external_exports.object({
4517
4551
  experimentId: ExperimentId,
4518
4552
  tenantId: external_exports.string().min(1).default("default")
@@ -4534,6 +4568,7 @@ var DeclareWinnerInput = ExperimentRef.extend({
4534
4568
  winningVariant: VariantKey,
4535
4569
  justification: external_exports.string().min(1).max(2e3)
4536
4570
  });
4571
+ var ArchiveInput = ExperimentRef;
4537
4572
  var UpdateExperimentInput = ExperimentRef.extend({
4538
4573
  spec: ExperimentSpec
4539
4574
  });
@@ -5186,7 +5221,9 @@ var experimentStateMachine = {
5186
5221
  { from: "paused", to: "running", causedByAction: "experiment.resume" },
5187
5222
  { from: "running", to: "killed", causedByAction: "experiment.kill" },
5188
5223
  { from: "paused", to: "killed", causedByAction: "experiment.kill" },
5189
- { from: "running", to: "concluded", causedByAction: "experiment.declare_winner" }
5224
+ { from: "running", to: "concluded", causedByAction: "experiment.declare_winner" },
5225
+ { from: "killed", to: "archived", causedByAction: "experiment.archive" },
5226
+ { from: "concluded", to: "archived", causedByAction: "experiment.archive" }
5190
5227
  ]
5191
5228
  };
5192
5229
  var separationOfDuties = {
@@ -5244,7 +5281,7 @@ async function executeGovernedExperimentAction(definition, parameters, ctx) {
5244
5281
  for (const policyId of definition.policies ?? []) {
5245
5282
  const policy = policiesById.get(policyId);
5246
5283
  if (!policy) {
5247
- return { success: false, error: `Required policy is not registered: ${policyId}` };
5284
+ return failure(`Required policy is not registered: ${policyId}`, "INTERNAL");
5248
5285
  }
5249
5286
  policyOutcomes.push(
5250
5287
  await policy.evaluate({
@@ -5266,10 +5303,10 @@ async function executeGovernedExperimentAction(definition, parameters, ctx) {
5266
5303
  });
5267
5304
  const blocked = policyOutcomes.find((policy) => policy.result === "block");
5268
5305
  if (blocked) {
5269
- return {
5270
- success: false,
5271
- error: `Policy ${blocked.policyId} blocked ${definition.actionId}: ${blocked.reason ?? "denied"}`
5272
- };
5306
+ return failure(
5307
+ `Policy ${blocked.policyId} blocked ${definition.actionId}: ${blocked.reason ?? "denied"}`,
5308
+ "POLICY_DENIED"
5309
+ );
5273
5310
  }
5274
5311
  }
5275
5312
  if (definition.stateMachine) {
@@ -5279,11 +5316,11 @@ async function executeGovernedExperimentAction(definition, parameters, ctx) {
5279
5316
  actionId: definition.actionId,
5280
5317
  error: transitionError
5281
5318
  });
5282
- return { success: false, error: transitionError };
5319
+ return failure(transitionError, "ILLEGAL_TRANSITION");
5283
5320
  }
5284
5321
  }
5285
5322
  if (!definition.handler) {
5286
- return { success: false, error: `Action ${definition.actionId} has no handler` };
5323
+ return failure(`Action ${definition.actionId} has no handler`, "INTERNAL");
5287
5324
  }
5288
5325
  return definition.handler(ctx, parameters);
5289
5326
  }
@@ -5292,9 +5329,7 @@ async function validateCurrentTransition(definition, parameters, ctx) {
5292
5329
  if (!binding) return null;
5293
5330
  const entityId = binding.getEntityId(parameters);
5294
5331
  if (!entityId) return `Action ${definition.actionId} did not identify an experiment`;
5295
- const params = actionParams({ parameters });
5296
- const tenantId = typeof params.tenantId === "string" ? params.tenantId : ctx.tenantId;
5297
- const experiment = await ctx.db.store.getExperiment(tenantId, entityId);
5332
+ const experiment = await ctx.db.store.getExperiment(ctx.tenantId, entityId);
5298
5333
  if (!experiment) return null;
5299
5334
  const target = typeof binding.targetState === "function" ? binding.targetState(parameters) : binding.targetState;
5300
5335
  const valid = experimentStateMachine.transitions.some(
@@ -5304,8 +5339,7 @@ async function validateCurrentTransition(definition, parameters, ctx) {
5304
5339
  }
5305
5340
  async function findExperiment(ctx, params) {
5306
5341
  if (typeof params.experimentId !== "string") return null;
5307
- const tenantId = typeof params.tenantId === "string" ? params.tenantId : ctx.tenantId;
5308
- return ctx.db.store.getExperiment(tenantId, params.experimentId);
5342
+ return ctx.db.store.getExperiment(ctx.tenantId, params.experimentId);
5309
5343
  }
5310
5344
  function actionParams(ctx) {
5311
5345
  return isRecord(ctx.parameters) ? ctx.parameters : {};
@@ -5324,7 +5358,7 @@ async function appendGovernanceEvent(ctx, parameters, type, payload) {
5324
5358
  await ctx.db.store.appendEvent({
5325
5359
  id: randomUUID(),
5326
5360
  type,
5327
- tenantId: typeof params.tenantId === "string" ? params.tenantId : ctx.tenantId,
5361
+ tenantId: ctx.tenantId,
5328
5362
  experimentId: typeof params.experimentId === "string" ? params.experimentId : "*",
5329
5363
  actorId: ctx.actorId,
5330
5364
  at: (/* @__PURE__ */ new Date()).toISOString(),
@@ -5339,6 +5373,31 @@ async function appendGovernanceEvent(ctx, parameters, type, payload) {
5339
5373
  function isRecord(value) {
5340
5374
  return value !== null && typeof value === "object" && !Array.isArray(value);
5341
5375
  }
5376
+ function failure(error, code) {
5377
+ return { success: false, error, code };
5378
+ }
5379
+ function bindTrustedActionParameters(actionId, parameters, context) {
5380
+ if (!isRecord2(parameters)) return parameters;
5381
+ const bound = { ...parameters, tenantId: context.tenantId };
5382
+ switch (actionId) {
5383
+ case "experiment.create":
5384
+ bound.ownerId = context.actorId;
5385
+ break;
5386
+ case "experiment.approve":
5387
+ bound.approverId = context.actorId;
5388
+ break;
5389
+ case "experiment.environment_publish":
5390
+ bound.publishedBy = context.actorId;
5391
+ break;
5392
+ case "experiment.environment_promote":
5393
+ bound.promotedBy = context.actorId;
5394
+ break;
5395
+ }
5396
+ return bound;
5397
+ }
5398
+ function isRecord2(value) {
5399
+ return value !== null && typeof value === "object" && !Array.isArray(value);
5400
+ }
5342
5401
  var Invoker = class {
5343
5402
  constructor(services) {
5344
5403
  this.services = services;
@@ -5359,32 +5418,48 @@ var Invoker = class {
5359
5418
  async invoke(actionId, params, options = {}) {
5360
5419
  const def = this.registry.get(actionId);
5361
5420
  if (!def) {
5362
- return { success: false, error: `Unknown action: ${actionId}` };
5421
+ return failure2(`Unknown action: ${actionId}`, "NOT_FOUND");
5363
5422
  }
5364
5423
  const parsed = def.schema.safeParse(params);
5365
5424
  if (!parsed.success) {
5366
- return {
5367
- success: false,
5368
- error: `Validation failed: ${JSON.stringify(parsed.error.issues)}`
5369
- };
5425
+ return failure2(
5426
+ `Validation failed: ${JSON.stringify(parsed.error.issues)}`,
5427
+ "VALIDATION_FAILED"
5428
+ );
5370
5429
  }
5371
5430
  const ctx = {
5372
5431
  actionInvocationId: (this.services.uuid ?? randomUUID)(),
5373
- tenantId: options.tenantId ?? "default",
5432
+ tenantId: options.tenantId ?? stringField(parsed.data, "tenantId") ?? "default",
5374
5433
  spaceId: options.spaceId ?? "default",
5375
- actorId: options.actorId ?? "system",
5434
+ actorId: options.actorId ?? serializedActorId(actionId, parsed.data) ?? "system",
5376
5435
  actorType: options.actorType ?? "system",
5377
5436
  correlationId: options.correlationId ?? (this.services.uuid ?? randomUUID)(),
5378
5437
  db: this.services
5379
5438
  };
5380
5439
  try {
5381
- return await executeGovernedExperimentAction(def, parsed.data, ctx);
5440
+ const trustedParameters = bindTrustedActionParameters(actionId, parsed.data, ctx);
5441
+ return await executeGovernedExperimentAction(def, trustedParameters, ctx);
5382
5442
  } catch (e) {
5383
5443
  const err = e;
5384
- return { success: false, error: err.message ?? String(e) };
5444
+ return failure2(err.message ?? String(e), err.code ?? "INTERNAL");
5385
5445
  }
5386
5446
  }
5387
5447
  };
5448
+ function failure2(error, code) {
5449
+ return { success: false, error, code };
5450
+ }
5451
+ function serializedActorId(actionId, parameters) {
5452
+ if (actionId === "experiment.create") return stringField(parameters, "ownerId");
5453
+ if (actionId === "experiment.approve") return stringField(parameters, "approverId");
5454
+ if (actionId === "experiment.environment_publish") return stringField(parameters, "publishedBy");
5455
+ if (actionId === "experiment.environment_promote") return stringField(parameters, "promotedBy");
5456
+ return void 0;
5457
+ }
5458
+ function stringField(value, key) {
5459
+ if (value === null || typeof value !== "object" || Array.isArray(value)) return void 0;
5460
+ const field = value[key];
5461
+ return typeof field === "string" && field.length > 0 ? field : void 0;
5462
+ }
5388
5463
  function requireResourceStore(store) {
5389
5464
  if (!store.getResource || !store.listResources || !store.putResource) {
5390
5465
  throw new Error("Control-plane store does not support workspace resources");
@@ -5406,13 +5481,13 @@ var upsertWorkspaceResource = {
5406
5481
  mutatesDomain: true,
5407
5482
  async handler(ctx, params) {
5408
5483
  const input = UpsertWorkspaceResourceInput.parse(params);
5409
- const resource = WorkspaceResource.parse({ ...input.resource, tenantId: input.tenantId });
5484
+ const resource = WorkspaceResource.parse({ ...input.resource, tenantId: ctx.tenantId });
5410
5485
  const store = requireResourceStore(ctx.db.store);
5411
5486
  await store.put(resource);
5412
5487
  await ctx.db.store.appendEvent({
5413
5488
  id: randomUUID(),
5414
5489
  type: "workspace_resource.upserted",
5415
- tenantId: input.tenantId,
5490
+ tenantId: ctx.tenantId,
5416
5491
  experimentId: `workspace:${resource.kind}:${resource.id}`,
5417
5492
  actorId: ctx.actorId,
5418
5493
  at: (/* @__PURE__ */ new Date()).toISOString(),
@@ -5441,26 +5516,26 @@ var publishEnvironment = {
5441
5516
  if (!store.nextVersion)
5442
5517
  throw new Error("Control-plane store does not support resource versions");
5443
5518
  const environment = Environment.parse(
5444
- await store.get(input.tenantId, "environment", input.environmentId)
5519
+ await store.get(ctx.tenantId, "environment", input.environmentId)
5445
5520
  );
5446
- const features = (await store.list(input.tenantId, "feature")).filter((resource) => resource.kind === "feature").filter((feature) => feature.projectId === environment.projectId && !feature.archived);
5521
+ const features = (await store.list(ctx.tenantId, "feature")).filter((resource) => resource.kind === "feature").filter((feature) => feature.projectId === environment.projectId && !feature.archived);
5447
5522
  const featureIds = new Set(features.map((feature) => feature.id));
5448
- const rules = (await store.list(input.tenantId, "rule")).filter((resource) => resource.kind === "rule").filter(
5523
+ const rules = (await store.list(ctx.tenantId, "rule")).filter((resource) => resource.kind === "rule").filter(
5449
5524
  (rule) => rule.environmentId === environment.id && featureIds.has(rule.featureId) && rule.enabled
5450
5525
  ).sort((a, b) => a.priority - b.priority || a.id.localeCompare(b.id));
5451
5526
  const snapshot = { features, rules };
5452
5527
  const resourceHash = createHash("sha256").update(stableJson(snapshot)).digest("hex");
5453
- const version = await store.nextVersion(input.tenantId, `environment:${environment.id}`);
5528
+ const version = await store.nextVersion(ctx.tenantId, `environment:${environment.id}`);
5454
5529
  const publication = {
5455
5530
  id: randomUUID(),
5456
5531
  kind: "publication",
5457
- tenantId: input.tenantId,
5532
+ tenantId: ctx.tenantId,
5458
5533
  environmentId: environment.id,
5459
5534
  version,
5460
5535
  status: "published",
5461
5536
  resourceHash,
5462
- manifestVersion: await ctx.db.store.currentManifestVersion(input.tenantId),
5463
- publishedBy: input.publishedBy,
5537
+ manifestVersion: await ctx.db.store.currentManifestVersion(ctx.tenantId),
5538
+ publishedBy: ctx.actorId,
5464
5539
  publishedAt: (/* @__PURE__ */ new Date()).toISOString(),
5465
5540
  snapshot
5466
5541
  };
@@ -5468,7 +5543,7 @@ var publishEnvironment = {
5468
5543
  await ctx.db.store.appendEvent({
5469
5544
  id: randomUUID(),
5470
5545
  type: "environment.published",
5471
- tenantId: input.tenantId,
5546
+ tenantId: ctx.tenantId,
5472
5547
  experimentId: `workspace:environment:${environment.id}`,
5473
5548
  actorId: ctx.actorId,
5474
5549
  at: publication.publishedAt,
@@ -5498,10 +5573,10 @@ var promoteEnvironment = {
5498
5573
  const input = PromoteEnvironmentInput.parse(params);
5499
5574
  const store = requireResourceStore(ctx.db.store);
5500
5575
  const source = Environment.parse(
5501
- await store.get(input.tenantId, "environment", input.sourceEnvironmentId)
5576
+ await store.get(ctx.tenantId, "environment", input.sourceEnvironmentId)
5502
5577
  );
5503
5578
  const target = Environment.parse(
5504
- await store.get(input.tenantId, "environment", input.targetEnvironmentId)
5579
+ await store.get(ctx.tenantId, "environment", input.targetEnvironmentId)
5505
5580
  );
5506
5581
  if (source.projectId !== target.projectId) {
5507
5582
  throw new Error("Source and target environments must belong to the same project");
@@ -5509,12 +5584,12 @@ var promoteEnvironment = {
5509
5584
  if (target.rank <= source.rank) {
5510
5585
  throw new Error("Promotions must move to a higher-ranked environment");
5511
5586
  }
5512
- const publications = (await store.list(input.tenantId, "publication")).filter(
5587
+ const publications = (await store.list(ctx.tenantId, "publication")).filter(
5513
5588
  (resource) => resource.kind === "publication" && resource.environmentId === source.id
5514
5589
  ).sort((a, b) => b.version - a.version);
5515
5590
  const sourcePublication = publications[0];
5516
5591
  if (!sourcePublication) throw new Error("Source environment has no published version");
5517
- const currentTargetRules = (await store.list(input.tenantId, "rule")).filter(
5592
+ const currentTargetRules = (await store.list(ctx.tenantId, "rule")).filter(
5518
5593
  (resource) => resource.kind === "rule" && resource.environmentId === target.id && resource.enabled
5519
5594
  );
5520
5595
  const at = (/* @__PURE__ */ new Date()).toISOString();
@@ -5532,7 +5607,7 @@ var promoteEnvironment = {
5532
5607
  await ctx.db.store.appendEvent({
5533
5608
  id: randomUUID(),
5534
5609
  type: "environment.promoted",
5535
- tenantId: input.tenantId,
5610
+ tenantId: ctx.tenantId,
5536
5611
  experimentId: `workspace:environment:${target.id}`,
5537
5612
  actorId: ctx.actorId,
5538
5613
  at,
@@ -5599,7 +5674,7 @@ var createExperiment = {
5599
5674
  async handler(ctx, params) {
5600
5675
  const input = params;
5601
5676
  const store = ctx.db.store;
5602
- const tenantId = input.tenantId ?? ctx.tenantId;
5677
+ const tenantId = ctx.tenantId;
5603
5678
  const existing = await store.getExperiment(tenantId, input.id);
5604
5679
  if (existing) {
5605
5680
  return { success: true, data: { experimentId: existing.id, idempotent: true } };
@@ -5646,7 +5721,7 @@ var createExperiment = {
5646
5721
  metadata: input.metadata,
5647
5722
  approval: null,
5648
5723
  killReason: null,
5649
- ownerId: input.ownerId,
5724
+ ownerId: ctx.actorId,
5650
5725
  tenantId,
5651
5726
  projectId: input.projectId,
5652
5727
  propertyId: input.propertyId,
@@ -5685,7 +5760,7 @@ function lifecycle(actionId, schema, evt, fn, options = {}) {
5685
5760
  async handler(ctx, params) {
5686
5761
  const p = params;
5687
5762
  const store = ctx.db.store;
5688
- const e = await loadExperiment(store, p.tenantId, p.experimentId);
5763
+ const e = await loadExperiment(store, ctx.tenantId, p.experimentId);
5689
5764
  options.policy?.(e, p, ctx);
5690
5765
  const updated = fn(e, p);
5691
5766
  await store.putExperiment(updated);
@@ -5783,6 +5858,13 @@ var declareWinner = lifecycle(
5783
5858
  },
5784
5859
  { targetState: "concluded" }
5785
5860
  );
5861
+ var archive = lifecycle(
5862
+ "experiment.archive",
5863
+ ArchiveInput,
5864
+ "experiment.archived",
5865
+ (experiment) => transition(experiment, "archive"),
5866
+ { targetState: "archived" }
5867
+ );
5786
5868
  var update = {
5787
5869
  actionId: "experiment.update",
5788
5870
  namespace: NAMESPACE,
@@ -5795,7 +5877,7 @@ var update = {
5795
5877
  async handler(ctx, params) {
5796
5878
  const p = params;
5797
5879
  const store = ctx.db.store;
5798
- const e = await loadExperiment(store, p.tenantId, p.experimentId);
5880
+ const e = await loadExperiment(store, ctx.tenantId, p.experimentId);
5799
5881
  const liveStates = /* @__PURE__ */ new Set(["running", "paused", "concluded"]);
5800
5882
  if (liveStates.has(e.state)) {
5801
5883
  const curKeys = new Set(e.variants.map((v) => v.key));
@@ -5858,7 +5940,7 @@ var guardrailBreach = {
5858
5940
  async handler(ctx, params) {
5859
5941
  const p = params;
5860
5942
  const store = ctx.db.store;
5861
- const e = await loadExperiment(store, p.tenantId, p.experimentId);
5943
+ const e = await loadExperiment(store, ctx.tenantId, p.experimentId);
5862
5944
  await store.appendEvent(
5863
5945
  event("guardrail.breached", e, ctx, {
5864
5946
  guardrailKey: p.guardrailKey,
@@ -5896,6 +5978,7 @@ var experimentActions = [
5896
5978
  resume,
5897
5979
  kill,
5898
5980
  declareWinner,
5981
+ archive,
5899
5982
  update,
5900
5983
  guardrailBreach,
5901
5984
  ...workspaceActions
@@ -6074,12 +6157,14 @@ var LocalWarehouse = class {
6074
6157
  }
6075
6158
  dir;
6076
6159
  kind = "local";
6077
- state = { exposures: [], conversions: [] };
6160
+ state = { exposures: [], conversions: [], evalScores: [], spans: [] };
6078
6161
  async init() {
6079
6162
  const fs = await import('fs/promises');
6080
6163
  await fs.mkdir(this.dir, { recursive: true });
6081
6164
  this.state.exposures = await readNdjson(`${this.dir}/exposures.ndjson`);
6082
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`);
6083
6168
  }
6084
6169
  async recordExposures(events) {
6085
6170
  if (events.length === 0) return;
@@ -6091,6 +6176,96 @@ var LocalWarehouse = class {
6091
6176
  this.state.conversions.push(...events);
6092
6177
  await appendNdjson(`${this.dir}/conversions.ndjson`, events);
6093
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
+ }
6094
6269
  async aggregate(query) {
6095
6270
  const exps = this.state.exposures.filter(
6096
6271
  (e) => e.tenantId === query.tenantId && e.experimentId === query.experimentId && (!query.fromIso || e.at >= query.fromIso) && (!query.untilIso || e.at < query.untilIso)
@@ -6194,6 +6369,71 @@ var LocalWarehouse = class {
6194
6369
  return first;
6195
6370
  }
6196
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
+ }
6197
6437
  async function readNdjson(path) {
6198
6438
  const fs = await import('fs/promises');
6199
6439
  try {
@@ -6680,203 +6920,28 @@ async function cmdKill(experimentId, options) {
6680
6920
  );
6681
6921
  return 0;
6682
6922
  }
6683
- async function cmdDev(options = {}) {
6684
- const ws = await loadWorkspace();
6685
- const port = options.port ?? Number(process.env.FX_DEV_PORT ?? 8787);
6686
- const tenantId = options.tenantId ?? "default";
6687
- const manifest = await ws.module.publishManifest(tenantId);
6688
- await writeFile(ws.manifestFile, JSON.stringify(manifest, null, 2), "utf8");
6689
- const server = createServer(async (req, res) => {
6690
- try {
6691
- const url = new URL(req.url ?? "/", `http://${req.headers.host}`);
6692
- res.setHeader("access-control-allow-origin", "*");
6693
- res.setHeader("access-control-allow-headers", "content-type");
6694
- res.setHeader("access-control-allow-methods", "GET,POST,OPTIONS");
6695
- if (req.method === "OPTIONS") {
6696
- res.statusCode = 204;
6697
- res.end();
6698
- return;
6699
- }
6700
- if (req.method === "GET" && url.pathname === "/manifest") {
6701
- const m = await ws.module.publishManifest(tenantId);
6702
- res.setHeader("content-type", "application/json");
6703
- res.setHeader("cache-control", "no-store");
6704
- res.end(JSON.stringify(m));
6705
- log(`GET /manifest \u2192 v${m.manifestVersion} (${m.experiments.length} exps)`);
6706
- return;
6707
- }
6708
- if (req.method === "POST" && url.pathname === "/v1/exposure") {
6709
- const body = await readJson(req);
6710
- const parsed = Exposure.safeParse({
6711
- experimentId: body.experimentId,
6712
- subjectId: body.subjectId,
6713
- variantKey: body.variantKey,
6714
- tenantId: body.tenantId ?? tenantId,
6715
- manifestVersion: body.manifestVersion ?? 0,
6716
- at: body.at ?? (/* @__PURE__ */ new Date()).toISOString(),
6717
- failure: body.failure ?? null
6718
- });
6719
- if (!parsed.success) {
6720
- res.statusCode = 400;
6721
- res.setHeader("content-type", "application/json");
6722
- res.end(JSON.stringify({ error: "invalid exposure", issues: parsed.error.issues }));
6723
- log(
6724
- `POST /v1/exposure 400 invalid: ${parsed.error.issues.map((i) => i.path.join(".")).join(",")}`
6725
- );
6726
- return;
6727
- }
6728
- await ws.warehouse.recordExposures([parsed.data]);
6729
- res.statusCode = 204;
6730
- res.end();
6731
- log(
6732
- `POST /v1/exposure ${parsed.data.experimentId} ${parsed.data.variantKey} ${parsed.data.subjectId}`
6733
- );
6734
- return;
6735
- }
6736
- if (req.method === "POST" && url.pathname === "/v1/conversion") {
6737
- const body = await readJson(req);
6738
- const parsed = ConversionEvent.safeParse({
6739
- ...body,
6740
- tenantId: body.tenantId ?? tenantId,
6741
- at: body.at ?? (/* @__PURE__ */ new Date()).toISOString()
6742
- });
6743
- if (!parsed.success) {
6744
- res.statusCode = 400;
6745
- res.setHeader("content-type", "application/json");
6746
- res.end(JSON.stringify({ error: "invalid conversion", issues: parsed.error.issues }));
6747
- log(
6748
- `POST /v1/conversion 400 invalid: ${parsed.error.issues.map((i) => i.path.join(".")).join(",")}`
6749
- );
6750
- return;
6751
- }
6752
- await ws.warehouse.recordConversions([parsed.data]);
6753
- res.statusCode = 204;
6754
- res.end();
6755
- log(`POST /v1/conversion ${parsed.data.eventName} ${parsed.data.subjectId}`);
6756
- return;
6757
- }
6758
- if (req.method === "GET" && url.pathname === "/healthz") {
6759
- res.setHeader("content-type", "application/json");
6760
- res.end(JSON.stringify({ ok: true, port, tenantId }));
6761
- return;
6762
- }
6763
- res.statusCode = 404;
6764
- res.end("not found");
6765
- } catch (e) {
6766
- const err = e;
6767
- res.statusCode = 500;
6768
- res.end(`error: ${err.message}`);
6769
- log(`ERR ${err.message}`);
6770
- }
6771
- });
6772
- try {
6773
- await new Promise((resolveStart, rejectStart) => {
6774
- server.once("error", rejectStart);
6775
- server.listen(port, "127.0.0.1", () => {
6776
- server.off("error", rejectStart);
6777
- resolveStart();
6778
- });
6779
- });
6780
- } catch (e) {
6781
- const err = e;
6782
- if (err.code === "EADDRINUSE") {
6783
- process.stderr.write(
6784
- `fx dev: port ${port} is already in use.
6785
-
6786
- Another fx dev server may already be running. Either stop that process or choose another port:
6787
6923
 
6788
- fx dev --port ${port + 1}
6789
-
6790
- To find the process on Linux/macOS:
6791
-
6792
- lsof -nP -iTCP:${port} -sTCP:LISTEN
6793
- `
6794
- );
6795
- return 1;
6796
- }
6797
- throw e;
6798
- }
6799
- log(`fx dev \u2014 listening on http://127.0.0.1:${port}`);
6800
- log(" GET /manifest");
6801
- log(" POST /v1/exposure");
6802
- log(" POST /v1/conversion");
6803
- log(` workspace=${ws.root}`);
6804
- await new Promise((resolveStop) => {
6805
- const stop = () => {
6806
- log("shutting down\u2026");
6807
- server.close(() => resolveStop());
6808
- };
6809
- process.once("SIGINT", stop);
6810
- process.once("SIGTERM", stop);
6811
- });
6812
- return 0;
6924
+ // ../manifest-signing/dist/index.js
6925
+ function canonicalSignedPayload(m) {
6926
+ return JSON.stringify(
6927
+ {
6928
+ contentHash: m.contentHash,
6929
+ manifestVersion: m.manifestVersion,
6930
+ schemaVersion: m.schemaVersion,
6931
+ tenantId: m.tenantId
6932
+ },
6933
+ null,
6934
+ 0
6935
+ );
6813
6936
  }
6814
- function log(msg) {
6815
- const t = (/* @__PURE__ */ new Date()).toISOString().slice(11, 19);
6816
- process.stdout.write(`[${t}] ${msg}
6817
- `);
6937
+ function canonicalSignedBytes(m) {
6938
+ return new TextEncoder().encode(canonicalSignedPayload(m));
6818
6939
  }
6819
- function readJson(req) {
6820
- return new Promise((resolveBody, reject) => {
6821
- const chunks = [];
6822
- req.on("data", (c) => chunks.push(c));
6823
- req.on("end", () => {
6824
- try {
6825
- const raw = Buffer.concat(chunks).toString("utf8");
6826
- resolveBody(raw.length === 0 ? {} : JSON.parse(raw));
6827
- } catch (e) {
6828
- reject(e);
6829
- }
6830
- });
6831
- req.on("error", reject);
6832
- });
6833
- }
6834
- async function cmdPlan(dir, options = {}) {
6835
- try {
6836
- const ws = await loadWorkspace();
6837
- const specs = (await loadExperimentDir(resolve(dir))).map((s) => s.spec);
6838
- const tenantId = options.tenantId ?? "default";
6839
- const current = await ws.module.store.listExperiments(tenantId);
6840
- const p = plan({
6841
- specs,
6842
- current,
6843
- tenantId,
6844
- ownerId: options.ownerId ?? "cli",
6845
- approverId: options.approverId ?? "cli-reviewer",
6846
- allowDeletes: options.allowDeletes
6847
- });
6848
- if (options.json) {
6849
- process.stdout.write(`${JSON.stringify(p, null, 2)}
6850
- `);
6851
- } else {
6852
- process.stdout.write(formatPlan(p));
6853
- process.stdout.write("\n");
6854
- }
6855
- if (p.blocked.length > 0) return 2;
6856
- const hasChanges = p.diffs.some((d) => d.kind !== "noop");
6857
- return hasChanges ? 2 : 0;
6858
- } catch (e) {
6859
- process.stderr.write(`fx plan: ${e.message}
6860
- `);
6861
- return 1;
6862
- }
6863
- }
6864
-
6865
- // ../manifest-signing/dist/index.js
6866
- function canonicalSignedPayload(m) {
6867
- return JSON.stringify(
6868
- {
6869
- contentHash: m.contentHash,
6870
- manifestVersion: m.manifestVersion,
6871
- schemaVersion: m.schemaVersion,
6872
- tenantId: m.tenantId
6873
- },
6874
- null,
6875
- 0
6876
- );
6877
- }
6878
- function canonicalSignedBytes(m) {
6879
- return new TextEncoder().encode(canonicalSignedPayload(m));
6940
+ async function getSubtle() {
6941
+ if (globalThis.crypto?.subtle) return globalThis.crypto.subtle;
6942
+ const nodeCryptoSpecifier = "node:crypto";
6943
+ const { webcrypto: webcrypto2 } = await import(nodeCryptoSpecifier);
6944
+ return webcrypto2.subtle;
6880
6945
  }
6881
6946
  async function sha256(data) {
6882
6947
  const subtle = await getSubtle();
@@ -6888,13 +6953,8 @@ function hexEncode(bytes) {
6888
6953
  for (let i = 0; i < bytes.length; i++) s += bytes[i].toString(16).padStart(2, "0");
6889
6954
  return s;
6890
6955
  }
6891
- async function getSubtle() {
6892
- if (typeof crypto !== "undefined" && crypto.subtle) return crypto.subtle;
6893
- const { webcrypto: webcrypto2 } = await import('crypto');
6894
- return webcrypto2.subtle;
6895
- }
6896
6956
  async function signManifest(manifest, key) {
6897
- const subtle = await getSubtle2();
6957
+ const subtle = await getSubtle();
6898
6958
  const payload = canonicalSignedBytes(manifest);
6899
6959
  const signedHash = await sha256(payload);
6900
6960
  const pkcs8 = ed25519PrivateKeyToPkcs8(hexDecode(key.privateKeyHex));
@@ -6913,11 +6973,6 @@ async function signManifest(manifest, key) {
6913
6973
  signedHash: hexEncode(signedHash)
6914
6974
  };
6915
6975
  }
6916
- async function getSubtle2() {
6917
- if (typeof crypto !== "undefined" && crypto.subtle) return crypto.subtle;
6918
- const { webcrypto: webcrypto2 } = await import('crypto');
6919
- return webcrypto2.subtle;
6920
- }
6921
6976
  function hexDecode(hex) {
6922
6977
  if (hex.length % 2 !== 0) throw new Error("hexDecode: odd length");
6923
6978
  const out = new Uint8Array(hex.length / 2);
@@ -6949,8 +7004,34 @@ function ed25519PrivateKeyToPkcs8(seed) {
6949
7004
  out.set(seed, prefix.length);
6950
7005
  return out;
6951
7006
  }
7007
+ function jwksFromKeys(keys) {
7008
+ return {
7009
+ keys: keys.map((k) => ({
7010
+ kid: k.keyId,
7011
+ kty: "OKP",
7012
+ crv: "Ed25519",
7013
+ x: hexToBase64Url(k.publicKeyHex),
7014
+ alg: "EdDSA",
7015
+ use: "sig",
7016
+ status: k.status
7017
+ }))
7018
+ };
7019
+ }
7020
+ function hexToBytes(hex) {
7021
+ const out = new Uint8Array(hex.length / 2);
7022
+ for (let i = 0; i < out.length; i++) out[i] = Number.parseInt(hex.slice(i * 2, i * 2 + 2), 16);
7023
+ return out;
7024
+ }
7025
+ function hexToBase64Url(hex) {
7026
+ return bytesToBase64Url(hexToBytes(hex));
7027
+ }
7028
+ function bytesToBase64Url(bytes) {
7029
+ let s = "";
7030
+ for (let i = 0; i < bytes.length; i++) s += String.fromCharCode(bytes[i]);
7031
+ return btoa(s).replace(/=+$/g, "").replace(/\+/g, "-").replace(/\//g, "_");
7032
+ }
6952
7033
  async function generateKeypair(keyId) {
6953
- const subtle = await getSubtle4();
7034
+ const subtle = await getSubtle();
6954
7035
  const kp = await subtle.generateKey({ name: "Ed25519" }, true, [
6955
7036
  "sign",
6956
7037
  "verify"
@@ -6964,13 +7045,6 @@ async function generateKeypair(keyId) {
6964
7045
  keyId
6965
7046
  };
6966
7047
  }
6967
- async function getSubtle4() {
6968
- if (typeof crypto !== "undefined" && crypto.subtle) return crypto.subtle;
6969
- const { webcrypto: webcrypto2 } = await import('crypto');
6970
- return webcrypto2.subtle;
6971
- }
6972
-
6973
- // src/commands/publish.ts
6974
7048
  async function cmdPublish(options = {}) {
6975
7049
  const ws = await loadWorkspace();
6976
7050
  const tenantId = options.tenantId ?? "default";
@@ -7021,6 +7095,23 @@ async function cmdPublish(options = {}) {
7021
7095
  const out = resolve(options.staticDir);
7022
7096
  await mkdir(out, { recursive: true });
7023
7097
  await writeFile(join(out, "manifest.json"), JSON.stringify(signed), "utf8");
7098
+ const tenantPath = encodeURIComponent(manifest.tenantId);
7099
+ const jwksDirectory = join(out, ".well-known", "jwks");
7100
+ const revocationsDirectory = join(out, ".well-known", "revocations");
7101
+ await mkdir(jwksDirectory, { recursive: true });
7102
+ await mkdir(revocationsDirectory, { recursive: true });
7103
+ await writeFile(
7104
+ join(jwksDirectory, tenantPath),
7105
+ JSON.stringify(
7106
+ jwksFromKeys([{ keyId: key.keyId, publicKeyHex: key.publicKeyHex, status: "active" }])
7107
+ ),
7108
+ "utf8"
7109
+ );
7110
+ await writeFile(
7111
+ join(revocationsDirectory, tenantPath),
7112
+ JSON.stringify({ versions: [] }),
7113
+ "utf8"
7114
+ );
7024
7115
  const tagLoader = await locateTagLoaderBundle();
7025
7116
  if (tagLoader) {
7026
7117
  await copyFile(tagLoader.js, join(out, "experiments.tag.global.js"));
@@ -7028,7 +7119,7 @@ async function cmdPublish(options = {}) {
7028
7119
  await copyFile(tagLoader.map, join(out, "experiments.tag.global.js.map"));
7029
7120
  }
7030
7121
  process.stdout.write(
7031
- `Static export written to ${out} (manifest.json + experiments.tag.global.js)
7122
+ `Static export written to ${out} (signed manifest, JWKS, revocations + experiments.tag.global.js)
7032
7123
  `
7033
7124
  );
7034
7125
  } else {
@@ -7071,6 +7162,222 @@ async function loadOrCreateKey(fxDir, keyId) {
7071
7162
  return kp;
7072
7163
  }
7073
7164
  }
7165
+
7166
+ // src/commands/dev.ts
7167
+ async function cmdDev(options = {}) {
7168
+ const ws = await loadWorkspace();
7169
+ const port = options.port ?? Number(process.env.FX_DEV_PORT ?? 8787);
7170
+ const tenantId = options.tenantId ?? "default";
7171
+ const key = await loadOrCreateKey(ws.fxDir, "dev-default");
7172
+ const manifest = await signedManifest(ws.module.publishManifest.bind(ws.module), tenantId, key);
7173
+ await writeFile(ws.manifestFile, JSON.stringify(manifest, null, 2), "utf8");
7174
+ const server = createServer(async (req, res) => {
7175
+ try {
7176
+ const url = new URL(req.url ?? "/", `http://${req.headers.host}`);
7177
+ res.setHeader("access-control-allow-origin", "*");
7178
+ res.setHeader("access-control-allow-headers", "content-type");
7179
+ res.setHeader("access-control-allow-methods", "GET,POST,OPTIONS");
7180
+ if (req.method === "OPTIONS") {
7181
+ res.statusCode = 204;
7182
+ res.end();
7183
+ return;
7184
+ }
7185
+ if (req.method === "GET" && url.pathname === "/manifest") {
7186
+ const m = await signedManifest(ws.module.publishManifest.bind(ws.module), tenantId, key);
7187
+ res.setHeader("content-type", "application/json");
7188
+ res.setHeader("cache-control", "no-store");
7189
+ res.end(JSON.stringify(m));
7190
+ log(`GET /manifest \u2192 v${m.manifestVersion} (${m.experiments.length} exps)`);
7191
+ return;
7192
+ }
7193
+ const tenantPath = encodeURIComponent(tenantId);
7194
+ if (req.method === "GET" && url.pathname === `/.well-known/jwks/${tenantPath}`) {
7195
+ res.setHeader("content-type", "application/json");
7196
+ res.setHeader("cache-control", "no-store");
7197
+ res.end(
7198
+ JSON.stringify(
7199
+ jwksFromKeys([{ keyId: key.keyId, publicKeyHex: key.publicKeyHex, status: "active" }])
7200
+ )
7201
+ );
7202
+ return;
7203
+ }
7204
+ if (req.method === "GET" && url.pathname === `/.well-known/revocations/${tenantPath}`) {
7205
+ res.setHeader("content-type", "application/json");
7206
+ res.setHeader("cache-control", "no-store");
7207
+ res.end(JSON.stringify({ versions: [] }));
7208
+ return;
7209
+ }
7210
+ if (req.method === "POST" && url.pathname === "/v1/exposure") {
7211
+ const body = await readJson(req);
7212
+ const parsed = Exposure.safeParse({
7213
+ experimentId: body.experimentId,
7214
+ subjectId: body.subjectId,
7215
+ variantKey: body.variantKey,
7216
+ tenantId: body.tenantId ?? tenantId,
7217
+ manifestVersion: body.manifestVersion ?? 0,
7218
+ at: body.at ?? (/* @__PURE__ */ new Date()).toISOString(),
7219
+ failure: body.failure ?? null
7220
+ });
7221
+ if (!parsed.success) {
7222
+ res.statusCode = 400;
7223
+ res.setHeader("content-type", "application/json");
7224
+ res.end(JSON.stringify({ error: "invalid exposure", issues: parsed.error.issues }));
7225
+ log(
7226
+ `POST /v1/exposure 400 invalid: ${parsed.error.issues.map((i) => i.path.join(".")).join(",")}`
7227
+ );
7228
+ return;
7229
+ }
7230
+ await ws.warehouse.recordExposures([parsed.data]);
7231
+ res.statusCode = 204;
7232
+ res.end();
7233
+ log(
7234
+ `POST /v1/exposure ${parsed.data.experimentId} ${parsed.data.variantKey} ${parsed.data.subjectId}`
7235
+ );
7236
+ return;
7237
+ }
7238
+ if (req.method === "POST" && url.pathname === "/v1/conversion") {
7239
+ const body = await readJson(req);
7240
+ const parsed = ConversionEvent.safeParse({
7241
+ ...body,
7242
+ tenantId: body.tenantId ?? tenantId,
7243
+ at: body.at ?? (/* @__PURE__ */ new Date()).toISOString()
7244
+ });
7245
+ if (!parsed.success) {
7246
+ res.statusCode = 400;
7247
+ res.setHeader("content-type", "application/json");
7248
+ res.end(JSON.stringify({ error: "invalid conversion", issues: parsed.error.issues }));
7249
+ log(
7250
+ `POST /v1/conversion 400 invalid: ${parsed.error.issues.map((i) => i.path.join(".")).join(",")}`
7251
+ );
7252
+ return;
7253
+ }
7254
+ await ws.warehouse.recordConversions([parsed.data]);
7255
+ res.statusCode = 204;
7256
+ res.end();
7257
+ log(`POST /v1/conversion ${parsed.data.eventName} ${parsed.data.subjectId}`);
7258
+ return;
7259
+ }
7260
+ if (req.method === "GET" && url.pathname === "/healthz") {
7261
+ res.setHeader("content-type", "application/json");
7262
+ res.end(JSON.stringify({ ok: true, port, tenantId }));
7263
+ return;
7264
+ }
7265
+ res.statusCode = 404;
7266
+ res.end("not found");
7267
+ } catch (e) {
7268
+ const err = e;
7269
+ res.statusCode = 500;
7270
+ res.end(`error: ${err.message}`);
7271
+ log(`ERR ${err.message}`);
7272
+ }
7273
+ });
7274
+ try {
7275
+ await new Promise((resolveStart, rejectStart) => {
7276
+ server.once("error", rejectStart);
7277
+ server.listen(port, "127.0.0.1", () => {
7278
+ server.off("error", rejectStart);
7279
+ resolveStart();
7280
+ });
7281
+ });
7282
+ } catch (e) {
7283
+ const err = e;
7284
+ if (err.code === "EADDRINUSE") {
7285
+ process.stderr.write(
7286
+ `fx dev: port ${port} is already in use.
7287
+
7288
+ Another fx dev server may already be running. Either stop that process or choose another port:
7289
+
7290
+ fx dev --port ${port + 1}
7291
+
7292
+ To find the process on Linux/macOS:
7293
+
7294
+ lsof -nP -iTCP:${port} -sTCP:LISTEN
7295
+ `
7296
+ );
7297
+ return 1;
7298
+ }
7299
+ throw e;
7300
+ }
7301
+ log(`fx dev \u2014 listening on http://127.0.0.1:${port}`);
7302
+ log(" GET /manifest");
7303
+ log(` GET /.well-known/jwks/${encodeURIComponent(tenantId)}`);
7304
+ log(` GET /.well-known/revocations/${encodeURIComponent(tenantId)}`);
7305
+ log(" POST /v1/exposure");
7306
+ log(" POST /v1/conversion");
7307
+ log(` workspace=${ws.root}`);
7308
+ await new Promise((resolveStop) => {
7309
+ const stop = () => {
7310
+ log("shutting down\u2026");
7311
+ server.close(() => resolveStop());
7312
+ };
7313
+ process.once("SIGINT", stop);
7314
+ process.once("SIGTERM", stop);
7315
+ });
7316
+ return 0;
7317
+ }
7318
+ async function signedManifest(publish, tenantId, key) {
7319
+ const manifest = await publish(tenantId);
7320
+ const signature = await signManifest(
7321
+ {
7322
+ schemaVersion: manifest.schemaVersion,
7323
+ manifestVersion: manifest.manifestVersion,
7324
+ tenantId: manifest.tenantId,
7325
+ contentHash: manifest.contentHash
7326
+ },
7327
+ { keyId: key.keyId, privateKeyHex: key.privateKeyHex }
7328
+ );
7329
+ return { ...manifest, signature };
7330
+ }
7331
+ function log(msg) {
7332
+ const t = (/* @__PURE__ */ new Date()).toISOString().slice(11, 19);
7333
+ process.stdout.write(`[${t}] ${msg}
7334
+ `);
7335
+ }
7336
+ function readJson(req) {
7337
+ return new Promise((resolveBody, reject) => {
7338
+ const chunks = [];
7339
+ req.on("data", (c) => chunks.push(c));
7340
+ req.on("end", () => {
7341
+ try {
7342
+ const raw = Buffer.concat(chunks).toString("utf8");
7343
+ resolveBody(raw.length === 0 ? {} : JSON.parse(raw));
7344
+ } catch (e) {
7345
+ reject(e);
7346
+ }
7347
+ });
7348
+ req.on("error", reject);
7349
+ });
7350
+ }
7351
+ async function cmdPlan(dir, options = {}) {
7352
+ try {
7353
+ const ws = await loadWorkspace();
7354
+ const specs = (await loadExperimentDir(resolve(dir))).map((s) => s.spec);
7355
+ const tenantId = options.tenantId ?? "default";
7356
+ const current = await ws.module.store.listExperiments(tenantId);
7357
+ const p = plan({
7358
+ specs,
7359
+ current,
7360
+ tenantId,
7361
+ ownerId: options.ownerId ?? "cli",
7362
+ approverId: options.approverId ?? "cli-reviewer",
7363
+ allowDeletes: options.allowDeletes
7364
+ });
7365
+ if (options.json) {
7366
+ process.stdout.write(`${JSON.stringify(p, null, 2)}
7367
+ `);
7368
+ } else {
7369
+ process.stdout.write(formatPlan(p));
7370
+ process.stdout.write("\n");
7371
+ }
7372
+ if (p.blocked.length > 0) return 2;
7373
+ const hasChanges = p.diffs.some((d) => d.kind !== "noop");
7374
+ return hasChanges ? 2 : 0;
7375
+ } catch (e) {
7376
+ process.stderr.write(`fx plan: ${e.message}
7377
+ `);
7378
+ return 1;
7379
+ }
7380
+ }
7074
7381
  async function cmdImportMojito(inputDir, options = {}) {
7075
7382
  const root = resolve(inputDir);
7076
7383
  const outDir = resolve(options.outputDir ?? join(root, "converted"));
@@ -7554,7 +7861,9 @@ var TestRunArtifact = external_exports.object({
7554
7861
  });
7555
7862
  var CreateTestRunInput = external_exports.object({
7556
7863
  externalId: external_exports.string().min(1).max(300).optional(),
7557
- source: external_exports.enum(["bdd", "live-suite", "junit", "cli", "other"]),
7864
+ // 'eval-run' rows are written by the API itself when an eval run concludes
7865
+ // (Quality Center evidence for the evals suite) — never via testRuns.create.
7866
+ source: external_exports.enum(["bdd", "live-suite", "junit", "cli", "other", "eval-run", "databricks-mlflow"]),
7558
7867
  suite: external_exports.string().min(1).max(240),
7559
7868
  status: TestRunStatus,
7560
7869
  startedAt: external_exports.string().datetime().nullable().optional(),
@@ -7566,33 +7875,373 @@ var CreateTestRunInput = external_exports.object({
7566
7875
  cases: external_exports.array(TestCaseResult).max(2e3).default([]),
7567
7876
  artifacts: external_exports.array(TestRunArtifact).max(100).default([])
7568
7877
  });
7569
- var TestRun = CreateTestRunInput.extend({
7570
- id: external_exports.string().uuid(),
7571
- orgId: external_exports.string(),
7572
- createdBy: external_exports.string(),
7573
- createdAt: external_exports.string().datetime(),
7574
- updatedAt: external_exports.string().datetime()
7878
+ var TestRun = CreateTestRunInput.extend({
7879
+ id: external_exports.string().uuid(),
7880
+ orgId: external_exports.string(),
7881
+ createdBy: external_exports.string(),
7882
+ createdAt: external_exports.string().datetime(),
7883
+ updatedAt: external_exports.string().datetime()
7884
+ });
7885
+ var TestRunListInput = external_exports.object({
7886
+ status: TestRunStatus.optional(),
7887
+ source: CreateTestRunInput.shape.source.optional(),
7888
+ suite: external_exports.string().min(1).max(240).optional(),
7889
+ targetPack: external_exports.string().min(1).max(120).regex(/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/).optional(),
7890
+ limit: external_exports.coerce.number().int().min(1).max(200).optional(),
7891
+ offset: external_exports.coerce.number().int().min(0).max(1e5).optional()
7892
+ });
7893
+ var TestRunListResponse = external_exports.object({
7894
+ runs: external_exports.array(TestRun.omit({ cases: true }))
7895
+ });
7896
+ var HarnessOperatorDefinition = external_exports.object({
7897
+ name: external_exports.enum(["quality-status", "srm-watcher", "analyst"]),
7898
+ kind: external_exports.literal("job"),
7899
+ description: external_exports.string(),
7900
+ mutates: external_exports.boolean()
7901
+ });
7902
+ var HarnessOperatorListResponse = external_exports.array(HarnessOperatorDefinition);
7903
+ var HarnessJobInput = external_exports.record(external_exports.unknown()).default({});
7904
+ var HarnessJobResponse = external_exports.record(external_exports.unknown());
7905
+ var DatasetSummary = external_exports.object({
7906
+ id: external_exports.string(),
7907
+ name: external_exports.string(),
7908
+ description: external_exports.string().optional(),
7909
+ latestVersion: external_exports.number().int(),
7910
+ exampleCount: external_exports.number().int(),
7911
+ createdAtIso: external_exports.string().datetime(),
7912
+ updatedAtIso: external_exports.string().datetime()
7913
+ });
7914
+ var DatasetListResponse = external_exports.object({ datasets: external_exports.array(DatasetSummary) });
7915
+ var CreateDatasetInput = external_exports.object({
7916
+ id: external_exports.string().min(2).max(64).regex(/^[a-z][a-z0-9-]*$/),
7917
+ name: external_exports.string().min(1).max(120),
7918
+ description: external_exports.string().max(2e3).optional()
7919
+ });
7920
+ var DatasetExampleWire = external_exports.object({
7921
+ exampleId: external_exports.string().uuid(),
7922
+ input: external_exports.unknown(),
7923
+ expectedOutput: external_exports.unknown().optional(),
7924
+ metadata: external_exports.record(external_exports.unknown()).default({}),
7925
+ split: external_exports.enum(["train", "test", "validation"]).default("test")
7926
+ });
7927
+ var AddExamplesInput = external_exports.object({
7928
+ examples: external_exports.array(DatasetExampleWire).min(1).max(1e3)
7929
+ });
7930
+ var AddExamplesResponse = external_exports.object({ added: external_exports.number().int() });
7931
+ var ListExamplesInput = external_exports.object({
7932
+ version: external_exports.coerce.number().int().min(1).optional(),
7933
+ split: external_exports.enum(["train", "test", "validation"]).optional(),
7934
+ limit: external_exports.coerce.number().int().min(1).max(500).default(100),
7935
+ offset: external_exports.coerce.number().int().min(0).default(0)
7936
+ });
7937
+ var ListExamplesResponse = external_exports.object({
7938
+ examples: external_exports.array(DatasetExampleWire),
7939
+ total: external_exports.number().int()
7940
+ });
7941
+ var CreateDatasetVersionInput = external_exports.object({ note: external_exports.string().max(500).optional() });
7942
+ var DatasetVersionWire = external_exports.object({
7943
+ datasetId: external_exports.string(),
7944
+ version: external_exports.number().int(),
7945
+ exampleCount: external_exports.number().int(),
7946
+ contentHash: external_exports.string(),
7947
+ createdAtIso: external_exports.string().datetime(),
7948
+ note: external_exports.string().optional()
7949
+ });
7950
+ var DatasetVersionListResponse = external_exports.object({
7951
+ versions: external_exports.array(DatasetVersionWire)
7952
+ });
7953
+ var EvalRunTargetWire = external_exports.discriminatedUnion("kind", [
7954
+ external_exports.object({ kind: external_exports.literal("dataset"), datasetId: external_exports.string(), version: external_exports.number().int().min(1) }),
7955
+ external_exports.object({
7956
+ kind: external_exports.literal("experiment"),
7957
+ experimentId: external_exports.string(),
7958
+ metricEventName: external_exports.string().optional()
7959
+ })
7960
+ ]);
7961
+ var CreateEvalRunInput = external_exports.object({
7962
+ target: EvalRunTargetWire,
7963
+ evaluatorNames: external_exports.array(external_exports.string().min(1)).min(1).max(10),
7964
+ maxJudgeTokens: external_exports.number().int().min(0).optional(),
7965
+ /**
7966
+ * Quality Center policy for binary evaluators: the run's companion
7967
+ * fx.test_runs evidence row is `failed` when any binary evaluator's pass
7968
+ * rate lands below this threshold, even if the run itself succeeded.
7969
+ * Defaults server-side to 0.9.
7970
+ */
7971
+ passThreshold: external_exports.number().min(0).max(1).optional()
7972
+ });
7973
+ var EvalRunGenerationWire = external_exports.object({
7974
+ promptId: external_exports.string(),
7975
+ promptVersion: external_exports.number().int().min(1),
7976
+ datasetId: external_exports.string(),
7977
+ datasetVersion: external_exports.number().int().min(1),
7978
+ maxExamples: external_exports.number().int().min(1)
7979
+ });
7980
+ var EvalRunSummary = external_exports.object({
7981
+ runId: external_exports.string(),
7982
+ target: EvalRunTargetWire,
7983
+ generation: EvalRunGenerationWire.optional(),
7984
+ evaluatorNames: external_exports.array(external_exports.string()),
7985
+ status: external_exports.enum(["pending", "running", "succeeded", "failed", "cancelled"]),
7986
+ scoredExamples: external_exports.number().int(),
7987
+ totalExamples: external_exports.number().int(),
7988
+ tokensSpent: external_exports.number().int(),
7989
+ costUsd: external_exports.number().nullable(),
7990
+ passThreshold: external_exports.number(),
7991
+ createdAtIso: external_exports.string().datetime(),
7992
+ startedAtIso: external_exports.string().datetime().optional(),
7993
+ finishedAtIso: external_exports.string().datetime().optional(),
7994
+ error: external_exports.string().optional()
7995
+ });
7996
+ var EvalRunListInput = external_exports.object({
7997
+ limit: external_exports.coerce.number().int().min(1).max(200).default(50),
7998
+ offset: external_exports.coerce.number().int().min(0).default(0),
7999
+ status: external_exports.enum(["pending", "running", "succeeded", "failed", "cancelled"]).optional()
8000
+ });
8001
+ var EvalRunListResponse = external_exports.object({ runs: external_exports.array(EvalRunSummary) });
8002
+ var EvaluatorAggregateWire = external_exports.object({
8003
+ evaluatorName: external_exports.string(),
8004
+ evaluatorVersion: external_exports.string(),
8005
+ scored: external_exports.number().int(),
8006
+ unscored: external_exports.number().int(),
8007
+ meanScore: external_exports.number().nullable(),
8008
+ passRate: external_exports.object({ rate: external_exports.number(), low: external_exports.number(), high: external_exports.number() }).nullable(),
8009
+ labelCounts: external_exports.record(external_exports.number().int()),
8010
+ totalTokens: external_exports.number().int(),
8011
+ meanLatencyMs: external_exports.number().nullable()
8012
+ });
8013
+ var EvalRunDetail = external_exports.object({
8014
+ run: EvalRunSummary,
8015
+ aggregates: external_exports.array(EvaluatorAggregateWire)
8016
+ });
8017
+ var EvalScoreWire = external_exports.object({
8018
+ itemId: external_exports.string(),
8019
+ evaluatorName: external_exports.string(),
8020
+ evaluatorVersion: external_exports.string(),
8021
+ label: external_exports.string().nullable(),
8022
+ score: external_exports.number().nullable(),
8023
+ explanation: external_exports.string().nullable(),
8024
+ latencyMs: external_exports.number()
8025
+ });
8026
+ var EvalScoreListInput = external_exports.object({
8027
+ evaluatorName: external_exports.string().optional(),
8028
+ limit: external_exports.coerce.number().int().min(1).max(500).default(100),
8029
+ offset: external_exports.coerce.number().int().min(0).default(0)
8030
+ });
8031
+ var EvalScoreListResponse = external_exports.object({
8032
+ scores: external_exports.array(EvalScoreWire),
8033
+ total: external_exports.number().int()
8034
+ });
8035
+ var PromptMessageWire = external_exports.object({
8036
+ role: external_exports.enum(["system", "user", "assistant"]),
8037
+ content: external_exports.string().min(1).max(1e5)
8038
+ });
8039
+ var PromptTemplateWire = external_exports.object({
8040
+ messages: external_exports.array(PromptMessageWire).min(1).max(50),
8041
+ params: external_exports.object({
8042
+ model: external_exports.string().max(256).optional(),
8043
+ temperature: external_exports.number().min(0).max(2).optional(),
8044
+ maxTokens: external_exports.number().int().min(1).max(2e5).optional(),
8045
+ topP: external_exports.number().min(0).max(1).optional()
8046
+ }).default({})
8047
+ });
8048
+ var PromptSummary = external_exports.object({
8049
+ id: external_exports.string(),
8050
+ name: external_exports.string(),
8051
+ description: external_exports.string().optional(),
8052
+ latestVersion: external_exports.number().int(),
8053
+ createdAtIso: external_exports.string().datetime(),
8054
+ updatedAtIso: external_exports.string().datetime()
8055
+ });
8056
+ var PromptListResponse = external_exports.object({ prompts: external_exports.array(PromptSummary) });
8057
+ var CreatePromptInput = external_exports.object({
8058
+ id: external_exports.string().min(2).max(64).regex(/^[a-z][a-z0-9-]*$/),
8059
+ name: external_exports.string().min(1).max(120),
8060
+ description: external_exports.string().max(2e3).optional()
8061
+ });
8062
+ var PromptVersionWire = external_exports.object({
8063
+ promptId: external_exports.string(),
8064
+ version: external_exports.number().int(),
8065
+ template: PromptTemplateWire,
8066
+ contentHash: external_exports.string(),
8067
+ variables: external_exports.array(external_exports.string()),
8068
+ createdAtIso: external_exports.string().datetime(),
8069
+ note: external_exports.string().optional()
8070
+ });
8071
+ var CreatePromptVersionInput = external_exports.object({
8072
+ template: PromptTemplateWire,
8073
+ note: external_exports.string().max(500).optional()
8074
+ });
8075
+ var PromptVersionListResponse = external_exports.object({
8076
+ versions: external_exports.array(PromptVersionWire)
8077
+ });
8078
+ var PlaygroundInvokeInput = external_exports.object({
8079
+ /** Registry reference (promptId + optional version, defaulting to latest)... */
8080
+ promptId: external_exports.string().optional(),
8081
+ version: external_exports.number().int().min(1).optional(),
8082
+ /** ...or an inline template (draft mode). Exactly one source is required. */
8083
+ template: PromptTemplateWire.optional(),
8084
+ variables: external_exports.record(external_exports.string()).default({})
8085
+ });
8086
+ var PlaygroundInvokeResponse = external_exports.object({
8087
+ messages: external_exports.array(PromptMessageWire),
8088
+ missingVariables: external_exports.array(external_exports.string()),
8089
+ text: external_exports.string(),
8090
+ inputTokens: external_exports.number().int(),
8091
+ outputTokens: external_exports.number().int(),
8092
+ latencyMs: external_exports.number(),
8093
+ modelEndpoint: external_exports.string(),
8094
+ /** Manifest cost of this invocation; null when the endpoint is unpriced. */
8095
+ costUsd: external_exports.number().nullable()
8096
+ });
8097
+ var PlaygroundReplayInput = external_exports.object({
8098
+ promptId: external_exports.string(),
8099
+ version: external_exports.number().int().min(1),
8100
+ datasetId: external_exports.string(),
8101
+ datasetVersion: external_exports.number().int().min(1),
8102
+ evaluatorNames: external_exports.array(external_exports.string().min(1)).min(1).max(10),
8103
+ /** Shared budget: generation AND judge tokens both count against it. */
8104
+ maxJudgeTokens: external_exports.number().int().min(0).optional(),
8105
+ /** Cap on examples replayed through the model. */
8106
+ maxExamples: external_exports.number().int().min(1).max(200).default(50)
8107
+ });
8108
+ var VariantEvalWire = external_exports.object({
8109
+ variantKey: external_exports.string(),
8110
+ evaluatorName: external_exports.string(),
8111
+ evaluatorVersion: external_exports.string(),
8112
+ scored: external_exports.number().int(),
8113
+ unscored: external_exports.number().int(),
8114
+ meanScore: external_exports.number().nullable(),
8115
+ passCount: external_exports.number().int(),
8116
+ binary: external_exports.boolean()
8117
+ });
8118
+ var VariantEvalListResponse = external_exports.object({ variants: external_exports.array(VariantEvalWire) });
8119
+ var SpanKindWire = external_exports.enum([
8120
+ "LLM",
8121
+ "CHAIN",
8122
+ "RETRIEVER",
8123
+ "EMBEDDING",
8124
+ "TOOL",
8125
+ "AGENT",
8126
+ "RERANKER",
8127
+ "GUARDRAIL",
8128
+ "EVALUATOR",
8129
+ "UNKNOWN"
8130
+ ]);
8131
+ var TraceSummaryWire = external_exports.object({
8132
+ traceId: external_exports.string(),
8133
+ rootSpanName: external_exports.string(),
8134
+ rootSpanKind: SpanKindWire,
8135
+ sessionId: external_exports.string().nullable(),
8136
+ experimentId: external_exports.string().nullable(),
8137
+ variantKey: external_exports.string().nullable(),
8138
+ startedAtIso: external_exports.string().datetime(),
8139
+ durationMs: external_exports.number(),
8140
+ spanCount: external_exports.number().int(),
8141
+ errorCount: external_exports.number().int(),
8142
+ totalInputTokens: external_exports.number().int(),
8143
+ totalOutputTokens: external_exports.number().int()
8144
+ });
8145
+ var TraceListInput = external_exports.object({
8146
+ experimentId: external_exports.string().optional(),
8147
+ variantKey: external_exports.string().optional(),
8148
+ sessionId: external_exports.string().optional(),
8149
+ kind: SpanKindWire.optional(),
8150
+ errorsOnly: external_exports.coerce.boolean().optional(),
8151
+ fromIso: external_exports.string().datetime().optional(),
8152
+ untilIso: external_exports.string().datetime().optional(),
8153
+ limit: external_exports.coerce.number().int().min(1).max(200).default(50),
8154
+ offset: external_exports.coerce.number().int().min(0).default(0)
8155
+ });
8156
+ var TraceListResponse = external_exports.object({
8157
+ traces: external_exports.array(TraceSummaryWire),
8158
+ total: external_exports.number().int()
8159
+ });
8160
+ var SessionTraceWire = TraceSummaryWire.extend({
8161
+ rootInputValue: external_exports.string().nullable(),
8162
+ rootOutputValue: external_exports.string().nullable()
8163
+ });
8164
+ var SessionDetailResponse = external_exports.object({
8165
+ sessionId: external_exports.string(),
8166
+ /** Conversation order: ascending by trace start time. */
8167
+ traces: external_exports.array(SessionTraceWire)
7575
8168
  });
7576
- var TestRunListInput = external_exports.object({
7577
- status: TestRunStatus.optional(),
7578
- source: CreateTestRunInput.shape.source.optional(),
7579
- suite: external_exports.string().min(1).max(240).optional(),
7580
- targetPack: external_exports.string().min(1).max(120).regex(/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/).optional(),
7581
- limit: external_exports.coerce.number().int().min(1).max(200).optional(),
7582
- offset: external_exports.coerce.number().int().min(0).max(1e5).optional()
8169
+ var SpanWire = external_exports.object({
8170
+ traceId: external_exports.string(),
8171
+ spanId: external_exports.string(),
8172
+ parentSpanId: external_exports.string().nullable(),
8173
+ name: external_exports.string(),
8174
+ kind: SpanKindWire,
8175
+ startedAtIso: external_exports.string().datetime(),
8176
+ durationMs: external_exports.number(),
8177
+ status: external_exports.enum(["UNSET", "OK", "ERROR"]),
8178
+ statusMessage: external_exports.string().nullable(),
8179
+ sessionId: external_exports.string().nullable(),
8180
+ experimentId: external_exports.string().nullable(),
8181
+ variantKey: external_exports.string().nullable(),
8182
+ inputValue: external_exports.string().nullable(),
8183
+ outputValue: external_exports.string().nullable(),
8184
+ inputTokens: external_exports.number().int().nullable(),
8185
+ outputTokens: external_exports.number().int().nullable(),
8186
+ modelName: external_exports.string().nullable(),
8187
+ /** Ingest-time dollar cost from the model-cost manifest; null when unpriceable. */
8188
+ costUsd: external_exports.number().nullable(),
8189
+ attributes: external_exports.record(external_exports.unknown())
7583
8190
  });
7584
- var TestRunListResponse = external_exports.object({
7585
- runs: external_exports.array(TestRun.omit({ cases: true }))
8191
+ var SpanAnnotationWire = external_exports.object({
8192
+ spanId: external_exports.string(),
8193
+ annotator: external_exports.enum(["human", "llm"]),
8194
+ /** Evaluator name for llm annotations; user id for human ones. */
8195
+ annotatorId: external_exports.string(),
8196
+ label: external_exports.string().nullable(),
8197
+ score: external_exports.number().nullable(),
8198
+ explanation: external_exports.string().nullable(),
8199
+ createdAtIso: external_exports.string().datetime()
7586
8200
  });
7587
- var HarnessOperatorDefinition = external_exports.object({
7588
- name: external_exports.enum(["quality-status", "srm-watcher", "analyst"]),
7589
- kind: external_exports.literal("job"),
7590
- description: external_exports.string(),
7591
- mutates: external_exports.boolean()
8201
+ var TraceDetail = external_exports.object({
8202
+ traceId: external_exports.string(),
8203
+ spans: external_exports.array(SpanWire),
8204
+ annotations: external_exports.array(SpanAnnotationWire)
7592
8205
  });
7593
- var HarnessOperatorListResponse = external_exports.array(HarnessOperatorDefinition);
7594
- var HarnessJobInput = external_exports.record(external_exports.unknown()).default({});
7595
- var HarnessJobResponse = external_exports.record(external_exports.unknown());
8206
+ var AnnotateSpanInput = external_exports.object({
8207
+ spanId: external_exports.string(),
8208
+ label: external_exports.string().max(64).optional(),
8209
+ score: external_exports.number().min(0).max(1).optional(),
8210
+ explanation: external_exports.string().max(1e4).optional()
8211
+ });
8212
+ var SpanAnalyticsInput = external_exports.object({
8213
+ experimentId: external_exports.string().optional(),
8214
+ variantKey: external_exports.string().optional(),
8215
+ groupBy: external_exports.enum(["kind", "model"]).default("kind"),
8216
+ fromIso: external_exports.string().datetime().optional(),
8217
+ untilIso: external_exports.string().datetime().optional()
8218
+ });
8219
+ var SpanAnalyticsResponse = external_exports.object({
8220
+ groups: external_exports.array(
8221
+ external_exports.object({
8222
+ groupKey: external_exports.string(),
8223
+ spanCount: external_exports.number().int(),
8224
+ errorCount: external_exports.number().int(),
8225
+ meanDurationMs: external_exports.number().nullable(),
8226
+ p95DurationMs: external_exports.number().nullable(),
8227
+ totalInputTokens: external_exports.number().int(),
8228
+ totalOutputTokens: external_exports.number().int(),
8229
+ totalCostUsd: external_exports.number()
8230
+ })
8231
+ ),
8232
+ traceCount: external_exports.number().int(),
8233
+ /** Cost over the full filtered span set — NOT restricted by groupBy model. */
8234
+ totalCostUsd: external_exports.number()
8235
+ });
8236
+ var IngestTokenSummary = external_exports.object({
8237
+ tokenId: external_exports.string(),
8238
+ label: external_exports.string(),
8239
+ createdAtIso: external_exports.string().datetime(),
8240
+ revokedAtIso: external_exports.string().datetime().nullable()
8241
+ });
8242
+ var IngestTokenListResponse = external_exports.object({ tokens: external_exports.array(IngestTokenSummary) });
8243
+ var CreateIngestTokenInput = external_exports.object({ label: external_exports.string().min(1).max(120) });
8244
+ var CreatedIngestToken = IngestTokenSummary.extend({ token: external_exports.string() });
7596
8245
  var endpoints = {
7597
8246
  "tenants.me": {
7598
8247
  method: "GET",
@@ -7906,6 +8555,232 @@ var endpoints = {
7906
8555
  mutates: false,
7907
8556
  requiresRole: "viewer"
7908
8557
  },
8558
+ "datasets.list": {
8559
+ method: "GET",
8560
+ path: "/v1/orgs/:orgId/datasets",
8561
+ params: Empty,
8562
+ response: DatasetListResponse,
8563
+ mutates: false,
8564
+ requiresRole: "viewer"
8565
+ },
8566
+ "datasets.create": {
8567
+ method: "POST",
8568
+ path: "/v1/orgs/:orgId/datasets",
8569
+ params: CreateDatasetInput,
8570
+ response: DatasetSummary,
8571
+ mutates: true,
8572
+ requiresRole: "experimenter"
8573
+ },
8574
+ "datasets.get": {
8575
+ method: "GET",
8576
+ path: "/v1/orgs/:orgId/datasets/:datasetId",
8577
+ params: Empty,
8578
+ response: DatasetSummary,
8579
+ mutates: false,
8580
+ requiresRole: "viewer"
8581
+ },
8582
+ "datasets.addExamples": {
8583
+ method: "POST",
8584
+ path: "/v1/orgs/:orgId/datasets/:datasetId/examples",
8585
+ params: AddExamplesInput,
8586
+ response: AddExamplesResponse,
8587
+ mutates: true,
8588
+ requiresRole: "experimenter"
8589
+ },
8590
+ "datasets.listExamples": {
8591
+ method: "GET",
8592
+ path: "/v1/orgs/:orgId/datasets/:datasetId/examples",
8593
+ params: ListExamplesInput,
8594
+ response: ListExamplesResponse,
8595
+ mutates: false,
8596
+ requiresRole: "viewer"
8597
+ },
8598
+ "datasets.createVersion": {
8599
+ method: "POST",
8600
+ path: "/v1/orgs/:orgId/datasets/:datasetId/versions",
8601
+ params: CreateDatasetVersionInput,
8602
+ response: DatasetVersionWire,
8603
+ mutates: true,
8604
+ requiresRole: "experimenter"
8605
+ },
8606
+ "datasets.listVersions": {
8607
+ method: "GET",
8608
+ path: "/v1/orgs/:orgId/datasets/:datasetId/versions",
8609
+ params: Empty,
8610
+ response: DatasetVersionListResponse,
8611
+ mutates: false,
8612
+ requiresRole: "viewer"
8613
+ },
8614
+ "traces.list": {
8615
+ method: "GET",
8616
+ path: "/v1/orgs/:orgId/traces",
8617
+ params: TraceListInput,
8618
+ response: TraceListResponse,
8619
+ mutates: false,
8620
+ requiresRole: "viewer"
8621
+ },
8622
+ "traces.get": {
8623
+ method: "GET",
8624
+ path: "/v1/orgs/:orgId/traces/:traceId",
8625
+ params: Empty,
8626
+ response: TraceDetail,
8627
+ mutates: false,
8628
+ requiresRole: "viewer"
8629
+ },
8630
+ "traces.annotate": {
8631
+ method: "POST",
8632
+ path: "/v1/orgs/:orgId/traces/:traceId/annotations",
8633
+ params: AnnotateSpanInput,
8634
+ response: SpanAnnotationWire,
8635
+ mutates: true,
8636
+ requiresRole: "experimenter"
8637
+ },
8638
+ "traces.analytics": {
8639
+ method: "GET",
8640
+ path: "/v1/orgs/:orgId/traces/analytics",
8641
+ params: SpanAnalyticsInput,
8642
+ response: SpanAnalyticsResponse,
8643
+ mutates: false,
8644
+ requiresRole: "viewer"
8645
+ },
8646
+ "traces.session": {
8647
+ method: "GET",
8648
+ path: "/v1/orgs/:orgId/traces/sessions/:sessionId",
8649
+ params: Empty,
8650
+ response: SessionDetailResponse,
8651
+ mutates: false,
8652
+ requiresRole: "viewer"
8653
+ },
8654
+ "evals.createRun": {
8655
+ method: "POST",
8656
+ path: "/v1/orgs/:orgId/evals/runs",
8657
+ params: CreateEvalRunInput,
8658
+ response: EvalRunSummary,
8659
+ mutates: true,
8660
+ requiresRole: "experimenter"
8661
+ },
8662
+ "evals.listRuns": {
8663
+ method: "GET",
8664
+ path: "/v1/orgs/:orgId/evals/runs",
8665
+ params: EvalRunListInput,
8666
+ response: EvalRunListResponse,
8667
+ mutates: false,
8668
+ requiresRole: "viewer"
8669
+ },
8670
+ "evals.getRun": {
8671
+ method: "GET",
8672
+ path: "/v1/orgs/:orgId/evals/runs/:runId",
8673
+ params: Empty,
8674
+ response: EvalRunDetail,
8675
+ mutates: false,
8676
+ requiresRole: "viewer"
8677
+ },
8678
+ "evals.listScores": {
8679
+ method: "GET",
8680
+ path: "/v1/orgs/:orgId/evals/runs/:runId/scores",
8681
+ params: EvalScoreListInput,
8682
+ response: EvalScoreListResponse,
8683
+ mutates: false,
8684
+ requiresRole: "viewer"
8685
+ },
8686
+ "evals.cancelRun": {
8687
+ method: "POST",
8688
+ path: "/v1/orgs/:orgId/evals/runs/:runId/cancel",
8689
+ params: Empty,
8690
+ response: EvalRunSummary,
8691
+ mutates: true,
8692
+ requiresRole: "experimenter"
8693
+ },
8694
+ "evals.byVariant": {
8695
+ method: "GET",
8696
+ path: "/v1/orgs/:orgId/experiments/:experimentId/evals",
8697
+ params: Empty,
8698
+ response: VariantEvalListResponse,
8699
+ mutates: false,
8700
+ requiresRole: "viewer"
8701
+ },
8702
+ "ingestTokens.list": {
8703
+ method: "GET",
8704
+ path: "/v1/orgs/:orgId/ingest-tokens",
8705
+ params: Empty,
8706
+ response: IngestTokenListResponse,
8707
+ mutates: false,
8708
+ requiresRole: "admin"
8709
+ },
8710
+ "ingestTokens.create": {
8711
+ method: "POST",
8712
+ path: "/v1/orgs/:orgId/ingest-tokens",
8713
+ params: CreateIngestTokenInput,
8714
+ response: CreatedIngestToken,
8715
+ mutates: true,
8716
+ requiresRole: "admin"
8717
+ },
8718
+ "ingestTokens.revoke": {
8719
+ method: "POST",
8720
+ path: "/v1/orgs/:orgId/ingest-tokens/:tokenId/revoke",
8721
+ params: Empty,
8722
+ response: IngestTokenSummary,
8723
+ mutates: true,
8724
+ requiresRole: "admin"
8725
+ },
8726
+ "prompts.list": {
8727
+ method: "GET",
8728
+ path: "/v1/orgs/:orgId/prompts",
8729
+ params: Empty,
8730
+ response: PromptListResponse,
8731
+ mutates: false,
8732
+ requiresRole: "viewer"
8733
+ },
8734
+ "prompts.create": {
8735
+ method: "POST",
8736
+ path: "/v1/orgs/:orgId/prompts",
8737
+ params: CreatePromptInput,
8738
+ response: PromptSummary,
8739
+ mutates: true,
8740
+ requiresRole: "experimenter"
8741
+ },
8742
+ "prompts.get": {
8743
+ method: "GET",
8744
+ path: "/v1/orgs/:orgId/prompts/:promptId",
8745
+ params: Empty,
8746
+ response: PromptSummary,
8747
+ mutates: false,
8748
+ requiresRole: "viewer"
8749
+ },
8750
+ "prompts.createVersion": {
8751
+ method: "POST",
8752
+ path: "/v1/orgs/:orgId/prompts/:promptId/versions",
8753
+ params: CreatePromptVersionInput,
8754
+ response: PromptVersionWire,
8755
+ mutates: true,
8756
+ requiresRole: "experimenter"
8757
+ },
8758
+ "prompts.listVersions": {
8759
+ method: "GET",
8760
+ path: "/v1/orgs/:orgId/prompts/:promptId/versions",
8761
+ params: Empty,
8762
+ response: PromptVersionListResponse,
8763
+ mutates: false,
8764
+ requiresRole: "viewer"
8765
+ },
8766
+ "playground.invoke": {
8767
+ method: "POST",
8768
+ path: "/v1/orgs/:orgId/playground/invoke",
8769
+ params: PlaygroundInvokeInput,
8770
+ response: PlaygroundInvokeResponse,
8771
+ mutates: false,
8772
+ requiresRole: "experimenter"
8773
+ },
8774
+ // 202-style: replay only creates a pending eval run (durable via the
8775
+ // outbox); generation + judging happen in the executor, off the request.
8776
+ "playground.replay": {
8777
+ method: "POST",
8778
+ path: "/v1/orgs/:orgId/playground/replay",
8779
+ params: PlaygroundReplayInput,
8780
+ response: EvalRunSummary,
8781
+ mutates: true,
8782
+ requiresRole: "experimenter"
8783
+ },
7909
8784
  "harness.definitions": {
7910
8785
  method: "GET",
7911
8786
  path: "/v1/orgs/:orgId/harness/admin/agents",
@@ -8102,6 +8977,46 @@ var ApiClient = class {
8102
8977
  get: (orgId) => this.call("saml.get", {}, orgId ? { orgId } : void 0),
8103
8978
  update: (params, orgId) => this.call("saml.update", params, orgId ? { orgId } : void 0)
8104
8979
  };
8980
+ datasets = {
8981
+ list: (orgId) => this.call("datasets.list", {}, orgId ? { orgId } : void 0),
8982
+ create: (params, orgId) => this.call("datasets.create", params, orgId ? { orgId } : void 0),
8983
+ get: (datasetId, orgId) => this.call("datasets.get", {}, orgId ? { orgId, datasetId } : { datasetId }),
8984
+ addExamples: (datasetId, params, orgId) => this.call("datasets.addExamples", params, orgId ? { orgId, datasetId } : { datasetId }),
8985
+ listExamples: (datasetId, params, orgId) => this.call("datasets.listExamples", params, orgId ? { orgId, datasetId } : { datasetId }),
8986
+ createVersion: (datasetId, params, orgId) => this.call("datasets.createVersion", params, orgId ? { orgId, datasetId } : { datasetId }),
8987
+ listVersions: (datasetId, orgId) => this.call("datasets.listVersions", {}, orgId ? { orgId, datasetId } : { datasetId })
8988
+ };
8989
+ evals = {
8990
+ createRun: (params, orgId) => this.call("evals.createRun", params, orgId ? { orgId } : void 0),
8991
+ listRuns: (params, orgId) => this.call("evals.listRuns", params, orgId ? { orgId } : void 0),
8992
+ getRun: (runId, orgId) => this.call("evals.getRun", {}, orgId ? { orgId, runId } : { runId }),
8993
+ listScores: (runId, params, orgId) => this.call("evals.listScores", params, orgId ? { orgId, runId } : { runId }),
8994
+ cancelRun: (runId, orgId) => this.call("evals.cancelRun", {}, orgId ? { orgId, runId } : { runId }),
8995
+ byVariant: (experimentId, orgId) => this.call("evals.byVariant", {}, orgId ? { orgId, experimentId } : { experimentId })
8996
+ };
8997
+ traces = {
8998
+ list: (params, orgId) => this.call("traces.list", params, orgId ? { orgId } : void 0),
8999
+ get: (traceId, orgId) => this.call("traces.get", {}, orgId ? { orgId, traceId } : { traceId }),
9000
+ annotate: (traceId, params, orgId) => this.call("traces.annotate", params, orgId ? { orgId, traceId } : { traceId }),
9001
+ analytics: (params, orgId) => this.call("traces.analytics", params, orgId ? { orgId } : void 0),
9002
+ session: (sessionId, orgId) => this.call("traces.session", {}, orgId ? { orgId, sessionId } : { sessionId })
9003
+ };
9004
+ ingestTokens = {
9005
+ list: (orgId) => this.call("ingestTokens.list", {}, orgId ? { orgId } : void 0),
9006
+ create: (params, orgId) => this.call("ingestTokens.create", params, orgId ? { orgId } : void 0),
9007
+ revoke: (tokenId, orgId) => this.call("ingestTokens.revoke", {}, orgId ? { orgId, tokenId } : { tokenId })
9008
+ };
9009
+ prompts = {
9010
+ list: (orgId) => this.call("prompts.list", {}, orgId ? { orgId } : void 0),
9011
+ create: (params, orgId) => this.call("prompts.create", params, orgId ? { orgId } : void 0),
9012
+ get: (promptId, orgId) => this.call("prompts.get", {}, orgId ? { orgId, promptId } : { promptId }),
9013
+ createVersion: (promptId, params, orgId) => this.call("prompts.createVersion", params, orgId ? { orgId, promptId } : { promptId }),
9014
+ listVersions: (promptId, orgId) => this.call("prompts.listVersions", {}, orgId ? { orgId, promptId } : { promptId })
9015
+ };
9016
+ playground = {
9017
+ invoke: (params, orgId) => this.call("playground.invoke", params, orgId ? { orgId } : void 0),
9018
+ replay: (params, orgId) => this.call("playground.replay", params, orgId ? { orgId } : void 0)
9019
+ };
8105
9020
  testRuns = {
8106
9021
  list: (params = {}, orgId) => this.call("testRuns.list", params, orgId ? { orgId } : void 0),
8107
9022
  get: (runId, orgId) => this.call("testRuns.get", {}, orgId ? { orgId, runId } : { runId }),
@@ -8307,9 +9222,11 @@ var FILES = {
8307
9222
  2
8308
9223
  )}
8309
9224
  `,
8310
- "cucumber.mjs": `export default {
9225
+ "cucumber.mjs": `process.env.DBX_TEST_PROFILE ??= 'local';
9226
+
9227
+ export default {
8311
9228
  paths: ['features/**/*.feature'],
8312
- import: ['features/support/steps.ts'],
9229
+ import: ['cucumber-register.mjs'],
8313
9230
  format: [
8314
9231
  'progress',
8315
9232
  ['junit', 'reports/bdd-junit.xml'],
@@ -8318,6 +9235,11 @@ var FILES = {
8318
9235
  ['@fabricorg/databricks-bdd/evidence-formatter', 'reports/evidence.json'],
8319
9236
  ],
8320
9237
  };
9238
+ `,
9239
+ "cucumber-register.mjs": `import { register } from 'tsx/esm/api';
9240
+
9241
+ register();
9242
+ await import('./features/support/steps.ts');
8321
9243
  `,
8322
9244
  "features/support/steps.ts": `import '@fabricorg/databricks-bdd/steps';
8323
9245
  `,
@@ -8801,7 +9723,7 @@ function normalizeTestEvidence(value, options = {}) {
8801
9723
  if (kind === "databricks-bdd") {
8802
9724
  const cases = arrayOfRecords(evidence.scenarios).map((scenario, index) => {
8803
9725
  const failures = arrayOfRecords(scenario.failures);
8804
- const statementId = failures.find((failure) => typeof failure.statementId === "string")?.statementId;
9726
+ const statementId = failures.find((failure3) => typeof failure3.statementId === "string")?.statementId;
8805
9727
  return {
8806
9728
  id: `${scenario.uri ?? "scenario"}:${index}`,
8807
9729
  name: String(scenario.name ?? `Scenario ${index + 1}`),
@@ -8948,14 +9870,14 @@ function parseEvidenceText(text) {
8948
9870
  const suites = collectSuites(parsed.testsuites ?? parsed.testsuite);
8949
9871
  const cases = suites.flatMap(
8950
9872
  (suite, suiteIndex) => asRecords(suite.testcase).map((testCase, caseIndex) => {
8951
- const failure = testCase.failure ?? testCase.error;
9873
+ const failure3 = testCase.failure ?? testCase.error;
8952
9874
  const skipped = testCase.skipped;
8953
- const error = xmlText(failure);
9875
+ const error = xmlText(failure3);
8954
9876
  return {
8955
9877
  id: `${suite["@_name"] ?? suiteIndex}:${testCase["@_name"] ?? caseIndex}`,
8956
9878
  name: String(testCase["@_name"] ?? `Test ${caseIndex + 1}`),
8957
9879
  uri: String(testCase["@_classname"] ?? suite["@_name"] ?? ""),
8958
- status: failure ? "failed" : skipped ? "skipped" : "passed",
9880
+ status: failure3 ? "failed" : skipped ? "skipped" : "passed",
8959
9881
  durationMs: Math.round(Number(testCase["@_time"] ?? 0) * 1e3),
8960
9882
  ...error ? { error } : {}
8961
9883
  };
@@ -9501,6 +10423,295 @@ function parseInput(value) {
9501
10423
  return parsed;
9502
10424
  }
9503
10425
 
10426
+ // ../evals/dist/databricks.js
10427
+ var DatabricksBearerProvider = class {
10428
+ host;
10429
+ auth;
10430
+ fetchImpl;
10431
+ timeoutMs;
10432
+ oauthToken = null;
10433
+ constructor(config) {
10434
+ this.host = normalizeDatabricksHost(config.host);
10435
+ this.auth = config.auth;
10436
+ this.fetchImpl = config.fetchImpl ?? fetch;
10437
+ this.timeoutMs = config.timeoutMs ?? 6e4;
10438
+ if (!Number.isFinite(this.timeoutMs) || this.timeoutMs <= 0) {
10439
+ throw new Error("Databricks timeoutMs must be positive");
10440
+ }
10441
+ }
10442
+ async token() {
10443
+ if (this.auth.kind === "pat") return this.auth.token;
10444
+ if (this.oauthToken && this.oauthToken.expiresAt > Date.now() + 6e4) {
10445
+ return this.oauthToken.value;
10446
+ }
10447
+ const response = await this.fetchImpl(`${this.host}/oidc/v1/token`, {
10448
+ method: "POST",
10449
+ headers: {
10450
+ authorization: `Basic ${toBase64(`${this.auth.clientId}:${this.auth.clientSecret}`)}`,
10451
+ "content-type": "application/x-www-form-urlencoded"
10452
+ },
10453
+ body: new URLSearchParams({ grant_type: "client_credentials", scope: "all-apis" }),
10454
+ signal: AbortSignal.timeout(this.timeoutMs)
10455
+ });
10456
+ if (!response.ok) throw new Error(`Databricks OAuth exchange failed (${response.status})`);
10457
+ const body = await response.json();
10458
+ if (!body.access_token) throw new Error("Databricks OAuth exchange returned no access token");
10459
+ this.oauthToken = {
10460
+ value: body.access_token,
10461
+ expiresAt: Date.now() + (body.expires_in ?? 3600) * 1e3
10462
+ };
10463
+ return this.oauthToken.value;
10464
+ }
10465
+ };
10466
+ function normalizeDatabricksHost(host) {
10467
+ return host.startsWith("http://") || host.startsWith("https://") ? host.replace(/\/$/, "") : `https://${host.replace(/\/$/, "")}`;
10468
+ }
10469
+ function toBase64(value) {
10470
+ if (typeof Buffer !== "undefined") return Buffer.from(value).toString("base64");
10471
+ return btoa(value);
10472
+ }
10473
+ var MlflowMetric = external_exports.object({
10474
+ key: external_exports.string().min(1),
10475
+ value: external_exports.number(),
10476
+ timestamp: external_exports.number().optional(),
10477
+ step: external_exports.number().optional()
10478
+ });
10479
+ var MlflowRunResponse = external_exports.object({
10480
+ run: external_exports.object({
10481
+ info: external_exports.object({
10482
+ run_id: external_exports.string().min(1),
10483
+ experiment_id: external_exports.string().min(1),
10484
+ status: external_exports.string().min(1),
10485
+ start_time: external_exports.number().optional(),
10486
+ end_time: external_exports.number().optional(),
10487
+ artifact_uri: external_exports.string().optional(),
10488
+ run_name: external_exports.string().optional()
10489
+ }),
10490
+ data: external_exports.object({
10491
+ metrics: external_exports.array(MlflowMetric).default([]),
10492
+ params: external_exports.array(external_exports.object({ key: external_exports.string(), value: external_exports.string() })).default([]),
10493
+ tags: external_exports.array(external_exports.object({ key: external_exports.string(), value: external_exports.string() })).default([])
10494
+ }).default({ metrics: [], params: [], tags: [] })
10495
+ })
10496
+ });
10497
+ var DatabricksMlflowClient = class {
10498
+ host;
10499
+ authMode;
10500
+ fetchImpl;
10501
+ timeoutMs;
10502
+ bearer;
10503
+ constructor(config) {
10504
+ this.host = normalizeDatabricksHost(config.host);
10505
+ this.authMode = config.auth.kind;
10506
+ this.fetchImpl = config.fetchImpl ?? fetch;
10507
+ this.timeoutMs = config.timeoutMs ?? 6e4;
10508
+ if (!Number.isFinite(this.timeoutMs) || this.timeoutMs <= 0) {
10509
+ throw new Error("Databricks MLflow timeoutMs must be positive");
10510
+ }
10511
+ this.bearer = new DatabricksBearerProvider({
10512
+ host: this.host,
10513
+ auth: config.auth,
10514
+ fetchImpl: this.fetchImpl,
10515
+ timeoutMs: this.timeoutMs
10516
+ });
10517
+ }
10518
+ async getRun(runId) {
10519
+ if (!runId.trim()) throw new Error("MLflow runId is required");
10520
+ const url = new URL(`${this.host}/api/2.0/mlflow/runs/get`);
10521
+ url.searchParams.set("run_id", runId);
10522
+ const response = await this.fetchImpl(url, {
10523
+ headers: { authorization: `Bearer ${await this.bearer.token()}` },
10524
+ signal: AbortSignal.timeout(this.timeoutMs)
10525
+ });
10526
+ if (!response.ok) {
10527
+ const body = await response.text();
10528
+ throw new Error(
10529
+ `Databricks MLflow run lookup failed (${response.status}): ${body.slice(0, 500)}`
10530
+ );
10531
+ }
10532
+ const parsed = MlflowRunResponse.safeParse(await response.json());
10533
+ if (!parsed.success) {
10534
+ throw new Error(
10535
+ `Databricks MLflow returned an invalid run: ${parsed.error.issues[0]?.message ?? "schema mismatch"}`
10536
+ );
10537
+ }
10538
+ return parsed.data.run;
10539
+ }
10540
+ runUrl(run) {
10541
+ return `${this.host}/ml/experiments/${encodeURIComponent(run.info.experiment_id)}/runs/${encodeURIComponent(run.info.run_id)}`;
10542
+ }
10543
+ };
10544
+ function parseMlflowMetricGates(value) {
10545
+ const entries = value.split(",").map((entry) => entry.trim()).filter(Boolean);
10546
+ if (entries.length === 0) throw new Error("At least one MLflow metric gate is required");
10547
+ return entries.map((entry) => {
10548
+ const match = /^(.+?)(>=|<=|==|!=|>|<)(-?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?)$/i.exec(entry);
10549
+ if (!match) throw new Error(`Invalid MLflow metric gate '${entry}'`);
10550
+ const metric = match[1].trim();
10551
+ if (!metric) throw new Error(`Invalid MLflow metric gate '${entry}'`);
10552
+ return {
10553
+ metric,
10554
+ operator: match[2],
10555
+ threshold: Number(match[3])
10556
+ };
10557
+ });
10558
+ }
10559
+ function evaluateMlflowMetricGates(run, gates) {
10560
+ const metrics = new Map(run.data.metrics.map((metric) => [metric.key, metric.value]));
10561
+ return gates.map((gate) => {
10562
+ const actual = metrics.get(gate.metric) ?? null;
10563
+ return {
10564
+ ...gate,
10565
+ actual,
10566
+ passed: actual === null ? false : compare(actual, gate.operator, gate.threshold),
10567
+ ...actual === null ? { reason: "missing-metric" } : {}
10568
+ };
10569
+ });
10570
+ }
10571
+ function compare(actual, operator, threshold) {
10572
+ switch (operator) {
10573
+ case ">=":
10574
+ return actual >= threshold;
10575
+ case ">":
10576
+ return actual > threshold;
10577
+ case "<=":
10578
+ return actual <= threshold;
10579
+ case "<":
10580
+ return actual < threshold;
10581
+ case "==":
10582
+ return actual === threshold;
10583
+ case "!=":
10584
+ return actual !== threshold;
10585
+ }
10586
+ }
10587
+
10588
+ // src/commands/import-mlflow.ts
10589
+ async function cmdImportMlflow(runId, options = {}) {
10590
+ const env = options.env ?? process.env;
10591
+ const apiUrl = options.apiUrl ?? env.FX_API_URL;
10592
+ const apiKey = options.apiKey ?? env.FX_API_KEY;
10593
+ const tenantId = options.tenantId ?? env.FX_ORG_ID;
10594
+ const workspaceHost = options.workspaceHost ?? env.DATABRICKS_HOST;
10595
+ const gatesText = options.gates ?? env.FX_MLFLOW_GATES;
10596
+ if (!apiUrl || !apiKey || !tenantId || !workspaceHost || !gatesText) {
10597
+ process.stderr.write(
10598
+ 'Usage: fx test import-mlflow <run-id> --workspace-host <url> --gates "accuracy>=0.9" [hosted profile flags]\n'
10599
+ );
10600
+ return 1;
10601
+ }
10602
+ const auth = resolveDatabricksAuth(env);
10603
+ const client = new DatabricksMlflowClient({
10604
+ host: workspaceHost,
10605
+ auth,
10606
+ fetchImpl: options.fetchImpl
10607
+ });
10608
+ const run = await client.getRun(runId);
10609
+ if (run.info.run_id !== runId) {
10610
+ throw new Error(`Databricks returned MLflow run ${run.info.run_id}, expected ${runId}`);
10611
+ }
10612
+ const nativeRunUrl = client.runUrl(run);
10613
+ const input = mlflowRunToQualityEvidence(run, {
10614
+ gates: gatesText,
10615
+ workspaceHost: client.host,
10616
+ nativeRunUrl,
10617
+ suite: options.suite,
10618
+ externalId: options.externalId
10619
+ });
10620
+ const api = new ApiClient({
10621
+ baseUrl: apiUrl,
10622
+ apiKey,
10623
+ fetchImpl: options.fetchImpl,
10624
+ ...options.bearerToken ? { bearerToken: options.bearerToken } : {},
10625
+ defaultOrgId: tenantId
10626
+ });
10627
+ const created = await api.testRuns.create(input);
10628
+ process.stdout.write(
10629
+ `Linked Databricks MLflow run ${runId} to Quality Center: ${created.status} (${created.summary.passed}/${created.summary.total} gates passed)
10630
+ `
10631
+ );
10632
+ return created.status === "failed" ? 2 : 0;
10633
+ }
10634
+ function mlflowRunToQualityEvidence(run, options) {
10635
+ const gateResults = evaluateMlflowMetricGates(run, parseMlflowMetricGates(options.gates));
10636
+ const nativeStatus = run.info.status.toUpperCase();
10637
+ const terminalFailure = ["FAILED", "KILLED"].includes(nativeStatus);
10638
+ const stillRunning = ["RUNNING", "SCHEDULED"].includes(nativeStatus);
10639
+ const cases = gateResults.map(
10640
+ (gate) => ({
10641
+ id: `mlflow:${run.info.run_id}:${gate.metric}`,
10642
+ name: `${gate.metric} ${gate.operator} ${gate.threshold}`,
10643
+ status: gate.passed ? "passed" : "failed",
10644
+ durationMs: 0,
10645
+ tags: ["databricks", "mlflow", "native-evaluation"],
10646
+ resourceUrl: options.nativeRunUrl,
10647
+ ...gate.reason ? { error: `Native MLflow metric '${gate.metric}' was not recorded on this run` } : {},
10648
+ details: {
10649
+ metric: gate.metric,
10650
+ operator: gate.operator,
10651
+ threshold: gate.threshold,
10652
+ actual: gate.actual,
10653
+ mlflowRunId: run.info.run_id,
10654
+ mlflowExperimentId: run.info.experiment_id
10655
+ }
10656
+ })
10657
+ );
10658
+ const passed = cases.filter((item) => item.status === "passed").length;
10659
+ const failed = cases.length - passed;
10660
+ const startedAt = millisToIso(run.info.start_time);
10661
+ const finishedAt = millisToIso(run.info.end_time);
10662
+ return {
10663
+ externalId: options.externalId ?? `databricks-mlflow:${run.info.run_id}`,
10664
+ source: "databricks-mlflow",
10665
+ suite: options.suite ?? run.info.run_name ?? "Databricks MLflow evaluation",
10666
+ status: stillRunning ? "running" : terminalFailure || failed > 0 ? "failed" : "passed",
10667
+ startedAt,
10668
+ finishedAt,
10669
+ durationMs: startedAt && finishedAt ? Math.max(0, new Date(finishedAt).getTime() - new Date(startedAt).getTime()) : 0,
10670
+ summary: {
10671
+ total: cases.length,
10672
+ passed,
10673
+ failed,
10674
+ skipped: 0,
10675
+ pending: stillRunning ? cases.length : 0
10676
+ },
10677
+ environment: {
10678
+ platform: "databricks",
10679
+ nativeSystem: "managed-mlflow",
10680
+ workspace: options.workspaceHost,
10681
+ mlflowExperimentId: run.info.experiment_id,
10682
+ mlflowRunId: run.info.run_id,
10683
+ mlflowRunStatus: run.info.status,
10684
+ nativeRunUrl: options.nativeRunUrl,
10685
+ evidenceOwnership: "databricks"
10686
+ },
10687
+ revision: {},
10688
+ cases,
10689
+ artifacts: [
10690
+ {
10691
+ name: "Open native MLflow run in Databricks",
10692
+ url: options.nativeRunUrl,
10693
+ mediaType: "text/html"
10694
+ }
10695
+ ]
10696
+ };
10697
+ }
10698
+ function resolveDatabricksAuth(env) {
10699
+ if (env.DATABRICKS_TOKEN) return { kind: "pat", token: env.DATABRICKS_TOKEN };
10700
+ if (env.DATABRICKS_CLIENT_ID && env.DATABRICKS_CLIENT_SECRET) {
10701
+ return {
10702
+ kind: "oauth-m2m",
10703
+ clientId: env.DATABRICKS_CLIENT_ID,
10704
+ clientSecret: env.DATABRICKS_CLIENT_SECRET
10705
+ };
10706
+ }
10707
+ throw new Error(
10708
+ "Native MLflow import requires DATABRICKS_TOKEN or DATABRICKS_CLIENT_ID and DATABRICKS_CLIENT_SECRET"
10709
+ );
10710
+ }
10711
+ function millisToIso(value) {
10712
+ return typeof value === "number" && Number.isFinite(value) ? new Date(value).toISOString() : null;
10713
+ }
10714
+
9504
10715
  // src/bin/fx.ts
9505
10716
  var HELP = `fx \u2014 Fabric Experiments CLI
9506
10717
 
@@ -9520,6 +10731,7 @@ COMMANDS
9520
10731
  preview <experimentId> Mint a signed preview link for a variant. Requires --variant.
9521
10732
  test env <action> Create, destroy, list, or reap Databricks test environments.
9522
10733
  test publish <file> Publish BDD/live/JUnit/CLI evidence to Studio Quality.
10734
+ test import-mlflow <id> Link a native Databricks MLflow run to Studio Quality.
9523
10735
  init databricks-tests Scaffold a Databricks BDD test project.
9524
10736
  login Configure and verify a secure hosted profile.
9525
10737
  logout [profile] Remove a stored hosted profile.
@@ -9543,12 +10755,14 @@ GLOBAL FLAGS
9543
10755
  --json plan: emit machine-readable output
9544
10756
  --remote-url <url> publish: post to a manifest-worker
9545
10757
  --admin-token <tok> publish: bearer token for --remote-url
9546
- --static <dir> publish: write signed manifest + tag-loader bundle to <dir>
10758
+ --static <dir> publish: write signed manifest + verification files + tag-loader
9547
10759
  --api-url <url> push/preview/test publish: hosted API base URL
9548
10760
  --api-key <key> push/preview/test publish: hosted API key
9549
10761
  --profile <name> hosted profile (default: active profile)
9550
10762
  --studio-url <url> login: branded Studio URL
9551
10763
  --databricks-profile <p> Databricks CLI profile used for Apps OAuth
10764
+ --workspace-host <url> Databricks workspace URL for native MLflow evidence.
10765
+ --gates <rules> Native MLflow metric policy, e.g. "accuracy>=0.9,toxicity<=0.05".
9552
10766
  --no-publish push: apply actions without publishing manifest
9553
10767
  --name <name> test env: environment name (for example pr-1234)
9554
10768
  --seed <dir> test env create: JSON fixture directory
@@ -9573,7 +10787,7 @@ GLOBAL FLAGS
9573
10787
  -h, --help print this help
9574
10788
  -v, --version print version
9575
10789
  `;
9576
- var VERSION2 = "0.12.0";
10790
+ var VERSION2 = package_default.version;
9577
10791
  function parse2(argv) {
9578
10792
  const positional = [];
9579
10793
  const flags = {};
@@ -9803,6 +11017,31 @@ async function main() {
9803
11017
  });
9804
11018
  }
9805
11019
  case "test":
11020
+ if (args.positional[0] === "import-mlflow") {
11021
+ if (!args.positional[1]) {
11022
+ process.stderr.write(
11023
+ 'Usage: fx test import-mlflow <run-id> --workspace-host <url> --gates "accuracy>=0.9" [flags]\n'
11024
+ );
11025
+ return 1;
11026
+ }
11027
+ const hosted = await resolveHostedContext({
11028
+ profileName: args.flags.profile,
11029
+ databricksProfile: args.flags["databricks-profile"],
11030
+ apiUrl: args.flags["api-url"],
11031
+ apiKey: args.flags["api-key"],
11032
+ tenantId: explicitTenantId
11033
+ });
11034
+ return cmdImportMlflow(args.positional[1], {
11035
+ tenantId: hosted.tenantId,
11036
+ apiUrl: hosted.apiUrl,
11037
+ apiKey: hosted.apiKey,
11038
+ bearerToken: hosted.bearerToken,
11039
+ workspaceHost: args.flags["workspace-host"],
11040
+ gates: args.flags.gates,
11041
+ suite: args.flags.suite,
11042
+ externalId: args.flags["external-id"]
11043
+ });
11044
+ }
9806
11045
  if (args.positional[0] === "publish") {
9807
11046
  if (!args.positional[1]) {
9808
11047
  process.stderr.write("Usage: fx test publish <evidence.json|junit.xml> [flags]\n");
@@ -9825,7 +11064,7 @@ async function main() {
9825
11064
  });
9826
11065
  }
9827
11066
  if (args.positional[0] !== "env") {
9828
- process.stderr.write("Usage: fx test <env|publish> [args] [flags]\n");
11067
+ process.stderr.write("Usage: fx test <env|publish|import-mlflow> [args] [flags]\n");
9829
11068
  return 1;
9830
11069
  }
9831
11070
  return cmdTestEnv(args.positional[1] ?? "", {