Repository navigation
Expand file tree
/
Copy pathserver.js
More file actions
1837 lines (1603 loc) · 69.3 KB
/
Copy pathserver.js
File metadata and controls
1837 lines (1603 loc) · 69.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
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
#!/usr/bin/env node
/**
* AgentFlow — Full-Stack Local Server
* Node.js + Express + SQLite + WebSocket
*
* Usage:
* npm install
* npm start # → http://localhost:3000
* PORT=8080 npm start # custom port
*/
const express = require('express');
const Database = require('better-sqlite3');
const { WebSocketServer } = require('ws');
const cors = require('cors');
const { v4: uuidv4 } = require('uuid');
const path = require('path');
const http = require('http');
const fs = require('fs');
const { execSync } = require('child_process');
const os = require('os');
// ─── Config ───────────────────────────────────────────
const PORT = parseInt(process.env.PORT || '3000', 10);
// DB goes in a data/ subdirectory (created if needed) to keep things clean
const DATA_DIR = process.env.DATA_DIR || path.join(__dirname, 'data');
if (!fs.existsSync(DATA_DIR)) fs.mkdirSync(DATA_DIR, { recursive: true });
const DB_PATH = process.env.DB_PATH || path.join(DATA_DIR, 'agentflow.db');
const isDev = process.argv.includes('--dev');
// ─── Discovery Config ────────────────────────────────
const DISCOVERY_INTERVAL_MS = parseInt(process.env.DISCOVERY_INTERVAL || '30000', 10); // 30s default
const OPENCLAW_HOST = process.env.OPENCLAW_HOST || 'http://127.0.0.1:18789';
const OPENCLAW_TOKEN = process.env.OPENCLAW_TOKEN || ''; // from gateway.auth.token
const CLAUDE_SESSIONS_DIR = process.env.CLAUDE_SESSIONS_DIR ||
path.join(os.homedir(), '.claude', 'projects');
// ─── Auth Config ──────────────────────────────────────
const AGENTFLOW_TOKEN = process.env.AGENTFLOW_TOKEN || null;
// ─── Helper Functions ─────────────────────────────────
// Check for circular dependencies
function checkDependencyCycle(taskId, deps, allTasks) {
if (!deps || deps.length === 0) return false;
const visited = new Set();
const visiting = new Set();
function hasCycle(id) {
if (visited.has(id)) return false;
if (visiting.has(id)) return true;
visiting.add(id);
const task = allTasks.find(t => t.id === id);
if (task && task.deps) {
for (const depId of task.deps) {
if (hasCycle(depId)) return true;
}
}
visiting.delete(id);
visited.add(id);
return false;
}
return hasCycle(taskId);
}
// Token auth middleware
function validateToken(req, res, next) {
// Health check always open
if (req.path === '/api/health') return next();
// GET endpoints are open (no auth required) - optional protection below
if (req.method === 'GET') return next();
// If token is not configured, allow all mutations
if (!AGENTFLOW_TOKEN) return next();
// Require token on POST/PUT/DELETE
const authHeader = req.headers.authorization || '';
const token = authHeader.replace('Bearer ', '').trim();
if (token !== AGENTFLOW_TOKEN) {
return res.status(401).json({ error: 'Unauthorized' });
}
next();
}
// ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
// SYSTEM 1: AGENT CAPABILITY REGISTRY
// Defines what each agent/sub-agent IS and what it CAN DO
// ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
const AgentRegistry = {
// Default capability profiles for known agent types
profiles: {
'openclaw': {
description: 'Multi-agent orchestrator with specialized sub-agents for different task types',
capabilities: ['code-generation', 'research', 'analysis', 'file-operations', 'web-search'],
canHandle: ['coding', 'research', 'analysis', 'documentation', 'testing'],
maxConcurrent: 5,
subAgentDefaults: {
'Researcher': { purpose: 'Web research, data gathering, fact-checking', skills: ['web-search', 'analysis'], taskTypes: ['research', 'analysis'] },
'Coder': { purpose: 'Code generation, debugging, refactoring, testing', skills: ['code-generation', 'file-operations'], taskTypes: ['coding', 'testing', 'bugfix'] },
'Analyst': { purpose: 'Data analysis, visualization, reporting', skills: ['analysis', 'visualization'], taskTypes: ['analysis', 'reporting'] },
'Planner': { purpose: 'Task planning, decomposition, dependency analysis', skills: ['planning', 'analysis'], taskTypes: ['planning', 'architecture'] },
'Executor': { purpose: 'General task execution with tool access', skills: ['file-operations', 'code-generation'], taskTypes: ['coding', 'automation'] },
'Validator': { purpose: 'Testing, validation, quality assurance', skills: ['testing', 'analysis'], taskTypes: ['testing', 'review', 'qa'] },
}
},
'claude-code': {
description: 'AI pair programmer with full-stack coding, analysis, and debugging capabilities',
capabilities: ['code-generation', 'file-operations', 'analysis', 'debugging', 'refactoring'],
canHandle: ['coding', 'testing', 'bugfix', 'refactoring', 'documentation', 'architecture', 'review'],
maxConcurrent: 1,
subAgentDefaults: {
'Coder': { purpose: 'Write and modify code across languages', skills: ['code-generation', 'file-operations'], taskTypes: ['coding', 'bugfix'] },
'Reviewer': { purpose: 'Code review, best practices, security analysis', skills: ['analysis', 'testing'], taskTypes: ['review', 'qa'] },
'Architect': { purpose: 'System design, architecture decisions, tech stack', skills: ['planning', 'analysis'], taskTypes: ['architecture', 'planning'] },
}
},
'human': {
description: 'Human team member — handles approvals, creative decisions, and manual tasks',
capabilities: ['approval', 'creative', 'manual', 'decision-making'],
canHandle: ['approval', 'creative', 'manual', 'decision', 'review'],
maxConcurrent: 3,
subAgentDefaults: {}
}
},
// Resolve agent profile (from DB actor + defaults)
resolve(actor) {
if (!actor || typeof actor !== 'object' || !actor.id || !actor.type) {
return { description: 'Unknown actor', capabilities: [], canHandle: [], maxConcurrent: 1, subAgents: {} };
}
const baseType = actor.type === 'ai' ? (
actor.endpoint?.includes('18789') ? 'openclaw' :
actor.name?.toLowerCase().includes('claude') ? 'claude-code' : 'generic'
) : actor.type;
const profile = this.profiles[baseType] || this.profiles['human'];
const subAgents = {};
// Merge stored sub-agents with default profiles
const storedSubs = actor.subAgents || actor.agents || [];
for (const sa of storedSubs) {
const name = typeof sa === 'string' ? sa : sa.name;
const defaults = profile.subAgentDefaults?.[name] || {};
subAgents[name] = {
name,
purpose: sa.fn || sa.purpose || defaults.purpose || 'General-purpose agent',
skills: sa.skills || defaults.skills || [],
taskTypes: sa.taskTypes || defaults.taskTypes || [],
status: 'unknown',
currentTask: null,
};
}
return {
id: actor.id,
name: actor.name,
type: baseType,
description: actor.description || profile.description,
capabilities: actor.capabilities || profile.capabilities,
canHandle: profile.canHandle,
maxConcurrent: profile.maxConcurrent,
subAgents,
};
},
// Match a task to the best agent/sub-agent
suggestAssignment(task, actors) {
const taskTags = task.tags || [];
const taskTitle = (task.title || '').toLowerCase();
const scores = [];
for (const actor of actors) {
if (actor.type === 'human' && actor.status !== 'online') continue;
const profile = this.resolve(actor);
// Score based on tag/taskType overlap
let score = 0;
for (const tag of taskTags) {
if (profile.canHandle.includes(tag)) score += 10;
if (profile.capabilities.includes(tag)) score += 5;
}
// Keyword matching on title
const keywords = {
coding: ['implement', 'build', 'create', 'code', 'write', 'develop', 'fix', 'bug'],
review: ['review', 'audit', 'check', 'validate', 'verify'],
research: ['research', 'investigate', 'analyze', 'study', 'explore'],
testing: ['test', 'qa', 'load test', 'integration test', 'e2e'],
architecture: ['architect', 'design', 'system', 'infrastructure'],
documentation: ['doc', 'readme', 'guide', 'tutorial'],
};
for (const [type, words] of Object.entries(keywords)) {
if (words.some(w => taskTitle.includes(w))) {
if (profile.canHandle.includes(type)) score += 8;
}
}
// Best sub-agent for this task
let bestSub = null, bestSubScore = 0;
for (const [name, sa] of Object.entries(profile.subAgents)) {
let subScore = 0;
for (const tag of taskTags) {
if (sa.taskTypes.includes(tag)) subScore += 10;
if (sa.skills.includes(tag)) subScore += 5;
}
for (const [type, words] of Object.entries(keywords)) {
if (words.some(w => taskTitle.includes(w)) && sa.taskTypes.includes(type)) subScore += 8;
}
if (subScore > bestSubScore) { bestSubScore = subScore; bestSub = name; }
}
scores.push({ actorId: actor.id, actorName: actor.name, score: score + bestSubScore, subAgent: bestSub, profile });
}
return scores.sort((a, b) => b.score - a.score);
}
};
// ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
// SYSTEM 2: TASK STATE MACHINE
// Formal state transitions with triggers and guards
// ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
const TaskStateMachine = {
// All valid states (= kanban columns)
states: ['inbox', 'todo', 'in_progress', 'review', 'pending_human', 'failed', 'done'],
// All valid transitions: from → to → { trigger, guard, effect }
transitions: {
// ── FROM INBOX ──
'inbox→todo': { trigger: 'manual|auto_route|deps_met', guard: null, effect: 'setStatus:ready' },
'inbox→in_progress': { trigger: 'dispatch|agent_pickup|manual', guard: 'hasAssignee', effect: 'setStarted' },
'inbox→done': { trigger: 'manual', guard: null, effect: 'setCompleted' },
// ── FROM TODO (Ready) ──
'todo→in_progress': { trigger: 'dispatch|agent_pickup|session_detected|manual', guard: 'hasAssignee', effect: 'setStarted' },
'todo→inbox': { trigger: 'manual|unassign', guard: null, effect: 'clearStart' },
'todo→done': { trigger: 'manual', guard: null, effect: 'setCompleted' },
// ── FROM IN_PROGRESS ──
'in_progress→review': { trigger: 'agent_completed|manual', guard: null, effect: 'setReviewRequested' },
'in_progress→done': { trigger: 'manual|auto_complete', guard: null, effect: 'setCompleted' },
'in_progress→failed': { trigger: 'agent_error|timeout|manual', guard: null, effect: 'setFailed' },
'in_progress→pending_human': { trigger: 'agent_needs_input|clarification|approval_needed', guard: null, effect: 'setWaitingHuman' },
'in_progress→todo': { trigger: 'agent_paused|manual', guard: null, effect: 'clearStart' },
'in_progress→inbox': { trigger: 'manual|unassign', guard: null, effect: 'clearStart' },
// ── FROM REVIEW ──
'review→done': { trigger: 'approved|manual', guard: null, effect: 'setCompleted' },
'review→in_progress': { trigger: 'changes_requested|manual', guard: null, effect: 'setStatus:active' },
'review→failed': { trigger: 'rejected|manual', guard: null, effect: 'setFailed' },
'review→pending_human': { trigger: 'needs_human_review', guard: null, effect: 'setWaitingHuman' },
// ── FROM PENDING_HUMAN ──
'pending_human→in_progress': { trigger: 'human_responded|input_provided|manual', guard: null, effect: 'setStatus:active' },
'pending_human→done': { trigger: 'manual', guard: null, effect: 'setCompleted' },
'pending_human→failed': { trigger: 'timeout|manual', guard: null, effect: 'setFailed' },
'pending_human→todo': { trigger: 'manual', guard: null, effect: 'setStatus:ready' },
// ── FROM FAILED ──
'failed→todo': { trigger: 'retry|manual', guard: 'retryAvailable', effect: 'incrementRetry' },
'failed→in_progress': { trigger: 'auto_retry|manual', guard: 'retryAvailable', effect: 'incrementRetry;setStarted' },
'failed→inbox': { trigger: 'manual|reassign', guard: null, effect: 'clearStart;clearAssignee' },
'failed→done': { trigger: 'manual', guard: null, effect: 'setCompleted' },
// ── FROM DONE ──
'done→in_progress': { trigger: 'reopen|manual', guard: null, effect: 'clearCompleted;setStarted' },
'done→todo': { trigger: 'reopen|manual', guard: null, effect: 'clearCompleted' },
},
// Check if a transition is valid
canTransition(fromCol, toCol, task, trigger) {
const key = `${fromCol}→${toCol}`;
const rule = this.transitions[key];
if (!rule) return { allowed: false, reason: `No transition ${key} defined` };
// Check trigger is one of the allowed triggers
const triggers = rule.trigger.split('|');
if (trigger && !triggers.includes(trigger) && !triggers.includes('manual')) {
return { allowed: false, reason: `Trigger "${trigger}" not valid for ${key}. Expected: ${rule.trigger}` };
}
// Check guard
if (rule.guard) {
const guards = rule.guard.split(';');
for (const g of guards) {
if (g === 'hasAssignee' && !task.assignee) {
return { allowed: false, reason: 'Task must have an assignee to move to this column' };
}
if (g === 'retryAvailable' && task.retryCount >= (task.maxRetries || 3)) {
return { allowed: false, reason: `Max retries (${task.maxRetries || 3}) exceeded` };
}
}
}
return { allowed: true, rule, triggers };
},
// Apply a transition's effects to a task
applyEffects(task, rule) {
if (!rule || !rule.effect) return;
const effects = rule.effect.split(';');
const now = Date.now();
for (const effect of effects) {
if (effect === 'setStarted') { if (!task.startedAt) task.startedAt = now; task.status = 'active'; }
else if (effect === 'setCompleted') { task.completedAt = now; task.status = 'completed'; }
else if (effect === 'setFailed') { task.status = 'failed'; task.failedAt = now; }
else if (effect === 'setReviewRequested') { task.status = 'in_review'; task.reviewRequestedAt = now; }
else if (effect === 'setWaitingHuman') { task.status = 'waiting_human'; }
else if (effect === 'clearStart') { task.startedAt = null; task.status = 'ready'; }
else if (effect === 'clearCompleted') { task.completedAt = null; task.status = 'active'; }
else if (effect === 'clearAssignee') { task.assignee = null; task.assigneeAgent = null; }
else if (effect === 'incrementRetry') { task.retryCount = (task.retryCount || 0) + 1; }
else if (effect.startsWith('setStatus:')) { task.status = effect.split(':')[1]; }
}
task.updated = now;
},
// Execute a state transition
transition(task, toCol, trigger, auditFn) {
const fromCol = task.column;
if (fromCol === toCol) return { moved: false, reason: 'Already in target column' };
const check = this.canTransition(fromCol, toCol, task, trigger);
if (!check.allowed) return { moved: false, reason: check.reason };
// Apply
task.column = toCol;
this.applyEffects(task, check.rule);
if (auditFn) {
auditFn(Date.now(), 'TASK_TRANSITION',
`Task #${task.num} ${fromCol}→${toCol} [trigger:${trigger}]`,
task.id, task.assignee, null);
}
return { moved: true, from: fromCol, to: toCol, trigger, effects: check.rule.effect };
}
};
// ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
// SYSTEM 3: ORCHESTRATION ENGINE
// Watches agent activity → applies state machine transitions
// ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
const Orchestrator = {
// Process discovery results and auto-transition tasks
processDiscoveryResults(discoveryResults, allTasks, allActors, stmtsRef, broadcastFn) {
const changes = [];
const r = discoveryResults;
// ── 1. Agent went ONLINE → move assigned tasks inbox/todo → in_progress ──
for (const actor of allActors) {
const profile = AgentRegistry.resolve(actor);
if (actor.status === 'online' && actor.type === 'ai') {
const assignedTasks = allTasks.filter(t =>
t.assignee === actor.id && (t.column === 'todo' || t.column === 'inbox')
);
for (const task of assignedTasks) {
// Only auto-move if agent has an active session that could be working on this
const hasActiveSession = this.taskHasActiveSession(task, actor, r);
if (hasActiveSession) {
const result = TaskStateMachine.transition(task, 'in_progress', 'agent_pickup', stmtsRef.addAudit.run.bind(stmtsRef.addAudit));
if (result.moved) {
const persisted = this.persistTask(task, stmtsRef);
if (!persisted) continue; // skip if persist failed
changes.push({ taskId: task.id, taskNum: task.num, ...result, reason: 'Agent online with active session' });
}
}
}
}
// ── 2. Agent went OFFLINE → move in_progress tasks to pending or failed ──
if (actor.status === 'offline' && actor.type === 'ai') {
const activeTasks = allTasks.filter(t =>
t.assignee === actor.id && t.column === 'in_progress'
);
for (const task of activeTasks) {
// Don't immediately fail — move to pending_human for human decision
const result = TaskStateMachine.transition(task, 'pending_human', 'agent_needs_input', stmtsRef.addAudit.run.bind(stmtsRef.addAudit));
if (result.moved) {
task.humanReqDoc = {
what: `Agent "${actor.name}" went offline while working on this task`,
urgency: 'medium',
context: 'The agent disconnected. You can: reassign, wait for reconnect, or move to failed.',
ts: Date.now()
};
this.persistTask(task, stmtsRef);
changes.push({ taskId: task.id, taskNum: task.num, ...result, reason: 'Agent went offline' });
}
}
}
}
// ── 3. Session-based detection (OpenClaw sessions → match to tasks) ──
if (r.openclaw?.sessions?.length > 0) {
for (const session of r.openclaw.sessions) {
const matched = this.matchSessionToTask(session, allTasks, allActors);
if (matched && (matched.column === 'todo' || matched.column === 'inbox')) {
const result = TaskStateMachine.transition(matched, 'in_progress', 'session_detected', stmtsRef.addAudit.run.bind(stmtsRef.addAudit));
if (result.moved) {
matched.meta = matched.meta || {};
matched.meta.linkedSession = session.key;
matched.meta.sessionModel = session.model;
this.persistTask(matched, stmtsRef);
changes.push({ taskId: matched.id, taskNum: matched.num, ...result, reason: `Linked to session ${session.key}` });
}
}
}
}
// ── 4. Claude Code session files → detect activity ──
if (r.claudeCode?.sessions?.length > 0) {
for (const session of r.claudeCode.sessions) {
// Check if any task title appears in the session's project path
for (const task of allTasks) {
if (task.column !== 'todo' && task.column !== 'inbox') continue;
const actor = allActors.find(a => a.id === task.assignee);
if (!actor || !actor.name?.toLowerCase().includes('claude')) continue;
// Heuristic: if session was active in last 5 min and task title keywords match project path
const sessionAge = Date.now() - new Date(session.lastActive).getTime();
if (sessionAge < 300000) { // 5 min
const result = TaskStateMachine.transition(task, 'in_progress', 'session_detected', stmtsRef.addAudit.run.bind(stmtsRef.addAudit));
if (result.moved) {
task.meta = task.meta || {};
task.meta.linkedSession = session.sessionId;
task.meta.sessionProject = session.project;
this.persistTask(task, stmtsRef);
changes.push({ taskId: task.id, taskNum: task.num, ...result, reason: `Claude Code session active: ${session.project}` });
}
}
}
}
}
// ── 5. Timeout detection → move stale in_progress tasks ──
const staleTimeout = 3600000; // 1 hour
for (const task of allTasks) {
if (task.column !== 'in_progress') continue;
if (!task.startedAt) continue;
const elapsed = Date.now() - task.startedAt;
const actor = allActors.find(a => a.id === task.assignee);
// If task has been in_progress for > 1 hour and agent is offline
if (elapsed > staleTimeout && actor && actor.status === 'offline') {
const result = TaskStateMachine.transition(task, 'failed', 'timeout', stmtsRef.addAudit.run.bind(stmtsRef.addAudit));
if (result.moved) {
task.failureDoc = {
reason: 'timeout',
detail: `Task stale for ${Math.round(elapsed / 60000)}min while agent "${actor?.name}" is offline`,
ts: Date.now()
};
this.persistTask(task, stmtsRef);
changes.push({ taskId: task.id, taskNum: task.num, ...result, reason: 'Stale timeout (agent offline)' });
}
}
}
// ── 6. Auto-retry failed tasks if retries available ──
for (const task of allTasks) {
if (task.column !== 'failed') continue;
if (!task.assignee) continue;
const actor = allActors.find(a => a.id === task.assignee);
if (!actor || actor.status !== 'online') continue;
const retryCount = task.retryCount || 0;
const maxRetries = task.maxRetries || 3;
if (retryCount >= maxRetries) continue;
// Only auto-retry if failure was recent (< 10 min) and auto-retry is not disabled
const failedAge = Date.now() - (task.failedAt || 0);
if (failedAge < 600000 && task.meta?.autoRetry !== false) {
const result = TaskStateMachine.transition(task, 'in_progress', 'auto_retry', stmtsRef.addAudit.run.bind(stmtsRef.addAudit));
if (result.moved) {
task.meta = task.meta || {};
task.meta.lastRetryAt = Date.now();
this.persistTask(task, stmtsRef);
changes.push({ taskId: task.id, taskNum: task.num, ...result, reason: `Auto-retry ${retryCount + 1}/${maxRetries}` });
}
}
}
// ── 7. Dependency resolution → unblock tasks ──
for (const task of allTasks) {
if (task.column !== 'inbox') continue;
if (!task.deps || task.deps.length === 0) continue;
const allDepsDone = task.deps.every(depId => {
const dep = allTasks.find(t => t.id === depId);
return dep && dep.column === 'done';
});
if (allDepsDone) {
const result = TaskStateMachine.transition(task, 'todo', 'deps_met', stmtsRef.addAudit.run.bind(stmtsRef.addAudit));
if (result.moved) {
this.persistTask(task, stmtsRef);
changes.push({ taskId: task.id, taskNum: task.num, ...result, reason: 'All dependencies completed' });
}
}
}
return changes;
},
// Check if a task has a corresponding active agent session
taskHasActiveSession(task, actor, discoveryResults) {
const r = discoveryResults;
// OpenClaw: check sessions
if (actor.endpoint?.includes('18789') && r.openclaw?.sessions) {
return r.openclaw.sessions.some(s =>
(s.key && task.remoteId && s.key.includes(task.remoteId)) ||
(s.agentId && task.assigneeAgent && s.agentId === task.assigneeAgent) ||
(s.key && s.key.includes(task.id))
);
}
// Claude Code: check running process
if (actor.name?.toLowerCase().includes('claude') && r.claudeCode?.running) {
return true; // Claude Code is running, could be working on anything
}
return false;
},
// Match an OpenClaw session to a board task
matchSessionToTask(session, allTasks, allActors) {
for (const task of allTasks) {
if (task.remoteId && session.key === task.remoteId) return task;
if (session.key === task.id) return task;
if (task.assigneeAgent && session.agentId === task.assigneeAgent) {
const actor = allActors.find(a => a.id === task.assignee);
if (actor?.endpoint?.includes('18789')) return task;
}
}
return null;
},
// Persist task changes to DB
persistTask(task, stmtsRef) {
try {
stmtsRef.upsertTask.run({
id: task.id, num: task.num, data: JSON.stringify(task),
column_id: task.column, priority: task.priority,
assignee: task.assignee, created_at: task.created, updated_at: task.updated
});
return true;
} catch (e) {
console.error(` Orchestrator: failed to persist task #${task.num}:`, e.message);
return false;
}
}
};
// ─── Express + HTTP Server ────────────────────────────
const app = express();
const server = http.createServer(app);
app.use(cors());
app.use(express.json({ limit: '10mb' }));
// Token authentication middleware
app.use(validateToken);
// Serve the frontend
app.use(express.static(__dirname));
// ─── SQLite Database ──────────────────────────────────
const db = new Database(DB_PATH);
db.pragma('journal_mode = WAL');
db.pragma('foreign_keys = ON');
function initDB() {
db.exec(`
CREATE TABLE IF NOT EXISTS state (
id TEXT PRIMARY KEY DEFAULT 'main',
data TEXT NOT NULL,
updated_at INTEGER NOT NULL
);
CREATE TABLE IF NOT EXISTS tasks (
id TEXT PRIMARY KEY,
num INTEGER NOT NULL,
data TEXT NOT NULL,
column_id TEXT NOT NULL DEFAULT 'inbox',
priority TEXT NOT NULL DEFAULT 'medium',
assignee TEXT,
created_at INTEGER NOT NULL,
updated_at INTEGER NOT NULL
);
CREATE TABLE IF NOT EXISTS actors (
id TEXT PRIMARY KEY,
type TEXT NOT NULL,
name TEXT NOT NULL,
data TEXT NOT NULL,
status TEXT NOT NULL DEFAULT 'offline',
created_at INTEGER NOT NULL
);
CREATE TABLE IF NOT EXISTS audit_log (
id INTEGER PRIMARY KEY AUTOINCREMENT,
ts INTEGER NOT NULL,
action TEXT NOT NULL,
detail TEXT,
task_id TEXT,
actor_id TEXT,
nonce TEXT
);
CREATE TABLE IF NOT EXISTS reasoning (
id INTEGER PRIMARY KEY AUTOINCREMENT,
type TEXT NOT NULL,
text TEXT NOT NULL,
task_id TEXT,
ts INTEGER NOT NULL
);
CREATE INDEX IF NOT EXISTS idx_tasks_column ON tasks(column_id);
CREATE INDEX IF NOT EXISTS idx_tasks_assignee ON tasks(assignee);
CREATE INDEX IF NOT EXISTS idx_audit_ts ON audit_log(ts);
CREATE INDEX IF NOT EXISTS idx_audit_task ON audit_log(task_id);
CREATE INDEX IF NOT EXISTS idx_reasoning_ts ON reasoning(ts);
`);
// Ensure main state row exists
const row = db.prepare('SELECT id FROM state WHERE id = ?').get('main');
if (!row) {
const defaultState = {
title: 'AgentFlow',
logoUrl: '',
plan: 'free',
columns: [
{ id: 'inbox', name: 'Inbox / Queued', color: '#8b949e', wipLimit: 0 },
{ id: 'todo', name: 'Ready', color: '#d29922', wipLimit: 0 },
{ id: 'in_progress', name: 'In Progress', color: '#00b4d8', wipLimit: 5 },
{ id: 'review', name: 'Review', color: '#7c3aed', wipLimit: 3 },
{ id: 'pending_human', name: 'Pending (Human)', color: '#f0883e', wipLimit: 0 },
{ id: 'failed', name: 'Failed', color: '#da3633', wipLimit: 0 },
{ id: 'done', name: 'Done', color: '#2ea043', wipLimit: 0 }
],
taskCounter: 0,
theme: { accent: '#00b4d8', secondary: '#7c3aed', bg: '#06090f', card: '#161b22', text: '#e6edf3', border: '#21262d' },
settings: {
autoRetryOnRateLimit: true,
rateLimitCooldownSec: 60,
maxAutoRetries: 3,
requireCompletionDoc: true,
enablePolling: true,
pollingIntervalSec: 30
}
};
db.prepare('INSERT INTO state (id, data, updated_at) VALUES (?, ?, ?)').run('main', JSON.stringify(defaultState), Date.now());
}
}
initDB();
// ─── Prepared Statements ──────────────────────────────
const stmts = {
getState: db.prepare('SELECT data FROM state WHERE id = ?'),
setState: db.prepare('UPDATE state SET data = ?, updated_at = ? WHERE id = ?'),
getAllTasks: db.prepare('SELECT data FROM tasks ORDER BY created_at ASC'),
getTask: db.prepare('SELECT data FROM tasks WHERE id = ?'),
upsertTask: db.prepare(`INSERT INTO tasks (id, num, data, column_id, priority, assignee, created_at, updated_at)
VALUES (@id, @num, @data, @column_id, @priority, @assignee, @created_at, @updated_at)
ON CONFLICT(id) DO UPDATE SET data=@data, column_id=@column_id, priority=@priority, assignee=@assignee, updated_at=@updated_at`),
deleteTask: db.prepare('DELETE FROM tasks WHERE id = ?'),
deleteAllTasks: db.prepare('DELETE FROM tasks'),
getAllActors: db.prepare('SELECT data FROM actors ORDER BY created_at ASC'),
getActor: db.prepare('SELECT data FROM actors WHERE id = ?'),
upsertActor: db.prepare(`INSERT INTO actors (id, type, name, data, status, created_at)
VALUES (@id, @type, @name, @data, @status, @created_at)
ON CONFLICT(id) DO UPDATE SET type=@type, name=@name, data=@data, status=@status`),
deleteActor: db.prepare('DELETE FROM actors WHERE id = ?'),
deleteAllActors: db.prepare('DELETE FROM actors'),
addAudit: db.prepare('INSERT INTO audit_log (ts, action, detail, task_id, actor_id, nonce) VALUES (?, ?, ?, ?, ?, ?)'),
getAuditAll: db.prepare('SELECT * FROM audit_log ORDER BY ts DESC LIMIT ?'),
getAuditByTask: db.prepare('SELECT * FROM audit_log WHERE task_id = ? ORDER BY ts DESC LIMIT ?'),
deleteAllAudit: db.prepare('DELETE FROM audit_log'),
addReasoning: db.prepare('INSERT INTO reasoning (type, text, task_id, ts) VALUES (?, ?, ?, ?)'),
getReasoningAll: db.prepare('SELECT * FROM reasoning ORDER BY ts DESC LIMIT ?'),
deleteAllReasoning: db.prepare('DELETE FROM reasoning'),
};
// ─── WebSocket ────────────────────────────────────────
const wss = new WebSocketServer({ server, path: '/ws' });
const clients = new Set();
wss.on('connection', (ws) => {
clients.add(ws);
ws.isAlive = true;
ws.missedPongs = 0;
if (isDev) console.log(`[WS] Client connected (${clients.size} total)`);
ws.on('pong', () => {
ws.isAlive = true;
ws.missedPongs = 0;
});
ws.on('close', () => {
clients.delete(ws);
if (isDev) console.log(`[WS] Client disconnected (${clients.size} total)`);
});
ws.on('error', () => clients.delete(ws));
});
// WebSocket heartbeat: ping every 30s, track missed pongs
setInterval(() => {
clients.forEach(ws => {
if (!ws.isAlive) {
ws.missedPongs++;
if (ws.missedPongs >= 2) {
try {
ws.terminate();
} catch (e) {
// ignore errors when terminating
}
clients.delete(ws);
return;
}
}
ws.isAlive = false;
try {
ws.ping();
} catch (e) {
// ignore errors when pinging
}
});
}, 30000);
function broadcast(event, data) {
const msg = JSON.stringify({ event, data, ts: Date.now() });
clients.forEach(ws => {
if (ws.readyState === 1) ws.send(msg);
});
}
// ─── Helper: get full state for frontend ──────────────
function getFullState() {
const stateRow = stmts.getState.get('main');
const state = JSON.parse(stateRow.data);
state.tasks = stmts.getAllTasks.all().map(r => JSON.parse(r.data));
state.actors = stmts.getAllActors.all().map(r => JSON.parse(r.data));
state.auditLog = stmts.getAuditAll.all(5000);
state.reasoning = stmts.getReasoningAll.all(200);
return state;
}
// ─── API Routes ───────────────────────────────────────
// ── Full State (load/save for frontend sync) ──
app.get('/api/state', (req, res) => {
try {
res.json(getFullState());
} catch (e) {
res.status(500).json({ error: e.message });
}
});
app.put('/api/state', (req, res) => {
try {
const incoming = req.body;
const now = Date.now();
// Input validation
if (incoming.logoUrl && typeof incoming.logoUrl === 'string' && incoming.logoUrl.startsWith('javascript:')) {
return res.status(400).json({ error: 'logoUrl cannot start with javascript:' });
}
// Wrap entire sync in transaction
const syncState = db.transaction(() => {
// Save core state (columns, theme, settings, etc.)
const coreState = {
title: incoming.title,
logoUrl: incoming.logoUrl,
plan: incoming.plan,
columns: incoming.columns,
taskCounter: incoming.taskCounter,
theme: incoming.theme,
settings: incoming.settings,
isDemo: incoming.isDemo || false
};
stmts.setState.run(JSON.stringify(coreState), now, 'main');
// Sync tasks
if (incoming.tasks) {
const existingIds = new Set(stmts.getAllTasks.all().map(r => JSON.parse(r.data).id));
const incomingIds = new Set(incoming.tasks.map(t => t.id));
// Delete tasks not in incoming
for (const id of existingIds) {
if (!incomingIds.has(id)) stmts.deleteTask.run(id);
}
// Upsert all incoming tasks
for (const t of incoming.tasks) {
stmts.upsertTask.run({
id: t.id,
num: t.num,
data: JSON.stringify(t),
column_id: t.column || 'inbox',
priority: t.priority || 'medium',
assignee: t.assignee || null,
created_at: t.created || now,
updated_at: t.updated || now
});
}
}
// Sync actors (preserving discovery metadata)
if (incoming.actors) {
// Build lookup of existing actors with discovery metadata
const existingActors = {};
stmts.getAllActors.all().forEach(r => {
const a = JSON.parse(r.data);
existingActors[a.id] = a;
});
const existingIds = new Set(Object.keys(existingActors));
const incomingIds = new Set(incoming.actors.map(a => a.id));
for (const id of existingIds) {
if (!incomingIds.has(id)) stmts.deleteActor.run(id);
}
for (const a of incoming.actors) {
// Merge: keep discovery metadata from server, take everything else from frontend
const existing = existingActors[a.id];
if (existing && existing.meta) {
// Preserve discovery fields the frontend doesn't know about
const discoveryFields = ['lastProbe', 'lastProbeResult', 'discoveredAgents',
'activeSessions', 'sessionDetails', 'claudeVersion', 'recentSessions'];
if (!a.meta) a.meta = {};
for (const field of discoveryFields) {
if (existing.meta[field] !== undefined && a.meta[field] === undefined) {
a.meta[field] = existing.meta[field];
}
}
}
// Use discovery-determined status if frontend sent stale status
let status = a.status || 'offline';
if (existing && existing.meta?.lastProbe) {
try {
const probeAge = now - new Date(existing.meta.lastProbe).getTime();
if (probeAge < 60000) {
// Discovery probed within last 60s — trust its status over frontend
status = existing.status || status;
}
} catch (e) {
// Invalid ISO date, ignore
}
}
stmts.upsertActor.run({
id: a.id,
type: a.type,
name: a.name,
data: JSON.stringify({ ...a, status }),
status,
created_at: existing?.created_at || now
});
}
}
});
syncState();
broadcast('state_updated', { ts: now });
res.json({ ok: true, ts: now });
} catch (e) {
res.status(500).json({ error: e.message });
}
});
// ── Tasks CRUD ──
app.get('/api/tasks', (req, res) => {
try {
const tasks = stmts.getAllTasks.all().map(r => JSON.parse(r.data));
if (req.query.column) {
res.json(tasks.filter(t => t.column === req.query.column));
} else if (req.query.assignee) {
res.json(tasks.filter(t => t.assignee === req.query.assignee));
} else {
res.json(tasks);
}
} catch (e) {
res.status(500).json({ error: e.message });
}
});
app.get('/api/tasks/:id', (req, res) => {
try {
const row = stmts.getTask.get(req.params.id);
if (!row) return res.status(404).json({ error: 'Task not found' });
res.json(JSON.parse(row.data));
} catch (e) {
res.status(500).json({ error: e.message });
}
});
app.post('/api/tasks', (req, res) => {
try {
// Input validation
const t = req.body;
if (!t.title) return res.status(400).json({ error: 'title is required' });
if (t.title.length >= 500) return res.status(400).json({ error: 'title must be less than 500 characters' });
if (t.priority && !['low', 'medium', 'high', 'urgent'].includes(t.priority)) {
return res.status(400).json({ error: 'priority must be one of: low, medium, high, urgent' });
}
if (t.tags && (!Array.isArray(t.tags) || !t.tags.every(tag => typeof tag === 'string'))) {
return res.status(400).json({ error: 'tags must be an array of strings' });
}
// Dependency cycle detection
if (t.deps && t.deps.length > 0) {
const hasCycle = checkDependencyCycle(t.id, t.deps, stmts.getAllTasks.all().map(r => JSON.parse(r.data)));
if (hasCycle) return res.status(400).json({ error: 'Circular dependency detected' });
}
if (!t.id) t.id = uuidv4();
if (!t.created) t.created = Date.now();
t.updated = Date.now();
// Increment task counter in transaction
const createTask = db.transaction(() => {
const stateRow = stmts.getState.get('main');
const state = JSON.parse(stateRow.data);
state.taskCounter = (state.taskCounter || 0) + 1;
t.num = state.taskCounter;
stmts.setState.run(JSON.stringify(state), Date.now(), 'main');
stmts.upsertTask.run({
id: t.id, num: t.num, data: JSON.stringify(t),
column_id: t.column || 'inbox', priority: t.priority || 'medium',
assignee: t.assignee || null, created_at: t.created, updated_at: t.updated
});
stmts.addAudit.run(Date.now(), 'TASK_CREATED', `Task #${t.num} "${t.title}" created`, t.id, null, null);
});
createTask();
broadcast('task_created', t);
res.status(201).json(t);
} catch (e) {
res.status(500).json({ error: e.message });
}
});
app.put('/api/tasks/:id', (req, res) => {
try {
const existing = stmts.getTask.get(req.params.id);
if (!existing) return res.status(404).json({ error: 'Task not found' });
const t = { ...JSON.parse(existing.data), ...req.body, updated: Date.now() };
// Input validation
if (!t.title) return res.status(400).json({ error: 'title is required' });
// Dependency cycle detection
if (t.deps && t.deps.length > 0) {
const allTasks = stmts.getAllTasks.all().map(r => JSON.parse(r.data)).filter(task => task.id !== req.params.id);
const hasCycle = checkDependencyCycle(t.id, t.deps, allTasks);
if (hasCycle) return res.status(400).json({ error: 'Circular dependency detected' });
}
stmts.upsertTask.run({
id: t.id, num: t.num, data: JSON.stringify(t),
column_id: t.column || 'inbox', priority: t.priority || 'medium',
assignee: t.assignee || null, created_at: t.created, updated_at: t.updated
});
stmts.addAudit.run(Date.now(), 'TASK_UPDATED', `Task #${t.num} updated`, t.id, null, null);
broadcast('task_updated', t);
res.json(t);
} catch (e) {
res.status(500).json({ error: e.message });
}
});