-
Notifications
You must be signed in to change notification settings - Fork 23
Expand file tree
/
Copy pathapp.py
More file actions
2224 lines (1863 loc) · 89.3 KB
/
app.py
File metadata and controls
2224 lines (1863 loc) · 89.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
"""
RIZQ Task Board - FastAPI Backend
Simple, fast, full agent control, LIVE updates
"""
import sqlite3
import json
import asyncio
import re
import httpx
from datetime import datetime
from pathlib import Path
from typing import Optional, List, Set
from contextlib import contextmanager
from fastapi import FastAPI, HTTPException, WebSocket, WebSocketDisconnect, Depends, Header, Request
from fastapi.staticfiles import StaticFiles
from fastapi.responses import FileResponse, PlainTextResponse
from fastapi.middleware.cors import CORSMiddleware
from starlette.middleware.base import BaseHTTPMiddleware
from pydantic import BaseModel, field_validator
# =============================================================================
# CONFIG
# =============================================================================
import os
import secrets
import hashlib
DATA_DIR = Path(__file__).parent / "data"
DATA_DIR.mkdir(exist_ok=True)
DB_PATH = DATA_DIR / "tasks.db"
STATIC_PATH = Path(__file__).parent / "static"
# =============================================================================
# BRANDING (configurable via environment variables)
# =============================================================================
MAIN_AGENT_NAME = os.getenv("MAIN_AGENT_NAME", "Jarvis")
MAIN_AGENT_EMOJI = os.getenv("MAIN_AGENT_EMOJI", "\U0001F6E1")
HUMAN_NAME = os.getenv("HUMAN_NAME", "User")
HUMAN_SUPERVISOR_LABEL = os.getenv("HUMAN_SUPERVISOR_LABEL", "User")
BOARD_TITLE = os.getenv("BOARD_TITLE", "Task Board")
AGENTS = [MAIN_AGENT_NAME, "Architect", "Security Auditor", "Code Reviewer", "UX Manager", "User", "Unassigned"]
STATUSES = ["Backlog", "In Progress", "Review", "Done", "Blocked"]
PRIORITIES = ["Critical", "High", "Medium", "Low"]
# Map task board agent names to OpenClaw agent IDs
# Customize these to match your OpenClaw agent configuration
AGENT_TO_OPENCLAW_ID = {
MAIN_AGENT_NAME: "main", # Main agent (handles command bar chat)
"Architect": "architect",
"Security Auditor": "security-auditor",
"Code Reviewer": "code-reviewer",
"UX Manager": "ux-manager",
}
# Alias for backward compatibility
AGENT_TO_OPENCLAW_ID = AGENT_TO_OPENCLAW_ID
# Build mention regex dynamically from agent names (including main agent now)
MENTIONABLE_AGENTS = list(AGENT_TO_OPENCLAW_ID.keys())
MENTION_PATTERN = re.compile(r'@(' + '|'.join(re.escape(a) for a in MENTIONABLE_AGENTS) + r')', re.IGNORECASE)
# Security: Load secrets from environment variables
OPENCLAW_GATEWAY_URL = os.getenv("OPENCLAW_GATEWAY_URL", "http://host.docker.internal:18789")
OPENCLAW_TOKEN = os.getenv("OPENCLAW_TOKEN", "")
TASKBOARD_API_KEY = os.getenv("TASKBOARD_API_KEY", "")
OPENCLAW_ENABLED = bool(OPENCLAW_TOKEN)
# Project configuration (customize in .env)
PROJECT_NAME = os.getenv("PROJECT_NAME", "My Project")
COMPANY_NAME = os.getenv("COMPANY_NAME", "Acme Corp")
COMPANY_CONTEXT = os.getenv("COMPANY_CONTEXT", "software development")
ALLOWED_PATHS = os.getenv("ALLOWED_PATHS", "/workspace, /project")
COMPLIANCE_FRAMEWORKS = os.getenv("COMPLIANCE_FRAMEWORKS", "your security requirements")
# IP-based access restriction
# Always allowed: localhost variants and Docker internal networks
ALWAYS_ALLOWED_IPS = {"127.0.0.1", "localhost", "::1"}
# Additional allowed IPs from env (comma-separated)
_env_ips = os.getenv("ALLOWED_IPS", "").strip()
ALLOWED_IPS = set(ip.strip() for ip in _env_ips.split(",") if ip.strip()) if _env_ips else set()
print(f"🔒 IP Restriction: localhost + 172.20.200.59 + 172.20.200.119 + 172.18.0.1 (internal) + {ALLOWED_IPS if ALLOWED_IPS else 'no external IPs'}")
# Warn if running without security
if not TASKBOARD_API_KEY:
print("⚠️ WARNING: TASKBOARD_API_KEY not set. API authentication disabled!")
if not OPENCLAW_TOKEN:
print("⚠️ WARNING: OPENCLAW_TOKEN not set. OPENCLAW integration disabled!")
# File upload limits
MAX_ATTACHMENT_SIZE_MB = 10
MAX_ATTACHMENT_SIZE_BYTES = MAX_ATTACHMENT_SIZE_MB * 1024 * 1024
# =============================================================================
# SECURITY
# =============================================================================
def verify_api_key(authorization: str = Header(None), x_api_key: str = Header(None)):
"""Verify API key from Authorization header or X-API-Key header."""
if not TASKBOARD_API_KEY:
return True # Auth disabled if no key configured
# Check Authorization: Bearer <token>
if authorization:
if authorization.startswith("Bearer "):
token = authorization[7:]
if secrets.compare_digest(token, TASKBOARD_API_KEY):
return True
# Check X-API-Key header
if x_api_key:
if secrets.compare_digest(x_api_key, TASKBOARD_API_KEY):
return True
raise HTTPException(status_code=401, detail="Invalid or missing API key")
def verify_internal_only(request: Request):
"""Only allow requests from localhost/internal sources."""
client_host = request.client.host if request.client else None
allowed_hosts = ["127.0.0.1", "localhost", "::1", "172.17.0.1", "host.docker.internal"]
# Also allow Docker internal IPs (172.x.x.x)
if client_host and (client_host in allowed_hosts or client_host.startswith("172.")):
return True
# If API key is provided, allow from anywhere
if TASKBOARD_API_KEY:
return True
raise HTTPException(status_code=403, detail="Access denied")
async def notify_OPENCLAW(task_id: int, task_title: str, comment_agent: str, comment_content: str):
"""Send webhook to OpenClaw when a comment needs attention."""
if not OPENCLAW_ENABLED or comment_agent == MAIN_AGENT_NAME:
return # Don't notify for main agent's own comments
try:
async with httpx.AsyncClient(timeout=5.0) as client:
# Use OPENCLAW's cron wake endpoint
payload = {
"action": "wake",
"text": f"💬 Task Board: New comment on #{task_id} ({task_title}) from {comment_agent}:\n\n{comment_content[:200]}{'...' if len(comment_content) > 200 else ''}\n\nCheck and respond: http://localhost:8080"
}
headers = {
"Authorization": f"Bearer {OPENCLAW_TOKEN}",
"Content-Type": "application/json"
}
await client.post(f"{OPENCLAW_GATEWAY_URL}/api/cron/wake", json=payload, headers=headers)
print(f"Notified OPENCLAW about comment from {comment_agent}")
except Exception as e:
print(f"Webhook to OPENCLAW failed: {e}")
async def send_to_agent_session(session_key: str, message: str) -> bool:
"""Send a follow-up message to an active agent session."""
if not OPENCLAW_ENABLED or not session_key:
return False
try:
async with httpx.AsyncClient(timeout=30.0) as client:
payload = {
"tool": "sessions_send",
"args": {
"sessionKey": session_key,
"message": message
}
}
headers = {
"Authorization": f"Bearer {OPENCLAW_TOKEN}",
"Content-Type": "application/json"
}
response = await client.post(
f"{OPENCLAW_GATEWAY_URL}/tools/invoke",
json=payload,
headers=headers
)
result = response.json() if response.status_code == 200 else None
if result and result.get("ok"):
print(f"✅ Sent message to session {session_key}")
return True
else:
print(f"❌ Failed to send to session: {response.text}")
return False
except Exception as e:
print(f"❌ Failed to send to agent session: {e}")
return False
def get_task_session(task_id: int) -> Optional[str]:
"""Get the active agent session key for a task."""
with get_db() as conn:
row = conn.execute("SELECT agent_session_key FROM tasks WHERE id = ?", (task_id,)).fetchone()
return row["agent_session_key"] if row and row["agent_session_key"] else None
async def spawn_followup_session(task_id: int, task_title: str, agent_name: str, previous_context: str, new_message: str):
"""Spawn a follow-up session for an agent with conversation context."""
if not OPENCLAW_ENABLED:
return None
agent_id = AGENT_TO_OPENCLAW_ID.get(agent_name)
if not agent_id:
return None
# Main agent can spawn follow-up sessions too
system_prompt = AGENT_SYSTEM_PROMPTS.get(agent_id, "")
followup_prompt = f"""# Follow-up on Task #{task_id}: {task_title}
You previously worked on this task and moved it to Review. User has a follow-up question.
## Previous Conversation:
{previous_context if previous_context else "(No previous messages)"}
## User's New Message:
{new_message}
## Your Role:
{system_prompt}
## Instructions:
1. Call start-work API: POST http://localhost:8080/api/tasks/{task_id}/start-work?agent={agent_name}
2. Read the context and User's question
3. Respond helpfully by posting a comment: POST http://localhost:8080/api/tasks/{task_id}/comments
4. Keep your response focused on what User asked
5. Call stop-work API: POST http://localhost:8080/api/tasks/{task_id}/stop-work?agent={agent_name}
- Add &outcome=review&reason=<summary> if work is complete
- Add &outcome=blocked&reason=<why> if you need more input
Respond now.
"""
try:
async with httpx.AsyncClient(timeout=60.0) as client:
payload = {
"tool": "sessions_spawn",
"args": {
"agentId": agent_id,
"task": followup_prompt,
"label": f"task-{task_id}-followup",
"cleanup": "keep"
}
}
headers = {
"Authorization": f"Bearer {OPENCLAW_TOKEN}",
"Content-Type": "application/json"
}
response = await client.post(
f"{OPENCLAW_GATEWAY_URL}/tools/invoke",
json=payload,
headers=headers
)
result = response.json() if response.status_code == 200 else None
if result and result.get("ok"):
spawn_info = result.get("result", {})
session_key = spawn_info.get("childSessionKey", None)
if session_key:
set_task_session(task_id, session_key)
print(f"✅ Spawned follow-up session for {agent_name} on task #{task_id}")
return result
else:
print(f"❌ Failed to spawn follow-up: {response.text}")
return None
except Exception as e:
print(f"❌ Failed to spawn follow-up session: {e}")
return None
def set_task_session(task_id: int, session_key: Optional[str]):
"""Set or clear the agent session key for a task."""
with get_db() as conn:
conn.execute(
"UPDATE tasks SET agent_session_key = ?, updated_at = ? WHERE id = ?",
(session_key, datetime.now().isoformat(), task_id)
)
conn.commit()
async def spawn_mentioned_agent(task_id: int, task_title: str, task_description: str,
mentioned_agent: str, mentioner: str, comment_content: str,
previous_context: str = ""):
"""Spawn a session for an @mentioned agent to contribute to a task they don't own.
For the main agent (Jarvis), sends to main session instead of spawning.
"""
if not OPENCLAW_ENABLED:
return None
agent_id = AGENT_TO_OPENCLAW_ID.get(mentioned_agent)
if not agent_id:
return None
# All agents (including main) now spawn subagent sessions
system_prompt = AGENT_SYSTEM_PROMPTS.get(agent_id, "")
mention_prompt = f"""# You've Been Tagged: Task #{task_id}
**{mentioner}** mentioned you on a task and needs your input.
## Task: {task_title}
{task_description or '(No description)'}
## What {mentioner} Said:
{comment_content}
## Previous Conversation:
{previous_context if previous_context else "(No prior comments)"}
## Your Role:
{system_prompt}
## Instructions:
1. Call start-work API: POST http://localhost:8080/api/tasks/{task_id}/start-work?agent={mentioned_agent}
2. Review the task from YOUR perspective ({mentioned_agent})
3. Post your findings/response as a comment: POST http://localhost:8080/api/tasks/{task_id}/comments
4. Call stop-work API: POST http://localhost:8080/api/tasks/{task_id}/stop-work?agent={mentioned_agent}
**Note:** You are NOT the assigned owner of this task. You're providing your expertise because you were tagged.
Do NOT move the task (no outcome param) — that's the owner's job.
{AGENT_GUARDRAILS}
Respond now with your assessment.
"""
try:
async with httpx.AsyncClient(timeout=60.0) as client:
payload = {
"tool": "sessions_spawn",
"args": {
"agentId": agent_id,
"task": mention_prompt,
"label": f"task-{task_id}-mention-{agent_id}",
"cleanup": "delete" # Cleanup after since they're just dropping in
}
}
headers = {
"Authorization": f"Bearer {OPENCLAW_TOKEN}",
"Content-Type": "application/json"
}
response = await client.post(
f"{OPENCLAW_GATEWAY_URL}/tools/invoke",
json=payload,
headers=headers
)
result = response.json() if response.status_code == 200 else None
if result and result.get("ok"):
spawn_info = result.get("result", {})
session_key = spawn_info.get("childSessionKey", "unknown")
# Post system comment about the spawn
async with httpx.AsyncClient(timeout=5.0) as comment_client:
await comment_client.post(
f"http://localhost:8080/api/tasks/{task_id}/comments",
json={
"agent": "System",
"content": f"📢 **{mentioned_agent}** was tagged by {mentioner} and is now reviewing this task."
}
)
print(f"✅ Spawned {mentioned_agent} for mention on task #{task_id}")
return result
else:
print(f"❌ Failed to spawn {mentioned_agent} for mention: {response.text}")
return None
except Exception as e:
print(f"❌ Failed to spawn mentioned agent: {e}")
return None
# Guardrails to inject into every sub-agent task
AGENT_GUARDRAILS = f"""
⚠️ MANDATORY CONSTRAINTS (Approved by User via Task Board assignment):
FILESYSTEM BOUNDARIES:
- ONLY access: {ALLOWED_PATHS}
- Everything else is FORBIDDEN without explicit authorization
FORBIDDEN ACTIONS (do not attempt without approval):
- Browser tool (except UX Manager on localhost only)
- git commit (requires safeword from User)
- Any action outside the authorized paths
WEB_FETCH (requires approval):
- You have web_fetch available but MUST ask User first
- Create an action item (type: question) explaining what URL you need and why
- Wait for User to resolve the action item before fetching
- Only fetch after explicit approval
COMPLIANCE CONTEXT:
- {COMPANY_NAME}, {COMPANY_CONTEXT}
- {COMPLIANCE_FRAMEWORKS}
- Security over convenience — always
COMMUNICATION & ESCALATION:
- Post comments on the task card to communicate
- Create action items for questions that need answers (type: question)
- Create action items for blockers (type: blocker)
ESCALATION CHAIN:
1. {MAIN_AGENT_NAME} (coordinator) monitors your action items and may answer if confident
2. If {MAIN_AGENT_NAME} answers, the item gets resolved and you can proceed
3. If {MAIN_AGENT_NAME} is unsure, they leave it for {HUMAN_SUPERVISOR_LABEL} to review
4. {HUMAN_SUPERVISOR_LABEL} has final authority on all decisions
TASK BOARD INTEGRATION:
- Use start-work API when beginning: POST http://localhost:8080/api/tasks/{{task_id}}/start-work?agent={{your_name}}
- Post updates as comments: POST http://localhost:8080/api/tasks/{{task_id}}/comments (json: {{"agent": "your_name", "content": "message"}})
- Create action items for questions: POST http://localhost:8080/api/tasks/{{task_id}}/action-items (json: {{"agent": "your_name", "content": "question", "item_type": "question"}})
- Move to Review when done: POST http://localhost:8080/api/tasks/{{task_id}}/move?status=Review&agent={{your_name}}&reason=...
- Use stop-work API when finished: POST http://localhost:8080/api/tasks/{{task_id}}/stop-work
REPORT FORMAT:
When complete, post a comment with your findings using this format:
## [Your Role] Report
**Task:** [task title]
**Verdict:** ✅ APPROVED / ⚠️ CONCERNS / 🛑 BLOCKED
### Findings
- [SEVERITY] Issue description
### Summary
[1-2 sentence assessment]
"""
AGENT_SYSTEM_PROMPTS = {
"main": f"""You are {MAIN_AGENT_NAME}, the primary coordinator for {COMPANY_NAME}.
Your focus:
- General task implementation and coordination
- Code writing and debugging
- Cross-cutting concerns that don't fit specialist roles
- Synthesizing input from other agents
- Direct implementation work
Project: {PROJECT_NAME}
You're the hands-on executor. When assigned a task, dig in and get it done.""",
"architect": f"""You are the Architect for {COMPANY_NAME}.
Your focus:
- System design and architectural patterns
- Scalability and performance implications
- Technical trade-offs and recommendations
- Integration architecture
- Database design and data modeling
Project: {PROJECT_NAME}
Be concise. Flag concerns with severity (CRITICAL/HIGH/MEDIUM/LOW).""",
"security-auditor": f"""You are the Security Auditor for {COMPANY_NAME}.
Your focus:
- SOC2 Trust Services Criteria (Security, Availability, Confidentiality, Privacy)
- HIPAA compliance (PHI handling, access controls, audit logging)
- CIS Controls benchmarks
- OWASP Top 10 vulnerabilities
- Secure credential storage and handling
- Tenant data isolation (multi-tenant SaaS)
NON-NEGOTIABLE: Security over convenience. Always.
Rate findings: CRITICAL (blocks deploy) / HIGH / MEDIUM / LOW""",
"code-reviewer": f"""You are the Code Reviewer for {COMPANY_NAME}.
Your focus:
- Code quality and best practices
- DRY, SOLID principles
- Error handling and edge cases
- Performance considerations
- Code readability and maintainability
- Test coverage gaps
Project: {PROJECT_NAME}
Format: MUST FIX / SHOULD FIX / CONSIDER / NICE TO HAVE""",
"ux-manager": f"""You are the UX Manager for {COMPANY_NAME}.
Your focus:
- User flow clarity and efficiency
- Error message helpfulness
- Form design and validation feedback
- UI consistency across the platform
- Accessibility basics
- Onboarding experience
Project: {PROJECT_NAME}
BROWSER ACCESS (localhost only):
You have browser access to review the app UI. Use it to:
- Take snapshots of pages to analyze layout, spacing, colors
- Check user flows and navigation
- Verify form designs and error states
- Assess overall visual consistency
ALLOWED URLs (localhost only):
- http://localhost:* (any port)
- http://127.0.0.1:*
DO NOT navigate to any external URLs. Your browser access is strictly for reviewing the local app."""
}
async def spawn_agent_session(task_id: int, task_title: str, task_description: str, agent_name: str):
"""Spawn a OPENCLAW sub-agent session for a task via tools/invoke API."""
if not OPENCLAW_ENABLED:
return None
agent_id = AGENT_TO_OPENCLAW_ID.get(agent_name)
if not agent_id:
return None # Don't spawn for unknown agents
# Note: Main agent (Jarvis) CAN spawn subagents now - no special case
# Build the task prompt with guardrails
system_prompt = AGENT_SYSTEM_PROMPTS.get(agent_id, "")
task_prompt = f"""# Task Assignment from RIZQ Task Board (Approved by {HUMAN_SUPERVISOR_LABEL})
**Task #{task_id}:** {task_title}
**Description:**
{task_description or 'No description provided.'}
{AGENT_GUARDRAILS}
## Your Role
{system_prompt}
---
## Instructions
1. Call start-work API: POST http://localhost:8080/api/tasks/{task_id}/start-work?agent={agent_name}
- This auto-moves the card to "In Progress" if needed
2. Analyze the task thoroughly
3. Post your findings as a comment on the task
4. When done, call stop-work with outcome: POST http://localhost:8080/api/tasks/{task_id}/stop-work?agent={agent_name}&outcome=review&reason=<summary>
- Use outcome=review when work is complete (auto-moves to Review)
- Use outcome=blocked&reason=<why> if you need input (auto-moves to Blocked)
## IMPORTANT: Stay Available
After posting your findings, **remain available for follow-up questions**. User may reply with questions or requests for clarification. When you receive a message starting with "💬 **User replied**", respond thoughtfully and post your response as a comment on the task.
Your session will automatically end when User marks the task as Done.
Begin now.
"""
try:
async with httpx.AsyncClient(timeout=60.0) as client:
# Use OPENCLAW's tools/invoke API to spawn sub-agent directly
payload = {
"tool": "sessions_spawn",
"args": {
"agentId": agent_id,
"task": task_prompt,
"label": f"task-{task_id}",
"cleanup": "keep"
}
}
headers = {
"Authorization": f"Bearer {OPENCLAW_TOKEN}",
"Content-Type": "application/json"
}
response = await client.post(
f"{OPENCLAW_GATEWAY_URL}/tools/invoke",
json=payload,
headers=headers
)
result = response.json() if response.status_code == 200 else None
if result and result.get("ok"):
print(f"✅ Spawned {agent_name} ({agent_id}) for task #{task_id}")
# Add a comment to the task noting the agent was spawned
spawn_info = result.get("result", {})
run_id = spawn_info.get("runId", "unknown")
session_key = spawn_info.get("childSessionKey", None)
# Save session key to database for follow-up messages
if session_key:
set_task_session(task_id, session_key)
async with httpx.AsyncClient(timeout=5.0) as comment_client:
await comment_client.post(
f"http://localhost:8080/api/tasks/{task_id}/comments",
json={
"agent": "System",
"content": f"🤖 **{agent_name}** agent spawned automatically.\n\nSession: `{session_key or 'unknown'}`\nRun ID: `{run_id}`\n\n💬 *Reply to this task and the agent will respond.*"
}
)
return result
else:
print(f"❌ Failed to spawn {agent_name}: {response.text}")
return None
except Exception as e:
print(f"❌ Failed to spawn agent session: {e}")
return None
# =============================================================================
# WEBSOCKET MANAGER
# =============================================================================
class ConnectionManager:
"""Manage WebSocket connections for live updates."""
def __init__(self):
self.active_connections: Set[WebSocket] = set()
async def connect(self, websocket: WebSocket):
await websocket.accept()
self.active_connections.add(websocket)
def disconnect(self, websocket: WebSocket):
self.active_connections.discard(websocket)
async def broadcast(self, message: dict):
"""Send update to all connected clients."""
dead = set()
for connection in self.active_connections:
try:
await connection.send_json(message)
except:
dead.add(connection)
self.active_connections -= dead
manager = ConnectionManager()
# =============================================================================
# DATABASE
# =============================================================================
def init_db():
"""Initialize the database."""
with get_db() as conn:
conn.execute("""
CREATE TABLE IF NOT EXISTS tasks (
id INTEGER PRIMARY KEY AUTOINCREMENT,
title TEXT NOT NULL,
description TEXT DEFAULT '',
status TEXT DEFAULT 'Backlog',
priority TEXT DEFAULT 'Medium',
agent TEXT DEFAULT 'Unassigned',
due_date TEXT,
created_at TEXT NOT NULL,
updated_at TEXT NOT NULL,
board TEXT DEFAULT 'tasks'
)
""")
conn.execute("""
CREATE TABLE IF NOT EXISTS activity_log (
id INTEGER PRIMARY KEY AUTOINCREMENT,
task_id INTEGER,
action TEXT NOT NULL,
agent TEXT,
details TEXT,
timestamp TEXT NOT NULL
)
""")
conn.execute("""
CREATE TABLE IF NOT EXISTS comments (
id INTEGER PRIMARY KEY AUTOINCREMENT,
task_id INTEGER NOT NULL,
agent TEXT NOT NULL,
content TEXT NOT NULL,
created_at TEXT NOT NULL
)
""")
conn.execute("""
CREATE TABLE IF NOT EXISTS action_items (
id INTEGER PRIMARY KEY AUTOINCREMENT,
task_id INTEGER NOT NULL,
comment_id INTEGER,
agent TEXT NOT NULL,
content TEXT NOT NULL,
item_type TEXT DEFAULT 'question',
resolved INTEGER DEFAULT 0,
created_at TEXT NOT NULL,
resolved_at TEXT
)
""")
# Add working_agent column if it doesn't exist
try:
conn.execute("ALTER TABLE tasks ADD COLUMN working_agent TEXT DEFAULT NULL")
except:
pass # Column already exists
# Add agent_session_key column for persistent agent sessions
try:
conn.execute("ALTER TABLE tasks ADD COLUMN agent_session_key TEXT DEFAULT NULL")
except:
pass # Column already exists
# Add archived column to action_items
try:
conn.execute("ALTER TABLE action_items ADD COLUMN archived INTEGER DEFAULT 0")
except:
pass # Column already exists
# Chat messages table for persistent command bar history
conn.execute("""
CREATE TABLE IF NOT EXISTS chat_messages (
id INTEGER PRIMARY KEY AUTOINCREMENT,
session_key TEXT DEFAULT 'main',
role TEXT NOT NULL,
content TEXT NOT NULL,
attachments TEXT,
created_at TEXT NOT NULL
)
""")
# Add session_key column if upgrading from older schema
try:
conn.execute("ALTER TABLE chat_messages ADD COLUMN session_key TEXT DEFAULT 'main'")
except:
pass # Column already exists
# Deleted sessions table - to filter out from dropdown
conn.execute("""
CREATE TABLE IF NOT EXISTS deleted_sessions (
session_key TEXT PRIMARY KEY,
deleted_at TEXT NOT NULL
)
""")
conn.commit()
@contextmanager
def get_db():
"""Database connection context manager."""
conn = sqlite3.connect(DB_PATH)
conn.row_factory = sqlite3.Row
try:
yield conn
finally:
conn.close()
def log_activity(task_id: int, action: str, agent: str = None, details: str = None):
"""Log an activity."""
with get_db() as conn:
conn.execute(
"INSERT INTO activity_log (task_id, action, agent, details, timestamp) VALUES (?, ?, ?, ?, ?)",
(task_id, action, agent, details, datetime.now().isoformat())
)
conn.commit()
# =============================================================================
# MODELS
# =============================================================================
class TaskCreate(BaseModel):
title: str
description: str = ""
status: str = "Backlog"
priority: str = "Medium"
agent: str = "Unassigned"
due_date: Optional[str] = None
board: str = "tasks"
source_file: Optional[str] = None
source_ref: Optional[str] = None
class TaskUpdate(BaseModel):
title: Optional[str] = None
description: Optional[str] = None
status: Optional[str] = None
priority: Optional[str] = None
agent: Optional[str] = None
due_date: Optional[str] = None
source_file: Optional[str] = None
source_ref: Optional[str] = None
class Task(BaseModel):
id: int
title: str
description: str
status: str
priority: str
agent: str
due_date: Optional[str]
created_at: str
updated_at: str
board: str
source_file: Optional[str] = None
source_ref: Optional[str] = None
working_agent: Optional[str] = None
# =============================================================================
# APP
# =============================================================================
app = FastAPI(title="RIZQ Task Board", version="1.2.0")
# Restrict CORS to localhost origins only
ALLOWED_ORIGINS = [
"http://localhost:8080",
"http://127.0.0.1:8080",
"http://localhost:3000",
"http://127.0.0.1:3000",
]
app.add_middleware(
CORSMiddleware,
allow_origins=ALLOWED_ORIGINS,
allow_credentials=True,
allow_methods=["GET", "POST", "PATCH", "DELETE"],
allow_headers=["Authorization", "X-API-Key", "Content-Type"],
)
# IP Restriction Middleware
# Specific Docker IPs allowed (NOT blanket 172.x.x.x or 10.x.x.x)
ALLOWED_DOCKER_IPS = {
"172.20.200.59", # OpenClaw gateway IP (user's access)
"172.20.200.119", # Additional allowed IP (user's access)
"172.18.0.1", # Internal Docker bridge network (container-to-container)
}
class IPRestrictionMiddleware(BaseHTTPMiddleware):
"""Block requests from IPs not in the allowed list."""
async def dispatch(self, request: Request, call_next):
client_ip = request.client.host if request.client else None
# Always allow localhost
if client_ip in ALWAYS_ALLOWED_IPS:
return await call_next(request)
# Allow specific Docker IPs (NOT blanket ranges)
if client_ip in ALLOWED_DOCKER_IPS:
return await call_next(request)
# Check against allowed IPs from env
if client_ip in ALLOWED_IPS:
return await call_next(request)
# Block with clear message
print(f"🚫 Blocked request from {client_ip} - not in allowed IPs")
return PlainTextResponse(
f"Access denied. IP {client_ip} not authorized.",
status_code=403
)
app.add_middleware(IPRestrictionMiddleware)
# Initialize DB on startup
@app.on_event("startup")
def startup():
init_db()
# Serve static files
STATIC_PATH.mkdir(exist_ok=True)
app.mount("/static", StaticFiles(directory=STATIC_PATH), name="static")
# Serve data attachments (images uploaded via chat)
ATTACHMENTS_PATH = DATA_DIR / "attachments"
ATTACHMENTS_PATH.mkdir(exist_ok=True)
app.mount("/data/attachments", StaticFiles(directory=ATTACHMENTS_PATH), name="attachments")
@app.get("/")
def read_root():
"""Serve the Kanban UI."""
return FileResponse(STATIC_PATH / "index.html")
# =============================================================================
# WEBSOCKET ENDPOINT
# =============================================================================
@app.websocket("/ws")
async def websocket_endpoint(websocket: WebSocket):
"""WebSocket for live updates."""
await manager.connect(websocket)
try:
while True:
# Keep connection alive, wait for messages (ping/pong)
data = await websocket.receive_text()
# Echo back for ping
if data == "ping":
await websocket.send_text("pong")
except WebSocketDisconnect:
manager.disconnect(websocket)
# =============================================================================
# CONFIG ENDPOINTS
# =============================================================================
@app.get("/api/config")
def get_config():
"""Get board configuration including branding."""
return {
"agents": AGENTS,
"statuses": STATUSES,
"priorities": PRIORITIES,
"branding": {
"mainAgentName": MAIN_AGENT_NAME,
"mainAgentEmoji": MAIN_AGENT_EMOJI,
"humanName": HUMAN_NAME,
"humanSupervisorLabel": HUMAN_SUPERVISOR_LABEL,
"boardTitle": BOARD_TITLE,
}
}
# =============================================================================
# TASK ENDPOINTS
# =============================================================================
@app.get("/api/tasks", response_model=List[Task])
def list_tasks(board: str = "tasks", agent: str = None, status: str = None):
"""List all tasks with optional filters."""
with get_db() as conn:
query = "SELECT * FROM tasks WHERE board = ?"
params = [board]
if agent:
query += " AND agent = ?"
params.append(agent)
if status:
query += " AND status = ?"
params.append(status)
query += " ORDER BY CASE priority WHEN 'Critical' THEN 1 WHEN 'High' THEN 2 WHEN 'Medium' THEN 3 ELSE 4 END, created_at DESC"
rows = conn.execute(query, params).fetchall()
return [dict(row) for row in rows]
@app.get("/api/tasks/{task_id}", response_model=Task)
def get_task(task_id: int):
"""Get a single task."""
with get_db() as conn:
row = conn.execute("SELECT * FROM tasks WHERE id = ?", (task_id,)).fetchone()
if not row:
raise HTTPException(status_code=404, detail="Task not found")
return dict(row)
@app.post("/api/tasks", response_model=Task)
async def create_task(task: TaskCreate):
"""Create a new task."""
now = datetime.now().isoformat()
with get_db() as conn:
cursor = conn.execute(
"""INSERT INTO tasks (title, description, status, priority, agent, due_date, created_at, updated_at, board, source_file, source_ref)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)""",
(task.title, task.description, task.status, task.priority, task.agent, task.due_date, now, now, task.board, task.source_file, task.source_ref)
)
conn.commit()
task_id = cursor.lastrowid
log_activity(task_id, "created", task.agent, f"Created: {task.title}")
row = conn.execute("SELECT * FROM tasks WHERE id = ?", (task_id,)).fetchone()
result = dict(row)
# Broadcast to all clients
await manager.broadcast({"type": "task_created", "task": result})
return result
@app.patch("/api/tasks/{task_id}", response_model=Task)
async def update_task(task_id: int, updates: TaskUpdate):
"""Update a task."""
with get_db() as conn:
# Get current task
row = conn.execute("SELECT * FROM tasks WHERE id = ?", (task_id,)).fetchone()
if not row:
raise HTTPException(status_code=404, detail="Task not found")
current = dict(row)
changes = []
# Build update
update_fields = []
params = []
for field in ["title", "description", "status", "priority", "agent", "due_date", "source_file", "source_ref"]:
new_value = getattr(updates, field)
if new_value is not None and new_value != current[field]:
update_fields.append(f"{field} = ?")
params.append(new_value)
changes.append(f"{field}: {current[field]} → {new_value}")
if update_fields:
update_fields.append("updated_at = ?")
params.append(datetime.now().isoformat())
params.append(task_id)
conn.execute(f"UPDATE tasks SET {', '.join(update_fields)} WHERE id = ?", params)
conn.commit()
log_activity(task_id, "updated", updates.agent or current["agent"], "; ".join(changes))
row = conn.execute("SELECT * FROM tasks WHERE id = ?", (task_id,)).fetchone()
result = dict(row)
# Broadcast to all clients
await manager.broadcast({"type": "task_updated", "task": result})
return result
@app.delete("/api/tasks/{task_id}")
async def delete_task(task_id: int):
"""Delete a task."""
with get_db() as conn:
row = conn.execute("SELECT * FROM tasks WHERE id = ?", (task_id,)).fetchone()
if not row:
raise HTTPException(status_code=404, detail="Task not found")
conn.execute("DELETE FROM tasks WHERE id = ?", (task_id,))
conn.commit()
log_activity(task_id, "deleted", None, f"Deleted: {row['title']}")
# Broadcast to all clients
await manager.broadcast({"type": "task_deleted", "task_id": task_id})
return {"status": "deleted", "id": task_id}