Skip to content

The platform for continuously improving AI agents.

6.1 KB
Raw Blame
import { hashKey } from "@tanstack/react-query";

import type { BLOCKS } from "./catalogue";

export { BLOCKS } from "./catalogue";

export type BlockKind = keyof typeof BLOCKS;
export interface ExperimentBlock {
  id: string;
  kind: BlockKind;
  title: string;
  position: { x: number; y: number };
  config: Record<string, unknown>;
  operation: { tool: string; arguments: Record<string, unknown> } | null;
  notes: string;
}
export interface ExperimentDocument {
  parameters?: Record<
    string,
    {
      type: string;
      description?: string;
      default?: unknown;
      required?: boolean;
      enum?: unknown[] | null;
    }
  >;
  outputs?: Record<string, { node: string; port: string }>;
  nodes: ExperimentBlock[];
  edges: { source: string; target: string; output: string; input: string }[];
}

export function revisionChanges(current: ExperimentDocument, previous?: ExperimentDocument) {
  const before = new Map(previous?.nodes.map((node) => [node.id, node]));
  const after = new Map(current.nodes.map((node) => [node.id, node]));
  const changes: { id: string; label: string; detail: string }[] = [];
  const fields = {
    config: "Settings",
    kind: "Type",
    notes: "Notes",
    operation: "Operation",
    position: "Position",
    title: "Title",
  } as const;

  for (const node of current.nodes) {
    const old = before.get(node.id);
    const changed = old
      ? (Object.keys(fields) as (keyof typeof fields)[]).filter(
          (key) => hashKey([old[key]]) !== hashKey([node[key]])
        )
      : [];
    if (!old || changed.length)
      changes.push({
        detail: old ? `Updated ${changed.map((key) => fields[key]).join(", ")}` : "Step added",
        id: node.id,
        label: node.title,
      });
  }
  for (const node of previous?.nodes ?? []) {
    if (!after.has(node.id))
      changes.push({ detail: "Step removed", id: node.id, label: node.title });
  }

  const oldEdges = new Map(previous?.edges.map((edge) => [hashKey([edge]), edge]));
  const newEdges = new Map(current.edges.map((edge) => [hashKey([edge]), edge]));
  for (const [edges, other, detail] of [
    [newEdges, oldEdges, "Connection added"],
    [oldEdges, newEdges, "Connection removed"],
  ] as const) {
    for (const [id, edge] of edges) {
      if (other.has(id)) continue;
      const nodes = edges === oldEdges ? before : after;
      const from = nodes.get(edge.source)?.title ?? edge.source;
      const to = nodes.get(edge.target)?.title ?? edge.target;
      changes.push({
        detail: `${detail} (${edge.output} → ${edge.input})`,
        id,
        label: `${from} → ${to}`,
      });
    }
  }
  for (const [key, label] of [
    ["parameters", "Parameters"],
    ["outputs", "Outputs"],
  ] as const) {
    if (hashKey([current[key] ?? {}]) !== hashKey([previous?.[key] ?? {}]))
      changes.push({ detail: `${label} updated`, id: key, label });
  }
  return changes;
}
export interface NodeReceipt {
  node: string;
  revision: number;
  action: string;
  identity: string;
  tool: string;
  state: string;
  current: boolean;
  arguments: Record<string, unknown>;
  result: unknown;
  outputs: Record<
    string,
    {
      kind: string;
      model?: string;
      checkpoint?: { step?: number };
      artifact?: string;
      sealed?: boolean;
      [key: string]: unknown;
    }
  >;
  started_at: string | null;
  completed_at: string | null;
  reused_from?: { run: string; node: string; receipt: string } | null;
}
/** What the run's request in hand measured; a figure no record holds is null. */
export interface RequestMetrics {
  seconds_to_first_model_call: number | null;
  seconds_to_run: number | null;
  model_calls: number;
  model_calls_before_run: number | null;
  model_seconds: number | null;
  prompt_tokens: number | null;
  cached_tokens: number | null;
  completion_tokens: number | null;
  estimated_model_cost_usd: number | null;
}
export interface ExperimentScope {
  id: string;
  parent: string;
  parent_receipt: string;
  parent_scope: string;
  run: string;
  index: number;
  variant: string;
  document: ExperimentDocument;
  parameters: Record<string, unknown>;
  state: string;
  error: string;
  outputs: NodeReceipt["outputs"];
  nodes: NodeReceipt[];
}
export interface ExperimentRun {
  scopes?: ExperimentScope[];
  controller?: string | null;
  flow_run?: string | null;
  phase?: string;
  request_key?: string;
  execution?: "flow";
  parameters?: Record<string, unknown>;
  document?: ExperimentDocument;
  id: string;
  state: string;
  revision: number;
  current_revision: number;
  created_at: string;
  completed_at: string | null;
  budget: { committed_usd?: string; remaining_seconds?: number; model_calls_remaining?: number };
  metrics?: RequestMetrics | null;
  nodes: NodeReceipt[];
  artifacts: { id: string; kind: string; name: string; [key: string]: unknown }[];
  result: Record<string, unknown>;
}
export interface ExperimentRevision {
  number: number;
  node_identities: Record<string, string>;
  document: ExperimentDocument;
  note: string;
  created_at: string;
}

export interface ExperimentRecord {
  source_references?: { cell: string; dataset: string }[];
  id: string;
  name: string;
  objective: string;
  version: number;
  document: ExperimentDocument;
  node_identities: Record<string, string>;
  revisions: ExperimentRevision[];
  runs: ExperimentRun[];
}
export const activeRun = (run?: ExperimentRun) =>
  !!run && !["completed", "unmet", "cancelled", "blocked", "exhausted"].includes(run.state);

export const currentRun = (record: ExperimentRecord) => record.runs.find((run) => !run.controller);

export function runLabel(run?: ExperimentRun) {
  if (!run) return "Draft";
  if (run.state === "cancelled" && !run.flow_run && run.execution !== "flow" && !run.nodes.length)
    return "Cancelled before execution";
  const phase = run.phase ?? (activeRun(run) ? "drafting" : run.state);
  return (
    {
      blocked: "Blocked",
      cancelled: "Cancelled",
      completed: "Complete",
      drafting: "Drafting",
      executing: "Executing",
      exhausted: "Limit reached",
      repairing: "Repairing flow",
      stopping: "Stopping",
      unmet: "Incomplete",
      verifying: "Verifying results",
    }[phase] ?? phase
  );
}