-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathworkflow.go
More file actions
4392 lines (3848 loc) · 146 KB
/
Copy pathworkflow.go
File metadata and controls
4392 lines (3848 loc) · 146 KB
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
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package server
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"log"
"net/http"
"net/url"
"os"
"path/filepath"
"regexp"
"sort"
"strconv"
"strings"
"sync"
"time"
virtualtools "github.com/manishiitg/coding-agent-loop/agent_go/cmd/server/virtual-tools"
"github.com/manishiitg/coding-agent-loop/agent_go/pkg/fsutil"
"github.com/manishiitg/coding-agent-loop/agent_go/pkg/orchestrator"
"github.com/manishiitg/coding-agent-loop/agent_go/pkg/workflowtypes"
todo_creation_human "github.com/manishiitg/coding-agent-loop/agent_go/pkg/orchestrator/agents/workflow/step_based_workflow"
)
// resolveWorkflowLLMConfigForWorkspace reads the workflow.json manifest at workspacePath
// and extracts the LLM configuration for use in workflow execution.
//
//nolint:unused // retained for the workflow-manifest execution path while routes are being migrated.
func (api *StreamingAPI) resolveWorkflowLLMConfigForWorkspace(
ctx context.Context,
workspacePath string,
userID string,
) (*todo_creation_human.AgentLLMConfig, *todo_creation_human.TieredLLMConfig, string, error) {
// Try to load manifest from workspace
manifest, exists, err := ReadWorkflowManifest(ctx, workspacePath)
if err == nil && exists && manifest.Capabilities.LLMConfig != nil {
llmCfg := manifest.Capabilities.LLMConfig
phaseLLM, tieredConfig := workshopResolveLLMConfig(llmCfg)
return phaseLLM, tieredConfig, manifest.ID, nil
}
// Fallback to server defaults
if api.provider != "" && api.model != "" {
return &todo_creation_human.AgentLLMConfig{
Provider: api.provider,
ModelID: api.model,
}, nil, "", nil
}
return nil, nil, "", nil
}
// getWorkspaceAPIURL returns the workspace API base URL from environment or default
func getWorkspaceAPIURL() string {
if url := os.Getenv("WORKSPACE_API_URL"); url != "" {
return url
}
return "http://127.0.0.1:8081"
}
// getWorkspaceDocsAbsPath returns the absolute filesystem path to the workspace docs root.
//
//nolint:unused // kept as a shared helper for upcoming absolute-path route cleanup.
func getWorkspaceDocsAbsPath() string {
return fsutil.WorkspaceDocsRoot()
}
// listGroupSubdirs returns the names of immediate subdirectories under a workspace
// folder path, used to discover per-group folders inside an iteration (e.g. the
// "xspaces" / "excellence" / etc. dirs under runs/iteration-N/). Returns nil on
// any error or when the folder is empty.
func listGroupSubdirs(ctx context.Context, folderPath string) []string {
apiURL := getWorkspaceAPIURL() + "/api/documents"
req, err := http.NewRequestWithContext(ctx, "GET", apiURL, nil)
if err != nil {
return nil
}
q := req.URL.Query()
q.Add("folder", folderPath)
q.Add("max_depth", "1")
req.URL.RawQuery = q.Encode()
resp, err := workspaceHTTPClient.Do(req)
if err != nil {
return nil
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return nil
}
body, err := io.ReadAll(resp.Body)
if err != nil {
return nil
}
var listing struct {
Success bool `json:"success"`
Data virtualtools.WorkspaceFolderListing `json:"data"`
}
if err := json.Unmarshal(body, &listing); err != nil || !listing.Success {
return nil
}
var groups []string
for _, item := range listing.Data {
if item.Type != "folder" {
continue
}
name := filepath.Base(item.FilePath)
groups = append(groups, name)
}
return groups
}
// workspacePathExists reports whether a workspace folder path resolves to a
// listing. Used to detect whether the old flat "runs/{iter}/logs" layout exists
// before falling back to the newer "runs/{iter}/{group}/logs" nesting.
func workspacePathExists(ctx context.Context, folderPath string) bool {
apiURL := getWorkspaceAPIURL() + "/api/documents"
req, err := http.NewRequestWithContext(ctx, "GET", apiURL, nil)
if err != nil {
return false
}
q := req.URL.Query()
q.Add("folder", folderPath)
q.Add("max_depth", "1")
req.URL.RawQuery = q.Encode()
resp, err := workspaceHTTPClient.Do(req)
if err != nil {
return false
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return false
}
body, err := io.ReadAll(resp.Body)
if err != nil {
return false
}
var listing struct {
Success bool `json:"success"`
}
if err := json.Unmarshal(body, &listing); err != nil {
return false
}
return listing.Success
}
// readFileFromWorkspace reads a file from the workspace API and returns its content as a string
// Returns (content, true, nil) if file exists, (empty, false, nil) if file doesn't exist (404), or (empty, false, error) on error
func readFileFromWorkspace(ctx context.Context, filePath string) (string, bool, error) {
// URL-encode the filepath segments
pathSegments := strings.Split(filePath, "/")
encodedSegments := make([]string, len(pathSegments))
for i, segment := range pathSegments {
encodedSegments[i] = url.PathEscape(segment)
}
encodedPath := strings.Join(encodedSegments, "/")
// Read file from workspace API
apiURL := getWorkspaceAPIURL() + "/api/documents/" + encodedPath
req, err := http.NewRequestWithContext(ctx, "GET", apiURL, nil)
if err != nil {
return "", false, fmt.Errorf("failed to create request: %w", err)
}
resp, err := workspaceHTTPClient.Do(req)
if err != nil {
return "", false, fmt.Errorf("failed to call workspace API: %w", err)
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
return "", false, fmt.Errorf("failed to read response: %w", err)
}
// Check if file doesn't exist (404) - this is not an error
if resp.StatusCode == http.StatusNotFound {
return "", false, nil // File doesn't exist, but not an error
}
if resp.StatusCode != http.StatusOK {
return "", false, fmt.Errorf("workspace API returned status %d: %s", resp.StatusCode, string(body))
}
// Parse workspace API response
var apiResp virtualtools.WorkspaceAPIResponse
if err := json.Unmarshal(body, &apiResp); err != nil {
return "", false, fmt.Errorf("failed to parse API response: %w", err)
}
if !apiResp.Success {
return "", false, fmt.Errorf("workspace API error: %s", apiResp.Error)
}
// Check if file doesn't exist (API returns Success: true but with error/message)
if strings.Contains(apiResp.Message, "File does not exist") ||
strings.Contains(apiResp.Error, "File not found") {
return "", false, nil // File doesn't exist, not an error
}
// Extract content from response
var content string
isBinary := false
if fileContent, ok := apiResp.Data.(virtualtools.WorkspaceFileContent); ok {
content = fileContent.Content
} else if dataMap, ok := apiResp.Data.(map[string]interface{}); ok {
if b, ok := dataMap["is_binary"].(bool); ok {
isBinary = b
}
if c, ok := dataMap["content"].(string); ok {
content = c
}
}
if isBinary {
return "", true, fmt.Errorf("cannot read binary file as text: %s", filePath)
}
if content == "" {
if dataMap, ok := apiResp.Data.(map[string]interface{}); ok {
if _, hasContent := dataMap["content"]; hasContent {
return "", true, nil
}
if b, hasBinary := dataMap["is_binary"].(bool); hasBinary && !b {
return "", true, nil
}
}
// Debug logging to see actual response structure
dataBytes, _ := json.Marshal(apiResp.Data)
log.Printf("[DEBUG] readFileFromWorkspace: Failed to extract content from response. FilePath: %s, Response Data: %s", filePath, string(dataBytes))
return "", false, fmt.Errorf("failed to extract content from API response")
}
return content, true, nil
}
// deleteWorkspaceFile deletes a file from the workspace via the workspace API.
// Returns nil if the file doesn't exist (404) or was successfully deleted.
func deleteWorkspaceFile(ctx context.Context, configPath string) error {
pathSegments := strings.Split(configPath, "/")
encodedSegments := make([]string, len(pathSegments))
for i, segment := range pathSegments {
encodedSegments[i] = url.PathEscape(segment)
}
encodedPath := strings.Join(encodedSegments, "/")
apiURL := getWorkspaceAPIURL() + "/api/documents/" + encodedPath + "?confirm=true"
req, err := http.NewRequestWithContext(ctx, "DELETE", apiURL, nil)
if err != nil {
return fmt.Errorf("failed to create request: %w", err)
}
resp, err := workspaceHTTPClient.Do(req)
if err != nil {
return fmt.Errorf("failed to call workspace API: %w", err)
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
return fmt.Errorf("failed to read response: %w", err)
}
if resp.StatusCode == http.StatusNotFound {
return nil
}
if resp.StatusCode != http.StatusOK && resp.StatusCode != http.StatusNoContent {
return fmt.Errorf("workspace API returned status %d: %s", resp.StatusCode, string(body))
}
return nil
}
// writeFileToWorkspace writes content to a file in the workspace via the workspace API
func writeFileToWorkspace(ctx context.Context, filePath, content string) error {
pathSegments := strings.Split(filePath, "/")
encodedSegments := make([]string, len(pathSegments))
for i, segment := range pathSegments {
encodedSegments[i] = url.PathEscape(segment)
}
encodedPath := strings.Join(encodedSegments, "/")
requestBodyJSON, err := json.Marshal(map[string]interface{}{"content": content})
if err != nil {
return fmt.Errorf("failed to marshal request body: %w", err)
}
apiURL := getWorkspaceAPIURL() + "/api/documents/" + encodedPath
req, err := http.NewRequestWithContext(ctx, "PUT", apiURL, strings.NewReader(string(requestBodyJSON)))
if err != nil {
return fmt.Errorf("failed to create request: %w", err)
}
req.Header.Set("Content-Type", "application/json")
resp, err := workspaceHTTPClient.Do(req)
if err != nil {
return fmt.Errorf("failed to call workspace API: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK && resp.StatusCode != http.StatusCreated && resp.StatusCode != http.StatusNoContent {
body, _ := io.ReadAll(resp.Body)
return fmt.Errorf("workspace API returned status %d: %s", resp.StatusCode, string(body))
}
return nil
}
// readProgressForFolder reads steps_done.json for a given folder and returns the progress
// Returns nil if the file doesn't exist or can't be read (non-fatal)
func readRunMetadata(ctx context.Context, metadataFilePath string) (*RunMetadata, error) {
content, exists, err := readFileFromWorkspace(ctx, metadataFilePath)
if err != nil {
return nil, err
}
if !exists {
return nil, nil
}
var metadata RunMetadata
if err := json.Unmarshal([]byte(content), &metadata); err != nil {
return nil, nil
}
if metadata.StartedAt.IsZero() {
metadata.StartedAt = metadata.CreatedAt
}
if metadata.DurationMs == nil && metadata.CompletedAt != nil && !metadata.StartedAt.IsZero() {
durationMs := metadata.CompletedAt.Sub(metadata.StartedAt).Milliseconds()
metadata.DurationMs = &durationMs
}
return &metadata, nil
}
// inferRunMetadata creates metadata for legacy run folders that don't have run_metadata.json.
// Uses the migrated costs store created_at as start time, progress.LastUpdated for completion.
func inferRunMetadata(ctx context.Context, workspacePath, folderName string, progress *StepProgress) *RunMetadata {
if progress == nil {
return nil
}
metadata := &RunMetadata{
Status: "running",
TriggeredBy: "manual", // assume manual for legacy runs
}
if executionCosts, err := readAllRunTokenUsageFromCosts(ctx, workspacePath, orchestrator.CostScopeExecution); err == nil {
for _, execution := range executionCosts {
if execution == nil || execution.TokenUsage == nil || execution.effectiveRunFolder() != folderName || execution.TokenUsage.CreatedAt.IsZero() {
continue
}
if metadata.CreatedAt.IsZero() || execution.TokenUsage.CreatedAt.Before(metadata.CreatedAt) {
metadata.CreatedAt = execution.TokenUsage.CreatedAt
}
}
}
// Fallback: use progress.LastUpdated as rough created_at if cost metadata didn't work
if metadata.CreatedAt.IsZero() {
metadata.CreatedAt = progress.LastUpdated
}
metadata.StartedAt = metadata.CreatedAt
// Determine completion
if progress.TotalSteps > 0 && len(progress.CompletedStepIndices) >= progress.TotalSteps {
completedAt := progress.LastUpdated
metadata.Status = "completed"
metadata.CompletedAt = &completedAt
durationMs := completedAt.Sub(metadata.StartedAt).Milliseconds()
metadata.DurationMs = &durationMs
}
return metadata
}
func writeRunMetadata(ctx context.Context, metadataFilePath string, metadata *RunMetadata) error {
data, err := json.MarshalIndent(metadata, "", " ")
if err != nil {
return fmt.Errorf("failed to marshal run metadata: %w", err)
}
return writeFileToWorkspace(ctx, metadataFilePath, string(data))
}
func readProgressForFolder(ctx context.Context, stepsFilePath string) (*StepProgress, error) {
// Use the generic file reading helper
content, exists, err := readFileFromWorkspace(ctx, stepsFilePath)
if err != nil {
return nil, err
}
if !exists {
return nil, nil // File doesn't exist, not an error
}
// Parse the JSON content
var progress StepProgress
if err := json.Unmarshal([]byte(content), &progress); err != nil {
// If unable to parse JSON (e.g., merge conflicts, corrupted file), return nil (empty progress)
// This allows the API to continue working even if the file is corrupted
return nil, nil
}
return &progress, nil
}
// extractIterationFoldersFromTypedChildren extracts iteration folder names from typed WorkspaceFolderItem array
// Supports both top-level (iteration-X) and nested (iteration-X/group-Y) folders
func extractIterationFoldersFromTypedChildren(children []virtualtools.WorkspaceFolderItem, existingFolders []string) []string {
for _, child := range children {
// Check type field using typed struct
isDir := child.Type == "folder"
// Get name from FilePath field
name := ""
if child.FilePath != "" {
// Extract relative path from runs folder (e.g., "Workflow/HDFC Personal Accounts/runs/iteration-3/group-1" -> "iteration-3/group-1")
// Find "runs/" in the path and extract everything after it
runsIndex := strings.Index(child.FilePath, "/runs/")
if runsIndex >= 0 {
relativePath := child.FilePath[runsIndex+6:] // Skip "/runs/"
name = relativePath
} else {
// Fallback: extract last part
parts := strings.Split(child.FilePath, "/")
if len(parts) > 0 {
name = parts[len(parts)-1]
}
}
}
if isDir && name != "" {
// Include iteration folders (both top-level and nested)
// Top-level: iteration-X
// Nested: iteration-X/group-Y
if strings.HasPrefix(name, "iteration-") {
// If this is a top-level iteration folder, check for nested group folders first
if !strings.Contains(name, "/") {
if len(child.Children) > 0 {
// Check if this iteration has group subfolders
hasGroups := false
groupFolders := []string{}
for _, groupChild := range child.Children {
if groupChild.Type == "folder" {
groupName := ""
if groupChild.FilePath != "" {
// Extract relative path
runsIndex := strings.Index(groupChild.FilePath, "/runs/")
if runsIndex >= 0 {
groupName = groupChild.FilePath[runsIndex+6:]
} else {
parts := strings.Split(groupChild.FilePath, "/")
if len(parts) > 0 {
groupName = parts[len(parts)-1]
}
}
}
// Check if this is a group subfolder (nested under iteration-X)
// Accepts both "group-X" format (backward compatibility) and display names (e.g., "production", "staging")
if groupName != "" && strings.HasPrefix(groupName, name+"/") {
// Any nested folder under iteration-X is considered a group folder
hasGroups = true
groupFolders = append(groupFolders, groupName)
}
}
}
// If iteration has group subfolders, only add the groups (not the parent)
if hasGroups {
existingFolders = append(existingFolders, groupFolders...)
} else {
// No groups found, add the parent iteration folder (backward compatibility)
existingFolders = append(existingFolders, name)
}
} else {
// No children, add the parent iteration folder
existingFolders = append(existingFolders, name)
}
} else {
// Nested folder (already a group folder) - add it directly
existingFolders = append(existingFolders, name)
}
}
}
}
return existingFolders
}
// extractIterationFoldersFromInterfaceArray extracts from array of interface{} (backward compatibility)
func extractIterationFoldersFromInterfaceArray(dataArray []interface{}, existingFolders []string) []string {
for _, elem := range dataArray {
if elemMap, ok := elem.(map[string]interface{}); ok {
// Check if this element has children (the iteration folders)
if children, ok := elemMap["children"].([]interface{}); ok {
existingFolders = extractIterationFoldersFromChildren(children, existingFolders)
}
}
}
return existingFolders
}
// extractIterationFoldersFromChildren extracts iteration folder names from children array (interface{} version for backward compatibility)
// Supports both top-level (iteration-X) and nested (iteration-X/group-Y or iteration-X/display-name) folders
func extractIterationFoldersFromChildren(children []interface{}, existingFolders []string) []string {
for _, child := range children {
if childMap, ok := child.(map[string]interface{}); ok {
// Check type field
isDir := false
if t, ok := childMap["type"].(string); ok {
isDir = (t == "folder")
}
// Get name from filepath or name field
name := ""
if filepath, ok := childMap["filepath"].(string); ok {
// Extract relative path from runs folder (e.g., "Workflow/HDFC Personal Accounts/runs/iteration-3/group-1" -> "iteration-3/group-1")
runsIndex := strings.Index(filepath, "/runs/")
if runsIndex >= 0 {
relativePath := filepath[runsIndex+6:] // Skip "/runs/"
name = relativePath
} else {
// Fallback: extract last part
parts := strings.Split(filepath, "/")
if len(parts) > 0 {
name = parts[len(parts)-1]
}
}
} else if n, ok := childMap["name"].(string); ok {
name = n
}
if isDir && name != "" {
// Include iteration folders (both top-level and nested)
if strings.HasPrefix(name, "iteration-") {
// If this is a top-level iteration folder, check for nested group folders first
if !strings.Contains(name, "/") {
childrenArray, hasChildren := childMap["children"].([]interface{})
if hasChildren && len(childrenArray) > 0 {
// Check if this iteration has group subfolders
hasGroups := false
groupFolders := []string{}
for _, groupChild := range childrenArray {
if groupMap, ok := groupChild.(map[string]interface{}); ok {
groupIsDir := false
if t, ok := groupMap["type"].(string); ok {
groupIsDir = (t == "folder")
}
if groupIsDir {
groupName := ""
if groupFilePath, ok := groupMap["filepath"].(string); ok {
runsIndex := strings.Index(groupFilePath, "/runs/")
if runsIndex >= 0 {
groupName = groupFilePath[runsIndex+6:]
} else {
parts := strings.Split(groupFilePath, "/")
if len(parts) > 0 {
groupName = parts[len(parts)-1]
}
}
} else if n, ok := groupMap["name"].(string); ok {
groupName = n
}
// Check if this is a group subfolder (nested under iteration-X)
// Accepts both "group-X" format (backward compatibility) and display names (e.g., "production", "staging")
if groupName != "" && strings.HasPrefix(groupName, name+"/") {
// Any nested folder under iteration-X is considered a group folder
hasGroups = true
groupFolders = append(groupFolders, groupName)
}
}
}
}
// If iteration has group subfolders, only add the groups (not the parent)
if hasGroups {
existingFolders = append(existingFolders, groupFolders...)
} else {
// No groups found, add the parent iteration folder (backward compatibility)
existingFolders = append(existingFolders, name)
}
} else {
// No children or empty children, add the parent iteration folder
existingFolders = append(existingFolders, name)
}
} else {
// Nested folder (already a group folder) - add it directly
existingFolders = append(existingFolders, name)
}
}
}
}
}
return existingFolders
}
// ActiveWorkflowExecution is the backend half of the workflow/chat decoupling:
// workflow UI state lives here instead of being mirrored into chat session metadata.
type ActiveWorkflowExecution struct {
QueryID string `json:"query_id"`
SessionID string `json:"session_id"`
Kind string `json:"kind,omitempty"`
PresetQueryID string `json:"preset_query_id,omitempty"`
PresetName string `json:"preset_name,omitempty"`
WorkspacePath string `json:"workspace_path"`
RunFolder string `json:"run_folder,omitempty"`
PhaseID string `json:"phase_id,omitempty"`
PhaseName string `json:"phase_name,omitempty"`
Status string `json:"status,omitempty"` // "running", "completed", "failed"
UserID string `json:"user_id,omitempty"`
Title string `json:"title,omitempty"`
Query string `json:"query,omitempty"`
TriggeredBy string `json:"triggered_by"` // "manual", "cron", "workflow_builder", "workflow_phase"
StartedAt time.Time `json:"started_at"`
// Minimization state — frontend sets this when user minimizes a running workflow.
IsMinimized bool `json:"is_minimized,omitempty"`
MinimizedAt int64 `json:"minimized_at,omitempty"` // unix ms
CurrentStepID string `json:"current_step_id,omitempty"`
CurrentStepTitle string `json:"current_step_title,omitempty"`
// Blocking-input state — set by the list endpoint via deriveSessionUserInputState.
NeedsUserInput bool `json:"needs_user_input,omitempty"`
WaitingMessage string `json:"waiting_message,omitempty"`
WaitingSince *time.Time `json:"waiting_since,omitempty"`
RuntimeState *RuntimeSnapshot `json:"runtime_state,omitempty"`
// DisplayStatus is the same collapsed busy/idle/stopped read ActiveSessionInfo
// ships (sessionDisplayStatusFromRuntime(RuntimeState).Status), computed here
// too so a caller never has to re-derive it from RuntimeState.Phase itself —
// see PLAT-095.
DisplayStatus string `json:"display_status,omitempty"`
}
// RunMetadataLLM captures which model was used for a specific role
type RunMetadataLLM struct {
Provider string `json:"provider,omitempty"`
ModelID string `json:"model_id,omitempty"`
}
// RunMetadataModels captures the LLM configuration used for the run
type RunMetadataModels struct {
AllocationMode string `json:"allocation_mode,omitempty"`
ExecutionLLM *RunMetadataLLM `json:"execution_llm,omitempty"`
BuilderLLM *RunMetadataLLM `json:"builder_llm,omitempty"`
Tier1 *RunMetadataLLM `json:"tier_1,omitempty"`
Tier2 *RunMetadataLLM `json:"tier_2,omitempty"`
Tier3 *RunMetadataLLM `json:"tier_3,omitempty"`
TempOverride *RunMetadataLLM `json:"temp_override,omitempty"`
TempOverride2 *RunMetadataLLM `json:"temp_override_2,omitempty"`
}
// RunMetadata stores lifecycle information for a run folder
type RunMetadata struct {
CreatedAt time.Time `json:"created_at"`
StartedAt time.Time `json:"started_at,omitempty"`
CompletedAt *time.Time `json:"completed_at,omitempty"`
DurationMs *int64 `json:"duration_ms,omitempty"`
Status string `json:"status"` // "running", "completed", "failed", "canceled"
TriggeredBy string `json:"triggered_by,omitempty"` // "manual", "cron", "workflow_builder"
Models *RunMetadataModels `json:"models,omitempty"` // LLM config used for this run
}
// RunFolderInfo represents information about a single run folder
type RunFolderInfo struct {
Name string `json:"name"`
Progress *StepProgress `json:"progress,omitempty"` // Progress info if available
Metadata *RunMetadata `json:"metadata,omitempty"` // Lifecycle metadata
}
// RunFoldersResponse represents the response for listing run folders
type RunFoldersResponse struct {
Folders []RunFolderInfo `json:"folders"` // Changed from []string to []RunFolderInfo
TotalCount int `json:"total_count"`
ShowingCount int `json:"showing_count"`
}
// StepProgress represents the progress of workflow execution
type StepProgress struct {
CompletedStepIndices []int `json:"completed_step_indices"`
TotalSteps int `json:"total_steps"`
LastUpdated time.Time `json:"last_updated"`
}
// ExecutionOptions represents user-selected execution options from frontend
type ExecutionOptions struct {
RunMode string `json:"run_mode"` // "use_same_run" or "create_new_runs_always"
SelectedRunFolder string `json:"selected_run_folder,omitempty"` // If use_same_run and user selected specific folder
ExecutionStrategy string `json:"execution_strategy"` // "start_from_beginning", etc.
ResumeFromStep int `json:"resume_from_step,omitempty"` // 1-based step number to resume from
PlanChangeAction string `json:"plan_change_action,omitempty"` // "keep_old_progress" or "delete_old_progress"
// Variable group execution options (for batch execution with multiple groups)
EnabledGroupNames []string `json:"enabled_group_names,omitempty"` // Group names to execute (if empty, uses groups' enabled flags)
// Logging options
SaveValidationResponses bool `json:"save_validation_responses,omitempty"` // If true, save validation responses and execution logs to workspace (default: true)
// Deterministic routing overrides: routing step ID -> route_id or unique next_step_id.
RouteSelections map[string]string `json:"route_selections,omitempty"`
// Workshop mode override (builder/optimizer/runner) — sent from frontend toggle
WorkshopMode string `json:"workshop_mode,omitempty"`
}
// AgentLLMConfig represents LLM configuration for an agent (matches controller type)
type AgentLLMConfig struct {
PublishedLLMID string `json:"published_llm_id,omitempty"`
Provider string `json:"provider,omitempty"` // e.g., "openai", "bedrock", "vertex", "anthropic"
ModelID string `json:"model_id,omitempty"` // e.g., "gpt-4o", "claude-3-5-sonnet-20241022"
Options map[string]interface{} `json:"options,omitempty"`
}
// WorkflowRequest represents a workflow creation request
type WorkflowRequest struct {
PresetQueryID string `json:"preset_query_id"`
HumanVerificationRequired bool `json:"human_verification_required"`
}
// WorkflowUpdateRequest represents a workflow update request
type WorkflowUpdateRequest struct {
PresetQueryID string `json:"preset_query_id"`
WorkflowStatus *string `json:"workflow_status,omitempty"`
SelectedOptions *workflowtypes.WorkflowSelectedOptions `json:"selected_options,omitempty"`
StepID *string `json:"step_id,omitempty"` // Optional step ID for step-specific phase execution
}
// --- In-memory workflow runtime state (replaces DB workflows table) ---
// WorkflowRuntimeState holds ephemeral execution state for a workflow.
// This replaces the DB-backed workflows table. State doesn't survive server restarts
// (which is fine — workflow_status is only meaningful during active execution).
type WorkflowRuntimeState struct {
ID string `json:"id"`
PresetQueryID string `json:"preset_query_id"`
WorkflowStatus string `json:"workflow_status"`
SelectedOptions *workflowtypes.WorkflowSelectedOptions `json:"selected_options,omitempty"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
}
// workflowRuntimeStore is the in-memory store for workflow execution state.
// Key: preset_query_id → WorkflowRuntimeState
var workflowRuntimeStore = struct {
sync.RWMutex
m map[string]*WorkflowRuntimeState
}{m: make(map[string]*WorkflowRuntimeState)}
func getWorkflowRuntime(presetQueryID string) *WorkflowRuntimeState {
workflowRuntimeStore.RLock()
defer workflowRuntimeStore.RUnlock()
return workflowRuntimeStore.m[presetQueryID]
}
func setWorkflowRuntime(state *WorkflowRuntimeState) {
workflowRuntimeStore.Lock()
defer workflowRuntimeStore.Unlock()
workflowRuntimeStore.m[state.PresetQueryID] = state
}
func deleteWorkflowRuntime(presetQueryID string) {
workflowRuntimeStore.Lock()
defer workflowRuntimeStore.Unlock()
delete(workflowRuntimeStore.m, presetQueryID)
}
// handleCreateWorkflow handles workflow creation (in-memory runtime state).
func (api *StreamingAPI) handleCreateWorkflow(w http.ResponseWriter, r *http.Request) {
setCORS(w)
if r.Method == "OPTIONS" {
w.WriteHeader(http.StatusOK)
return
}
var req WorkflowRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
http.Error(w, fmt.Sprintf("Invalid request body: %v", err), http.StatusBadRequest)
return
}
if req.PresetQueryID == "" {
http.Error(w, "preset_query_id is required", http.StatusBadRequest)
return
}
// Check if already exists in memory
if existing := getWorkflowRuntime(req.PresetQueryID); existing != nil {
http.Error(w, "Workflow already exists for this preset query ID. Use update endpoint instead.", http.StatusConflict)
return
}
status := workflowtypes.WorkflowStatusPreVerification
if !req.HumanVerificationRequired {
status = workflowtypes.WorkflowStatusPostVerification
}
now := time.Now()
state := &WorkflowRuntimeState{
ID: fmt.Sprintf("wfrt_%d", now.UnixNano()),
PresetQueryID: req.PresetQueryID,
WorkflowStatus: status,
CreatedAt: now,
UpdatedAt: now,
}
setWorkflowRuntime(state)
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(map[string]interface{}{
"success": true,
"workflow": map[string]interface{}{
"id": state.ID,
"preset_query_id": state.PresetQueryID,
"workflow_status": state.WorkflowStatus,
"created_at": state.CreatedAt,
},
"message": "Workflow created successfully",
})
}
// handleGetWorkflowStatus handles getting workflow status (in-memory runtime state).
func (api *StreamingAPI) handleGetWorkflowStatus(w http.ResponseWriter, r *http.Request) {
setCORS(w)
if r.Method == "OPTIONS" {
w.WriteHeader(http.StatusOK)
return
}
presetQueryID := r.URL.Query().Get("preset_query_id")
if presetQueryID == "" {
http.Error(w, "preset_query_id parameter is required", http.StatusBadRequest)
return
}
state := getWorkflowRuntime(presetQueryID)
if state == nil {
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(map[string]interface{}{
"success": true,
"exists": false,
"message": "No workflow exists for this preset",
})
return
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(map[string]interface{}{
"success": true,
"exists": true,
"workflow": map[string]interface{}{
"id": state.ID,
"preset_query_id": state.PresetQueryID,
"workflow_status": state.WorkflowStatus,
"selected_options": state.SelectedOptions,
"created_at": state.CreatedAt,
"updated_at": state.UpdatedAt,
},
"status": map[string]interface{}{
"is_ready": state.WorkflowStatus == workflowtypes.WorkflowStatusPostVerification,
"requires_verification": state.WorkflowStatus == workflowtypes.WorkflowStatusPreVerification,
"can_execute": state.WorkflowStatus == workflowtypes.WorkflowStatusPostVerification,
},
})
}
// handleUpdateWorkflow handles workflow updates (in-memory runtime state).
func (api *StreamingAPI) handleUpdateWorkflow(w http.ResponseWriter, r *http.Request) {
setCORS(w)
if r.Method == "OPTIONS" {
w.WriteHeader(http.StatusOK)
return
}
var req WorkflowUpdateRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
http.Error(w, fmt.Sprintf("Invalid request body: %v", err), http.StatusBadRequest)
return
}
if req.PresetQueryID == "" {
http.Error(w, "preset_query_id is required", http.StatusBadRequest)
return
}
if req.WorkflowStatus == nil && req.SelectedOptions == nil {
http.Error(w, "at least one field (workflow_status or selected_options) must be provided", http.StatusBadRequest)
return
}
// Store step_id for execution
if req.StepID != nil && *req.StepID != "" {
api.workflowStepIDMux.Lock()
if api.workflowStepIDs == nil {
api.workflowStepIDs = make(map[string]string)
}
api.workflowStepIDs[req.PresetQueryID] = *req.StepID
api.workflowStepIDMux.Unlock()
}
// Get or create in-memory state (upsert)
state := getWorkflowRuntime(req.PresetQueryID)
if state == nil {
state = &WorkflowRuntimeState{
ID: fmt.Sprintf("wfrt_%d", time.Now().UnixNano()),
PresetQueryID: req.PresetQueryID,
WorkflowStatus: workflowtypes.WorkflowStatusPreVerification,
CreatedAt: time.Now(),
}
}
if req.WorkflowStatus != nil {
state.WorkflowStatus = *req.WorkflowStatus
}
if req.SelectedOptions != nil {
state.SelectedOptions = req.SelectedOptions
}
state.UpdatedAt = time.Now()
setWorkflowRuntime(state)
workflowResponse := map[string]interface{}{
"id": state.ID,
"preset_query_id": state.PresetQueryID,
"workflow_status": state.WorkflowStatus,
"created_at": state.CreatedAt,
"updated_at": state.UpdatedAt,
}
if state.SelectedOptions != nil {
workflowResponse["selected_options"] = state.SelectedOptions
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(map[string]interface{}{
"success": true,
"workflow": workflowResponse,
"message": "Workflow updated successfully",
})
}
// handleGetRunFolders handles listing available run folders for a workspace
func (api *StreamingAPI) handleGetRunFolders(w http.ResponseWriter, r *http.Request) {
// Enable CORS
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Methods", "GET, OPTIONS")
w.Header().Set("Access-Control-Allow-Headers", "Content-Type")
if r.Method == "OPTIONS" {
w.WriteHeader(http.StatusOK)
return
}
if r.Method != "GET" {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
workspacePath := r.URL.Query().Get("workspace_path")
if workspacePath == "" {
http.Error(w, "workspace_path parameter is required", http.StatusBadRequest)
return
}
// Build path to runs folder
runsPath := workspacePath + "/runs"
// List folders from workspace API
apiURL := getWorkspaceAPIURL() + "/api/documents"
req, err := http.NewRequestWithContext(r.Context(), "GET", apiURL, nil)
if err != nil {
http.Error(w, fmt.Sprintf("Failed to create request: %v", err), http.StatusInternalServerError)
return
}
// Add query parameters
// Use max_depth=2 to list nested folders (iteration-X/group-Y)
q := req.URL.Query()
q.Add("folder", runsPath)
q.Add("max_depth", "2")
req.URL.RawQuery = q.Encode()
resp, err := workspaceHTTPClient.Do(req)
if err != nil {
http.Error(w, fmt.Sprintf("Failed to call workspace API: %v", err), http.StatusInternalServerError)
return
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
http.Error(w, fmt.Sprintf("Failed to read response: %v", err), http.StatusInternalServerError)
return
}
// Check if runs folder doesn't exist (404)
if resp.StatusCode == http.StatusNotFound {
// No runs folder - return empty list
response := RunFoldersResponse{
Folders: []RunFolderInfo{},
TotalCount: 0,
ShowingCount: 0,
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(response)
return
}