mirror of
https://github.com/davidkaya/aryx.git
synced 2026-11-16 15:01:03 +01:00
feat(workflows): add phase 5 backend templates and export support
- add shared workflow template and serialization helpers for YAML, Mermaid, and DOT export - add pattern-to-workflow upgrade and template application flows in AryxAppService - persist built-in and custom workflow templates in workspace state and expose new IPC/preload methods - cover the new backend slice with shared and app-service tests Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
This commit is contained in:
1 parent
f05ec8ac7f
commit
4971dcf9fc
17 files changed
+1094
-6
No files matched your search
@@ -16,8 +16,13 @@ export const ipcChannels = {
|
||||
deletePattern: 'patterns:delete',
|
||||
setPatternFavorite: 'patterns:set-favorite',
|
||||
saveWorkflow: 'workflows:save',
|
||||
saveWorkflowTemplate: 'workflows:save-template',
|
||||
deleteWorkflow: 'workflows:delete',
|
||||
listWorkflowReferences: 'workflows:list-references',
|
||||
createWorkflowFromTemplate: 'workflows:create-from-template',
|
||||
exportWorkflow: 'workflows:export',
|
||||
importWorkflow: 'workflows:import',
|
||||
upgradePatternToWorkflow: 'workflows:upgrade-pattern',
|
||||
createWorkflowSession: 'workflows:create-session',
|
||||
setTheme: 'settings:set-theme',
|
||||
setTerminalHeight: 'settings:set-terminal-height',
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
import type { ApprovalDecision } from '@shared/domain/approval';
|
||||
import type { SidecarCapabilities, InteractionMode, MessageMode, QuotaSnapshot } from '@shared/contracts/sidecar';
|
||||
import type { PatternDefinition, ReasoningEffort } from '@shared/domain/pattern';
|
||||
import type { WorkflowExportFormat, WorkflowExportResult } from '@shared/domain/workflowSerialization';
|
||||
import type { WorkflowTemplateCategory } from '@shared/domain/workflowTemplate';
|
||||
import type { WorkflowDefinition, WorkflowReference } from '@shared/domain/workflow';
|
||||
import type {
|
||||
ProjectGitBranchSummary,
|
||||
@@ -42,6 +44,53 @@ export interface SaveWorkflowInput {
|
||||
workflow: WorkflowDefinition;
|
||||
}
|
||||
|
||||
export interface SaveWorkflowTemplateInput {
|
||||
workflowId: string;
|
||||
options?: {
|
||||
templateId?: string;
|
||||
name?: string;
|
||||
description?: string;
|
||||
category?: WorkflowTemplateCategory;
|
||||
};
|
||||
}
|
||||
|
||||
export interface CreateWorkflowFromTemplateInput {
|
||||
templateId: string;
|
||||
options?: {
|
||||
workflowId?: string;
|
||||
name?: string;
|
||||
description?: string;
|
||||
};
|
||||
}
|
||||
|
||||
export interface ExportWorkflowInput {
|
||||
workflowId: string;
|
||||
format: WorkflowExportFormat;
|
||||
}
|
||||
|
||||
export interface ImportWorkflowInput {
|
||||
content: string;
|
||||
format: 'yaml' | 'json';
|
||||
options?: {
|
||||
save?: boolean;
|
||||
};
|
||||
}
|
||||
|
||||
export interface UpgradePatternToWorkflowInput {
|
||||
patternId: string;
|
||||
options?: {
|
||||
workflowId?: string;
|
||||
name?: string;
|
||||
description?: string;
|
||||
save?: boolean;
|
||||
};
|
||||
}
|
||||
|
||||
export interface ImportWorkflowResult {
|
||||
workflow: WorkflowDefinition;
|
||||
workspace?: WorkspaceState;
|
||||
}
|
||||
|
||||
export interface SendSessionMessageInput {
|
||||
sessionId: string;
|
||||
content: string;
|
||||
@@ -285,8 +334,13 @@ export interface ElectronApi {
|
||||
savePattern(input: SavePatternInput): Promise<WorkspaceState>;
|
||||
deletePattern(patternId: string): Promise<WorkspaceState>;
|
||||
saveWorkflow(input: SaveWorkflowInput): Promise<WorkspaceState>;
|
||||
saveWorkflowTemplate(input: SaveWorkflowTemplateInput): Promise<WorkspaceState>;
|
||||
deleteWorkflow(workflowId: string): Promise<WorkspaceState>;
|
||||
listWorkflowReferences(workflowId: string): Promise<WorkflowReference[]>;
|
||||
createWorkflowFromTemplate(input: CreateWorkflowFromTemplateInput): Promise<WorkspaceState>;
|
||||
exportWorkflow(input: ExportWorkflowInput): Promise<WorkflowExportResult>;
|
||||
importWorkflow(input: ImportWorkflowInput): Promise<ImportWorkflowResult>;
|
||||
upgradePatternToWorkflow(input: UpgradePatternToWorkflowInput): Promise<ImportWorkflowResult>;
|
||||
saveMcpServer(input: SaveMcpServerInput): Promise<WorkspaceState>;
|
||||
deleteMcpServer(serverId: string): Promise<WorkspaceState>;
|
||||
saveLspProfile(input: SaveLspProfileInput): Promise<WorkspaceState>;
|
||||
|
||||
@@ -1084,12 +1084,12 @@ export function validateWorkflowDefinition(workflow: WorkflowDefinition): Workfl
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!edge.condition || edge.condition.type === 'always') {
|
||||
if (!edge.condition) {
|
||||
addIssue(issues, {
|
||||
level: 'error',
|
||||
field: 'graph.edges.condition',
|
||||
edgeId: edge.id,
|
||||
message: 'Loop edges require a non-default condition so the loop can terminate.',
|
||||
message: 'Loop edges require a condition so the loop can terminate.',
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,186 @@
|
||||
import { parse as parseYaml, stringify as stringifyYaml } from 'yaml';
|
||||
|
||||
import {
|
||||
normalizeWorkflowDefinition,
|
||||
validateWorkflowDefinition,
|
||||
type WorkflowDefinition,
|
||||
type WorkflowEdge,
|
||||
type WorkflowGraph,
|
||||
type WorkflowNode,
|
||||
type WorkflowSettings,
|
||||
} from '@shared/domain/workflow';
|
||||
import { nowIso } from '@shared/utils/ids';
|
||||
|
||||
export type WorkflowExportFormat = 'yaml' | 'mermaid' | 'dot';
|
||||
|
||||
export interface WorkflowExportResult {
|
||||
format: WorkflowExportFormat;
|
||||
content: string;
|
||||
}
|
||||
|
||||
function coerceWorkflowDefinition(value: unknown): WorkflowDefinition {
|
||||
if (!value || typeof value !== 'object') {
|
||||
throw new Error('Imported workflow must be an object.');
|
||||
}
|
||||
|
||||
const candidate = value as Partial<WorkflowDefinition>;
|
||||
const settings = candidate.settings as Partial<WorkflowSettings> | undefined;
|
||||
return normalizeWorkflowDefinition({
|
||||
id: typeof candidate.id === 'string' ? candidate.id.trim() : '',
|
||||
name: typeof candidate.name === 'string' ? candidate.name : '',
|
||||
description: typeof candidate.description === 'string' ? candidate.description : '',
|
||||
isFavorite: candidate.isFavorite,
|
||||
graph: (candidate.graph as WorkflowGraph | undefined) ?? { nodes: [], edges: [] },
|
||||
settings: {
|
||||
checkpointing: {
|
||||
enabled: settings?.checkpointing?.enabled ?? false,
|
||||
},
|
||||
executionMode: settings?.executionMode === 'lockstep' ? 'lockstep' : 'off-thread',
|
||||
maxIterations: settings?.maxIterations,
|
||||
approvalPolicy: settings?.approvalPolicy,
|
||||
stateScopes: settings?.stateScopes,
|
||||
telemetry: settings?.telemetry,
|
||||
},
|
||||
createdAt: typeof candidate.createdAt === 'string' ? candidate.createdAt : nowIso(),
|
||||
updatedAt: typeof candidate.updatedAt === 'string' ? candidate.updatedAt : nowIso(),
|
||||
});
|
||||
}
|
||||
|
||||
function ensureValidWorkflow(workflow: WorkflowDefinition): WorkflowDefinition {
|
||||
const normalized = normalizeWorkflowDefinition(workflow);
|
||||
const issue = validateWorkflowDefinition(normalized).find((candidate) => candidate.level === 'error');
|
||||
if (issue) {
|
||||
throw new Error(issue.message);
|
||||
}
|
||||
|
||||
return normalized;
|
||||
}
|
||||
|
||||
function escapeMermaidLabel(value: string): string {
|
||||
return value.replace(/\\/g, '\\\\').replace(/"/g, '\\"').replace(/\n/g, '<br/>');
|
||||
}
|
||||
|
||||
function escapeDotLabel(value: string): string {
|
||||
return value.replace(/\\/g, '\\\\').replace(/"/g, '\\"').replace(/\n/g, '\\n');
|
||||
}
|
||||
|
||||
function formatNodeLabel(node: WorkflowNode): string {
|
||||
return node.label || node.id;
|
||||
}
|
||||
|
||||
function formatEdgeConditionLabel(condition?: WorkflowEdge['condition']): string | undefined {
|
||||
if (!condition) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
switch (condition.type) {
|
||||
case 'always':
|
||||
return 'always';
|
||||
case 'message-type':
|
||||
return `message:${condition.typeName}`;
|
||||
case 'expression':
|
||||
return condition.expression;
|
||||
case 'property':
|
||||
return condition.rules
|
||||
.map((rule) => `${rule.propertyPath} ${rule.operator} ${rule.value}`)
|
||||
.join(` ${condition.combinator === 'or' ? 'OR' : 'AND'} `);
|
||||
}
|
||||
}
|
||||
|
||||
function formatEdgeLabel(edge: WorkflowEdge): string | undefined {
|
||||
const parts = [
|
||||
edge.label,
|
||||
edge.kind === 'fan-out' ? 'fan-out' : undefined,
|
||||
edge.kind === 'fan-in' ? 'fan-in' : undefined,
|
||||
edge.isLoop ? `loop≤${edge.maxIterations ?? '?'}` : undefined,
|
||||
formatEdgeConditionLabel(edge.condition),
|
||||
].filter((value): value is string => Boolean(value));
|
||||
|
||||
return parts.length > 0 ? parts.join(' • ') : undefined;
|
||||
}
|
||||
|
||||
function buildMermaidContent(workflow: WorkflowDefinition): string {
|
||||
const nodeIds = new Map(workflow.graph.nodes.map((node, index) => [node.id, `n${index}`]));
|
||||
const lines = ['flowchart LR'];
|
||||
|
||||
for (const node of workflow.graph.nodes) {
|
||||
const nodeId = nodeIds.get(node.id)!;
|
||||
const label = escapeMermaidLabel(formatNodeLabel(node));
|
||||
switch (node.kind) {
|
||||
case 'start':
|
||||
case 'end':
|
||||
lines.push(` ${nodeId}(["${label}"])`);
|
||||
break;
|
||||
default:
|
||||
lines.push(` ${nodeId}["${label}"]`);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
for (const edge of workflow.graph.edges) {
|
||||
const source = nodeIds.get(edge.source);
|
||||
const target = nodeIds.get(edge.target);
|
||||
if (!source || !target) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const label = formatEdgeLabel(edge);
|
||||
lines.push(label
|
||||
? ` ${source} -->|${escapeMermaidLabel(label)}| ${target}`
|
||||
: ` ${source} --> ${target}`);
|
||||
}
|
||||
|
||||
return `${lines.join('\n')}\n`;
|
||||
}
|
||||
|
||||
function buildDotContent(workflow: WorkflowDefinition): string {
|
||||
const lines = ['digraph Workflow {', ' rankdir=LR;'];
|
||||
|
||||
for (const node of workflow.graph.nodes) {
|
||||
const shape = node.kind === 'start' || node.kind === 'end' ? 'oval' : 'box';
|
||||
lines.push(` "${node.id}" [label="${escapeDotLabel(formatNodeLabel(node))}", shape=${shape}];`);
|
||||
}
|
||||
|
||||
for (const edge of workflow.graph.edges) {
|
||||
const label = formatEdgeLabel(edge);
|
||||
lines.push(label
|
||||
? ` "${edge.source}" -> "${edge.target}" [label="${escapeDotLabel(label)}"];`
|
||||
: ` "${edge.source}" -> "${edge.target}";`);
|
||||
}
|
||||
|
||||
lines.push('}');
|
||||
return `${lines.join('\n')}\n`;
|
||||
}
|
||||
|
||||
export function exportWorkflowDefinition(
|
||||
workflow: WorkflowDefinition,
|
||||
format: WorkflowExportFormat,
|
||||
): WorkflowExportResult {
|
||||
const normalized = ensureValidWorkflow(workflow);
|
||||
|
||||
switch (format) {
|
||||
case 'yaml':
|
||||
return {
|
||||
format,
|
||||
content: stringifyYaml(normalized, { indent: 2 }),
|
||||
};
|
||||
case 'mermaid':
|
||||
return {
|
||||
format,
|
||||
content: buildMermaidContent(normalized),
|
||||
};
|
||||
case 'dot':
|
||||
return {
|
||||
format,
|
||||
content: buildDotContent(normalized),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
export function importWorkflowDefinition(content: string, format: 'yaml' | 'json'): WorkflowDefinition {
|
||||
const parsed = format === 'yaml'
|
||||
? parseYaml(content)
|
||||
: JSON.parse(content) as unknown;
|
||||
|
||||
return ensureValidWorkflow(coerceWorkflowDefinition(parsed));
|
||||
}
|
||||
@@ -0,0 +1,444 @@
|
||||
import {
|
||||
createBuiltinPatterns,
|
||||
resolvePatternGraph,
|
||||
type PatternAgentDefinition,
|
||||
type PatternDefinition,
|
||||
type PatternGraphNode,
|
||||
} from '@shared/domain/pattern';
|
||||
import {
|
||||
normalizeWorkflowDefinition,
|
||||
type WorkflowDefinition,
|
||||
type WorkflowEdge,
|
||||
type WorkflowNode,
|
||||
type WorkflowSettings,
|
||||
} from '@shared/domain/workflow';
|
||||
import { nowIso } from '@shared/utils/ids';
|
||||
|
||||
export type WorkflowTemplateCategory = 'orchestration' | 'data-pipeline' | 'human-in-loop';
|
||||
|
||||
export interface WorkflowTemplateDefinition {
|
||||
id: string;
|
||||
name: string;
|
||||
description: string;
|
||||
category: WorkflowTemplateCategory;
|
||||
source: 'builtin' | 'custom';
|
||||
workflow: WorkflowDefinition;
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
}
|
||||
|
||||
const workflowTemplateCategories = new Set<WorkflowTemplateCategory>([
|
||||
'orchestration',
|
||||
'data-pipeline',
|
||||
'human-in-loop',
|
||||
]);
|
||||
|
||||
const builtinTemplateIdsByPatternId: Record<string, string> = {
|
||||
'pattern-single-chat': 'workflow-template-single',
|
||||
'pattern-sequential-review': 'workflow-template-sequential',
|
||||
'pattern-concurrent-brainstorm': 'workflow-template-concurrent',
|
||||
'pattern-handoff-support': 'workflow-template-handoff',
|
||||
'pattern-group-chat': 'workflow-template-group-chat',
|
||||
};
|
||||
|
||||
function normalizeTemplateCategory(category?: WorkflowTemplateCategory): WorkflowTemplateCategory {
|
||||
return category && workflowTemplateCategories.has(category) ? category : 'orchestration';
|
||||
}
|
||||
|
||||
function normalizeOptionalString(value?: string): string | undefined {
|
||||
const trimmed = value?.trim();
|
||||
return trimmed ? trimmed : undefined;
|
||||
}
|
||||
|
||||
function normalizeRequiredString(value: string | undefined, fallback: string): string {
|
||||
return normalizeOptionalString(value) ?? fallback;
|
||||
}
|
||||
|
||||
function toWorkflowIdFromPatternId(patternId: string): string {
|
||||
const trimmed = patternId.trim();
|
||||
return trimmed.startsWith('pattern-')
|
||||
? `workflow-${trimmed.slice('pattern-'.length)}`
|
||||
: `${trimmed}-workflow`;
|
||||
}
|
||||
|
||||
function createWorkflowEdge(
|
||||
source: string,
|
||||
target: string,
|
||||
kind: WorkflowEdge['kind'],
|
||||
overrides?: Partial<WorkflowEdge>,
|
||||
): WorkflowEdge {
|
||||
return {
|
||||
id: overrides?.id?.trim() || `workflow-edge-${source}-to-${target}`,
|
||||
source,
|
||||
target,
|
||||
kind,
|
||||
label: normalizeOptionalString(overrides?.label),
|
||||
condition: overrides?.condition,
|
||||
fanOutConfig: overrides?.fanOutConfig,
|
||||
isLoop: overrides?.isLoop,
|
||||
maxIterations: overrides?.maxIterations,
|
||||
};
|
||||
}
|
||||
|
||||
function sortAgentNodes(nodes: ReadonlyArray<PatternGraphNode>): PatternGraphNode[] {
|
||||
return nodes
|
||||
.filter((node) => node.kind === 'agent' && node.agentId)
|
||||
.slice()
|
||||
.sort((left, right) => {
|
||||
const leftOrder = left.order ?? Number.MAX_SAFE_INTEGER;
|
||||
const rightOrder = right.order ?? Number.MAX_SAFE_INTEGER;
|
||||
if (leftOrder !== rightOrder) {
|
||||
return leftOrder - rightOrder;
|
||||
}
|
||||
|
||||
return left.id.localeCompare(right.id);
|
||||
});
|
||||
}
|
||||
|
||||
function normalizeTemplateWorkflow(
|
||||
workflow: WorkflowDefinition | Partial<WorkflowDefinition> | undefined,
|
||||
): WorkflowDefinition {
|
||||
const candidate = workflow ?? {};
|
||||
const settings = candidate.settings as Partial<WorkflowSettings> | undefined;
|
||||
return normalizeWorkflowDefinition({
|
||||
id: normalizeRequiredString(candidate.id, 'workflow-template'),
|
||||
name: typeof candidate.name === 'string' ? candidate.name : '',
|
||||
description: typeof candidate.description === 'string' ? candidate.description : '',
|
||||
isFavorite: candidate.isFavorite,
|
||||
graph: (candidate.graph as WorkflowDefinition['graph'] | undefined) ?? {
|
||||
nodes: [],
|
||||
edges: [],
|
||||
},
|
||||
settings: {
|
||||
checkpointing: {
|
||||
enabled: settings?.checkpointing?.enabled ?? false,
|
||||
},
|
||||
executionMode: settings?.executionMode === 'lockstep' ? 'lockstep' : 'off-thread',
|
||||
maxIterations: settings?.maxIterations,
|
||||
approvalPolicy: settings?.approvalPolicy,
|
||||
stateScopes: settings?.stateScopes,
|
||||
telemetry: settings?.telemetry,
|
||||
},
|
||||
createdAt: typeof candidate.createdAt === 'string' ? candidate.createdAt : nowIso(),
|
||||
updatedAt: typeof candidate.updatedAt === 'string' ? candidate.updatedAt : nowIso(),
|
||||
});
|
||||
}
|
||||
|
||||
function createWorkflowAgentNode(
|
||||
patternNode: PatternGraphNode,
|
||||
agent: PatternAgentDefinition,
|
||||
fallbackOrder: number,
|
||||
): WorkflowNode {
|
||||
return {
|
||||
id: patternNode.id.trim(),
|
||||
kind: 'agent',
|
||||
label: normalizeRequiredString(agent.name, `Agent ${fallbackOrder + 1}`),
|
||||
position: {
|
||||
x: patternNode.position.x,
|
||||
y: patternNode.position.y,
|
||||
},
|
||||
order: patternNode.order ?? fallbackOrder,
|
||||
config: {
|
||||
kind: 'agent',
|
||||
...agent,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function mapPatternNodeId(node: PatternGraphNode | undefined): string | undefined {
|
||||
if (!node) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
switch (node.kind) {
|
||||
case 'user-input':
|
||||
return 'start';
|
||||
case 'user-output':
|
||||
return 'end';
|
||||
case 'agent':
|
||||
return node.id.trim();
|
||||
default:
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
function buildWorkflowAdjacency(
|
||||
edges: ReadonlyArray<WorkflowEdge>,
|
||||
excludedEdgeId?: string,
|
||||
): Map<string, string[]> {
|
||||
const adjacency = new Map<string, string[]>();
|
||||
for (const edge of edges) {
|
||||
if (edge.id === excludedEdgeId) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const next = adjacency.get(edge.source);
|
||||
if (next) {
|
||||
next.push(edge.target);
|
||||
} else {
|
||||
adjacency.set(edge.source, [edge.target]);
|
||||
}
|
||||
}
|
||||
|
||||
return adjacency;
|
||||
}
|
||||
|
||||
function canReachWorkflowNode(
|
||||
edges: ReadonlyArray<WorkflowEdge>,
|
||||
startNodeId: string,
|
||||
targetNodeId: string,
|
||||
excludedEdgeId?: string,
|
||||
): boolean {
|
||||
if (startNodeId === targetNodeId) {
|
||||
return true;
|
||||
}
|
||||
|
||||
const adjacency = buildWorkflowAdjacency(edges, excludedEdgeId);
|
||||
const queue = [startNodeId];
|
||||
const visited = new Set<string>();
|
||||
while (queue.length > 0) {
|
||||
const current = queue.shift()!;
|
||||
if (visited.has(current)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
visited.add(current);
|
||||
for (const candidate of adjacency.get(current) ?? []) {
|
||||
if (candidate === targetNodeId) {
|
||||
return true;
|
||||
}
|
||||
|
||||
queue.push(candidate);
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
function markLoopEdges(
|
||||
edges: ReadonlyArray<WorkflowEdge>,
|
||||
maxIterations: number,
|
||||
): WorkflowEdge[] {
|
||||
return edges.map((edge) => {
|
||||
const participatesInCycle = canReachWorkflowNode(edges, edge.target, edge.source, edge.id);
|
||||
if (!participatesInCycle) {
|
||||
return edge;
|
||||
}
|
||||
|
||||
return {
|
||||
...edge,
|
||||
isLoop: true,
|
||||
maxIterations,
|
||||
condition: edge.condition ?? { type: 'always' },
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
export function normalizeWorkflowTemplateDefinition(template: WorkflowTemplateDefinition): WorkflowTemplateDefinition {
|
||||
const workflow = normalizeTemplateWorkflow(template.workflow);
|
||||
return {
|
||||
...template,
|
||||
id: normalizeRequiredString(template.id, `workflow-template-${workflow.id}`),
|
||||
name: normalizeRequiredString(template.name, workflow.name || 'Workflow Template'),
|
||||
description: template.description?.trim() ?? '',
|
||||
category: normalizeTemplateCategory(template.category),
|
||||
source: template.source === 'builtin' ? 'builtin' : 'custom',
|
||||
workflow,
|
||||
createdAt: template.createdAt,
|
||||
updatedAt: template.updatedAt,
|
||||
};
|
||||
}
|
||||
|
||||
export function buildWorkflowFromPattern(pattern: PatternDefinition): WorkflowDefinition {
|
||||
const resolvedGraph = resolvePatternGraph(pattern);
|
||||
const patternNodesById = new Map(resolvedGraph.nodes.map((node) => [node.id, node]));
|
||||
const agentsById = new Map(pattern.agents.map((agent) => [agent.id, agent]));
|
||||
const orderedAgentNodes = sortAgentNodes(resolvedGraph.nodes);
|
||||
const startPosition = patternNodesById.get('system-user-input')?.position ?? { x: 0, y: 0 };
|
||||
const endPosition = patternNodesById.get('system-user-output')?.position ?? { x: 500, y: 0 };
|
||||
const workflowNodes: WorkflowNode[] = [
|
||||
{
|
||||
id: 'start',
|
||||
kind: 'start',
|
||||
label: 'Start',
|
||||
position: { x: startPosition.x, y: startPosition.y },
|
||||
config: { kind: 'start' },
|
||||
},
|
||||
...orderedAgentNodes.map((node, index) => {
|
||||
const agent = node.agentId ? agentsById.get(node.agentId) : undefined;
|
||||
if (!agent) {
|
||||
throw new Error(`Pattern "${pattern.id}" references missing agent "${node.agentId ?? node.id}".`);
|
||||
}
|
||||
|
||||
return createWorkflowAgentNode(node, agent, index);
|
||||
}),
|
||||
{
|
||||
id: 'end',
|
||||
kind: 'end',
|
||||
label: 'End',
|
||||
position: { x: endPosition.x, y: endPosition.y },
|
||||
config: { kind: 'end' },
|
||||
},
|
||||
];
|
||||
|
||||
const orderedAgentIds = workflowNodes.filter((node) => node.kind === 'agent').map((node) => node.id);
|
||||
const edges: WorkflowEdge[] = [];
|
||||
const seenEdges = new Set<string>();
|
||||
const pushEdge = (edge: WorkflowEdge) => {
|
||||
const dedupeKey = `${edge.source}:${edge.target}:${edge.kind}:${edge.isLoop === true ? 'loop' : 'plain'}`;
|
||||
if (seenEdges.has(dedupeKey)) {
|
||||
return;
|
||||
}
|
||||
|
||||
seenEdges.add(dedupeKey);
|
||||
edges.push(edge);
|
||||
};
|
||||
|
||||
switch (pattern.mode) {
|
||||
case 'single':
|
||||
case 'sequential':
|
||||
case 'magentic': {
|
||||
const path = ['start', ...orderedAgentIds, 'end'];
|
||||
for (let index = 0; index < path.length - 1; index += 1) {
|
||||
pushEdge(createWorkflowEdge(path[index]!, path[index + 1]!, 'direct'));
|
||||
}
|
||||
break;
|
||||
}
|
||||
case 'concurrent': {
|
||||
for (const agentId of orderedAgentIds) {
|
||||
pushEdge(createWorkflowEdge('start', agentId, 'fan-out', {
|
||||
fanOutConfig: { strategy: 'broadcast' },
|
||||
}));
|
||||
pushEdge(createWorkflowEdge(agentId, 'end', 'fan-in'));
|
||||
}
|
||||
break;
|
||||
}
|
||||
case 'handoff': {
|
||||
for (const patternEdge of resolvedGraph.edges) {
|
||||
const sourceNode = patternNodesById.get(patternEdge.source);
|
||||
const targetNode = patternNodesById.get(patternEdge.target);
|
||||
const source = mapPatternNodeId(sourceNode);
|
||||
const target = mapPatternNodeId(targetNode);
|
||||
if (!source || !target) {
|
||||
continue;
|
||||
}
|
||||
|
||||
pushEdge(createWorkflowEdge(source, target, 'direct', {
|
||||
id: `workflow-${patternEdge.id.trim()}`,
|
||||
}));
|
||||
}
|
||||
break;
|
||||
}
|
||||
case 'group-chat': {
|
||||
const path = ['start', ...orderedAgentIds, 'end'];
|
||||
for (let index = 0; index < path.length - 1; index += 1) {
|
||||
const source = path[index]!;
|
||||
const target = path[index + 1]!;
|
||||
pushEdge(createWorkflowEdge(source, target, 'direct', source !== 'start' && target !== 'end'
|
||||
? {
|
||||
isLoop: true,
|
||||
maxIterations: pattern.maxIterations,
|
||||
condition: { type: 'always' },
|
||||
}
|
||||
: undefined));
|
||||
}
|
||||
|
||||
if (orderedAgentIds.length > 0) {
|
||||
pushEdge(createWorkflowEdge(
|
||||
orderedAgentIds[orderedAgentIds.length - 1]!,
|
||||
orderedAgentIds[0]!,
|
||||
'direct',
|
||||
{
|
||||
id: `workflow-edge-${orderedAgentIds[orderedAgentIds.length - 1]}-loop-${orderedAgentIds[0]}`,
|
||||
isLoop: true,
|
||||
maxIterations: pattern.maxIterations,
|
||||
condition: { type: 'always' },
|
||||
label: 'Loop',
|
||||
},
|
||||
));
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
const finalizedEdges = pattern.mode === 'handoff'
|
||||
? markLoopEdges(edges, Math.max(pattern.maxIterations, 1))
|
||||
: edges;
|
||||
|
||||
return normalizeWorkflowDefinition({
|
||||
id: toWorkflowIdFromPatternId(pattern.id),
|
||||
name: pattern.name,
|
||||
description: pattern.description,
|
||||
graph: {
|
||||
nodes: workflowNodes,
|
||||
edges: finalizedEdges,
|
||||
},
|
||||
settings: {
|
||||
checkpointing: { enabled: false },
|
||||
executionMode: 'off-thread',
|
||||
maxIterations: pattern.maxIterations,
|
||||
approvalPolicy: pattern.approvalPolicy,
|
||||
},
|
||||
createdAt: pattern.createdAt,
|
||||
updatedAt: pattern.updatedAt,
|
||||
});
|
||||
}
|
||||
|
||||
export function createBuiltinWorkflowTemplates(timestamp: string): WorkflowTemplateDefinition[] {
|
||||
return createBuiltinPatterns(timestamp)
|
||||
.filter((pattern) => pattern.availability !== 'unavailable')
|
||||
.map((pattern) => normalizeWorkflowTemplateDefinition({
|
||||
id: builtinTemplateIdsByPatternId[pattern.id] ?? `workflow-template-${pattern.id}`,
|
||||
name: pattern.name,
|
||||
description: pattern.description,
|
||||
category: 'orchestration',
|
||||
source: 'builtin',
|
||||
workflow: buildWorkflowFromPattern(pattern),
|
||||
createdAt: timestamp,
|
||||
updatedAt: timestamp,
|
||||
}));
|
||||
}
|
||||
|
||||
export function createWorkflowTemplateFromWorkflow(
|
||||
workflow: WorkflowDefinition,
|
||||
options?: {
|
||||
templateId?: string;
|
||||
name?: string;
|
||||
description?: string;
|
||||
category?: WorkflowTemplateCategory;
|
||||
},
|
||||
): WorkflowTemplateDefinition {
|
||||
const timestamp = nowIso();
|
||||
const normalizedWorkflow = normalizeTemplateWorkflow(workflow);
|
||||
return normalizeWorkflowTemplateDefinition({
|
||||
id: normalizeOptionalString(options?.templateId) ?? `workflow-template-${normalizedWorkflow.id}`,
|
||||
name: normalizeOptionalString(options?.name) ?? normalizedWorkflow.name,
|
||||
description: options?.description?.trim() ?? normalizedWorkflow.description,
|
||||
category: options?.category ?? 'orchestration',
|
||||
source: 'custom',
|
||||
workflow: normalizedWorkflow,
|
||||
createdAt: timestamp,
|
||||
updatedAt: timestamp,
|
||||
});
|
||||
}
|
||||
|
||||
export function applyWorkflowTemplate(
|
||||
template: WorkflowTemplateDefinition,
|
||||
options?: {
|
||||
workflowId?: string;
|
||||
name?: string;
|
||||
description?: string;
|
||||
},
|
||||
): WorkflowDefinition {
|
||||
const timestamp = nowIso();
|
||||
const normalizedTemplate = normalizeWorkflowTemplateDefinition(template);
|
||||
return normalizeWorkflowDefinition({
|
||||
...normalizedTemplate.workflow,
|
||||
id: normalizeOptionalString(options?.workflowId) ?? normalizedTemplate.workflow.id,
|
||||
name: normalizeOptionalString(options?.name) ?? normalizedTemplate.workflow.name,
|
||||
description: options?.description?.trim() ?? normalizedTemplate.workflow.description,
|
||||
isFavorite: undefined,
|
||||
createdAt: timestamp,
|
||||
updatedAt: timestamp,
|
||||
});
|
||||
}
|
||||
@@ -3,6 +3,10 @@ import { createBuiltinPatterns } from '@shared/domain/pattern';
|
||||
import type { ProjectRecord } from '@shared/domain/project';
|
||||
import type { SessionRecord } from '@shared/domain/session';
|
||||
import { createWorkspaceSettings, type WorkspaceSettings } from '@shared/domain/tooling';
|
||||
import {
|
||||
createBuiltinWorkflowTemplates,
|
||||
type WorkflowTemplateDefinition,
|
||||
} from '@shared/domain/workflowTemplate';
|
||||
import type { WorkflowDefinition } from '@shared/domain/workflow';
|
||||
import { nowIso } from '@shared/utils/ids';
|
||||
|
||||
@@ -10,6 +14,7 @@ export interface WorkspaceState {
|
||||
projects: ProjectRecord[];
|
||||
patterns: PatternDefinition[];
|
||||
workflows: WorkflowDefinition[];
|
||||
workflowTemplates: WorkflowTemplateDefinition[];
|
||||
sessions: SessionRecord[];
|
||||
settings: WorkspaceSettings;
|
||||
/** IDs of built-in patterns the user has deleted. Prevents re-adding on load. */
|
||||
@@ -29,6 +34,7 @@ export function createWorkspaceSeed(): WorkspaceState {
|
||||
projects: [],
|
||||
patterns: createBuiltinPatterns(timestamp),
|
||||
workflows: [],
|
||||
workflowTemplates: createBuiltinWorkflowTemplates(timestamp),
|
||||
sessions: [],
|
||||
settings: createWorkspaceSettings(),
|
||||
lastUpdatedAt: timestamp,
|
||||
|
||||
Reference in new issue
Block a user