@marktoflow/gui 2.0.0-alpha.12 → 2.0.0-alpha.14

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (141) hide show
  1. package/README.md +380 -14
  2. package/client.log +0 -0
  3. package/dist/client/assets/{index-CM44OayM.js → index-CIvjE2Ts.js} +144 -145
  4. package/dist/client/assets/index-CIvjE2Ts.js.map +1 -0
  5. package/dist/client/assets/index-Cu3CHOQw.css +1 -0
  6. package/dist/client/index.html +2 -2
  7. package/dist/server/index.js +10 -2
  8. package/dist/server/index.js.map +1 -1
  9. package/dist/server/routes/ai.js +2 -2
  10. package/dist/server/routes/ai.js.map +1 -1
  11. package/dist/server/routes/execute.js +181 -14
  12. package/dist/server/routes/execute.js.map +1 -1
  13. package/dist/server/services/AIService.js +39 -2
  14. package/dist/server/services/AIService.js.map +1 -1
  15. package/dist/server/services/ExecutionManager.js +428 -0
  16. package/dist/server/services/ExecutionManager.js.map +1 -0
  17. package/package.json +2 -4
  18. package/server.log +0 -0
  19. package/tests/integration/fixtures/test-workflow.md +6 -0
  20. package/.marktoflow/state/workflow-state.db +0 -0
  21. package/.marktoflow/state/workflow-state.db-shm +0 -0
  22. package/.marktoflow/state/workflow-state.db-wal +0 -0
  23. package/.turbo/turbo-build.log +0 -42
  24. package/.turbo/turbo-test.log +0 -38
  25. package/dist/client/assets/index-CM44OayM.js.map +0 -1
  26. package/dist/client/assets/index-Dru63gi6.css +0 -1
  27. package/marktoflow-gui-2.0.0-alpha.12.tgz +0 -0
  28. package/playwright.config.ts +0 -27
  29. package/postcss.config.js +0 -6
  30. package/src/client/App.tsx +0 -520
  31. package/src/client/components/Canvas/Canvas.tsx +0 -425
  32. package/src/client/components/Canvas/ExecutionOverlay.tsx +0 -935
  33. package/src/client/components/Canvas/ForEachNode.tsx +0 -152
  34. package/src/client/components/Canvas/IfElseNode.tsx +0 -141
  35. package/src/client/components/Canvas/NodeContextMenu.tsx +0 -192
  36. package/src/client/components/Canvas/OutputNode.tsx +0 -111
  37. package/src/client/components/Canvas/ParallelNode.tsx +0 -157
  38. package/src/client/components/Canvas/StepNode.tsx +0 -106
  39. package/src/client/components/Canvas/SubWorkflowNode.tsx +0 -141
  40. package/src/client/components/Canvas/SwitchNode.tsx +0 -185
  41. package/src/client/components/Canvas/Toolbar.tsx +0 -227
  42. package/src/client/components/Canvas/TransformNode.tsx +0 -194
  43. package/src/client/components/Canvas/TriggerNode.tsx +0 -128
  44. package/src/client/components/Canvas/TryCatchNode.tsx +0 -164
  45. package/src/client/components/Canvas/WhileNode.tsx +0 -161
  46. package/src/client/components/Canvas/index.ts +0 -24
  47. package/src/client/components/Debug/VariableInspector.tsx +0 -148
  48. package/src/client/components/Editor/InputsEditor.tsx +0 -458
  49. package/src/client/components/Editor/NewStepWizard.tsx +0 -344
  50. package/src/client/components/Editor/StepEditor.tsx +0 -532
  51. package/src/client/components/Editor/YamlEditor.tsx +0 -160
  52. package/src/client/components/Panels/PropertiesPanel.tsx +0 -589
  53. package/src/client/components/Prompt/ChangePreview.tsx +0 -281
  54. package/src/client/components/Prompt/PromptHistoryPanel.tsx +0 -209
  55. package/src/client/components/Prompt/PromptInput.tsx +0 -110
  56. package/src/client/components/Settings/ProviderSwitcher.tsx +0 -228
  57. package/src/client/components/Sidebar/ImportDialog.tsx +0 -257
  58. package/src/client/components/Sidebar/Sidebar.tsx +0 -362
  59. package/src/client/components/common/Breadcrumb.tsx +0 -40
  60. package/src/client/components/common/Button.tsx +0 -68
  61. package/src/client/components/common/ContextMenu.tsx +0 -202
  62. package/src/client/components/common/KeyboardShortcuts.tsx +0 -149
  63. package/src/client/components/common/Modal.tsx +0 -93
  64. package/src/client/components/common/Tabs.tsx +0 -57
  65. package/src/client/components/common/ThemeToggle.tsx +0 -63
  66. package/src/client/components/index.ts +0 -32
  67. package/src/client/hooks/index.ts +0 -4
  68. package/src/client/hooks/useAIPrompt.ts +0 -108
  69. package/src/client/hooks/useCanvas.ts +0 -247
  70. package/src/client/hooks/useWebSocket.ts +0 -164
  71. package/src/client/hooks/useWorkflow.ts +0 -138
  72. package/src/client/main.tsx +0 -10
  73. package/src/client/stores/agentStore.ts +0 -109
  74. package/src/client/stores/canvasStore.ts +0 -348
  75. package/src/client/stores/editorStore.ts +0 -133
  76. package/src/client/stores/executionStore.ts +0 -502
  77. package/src/client/stores/index.ts +0 -4
  78. package/src/client/stores/layoutStore.ts +0 -103
  79. package/src/client/stores/navigationStore.ts +0 -49
  80. package/src/client/stores/promptStore.ts +0 -113
  81. package/src/client/stores/themeStore.ts +0 -75
  82. package/src/client/stores/workflowStore.ts +0 -185
  83. package/src/client/styles/globals.css +0 -452
  84. package/src/client/utils/cn.ts +0 -9
  85. package/src/client/utils/index.ts +0 -4
  86. package/src/client/utils/platform.ts +0 -46
  87. package/src/client/utils/serviceIcons.tsx +0 -97
  88. package/src/client/utils/stepValidation.ts +0 -155
  89. package/src/client/utils/workflowToGraph.ts +0 -523
  90. package/src/server/index.ts +0 -137
  91. package/src/server/routes/ai.ts +0 -91
  92. package/src/server/routes/execute.ts +0 -71
  93. package/src/server/routes/executions.ts +0 -136
  94. package/src/server/routes/tools.ts +0 -970
  95. package/src/server/routes/workflows.ts +0 -147
  96. package/src/server/services/AIService.ts +0 -105
  97. package/src/server/services/FileWatcher.ts +0 -69
  98. package/src/server/services/WorkflowService.ts +0 -601
  99. package/src/server/services/agents/claude-code-provider.ts +0 -320
  100. package/src/server/services/agents/claude-provider.ts +0 -248
  101. package/src/server/services/agents/codex-provider.ts +0 -398
  102. package/src/server/services/agents/copilot-provider.ts +0 -311
  103. package/src/server/services/agents/demo-provider.ts +0 -184
  104. package/src/server/services/agents/index.ts +0 -31
  105. package/src/server/services/agents/ollama-provider.ts +0 -267
  106. package/src/server/services/agents/prompts.ts +0 -509
  107. package/src/server/services/agents/registry.ts +0 -310
  108. package/src/server/services/agents/types.ts +0 -146
  109. package/src/server/websocket/index.ts +0 -117
  110. package/src/shared/constants.ts +0 -180
  111. package/src/shared/types.ts +0 -179
  112. package/tailwind.config.ts +0 -73
  113. package/tests/e2e/app.spec.ts +0 -90
  114. package/tests/e2e/canvas.spec.ts +0 -128
  115. package/tests/e2e/workflow.spec.ts +0 -185
  116. package/tests/integration/api.test.ts +0 -452
  117. package/tests/integration/testApp.ts +0 -31
  118. package/tests/setup.ts +0 -72
  119. package/tests/unit/ForEachNode.test.tsx +0 -308
  120. package/tests/unit/IfElseNode.test.tsx +0 -235
  121. package/tests/unit/ParallelNode.test.tsx +0 -344
  122. package/tests/unit/SwitchNode.test.tsx +0 -327
  123. package/tests/unit/TransformNode.test.tsx +0 -386
  124. package/tests/unit/TryCatchNode.test.tsx +0 -243
  125. package/tests/unit/WhileNode.test.tsx +0 -230
  126. package/tests/unit/agentStore.test.ts +0 -218
  127. package/tests/unit/canvasStore.test.ts +0 -502
  128. package/tests/unit/codexProvider.test.ts +0 -399
  129. package/tests/unit/components.test.tsx +0 -151
  130. package/tests/unit/executionStore.test.ts +0 -567
  131. package/tests/unit/layoutStore.test.ts +0 -194
  132. package/tests/unit/navigationStore.test.ts +0 -152
  133. package/tests/unit/platform.test.ts +0 -118
  134. package/tests/unit/serviceIcons.test.ts +0 -197
  135. package/tests/unit/stepValidation.test.ts +0 -226
  136. package/tests/unit/themeStore.test.ts +0 -141
  137. package/tests/unit/workflowToGraph.test.ts +0 -311
  138. package/tsconfig.json +0 -29
  139. package/tsconfig.server.json +0 -28
  140. package/vite.config.ts +0 -31
  141. package/vitest.config.ts +0 -26
@@ -1,184 +0,0 @@
1
- /**
2
- * Demo AI agent provider
3
- * Provides simulated responses for testing without an API key
4
- */
5
-
6
- import type {
7
- AgentProvider,
8
- AgentCapabilities,
9
- AgentConfig,
10
- PromptResult,
11
- Workflow,
12
- } from './types.js';
13
- import { generateSuggestions, AVAILABLE_SERVICES } from './prompts.js';
14
-
15
- export class DemoProvider implements AgentProvider {
16
- readonly id = 'demo';
17
- readonly name = 'Demo Mode (No API)';
18
- readonly capabilities: AgentCapabilities = {
19
- streaming: false,
20
- toolUse: false,
21
- codeExecution: false,
22
- systemPrompts: false,
23
- models: ['demo'],
24
- };
25
-
26
- private ready: boolean = true;
27
-
28
- async initialize(_config: AgentConfig): Promise<void> {
29
- this.ready = true;
30
- }
31
-
32
- isReady(): boolean {
33
- return this.ready;
34
- }
35
-
36
- getStatus(): { ready: boolean; model?: string; error?: string } {
37
- return { ready: true, model: 'demo' };
38
- }
39
-
40
- async processPrompt(prompt: string, workflow: Workflow): Promise<PromptResult> {
41
- const promptLower = prompt.toLowerCase();
42
- let explanation = '';
43
- const modifiedWorkflow = { ...workflow, steps: [...(workflow.steps || [])] };
44
-
45
- // Detect which service is being requested
46
- const serviceMatch = Object.keys(AVAILABLE_SERVICES).find((s) =>
47
- promptLower.includes(s.toLowerCase())
48
- );
49
-
50
- // Simulate different responses based on prompt patterns
51
- if (promptLower.includes('add') && serviceMatch) {
52
- const service = AVAILABLE_SERVICES[serviceMatch as keyof typeof AVAILABLE_SERVICES];
53
- const action = service.commonActions[0];
54
- const stepId = `${serviceMatch}-${Date.now().toString(36)}`;
55
-
56
- const newStep: any = {
57
- id: stepId,
58
- name: `${serviceMatch.charAt(0).toUpperCase() + serviceMatch.slice(1)} Action`,
59
- action: `${serviceMatch}.${action}`,
60
- inputs: this.generateDefaultInputs(serviceMatch, action),
61
- outputVariable: `${serviceMatch}_result`,
62
- };
63
-
64
- modifiedWorkflow.steps.push(newStep);
65
- explanation = `Added a ${serviceMatch} step using ${serviceMatch}.${action}. The step is configured with default inputs that you should customize.`;
66
- } else if (promptLower.includes('error') || promptLower.includes('retry') || promptLower.includes('handling')) {
67
- const maxRetries = promptLower.match(/(\d+)\s*(retry|retries|times)/)?.[1] || '3';
68
- modifiedWorkflow.steps = modifiedWorkflow.steps.map((step) => ({
69
- ...step,
70
- errorHandling: {
71
- action: 'retry' as const,
72
- maxRetries: parseInt(maxRetries),
73
- retryDelay: 1000,
74
- },
75
- }));
76
- explanation = `Added error handling with ${maxRetries} retries to all ${modifiedWorkflow.steps.length} steps.`;
77
- } else if (promptLower.includes('condition') || promptLower.includes('if') || promptLower.includes('when')) {
78
- if (modifiedWorkflow.steps.length > 0) {
79
- const condition = this.extractCondition(promptLower);
80
- modifiedWorkflow.steps[modifiedWorkflow.steps.length - 1] = {
81
- ...modifiedWorkflow.steps[modifiedWorkflow.steps.length - 1],
82
- conditions: [condition],
83
- };
84
- explanation = `Added condition "${condition}" to the last step.`;
85
- } else {
86
- explanation = 'No steps to add conditions to. Please add some steps first.';
87
- }
88
- } else if (promptLower.includes('remove') || promptLower.includes('delete')) {
89
- if (modifiedWorkflow.steps.length > 0) {
90
- // Try to find a specific step to remove
91
- const stepNameMatch = promptLower.match(/(?:remove|delete)\s+(?:the\s+)?["']?([^"']+)["']?\s+step/);
92
- if (stepNameMatch) {
93
- const targetName = stepNameMatch[1].toLowerCase();
94
- const index = modifiedWorkflow.steps.findIndex(
95
- (s) =>
96
- s.id.toLowerCase().includes(targetName) ||
97
- (s.name && s.name.toLowerCase().includes(targetName))
98
- );
99
- if (index >= 0) {
100
- const removed = modifiedWorkflow.steps.splice(index, 1)[0];
101
- explanation = `Removed step "${removed.name || removed.id}".`;
102
- } else {
103
- const removed = modifiedWorkflow.steps.pop();
104
- explanation = `Could not find a step matching "${targetName}". Removed the last step "${removed?.name || removed?.id}" instead.`;
105
- }
106
- } else {
107
- const removed = modifiedWorkflow.steps.pop();
108
- explanation = `Removed the last step "${removed?.name || removed?.id}".`;
109
- }
110
- } else {
111
- explanation = 'No steps to remove.';
112
- }
113
- } else if (promptLower.includes('notification') || promptLower.includes('notify')) {
114
- modifiedWorkflow.steps.push({
115
- id: `notify-${Date.now().toString(36)}`,
116
- name: 'Send Notification',
117
- action: 'slack.chat.postMessage',
118
- inputs: {
119
- channel: '#notifications',
120
- text: 'Workflow "{{ workflow.name }}" completed successfully!',
121
- },
122
- outputVariable: 'notification_result',
123
- });
124
- explanation = 'Added a Slack notification step at the end of the workflow.';
125
- } else if (promptLower.includes('http') || promptLower.includes('api') || promptLower.includes('request')) {
126
- const method = promptLower.includes('post') ? 'POST' : promptLower.includes('put') ? 'PUT' : 'GET';
127
- modifiedWorkflow.steps.push({
128
- id: `http-${Date.now().toString(36)}`,
129
- name: `HTTP ${method} Request`,
130
- action: 'http.request',
131
- inputs: {
132
- method,
133
- url: '{{ inputs.api_url }}',
134
- headers: { 'Content-Type': 'application/json' },
135
- },
136
- outputVariable: 'api_response',
137
- });
138
- explanation = `Added an HTTP ${method} request step. Configure the URL and any required headers.`;
139
- } else {
140
- explanation = `Demo mode: I understood "${prompt}". In production mode with Claude or Ollama, this would intelligently analyze your request and modify the workflow accordingly. For now, try commands like:\n- "Add a Slack notification"\n- "Add error handling with 5 retries"\n- "Add a condition to run only on success"\n- "Remove the last step"`;
141
- }
142
-
143
- return {
144
- explanation,
145
- workflow: modifiedWorkflow,
146
- };
147
- }
148
-
149
- async getSuggestions(workflow: Workflow, selectedStepId?: string): Promise<string[]> {
150
- // Use the shared suggestions generator
151
- return generateSuggestions(workflow, selectedStepId);
152
- }
153
-
154
- private generateDefaultInputs(service: string, _action: string): Record<string, unknown> {
155
- const defaults: Record<string, Record<string, unknown>> = {
156
- slack: { channel: '#general', text: 'Hello from Marktoflow!' },
157
- github: { owner: '{{ inputs.owner }}', repo: '{{ inputs.repo }}' },
158
- jira: { projectKey: '{{ inputs.project }}', summary: 'New Issue' },
159
- gmail: { to: '{{ inputs.email }}', subject: 'Notification', body: 'Hello!' },
160
- http: { method: 'GET', url: '{{ inputs.url }}' },
161
- linear: { title: 'New Issue', teamId: '{{ inputs.team_id }}' },
162
- notion: { parent: { database_id: '{{ inputs.database_id }}' } },
163
- };
164
- return defaults[service] || {};
165
- }
166
-
167
- private extractCondition(prompt: string): string {
168
- // Try to extract a meaningful condition from the prompt
169
- if (prompt.includes('success')) {
170
- return '{{ previous_step.success === true }}';
171
- }
172
- if (prompt.includes('fail')) {
173
- return '{{ previous_step.success === false }}';
174
- }
175
- if (prompt.includes('production')) {
176
- return '{{ inputs.environment === "production" }}';
177
- }
178
- return '{{ previous_step.success === true }}';
179
- }
180
- }
181
-
182
- export function createDemoProvider(): DemoProvider {
183
- return new DemoProvider();
184
- }
@@ -1,31 +0,0 @@
1
- /**
2
- * Agent Providers Module
3
- *
4
- * This module provides a unified interface for AI agent providers,
5
- * allowing the GUI to work with different backends:
6
- *
7
- * - Claude (Anthropic) - Full-featured AI with streaming support
8
- * - Ollama (Local) - Local LLM support via Ollama
9
- * - Demo Mode - Simulated responses for testing
10
- *
11
- * Usage:
12
- * ```typescript
13
- * import { getAgentRegistry } from './agents';
14
- *
15
- * const registry = getAgentRegistry();
16
- * await registry.autoDetectProvider();
17
- *
18
- * const result = await registry.processPrompt(
19
- * "Add a Slack notification step",
20
- * currentWorkflow
21
- * );
22
- * ```
23
- */
24
-
25
- export * from './types.js';
26
- export * from './registry.js';
27
- export * from './prompts.js';
28
- export { ClaudeProvider, createClaudeProvider } from './claude-provider.js';
29
- export { CopilotProvider, createCopilotProvider } from './copilot-provider.js';
30
- export { DemoProvider, createDemoProvider } from './demo-provider.js';
31
- export { OllamaProvider, createOllamaProvider } from './ollama-provider.js';
@@ -1,267 +0,0 @@
1
- /**
2
- * Ollama AI agent provider
3
- * Uses local Ollama instance for AI capabilities
4
- */
5
-
6
- import { stringify as yamlStringify, parse as yamlParse } from 'yaml';
7
- import type {
8
- AgentProvider,
9
- AgentCapabilities,
10
- AgentConfig,
11
- PromptResult,
12
- Workflow,
13
- } from './types.js';
14
-
15
- const SYSTEM_PROMPT = `You are an expert workflow automation assistant. Help users modify their workflows.
16
-
17
- When modifying workflows:
18
- - Each step has: id, name, action, inputs, output_variable
19
- - Actions use format: service.method (e.g., slack.chat.postMessage)
20
- - Template variables use: {{ variable_name }} syntax
21
-
22
- Respond with:
23
- 1. A brief explanation of changes
24
- 2. The complete modified workflow in YAML format between \`\`\`yaml and \`\`\``;
25
-
26
- export class OllamaProvider implements AgentProvider {
27
- readonly id = 'ollama';
28
- readonly name = 'Ollama (Local)';
29
- readonly capabilities: AgentCapabilities = {
30
- streaming: true,
31
- toolUse: false,
32
- codeExecution: false,
33
- systemPrompts: true,
34
- models: [
35
- 'llama3.2',
36
- 'llama3.1',
37
- 'codellama',
38
- 'mistral',
39
- 'mixtral',
40
- 'phi3',
41
- 'gemma2',
42
- ],
43
- };
44
-
45
- private baseUrl: string = 'http://localhost:11434';
46
- private model: string = 'llama3.2';
47
- private ready: boolean = false;
48
- private error: string | undefined;
49
-
50
- async initialize(config: AgentConfig): Promise<void> {
51
- try {
52
- if (config.baseUrl) {
53
- this.baseUrl = config.baseUrl;
54
- }
55
- if (config.model) {
56
- this.model = config.model;
57
- }
58
-
59
- // Check if Ollama is available
60
- const response = await fetch(`${this.baseUrl}/api/tags`, {
61
- method: 'GET',
62
- signal: AbortSignal.timeout(5000),
63
- });
64
-
65
- if (response.ok) {
66
- this.ready = true;
67
- this.error = undefined;
68
- } else {
69
- this.ready = false;
70
- this.error = 'Ollama server returned an error';
71
- }
72
- } catch (err) {
73
- this.ready = false;
74
- this.error = `Cannot connect to Ollama at ${this.baseUrl}. Is Ollama running?`;
75
- }
76
- }
77
-
78
- isReady(): boolean {
79
- return this.ready;
80
- }
81
-
82
- getStatus(): { ready: boolean; model?: string; error?: string } {
83
- return {
84
- ready: this.ready,
85
- model: this.model,
86
- error: this.error,
87
- };
88
- }
89
-
90
- async processPrompt(prompt: string, workflow: Workflow): Promise<PromptResult> {
91
- if (!this.ready) {
92
- return {
93
- explanation: 'Ollama is not available. Please ensure Ollama is running.',
94
- error: this.error,
95
- };
96
- }
97
-
98
- try {
99
- const workflowYaml = yamlStringify(workflow, { indent: 2, lineWidth: 0 });
100
-
101
- const response = await fetch(`${this.baseUrl}/api/generate`, {
102
- method: 'POST',
103
- headers: { 'Content-Type': 'application/json' },
104
- body: JSON.stringify({
105
- model: this.model,
106
- prompt: `${SYSTEM_PROMPT}\n\nCurrent workflow:\n\`\`\`yaml\n${workflowYaml}\n\`\`\`\n\nUser request: ${prompt}`,
107
- stream: false,
108
- }),
109
- });
110
-
111
- if (!response.ok) {
112
- throw new Error(`Ollama API error: ${response.status}`);
113
- }
114
-
115
- const data = (await response.json()) as { response: string };
116
- return this.parseAIResponse(data.response, workflow);
117
- } catch (err) {
118
- return {
119
- explanation: '',
120
- error: err instanceof Error ? err.message : 'Unknown error',
121
- };
122
- }
123
- }
124
-
125
- async getSuggestions(workflow: Workflow, selectedStepId?: string): Promise<string[]> {
126
- const suggestions: string[] = [];
127
-
128
- if (!workflow || !workflow.steps) {
129
- return [
130
- 'Add your first step',
131
- 'Create a simple workflow',
132
- 'Add an HTTP request',
133
- ];
134
- }
135
-
136
- suggestions.push(
137
- 'Add error handling',
138
- 'Add a notification step',
139
- 'Simplify the workflow'
140
- );
141
-
142
- if (selectedStepId) {
143
- const step = workflow.steps.find((s) => s.id === selectedStepId);
144
- if (step) {
145
- suggestions.push(
146
- `Improve "${step.name || step.id}"`,
147
- `Add validation to "${step.name || step.id}"`
148
- );
149
- }
150
- }
151
-
152
- return suggestions.slice(0, 5);
153
- }
154
-
155
- async streamPrompt(
156
- prompt: string,
157
- workflow: Workflow,
158
- onChunk: (chunk: string) => void
159
- ): Promise<PromptResult> {
160
- if (!this.ready) {
161
- return this.processPrompt(prompt, workflow);
162
- }
163
-
164
- const workflowYaml = yamlStringify(workflow, { indent: 2, lineWidth: 0 });
165
- let fullResponse = '';
166
-
167
- try {
168
- const response = await fetch(`${this.baseUrl}/api/generate`, {
169
- method: 'POST',
170
- headers: { 'Content-Type': 'application/json' },
171
- body: JSON.stringify({
172
- model: this.model,
173
- prompt: `${SYSTEM_PROMPT}\n\nCurrent workflow:\n\`\`\`yaml\n${workflowYaml}\n\`\`\`\n\nUser request: ${prompt}`,
174
- stream: true,
175
- }),
176
- });
177
-
178
- if (!response.ok || !response.body) {
179
- throw new Error(`Ollama API error: ${response.status}`);
180
- }
181
-
182
- const reader = response.body.getReader();
183
- const decoder = new TextDecoder();
184
-
185
- while (true) {
186
- const { done, value } = await reader.read();
187
- if (done) break;
188
-
189
- const chunk = decoder.decode(value);
190
- const lines = chunk.split('\n').filter(Boolean);
191
-
192
- for (const line of lines) {
193
- try {
194
- const data = JSON.parse(line);
195
- if (data.response) {
196
- fullResponse += data.response;
197
- onChunk(data.response);
198
- }
199
- } catch {
200
- // Skip invalid JSON
201
- }
202
- }
203
- }
204
-
205
- return this.parseAIResponse(fullResponse, workflow);
206
- } catch (err) {
207
- return {
208
- explanation: '',
209
- error: err instanceof Error ? err.message : 'Unknown error',
210
- };
211
- }
212
- }
213
-
214
- private parseAIResponse(responseText: string, originalWorkflow: Workflow): PromptResult {
215
- const yamlMatch = responseText.match(/```yaml\n([\s\S]*?)\n```/);
216
- let modifiedWorkflow: Workflow | undefined;
217
- let explanation = responseText;
218
-
219
- if (yamlMatch) {
220
- try {
221
- const parsedYaml = yamlParse(yamlMatch[1]);
222
- if (parsedYaml && (parsedYaml.steps || parsedYaml.metadata)) {
223
- modifiedWorkflow = parsedYaml as Workflow;
224
- const explanationMatch = responseText.match(/^([\s\S]*?)```yaml/);
225
- if (explanationMatch) {
226
- explanation = explanationMatch[1].trim();
227
- }
228
- }
229
- } catch {
230
- // Failed to parse YAML
231
- }
232
- }
233
-
234
- let diff: string | undefined;
235
- if (modifiedWorkflow) {
236
- diff = this.generateDiff(originalWorkflow, modifiedWorkflow);
237
- }
238
-
239
- return { explanation, workflow: modifiedWorkflow, diff };
240
- }
241
-
242
- private generateDiff(original: Workflow, modified: Workflow): string {
243
- const originalStepIds = new Set(original.steps?.map((s) => s.id) || []);
244
- const modifiedStepIds = new Set(modified.steps?.map((s) => s.id) || []);
245
-
246
- const added = modified.steps?.filter((s) => !originalStepIds.has(s.id)) || [];
247
- const removed = original.steps?.filter((s) => !modifiedStepIds.has(s.id)) || [];
248
-
249
- let diff = '';
250
- if (added.length > 0) {
251
- diff += `+ Added ${added.length} step(s)\n`;
252
- }
253
- if (removed.length > 0) {
254
- diff += `- Removed ${removed.length} step(s)\n`;
255
- }
256
-
257
- return diff || 'No structural changes';
258
- }
259
- }
260
-
261
- export function createOllamaProvider(config?: AgentConfig): OllamaProvider {
262
- const provider = new OllamaProvider();
263
- if (config) {
264
- provider.initialize(config);
265
- }
266
- return provider;
267
- }