Repository navigation
Expand file tree
/
Copy pathserver.py
More file actions
executable file
·4052 lines (3805 loc) · 176 KB
/
Copy pathserver.py
File metadata and controls
executable file
·4052 lines (3805 loc) · 176 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 python3
"""FastLab: a local multi-Agent task gateway for the web and Feishu."""
import argparse
import json
import math
import mimetypes
import os
import re
import secrets
import shutil
import signal
import sqlite3
import subprocess
import sys
import threading
import time
import traceback
import uuid
from collections import deque
from contextlib import contextmanager
from datetime import datetime, timezone
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path, PurePosixPath, PureWindowsPath
from urllib.parse import unquote, urlparse
from agent_adapter import (
AgentAdapter,
ClaudeCLIAdapter,
ClaudePlanner,
CodexCLIAdapter,
CodexPlanner,
Planner,
RESUME_CAPABILITY,
VERIFY_CAPABILITY,
WRITE_CAPABILITY,
)
from feishu_gateway import FeishuGateway
from feishu_help import help_payload as feishu_help_payload
from fastcas_pairing import FastCASPairing
from web_accounts import WebAccounts
APP_ROOT = Path(__file__).resolve().parent
WEB_ROOT = APP_ROOT / "web"
PLANNER_SCHEMA = APP_ROOT / "schemas" / "planner.schema.json"
VERIFIER_SCHEMA = APP_ROOT / "schemas" / "verifier.schema.json"
PLANNER_SKILL = APP_ROOT / "skills" / "orchestration" / "SKILL.md"
ROLE_NAMES = ("planner", "worker", "verifier")
EFFORTS = {"low", "medium", "high", "xhigh", "max", "ultra"}
TASK_STATES = {
"planning",
"awaiting_approval",
"running",
"verifying",
"completed",
"needs_attention",
"failed",
"cancelled",
}
SUBTASK_STATES = {"pending", "running", "succeeded", "failed", "blocked", "cancelled"}
LOCAL_ENV_KEYS = {
"FEISHU_APP_ID",
"FEISHU_APP_SECRET",
"FASTLAB_FEISHU_ALLOWED_OPEN_IDS",
"FASTLAB_FEISHU_DEFAULT_CHAT_ID",
"FASTLAB_PLANNER_BACKEND",
"FASTLAB_CODEX_BIN",
"FASTLAB_CLAUDE_BIN",
"FASTLAB_CLAUDE_EXTRA_ALLOWED_TOOLS",
"FASTLAB_AGENT_TIMEOUT",
"FASTLAB_FASTCAS_ISSUER",
"FASTLAB_FASTCAS_CLIENT_ID",
"FASTLAB_FASTCAS_ALLOW_LOOPBACK_HTTP",
}
DEFAULT_GLOBAL_CONCURRENCY = 4
MAX_GLOBAL_CONCURRENCY = 32
DEFAULT_AGENT_TIMEOUT = 3600
EXECUTOR_LABELS = {"codex": "Codex", "claude": "Claude Code"}
MAX_EVENT_PAYLOAD = 20000
class RepositoryInitializationRequired(ValueError):
"""Signal that repository setup needs an explicit user confirmation."""
def __init__(self, path, reason):
self.path = str(path)
self.reason = reason
if reason == "not_git":
message = "该文件夹不是 Git 仓库。是否初始化并创建初始提交?"
else:
message = "该 Git 仓库还没有任何提交。是否创建初始提交?"
super().__init__(message)
class DeliveryReverificationRequired(RuntimeError):
"""Signal that target-side commits were reconciled and must be verified."""
def utc_now():
return datetime.now(timezone.utc).isoformat(timespec="seconds")
def compact_error(value, limit=1200):
text = str(value or "").strip()
return text if len(text) <= limit else text[-limit:]
def slug(value, limit=52):
cleaned = re.sub(r"[^a-zA-Z0-9._-]+", "-", value).strip("-.").lower()
return (cleaned or "task")[:limit]
def resolve_executable(value):
"""Resolve commands once so Windows PATHEXT launchers (for example .cmd) work."""
raw = os.path.expanduser(str(value or "").strip())
if not raw:
return None
if os.path.dirname(raw) or Path(raw).is_absolute():
candidate = Path(raw)
return str(candidate.resolve()) if candidate.is_file() else None
return shutil.which(raw)
def executable_command(binary):
"""Use the current interpreter for Python command doubles on every platform."""
binary = str(binary)
if Path(binary).suffix.lower() == ".py":
return [sys.executable, binary]
return [binary]
def process_group_options(platform=None):
platform = os.name if platform is None else platform
if platform == "nt":
return {"creationflags": getattr(subprocess, "CREATE_NEW_PROCESS_GROUP", 0x00000200)}
return {"start_new_session": True}
def load_local_env(path, required=False):
"""Load FastLab's small, explicit environment-file surface.
Existing process environment values win, which keeps one-off overrides
possible without changing the file. Values are never logged.
"""
path = Path(path).expanduser()
if not path.exists():
if required:
raise ValueError("找不到环境配置文件:%s" % path)
return []
if not path.is_file():
raise ValueError("环境配置路径不是文件:%s" % path)
if os.name != "nt" and path.stat().st_mode & 0o077:
print(
"警告:%s 可被其他用户读取,建议执行 chmod 600。" % path,
file=sys.stderr,
)
loaded = []
for line_number, raw_line in enumerate(path.read_text(encoding="utf-8").splitlines(), 1):
line = raw_line.strip()
if not line or line.startswith("#"):
continue
if line.startswith("export "):
line = line[7:].lstrip()
key, separator, raw_value = line.partition("=")
key = key.strip()
if not separator or not re.fullmatch(r"[A-Z_][A-Z0-9_]*", key):
raise ValueError("%s:%s 不是有效的 KEY=VALUE 配置。" % (path, line_number))
if key.startswith("FASTLAB_PLANNER_") and key != "FASTLAB_PLANNER_BACKEND":
continue
if key not in LOCAL_ENV_KEYS:
raise ValueError("%s:%s 不支持配置 %s。" % (path, line_number, key))
value = raw_value.strip()
if len(value) >= 2 and value[0] == value[-1] and value[0] in {"'", '"'}:
value = value[1:-1]
if key not in os.environ:
os.environ[key] = value
loaded.append(key)
return loaded
def parse_claude_extra_allowed_tools(value):
raw = str(value or "").strip()
if not raw:
return ()
try:
parsed = json.loads(raw)
except json.JSONDecodeError as exc:
raise ValueError(
"FASTLAB_CLAUDE_EXTRA_ALLOWED_TOOLS 必须是 JSON 字符串数组。"
) from exc
if not isinstance(parsed, list) or not all(
isinstance(item, str) and item.strip() for item in parsed
):
raise ValueError(
"FASTLAB_CLAUDE_EXTRA_ALLOWED_TOOLS 必须是非空字符串组成的 JSON 数组。"
)
tools = []
for item in parsed:
rule = item.strip()
if rule in {"Bash", "Bash(*)"}:
raise ValueError(
"FastLab 不允许通过环境变量开放全部 Bash;请配置具体命令规则。"
)
if "\n" in rule or "\r" in rule:
raise ValueError("Claude 命令权限规则不能包含换行。")
if rule not in tools:
tools.append(rule)
return tuple(tools)
class AgentRunCancelled(RuntimeError):
pass
class AgentRunTimeout(RuntimeError):
pass
def parse_agent_timeout(value):
raw = str(DEFAULT_AGENT_TIMEOUT if value is None else value).strip()
try:
timeout = float(raw)
except (TypeError, ValueError) as exc:
raise ValueError("FASTLAB_AGENT_TIMEOUT 必须是大于等于 0 的秒数。") from exc
if not math.isfinite(timeout) or timeout < 0:
raise ValueError("FASTLAB_AGENT_TIMEOUT 必须是有限且大于等于 0 的秒数。")
return timeout
class AgentRunGate:
"""Cancellation-aware global concurrency limiter."""
def __init__(self, limit=DEFAULT_GLOBAL_CONCURRENCY):
self.limit = max(1, min(MAX_GLOBAL_CONCURRENCY, int(limit)))
self.active = 0
self.waiters = deque()
self.condition = threading.Condition()
def set_limit(self, limit):
with self.condition:
self.limit = max(1, min(MAX_GLOBAL_CONCURRENCY, int(limit)))
self.condition.notify_all()
def acquire(self, cancelled):
token = {"id": object()}
with self.condition:
self.waiters.append(token)
while True:
if cancelled():
try:
self.waiters.remove(token)
except ValueError:
pass
self.condition.notify_all()
raise AgentRunCancelled("Agent 运行在排队期间被取消。")
if self.waiters[0] is token and self.active < self.limit:
self.waiters.remove(token)
self.active += 1
return
self.condition.wait(timeout=0.1)
def release(self):
with self.condition:
self.active = max(0, self.active - 1)
self.condition.notify_all()
def wake_all(self):
with self.condition:
self.condition.notify_all()
def snapshot(self):
with self.condition:
return {
"active": self.active,
"queued": len(self.waiters),
"limit": self.limit,
}
class Store:
def __init__(self, path):
self.path = Path(path)
self.repaired_event_payloads = 0
self.path.parent.mkdir(parents=True, exist_ok=True)
self._initialize()
@contextmanager
def connect(self):
connection = sqlite3.connect(str(self.path), timeout=30)
connection.row_factory = sqlite3.Row
connection.execute("PRAGMA foreign_keys = ON")
connection.execute("PRAGMA journal_mode = WAL")
try:
yield connection
connection.commit()
except Exception:
connection.rollback()
raise
finally:
connection.close()
def _initialize(self):
with self.connect() as db:
db.executescript(
"""
CREATE TABLE IF NOT EXISTS repositories (
id TEXT PRIMARY KEY,
alias TEXT NOT NULL UNIQUE COLLATE NOCASE,
path TEXT NOT NULL UNIQUE,
is_default INTEGER NOT NULL DEFAULT 0,
created_at TEXT NOT NULL,
updated_at TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS settings (
key TEXT PRIMARY KEY,
value_json TEXT NOT NULL,
updated_at TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS tasks (
id TEXT PRIMARY KEY,
parent_task_id TEXT,
title TEXT NOT NULL,
goal TEXT NOT NULL,
constraints_text TEXT NOT NULL DEFAULT '',
workspace TEXT NOT NULL,
status TEXT NOT NULL,
max_concurrency INTEGER NOT NULL DEFAULT 3,
base_branch TEXT,
base_commit TEXT,
integration_branch TEXT,
integration_worktree TEXT,
delivered_commit TEXT,
delivered_at TEXT,
cleaned_at TEXT,
plan_json TEXT,
error TEXT,
cancel_requested INTEGER NOT NULL DEFAULT 0,
created_at TEXT NOT NULL,
updated_at TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS subtasks (
id TEXT PRIMARY KEY,
task_id TEXT NOT NULL REFERENCES tasks(id) ON DELETE CASCADE,
plan_key TEXT NOT NULL,
ordinal INTEGER NOT NULL,
title TEXT NOT NULL,
instructions TEXT NOT NULL,
weight INTEGER NOT NULL DEFAULT 1,
dependencies_json TEXT NOT NULL DEFAULT '[]',
status TEXT NOT NULL,
branch TEXT,
worktree TEXT,
session_id TEXT,
dispatch_id TEXT,
exit_code INTEGER,
attempt INTEGER NOT NULL DEFAULT 0,
error TEXT,
created_at TEXT NOT NULL,
updated_at TEXT NOT NULL,
UNIQUE(task_id, plan_key)
);
CREATE TABLE IF NOT EXISTS events (
id INTEGER PRIMARY KEY AUTOINCREMENT,
task_id TEXT NOT NULL REFERENCES tasks(id) ON DELETE CASCADE,
subtask_id TEXT,
kind TEXT NOT NULL,
message TEXT NOT NULL,
payload_json TEXT,
created_at TEXT NOT NULL
);
CREATE INDEX IF NOT EXISTS idx_subtasks_task ON subtasks(task_id, ordinal);
CREATE INDEX IF NOT EXISTS idx_events_task ON events(task_id, id);
CREATE TABLE IF NOT EXISTS channel_bindings (
id INTEGER PRIMARY KEY AUTOINCREMENT,
task_id TEXT NOT NULL REFERENCES tasks(id) ON DELETE CASCADE,
channel TEXT NOT NULL,
conversation_id TEXT NOT NULL,
message_id TEXT,
source_message_id TEXT,
operator_id TEXT,
created_at TEXT NOT NULL,
updated_at TEXT NOT NULL,
UNIQUE(task_id, channel, conversation_id)
);
CREATE TABLE IF NOT EXISTS inbound_events (
channel TEXT NOT NULL,
event_id TEXT NOT NULL,
action TEXT,
task_id TEXT,
created_at TEXT NOT NULL,
PRIMARY KEY(channel, event_id)
);
CREATE TABLE IF NOT EXISTS notification_outbox (
id INTEGER PRIMARY KEY AUTOINCREMENT,
task_id TEXT REFERENCES tasks(id) ON DELETE CASCADE,
channel TEXT NOT NULL,
destination TEXT NOT NULL,
payload_json TEXT NOT NULL,
status TEXT NOT NULL DEFAULT 'pending',
attempts INTEGER NOT NULL DEFAULT 0,
error TEXT,
created_at TEXT NOT NULL,
updated_at TEXT NOT NULL
);
CREATE INDEX IF NOT EXISTS idx_outbox_pending
ON notification_outbox(status, id);
"""
)
self._ensure_column(db, "tasks", "repository_id", "TEXT")
self._ensure_column(db, "tasks", "parent_task_id", "TEXT")
self._ensure_column(db, "tasks", "working_subdir", "TEXT NOT NULL DEFAULT ''")
self._ensure_column(db, "tasks", "source_channel", "TEXT NOT NULL DEFAULT 'web'")
self._ensure_column(db, "tasks", "role_settings_json", "TEXT NOT NULL DEFAULT '{}'")
self._ensure_column(db, "tasks", "planner_thread_id", "TEXT")
self._ensure_column(db, "tasks", "verifier_thread_id", "TEXT")
self._ensure_column(db, "tasks", "delivered_commit", "TEXT")
self._ensure_column(db, "tasks", "delivered_at", "TEXT")
self._ensure_column(db, "tasks", "cleaned_at", "TEXT")
self._ensure_column(db, "subtasks", "model", "TEXT")
self._ensure_column(db, "subtasks", "reasoning_effort", "TEXT")
self._ensure_column(db, "subtasks", "pending_message", "TEXT")
self._ensure_column(db, "subtasks", "dispatch_id", "TEXT")
self._ensure_column(db, "subtasks", "executor", "TEXT")
self._ensure_column(db, "subtasks", "executor_snapshot_json", "TEXT NOT NULL DEFAULT '{}'")
legacy_columns = {
row["name"] for row in db.execute("PRAGMA table_info(subtasks)")
}
if "agent_profile_id" in legacy_columns:
db.execute(
"UPDATE subtasks SET executor=CASE "
"WHEN agent_profile_id IN ('builtin-codex','codex') THEN 'codex' "
"WHEN agent_profile_id IN ('builtin-claude','claude') THEN 'claude' "
"ELSE executor END WHERE executor IS NULL"
)
self._ensure_column(db, "channel_bindings", "source_message_id", "TEXT")
defaults = {
"models": {
"planner": {"model": "", "reasoningEffort": "high"},
"worker": {"model": "", "reasoningEffort": "high"},
"verifier": {"model": "", "reasoningEffort": "high"},
},
"feishu.defaultConversation": "",
"agent.globalConcurrency": DEFAULT_GLOBAL_CONCURRENCY,
}
now = utc_now()
for key, value in defaults.items():
db.execute(
"INSERT OR IGNORE INTO settings (key,value_json,updated_at) VALUES (?,?,?)",
(key, json.dumps(value, ensure_ascii=False), now),
)
self.repaired_event_payloads = self._repair_event_payloads(db)
interrupted = db.execute(
"SELECT id FROM tasks WHERE status IN ('planning', 'running', 'verifying')"
).fetchall()
for row in interrupted:
db.execute(
"UPDATE tasks SET status='needs_attention', error=?, updated_at=? WHERE id=?",
("服务上次退出时任务仍在运行,请检查后重试。", utc_now(), row["id"]),
)
db.execute(
"UPDATE subtasks SET status='failed', error=?, updated_at=? "
"WHERE task_id=? AND status='running'",
("服务退出导致执行中断。", utc_now(), row["id"]),
)
@staticmethod
def _ensure_column(db, table, column, definition):
existing = {row["name"] for row in db.execute("PRAGMA table_info(%s)" % table)}
if column not in existing:
db.execute("ALTER TABLE %s ADD COLUMN %s %s" % (table, column, definition))
@staticmethod
def _load_json(value, label):
try:
return json.loads(value)
except (TypeError, json.JSONDecodeError) as exc:
raise ValueError("数据库中的 %s 不是有效 JSON:%s" % (label, exc)) from exc
@staticmethod
def _encode_event_payload(payload):
encoded = json.dumps(payload, ensure_ascii=False, default=str)
if len(encoded) <= MAX_EVENT_PAYLOAD:
return encoded
return json.dumps(
{
"_fastlabTruncated": True,
"originalLength": len(encoded),
"preview": encoded[:MAX_EVENT_PAYLOAD // 4],
},
ensure_ascii=False,
)
@classmethod
def _repair_event_payloads(cls, db):
repaired = 0
rows = db.execute(
"SELECT id,payload_json FROM events WHERE payload_json IS NOT NULL"
).fetchall()
for row in rows:
try:
json.loads(row["payload_json"])
except (TypeError, json.JSONDecodeError):
replacement = cls._encode_event_payload({
"_fastlabRecovered": True,
"reason": "旧版本截断了日志 JSON",
"preview": str(row["payload_json"])[:MAX_EVENT_PAYLOAD // 4],
})
db.execute(
"UPDATE events SET payload_json=? WHERE id=?",
(replacement, row["id"]),
)
repaired += 1
return repaired
def create_task(self, title, goal, constraints_text, workspace, max_concurrency,
repository_id=None, source_channel="web", role_settings=None,
working_subdir="", parent_task_id=None, base_branch=None,
base_commit=None):
task_id = uuid.uuid4().hex
now = utc_now()
with self.connect() as db:
db.execute(
"INSERT INTO tasks "
"(id,parent_task_id,title,goal,constraints_text,workspace,status,max_concurrency,"
"repository_id,source_channel,role_settings_json,working_subdir,base_branch,"
"base_commit,created_at,updated_at) "
"VALUES (?,?,?,?,?,?,'planning',?,?,?,?,?,?,?,?,?)",
(
task_id, parent_task_id, title, goal, constraints_text, workspace,
max_concurrency,
repository_id, source_channel, json.dumps(role_settings or {}, ensure_ascii=False),
working_subdir, base_branch, base_commit, now, now,
),
)
return task_id
def update_task(self, task_id, **values):
allowed = {
"title",
"status",
"base_branch",
"base_commit",
"integration_branch",
"integration_worktree",
"delivered_commit",
"delivered_at",
"cleaned_at",
"plan_json",
"error",
"cancel_requested",
"planner_thread_id",
"verifier_thread_id",
"repository_id",
"role_settings_json",
"working_subdir",
"parent_task_id",
}
pairs = [(key, value) for key, value in values.items() if key in allowed]
if not pairs:
return
pairs.append(("updated_at", utc_now()))
statement = ", ".join("%s=?" % key for key, _ in pairs)
with self.connect() as db:
db.execute(
"UPDATE tasks SET %s WHERE id=?" % statement,
[value for _, value in pairs] + [task_id],
)
def update_subtask(self, subtask_id, **values):
allowed = {
"title",
"instructions",
"status",
"branch",
"worktree",
"session_id",
"exit_code",
"attempt",
"error",
"model",
"reasoning_effort",
"pending_message",
"dispatch_id",
"executor",
"executor_snapshot_json",
}
pairs = [(key, value) for key, value in values.items() if key in allowed]
if not pairs:
return
pairs.append(("updated_at", utc_now()))
statement = ", ".join("%s=?" % key for key, _ in pairs)
with self.connect() as db:
db.execute(
"UPDATE subtasks SET %s WHERE id=?" % statement,
[value for _, value in pairs] + [subtask_id],
)
def update_subtask_for_dispatch(self, subtask_id, dispatch_id, **values):
"""Fence a Worker result to its currently running Dispatch."""
allowed = {
"status", "session_id", "exit_code", "error", "pending_message",
}
pairs = [(key, value) for key, value in values.items() if key in allowed]
if not pairs:
return False
pairs.append(("updated_at", utc_now()))
statement = ", ".join("%s=?" % key for key, _ in pairs)
with self.connect() as db:
cursor = db.execute(
"UPDATE subtasks SET %s WHERE id=? AND dispatch_id=? AND status='running'"
% statement,
[value for _, value in pairs] + [subtask_id, dispatch_id],
)
return bool(cursor.rowcount)
def replace_subtasks(self, task_id, subtasks):
now = utc_now()
with self.connect() as db:
db.execute("DELETE FROM subtasks WHERE task_id=?", (task_id,))
for ordinal, item in enumerate(subtasks, 1):
db.execute(
"INSERT INTO subtasks "
"(id,task_id,plan_key,ordinal,title,instructions,weight,dependencies_json,"
"executor,executor_snapshot_json,status,created_at,updated_at) "
"VALUES (?,?,?,?,?,?,?,?,?,?, 'pending',?,?)",
(
"%s:%s" % (task_id, item["key"]),
task_id,
item["key"],
ordinal,
item["title"],
item["instructions"],
item["weight"],
json.dumps(item["dependencies"], ensure_ascii=False),
item.get("executor"),
"{}",
now,
now,
),
)
def add_event(self, task_id, kind, message, subtask_id=None, payload=None):
encoded = self._encode_event_payload(payload) if payload is not None else None
with self.connect() as db:
db.execute(
"INSERT INTO events (task_id,subtask_id,kind,message,payload_json,created_at) "
"VALUES (?,?,?,?,?,?)",
(task_id, subtask_id, kind, compact_error(message, 8000), encoded, utc_now()),
)
db.execute("UPDATE tasks SET updated_at=? WHERE id=?", (utc_now(), task_id))
def get_task(self, task_id, include_events=True):
with self.connect() as db:
row = db.execute("SELECT * FROM tasks WHERE id=?", (task_id,)).fetchone()
if row is None:
return None
task = dict(row)
task["plan"] = self._load_json(
task.pop("plan_json"), "任务 %s 的计划" % task_id
) if task.get("plan_json") else None
task["role_settings"] = self._load_json(
task.pop("role_settings_json") or "{}", "任务 %s 的角色设置" % task_id
)
task["cancel_requested"] = bool(task["cancel_requested"])
children = db.execute(
"SELECT * FROM subtasks WHERE task_id=? ORDER BY ordinal", (task_id,)
).fetchall()
task["subtasks"] = []
for child in children:
item = dict(child)
item["dependencies"] = self._load_json(
item.pop("dependencies_json"), "子任务 %s 的依赖" % item["id"]
)
item["executor_snapshot"] = self._load_json(
item.pop("executor_snapshot_json") or "{}",
"子任务 %s 的执行器设置" % item["id"],
)
task["subtasks"].append(item)
task["events"] = []
if include_events:
rows = db.execute(
"SELECT * FROM (SELECT * FROM events WHERE task_id=? ORDER BY id DESC LIMIT 300) "
"ORDER BY id",
(task_id,),
).fetchall()
for event in rows:
item = dict(event)
item["payload"] = self._load_json(
item.pop("payload_json"), "日志事件 %s" % item["id"]
) if item.get("payload_json") else None
task["events"].append(item)
task["progress"] = self.progress(task["subtasks"])
return task
def list_tasks(self):
with self.connect() as db:
rows = db.execute("SELECT id FROM tasks ORDER BY updated_at DESC").fetchall()
return [self.get_task(row["id"], include_events=False) for row in rows]
def set_setting(self, key, value):
now = utc_now()
with self.connect() as db:
db.execute(
"INSERT INTO settings (key,value_json,updated_at) VALUES (?,?,?) "
"ON CONFLICT(key) DO UPDATE SET value_json=excluded.value_json,updated_at=excluded.updated_at",
(key, json.dumps(value, ensure_ascii=False), now),
)
def get_setting(self, key, default=None):
with self.connect() as db:
row = db.execute("SELECT value_json FROM settings WHERE key=?", (key,)).fetchone()
return self._load_json(row["value_json"], "设置 %s" % key) if row else default
def add_repository(self, alias, path, is_default=False, repository_id=None):
now = utc_now()
repository_id = repository_id or uuid.uuid4().hex
with self.connect() as db:
if is_default:
db.execute("UPDATE repositories SET is_default=0")
db.execute(
"INSERT INTO repositories (id,alias,path,is_default,created_at,updated_at) "
"VALUES (?,?,?,?,?,?)",
(repository_id, alias, path, int(bool(is_default)), now, now),
)
return self.get_repository(repository_id)
def update_repository(self, repository_id, alias, path, is_default=False):
now = utc_now()
with self.connect() as db:
if is_default:
db.execute("UPDATE repositories SET is_default=0")
cursor = db.execute(
"UPDATE repositories SET alias=?,path=?,is_default=?,updated_at=? WHERE id=?",
(alias, path, int(bool(is_default)), now, repository_id),
)
if not cursor.rowcount:
raise KeyError("找不到仓库。")
return self.get_repository(repository_id)
def get_repository(self, repository_id):
with self.connect() as db:
row = db.execute("SELECT * FROM repositories WHERE id=?", (repository_id,)).fetchone()
if row is None:
return None
item = dict(row)
item["is_default"] = bool(item["is_default"])
return item
def find_repository(self, value):
with self.connect() as db:
row = db.execute(
"SELECT * FROM repositories WHERE id=? OR alias=? COLLATE NOCASE OR path=?",
(str(value), str(value), str(value)),
).fetchone()
if row is None:
return None
item = dict(row)
item["is_default"] = bool(item["is_default"])
return item
def list_repositories(self):
with self.connect() as db:
rows = db.execute(
"SELECT * FROM repositories ORDER BY is_default DESC, alias COLLATE NOCASE"
).fetchall()
items = []
for row in rows:
item = dict(row)
item["is_default"] = bool(item["is_default"])
items.append(item)
return items
def delete_repository(self, repository_id):
with self.connect() as db:
active = db.execute(
"SELECT COUNT(*) AS total FROM tasks WHERE repository_id=? "
"AND status NOT IN ('completed','cancelled','failed')",
(repository_id,),
).fetchone()["total"]
if active:
raise ValueError("该仓库仍有未结束任务,不能删除。")
cursor = db.execute("DELETE FROM repositories WHERE id=?", (repository_id,))
if not cursor.rowcount:
raise KeyError("找不到仓库。")
def clear_task_events(self, task_id):
with self.connect() as db:
if not db.execute("SELECT 1 FROM tasks WHERE id=?", (task_id,)).fetchone():
raise KeyError("找不到任务。")
db.execute("DELETE FROM events WHERE task_id=?", (task_id,))
db.execute("UPDATE tasks SET updated_at=? WHERE id=?", (utc_now(), task_id))
def delete_task(self, task_id):
with self.connect() as db:
db.execute("DELETE FROM inbound_events WHERE task_id=?", (task_id,))
cursor = db.execute("DELETE FROM tasks WHERE id=?", (task_id,))
if not cursor.rowcount:
raise KeyError("找不到任务。")
def bind_task_channel(self, task_id, channel, conversation_id, operator_id=None,
message_id=None, source_message_id=None):
now = utc_now()
with self.connect() as db:
db.execute(
"INSERT INTO channel_bindings "
"(task_id,channel,conversation_id,message_id,source_message_id,operator_id,created_at,updated_at) "
"VALUES (?,?,?,?,?,?,?,?) ON CONFLICT(task_id,channel,conversation_id) DO UPDATE SET "
"message_id=COALESCE(excluded.message_id,channel_bindings.message_id),"
"source_message_id=COALESCE(excluded.source_message_id,channel_bindings.source_message_id),"
"operator_id=COALESCE(excluded.operator_id,channel_bindings.operator_id),"
"updated_at=excluded.updated_at",
(
task_id, channel, conversation_id, message_id, source_message_id,
operator_id, now, now,
),
)
def channel_bindings(self, task_id):
with self.connect() as db:
return [dict(row) for row in db.execute(
"SELECT * FROM channel_bindings WHERE task_id=?", (task_id,)
)]
def claim_inbound_event(self, channel, event_id, action=None, task_id=None):
try:
with self.connect() as db:
db.execute(
"INSERT INTO inbound_events (channel,event_id,action,task_id,created_at) "
"VALUES (?,?,?,?,?)",
(channel, event_id, action, task_id, utc_now()),
)
return True
except sqlite3.IntegrityError:
return False
def transition_task(self, task_id, status, kind, message, error=None, payload=None,
subtask_id=None):
now = utc_now()
encoded_payload = json.dumps(payload, ensure_ascii=False, default=str) if payload else None
with self.connect() as db:
db.execute(
"UPDATE tasks SET status=?,error=?,updated_at=? WHERE id=?",
(status, error, now, task_id),
)
db.execute(
"INSERT INTO events (task_id,subtask_id,kind,message,payload_json,created_at) "
"VALUES (?,?,?,?,?,?)",
(task_id, subtask_id, kind, compact_error(message, 8000), encoded_payload, now),
)
destinations = [dict(row) for row in db.execute(
"SELECT channel,conversation_id FROM channel_bindings WHERE task_id=?", (task_id,)
)]
if not destinations:
default_row = db.execute(
"SELECT value_json FROM settings WHERE key='feishu.defaultConversation'"
).fetchone()
default = self._load_json(
default_row["value_json"], "设置 feishu.defaultConversation"
) if default_row else ""
if default:
destinations.append({"channel": "feishu", "conversation_id": default})
outbox_payload = json.dumps(
{"taskId": task_id, "status": status, "kind": kind, "message": message},
ensure_ascii=False,
)
for destination in destinations:
db.execute(
"INSERT INTO notification_outbox "
"(task_id,channel,destination,payload_json,status,created_at,updated_at) "
"VALUES (?,?,?,?,'pending',?,?)",
(task_id, destination["channel"], destination["conversation_id"], outbox_payload, now, now),
)
def pending_outbox(self, limit=20):
with self.connect() as db:
rows = db.execute(
"SELECT * FROM notification_outbox WHERE status='pending' ORDER BY id LIMIT ?",
(limit,),
).fetchall()
result = []
for row in rows:
item = dict(row)
item["payload"] = self._load_json(
item.pop("payload_json"), "通知 %s" % item["id"]
)
result.append(item)
return result
def enqueue_notification(self, task_id, kind, message):
now = utc_now()
payload = json.dumps(
{"taskId": task_id, "kind": kind, "message": message}, ensure_ascii=False
)
with self.connect() as db:
destinations = [dict(row) for row in db.execute(
"SELECT channel,conversation_id FROM channel_bindings WHERE task_id=?", (task_id,)
)]
if not destinations:
default_row = db.execute(
"SELECT value_json FROM settings WHERE key='feishu.defaultConversation'"
).fetchone()
default = self._load_json(
default_row["value_json"], "设置 feishu.defaultConversation"
) if default_row else ""
if default:
destinations.append({"channel": "feishu", "conversation_id": default})
for destination in destinations:
db.execute(
"INSERT INTO notification_outbox "
"(task_id,channel,destination,payload_json,status,created_at,updated_at) "
"VALUES (?,?,?,?,'pending',?,?)",
(task_id, destination["channel"], destination["conversation_id"], payload, now, now),
)
def finish_outbox(self, item_id, error=None):
with self.connect() as db:
db.execute(
"UPDATE notification_outbox SET status=?,attempts=attempts+1,error=?,updated_at=? WHERE id=?",
("pending" if error else "sent", compact_error(error) if error else None, utc_now(), item_id),
)
@staticmethod
def progress(subtasks):
if not subtasks:
return 0
total = sum(max(1, int(item["weight"])) for item in subtasks)
finished = sum(
max(1, int(item["weight"])) for item in subtasks if item["status"] == "succeeded"
)
return round(finished * 100 / total)
class FastLab:
def __init__(self, workspace=None, data_dir=None, codex_bin=None, agent_adapter=None,
claude_bin=None, planner=None):
self.workspace = None
self.default_repository_id = None
self.data_dir = Path(data_dir or APP_ROOT / ".fastlab").expanduser().resolve()
self.data_dir.mkdir(parents=True, exist_ok=True)
self.store = Store(self.data_dir / "fastlab.db")
self.fastcas_pairing = FastCASPairing(self.store)
self.web_accounts = WebAccounts(self.store)
default_feishu_conversation = os.environ.get("FASTLAB_FEISHU_DEFAULT_CHAT_ID", "").strip()
if default_feishu_conversation:
self.store.set_setting("feishu.defaultConversation", default_feishu_conversation)
self.merge_lock = threading.Lock()
self.repository_lock = threading.Lock()
self.scheduler_lock = threading.Lock()
self.schedulers = {}
self.thread_lock = threading.Lock()
self.background_threads = set()
self.task_locks_lock = threading.Lock()
self.task_locks = {}
self.shutting_down = False
self.agent_timeout = parse_agent_timeout(os.environ.get("FASTLAB_AGENT_TIMEOUT"))
self.git_bin = shutil.which("git")
self._validate_environment()
self._initialize_repositories(workspace)
codex_adapter = None
if agent_adapter is not None:
if not isinstance(agent_adapter, AgentAdapter):
required = {"run", "interrupt", "health", "models"}
if not all(hasattr(agent_adapter, name) for name in required):
raise TypeError("agent_adapter 不符合 AgentAdapter 接口。")
codex_adapter = agent_adapter
else:
requested_codex = codex_bin or os.environ.get("FASTLAB_CODEX_BIN") or "codex"
resolved = resolve_executable(requested_codex)
if resolved:
codex_adapter = CodexCLIAdapter(resolved, self.data_dir / "runtime")
self.codex_bin = getattr(codex_adapter, "binary", None)
requested_claude = claude_bin or os.environ.get("FASTLAB_CLAUDE_BIN") or "claude"
self.claude_bin = resolve_executable(requested_claude)
self.executors = {}
if codex_adapter:
self.executors["codex"] = codex_adapter
if self.claude_bin:
claude_allowed_tools = list(ClaudeCLIAdapter.DEFAULT_ALLOWED_TOOLS)
claude_allowed_tools.extend(parse_claude_extra_allowed_tools(
os.environ.get("FASTLAB_CLAUDE_EXTRA_ALLOWED_TOOLS")
))
self.executors["claude"] = ClaudeCLIAdapter(
self.claude_bin,
allowed_tools=claude_allowed_tools,
models=["sonnet", "opus"],
)
self.planner = planner or self._planner_from_environment()
if not isinstance(self.planner, Planner) and not all(
hasattr(self.planner, name) for name in ("plan", "interrupt", "health", "settings")
):
raise TypeError("planner 不符合 Planner 接口。")
self.active_run_adapters = {}
self.active_run_lock = threading.Lock()
global_limit = self._normalize_global_concurrency(
self.store.get_setting("agent.globalConcurrency", DEFAULT_GLOBAL_CONCURRENCY)
)
self.agent_gate = AgentRunGate(global_limit)
self._rebuild_documents()
self.feishu = FeishuGateway(self)