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