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

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 (121) hide show
  1. package/package.json +1 -3
  2. package/.marktoflow/state/workflow-state.db +0 -0
  3. package/.marktoflow/state/workflow-state.db-shm +0 -0
  4. package/.marktoflow/state/workflow-state.db-wal +0 -0
  5. package/.turbo/turbo-build.log +0 -42
  6. package/.turbo/turbo-test.log +0 -38
  7. package/marktoflow-gui-2.0.0-alpha.12.tgz +0 -0
  8. package/playwright.config.ts +0 -27
  9. package/postcss.config.js +0 -6
  10. package/src/client/App.tsx +0 -520
  11. package/src/client/components/Canvas/Canvas.tsx +0 -425
  12. package/src/client/components/Canvas/ExecutionOverlay.tsx +0 -935
  13. package/src/client/components/Canvas/ForEachNode.tsx +0 -152
  14. package/src/client/components/Canvas/IfElseNode.tsx +0 -141
  15. package/src/client/components/Canvas/NodeContextMenu.tsx +0 -192
  16. package/src/client/components/Canvas/OutputNode.tsx +0 -111
  17. package/src/client/components/Canvas/ParallelNode.tsx +0 -157
  18. package/src/client/components/Canvas/StepNode.tsx +0 -106
  19. package/src/client/components/Canvas/SubWorkflowNode.tsx +0 -141
  20. package/src/client/components/Canvas/SwitchNode.tsx +0 -185
  21. package/src/client/components/Canvas/Toolbar.tsx +0 -227
  22. package/src/client/components/Canvas/TransformNode.tsx +0 -194
  23. package/src/client/components/Canvas/TriggerNode.tsx +0 -128
  24. package/src/client/components/Canvas/TryCatchNode.tsx +0 -164
  25. package/src/client/components/Canvas/WhileNode.tsx +0 -161
  26. package/src/client/components/Canvas/index.ts +0 -24
  27. package/src/client/components/Debug/VariableInspector.tsx +0 -148
  28. package/src/client/components/Editor/InputsEditor.tsx +0 -458
  29. package/src/client/components/Editor/NewStepWizard.tsx +0 -344
  30. package/src/client/components/Editor/StepEditor.tsx +0 -532
  31. package/src/client/components/Editor/YamlEditor.tsx +0 -160
  32. package/src/client/components/Panels/PropertiesPanel.tsx +0 -589
  33. package/src/client/components/Prompt/ChangePreview.tsx +0 -281
  34. package/src/client/components/Prompt/PromptHistoryPanel.tsx +0 -209
  35. package/src/client/components/Prompt/PromptInput.tsx +0 -110
  36. package/src/client/components/Settings/ProviderSwitcher.tsx +0 -228
  37. package/src/client/components/Sidebar/ImportDialog.tsx +0 -257
  38. package/src/client/components/Sidebar/Sidebar.tsx +0 -362
  39. package/src/client/components/common/Breadcrumb.tsx +0 -40
  40. package/src/client/components/common/Button.tsx +0 -68
  41. package/src/client/components/common/ContextMenu.tsx +0 -202
  42. package/src/client/components/common/KeyboardShortcuts.tsx +0 -149
  43. package/src/client/components/common/Modal.tsx +0 -93
  44. package/src/client/components/common/Tabs.tsx +0 -57
  45. package/src/client/components/common/ThemeToggle.tsx +0 -63
  46. package/src/client/components/index.ts +0 -32
  47. package/src/client/hooks/index.ts +0 -4
  48. package/src/client/hooks/useAIPrompt.ts +0 -108
  49. package/src/client/hooks/useCanvas.ts +0 -247
  50. package/src/client/hooks/useWebSocket.ts +0 -164
  51. package/src/client/hooks/useWorkflow.ts +0 -138
  52. package/src/client/main.tsx +0 -10
  53. package/src/client/stores/agentStore.ts +0 -109
  54. package/src/client/stores/canvasStore.ts +0 -348
  55. package/src/client/stores/editorStore.ts +0 -133
  56. package/src/client/stores/executionStore.ts +0 -502
  57. package/src/client/stores/index.ts +0 -4
  58. package/src/client/stores/layoutStore.ts +0 -103
  59. package/src/client/stores/navigationStore.ts +0 -49
  60. package/src/client/stores/promptStore.ts +0 -113
  61. package/src/client/stores/themeStore.ts +0 -75
  62. package/src/client/stores/workflowStore.ts +0 -185
  63. package/src/client/styles/globals.css +0 -452
  64. package/src/client/utils/cn.ts +0 -9
  65. package/src/client/utils/index.ts +0 -4
  66. package/src/client/utils/platform.ts +0 -46
  67. package/src/client/utils/serviceIcons.tsx +0 -97
  68. package/src/client/utils/stepValidation.ts +0 -155
  69. package/src/client/utils/workflowToGraph.ts +0 -523
  70. package/src/server/index.ts +0 -137
  71. package/src/server/routes/ai.ts +0 -91
  72. package/src/server/routes/execute.ts +0 -71
  73. package/src/server/routes/executions.ts +0 -136
  74. package/src/server/routes/tools.ts +0 -970
  75. package/src/server/routes/workflows.ts +0 -147
  76. package/src/server/services/AIService.ts +0 -105
  77. package/src/server/services/FileWatcher.ts +0 -69
  78. package/src/server/services/WorkflowService.ts +0 -601
  79. package/src/server/services/agents/claude-code-provider.ts +0 -320
  80. package/src/server/services/agents/claude-provider.ts +0 -248
  81. package/src/server/services/agents/codex-provider.ts +0 -398
  82. package/src/server/services/agents/copilot-provider.ts +0 -311
  83. package/src/server/services/agents/demo-provider.ts +0 -184
  84. package/src/server/services/agents/index.ts +0 -31
  85. package/src/server/services/agents/ollama-provider.ts +0 -267
  86. package/src/server/services/agents/prompts.ts +0 -509
  87. package/src/server/services/agents/registry.ts +0 -310
  88. package/src/server/services/agents/types.ts +0 -146
  89. package/src/server/websocket/index.ts +0 -117
  90. package/src/shared/constants.ts +0 -180
  91. package/src/shared/types.ts +0 -179
  92. package/tailwind.config.ts +0 -73
  93. package/tests/e2e/app.spec.ts +0 -90
  94. package/tests/e2e/canvas.spec.ts +0 -128
  95. package/tests/e2e/workflow.spec.ts +0 -185
  96. package/tests/integration/api.test.ts +0 -452
  97. package/tests/integration/testApp.ts +0 -31
  98. package/tests/setup.ts +0 -72
  99. package/tests/unit/ForEachNode.test.tsx +0 -308
  100. package/tests/unit/IfElseNode.test.tsx +0 -235
  101. package/tests/unit/ParallelNode.test.tsx +0 -344
  102. package/tests/unit/SwitchNode.test.tsx +0 -327
  103. package/tests/unit/TransformNode.test.tsx +0 -386
  104. package/tests/unit/TryCatchNode.test.tsx +0 -243
  105. package/tests/unit/WhileNode.test.tsx +0 -230
  106. package/tests/unit/agentStore.test.ts +0 -218
  107. package/tests/unit/canvasStore.test.ts +0 -502
  108. package/tests/unit/codexProvider.test.ts +0 -399
  109. package/tests/unit/components.test.tsx +0 -151
  110. package/tests/unit/executionStore.test.ts +0 -567
  111. package/tests/unit/layoutStore.test.ts +0 -194
  112. package/tests/unit/navigationStore.test.ts +0 -152
  113. package/tests/unit/platform.test.ts +0 -118
  114. package/tests/unit/serviceIcons.test.ts +0 -197
  115. package/tests/unit/stepValidation.test.ts +0 -226
  116. package/tests/unit/themeStore.test.ts +0 -141
  117. package/tests/unit/workflowToGraph.test.ts +0 -311
  118. package/tsconfig.json +0 -29
  119. package/tsconfig.server.json +0 -28
  120. package/vite.config.ts +0 -31
  121. package/vitest.config.ts +0 -26
@@ -1,398 +0,0 @@
1
- /**
2
- * OpenAI Codex AI agent provider
3
- * Uses the @openai/codex-sdk for AI capabilities
4
- */
5
-
6
- import { parse as yamlParse } from 'yaml';
7
- import type {
8
- AgentProvider,
9
- AgentCapabilities,
10
- AgentConfig,
11
- PromptResult,
12
- Workflow,
13
- } from './types.js';
14
- import { buildPrompt, generateSuggestions } from './prompts.js';
15
-
16
- // Dynamic import types for Codex SDK
17
- interface CodexSDK {
18
- Codex: new (options?: CodexOptions) => CodexInstance;
19
- }
20
-
21
- interface CodexOptions {
22
- codexPathOverride?: string;
23
- baseUrl?: string;
24
- apiKey?: string;
25
- env?: Record<string, string>;
26
- }
27
-
28
- interface ThreadOptions {
29
- model?: string;
30
- sandboxMode?: 'read-only' | 'workspace-write' | 'danger-full-access';
31
- workingDirectory?: string;
32
- skipGitRepoCheck?: boolean;
33
- modelReasoningEffort?: 'minimal' | 'low' | 'medium' | 'high' | 'xhigh';
34
- networkAccessEnabled?: boolean;
35
- webSearchMode?: 'disabled' | 'cached' | 'live';
36
- approvalPolicy?: 'never' | 'on-request' | 'on-failure' | 'untrusted';
37
- additionalDirectories?: string[];
38
- }
39
-
40
- interface ThreadItem {
41
- id: string;
42
- type: string;
43
- text?: string;
44
- command?: string;
45
- aggregated_output?: string;
46
- status?: string;
47
- changes?: unknown[];
48
- }
49
-
50
- interface Usage {
51
- input_tokens: number;
52
- cached_input_tokens: number;
53
- output_tokens: number;
54
- }
55
-
56
- interface TurnResult {
57
- items: ThreadItem[];
58
- finalResponse: string;
59
- usage: Usage | null;
60
- }
61
-
62
- interface ThreadEvent {
63
- type: string;
64
- thread_id?: string;
65
- item?: ThreadItem;
66
- usage?: Usage;
67
- message?: string;
68
- error?: { message: string };
69
- }
70
-
71
- interface StreamedTurnResult {
72
- events: AsyncGenerator<ThreadEvent>;
73
- }
74
-
75
- interface Thread {
76
- id: string | null;
77
- run(input: string, options?: unknown): Promise<TurnResult>;
78
- runStreamed(input: string, options?: unknown): Promise<StreamedTurnResult>;
79
- }
80
-
81
- interface CodexInstance {
82
- startThread(options?: ThreadOptions): Thread;
83
- resumeThread(id: string, options?: ThreadOptions): Thread;
84
- }
85
-
86
- export class CodexProvider implements AgentProvider {
87
- readonly id = 'codex';
88
- readonly name = 'OpenAI Codex';
89
- readonly capabilities: AgentCapabilities = {
90
- streaming: true,
91
- toolUse: true,
92
- codeExecution: true,
93
- systemPrompts: true,
94
- models: [
95
- 'codex-1',
96
- 'o3',
97
- 'o3-mini',
98
- 'o4-mini',
99
- 'gpt-4.1',
100
- ],
101
- };
102
-
103
- private codex: CodexInstance | null = null;
104
- private model: string = 'codex-1';
105
- private ready: boolean = false;
106
- private error: string | undefined;
107
- private workingDirectory: string = process.cwd();
108
- private lastThreadId: string | null = null;
109
-
110
- async initialize(config: AgentConfig): Promise<void> {
111
- try {
112
- // Try to import the Codex SDK (dynamic import with webpackIgnore to avoid bundling issues)
113
- const sdkModule = (await import(
114
- /* webpackIgnore: true */ '@openai/codex-sdk'
115
- ).catch(() => null)) as CodexSDK | null;
116
-
117
- if (!sdkModule || !sdkModule.Codex) {
118
- this.ready = false;
119
- this.error = 'OpenAI Codex SDK not installed. Run: npm install @openai/codex-sdk';
120
- return;
121
- }
122
-
123
- const { Codex } = sdkModule;
124
-
125
- const codexOptions: CodexOptions = {};
126
-
127
- // API key from config or environment
128
- if (config.apiKey) {
129
- codexOptions.apiKey = config.apiKey;
130
- } else if (process.env.OPENAI_API_KEY) {
131
- codexOptions.apiKey = process.env.OPENAI_API_KEY;
132
- }
133
-
134
- // Base URL
135
- if (config.baseUrl) {
136
- codexOptions.baseUrl = config.baseUrl;
137
- }
138
-
139
- // Codex path override
140
- if (config.options?.codexPath) {
141
- codexOptions.codexPathOverride = config.options.codexPath as string;
142
- }
143
-
144
- // Environment variables
145
- if (config.options?.env) {
146
- codexOptions.env = config.options.env as Record<string, string>;
147
- }
148
-
149
- this.codex = new Codex(codexOptions);
150
-
151
- if (config.model) {
152
- this.model = config.model;
153
- }
154
-
155
- // Working directory
156
- if (config.options?.workingDirectory) {
157
- this.workingDirectory = config.options.workingDirectory as string;
158
- } else if (config.options?.cwd) {
159
- this.workingDirectory = config.options.cwd as string;
160
- }
161
-
162
- // Test connectivity by starting a simple thread
163
- try {
164
- const thread = this.codex.startThread({
165
- skipGitRepoCheck: true,
166
- sandboxMode: 'read-only',
167
- workingDirectory: this.workingDirectory,
168
- });
169
- // Just verify it can be created
170
- if (thread) {
171
- this.ready = true;
172
- this.error = undefined;
173
- }
174
- } catch (testError) {
175
- this.ready = false;
176
- this.error = `Cannot initialize Codex: ${testError instanceof Error ? testError.message : 'Unknown error'}`;
177
- }
178
- } catch (err) {
179
- this.ready = false;
180
- this.error = err instanceof Error ? err.message : 'Unknown error initializing Codex';
181
- }
182
- }
183
-
184
- isReady(): boolean {
185
- return this.ready;
186
- }
187
-
188
- getStatus(): { ready: boolean; model?: string; error?: string } {
189
- return {
190
- ready: this.ready,
191
- model: this.model,
192
- error: this.error,
193
- };
194
- }
195
-
196
- async processPrompt(
197
- prompt: string,
198
- workflow: Workflow,
199
- context?: { selectedStepId?: string; recentHistory?: string[] }
200
- ): Promise<PromptResult> {
201
- if (!this.codex || !this.ready) {
202
- return {
203
- explanation: 'OpenAI Codex provider not available.',
204
- error: this.error || 'Provider not initialized',
205
- };
206
- }
207
-
208
- try {
209
- // Build context-aware prompts
210
- const { systemPrompt, userPrompt } = buildPrompt(prompt, workflow, context);
211
-
212
- // Combine system and user prompts for Codex
213
- const fullPrompt = `${systemPrompt}\n\n---\n\n${userPrompt}`;
214
-
215
- const thread = this.codex.startThread({
216
- model: this.model,
217
- skipGitRepoCheck: true,
218
- sandboxMode: 'read-only', // Safe for workflow modifications
219
- workingDirectory: this.workingDirectory,
220
- modelReasoningEffort: 'medium',
221
- });
222
-
223
- const result = await thread.run(fullPrompt);
224
- this.lastThreadId = thread.id;
225
-
226
- // Extract the response text
227
- const responseText = result.finalResponse ||
228
- result.items.find((item) => item.type === 'agent_message')?.text || '';
229
-
230
- return this.parseAIResponse(responseText, workflow);
231
- } catch (err) {
232
- return {
233
- explanation: '',
234
- error: err instanceof Error ? err.message : 'Unknown error',
235
- };
236
- }
237
- }
238
-
239
- async getSuggestions(workflow: Workflow, selectedStepId?: string): Promise<string[]> {
240
- return generateSuggestions(workflow, selectedStepId);
241
- }
242
-
243
- async streamPrompt(
244
- prompt: string,
245
- workflow: Workflow,
246
- onChunk: (chunk: string) => void,
247
- context?: { selectedStepId?: string; recentHistory?: string[] }
248
- ): Promise<PromptResult> {
249
- if (!this.codex || !this.ready) {
250
- return this.processPrompt(prompt, workflow, context);
251
- }
252
-
253
- const { systemPrompt, userPrompt } = buildPrompt(prompt, workflow, context);
254
- const fullPrompt = `${systemPrompt}\n\n---\n\n${userPrompt}`;
255
- let fullResponse = '';
256
-
257
- try {
258
- const thread = this.codex.startThread({
259
- model: this.model,
260
- skipGitRepoCheck: true,
261
- sandboxMode: 'read-only',
262
- workingDirectory: this.workingDirectory,
263
- modelReasoningEffort: 'medium',
264
- });
265
-
266
- const streamResult = await thread.runStreamed(fullPrompt);
267
-
268
- for await (const event of streamResult.events) {
269
- if (event.type === 'thread.started') {
270
- this.lastThreadId = event.thread_id || null;
271
- } else if (event.type === 'item.completed' && event.item?.type === 'agent_message') {
272
- const text = event.item.text || '';
273
- fullResponse = text;
274
- onChunk(text);
275
- } else if (event.type === 'error') {
276
- throw new Error(event.message || 'Stream error');
277
- } else if (event.type === 'turn.failed') {
278
- throw new Error(event.error?.message || 'Turn failed');
279
- }
280
- }
281
-
282
- return this.parseAIResponse(fullResponse, workflow);
283
- } catch (err) {
284
- return {
285
- explanation: '',
286
- error: err instanceof Error ? err.message : 'Unknown error',
287
- };
288
- }
289
- }
290
-
291
- async cancel(): Promise<void> {
292
- // Codex SDK doesn't have explicit cancellation, but we can reset state
293
- this.lastThreadId = null;
294
- }
295
-
296
- /**
297
- * Get the last thread ID for resumption
298
- */
299
- getLastThreadId(): string | null {
300
- return this.lastThreadId;
301
- }
302
-
303
- /**
304
- * Resume a previous thread
305
- */
306
- async resumePrompt(
307
- threadId: string,
308
- prompt: string,
309
- workflow: Workflow,
310
- context?: { selectedStepId?: string; recentHistory?: string[] }
311
- ): Promise<PromptResult> {
312
- if (!this.codex || !this.ready) {
313
- return {
314
- explanation: 'OpenAI Codex provider not available.',
315
- error: this.error || 'Provider not initialized',
316
- };
317
- }
318
-
319
- try {
320
- const { systemPrompt, userPrompt } = buildPrompt(prompt, workflow, context);
321
- const fullPrompt = `${systemPrompt}\n\n---\n\n${userPrompt}`;
322
-
323
- const thread = this.codex.resumeThread(threadId, {
324
- model: this.model,
325
- skipGitRepoCheck: true,
326
- sandboxMode: 'read-only',
327
- workingDirectory: this.workingDirectory,
328
- });
329
-
330
- const result = await thread.run(fullPrompt);
331
- this.lastThreadId = thread.id;
332
-
333
- const responseText = result.finalResponse ||
334
- result.items.find((item) => item.type === 'agent_message')?.text || '';
335
-
336
- return this.parseAIResponse(responseText, workflow);
337
- } catch (err) {
338
- return {
339
- explanation: '',
340
- error: err instanceof Error ? err.message : 'Unknown error',
341
- };
342
- }
343
- }
344
-
345
- private parseAIResponse(responseText: string, originalWorkflow: Workflow): PromptResult {
346
- const yamlMatch = responseText.match(/```yaml\n([\s\S]*?)\n```/);
347
- let modifiedWorkflow: Workflow | undefined;
348
- let explanation = responseText;
349
-
350
- if (yamlMatch) {
351
- try {
352
- const parsedYaml = yamlParse(yamlMatch[1]);
353
- if (parsedYaml && (parsedYaml.steps || parsedYaml.metadata)) {
354
- modifiedWorkflow = parsedYaml as Workflow;
355
- const explanationMatch = responseText.match(/^([\s\S]*?)```yaml/);
356
- if (explanationMatch) {
357
- explanation = explanationMatch[1].trim();
358
- }
359
- }
360
- } catch {
361
- // Failed to parse YAML
362
- }
363
- }
364
-
365
- let diff: string | undefined;
366
- if (modifiedWorkflow) {
367
- diff = this.generateDiff(originalWorkflow, modifiedWorkflow);
368
- }
369
-
370
- return { explanation, workflow: modifiedWorkflow, diff };
371
- }
372
-
373
- private generateDiff(original: Workflow, modified: Workflow): string {
374
- const originalStepIds = new Set(original.steps?.map((s) => s.id) || []);
375
- const modifiedStepIds = new Set(modified.steps?.map((s) => s.id) || []);
376
-
377
- const added = modified.steps?.filter((s) => !originalStepIds.has(s.id)) || [];
378
- const removed = original.steps?.filter((s) => !modifiedStepIds.has(s.id)) || [];
379
-
380
- let diff = '';
381
- if (added.length > 0) {
382
- diff += `+ Added ${added.length} step(s): ${added.map((s) => s.name || s.id).join(', ')}\n`;
383
- }
384
- if (removed.length > 0) {
385
- diff += `- Removed ${removed.length} step(s): ${removed.map((s) => s.name || s.id).join(', ')}\n`;
386
- }
387
-
388
- return diff || 'No structural changes detected';
389
- }
390
- }
391
-
392
- export function createCodexProvider(config?: AgentConfig): CodexProvider {
393
- const provider = new CodexProvider();
394
- if (config) {
395
- provider.initialize(config);
396
- }
397
- return provider;
398
- }
@@ -1,311 +0,0 @@
1
- /**
2
- * GitHub Copilot AI agent provider
3
- * Uses the @github/copilot-sdk for AI capabilities
4
- */
5
-
6
- import { createRequire } from 'node:module';
7
- import { parse as yamlParse } from 'yaml';
8
- import type {
9
- AgentProvider,
10
- AgentCapabilities,
11
- AgentConfig,
12
- PromptResult,
13
- Workflow,
14
- } from './types.js';
15
- import { buildPrompt, generateSuggestions } from './prompts.js';
16
-
17
- // Polyfill require for ESM environments (needed by Copilot SDK dependencies)
18
- if (typeof globalThis.require === 'undefined') {
19
- (globalThis as unknown as { require: NodeRequire }).require = createRequire(import.meta.url);
20
- }
21
-
22
- // Dynamic import types for Copilot SDK
23
- // Using loose types to handle SDK version differences
24
- interface CopilotClientConfig {
25
- cliPath?: string;
26
- cliUrl?: string;
27
- autoStart?: boolean;
28
- logLevel?: 'error' | 'info' | 'none' | 'warning' | 'debug' | 'all';
29
- }
30
-
31
- interface CopilotSessionOptions {
32
- model?: string;
33
- streaming?: boolean;
34
- systemMessage?: { content: string };
35
- }
36
-
37
- interface CopilotSessionResponse {
38
- data?: {
39
- content?: string;
40
- messageId?: string;
41
- };
42
- }
43
-
44
- interface SessionEvent {
45
- type: string;
46
- data: {
47
- deltaContent?: string;
48
- content?: string;
49
- message?: string;
50
- };
51
- }
52
-
53
- export class CopilotProvider implements AgentProvider {
54
- readonly id = 'copilot';
55
- readonly name = 'GitHub Copilot';
56
- readonly capabilities: AgentCapabilities = {
57
- streaming: true,
58
- toolUse: true,
59
- codeExecution: true,
60
- systemPrompts: true,
61
- models: [
62
- 'gpt-4.1',
63
- 'gpt-4o',
64
- 'gpt-4-turbo',
65
- 'claude-3.5-sonnet',
66
- ],
67
- };
68
-
69
- // Using 'unknown' to handle SDK version differences
70
- private client: unknown = null;
71
- private model: string = 'gpt-4.1';
72
- private ready: boolean = false;
73
- private error: string | undefined;
74
- private cliPath?: string;
75
- private cliUrl?: string;
76
-
77
- async initialize(config: AgentConfig): Promise<void> {
78
- try {
79
- // Try to import the Copilot SDK (dynamic import with webpackIgnore to avoid bundling issues)
80
- const sdkModule = await import(/* webpackIgnore: true */ '@github/copilot-sdk').catch(
81
- () => null
82
- );
83
- if (!sdkModule || !sdkModule.CopilotClient) {
84
- this.ready = false;
85
- this.error = 'GitHub Copilot SDK not installed. Run: npm install @github/copilot-sdk';
86
- return;
87
- }
88
- const { CopilotClient } = sdkModule;
89
-
90
- this.cliPath = config.options?.cliPath as string;
91
- this.cliUrl = config.baseUrl || (config.options?.cliUrl as string);
92
-
93
- const clientConfig: CopilotClientConfig = {
94
- autoStart: true,
95
- logLevel: 'error',
96
- };
97
-
98
- if (this.cliUrl) {
99
- clientConfig.cliUrl = this.cliUrl;
100
- } else {
101
- clientConfig.cliPath = this.cliPath || 'copilot';
102
- }
103
-
104
- this.client = new CopilotClient(clientConfig);
105
-
106
- if (config.model) {
107
- this.model = config.model;
108
- }
109
-
110
- // Start the client and test connectivity
111
- try {
112
- if (this.client) {
113
- // Some SDK versions have start(), some don't (auto-start)
114
- const client = this.client as { start?: () => Promise<void>; ping?: () => Promise<unknown> };
115
- if (typeof client.start === 'function') {
116
- await client.start();
117
- }
118
- if (typeof client.ping === 'function') {
119
- await client.ping();
120
- }
121
- this.ready = true;
122
- this.error = undefined;
123
- }
124
- } catch (pingError) {
125
- this.ready = false;
126
- this.error = `Cannot connect to GitHub Copilot CLI: ${pingError instanceof Error ? pingError.message : 'Unknown error'}`;
127
- }
128
- } catch (err) {
129
- this.ready = false;
130
- this.error = err instanceof Error ? err.message : 'Unknown error initializing Copilot';
131
- }
132
- }
133
-
134
- isReady(): boolean {
135
- return this.ready;
136
- }
137
-
138
- getStatus(): { ready: boolean; model?: string; error?: string } {
139
- return {
140
- ready: this.ready,
141
- model: this.model,
142
- error: this.error,
143
- };
144
- }
145
-
146
- async processPrompt(
147
- prompt: string,
148
- workflow: Workflow,
149
- context?: { selectedStepId?: string; recentHistory?: string[] }
150
- ): Promise<PromptResult> {
151
- if (!this.client || !this.ready) {
152
- return {
153
- explanation: 'GitHub Copilot provider not available.',
154
- error: this.error || 'Provider not initialized',
155
- };
156
- }
157
-
158
- try {
159
- // Build context-aware prompts
160
- const { systemPrompt, userPrompt } = buildPrompt(prompt, workflow, context);
161
-
162
- const client = this.client as {
163
- createSession: (opts: CopilotSessionOptions) => Promise<{
164
- sendAndWait: (opts: { prompt: string }) => Promise<CopilotSessionResponse | null>;
165
- destroy: () => Promise<void>;
166
- }>;
167
- };
168
-
169
- const session = await client.createSession({
170
- model: this.model,
171
- systemMessage: { content: systemPrompt },
172
- });
173
-
174
- try {
175
- const response = await session.sendAndWait({ prompt: userPrompt });
176
- const responseText = response?.data?.content || '';
177
- return this.parseAIResponse(responseText, workflow);
178
- } finally {
179
- await session.destroy();
180
- }
181
- } catch (err) {
182
- return {
183
- explanation: '',
184
- error: err instanceof Error ? err.message : 'Unknown error',
185
- };
186
- }
187
- }
188
-
189
- async getSuggestions(workflow: Workflow, selectedStepId?: string): Promise<string[]> {
190
- return generateSuggestions(workflow, selectedStepId);
191
- }
192
-
193
- async streamPrompt(
194
- prompt: string,
195
- workflow: Workflow,
196
- onChunk: (chunk: string) => void,
197
- context?: { selectedStepId?: string; recentHistory?: string[] }
198
- ): Promise<PromptResult> {
199
- if (!this.client || !this.ready) {
200
- return this.processPrompt(prompt, workflow, context);
201
- }
202
-
203
- const { systemPrompt, userPrompt } = buildPrompt(prompt, workflow, context);
204
- let fullResponse = '';
205
-
206
- try {
207
- const client = this.client as {
208
- createSession: (opts: CopilotSessionOptions) => Promise<{
209
- send: (opts: { prompt: string }) => Promise<void>;
210
- on: (callback: (event: SessionEvent) => void) => void;
211
- destroy: () => Promise<void>;
212
- }>;
213
- };
214
-
215
- const session = await client.createSession({
216
- model: this.model,
217
- streaming: true,
218
- systemMessage: { content: systemPrompt },
219
- });
220
-
221
- return new Promise((resolve, reject) => {
222
- session.on((event: SessionEvent) => {
223
- if (event.type === 'assistant.message_delta') {
224
- const chunk = event.data.deltaContent || '';
225
- fullResponse += chunk;
226
- onChunk(chunk);
227
- } else if (event.type === 'assistant.message') {
228
- fullResponse = event.data.content || fullResponse;
229
- } else if (event.type === 'session.idle') {
230
- session
231
- .destroy()
232
- .then(() => resolve(this.parseAIResponse(fullResponse, workflow)))
233
- .catch(reject);
234
- } else if (event.type === 'session.error') {
235
- reject(new Error(event.data.message || 'Session error'));
236
- }
237
- });
238
-
239
- session.send({ prompt: userPrompt }).catch(reject);
240
- });
241
- } catch (err) {
242
- return {
243
- explanation: '',
244
- error: err instanceof Error ? err.message : 'Unknown error',
245
- };
246
- }
247
- }
248
-
249
- async cancel(): Promise<void> {
250
- if (this.client) {
251
- const client = this.client as { stop?: () => Promise<unknown> };
252
- if (typeof client.stop === 'function') {
253
- await client.stop();
254
- }
255
- }
256
- }
257
-
258
- private parseAIResponse(responseText: string, originalWorkflow: Workflow): PromptResult {
259
- const yamlMatch = responseText.match(/```yaml\n([\s\S]*?)\n```/);
260
- let modifiedWorkflow: Workflow | undefined;
261
- let explanation = responseText;
262
-
263
- if (yamlMatch) {
264
- try {
265
- const parsedYaml = yamlParse(yamlMatch[1]);
266
- if (parsedYaml && (parsedYaml.steps || parsedYaml.metadata)) {
267
- modifiedWorkflow = parsedYaml as Workflow;
268
- const explanationMatch = responseText.match(/^([\s\S]*?)```yaml/);
269
- if (explanationMatch) {
270
- explanation = explanationMatch[1].trim();
271
- }
272
- }
273
- } catch {
274
- // Failed to parse YAML
275
- }
276
- }
277
-
278
- let diff: string | undefined;
279
- if (modifiedWorkflow) {
280
- diff = this.generateDiff(originalWorkflow, modifiedWorkflow);
281
- }
282
-
283
- return { explanation, workflow: modifiedWorkflow, diff };
284
- }
285
-
286
- private generateDiff(original: Workflow, modified: Workflow): string {
287
- const originalStepIds = new Set(original.steps?.map((s) => s.id) || []);
288
- const modifiedStepIds = new Set(modified.steps?.map((s) => s.id) || []);
289
-
290
- const added = modified.steps?.filter((s) => !originalStepIds.has(s.id)) || [];
291
- const removed = original.steps?.filter((s) => !modifiedStepIds.has(s.id)) || [];
292
-
293
- let diff = '';
294
- if (added.length > 0) {
295
- diff += `+ Added ${added.length} step(s): ${added.map((s) => s.name || s.id).join(', ')}\n`;
296
- }
297
- if (removed.length > 0) {
298
- diff += `- Removed ${removed.length} step(s): ${removed.map((s) => s.name || s.id).join(', ')}\n`;
299
- }
300
-
301
- return diff || 'No structural changes detected';
302
- }
303
- }
304
-
305
- export function createCopilotProvider(config?: AgentConfig): CopilotProvider {
306
- const provider = new CopilotProvider();
307
- if (config) {
308
- provider.initialize(config);
309
- }
310
- return provider;
311
- }