sycommon-python-lib 0.2.12a5__py3-none-any.whl → 0.2.12a6__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -157,6 +157,19 @@
157
157
  </button>
158
158
 
159
159
  <div class="dc-panel" id="dcPanel" role="dialog" aria-label="DevChat 开发协作面板">
160
+ <!-- 登录视图(LDAP 模式未登录;登录后隐藏) -->
161
+ <div class="dc-login" id="dcLoginView" style="display:none;flex:1;flex-direction:column;align-items:center;justify-content:center;gap:12px;padding:24px">
162
+ <div style="font-size:30px">🤖</div>
163
+ <div style="font-weight:700;font-size:15px">DevChat 登录(LDAP 域账号)</div>
164
+ <input id="dcLoginUser" placeholder="域账号(如 osulcode.xiao)" autocomplete="username"
165
+ style="width:100%;max-width:300px;padding:8px 10px;border:1px solid var(--line);border-radius:8px;font:inherit;outline:none">
166
+ <input id="dcLoginPass" type="password" placeholder="密码" autocomplete="current-password"
167
+ style="width:100%;max-width:300px;padding:8px 10px;border:1px solid var(--line);border-radius:8px;font:inherit;outline:none">
168
+ <div id="dcLoginErr" style="font-size:12px;color:var(--red);min-height:16px"></div>
169
+ <button id="dcLoginBtn" class="dc-btn" style="width:100%;max-width:300px">登录</button>
170
+ <div style="font-size:11px;color:var(--ink-3)">登录一次后同一浏览器 7 天内免登录;提交人将记录到每条需求</div>
171
+ </div>
172
+ <div id="dcMainView" style="display:none;flex-direction:column;flex:1;min-height:0">
160
173
  <div class="dc-head">
161
174
  <div style="flex:1">
162
175
  <div class="dc-title">DevChat 开发协作</div>
@@ -184,6 +197,7 @@
184
197
  <button class="dc-btn" id="dcSendBtn">发送</button>
185
198
  </div>
186
199
  </div>
200
+ </div><!-- /dcMainView -->
187
201
  </div>
188
202
 
189
203
  <script>
@@ -545,11 +559,47 @@
545
559
  });
546
560
 
547
561
  // ── 启动 ──
548
- renderOpen();
549
- loadTasks();
550
- loadHistory().then(refreshStatus).then(connect);
551
- setInterval(refreshStatus, 15000);
552
- setInterval(function () { if (state.activeTab === 'tasks') loadTasks(); }, 10000);
562
+ // 登录态分流:数据端点 401 = LDAP 模式未登录 → 登录视图挡住面板主体。
563
+ var loginView = $('dcLoginView'), mainView = $('dcMainView');
564
+ var loginUser = $('dcLoginUser'), loginPass = $('dcLoginPass'),
565
+ loginBtn = $('dcLoginBtn'), loginErr = $('dcLoginErr');
566
+ var authRequired = false;
567
+ function checkAuth() {
568
+ return fetch(url('/devchat/messages?limit=1'), { credentials: 'include' })
569
+ .then(function (r) {
570
+ if (r.status === 401) { authRequired = true; showLogin(true); return false; }
571
+ showLogin(false); return true;
572
+ }).catch(function () { showLogin(false); return true; });
573
+ }
574
+ function showLogin(req) {
575
+ loginView.style.display = req ? 'flex' : 'none';
576
+ mainView.style.display = req ? 'none' : 'flex';
577
+ }
578
+ function doLogin() {
579
+ var u = (loginUser.value || '').trim(), p = loginPass.value || '';
580
+ if (!u || !p) { loginErr.textContent = '请输入用户名和密码'; return; }
581
+ loginBtn.disabled = true; loginErr.textContent = '';
582
+ fetch(url('/devchat/login'), {
583
+ method: 'POST', credentials: 'include',
584
+ headers: { 'Content-Type': 'application/json' },
585
+ body: JSON.stringify({ username: u, password: p })
586
+ }).then(function (r) { return r.json().catch(function () { return {}; }); })
587
+ .then(function (d) {
588
+ loginBtn.disabled = false;
589
+ if (d.success) { loginPass.value = ''; checkAuth().then(function (ok) { if (ok) boot(); }); }
590
+ else loginErr.textContent = d.error || '登录失败';
591
+ }).catch(function () { loginBtn.disabled = false; loginErr.textContent = '登录请求失败,请检查连接'; });
592
+ }
593
+ loginBtn.addEventListener('click', doLogin);
594
+ loginPass.addEventListener('keydown', function (e) { if (e.key === 'Enter') doLogin(); });
595
+ function boot() {
596
+ renderOpen();
597
+ loadTasks();
598
+ loadHistory().then(refreshStatus).then(connect);
599
+ setInterval(refreshStatus, 15000);
600
+ setInterval(function () { if (state.activeTab === 'tasks') loadTasks(); }, 10000);
601
+ }
602
+ checkAuth().then(function (ok) { if (ok) boot(); });
553
603
  })();
554
604
  </script>
555
605
  </body>
@@ -46,6 +46,17 @@ from sycommon.logging.kafka_log import SYLogger
46
46
 
47
47
  # 需求队列状态值(与 Go 版同契约)。
48
48
  from .tasks import TASK_QUEUED, TASK_RUNNING, TASK_DONE, TASK_ERROR, TASK_CANCELLED # noqa: F401
49
+ from .login import (
50
+ LOGIN_COOKIE_NAME,
51
+ LOGIN_TTL_DEFAULT,
52
+ LdapAuthn,
53
+ LoginSession,
54
+ SqliteLoginStore,
55
+ build_ldap_authn,
56
+ ldap_settings_from_config,
57
+ ldap_settings_from_env,
58
+ new_login_token,
59
+ )
49
60
 
50
61
  # 自带前端页面(与 Go 版同源同样式,单文件无外部依赖)。
51
62
  from ._page import DEVCHAT_HTML
@@ -66,6 +77,7 @@ class DevchatConfig:
66
77
  corsOrigins: List[str] = field(default_factory=list)
67
78
  maxHistory: int = 500
68
79
  commandTimeoutSec: float = 1800.0
80
+ loginSessionTTL: int = 0 # 登录会话 TTL 秒;0 = 默认 7 天
69
81
 
70
82
  @classmethod
71
83
  def from_mapping(cls, raw: Any) -> "DevchatConfig":
@@ -90,6 +102,8 @@ class DevchatConfig:
90
102
  cfg.maxHistory = int(raw.get("maxHistory") or 500)
91
103
  with contextlib.suppress(Exception):
92
104
  cfg.commandTimeoutSec = float(raw.get("commandTimeoutSec") or 1800.0)
105
+ with contextlib.suppress(Exception):
106
+ cfg.loginSessionTTL = int(raw.get("loginSessionTTL") or raw.get("login_session_ttl") or 0)
93
107
  return cfg
94
108
 
95
109
  def is_admin(self, user_id: str) -> bool:
@@ -649,6 +663,24 @@ def setup_devchat_handler(app: FastAPI, config: Optional[dict] = None) -> FastAP
649
663
  port = int(conf.get("Port", 0) or 0)
650
664
  st.set_fallback_addr(host, port)
651
665
 
666
+ def _config_dict() -> dict:
667
+ """宿主配置 dict(Services 已装配优先;退 Config 单例)。fail-soft。"""
668
+ try:
669
+ from sycommon.services import Services
670
+ d = getattr(Services, "_config", None)
671
+ if isinstance(d, dict):
672
+ return d
673
+ except Exception: # noqa: BLE001
674
+ pass
675
+ try:
676
+ from sycommon.config.Config import Config
677
+ d = Config().config
678
+ if isinstance(d, dict):
679
+ return d
680
+ except Exception: # noqa: BLE001
681
+ pass
682
+ return {}
683
+
652
684
  router = APIRouter(prefix=cfg.basePath, tags=["Devchat"])
653
685
 
654
686
  def _capture_host(request: Request) -> None:
@@ -656,12 +688,71 @@ def setup_devchat_handler(app: FastAPI, config: Optional[dict] = None) -> FastAP
656
688
  st.capture_host(request.headers.get("host", ""))
657
689
 
658
690
  # ---- 身份 ----
691
+ # LDAP 登录装配(与 Go 版 plugin_devchat.applyDevchatDefaults 对齐):
692
+ # 优先级 = 显式 identityFunc > DevchatService.ldap dict > 环境变量
693
+ # DEVCHAT_LDAP_* > nacos llm 共享配置提升后的顶层 LDAP.*(退 llm→LDAP
694
+ # 未提升形态)。DEVCHAT_LDAP=off 可强制关闭(保持匿名调试形态)。
695
+ ldap_authn = None
696
+ login_store = None
697
+ login_ttl = int(cfg.loginSessionTTL or 0) or LOGIN_TTL_DEFAULT
698
+ if cfg.identityFunc is None and os.environ.get("DEVCHAT_LDAP") != "off":
699
+ settings = None
700
+ if isinstance(config.get("DevchatService"), dict):
701
+ raw = config["DevchatService"].get("ldap")
702
+ if isinstance(raw, dict) and raw.get("urls"):
703
+ settings = {
704
+ "urls": [str(u).strip() for u in
705
+ (raw["urls"].split(",") if isinstance(raw["urls"], str)
706
+ else raw["urls"]) if str(u).strip()],
707
+ "base": str(raw.get("base") or "").strip(),
708
+ "username": str(raw.get("username") or "").strip(),
709
+ "password": str(raw.get("password") or "").strip(),
710
+ "defaultDC": str(raw.get("defaultDC") or "").strip(),
711
+ }
712
+ if not (settings["base"] and settings["username"] and settings["password"]):
713
+ settings = None
714
+ if settings is None:
715
+ settings = ldap_settings_from_env()
716
+ if settings is None:
717
+ merged: dict = {}
718
+ # 提升后形态(顶层 LDAP.*)与 llm→LDAP.* 双路径,与 Go 版一致。
719
+ with contextlib.suppress(Exception):
720
+ merged.update(_config_dict() or {})
721
+ settings = ldap_settings_from_config(merged)
722
+ if settings is not None:
723
+ ldap_authn = build_ldap_authn(settings)
724
+ if ldap_authn is not None and st.tasks is not None and st.tasks._conn is not None:
725
+ login_store = SqliteLoginStore(st.tasks._conn)
726
+ elif ldap_authn is not None:
727
+ login_store = {} # 内存降级:token → LoginSession
728
+
729
+ def _login_identity(request: Request) -> Optional[tuple]:
730
+ """cookie → 登录会话;无/过期返回 None(401)。"""
731
+ token = request.cookies.get(LOGIN_COOKIE_NAME, "")
732
+ if not token:
733
+ return None
734
+ if isinstance(login_store, dict):
735
+ s = login_store.get(token)
736
+ if s is None or time.time() > s.expires_at:
737
+ login_store.pop(token, None)
738
+ return None
739
+ return s.username, (s.display_name or s.username)
740
+ s = login_store.get(token)
741
+ if s is None:
742
+ return None
743
+ return s.username, (s.display_name or s.username)
744
+
659
745
  async def _identity(request: Request):
660
746
  if cfg.identityFunc is not None:
661
747
  uid, name, ok = await cfg.identityFunc(request)
662
748
  if not ok:
663
749
  return None
664
750
  return uid, name
751
+ if login_store is not None:
752
+ ident = _login_identity(request)
753
+ if ident is None:
754
+ return None
755
+ return ident
665
756
  return "anonymous", "匿名开发者"
666
757
 
667
758
  def _cors_headers(request: Request) -> Dict[str, str]:
@@ -765,6 +856,64 @@ def setup_devchat_handler(app: FastAPI, config: Optional[dict] = None) -> FastAP
765
856
  return JSONResponse({"detail": "已交给 claude 执行", "started": True},
766
857
  status_code=202)
767
858
 
859
+ @router.post("/tasks/update")
860
+ async def task_update(request: Request):
861
+ """编辑排队任务的需求数据(仅 queued 可改)。Go 版 /tasks/update 对齐。"""
862
+ ident = await _identity(request)
863
+ if ident is None:
864
+ return JSONResponse({"detail": "未登录或无权访问 DevChat"}, status_code=401)
865
+ body = await request.json()
866
+ task_id = str(body.get("id") or "").strip()
867
+ prompt = str(body.get("prompt") or "").strip()
868
+ if not task_id or not prompt:
869
+ return JSONResponse({"detail": "id 与 prompt 不能为空"}, status_code=400)
870
+ if st.tasks is None:
871
+ return JSONResponse({"detail": "任务存储不可用"}, status_code=503)
872
+ try:
873
+ st.tasks.update_prompt(task_id, prompt)
874
+ except ValueError as exc:
875
+ return JSONResponse({"detail": str(exc)}, status_code=409)
876
+ st.broadcast_tasks()
877
+ return {"success": True}
878
+
879
+ @router.post("/tasks/delete")
880
+ async def task_delete(request: Request):
881
+ """删除排队任务(幂等;绝不影响在跑任务)。"""
882
+ ident = await _identity(request)
883
+ if ident is None:
884
+ return JSONResponse({"detail": "未登录或无权访问 DevChat"}, status_code=401)
885
+ body = await request.json()
886
+ task_id = str(body.get("id") or "").strip()
887
+ if not task_id:
888
+ return JSONResponse({"detail": "id 不能为空"}, status_code=400)
889
+ if st.tasks is None:
890
+ return JSONResponse({"detail": "任务存储不可用"}, status_code=503)
891
+ with contextlib.suppress(Exception):
892
+ st.tasks.delete(task_id)
893
+ st.broadcast_tasks()
894
+ return {"success": True}
895
+
896
+ @router.post("/tasks/reorder")
897
+ async def task_reorder(request: Request):
898
+ """排队任务插队/上移/下移({id, ref_id?, before})。"""
899
+ ident = await _identity(request)
900
+ if ident is None:
901
+ return JSONResponse({"detail": "未登录或无权访问 DevChat"}, status_code=401)
902
+ body = await request.json()
903
+ task_id = str(body.get("id") or "").strip()
904
+ ref_id = str(body.get("ref_id") or "").strip()
905
+ before = body.get("before")
906
+ if not task_id or before is None:
907
+ return JSONResponse({"detail": "id 与 before 不能为空"}, status_code=400)
908
+ if st.tasks is None:
909
+ return JSONResponse({"detail": "任务存储不可用"}, status_code=503)
910
+ try:
911
+ st.tasks.reorder(task_id, ref_id, bool(before))
912
+ except ValueError as exc:
913
+ return JSONResponse({"detail": str(exc)}, status_code=409)
914
+ st.broadcast_tasks()
915
+ return {"success": True}
916
+
768
917
  @router.get("/tasks")
769
918
  async def tasks_list(request: Request, limit: int = 100):
770
919
  ident = await _identity(request)
@@ -833,6 +982,61 @@ def setup_devchat_handler(app: FastAPI, config: Optional[dict] = None) -> FastAP
833
982
  except Exception as exc: # noqa: BLE001
834
983
  return JSONResponse({"detail": f"上传失败: {exc}"}, status_code=500)
835
984
 
985
+ # ---- 内置登录(LDAP 模式才挂;静态资源放行让登录页可加载) ----
986
+
987
+ @router.post("/login")
988
+ async def login(request: Request):
989
+ """LDAP 用户名密码 → 会话 cookie(返回形态对齐 Go 版 {success,user?,error?})。"""
990
+ if ldap_authn is None:
991
+ return JSONResponse({"success": False, "error": "LDAP 未配置"}, status_code=503)
992
+ try:
993
+ body = await request.json()
994
+ except Exception: # noqa: BLE001
995
+ body = {}
996
+ username = str(body.get("username") or "").strip()
997
+ password = str(body.get("password") or "")
998
+ if not username or not password:
999
+ return {"success": False, "error": "用户名和密码不能为空"}
1000
+ display, err = await ldap_authn(username, password)
1001
+ if err is not None:
1002
+ return {"success": False, "error": f"认证失败: {err}"}
1003
+ username = username.replace(" ", "").lower()
1004
+ if not display:
1005
+ display = username
1006
+ token = new_login_token()
1007
+ if isinstance(login_store, dict):
1008
+ login_store[token] = LoginSession(username=username, display_name=display,
1009
+ expires_at=time.time() + login_ttl)
1010
+ else:
1011
+ login_store.put(token, LoginSession(username=username, display_name=display,
1012
+ expires_at=time.time() + login_ttl))
1013
+ resp = JSONResponse({"success": True,
1014
+ "user": {"username": username, "display_name": display}})
1015
+ resp.set_cookie(LOGIN_COOKIE_NAME, token, max_age=login_ttl,
1016
+ httponly=True, samesite="lax", path="/")
1017
+ return resp
1018
+
1019
+ @router.post("/logout")
1020
+ async def logout(request: Request):
1021
+ token = request.cookies.get(LOGIN_COOKIE_NAME, "")
1022
+ if token:
1023
+ if isinstance(login_store, dict):
1024
+ login_store.pop(token, None)
1025
+ else:
1026
+ login_store.del_token(token)
1027
+ resp = JSONResponse({"success": True})
1028
+ resp.delete_cookie(LOGIN_COOKIE_NAME, path="/")
1029
+ return resp
1030
+
1031
+ @router.get("/whoami")
1032
+ async def whoami(request: Request):
1033
+ if login_store is None:
1034
+ return JSONResponse({"detail": "匿名模式"}, status_code=404)
1035
+ ident = _login_identity(request)
1036
+ if ident is None:
1037
+ return JSONResponse({"detail": "未登录"}, status_code=401)
1038
+ return {"username": ident[0], "display_name": ident[1]}
1039
+
836
1040
  @router.get("/status")
837
1041
  async def status(request: Request):
838
1042
  ident = await _identity(request)
@@ -0,0 +1,223 @@
1
+ """devchat 内置登录(LDAP)— Go 版 web/devchat/login.go 的 Python 对齐。
2
+
3
+ 配置了 LDAP(nacos llm 共享配置的 LDAP.*,或 DevchatService 显式
4
+ ldap dict)后,devchat 全部数据端点要求登录;未登录回 401,面板自动弹
5
+ 登录框。匿名模式(既无 identityFunc 也无 LDAP)保持原样,仅限本机调试。
6
+
7
+ 会话模型:POST /devchat/login {username,password} → LDAP 认证 → 随机
8
+ token 落 SQLite(devchat_logins)+ HttpOnly cookie devchat_token(7 天,
9
+ 与服务端同 TTL)。同浏览器后续请求带 cookie 免登录;SQLite 持久 →
10
+ 服务重启后会话仍有效。登出删行 + 清 cookie。
11
+
12
+ 密码只在认证调用中瞬时使用,不落库不落日志(安全红线)。
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ import base64
18
+ import os
19
+ import secrets
20
+ import sqlite3
21
+ import time
22
+ from dataclasses import dataclass
23
+ from typing import Optional, Tuple
24
+
25
+ from sycommon.logging.kafka_log import SYLogger
26
+
27
+ LOGIN_COOKIE_NAME = "devchat_token"
28
+ LOGIN_TTL_DEFAULT = 7 * 24 * 3600 # 7 天(秒)
29
+
30
+ _SCHEMA = """
31
+ CREATE TABLE IF NOT EXISTS devchat_logins (
32
+ token TEXT PRIMARY KEY,
33
+ username TEXT NOT NULL DEFAULT '',
34
+ display_name TEXT NOT NULL DEFAULT '',
35
+ created_at DATETIME NOT NULL,
36
+ expires_at DATETIME NOT NULL
37
+ );
38
+ CREATE INDEX IF NOT EXISTS idx_devchat_logins_user ON devchat_logins(username);
39
+ """
40
+
41
+
42
+ def _ts(dt: float) -> str:
43
+ """Unix 秒 → SQLite DATETIME 串(与 Go 侧 '2006-01-02 15:04:05.000000' 对齐)。"""
44
+ import datetime as _dt
45
+
46
+ return _dt.datetime.fromtimestamp(dt, tz=_dt.timezone.utc).strftime(
47
+ "%Y-%m-%d %H:%M:%S.%f"
48
+ )
49
+
50
+
51
+ @dataclass
52
+ class LoginSession:
53
+ username: str
54
+ display_name: str
55
+ expires_at: float
56
+
57
+
58
+ class SqliteLoginStore:
59
+ """登录会话存取(SQLite devchat_logins 表;与任务/事件/消息同库)。"""
60
+
61
+ def __init__(self, conn: sqlite3.Connection):
62
+ self._conn = conn
63
+ with self._conn:
64
+ self._conn.executescript(_SCHEMA)
65
+
66
+ def get(self, token: str) -> Optional[LoginSession]:
67
+ row = self._conn.execute(
68
+ "SELECT username, display_name, expires_at FROM devchat_logins"
69
+ " WHERE token=?",
70
+ (token,),
71
+ ).fetchone()
72
+ if row is None:
73
+ return None
74
+ username, display_name, expires_at = row
75
+ exp = _parse_dt(expires_at)
76
+ if exp is None:
77
+ return None
78
+ if time.time() > exp:
79
+ with self._conn:
80
+ self._conn.execute(
81
+ "DELETE FROM devchat_logins WHERE token=?", (token,)
82
+ )
83
+ return None
84
+ return LoginSession(username=username or "", display_name=display_name or "",
85
+ expires_at=exp)
86
+
87
+ def put(self, token: str, s: LoginSession) -> None:
88
+ now = time.time()
89
+ with self._conn:
90
+ self._conn.execute(
91
+ "INSERT OR REPLACE INTO devchat_logins"
92
+ " (token, username, display_name, created_at, expires_at)"
93
+ " VALUES (?,?,?,?,?)",
94
+ (token, s.username, s.display_name, _ts(now), _ts(s.expires_at)),
95
+ )
96
+ # 顺带清理全部过期行(低频写路径,代价可忽略)。
97
+ self._conn.execute(
98
+ "DELETE FROM devchat_logins WHERE expires_at < ?", (_ts(now),)
99
+ )
100
+
101
+ def del_token(self, token: str) -> None:
102
+ with self._conn:
103
+ self._conn.execute("DELETE FROM devchat_logins WHERE token=?", (token,))
104
+
105
+
106
+ def _parse_dt(s: str) -> Optional[float]:
107
+ """SQLite DATETIME 串 → Unix 秒(容错:解析失败返回 None)。"""
108
+ import datetime as _dt
109
+
110
+ try:
111
+ d = _dt.datetime.strptime(s, "%Y-%m-%d %H:%M:%S.%f")
112
+ except (ValueError, TypeError):
113
+ try:
114
+ d = _dt.datetime.strptime(s, "%Y-%m-%d %H:%M:%S")
115
+ except (ValueError, TypeError):
116
+ return None
117
+ return d.replace(tzinfo=_dt.timezone.utc).timestamp()
118
+
119
+
120
+ class LdapAuthn:
121
+ """LDAPService 适配:认证成功后 search_user 取显示名(查不到退用户名 —
122
+ 登录不因目录查询失败而拒人)。密码仅在调用期间使用,不落任何存储。"""
123
+
124
+ def __init__(self, svc):
125
+ self._svc = svc
126
+
127
+ async def __call__(self, username: str, password: str) -> Tuple[str, Optional[Exception]]:
128
+ result = await self._svc.authenticate(username, password)
129
+ if not result.success:
130
+ return "", Exception(result.error or "认证失败")
131
+ try:
132
+ u = await self._svc.search_user(username)
133
+ if u is not None and (u.display_name or "").strip():
134
+ return (u.display_name or "").strip(), None
135
+ except Exception: # noqa: BLE001 — 目录查询失败不拒登录
136
+ pass
137
+ return username.strip(), None
138
+
139
+
140
+ def new_login_token() -> str:
141
+ """32 字节随机 → URL-safe base64(与 Go newLoginToken 同构)。"""
142
+ return base64.urlsafe_b64encode(secrets.token_bytes(32)).decode()
143
+
144
+
145
+ def ldap_settings_from_env() -> Optional[dict]:
146
+ """环境变量显式 LDAP(DEVCHAT_LDAP_URLS 等)→ settings dict。
147
+
148
+ 返回 None = 未显式指定(调用方继续走 nacos llm 共享配置装配)。
149
+ """
150
+
151
+ def _multi(v: str) -> list:
152
+ return [p.strip() for p in v.split(",") if p.strip()]
153
+
154
+ urls = os.environ.get("DEVCHAT_LDAP_URLS", "").strip()
155
+ if not urls:
156
+ return None
157
+ s = {"urls": _multi(urls)}
158
+ for env_key, key in (
159
+ ("DEVCHAT_LDAP_BASE", "base"),
160
+ ("DEVCHAT_LDAP_USERNAME", "username"),
161
+ ("DEVCHAT_LDAP_PASSWORD", "password"),
162
+ ("DEVCHAT_LDAP_DEFAULT_DC", "defaultDC"),
163
+ ):
164
+ if v := os.environ.get(env_key, "").strip():
165
+ s[key] = v
166
+ if not s.get("base") or not s.get("username") or not s.get("password"):
167
+ SYLogger.warning(
168
+ "[Devchat] DEVCHAT_LDAP_URLS 已设但 base/username/password 缺失,忽略"
169
+ )
170
+ return None
171
+ return s
172
+
173
+
174
+ def ldap_settings_from_config(config: Optional[dict]) -> Optional[dict]:
175
+ """宿主 config dict(提升后形态,顶层 LDAP.*)读 LDAP 登录配置。
176
+
177
+ 键路径与 Go 版 ldapSettingsFromConfig 对齐:先顶层 LDAP.*,再
178
+ llm→LDAP.*(未提升路径兼容)。任一必填缺失返回 None(不启用)。
179
+ """
180
+ if not isinstance(config, dict):
181
+ return None
182
+ raw = config.get("LDAP")
183
+ if not isinstance(raw, dict):
184
+ llm = config.get("llm")
185
+ raw = llm.get("LDAP") if isinstance(llm, dict) else None
186
+ if not isinstance(raw, dict):
187
+ return None
188
+
189
+ def _s(key: str) -> str:
190
+ v = raw.get(key)
191
+ return v.strip() if isinstance(v, str) else ""
192
+
193
+ urls, base = _s("urls"), _s("base")
194
+ user, password = _s("username"), _s("password")
195
+ if not urls or not base or not user or not password:
196
+ return None
197
+ s = {
198
+ "urls": [p.strip() for p in urls.split(",") if p.strip()],
199
+ "base": base,
200
+ "username": user,
201
+ "password": password,
202
+ }
203
+ if dc := _s("defaultDC"):
204
+ s["defaultDC"] = dc
205
+ return s
206
+
207
+
208
+ def build_ldap_authn(settings: dict):
209
+ """settings dict → LdapAuthn(失败返回 None,登录禁用 fail-soft)。"""
210
+ try:
211
+ from sycommon.auth.ldap_service import LDAPConfig, LDAPService
212
+
213
+ cfg = LDAPConfig(
214
+ urls=list(settings["urls"]),
215
+ base=settings["base"],
216
+ username=settings["username"],
217
+ password=settings["password"],
218
+ default_dc=settings.get("defaultDC", ""),
219
+ )
220
+ return LdapAuthn(LDAPService(cfg))
221
+ except Exception as exc: # noqa: BLE001
222
+ SYLogger.warning(f"[Devchat] LDAP config invalid, login disabled: {exc}")
223
+ return None
sycommon/devchat/tasks.py CHANGED
@@ -182,6 +182,82 @@ class SqliteTaskStore:
182
182
  duration_ms=row["duration_ms"] or 0, error=row["error"],
183
183
  created_at=row["created_at"])
184
184
 
185
+ def update_prompt(self, task_id: str, prompt: str) -> None:
186
+ """编辑排队任务的需求数据(仅 queued 可改;Go 版 UpdatePrompt 对齐)。
187
+ 行不存在或非 queued → ValueError(调用方回 409)。"""
188
+ with self._mu, self._conn:
189
+ cur = self._conn.execute(
190
+ "UPDATE devchat_tasks SET prompt=? WHERE id=? AND status=?",
191
+ (prompt, task_id, TASK_QUEUED))
192
+ if not cur.rowcount:
193
+ raise ValueError(f"task {task_id} not queued (cannot edit)")
194
+
195
+ def delete(self, task_id: str) -> None:
196
+ """删除排队任务(幂等:不存在或已终态 = no-op)。"""
197
+ with self._mu, self._conn:
198
+ self._conn.execute(
199
+ "DELETE FROM devchat_tasks WHERE id=? AND status=?",
200
+ (task_id, TASK_QUEUED))
201
+
202
+ def reorder(self, task_id: str, ref_id: str = "", before: bool = True) -> None:
203
+ """插队/调整优先级(seq=纳秒时戳,小 = 先执行)。Go 版 Reorder 对齐:
204
+ ref 空 → before=队首(MIN-1)/队尾(MAX+1);ref 给出 → ref 前后邻中点。
205
+ 仅 queued 可动;running 及终态不受影响。错误 → ValueError(409)。"""
206
+ with self._mu, self._conn:
207
+ row = self._conn.execute(
208
+ "SELECT status, seq FROM devchat_tasks WHERE id=?", (task_id,)
209
+ ).fetchone()
210
+ if row is None:
211
+ raise ValueError(f"task {task_id} not found")
212
+ if row["status"] != TASK_QUEUED:
213
+ raise ValueError(f"task {task_id} not queued (cannot reorder)")
214
+ cur_seq = row["seq"]
215
+
216
+ if not ref_id:
217
+ if before:
218
+ extreme = self._conn.execute(
219
+ "SELECT MIN(seq) AS v FROM devchat_tasks WHERE status=?",
220
+ (TASK_QUEUED,)).fetchone()
221
+ else:
222
+ extreme = self._conn.execute(
223
+ "SELECT MAX(seq) AS v FROM devchat_tasks WHERE status=?",
224
+ (TASK_QUEUED,)).fetchone()
225
+ if extreme is None or extreme["v"] is None:
226
+ raise ValueError("no queued tasks to reorder against")
227
+ new_seq = extreme["v"] + (-1 if before else 1)
228
+ elif ref_id == task_id:
229
+ return # 自指 no-op
230
+ else:
231
+ ref = self._conn.execute(
232
+ "SELECT status, seq FROM devchat_tasks WHERE id=?", (ref_id,)
233
+ ).fetchone()
234
+ if ref is None:
235
+ raise ValueError(f"reference task {ref_id} not found")
236
+ if ref["status"] != TASK_QUEUED:
237
+ raise ValueError(f"reference task {ref_id} not queued")
238
+ ref_seq = ref["seq"]
239
+ if (before and cur_seq < ref_seq) or (not before and cur_seq > ref_seq):
240
+ return # 已在目标侧 no-op
241
+ if before:
242
+ nb = self._conn.execute(
243
+ "SELECT MAX(seq) AS v FROM devchat_tasks"
244
+ " WHERE status=? AND seq<?", (TASK_QUEUED, ref_seq)).fetchone()
245
+ else:
246
+ nb = self._conn.execute(
247
+ "SELECT MIN(seq) AS v FROM devchat_tasks"
248
+ " WHERE status=? AND seq>?", (TASK_QUEUED, ref_seq)).fetchone()
249
+ nbv = nb["v"] if nb is not None else None
250
+ if nbv is None:
251
+ new_seq = ref_seq + (-1 if before else 1)
252
+ else:
253
+ lo, hi = sorted((nbv, ref_seq))
254
+ mid = lo + (hi - lo) // 2
255
+ new_seq = mid if mid != lo else lo + 1
256
+ if new_seq == cur_seq:
257
+ return
258
+ self._conn.execute(
259
+ "UPDATE devchat_tasks SET seq=? WHERE id=?", (new_seq, task_id))
260
+
185
261
 
186
262
  class MemTaskStore:
187
263
  """内存降级(重启即失)。"""
@@ -200,6 +276,54 @@ class MemTaskStore:
200
276
  def recover_stale(self) -> int:
201
277
  return 0 # 内存态重启即失,无残影
202
278
 
279
+ def update_prompt(self, task_id: str, prompt: str) -> None:
280
+ with self._mu:
281
+ for t in self._items:
282
+ if t.id == task_id:
283
+ if t.status != TASK_QUEUED:
284
+ raise ValueError(f"task {task_id} not queued (cannot edit)")
285
+ t.prompt = prompt
286
+ return
287
+ raise ValueError(f"task {task_id} not found")
288
+
289
+ def delete(self, task_id: str) -> None:
290
+ with self._mu:
291
+ self._items = [t for t in self._items
292
+ if not (t.id == task_id and t.status == TASK_QUEUED)]
293
+
294
+ def reorder(self, task_id: str, ref_id: str = "", before: bool = True) -> None:
295
+ with self._mu:
296
+ queued = sorted([t for t in self._items if t.status == TASK_QUEUED],
297
+ key=lambda t: t.seq)
298
+ by_id = {t.id: t for t in queued}
299
+ cur = by_id.get(task_id)
300
+ if cur is None:
301
+ # 找不到 queued 的目标任务:可能不存在或非 queued → 统一 409 文案
302
+ raise ValueError(f"task {task_id} not found or not queued")
303
+ import time as _time
304
+ if not ref_id:
305
+ cur.seq = (queued[0].seq - 1) if before else (queued[-1].seq + 1)
306
+ return
307
+ ref = by_id.get(ref_id)
308
+ if ref is None:
309
+ raise ValueError(f"reference task {ref_id} not found or not queued")
310
+ idx = queued.index(ref)
311
+ if ref is cur:
312
+ return
313
+ if before and cur.seq < ref.seq:
314
+ return
315
+ if not before and cur.seq > ref.seq:
316
+ return
317
+ # 邻位 seq:ref 前一 / 后一(相对队列顺序)。
318
+ if before:
319
+ nb = queued[idx - 1] if idx > 0 else None
320
+ lo, hi = sorted((nb.seq, ref.seq)) if nb else (ref.seq - 2, ref.seq)
321
+ else:
322
+ nb = queued[idx + 1] if idx + 1 < len(queued) else None
323
+ lo, hi = sorted((nb.seq, ref.seq)) if nb else (ref.seq, ref.seq + 2)
324
+ mid = lo + (hi - lo) // 2
325
+ cur.seq = mid if mid != lo else lo + 1
326
+
203
327
  def update_status(self, task_id: str, status: str, error: str = "",
204
328
  started: Optional[float] = None,
205
329
  finished: Optional[float] = None) -> None:
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: sycommon-python-lib
3
- Version: 0.2.12a5
3
+ Version: 0.2.12a6
4
4
  Summary: Add your description here
5
5
  Requires-Python: >=3.11
6
6
  Description-Content-Type: text/markdown
@@ -215,11 +215,12 @@ sycommon/database/resilient_pg_saver.py,sha256=S5hOoF7gGTa0b4-P3dM_iLy1GFesG_jEn
215
215
  sycommon/database/token_usage_db_service.py,sha256=iYK51ZtGNpBA4nj2IhflltbftE5Fsc3C0UksSJr-phY,10152
216
216
  sycommon/database/txnref.py,sha256=sOFp85PlanCA0oryVpHu53JbM0aSHAVkELWgEJKalLI,7755
217
217
  sycommon/devchat/__init__.py,sha256=Z2BgzDKrp_mR165d3a1kftP8lf1-WKz_5xuZMFXR-iw,2288
218
- sycommon/devchat/_page.html,sha256=ArLQMgymJhj9J3z00Y9fwHOhlc5jukhbifBuLh6cDeU,26007
218
+ sycommon/devchat/_page.html,sha256=CxzEhC867FawFjlEKk6uCChEX3EoRP4jwdn09C_MdaU,29126
219
219
  sycommon/devchat/_page.py,sha256=JzTX7Wv_4-nJky7wg5E44yftSQYvC9L9_YsQzNnaWhI,406
220
- sycommon/devchat/handler.py,sha256=nlyBO-pVm5g_snxGZT_vAq0zAnGg1c6pzz94zHFmewY,38214
220
+ sycommon/devchat/handler.py,sha256=PGYdmQHTY2SWRXVmFrYLyW0dZww1Wa-4oBfzEUXYMDQ,47400
221
+ sycommon/devchat/login.py,sha256=TF57n0iP3jHgiYs4NdDDgAXlGJNtiKcW8haw9Rd9Jjo,7701
221
222
  sycommon/devchat/store.py,sha256=iAxCJs5jrNbRDCVL4i0QnbEAUGLXtJumf8YsBGwfBe0,4047
222
- sycommon/devchat/tasks.py,sha256=r4v-ZWibJzr4y3uQzGvVtDQ87R3Zfc-togCveLxa5l8,13030
223
+ sycommon/devchat/tasks.py,sha256=ijGHe2gyBfEZ11ylqvRihQDtbF2ugchQ6AzdyNCbD_0,19080
223
224
  sycommon/health/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
224
225
  sycommon/health/health_check.py,sha256=EhfbhspRpQiKJaxdtE-PzpKQO_ucaFKtQxIm16F5Mpk,391
225
226
  sycommon/health/metrics.py,sha256=fHqO73JuhoZkNPR-xIlxieXiTCvttq-kG-tvxag1s1s,268
@@ -402,8 +403,8 @@ sycommon/tools/usercache.py,sha256=Zu2oiXISUOojleEYCAS9t06ZzgWSNHCIhCjv4yTtkRw,4
402
403
  sycommon/xxljob/__init__.py,sha256=7eoBlQxv-B39IfRSCY2bkqdGYs1QRe1umAWd88VMEEM,86
403
404
  sycommon/xxljob/sharding.py,sha256=LJ0tle7qSUS32S5ntjzri1aOcPzwL5CFde3W4Rf1AUE,2560
404
405
  sycommon/xxljob/xxljob_service.py,sha256=1yifwIBNGsCIxLnQjHKiBlbsigc_zvPH-dMTZcNxe-Q,7649
405
- sycommon_python_lib-0.2.12a5.dist-info/METADATA,sha256=r1u8Gyr23LnD18adv8eiXG4mHH5ODrCIbJ7-50CXcuQ,8028
406
- sycommon_python_lib-0.2.12a5.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
407
- sycommon_python_lib-0.2.12a5.dist-info/entry_points.txt,sha256=gsR4SssKxDWjRU8ggidzNcdMXDPRSKRS7UaGyNP84Qg,92
408
- sycommon_python_lib-0.2.12a5.dist-info/top_level.txt,sha256=RgphKrg7nJyZ7irJqbxFr-5H2LUYTvI7ivoWZH2hcD0,29
409
- sycommon_python_lib-0.2.12a5.dist-info/RECORD,,
406
+ sycommon_python_lib-0.2.12a6.dist-info/METADATA,sha256=sgZdAgKdyke6ZPhgGINbu6QrhEW2HSxgzEFIiczspB8,8028
407
+ sycommon_python_lib-0.2.12a6.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
408
+ sycommon_python_lib-0.2.12a6.dist-info/entry_points.txt,sha256=gsR4SssKxDWjRU8ggidzNcdMXDPRSKRS7UaGyNP84Qg,92
409
+ sycommon_python_lib-0.2.12a6.dist-info/top_level.txt,sha256=RgphKrg7nJyZ7irJqbxFr-5H2LUYTvI7ivoWZH2hcD0,29
410
+ sycommon_python_lib-0.2.12a6.dist-info/RECORD,,