import { computed, onMounted, ref, type Ref } from "vue"; import { parse } from "yaml"; import { api } from "@/lib/api"; import { branchingOf } from "./workflow-edit.ts"; import { useSettingsStore } from "@/stores/settings"; import { useWorkflowsStore } from "@/stores/workflows"; import type { Binding } from "@/bindings/binding-draft"; /** One way a workflow gets started. */ export interface WorkflowTrigger { kind: "issue" | "event" | "schedule" | "playbook" | "workflow"; label: string; detail?: string; /** The event binding this trigger is, for editing it. */ binding?: Binding; } export interface TriggerSources { /** Issue label kind to workflow, with "default" for an unlabelled issue. */ routes: Record; bindings: Binding[]; playbooks: { id: string; yaml: string }[]; definitions: { id: string; yaml: string }[]; /** Schedules by id, to name schedule triggers. */ schedules: { id: string; name: string }[]; } /** The reserved source a schedule's firings are captured on, and the * built-in mapping that hands a binding the firing's fields. */ export const SCHEDULE_SOURCE = "schedule"; export const SCHEDULE_MAPPING = "schedule-fired"; export const SCHEDULE_FIELDS = ["schedule_id", "name", "scheduled_for", "fired_at"] as const; /** The binding filter that admits only the firings of one schedule. */ export function scheduleFilter(id: string): string { return `schedule_id == ${JSON.stringify(id)}`; } /** The schedule a schedule trigger's filter names, or "". */ export function scheduleOfBinding(binding: Binding): string { const match = /^schedule_id == ("(?:[^"\\]|\\.)*")$/.exec(binding.filter?.trim() ?? ""); if (!match) return ""; try { return JSON.parse(match[1]!) as string; } catch { return ""; } } type Mapping = Record; function isMapping(value: unknown): value is Mapping { return typeof value === "object" && value !== null && !Array.isArray(value); } function parseQuietly(source: string): unknown { try { return parse(source); } catch { return null; } } /** Everything that starts the workflow named id. */ export function triggersFor(id: string, sources: TriggerSources): WorkflowTrigger[] { const triggers: WorkflowTrigger[] = []; for (const [kind, workflow] of Object.entries(sources.routes)) { if (workflow !== id) continue; triggers.push( kind === "default" ? { kind: "issue", label: "Unlabelled issues", detail: "anything no label routes elsewhere" } : { kind: "issue", label: `Issues labelled ${kind}` }, ); } for (const binding of sources.bindings) { if (binding.workflow !== id) continue; if (binding.matcher?.source === SCHEDULE_SOURCE) { const scheduleId = scheduleOfBinding(binding); const schedule = sources.schedules.find((s) => s.id === scheduleId); triggers.push({ kind: "schedule", label: schedule?.name ?? (scheduleId || "Schedule"), binding }); continue; } triggers.push({ kind: "event", label: binding.name || "Event binding", detail: binding.matcher?.source, binding }); } for (const playbook of sources.playbooks) { const value = parseQuietly(playbook.yaml); if (!isMapping(value) || !Array.isArray(value.actions)) continue; if (!value.actions.some((action) => isMapping(action) && action.workflow === id)) continue; const trigger = isMapping(value.trigger) ? value.trigger : {}; const labels = Array.isArray(trigger.labels) ? trigger.labels.join(", ") : ""; triggers.push({ kind: "playbook", label: playbook.id, detail: [trigger.kind, labels].filter(Boolean).join(" ยท ") }); } for (const definition of sources.definitions) { if (definition.id === id) continue; const how = startsVia(parseQuietly(definition.yaml), id); if (how) triggers.push({ kind: "workflow", label: definition.id, detail: how }); } return triggers; } /** How a workflow's steps start the target: a call, a handoff (including one * whose target an earlier agent picks from a fixed list), or an approval. */ function startsVia(value: unknown, target: string): string { const steps = isMapping(value) && Array.isArray(value.steps) ? value.steps : []; const all = steps.flatMap((step) => branchingOf(step)?.branches.flatMap(([, branch]) => branch) ?? [step], ); for (const step of all) { if (!isMapping(step) || !isMapping(step.settings)) continue; const settings = step.settings; switch (step.type) { case "workflow.call": if (settings.workflow === target) return "calls it"; break; case "workflow.handoff": if (settings.workflow === target || resultChoices(all, settings.workflow).includes(target)) return "hands off to it"; break; case "workflow.approve": if (settings.then === target) return "runs it once approved"; break; } } return ""; } /** The fixed choices an agent's result field allows, for a reference like * {{ steps.classify.result.workflow }}. */ function resultChoices(steps: unknown[], reference: unknown): string[] { const match = typeof reference === "string" ? /\{\{\s*steps\.([\w-]+)\.result\.([\w-]+)\s*\}\}/.exec(reference) : null; if (!match) return []; const source = steps.find((step) => isMapping(step) && step.id === match[1]); const result = isMapping(source) && isMapping(source.settings) ? source.settings.result : undefined; const field = isMapping(result) && isMapping(result.properties) ? result.properties[match[2]] : undefined; return isMapping(field) && Array.isArray(field.enum) ? field.enum.map(String) : []; } /** The triggers of the workflow named id, from the routes and definitions the * control plane serves, the stored playbooks, and the event bindings. */ export function useWorkflowTriggers(id: Ref) { const store = useSettingsStore(); const workflows = useWorkflowsStore(); const bindings = ref([]); const schedules = ref([]); async function reload(): Promise { const [response, listed] = await Promise.all([ api.bindings<{ bindings?: Binding[] }>().catch(() => null), api.schedules<{ schedules?: TriggerSources["schedules"] }>().catch(() => null), ]); bindings.value = response?.bindings ?? []; schedules.value = listed?.schedules ?? []; } onMounted(reload); const triggers = computed(() => triggersFor(id.value, { routes: workflows.intakeRoutes, bindings: bindings.value, playbooks: (store.stateFor("eda-playbooks").resource?.value as { playbooks?: TriggerSources["playbooks"] } | undefined)?.playbooks ?? [], definitions: workflows.collection.definitions, schedules: schedules.value, }), ); return { triggers, reload }; }