Spaces:
Running

Aynkhn's picture
Deploy WorkPilot demo (part 3)
03608f2 verified
Raw History Blame Contribute Delete
10.8 kB
// Pure helpers for the workflow editor: the plain-language describer (a port of
// core/workflows/dsl.py `describe`), definition -> canvas graph, JSON sync and step edits.
// Every edit returns a NEW definition object; the three views render the same one.
import type { Condition, ConditionOp, Issue, Step, Trigger, WorkflowDefinition } from "./types";
// ---------------------------------------------------------------- describer
/** Python's str() for scalars, so the client text matches the server's exactly. */
function pyStr(v: unknown): string {
if (v === null || v === undefined) return "None";
if (v === true) return "True";
if (v === false) return "False";
return String(v);
}
export function refText(v: unknown): string {
if (typeof v === "string" && v.startsWith("$.")) return `«${v.slice(2)}»`;
if (Array.isArray(v)) return `[${v.map(refText).join(", ")}]`;
if (v && typeof v === "object") {
return `{${Object.entries(v as Record<string, unknown>)
.map(([k, x]) => `${k}: ${refText(x)}`)
.join(", ")}}`;
}
return pyStr(v);
}
export const OP_TEXT: Record<ConditionOp, string> = {
eq: "is",
ne: "is not",
gt: ">",
gte: ">=",
lt: "<",
lte: "<=",
in: "is one of",
not_in: "is not one of",
contains: "contains",
exists: "exists",
not_exists: "is missing",
truthy: "is set",
falsy: "is not set",
};
const UNARY = new Set<ConditionOp>(["exists", "not_exists", "truthy", "falsy"]);
export function describeCondition(c: Condition): string {
const op = OP_TEXT[c.op] ?? c.op;
if (UNARY.has(c.op)) return `${refText(c.left)} ${op}`;
return `${refText(c.left)} ${op} ${refText(c.right ?? null)}`;
}
export function describeTrigger(t: Trigger): string {
if (t.type === "schedule") return `On schedule '${t.cron}' (${t.tz ?? "Asia/Karachi"})`;
if (t.type === "event") {
const extra = t.when?.length ? " when " + t.when.map(describeCondition).join(" and ") : "";
return `When event '${t.event_type}' arrives${extra}`;
}
return "When started by hand";
}
export type StepKind = "tool" | "wait" | "approval";
export function stepKind(s: Step): StepKind {
if (s.wait) return "wait";
if (s.approval) return "approval";
return "tool";
}
export function describeStep(s: Step, i: number): string {
const kind = stepKind(s);
let text: string;
if (kind === "wait") {
text = `wait ${pyStr(s.wait?.seconds)} seconds`;
} else if (kind === "approval") {
text = `ask the owner to sign off: ${s.approval?.summary ?? ""}`;
} else {
const args = Object.entries(s.args ?? {})
.map(([k, v]) => `${k}=${refText(v)}`)
.join(", ");
text = `call ${pyStr(s.tool)}(${args})`;
if (s.for_each) text = `for each item in ${refText(s.for_each)}, ${text}`;
if (s.requires_approval) text += " after a human approves";
}
if (s.when?.length) text += " only if " + s.when.map(describeCondition).join(" and ");
return `${i}. [${s.id}] ${text}`;
}
/** Deterministic plain-language rendering, identical to the server's ``describe``. */
export function describe(defn: WorkflowDefinition): string[] {
return [
describeTrigger(defn.trigger) + ":",
...(defn.steps ?? []).map((s, i) => describeStep(s, i + 1)),
];
}
// ---------------------------------------------------------------- canvas graph
export interface TriggerNodeData extends Record<string, unknown> {
label: string;
trigger: Trigger;
}
export interface StepNodeData extends Record<string, unknown> {
index: number;
step: Step;
kind: StepKind;
conditions: string[];
}
export interface FlowNode {
id: string;
type: "trigger" | "step";
position: { x: number; y: number };
data: TriggerNodeData | StepNodeData;
selected?: boolean;
}
export interface FlowEdge {
id: string;
source: string;
target: string;
}
export const TRIGGER_NODE_ID = "__trigger";
export const NODE_GAP_Y = 150;
/** Trigger node, then one node per step in a vertical column; edges in order. */
export function toFlow(
defn: WorkflowDefinition,
selected: number | null = null,
): { nodes: FlowNode[]; edges: FlowEdge[] } {
const nodes: FlowNode[] = [
{
id: TRIGGER_NODE_ID,
type: "trigger",
position: { x: 0, y: 0 },
data: { label: describeTrigger(defn.trigger), trigger: defn.trigger },
},
];
const edges: FlowEdge[] = [];
let prev = TRIGGER_NODE_ID;
(defn.steps ?? []).forEach((step, index) => {
const id = `step:${index}:${step.id}`;
nodes.push({
id,
type: "step",
position: { x: 0, y: (index + 1) * NODE_GAP_Y },
data: {
index,
step,
kind: stepKind(step),
conditions: (step.when ?? []).map(describeCondition),
},
selected: selected === index,
});
edges.push({ id: `e:${prev}->${id}`, source: prev, target: id });
prev = id;
});
return { nodes, edges };
}
// ---------------------------------------------------------------- JSON sync
/** JSON with sorted object keys: two definitions are the same iff these strings match. */
export function canonical(v: unknown): string {
return JSON.stringify(sortKeys(v));
}
function sortKeys(v: unknown): unknown {
if (Array.isArray(v)) return v.map(sortKeys);
if (v && typeof v === "object") {
return Object.fromEntries(
Object.keys(v as Record<string, unknown>)
.sort()
.filter((k) => (v as Record<string, unknown>)[k] !== undefined)
.map((k) => [k, sortKeys((v as Record<string, unknown>)[k])]),
);
}
return v;
}
export function sameDefinition(a: unknown, b: unknown): boolean {
return canonical(a) === canonical(b);
}
export function formatDefinition(defn: WorkflowDefinition): string {
return JSON.stringify(defn, null, 2);
}
export type ParseResult =
| { ok: true; value: WorkflowDefinition }
| { ok: false; error: string };
/** Parse editor text into a definition-shaped object (shape only; the server checks it). */
export function parseDefinition(text: string): ParseResult {
let v: unknown;
try {
v = JSON.parse(text);
} catch (e) {
return { ok: false, error: e instanceof Error ? e.message : String(e) };
}
if (!v || typeof v !== "object" || Array.isArray(v)) {
return { ok: false, error: "The definition must be a JSON object." };
}
const o = v as Record<string, unknown>;
if (!o.trigger || typeof o.trigger !== "object") {
return { ok: false, error: "Missing \"trigger\" object." };
}
if (!Array.isArray(o.steps)) return { ok: false, error: "\"steps\" must be a list." };
if (o.steps.some((s) => !s || typeof s !== "object" || Array.isArray(s))) {
return { ok: false, error: "Every step must be an object." };
}
return { ok: true, value: v as WorkflowDefinition };
}
// ---------------------------------------------------------------- step edits
function withSteps(defn: WorkflowDefinition, steps: Step[]): WorkflowDefinition {
return { ...defn, steps };
}
export function moveStep(defn: WorkflowDefinition, index: number, delta: number): WorkflowDefinition {
const to = index + delta;
if (index < 0 || index >= defn.steps.length || to < 0 || to >= defn.steps.length) return defn;
const steps = [...defn.steps];
const [s] = steps.splice(index, 1);
steps.splice(to, 0, s);
return withSteps(defn, steps);
}
export function deleteStep(defn: WorkflowDefinition, index: number): WorkflowDefinition {
if (index < 0 || index >= defn.steps.length) return defn;
return withSteps(
defn,
defn.steps.filter((_, i) => i !== index),
);
}
export function newStepId(defn: WorkflowDefinition, base = "step"): string {
const taken = new Set(defn.steps.map((s) => s.id));
for (let n = defn.steps.length + 1; ; n++) {
const id = `${base}_${n}`;
if (!taken.has(id)) return id;
}
}
export function blankStep(defn: WorkflowDefinition, kind: StepKind, tool = ""): Step {
const id = newStepId(defn);
if (kind === "wait") return { id, wait: { seconds: 60 } };
if (kind === "approval") return { id, approval: { summary: "Check before continuing" } };
return { id, tool, args: {} };
}
/** Insert ``step`` after ``after`` (or at the end). */
export function addStep(defn: WorkflowDefinition, step: Step, after: number | null = null): WorkflowDefinition {
const steps = [...defn.steps];
const at = after === null ? steps.length : Math.min(after + 1, steps.length);
steps.splice(at, 0, step);
return withSteps(defn, steps);
}
/** Replace step ``index``; keys set to ``undefined`` in ``patch`` are removed. */
export function updateStep(
defn: WorkflowDefinition,
index: number,
patch: Partial<Step>,
): WorkflowDefinition {
if (index < 0 || index >= defn.steps.length) return defn;
const merged: Record<string, unknown> = { ...defn.steps[index], ...patch };
for (const k of Object.keys(merged)) if (merged[k] === undefined) delete merged[k];
return withSteps(
defn,
defn.steps.map((s, i) => (i === index ? (merged as unknown as Step) : s)),
);
}
// ---------------------------------------------------------------- errors
export interface IssueReport {
message: string;
errors: Issue[];
warnings: Issue[];
}
/** The structured 422 ``detail`` of create/version calls, if the body has one. */
export function issuesFromBody(body: unknown): IssueReport | null {
if (!body || typeof body !== "object" || !("detail" in body)) return null;
const d = (body as { detail: unknown }).detail;
if (!d || typeof d !== "object" || Array.isArray(d)) return null;
const o = d as Record<string, unknown>;
if (!Array.isArray(o.errors)) return null;
return {
message: typeof o.message === "string" ? o.message : "",
errors: o.errors as Issue[],
warnings: Array.isArray(o.warnings) ? (o.warnings as Issue[]) : [],
};
}
/** Which lifecycle actions the selected version allows. */
export function versionActions(
v: { status: string; dry_run_current: boolean },
activeVersion: number | null,
) {
return {
approve: v.status === "dry_run_ok" && v.dry_run_current,
activate: ["approved", "superseded", "rolled_back"].includes(v.status),
rollback: activeVersion !== null,
};
}
/** Classify a dry-run line by its marker: + would execute, ? needs approval, x denied. */
export function lineTone(line: string): "execute" | "approval" | "denied" | "plain" {
const c = line.trimStart().charAt(0);
if (c === "+") return "execute";
if (c === "?") return "approval";
if (c === "x") return "denied";
return "plain";
}