Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 | /** * YAML Converter for Workflow Builder * * Bidirectional conversion between WorkflowCanvas (visual representation) * and Pipeline YAML (execution format). */ import * as yaml from 'js-yaml'; import type { Edge } from '@xyflow/react'; import dagre from '@dagrejs/dagre'; import type { WorkflowCanvas, WorkflowNode, WorkflowNodeData, InputNodeData, LlmNodeData, SkillNodeData, HandNodeData, ConditionNodeData, ParallelNodeData, ExportNodeData, PipelineYaml, PipelineStepYaml, ValidationError, ValidationResult, } from './types'; // ============================================================================= // Canvas to YAML Conversion // ============================================================================= /** * Convert a WorkflowCanvas to Pipeline YAML string */ export function canvasToYaml(canvas: WorkflowCanvas): string { const pipeline: PipelineYaml = { apiVersion: 'zclaw/v1', kind: 'Pipeline', metadata: { name: canvas.name, description: canvas.description, tags: canvas.metadata.tags, }, spec: { input: extractInputs(canvas.nodes), steps: nodesToSteps(canvas.nodes, canvas.edges), output: extractOutputs(canvas.nodes), }, }; return yaml.dump(pipeline, { indent: 2, lineWidth: -1, noRefs: true, sortKeys: false, }); } /** * Extract input definitions from input nodes */ function extractInputs(nodes: WorkflowNode[]): Record<string, unknown> | undefined { const inputs: Record<string, unknown> = {}; for (const node of nodes) { if (node.data.type === 'input') { const data = node.data as InputNodeData; inputs[data.variableName] = data.defaultValue ?? null; } } return Object.keys(inputs).length > 0 ? inputs : undefined; } /** * Extract output mappings from the last nodes or explicit output nodes */ function extractOutputs(nodes: WorkflowNode[]): Record<string, string> | undefined { const outputs: Record<string, string> = {}; for (const node of nodes) { if (node.data.type === 'export') { // Export nodes define outputs outputs[`${node.id}_export`] = `\${steps.${node.id}.output}`; } } return Object.keys(outputs).length > 0 ? outputs : undefined; } /** * Convert nodes and edges to pipeline steps */ function nodesToSteps(nodes: WorkflowNode[], edges: Edge[]): PipelineStepYaml[] { // Topological sort to get execution order const sortedNodes = topologicalSort(nodes, edges); return sortedNodes .filter(node => node.data.type !== 'input') // Skip input nodes .map(node => nodeToStep(node)) .filter((step): step is PipelineStepYaml => step !== null); } /** * Convert a single node to a pipeline step */ function nodeToStep(node: WorkflowNode): PipelineStepYaml | null { const data = node.data; const label = data.label as string | undefined; const base: PipelineStepYaml = { id: node.id, name: label, action: {}, }; const nodeType = data.type as string; switch (nodeType) { case 'llm': { const llmData = data as LlmNodeData; base.action = { llm_generate: { template: llmData.template, input: mapExpressionsToObject(llmData.template), model: llmData.model, temperature: llmData.temperature, max_tokens: llmData.maxTokens, json_mode: llmData.jsonMode, }, }; break; } case 'skill': { const skillData = data as SkillNodeData; base.action = { skill: { skill_id: skillData.skillId, input: skillData.inputMappings, }, }; break; } case 'hand': { const handData = data as HandNodeData; base.action = { hand: { hand_id: handData.handId, hand_action: handData.action, params: handData.params, }, }; break; } case 'orchestration': { const orchData = data as { graphId?: string; graph?: Record<string, unknown>; inputMappings?: Record<string, string> }; base.action = { skill_orchestration: { graph_id: orchData.graphId, graph: orchData.graph, input: orchData.inputMappings, }, }; break; } case 'condition': { const condData = data as ConditionNodeData; base.action = { condition: { condition: condData.condition, branches: condData.branches.map((b: { when: string }) => ({ when: b.when, then: { /* Will be filled by connected nodes */ }, })), }, }; break; } case 'parallel': { const parData = data as ParallelNodeData; base.action = { parallel: { each: parData.each, step: { /* Will be filled by child nodes */ }, max_workers: parData.maxWorkers, }, }; break; } case 'loop': { const loopData = data as { each: string; itemVar: string; indexVar: string }; base.action = { loop: { each: loopData.each, item_var: loopData.itemVar, index_var: loopData.indexVar, step: { /* Will be filled by child nodes */ }, }, }; break; } case 'export': { const exportData = data as ExportNodeData; base.action = { file_export: { formats: exportData.formats, input: `\${steps.${node.id}.input}`, output_dir: exportData.outputDir, }, }; break; } case 'http': { const httpData = data as { url: string; method: string; headers: Record<string, string>; body?: string }; base.action = { http_request: { url: httpData.url, method: httpData.method, headers: httpData.headers, body: httpData.body, }, }; break; } case 'setVar': { const varData = data as { variableName: string; value: string }; base.action = { set_var: { name: varData.variableName, value: varData.value, }, }; break; } case 'delay': { const delayData = data as { ms: number }; base.action = { delay: { ms: delayData.ms, }, }; break; } case 'input': // Input nodes don't become steps return null; default: console.warn(`Unknown node type: ${nodeType}`); return null; } return base; } /** * Topological sort of nodes based on edges */ function topologicalSort(nodes: WorkflowNode[], edges: Edge[]): WorkflowNode[] { const nodeMap = new Map(nodes.map(n => [n.id, n])); const inDegree = new Map<string, number>(); const adjacency = new Map<string, string[]>(); // Initialize for (const node of nodes) { inDegree.set(node.id, 0); adjacency.set(node.id, []); } // Build graph for (const edge of edges) { const current = adjacency.get(edge.source) || []; current.push(edge.target); adjacency.set(edge.source, current); inDegree.set(edge.target, (inDegree.get(edge.target) || 0) + 1); } // Kahn's algorithm const queue: string[] = []; const result: WorkflowNode[] = []; for (const [nodeId, degree] of inDegree) { if (degree === 0) { queue.push(nodeId); } } while (queue.length > 0) { const nodeId = queue.shift()!; const node = nodeMap.get(nodeId); if (node) { result.push(node); } const neighbors = adjacency.get(nodeId) || []; for (const neighbor of neighbors) { const newDegree = (inDegree.get(neighbor) || 0) - 1; inDegree.set(neighbor, newDegree); if (newDegree === 0) { queue.push(neighbor); } } } return result; } /** * Extract variable references from a template string */ function mapExpressionsToObject(template: string): Record<string, string> { const regex = /\$\{([^}]+)\}/g; const matches = template.match(regex) || []; const result: Record<string, string> = {}; for (const match of matches) { const expr = match.slice(2, -1); // Remove ${ and } const parts = expr.split('.'); if (parts.length >= 2) { result[parts[parts.length - 1]] = match; } } return result; } // ============================================================================= // YAML to Canvas Conversion // ============================================================================= /** * Parse Pipeline YAML string to WorkflowCanvas */ export function yamlToCanvas(yamlString: string): WorkflowCanvas { const pipeline = yaml.load(yamlString) as PipelineYaml; const nodes: WorkflowNode[] = []; const edges: Edge[] = []; // Create input nodes from spec.input if (pipeline.spec.input) { let y = 50; for (const [varName, defaultValue] of Object.entries(pipeline.spec.input)) { nodes.push({ id: `input_${varName}`, type: 'input', position: { x: 50, y }, data: { type: 'input', label: varName, variableName: varName, defaultValue, }, }); y += 100; } } // Convert steps to nodes if (pipeline.spec.steps) { let x = 300; let y = 50; for (const step of pipeline.spec.steps) { const node = stepToNode(step, x, y); if (node) { nodes.push(node); y += 150; } } } // Auto-layout with dagre const layoutedNodes = applyDagreLayout(nodes, edges); return { id: `workflow_${Date.now()}`, name: pipeline.metadata?.name || 'Imported Workflow', description: pipeline.metadata?.description, category: 'imported', nodes: layoutedNodes, edges, viewport: { x: 0, y: 0, zoom: 1 }, metadata: { createdAt: new Date().toISOString(), updatedAt: new Date().toISOString(), tags: pipeline.metadata?.tags || [], version: '1.0.0', }, }; } /** * Convert a pipeline step to a workflow node */ function stepToNode(step: PipelineStepYaml, x: number, y: number): WorkflowNode | null { const action = step.action; const actionType = Object.keys(action)[0]; const actionData = action[actionType]; const baseData = { label: step.name || step.id, }; switch (actionType) { case 'llm_generate': return { id: step.id, type: 'llm', position: { x, y }, data: { type: 'llm', ...baseData, template: (actionData as { template?: string }).template || '', isTemplateFile: false, model: (actionData as { model?: string }).model, temperature: (actionData as { temperature?: number }).temperature, maxTokens: (actionData as { max_tokens?: number }).max_tokens, jsonMode: (actionData as { json_mode?: boolean }).json_mode || false, } as WorkflowNodeData, }; case 'skill': return { id: step.id, type: 'skill', position: { x, y }, data: { type: 'skill', ...baseData, skillId: (actionData as { skill_id?: string }).skill_id || '', inputMappings: (actionData as { input?: Record<string, string> }).input || {}, } as WorkflowNodeData, }; case 'hand': return { id: step.id, type: 'hand', position: { x, y }, data: { type: 'hand', ...baseData, handId: (actionData as { hand_id?: string }).hand_id || '', action: (actionData as { hand_action?: string }).hand_action || '', params: (actionData as { params?: Record<string, string> }).params || {}, } as WorkflowNodeData, }; case 'skill_orchestration': return { id: step.id, type: 'orchestration', position: { x, y }, data: { type: 'orchestration', ...baseData, graphId: (actionData as { graph_id?: string }).graph_id, graph: (actionData as { graph?: Record<string, unknown> }).graph, inputMappings: (actionData as { input?: Record<string, string> }).input || {}, } as WorkflowNodeData, }; case 'condition': return { id: step.id, type: 'condition', position: { x, y }, data: { type: 'condition', ...baseData, condition: (actionData as { condition?: string }).condition || '', branches: ((actionData as { branches?: Array<{ when: string }> }).branches || []).map(b => ({ when: b.when, label: b.when.slice(0, 20), })), hasDefault: true, } as WorkflowNodeData, }; case 'parallel': return { id: step.id, type: 'parallel', position: { x, y }, data: { type: 'parallel', ...baseData, each: (actionData as { each?: string }).each || '', maxWorkers: (actionData as { max_workers?: number }).max_workers || 4, } as WorkflowNodeData, }; case 'file_export': return { id: step.id, type: 'export', position: { x, y }, data: { type: 'export', ...baseData, formats: (actionData as { formats?: string[] }).formats || [], outputDir: (actionData as { output_dir?: string }).output_dir, } as WorkflowNodeData, }; case 'http_request': return { id: step.id, type: 'http', position: { x, y }, data: { type: 'http', ...baseData, url: (actionData as { url?: string }).url || '', method: ((actionData as { method?: string }).method || 'GET') as 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH', headers: (actionData as { headers?: Record<string, string> }).headers || {}, body: (actionData as { body?: string }).body, } as WorkflowNodeData, }; case 'set_var': return { id: step.id, type: 'setVar', position: { x, y }, data: { type: 'setVar', ...baseData, variableName: (actionData as { name?: string }).name || '', value: (actionData as { value?: string }).value || '', } as WorkflowNodeData, }; case 'delay': return { id: step.id, type: 'delay', position: { x, y }, data: { type: 'delay', ...baseData, ms: (actionData as { ms?: number }).ms || 0, } as WorkflowNodeData, }; default: console.warn(`Unknown action type: ${actionType}`); return null; } } // ============================================================================= // Layout Utilities // ============================================================================= /** * Apply dagre layout to nodes */ export function applyDagreLayout(nodes: WorkflowNode[], edges: Edge[]): WorkflowNode[] { const dagreGraph = new dagre.graphlib.Graph(); dagreGraph.setDefaultEdgeLabel(() => ({})); dagreGraph.setGraph({ rankdir: 'LR', nodesep: 100, ranksep: 150, marginx: 50, marginy: 50, }); // Add nodes to dagre for (const node of nodes) { dagreGraph.setNode(node.id, { width: 250, height: 100, }); } // Add edges to dagre for (const edge of edges) { dagreGraph.setEdge(edge.source, edge.target); } // Apply layout dagre.layout(dagreGraph); // Update node positions return nodes.map(node => { const dagreNode = dagreGraph.node(node.id); if (dagreNode) { return { ...node, position: { x: dagreNode.x - dagreNode.width / 2, y: dagreNode.y - dagreNode.height / 2, }, }; } return node; }); } // ============================================================================= // Validation // ============================================================================= /** * Validate a workflow canvas */ export function validateCanvas(canvas: WorkflowCanvas): ValidationResult { const errors: ValidationError[] = []; const warnings: ValidationError[] = []; // Check for empty canvas if (canvas.nodes.length === 0) { errors.push({ nodeId: 'canvas', message: 'Workflow is empty', severity: 'error', }); return { valid: false, errors, warnings }; } // Check for input nodes const hasInput = canvas.nodes.some(n => n.data.type === 'input'); if (!hasInput) { warnings.push({ nodeId: 'canvas', message: 'No input nodes defined', severity: 'warning', }); } // Check for disconnected nodes const connectedNodeIds = new Set<string>(); for (const edge of canvas.edges) { connectedNodeIds.add(edge.source); connectedNodeIds.add(edge.target); } for (const node of canvas.nodes) { if (canvas.nodes.length > 1 && !connectedNodeIds.has(node.id) && node.data.type !== 'input') { warnings.push({ nodeId: node.id, message: `Node "${node.data.label}" is not connected`, severity: 'warning', }); } } // Validate individual nodes for (const node of canvas.nodes) { const nodeErrors = validateNode(node); errors.push(...nodeErrors); } // Check for cycles (basic check) if (hasCycle(canvas.nodes, canvas.edges)) { errors.push({ nodeId: 'canvas', message: 'Workflow contains a cycle', severity: 'error', }); } return { valid: errors.length === 0, errors, warnings, }; } /** * Validate a single node */ function validateNode(node: WorkflowNode): ValidationError[] { const errors: ValidationError[] = []; const data = node.data; switch (data.type) { case 'llm': if (!data.template) { errors.push({ nodeId: node.id, field: 'template', message: 'Template is required', severity: 'error', }); } break; case 'skill': if (!data.skillId) { errors.push({ nodeId: node.id, field: 'skillId', message: 'Skill ID is required', severity: 'error', }); } break; case 'hand': if (!data.handId) { errors.push({ nodeId: node.id, field: 'handId', message: 'Hand ID is required', severity: 'error', }); } if (!data.action) { errors.push({ nodeId: node.id, field: 'action', message: 'Action is required', severity: 'error', }); } break; case 'http': if (!data.url) { errors.push({ nodeId: node.id, field: 'url', message: 'URL is required', severity: 'error', }); } break; case 'input': if (!data.variableName) { errors.push({ nodeId: node.id, field: 'variableName', message: 'Variable name is required', severity: 'error', }); } break; } return errors; } /** * Check if the graph has a cycle */ function hasCycle(nodes: WorkflowNode[], edges: Edge[]): boolean { const adjacency = new Map<string, string[]>(); const visited = new Set<string>(); const recStack = new Set<string>(); // Build adjacency list for (const node of nodes) { adjacency.set(node.id, []); } for (const edge of edges) { const neighbors = adjacency.get(edge.source) || []; neighbors.push(edge.target); adjacency.set(edge.source, neighbors); } // DFS cycle detection function dfs(nodeId: string): boolean { visited.add(nodeId); recStack.add(nodeId); const neighbors = adjacency.get(nodeId) || []; for (const neighbor of neighbors) { if (!visited.has(neighbor)) { if (dfs(neighbor)) return true; } else if (recStack.has(neighbor)) { return true; } } recStack.delete(nodeId); return false; } for (const node of nodes) { if (!visited.has(node.id)) { if (dfs(node.id)) return true; } } return false; } |