-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtaskboard.py
More file actions
3745 lines (3436 loc) · 152 KB
/
taskboard.py
File metadata and controls
3745 lines (3436 loc) · 152 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
"""
AgentForge - macOS App
A kanban-style task board for orchestrating AI coding agents with cron scheduling and delayed execution.
"""
import json
import logging
import os
import secrets
import signal
import sqlite3
import subprocess
import sys
import threading
import time
from contextlib import contextmanager
from dataclasses import dataclass, field
from datetime import datetime, timedelta
from enum import Enum
from http.server import BaseHTTPRequestHandler, HTTPServer
from typing import Callable, Optional
from urllib.parse import parse_qs, urlparse
from croniter import croniter
from taskboard_bus import (
BusAwareSchedulerMixin,
MessageBus,
OutboundMessageType,
UIChannel,
)
log_level = os.environ.get("AGENTFORGE_LOG_LEVEL", "INFO").upper()
logging.basicConfig(
level=getattr(logging, log_level, logging.INFO),
format="%(asctime)s %(levelname)s %(name)s: %(message)s",
datefmt="%Y-%m-%d %H:%M:%S",
)
logger = logging.getLogger("agentforge")
try:
from channels.feishu_channel import FeishuChannel
FEISHU_CHANNEL_AVAILABLE = True
except ImportError:
FEISHU_CHANNEL_AVAILABLE = False
FeishuChannel = None
try:
from channels.telegram_channel import create_telegram_channel
TELEGRAM_CHANNEL_AVAILABLE = True
except ImportError:
TELEGRAM_CHANNEL_AVAILABLE = False
create_telegram_channel = None
try:
from channels.slack_channel import SlackChannel
SLACK_CHANNEL_AVAILABLE = True
except ImportError:
SLACK_CHANNEL_AVAILABLE = False
SlackChannel = None
try:
from channels.weixin_channel import WeixinChannel
WEIXIN_CHANNEL_AVAILABLE = True
except ImportError:
WEIXIN_CHANNEL_AVAILABLE = False
WeixinChannel = None
# ──────────────────────────── Helpers ────────────────────────────
def _get_env() -> dict:
"""Return os.environ augmented with common macOS tool install paths.
Electron (and other GUI launchers) inherit a stripped PATH that often
misses npm globals, Homebrew, and ~/.local/bin.
"""
env = os.environ.copy()
home = os.path.expanduser("~")
extra = [
f"{home}/.local/bin",
"/usr/local/bin",
"/opt/homebrew/bin", # Apple-silicon Homebrew
"/usr/local/opt/node/bin",
f"{home}/.npm/bin",
f"{home}/.nvm/current/bin",
"/usr/bin",
"/bin",
]
current = env.get("PATH", "")
env["PATH"] = ":".join(p for p in extra if p not in current) + (
f":{current}" if current else ""
)
return env
def _parse_comparable_datetime(value: Optional[str]) -> Optional[datetime]:
"""Parse ISO datetimes and collapse aware values into local naive datetimes.
The app historically stored naive local timestamps, but the Electron UI can
submit offset-aware ISO strings for `scheduled_at`. Converting aware values
into the local timezone and stripping tzinfo keeps storage/comparisons
consistent with the rest of the backend while remaining backward compatible
with legacy rows.
"""
if not value:
return None
dt = datetime.fromisoformat(value)
if dt.tzinfo is not None:
return dt.astimezone().replace(tzinfo=None)
return dt
def _normalize_datetime_for_storage(value: Optional[str]) -> Optional[str]:
if value is None:
return None
try:
dt = _parse_comparable_datetime(value)
except ValueError:
return value
return dt.isoformat() if dt else None
def _build_weixin_channel_status(db, weixin_channel) -> dict:
weixin_status = (
weixin_channel.get_status_snapshot()
if weixin_channel and hasattr(weixin_channel, "get_status_snapshot")
else {}
)
runtime_account_id = weixin_status.get("account_id", "")
configured_account_id = db.get_setting("weixin_account_id", "")
return {
"enabled": db.get_setting("weixin_enabled", "false") == "true",
"configured": bool(weixin_status.get("configured", False)),
"running": bool(weixin_channel and getattr(weixin_channel, "_running", False)),
"default_working_dir": db.get_setting("weixin_default_working_dir", "~"),
"base_url": db.get_setting("weixin_base_url", "https://ilinkai.weixin.qq.com"),
"account_id": runtime_account_id or configured_account_id,
"login_status": weixin_status.get("login_status", "idle"),
"qr_code_url": weixin_status.get("qr_code_url", ""),
"last_error": weixin_status.get("last_error", ""),
"user_id": weixin_status.get("user_id", ""),
}
# ──────────────────────────── Models ────────────────────────────
class TaskStatus(str, Enum):
PENDING = "pending"
SCHEDULED = "scheduled"
RUNNING = "running"
COMPLETED = "completed"
FAILED = "failed"
CANCELLED = "cancelled"
BLOCKED = "blocked" # has unmet upstream dependencies
class ScheduleType(str, Enum):
IMMEDIATE = "immediate"
DELAYED = "delayed" # run after N seconds
SCHEDULED_AT = "scheduled_at" # run at a specific datetime
CRON = "cron" # recurring cron expression
class HeartbeatScheduleType(str, Enum):
CRON = "cron"
INTERVAL = "interval"
class HeartbeatDecisionType(str, Enum):
IDLE = "idle"
TRIGGER_TASK = "trigger_task"
RESUME_TASK = "resume_task"
NOTIFY_ONLY = "notify_only"
ERROR = "error"
@dataclass
class Task:
id: Optional[int] = None
title: str = ""
prompt: str = ""
working_dir: str = "."
status: TaskStatus = TaskStatus.PENDING
schedule_type: ScheduleType = ScheduleType.IMMEDIATE
cron_expr: Optional[str] = None # e.g. "*/30 * * * *"
delay_seconds: Optional[int] = None # e.g. 300
next_run_at: Optional[str] = None # ISO timestamp
last_run_at: Optional[str] = None
result: Optional[str] = None
error: Optional[str] = None
run_count: int = 0
max_runs: Optional[int] = None # None = unlimited for cron
created_at: Optional[str] = None
updated_at: Optional[str] = None
tags: str = "" # comma-separated
agent: str = "claude"
question: Optional[str] = None # question the agent asked
answer: Optional[str] = None # user's answer
session_id: Optional[str] = None # claude session id for --resume
prompt_images: list = field(default_factory=list) # [{media_type, data, name}]
image_paths: list = field(default_factory=list) # list of local image file paths
dag_id: Optional[str] = None # optional DAG workflow group label
feishu_root_msg_id: Optional[str] = None # Feishu root message_id that created this task
@dataclass
class Heartbeat:
id: Optional[int] = None
name: str = ""
enabled: bool = True
working_dir: str = "."
schedule_type: HeartbeatScheduleType = HeartbeatScheduleType.INTERVAL
cron_expr: Optional[str] = None
interval_seconds: Optional[int] = None
check_prompt: str = ""
action_prompt_template: str = ""
default_agent: str = "claude"
cooldown_seconds: int = 0
next_run_at: Optional[str] = None
last_tick_at: Optional[str] = None
last_decision: Optional[str] = None
last_error: Optional[str] = None
last_triggered_at: Optional[str] = None
last_dedupe_key: Optional[str] = None
created_at: Optional[str] = None
updated_at: Optional[str] = None
# ──────────────────────────── Database ────────────────────────────
class TaskDB:
def __init__(self, db_path: str = "~/.agentforge/tasks.db"):
self.db_path = os.path.expanduser(db_path)
os.makedirs(os.path.dirname(self.db_path), exist_ok=True)
self.conn = sqlite3.connect(self.db_path, check_same_thread=False)
self.conn.row_factory = sqlite3.Row
self.lock = threading.RLock() # RLock allows transaction() to nest with per-method locking
self._init_db()
def _init_db(self):
self.conn.execute("""
CREATE TABLE IF NOT EXISTS tasks (
id INTEGER PRIMARY KEY AUTOINCREMENT,
title TEXT NOT NULL,
prompt TEXT NOT NULL,
working_dir TEXT DEFAULT '.',
status TEXT DEFAULT 'pending',
schedule_type TEXT DEFAULT 'immediate',
cron_expr TEXT,
delay_seconds INTEGER,
next_run_at TEXT,
last_run_at TEXT,
result TEXT,
error TEXT,
run_count INTEGER DEFAULT 0,
max_runs INTEGER,
created_at TEXT DEFAULT (datetime('now')),
updated_at TEXT DEFAULT (datetime('now')),
tags TEXT DEFAULT '',
agent TEXT DEFAULT 'claude',
question TEXT,
answer TEXT
)
""")
# Migration: add agent column if it doesn't exist (for existing DBs)
try:
self.conn.execute("ALTER TABLE tasks ADD COLUMN agent TEXT DEFAULT 'claude'")
self.conn.commit()
except sqlite3.OperationalError:
pass # Column already exists
# Migration: add question/answer columns
try:
self.conn.execute("ALTER TABLE tasks ADD COLUMN question TEXT")
self.conn.execute("ALTER TABLE tasks ADD COLUMN answer TEXT")
self.conn.commit()
except sqlite3.OperationalError:
pass # Columns already exist
# Migration: add session_id column
try:
self.conn.execute("ALTER TABLE tasks ADD COLUMN session_id TEXT")
self.conn.commit()
except sqlite3.OperationalError:
pass # Column already exists
# Migration: add prompt_images column
try:
self.conn.execute("ALTER TABLE tasks ADD COLUMN prompt_images TEXT DEFAULT '[]'")
self.conn.commit()
except sqlite3.OperationalError:
pass # Column already exists
# Migration: add image_paths column
try:
self.conn.execute("ALTER TABLE tasks ADD COLUMN image_paths TEXT DEFAULT '[]'")
self.conn.commit()
except sqlite3.OperationalError:
pass # Column already exists
# Migration: add notify_slack_channel column
try:
self.conn.execute("ALTER TABLE tasks ADD COLUMN notify_slack_channel TEXT")
self.conn.commit()
except sqlite3.OperationalError:
pass # Column already exists
# Migration: add notify_telegram_chat_id column
try:
self.conn.execute("ALTER TABLE tasks ADD COLUMN notify_telegram_chat_id TEXT")
self.conn.commit()
except sqlite3.OperationalError:
pass # Column already exists
self.conn.execute("""
CREATE TABLE IF NOT EXISTS settings (
key TEXT PRIMARY KEY,
value TEXT
)
""")
self.conn.execute("""
CREATE TABLE IF NOT EXISTS task_runs (
id INTEGER PRIMARY KEY AUTOINCREMENT,
task_id INTEGER NOT NULL,
started_at TEXT DEFAULT (datetime('now')),
finished_at TEXT,
status TEXT,
result TEXT,
error TEXT,
raw_output TEXT,
FOREIGN KEY (task_id) REFERENCES tasks(id)
)
""")
# Migration: add raw_output column to task_runs
try:
self.conn.execute("ALTER TABLE task_runs ADD COLUMN raw_output TEXT")
self.conn.commit()
except sqlite3.OperationalError:
pass # Column already exists
self.conn.execute("""
CREATE TABLE IF NOT EXISTS heartbeats (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
enabled INTEGER NOT NULL DEFAULT 1,
working_dir TEXT DEFAULT '.',
schedule_type TEXT NOT NULL,
cron_expr TEXT,
interval_seconds INTEGER,
check_prompt TEXT NOT NULL,
action_prompt_template TEXT DEFAULT '',
default_agent TEXT DEFAULT 'claude',
cooldown_seconds INTEGER DEFAULT 0,
next_run_at TEXT,
last_tick_at TEXT,
last_decision TEXT,
last_error TEXT,
last_triggered_at TEXT,
last_dedupe_key TEXT,
created_at TEXT DEFAULT (datetime('now')),
updated_at TEXT DEFAULT (datetime('now'))
)
""")
self.conn.execute("""
CREATE INDEX IF NOT EXISTS idx_heartbeats_next_run
ON heartbeats(enabled, next_run_at)
""")
self.conn.execute("""
CREATE TABLE IF NOT EXISTS heartbeat_ticks (
id INTEGER PRIMARY KEY AUTOINCREMENT,
heartbeat_id INTEGER NOT NULL,
started_at TEXT NOT NULL,
finished_at TEXT,
status TEXT NOT NULL,
decision_type TEXT,
decision_payload TEXT,
task_id INTEGER,
raw_output TEXT,
error TEXT,
FOREIGN KEY (heartbeat_id) REFERENCES heartbeats(id),
FOREIGN KEY (task_id) REFERENCES tasks(id)
)
""")
self.conn.execute("""
CREATE INDEX IF NOT EXISTS idx_heartbeat_ticks_heartbeat_id
ON heartbeat_ticks(heartbeat_id, started_at DESC)
""")
try:
self.conn.execute("ALTER TABLE heartbeat_ticks ADD COLUMN raw_output TEXT")
self.conn.commit()
except sqlite3.OperationalError:
pass # Column already exists
self.conn.execute("""
CREATE TABLE IF NOT EXISTS heartbeat_dedup (
id INTEGER PRIMARY KEY AUTOINCREMENT,
heartbeat_id INTEGER NOT NULL,
dedupe_key TEXT NOT NULL,
task_id INTEGER,
triggered_at TEXT NOT NULL,
FOREIGN KEY (heartbeat_id) REFERENCES heartbeats(id),
FOREIGN KEY (task_id) REFERENCES tasks(id),
UNIQUE(heartbeat_id, dedupe_key)
)
""")
self.conn.execute("""
CREATE INDEX IF NOT EXISTS idx_heartbeat_dedup_heartbeat_id
ON heartbeat_dedup(heartbeat_id, triggered_at DESC)
""")
# Create task_output_events table for structured output recording
self.conn.execute("""
CREATE TABLE IF NOT EXISTS task_output_events (
id INTEGER PRIMARY KEY AUTOINCREMENT,
task_id INTEGER NOT NULL,
run_id INTEGER NOT NULL,
event_type TEXT NOT NULL,
content TEXT NOT NULL,
timestamp TEXT DEFAULT (datetime('now')),
FOREIGN KEY (task_id) REFERENCES tasks(id),
FOREIGN KEY (run_id) REFERENCES task_runs(id)
)
""")
# Create indexes for performance
self.conn.execute("""
CREATE INDEX IF NOT EXISTS idx_task_output_events_task_id
ON task_output_events(task_id)
""")
self.conn.execute("""
CREATE INDEX IF NOT EXISTS idx_task_output_events_run_id
ON task_output_events(run_id)
""")
self.conn.execute("""
CREATE INDEX IF NOT EXISTS idx_task_output_events_timestamp
ON task_output_events(timestamp)
""")
# DAG dependency table
self.conn.execute("""
CREATE TABLE IF NOT EXISTS task_dependencies (
id INTEGER PRIMARY KEY AUTOINCREMENT,
task_id INTEGER NOT NULL,
depends_on_task_id INTEGER NOT NULL,
inject_result INTEGER DEFAULT 0,
created_at TEXT DEFAULT (datetime('now')),
FOREIGN KEY (task_id) REFERENCES tasks(id),
FOREIGN KEY (depends_on_task_id) REFERENCES tasks(id),
UNIQUE(task_id, depends_on_task_id)
)
""")
self.conn.execute("""
CREATE INDEX IF NOT EXISTS idx_task_deps_task_id
ON task_dependencies(task_id)
""")
self.conn.execute("""
CREATE INDEX IF NOT EXISTS idx_task_deps_depends_on
ON task_dependencies(depends_on_task_id)
""")
# Migration: add dag_id column to tasks
try:
self.conn.execute("ALTER TABLE tasks ADD COLUMN dag_id TEXT")
self.conn.commit()
except sqlite3.OperationalError:
pass # Column already exists
# Migration: add feishu_root_msg_id column for post-restart resume
try:
self.conn.execute("ALTER TABLE tasks ADD COLUMN feishu_root_msg_id TEXT")
self.conn.commit()
except sqlite3.OperationalError:
pass # Column already exists
self.conn.commit()
# On startup, reset any tasks left in 'running' state — they were
# interrupted by a process kill (e.g. hot reload) and will never
# self-transition to completed/failed without this reset.
now = datetime.now().isoformat()
self.conn.execute(
"""
UPDATE tasks
SET status = 'failed',
error = 'Interrupted: process was restarted while task was running',
updated_at = ?
WHERE status = 'running'
""",
(now,),
)
# Also close out any open task_runs rows that have no finished_at
self.conn.execute(
"""
UPDATE task_runs
SET status = 'failed',
finished_at = ?,
error = 'Interrupted: process was restarted while task was running'
WHERE finished_at IS NULL
""",
(now,),
)
self.conn.commit()
@contextmanager
def transaction(self):
"""Acquire the DB lock and run statements in an explicit transaction.
On success the transaction is committed; on any exception it is rolled
back and the exception re-raised. Callers must NOT call commit() or
rollback() themselves inside this block.
"""
with self.lock:
self.conn.execute("BEGIN")
try:
yield self.conn
self.conn.execute("COMMIT")
except Exception:
self.conn.execute("ROLLBACK")
raise
def add_task(self, task: Task) -> int:
with self.lock:
now = datetime.now().isoformat()
logger.debug(f"add_task called with image_paths: {task.image_paths}")
image_paths_json = json.dumps(task.image_paths, ensure_ascii=False)
logger.debug(f"image_paths JSON: {image_paths_json}")
cur = self.conn.execute(
"""
INSERT INTO tasks (title, prompt, working_dir, status, schedule_type,
cron_expr, delay_seconds, next_run_at, max_runs, created_at, updated_at, tags, agent, prompt_images, image_paths, dag_id, feishu_root_msg_id)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
""",
(
task.title,
task.prompt,
task.working_dir,
task.status.value,
task.schedule_type.value,
task.cron_expr,
task.delay_seconds,
task.next_run_at,
task.max_runs,
now,
now,
task.tags,
task.agent,
json.dumps(task.prompt_images, ensure_ascii=False),
image_paths_json,
task.dag_id,
task.feishu_root_msg_id,
),
)
self.conn.commit()
task_id = cur.lastrowid
logger.debug(f"Task {task_id} inserted with image_paths")
return task_id
def get_task_by_feishu_root_msg(self, root_msg_id: str) -> Optional[dict]:
"""Look up the most recent task created from a given Feishu root message ID."""
with self.lock:
row = self.conn.execute(
"SELECT * FROM tasks WHERE feishu_root_msg_id = ? ORDER BY id DESC LIMIT 1",
(root_msg_id,),
).fetchone()
return dict(row) if row else None
def get_setting(self, key: str, default: str = None) -> Optional[str]:
with self.lock:
row = self.conn.execute("SELECT value FROM settings WHERE key = ?", (key,)).fetchone()
return row["value"] if row else default
def set_setting(self, key: str, value: str):
with self.lock:
self.conn.execute(
"INSERT OR REPLACE INTO settings (key, value) VALUES (?, ?)", (key, value)
)
self.conn.commit()
def _deserialize_heartbeat(self, row) -> dict:
d = dict(row)
d["enabled"] = bool(d.get("enabled"))
return d
def _compute_heartbeat_next_run_at(
self, heartbeat: Heartbeat, now: Optional[datetime] = None
) -> str:
now = now or datetime.now()
if heartbeat.schedule_type == HeartbeatScheduleType.CRON:
if not heartbeat.cron_expr:
raise ValueError("cron heartbeat requires cron_expr")
return croniter(heartbeat.cron_expr, now).get_next(datetime).isoformat()
if heartbeat.schedule_type == HeartbeatScheduleType.INTERVAL:
if not heartbeat.interval_seconds or heartbeat.interval_seconds <= 0:
raise ValueError("interval heartbeat requires interval_seconds > 0")
return (now + timedelta(seconds=int(heartbeat.interval_seconds))).isoformat()
raise ValueError(f"Unsupported heartbeat schedule_type: {heartbeat.schedule_type}")
def add_heartbeat(self, heartbeat: Heartbeat) -> int:
with self.lock:
now = datetime.now().isoformat()
if heartbeat.next_run_at is None:
heartbeat.next_run_at = self._compute_heartbeat_next_run_at(
heartbeat, datetime.now()
)
cur = self.conn.execute(
"""
INSERT INTO heartbeats (
name, enabled, working_dir, schedule_type, cron_expr,
interval_seconds, check_prompt, action_prompt_template,
default_agent, cooldown_seconds, next_run_at, last_tick_at,
last_decision, last_error, last_triggered_at, last_dedupe_key,
created_at, updated_at
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
""",
(
heartbeat.name,
1 if heartbeat.enabled else 0,
heartbeat.working_dir,
heartbeat.schedule_type.value,
heartbeat.cron_expr,
heartbeat.interval_seconds,
heartbeat.check_prompt,
heartbeat.action_prompt_template,
heartbeat.default_agent,
heartbeat.cooldown_seconds,
heartbeat.next_run_at,
heartbeat.last_tick_at,
heartbeat.last_decision,
heartbeat.last_error,
heartbeat.last_triggered_at,
heartbeat.last_dedupe_key,
now,
now,
),
)
self.conn.commit()
return cur.lastrowid
ALLOWED_HEARTBEAT_COLUMNS = frozenset(
{
"name",
"enabled",
"working_dir",
"schedule_type",
"cron_expr",
"interval_seconds",
"check_prompt",
"action_prompt_template",
"default_agent",
"cooldown_seconds",
"next_run_at",
"last_tick_at",
"last_decision",
"last_error",
"last_triggered_at",
"last_dedupe_key",
"updated_at",
}
)
def update_heartbeat(self, heartbeat_id: int, **kwargs):
invalid = set(kwargs) - self.ALLOWED_HEARTBEAT_COLUMNS
if invalid:
raise ValueError(f"Invalid heartbeat column(s): {invalid}")
with self.lock:
kwargs["updated_at"] = datetime.now().isoformat()
sets = ", ".join(f"{k} = ?" for k in kwargs)
vals = list(kwargs.values()) + [heartbeat_id]
self.conn.execute(f"UPDATE heartbeats SET {sets} WHERE id = ?", vals)
self.conn.commit()
def get_heartbeat(self, heartbeat_id: int) -> Optional[dict]:
with self.lock:
row = self.conn.execute(
"SELECT * FROM heartbeats WHERE id = ?", (heartbeat_id,)
).fetchone()
return self._deserialize_heartbeat(row) if row else None
def get_all_heartbeats(self) -> list[dict]:
with self.lock:
rows = self.conn.execute("SELECT * FROM heartbeats ORDER BY created_at DESC").fetchall()
return [self._deserialize_heartbeat(r) for r in rows]
def get_due_heartbeats(self) -> list[dict]:
with self.lock:
rows = self.conn.execute(
"""
SELECT * FROM heartbeats
WHERE enabled = 1
AND next_run_at IS NOT NULL
"""
).fetchall()
now = datetime.now()
due = []
for row in rows:
heartbeat = self._deserialize_heartbeat(row)
try:
next_run_at = _parse_comparable_datetime(heartbeat.get("next_run_at"))
except ValueError:
continue
if next_run_at and next_run_at <= now:
due.append(heartbeat)
return due
def delete_heartbeat(self, heartbeat_id: int):
with self.transaction():
self.conn.execute("DELETE FROM heartbeat_ticks WHERE heartbeat_id = ?", (heartbeat_id,))
self.conn.execute("DELETE FROM heartbeat_dedup WHERE heartbeat_id = ?", (heartbeat_id,))
self.conn.execute("DELETE FROM heartbeats WHERE id = ?", (heartbeat_id,))
def add_heartbeat_tick(self, heartbeat_id: int) -> int:
with self.lock:
cur = self.conn.execute(
"""
INSERT INTO heartbeat_ticks (heartbeat_id, started_at, status)
VALUES (?, ?, 'running')
""",
(heartbeat_id, datetime.now().isoformat()),
)
self.conn.commit()
return cur.lastrowid
def finish_heartbeat_tick(
self,
tick_id: int,
status: str,
decision_type: Optional[str] = None,
decision_payload: Optional[dict] = None,
task_id: Optional[int] = None,
raw_output: Optional[str] = None,
error: Optional[str] = None,
):
payload_json = (
json.dumps(decision_payload, ensure_ascii=False)
if decision_payload is not None
else None
)
with self.lock:
self.conn.execute(
"""
UPDATE heartbeat_ticks
SET finished_at = ?, status = ?, decision_type = ?, decision_payload = ?, task_id = ?, raw_output = ?, error = ?
WHERE id = ?
""",
(
datetime.now().isoformat(),
status,
decision_type,
payload_json,
task_id,
raw_output,
error,
tick_id,
),
)
self.conn.commit()
def get_heartbeat_ticks(self, heartbeat_id: int, limit: int = 50) -> list[dict]:
with self.lock:
rows = self.conn.execute(
"""
SELECT * FROM heartbeat_ticks
WHERE heartbeat_id = ?
ORDER BY started_at DESC
LIMIT ?
""",
(heartbeat_id, limit),
).fetchall()
return [dict(r) for r in rows]
def get_heartbeat_tick(self, heartbeat_id: int, tick_id: int) -> Optional[dict]:
with self.lock:
row = self.conn.execute(
"""
SELECT * FROM heartbeat_ticks
WHERE heartbeat_id = ? AND id = ?
""",
(heartbeat_id, tick_id),
).fetchone()
return dict(row) if row else None
def get_latest_heartbeat_tick(self, heartbeat_id: int) -> Optional[dict]:
with self.lock:
row = self.conn.execute(
"""
SELECT * FROM heartbeat_ticks
WHERE heartbeat_id = ?
ORDER BY started_at DESC
LIMIT 1
""",
(heartbeat_id,),
).fetchone()
return dict(row) if row else None
def get_heartbeat_dedup(self, heartbeat_id: int, dedupe_key: str) -> Optional[dict]:
with self.lock:
row = self.conn.execute(
"""
SELECT * FROM heartbeat_dedup
WHERE heartbeat_id = ? AND dedupe_key = ?
""",
(heartbeat_id, dedupe_key),
).fetchone()
return dict(row) if row else None
def upsert_heartbeat_dedup(self, heartbeat_id: int, dedupe_key: str, task_id: Optional[int]):
with self.lock:
now = datetime.now().isoformat()
self.conn.execute(
"""
INSERT INTO heartbeat_dedup (heartbeat_id, dedupe_key, task_id, triggered_at)
VALUES (?, ?, ?, ?)
ON CONFLICT(heartbeat_id, dedupe_key)
DO UPDATE SET task_id = excluded.task_id, triggered_at = excluded.triggered_at
""",
(heartbeat_id, dedupe_key, task_id, now),
)
self.conn.commit()
ALLOWED_TASK_COLUMNS = frozenset(
{
"title",
"prompt",
"working_dir",
"status",
"schedule_type",
"cron_expr",
"delay_seconds",
"next_run_at",
"last_run_at",
"result",
"error",
"run_count",
"max_runs",
"updated_at",
"tags",
"agent",
"question",
"answer",
"session_id",
"prompt_images",
"image_paths",
"dag_id",
}
)
def update_task(self, task_id: int, **kwargs):
invalid = set(kwargs) - self.ALLOWED_TASK_COLUMNS
if invalid:
raise ValueError(f"Invalid task column(s): {invalid}")
with self.lock:
if "next_run_at" in kwargs:
kwargs["next_run_at"] = _normalize_datetime_for_storage(kwargs["next_run_at"])
kwargs["updated_at"] = datetime.now().isoformat()
sets = ", ".join(f"{k} = ?" for k in kwargs)
vals = list(kwargs.values()) + [task_id]
self.conn.execute(f"UPDATE tasks SET {sets} WHERE id = ?", vals)
self.conn.commit()
def _deserialize_task(self, row) -> dict:
d = dict(row)
# Deserialize prompt_images
raw = d.get("prompt_images")
if isinstance(raw, str):
try:
d["prompt_images"] = json.loads(raw)
except (json.JSONDecodeError, ValueError):
d["prompt_images"] = []
elif d.get("prompt_images") is None:
d["prompt_images"] = []
# Deserialize image_paths
raw_paths = d.get("image_paths")
if isinstance(raw_paths, str):
try:
d["image_paths"] = json.loads(raw_paths)
except (json.JSONDecodeError, ValueError):
d["image_paths"] = []
elif d.get("image_paths") is None:
d["image_paths"] = []
return d
def get_task(self, task_id: int) -> Optional[dict]:
with self.lock:
row = self.conn.execute("SELECT * FROM tasks WHERE id = ?", (task_id,)).fetchone()
return self._deserialize_task(row) if row else None
def get_all_tasks(self) -> list[dict]:
with self.lock:
rows = self.conn.execute("SELECT * FROM tasks ORDER BY created_at DESC").fetchall()
return [self._deserialize_task(r) for r in rows]
def get_due_tasks(self) -> list[dict]:
with self.lock:
rows = self.conn.execute(
"""
SELECT * FROM tasks
WHERE status IN ('pending', 'scheduled')
"""
).fetchall()
now = datetime.now()
due = []
for row in rows:
task = self._deserialize_task(row)
try:
next_run_at = _parse_comparable_datetime(task.get("next_run_at"))
except ValueError:
continue
if next_run_at is None or next_run_at <= now:
due.append(task)
return due
def add_run(self, task_id: int) -> int:
with self.lock:
cur = self.conn.execute(
"INSERT INTO task_runs (task_id, status) VALUES (?, 'running')", (task_id,)
)
self.conn.commit()
return cur.lastrowid
def finish_run(
self,
run_id: int,
status: str,
result: str = None,
error: str = None,
raw_output: str = None,
):
with self.lock:
self.conn.execute(
"""
UPDATE task_runs SET finished_at = datetime('now'),
status = ?, result = ?, error = ?, raw_output = ?
WHERE id = ?
""",
(status, result, error, raw_output, run_id),
)
self.conn.commit()
def finish_run_and_update_task(
self,
run_id: int,
run_status: str,
task_id: int,
task_updates: dict,
run_result: str = None,
run_error: str = None,
raw_output: str = None,
):
"""Atomically finish a run record and update the parent task in one transaction."""
task_updates = dict(task_updates)
task_updates["updated_at"] = datetime.now().isoformat()
sets = ", ".join(f"{k} = ?" for k in task_updates)
vals = list(task_updates.values()) + [task_id]
with self.transaction():
self.conn.execute(
"""
UPDATE task_runs SET finished_at = datetime('now'),
status = ?, result = ?, error = ?, raw_output = ?
WHERE id = ?
""",
(run_status, run_result, run_error, raw_output, run_id),
)
self.conn.execute(f"UPDATE tasks SET {sets} WHERE id = ?", vals)
def get_task_runs(self, task_id: int, limit: int = 20) -> list[dict]:
with self.lock:
rows = self.conn.execute(
"""
SELECT * FROM task_runs WHERE task_id = ?
ORDER BY started_at DESC LIMIT ?
""",
(task_id, limit),
).fetchall()
return [dict(r) for r in rows]
def add_output_event(self, task_id: int, run_id: int, event_type: str, content: str):
"""Add a new output event to the database."""
with self.lock:
self.conn.execute(
"""
INSERT INTO task_output_events (task_id, run_id, event_type, content)
VALUES (?, ?, ?, ?)
""",
(task_id, run_id, event_type, content),
)
self.conn.commit()
def get_output_events(self, task_id: int, limit: int = 1000, offset: int = 0) -> list[dict]:
"""Get output events for a task, ordered by timestamp."""
with self.lock:
rows = self.conn.execute(
"""
SELECT * FROM task_output_events
WHERE task_id = ?
ORDER BY timestamp DESC
LIMIT ? OFFSET ?
""",
(task_id, limit, offset),
).fetchall()
return [dict(r) for r in rows]
def get_run_output_events(self, run_id: int, limit: int = 1000) -> list[dict]: