-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtaskflow_handler.go
More file actions
409 lines (387 loc) · 14.3 KB
/
Copy pathtaskflow_handler.go
File metadata and controls
409 lines (387 loc) · 14.3 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
// taskflow_handler.go — FASE 4/5: HTTP API Category Task.
//
// Trigger + CRUD kategori/crew + run history (timeline). Definisi task di
// flowork.db (owner-level), di-edit dari GUI tab "Tasks". Run jalan ASYNC
// (background) + step di-persist live → GUI poll run-detail buat timeline.
//
// POST /api/taskflow/run?category=saham&subject=BBCA → start run (async), balik run_id
// ?solo=1 → baseline A/B (sync, 1 agent)
// GET /api/taskflow/categories → list kategori
// GET /api/taskflow/category?id=saham → 1 kategori + crew
// POST /api/taskflow/category → upsert kategori + crew (JSON)
// POST /api/taskflow/category/delete?id=saham → hapus kategori
// GET /api/taskflow/runs?category=saham[&limit=N] → run history
// GET /api/taskflow/run-detail?id=123 → 1 run + steps (timeline)
package main
import (
"context"
"encoding/json"
"fmt"
"io"
"log"
"net/http"
"net/url"
"strconv"
"strings"
"time"
"flowork-gui/internal/floworkdb"
"flowork-gui/internal/kernelhost"
"flowork-gui/internal/taskflow"
)
// notifyTelegram — kirim teks ke chat Telegram pakai bot token Mr.Flow (dibaca
// dari secrets state.db-nya). Best-effort: gagal = silent (cuma log). Dipakai
// Fase 6c buat ngirim hasil task balik ke chat yang men-trigger.
// notifyTelegram — kirim hasil task ke chat Telegram (token Mr.Flow). LOGGED di
// tiap titik gagal — anti GHOSTING silent (kalau ga nyampe, ketauan di log,
// bukan diem-diem ilang).
func notifyTelegram(host *kernelhost.Host, chatID, text string) {
if strings.TrimSpace(chatID) == "" {
log.Printf("[notify] SKIP — chat_id kosong (task ga di-trigger dari Telegram?)")
return
}
store, err := host.OpenAgentStore("mr-flow")
if err != nil {
log.Printf("[notify] GAGAL buka store mr-flow: %v", err)
return
}
defer store.Close()
secrets, err := store.Secrets()
if err != nil {
log.Printf("[notify] GAGAL baca secrets: %v", err)
return
}
token := strings.TrimSpace(secrets["TELEGRAM_BOT_TOKEN"])
if token == "" {
log.Printf("[notify] GAGAL — TELEGRAM_BOT_TOKEN kosong di mr-flow")
return
}
if len(text) > 4000 {
text = text[:4000] + "\n…(dipotong)"
}
form := url.Values{}
form.Set("chat_id", chatID)
form.Set("text", text)
req, _ := http.NewRequest(http.MethodPost,
"https://api.telegram.org/bot"+token+"/sendMessage",
strings.NewReader(form.Encode()))
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
req.Header.Set("User-Agent", "Flowork-Agent/1.0")
resp, derr := (&http.Client{Timeout: 15 * time.Second}).Do(req)
if derr != nil {
log.Printf("[notify] GAGAL kirim ke Telegram (chat=%s): %v", chatID, derr)
return
}
defer resp.Body.Close()
body, _ := io.ReadAll(io.LimitReader(resp.Body, 4096))
if resp.StatusCode == 200 {
log.Printf("[notify] ✓ TERKIRIM ke chat %s (telegram ok)", chatID)
} else {
log.Printf("[notify] DITOLAK telegram (chat=%s, http=%d): %s", chatID, resp.StatusCode, string(body))
}
}
// dbRecorder — implement taskflow.Recorder, persist step ke flowork.db (timeline).
type dbRecorder struct {
store *floworkdb.Store
runID int64
}
func (r *dbRecorder) StartStep(agentID, role string, idx int) int64 {
id, _ := r.store.StartStep(r.runID, agentID, role, idx)
return id
}
func (r *dbRecorder) FinishStep(stepID int64, status, outputRef, errStr string, ms int64) {
_ = r.store.FinishStep(stepID, status, outputRef, errStr, ms)
}
func tfWriteJSON(w http.ResponseWriter, code int, body any) {
w.Header().Set("Content-Type", "application/json")
if code != 0 {
w.WriteHeader(code)
}
_ = json.NewEncoder(w).Encode(body)
}
// toTaskflowCategory — map floworkdb.TaskCategory → taskflow.Category.
func toTaskflowCategory(c *floworkdb.TaskCategory) taskflow.Category {
tc := taskflow.Category{ID: c.ID, Name: c.Name, Synthesizer: c.Synthesizer, SynthDirective: c.SynthDirective, WorkerDirective: c.WorkerDirective}
for _, a := range c.Crew {
tc.Crew = append(tc.Crew, taskflow.CrewMember{AgentID: a.AgentID, RoleLabel: a.RoleLabel})
}
return tc
}
// taskflowRunHandler — POST trigger. Normal = async (timeline). solo = sync (A/B).
func taskflowRunHandler(host *kernelhost.Host, store *floworkdb.Store) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
tfWriteJSON(w, http.StatusMethodNotAllowed, map[string]any{"error": "POST only"})
return
}
category := strings.TrimSpace(r.URL.Query().Get("category"))
subject := strings.TrimSpace(r.URL.Query().Get("subject"))
if category == "" || subject == "" {
tfWriteJSON(w, http.StatusBadRequest, map[string]any{"error": "category + subject required"})
return
}
// ?solo=1 → BASELINE A/B (sync): 1 agent (analis pertama) ngerjain semua.
if r.URL.Query().Get("solo") == "1" {
cat, _ := store.GetCategory(category)
agentID := "saham-fundamental"
if cat != nil && len(cat.Crew) > 0 {
agentID = cat.Crew[0].AgentID
}
ctx, cancel := context.WithTimeout(context.Background(), 12*time.Minute)
defer cancel()
reply, ms := taskflow.RunSolo(ctx, host, agentID, subject)
tfWriteJSON(w, 0, map[string]any{"mode": "solo", "agent": agentID, "ms": ms, "reply": reply})
return
}
notify := strings.TrimSpace(r.URL.Query().Get("notify")) // chat_id Telegram (opsional)
runID, err := startTaskflowRun(host, store, category, subject, notify)
if err != nil {
tfWriteJSON(w, http.StatusBadRequest, map[string]any{"error": err.Error()})
return
}
tfWriteJSON(w, 0, map[string]any{
"run_id": runID, "status": "running",
"poll": "/api/taskflow/run-detail?id=" + strconv.FormatInt(runID, 10),
})
}
}
// startTaskflowRun — bikin run + jalanin Category Task ASYNC (goroutine) +
// notify Telegram pas kelar. Reusable: dipake HTTP handler + scheduler ticker.
// Balik run_id cepet (run jalan di belakang). Error = validasi gagal.
func startTaskflowRun(host *kernelhost.Host, store *floworkdb.Store, category, subject, notify string) (int64, error) {
cat, err := store.GetCategory(category)
if err != nil {
return 0, err
}
if cat == nil {
return 0, fmt.Errorf("kategori ga ada: %s", category)
}
if len(cat.Crew) == 0 {
return 0, fmt.Errorf("crew kosong — tambah analis dulu")
}
runID, err := store.CreateRun(category, subject, "owner", notify)
if err != nil {
return 0, fmt.Errorf("create run: %w", err)
}
tfCat := toTaskflowCategory(cat)
catName := cat.Name
go func() {
// recover: panic di task (worker/synth) JANGAN crash seluruh binary —
// tandain run error + log. (Section scanner: bare_goroutine_auditor.)
defer func() {
if r := recover(); r != nil {
log.Printf("[taskflow] run #%d PANIC: %v", runID, r)
_ = store.FinishRun(runID, "error", fmt.Sprintf("panic: %v", r))
}
}()
// 30 menit: crew bisa sampe 6 agent × cap 300s/agent (kernelhost). Budget
// total mesti muat worst-case, walau rata-rata agent ~120s. Cap, bukan wait.
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Minute)
defer cancel()
rec := &dbRecorder{store: store, runID: runID}
res := taskflow.RunCategoryTask(ctx, host, host.SharedDir, tfCat, subject, strconv.FormatInt(runID, 10), rec)
status := "done"
summary := res.Recommendation
if res.Err != "" {
status = "error"
if summary == "" {
summary = res.Err
}
}
_ = store.FinishRun(runID, status, summary)
notifTo := notify
if notifTo == "" {
notifTo = "NONE"
}
log.Printf("[taskflow] run #%d %s — notify=%s", runID, status, notifTo)
if notify != "" {
head := fmt.Sprintf("✅ Hasil %s — %s (run #%d):\n\n", catName, subject, runID)
if status == "error" {
head = fmt.Sprintf("⚠️ %s — %s (run #%d) gagal:\n\n", catName, subject, runID)
}
notifyTelegram(host, notify, head+summary)
}
}()
return runID, nil
}
// ── Scheduler (looping recurring task) ───────────────────────────────────────
// taskflowSchedulesHandler — GET list jadwal.
func taskflowSchedulesHandler(store *floworkdb.Store) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
list, err := store.ListSchedules()
if err != nil {
tfWriteJSON(w, http.StatusInternalServerError, map[string]any{"error": err.Error()})
return
}
tfWriteJSON(w, 0, map[string]any{"schedules": list})
}
}
// taskflowScheduleAddHandler — POST bikin jadwal (JSON body).
func taskflowScheduleAddHandler(store *floworkdb.Store) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
tfWriteJSON(w, http.StatusMethodNotAllowed, map[string]any{"error": "POST only"})
return
}
var sc floworkdb.TaskSchedule
if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, 1<<16)).Decode(&sc); err != nil {
tfWriteJSON(w, http.StatusBadRequest, map[string]any{"error": "invalid body"})
return
}
sc.Category = strings.TrimSpace(sc.Category)
sc.Subject = strings.TrimSpace(sc.Subject)
if sc.Category == "" || sc.Subject == "" {
tfWriteJSON(w, http.StatusBadRequest, map[string]any{"error": "category + subject required"})
return
}
id, err := store.AddSchedule(sc)
if err != nil {
tfWriteJSON(w, http.StatusInternalServerError, map[string]any{"error": err.Error()})
return
}
tfWriteJSON(w, 0, map[string]any{"ok": true, "id": id})
}
}
// taskflowScheduleDeleteHandler — POST hapus jadwal.
func taskflowScheduleDeleteHandler(store *floworkdb.Store) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
id, _ := strconv.ParseInt(r.URL.Query().Get("id"), 10, 64)
if id <= 0 {
tfWriteJSON(w, http.StatusBadRequest, map[string]any{"error": "id required"})
return
}
if r.URL.Query().Get("enabled") != "" {
_ = store.ToggleSchedule(id, r.URL.Query().Get("enabled") == "1")
} else {
_ = store.DeleteSchedule(id)
}
tfWriteJSON(w, 0, map[string]any{"ok": true})
}
}
// RunDueSchedules — dipanggil ticker tiap menit: fire jadwal yang udah waktunya.
func RunDueSchedules(host *kernelhost.Host, store *floworkdb.Store) int {
now := time.Now()
due, err := store.DueSchedules(now)
if err != nil {
return 0
}
fired := 0
for _, sc := range due {
if _, err := startTaskflowRun(host, store, sc.Category, sc.Subject, sc.NotifyChat); err == nil {
fired++
}
_ = store.MarkScheduleFired(sc, now) // tetep advance next_run walau gagal (anti spam)
}
return fired
}
// taskflowCategoriesHandler — GET list kategori.
func taskflowCategoriesHandler(store *floworkdb.Store) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
cats, err := store.ListCategories()
if err != nil {
tfWriteJSON(w, http.StatusInternalServerError, map[string]any{"error": err.Error()})
return
}
tfWriteJSON(w, 0, map[string]any{"categories": cats})
}
}
// taskflowCategoryHandler — GET (detail+crew) / POST (upsert+crew).
func taskflowCategoryHandler(store *floworkdb.Store) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
switch r.Method {
case http.MethodGet:
id := strings.TrimSpace(r.URL.Query().Get("id"))
if id == "" {
tfWriteJSON(w, http.StatusBadRequest, map[string]any{"error": "id required"})
return
}
cat, err := store.GetCategory(id)
if err != nil {
tfWriteJSON(w, http.StatusInternalServerError, map[string]any{"error": err.Error()})
return
}
if cat == nil {
tfWriteJSON(w, http.StatusNotFound, map[string]any{"error": "ga ada"})
return
}
tfWriteJSON(w, 0, cat)
case http.MethodPost:
var body floworkdb.TaskCategory
if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, 1<<16)).Decode(&body); err != nil {
tfWriteJSON(w, http.StatusBadRequest, map[string]any{"error": "invalid body"})
return
}
body.ID = strings.TrimSpace(body.ID)
if body.ID == "" {
tfWriteJSON(w, http.StatusBadRequest, map[string]any{"error": "id required"})
return
}
if err := store.UpsertCategory(body); err != nil {
tfWriteJSON(w, http.StatusInternalServerError, map[string]any{"error": err.Error()})
return
}
if err := store.SetCrew(body.ID, body.Crew); err != nil {
tfWriteJSON(w, http.StatusInternalServerError, map[string]any{"error": err.Error()})
return
}
tfWriteJSON(w, 0, map[string]any{"ok": true, "id": body.ID})
default:
tfWriteJSON(w, http.StatusMethodNotAllowed, map[string]any{"error": "GET/POST only"})
}
}
}
// taskflowCategoryDeleteHandler — POST hapus kategori.
func taskflowCategoryDeleteHandler(store *floworkdb.Store) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
tfWriteJSON(w, http.StatusMethodNotAllowed, map[string]any{"error": "POST only"})
return
}
id := strings.TrimSpace(r.URL.Query().Get("id"))
if id == "" {
tfWriteJSON(w, http.StatusBadRequest, map[string]any{"error": "id required"})
return
}
if err := store.DeleteCategory(id); err != nil {
tfWriteJSON(w, http.StatusInternalServerError, map[string]any{"error": err.Error()})
return
}
tfWriteJSON(w, 0, map[string]any{"ok": true})
}
}
// taskflowRunsHandler — GET run history 1 kategori.
func taskflowRunsHandler(store *floworkdb.Store) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
category := strings.TrimSpace(r.URL.Query().Get("category"))
if category == "" {
tfWriteJSON(w, http.StatusBadRequest, map[string]any{"error": "category required"})
return
}
limit, _ := strconv.Atoi(r.URL.Query().Get("limit"))
runs, err := store.ListRuns(category, limit)
if err != nil {
tfWriteJSON(w, http.StatusInternalServerError, map[string]any{"error": err.Error()})
return
}
tfWriteJSON(w, 0, map[string]any{"runs": runs})
}
}
// taskflowRunDetailHandler — GET 1 run + steps (timeline).
func taskflowRunDetailHandler(store *floworkdb.Store) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
id, _ := strconv.ParseInt(r.URL.Query().Get("id"), 10, 64)
if id <= 0 {
tfWriteJSON(w, http.StatusBadRequest, map[string]any{"error": "id required"})
return
}
run, err := store.GetRun(id)
if err != nil {
tfWriteJSON(w, http.StatusInternalServerError, map[string]any{"error": err.Error()})
return
}
if run == nil {
tfWriteJSON(w, http.StatusNotFound, map[string]any{"error": "run ga ada"})
return
}
tfWriteJSON(w, 0, run)
}
}