-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmonitor_panel.py
More file actions
2079 lines (1906 loc) · 73.2 KB
/
Copy pathmonitor_panel.py
File metadata and controls
2079 lines (1906 loc) · 73.2 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
import argparse
import ipaddress
import json
import os
import re
import secrets
import sqlite3
import subprocess
import sys
import threading
import time
from datetime import datetime
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
from urllib.error import HTTPError, URLError
from urllib.parse import parse_qs, urlparse
from urllib.request import ProxyHandler, Request, build_opener
from cookie_sync import (
DEFAULT_DEBUG_URL,
cookie_is_usable,
fetch_best_cookie_header,
merge_cookie_headers,
should_replace_cookie,
summarize_cookie,
)
ROOT = Path(__file__).resolve().parent
IS_WINDOWS = os.name == "nt"
SERVICE_LABEL = "com.xianyu.autoagent"
SERVICE_PLIST = Path.home() / "Library/LaunchAgents/com.xianyu.autoagent.plist"
TASK_PREFIX = "XianyuAutoAgent"
AGENT_TASK_NAME = f"{TASK_PREFIX}-Service"
OLLAMA_TASK_NAME = f"{TASK_PREFIX}-Ollama"
DASHBOARD_TASK_NAME = f"{TASK_PREFIX}-Dashboard"
DB_PATH = ROOT / "data" / "chat_history.db"
TOKEN_PATH = ROOT / "data" / "dashboard_token.txt"
EXTENSION_UPDATE_PATH = "/extensions/xianyu-cookie-sync-update.xml"
EXTENSION_CRX_PATH = "/extensions/xianyu-cookie-sync.crx"
COOKIE_SYNC_STATE = {
"enabled": False,
"running": False,
"last_run": None,
"last_result": None,
"debug_url": DEFAULT_DEBUG_URL,
"interval_seconds": 300,
"retry_seconds": 60,
}
COOKIE_SYNC_THREAD = None
AGENT_LOG_PATH = ROOT / "logs" / ("agent.err.log" if IS_WINDOWS else "launchd.err.log")
OLLAMA_URL = os.getenv("OLLAMA_URL", "http://127.0.0.1:11434")
PROMPT_FILES = {
"classify_prompt": {"label": "意图分类", "file": "classify_prompt.txt"},
"default_prompt": {"label": "默认回复", "file": "default_prompt.txt"},
"tech_prompt": {"label": "技术/使用咨询", "file": "tech_prompt.txt"},
"price_prompt": {"label": "议价回复", "file": "price_prompt.txt"},
}
def parse_launchctl_status(text):
state_match = re.search(r"\bstate = ([^\n]+)", text)
pid_match = re.search(r"\bpid = (\d+)", text)
runs_match = re.search(r"\bruns = (\d+)", text)
state = state_match.group(1).strip() if state_match else "unknown"
pid = int(pid_match.group(1)) if pid_match else None
runs = int(runs_match.group(1)) if runs_match else 0
return {
"state": state,
"pid": pid,
"pids": [pid] if pid else [],
"runs": runs,
"running": state == "running" and pid is not None,
"needs_cookie": False,
}
def read_text_auto(path):
data = Path(path).read_bytes()
for encoding in ("utf-8-sig", "utf-8", "gb18030", "cp936"):
try:
return data.decode(encoding)
except UnicodeDecodeError:
continue
return data.decode("utf-8", errors="replace")
def is_loopback_host(host):
try:
return ipaddress.ip_address(host).is_loopback
except ValueError:
return str(host).lower() == "localhost"
def extension_asset_response(path, client_host, root=ROOT):
if not is_loopback_host(client_host):
return 403, b"extension assets are only available from loopback clients", "text/plain; charset=utf-8"
root = Path(root)
if path == EXTENSION_CRX_PATH:
asset_path = root / "chrome-cookie-extension.crx"
content_type = "application/x-chrome-extension"
elif path == EXTENSION_UPDATE_PATH:
asset_path = root / "chrome-cookie-extension-update.xml"
content_type = "text/xml; charset=utf-8"
else:
return 404, b"extension asset not found", "text/plain; charset=utf-8"
if not asset_path.exists():
return 404, b"extension asset not found", "text/plain; charset=utf-8"
return 200, asset_path.read_bytes(), content_type
def tail_lines(path, limit=120):
try:
lines = read_text_auto(path).splitlines()
except FileNotFoundError:
return []
return lines[-limit:]
def run_command(args, timeout=8):
try:
return subprocess.run(args, capture_output=True, text=True, timeout=timeout, encoding="utf-8", errors="replace")
except Exception as exc:
return subprocess.CompletedProcess(args=args, returncode=1, stdout="", stderr=str(exc))
def powershell(script):
executable = os.path.join(os.environ.get("SystemRoot", r"C:\Windows"), "System32", "WindowsPowerShell", "v1.0", "powershell.exe")
if not Path(executable).exists():
executable = "powershell"
return run_command([executable, "-NoProfile", "-ExecutionPolicy", "Bypass", "-Command", script], timeout=12)
def current_launchctl_output(label=SERVICE_LABEL):
result = run_command(["launchctl", "print", f"gui/{os.getuid()}/{label}"])
return result.stdout if result.returncode == 0 else result.stderr
def get_dashboard_token():
env_token = os.getenv("DASHBOARD_TOKEN", "").strip()
if env_token:
return env_token
TOKEN_PATH.parent.mkdir(parents=True, exist_ok=True)
if TOKEN_PATH.exists():
token = TOKEN_PATH.read_text(encoding="utf-8", errors="replace").strip()
if token:
return token
token = secrets.token_urlsafe(24)
TOKEN_PATH.write_text(token, encoding="utf-8")
return token
def read_env_pairs(env_path):
pairs = {}
try:
lines = Path(env_path).read_text(encoding="utf-8-sig", errors="replace").splitlines()
except FileNotFoundError:
return pairs
for raw_line in lines:
line = raw_line.lstrip("\ufeff")
if not line or line.lstrip().startswith("#") or "=" not in line:
continue
key, value = line.split("=", 1)
pairs[key.strip()] = value
return pairs
def read_prompt_file(prompt_id):
meta = PROMPT_FILES.get(prompt_id)
if not meta:
raise KeyError(prompt_id)
path = ROOT / "prompts" / meta["file"]
try:
return read_text_auto(path)
except FileNotFoundError:
example_path = ROOT / "prompts" / meta["file"].replace(".txt", "_example.txt")
return read_text_auto(example_path) if example_path.exists() else ""
def prompt_payload():
prompts = []
for prompt_id, meta in PROMPT_FILES.items():
text = read_prompt_file(prompt_id)
prompts.append({
"id": prompt_id,
"label": meta["label"],
"filename": meta["file"],
"text": text,
"length": len(text),
})
return {"prompts": prompts}
def update_prompt(prompt_id, text):
meta = PROMPT_FILES.get(prompt_id)
if not meta:
return {"ok": False, "message": "未知提示词类型"}
text = (text or "").strip()
if len(text) < 20:
return {"ok": False, "message": "提示词太短,保存前请补充完整规则"}
prompt_dir = ROOT / "prompts"
prompt_dir.mkdir(parents=True, exist_ok=True)
(prompt_dir / meta["file"]).write_text(text.rstrip() + "\n", encoding="utf-8")
return {"ok": True, "message": "提示词已保存", "prompt_id": prompt_id, "length": len(text)}
def ensure_item_profile_schema(db_path=DB_PATH):
Path(db_path).parent.mkdir(parents=True, exist_ok=True)
conn = sqlite3.connect(db_path)
try:
conn.execute(
"""
CREATE TABLE IF NOT EXISTS item_reply_profiles (
item_id TEXT PRIMARY KEY,
enabled INTEGER DEFAULT 1,
delivery_text TEXT DEFAULT '',
custom_prompt TEXT DEFAULT '',
updated_at DATETIME DEFAULT CURRENT_TIMESTAMP
)
"""
)
conn.commit()
finally:
conn.close()
def _item_title_from_data(data):
if not data:
return ""
try:
parsed = json.loads(data)
except (TypeError, json.JSONDecodeError):
return ""
return parsed.get("title") or parsed.get("itemTitle") or ""
def item_profile_payload(root=ROOT):
db_path = Path(root) / "data" / "chat_history.db"
if not db_path.exists():
return {"items": []}
ensure_item_profile_schema(db_path)
conn = sqlite3.connect(db_path)
conn.row_factory = sqlite3.Row
try:
rows = conn.execute(
"""
WITH all_items AS (
SELECT item_id FROM items
UNION
SELECT item_id FROM messages
),
message_stats AS (
SELECT item_id, COUNT(*) AS message_count, MAX(timestamp) AS last_message
FROM messages
GROUP BY item_id
)
SELECT
all_items.item_id,
items.data,
items.price,
COALESCE(items.description, '') AS description,
items.last_updated AS item_updated_at,
COALESCE(message_stats.message_count, 0) AS message_count,
message_stats.last_message,
COALESCE(item_reply_profiles.enabled, 1) AS enabled,
COALESCE(item_reply_profiles.delivery_text, '') AS delivery_text,
COALESCE(item_reply_profiles.custom_prompt, '') AS custom_prompt,
item_reply_profiles.updated_at AS profile_updated_at
FROM all_items
LEFT JOIN items ON items.item_id = all_items.item_id
LEFT JOIN message_stats ON message_stats.item_id = all_items.item_id
LEFT JOIN item_reply_profiles ON item_reply_profiles.item_id = all_items.item_id
ORDER BY COALESCE(message_stats.last_message, items.last_updated, '') DESC
"""
).fetchall()
except sqlite3.Error:
return {"items": []}
finally:
conn.close()
items = []
for row in rows:
item = dict(row)
item["title"] = _item_title_from_data(item.pop("data", ""))
item["enabled"] = bool(item["enabled"])
item["description_preview"] = (item.get("description") or "").replace("\n", " ")[:160]
item["configured"] = bool((item.get("delivery_text") or "").strip() or (item.get("custom_prompt") or "").strip())
items.append(item)
return {"items": items}
def update_item_profile(item_id, enabled=True, delivery_text="", custom_prompt="", root=ROOT):
item_id = str(item_id or "").strip()
if not item_id:
return {"ok": False, "message": "缺少商品 ID"}
db_path = Path(root) / "data" / "chat_history.db"
ensure_item_profile_schema(db_path)
delivery_text = (delivery_text or "").strip()
custom_prompt = (custom_prompt or "").strip()
enabled_value = 1 if enabled else 0
updated_at = datetime.now().isoformat()
conn = sqlite3.connect(db_path)
try:
conn.execute(
"""
INSERT INTO item_reply_profiles (item_id, enabled, delivery_text, custom_prompt, updated_at)
VALUES (?, ?, ?, ?, ?)
ON CONFLICT(item_id)
DO UPDATE SET enabled = ?, delivery_text = ?, custom_prompt = ?, updated_at = ?
""",
(
item_id, enabled_value, delivery_text, custom_prompt, updated_at,
enabled_value, delivery_text, custom_prompt, updated_at,
),
)
conn.commit()
finally:
conn.close()
return {
"ok": True,
"message": "商品策略已保存",
"item_id": item_id,
"enabled": bool(enabled_value),
}
def read_safe_config(env_path):
values = {}
env_path = Path(env_path)
pairs = read_env_pairs(env_path)
default_pairs = read_env_pairs(env_path.parent / ".env.windows.example")
effective_pairs = dict(default_pairs)
effective_pairs.update({key: value for key, value in pairs.items() if value})
for key in ["MODEL_NAME", "MODEL_BASE_URL", "LOG_LEVEL", "SIMULATE_HUMAN_TYPING", "TOGGLE_KEYWORDS", "ENABLE_MODEL_SEARCH"]:
if key in effective_pairs:
values[key] = effective_pairs[key]
api_key = effective_pairs.get("API_KEY", "")
cookie = pairs.get("COOKIES_STR", "")
cookie_summary = summarize_cookie(cookie) if cookie and cookie != "your_cookies_here" else {}
values["API_KEY"] = "已设置" if api_key else "未设置"
values["COOKIES_STR"] = "已设置" if cookie and cookie != "your_cookies_here" else "未设置"
values["COOKIE_LENGTH"] = len(cookie) if cookie and cookie != "your_cookies_here" else 0
values["COOKIE_HAS_X5SEC"] = bool(cookie_summary.get("has_x5sec"))
return values
def default_env_values(env_path):
defaults = read_env_pairs(Path(env_path).parent / ".env.windows.example")
return {
key: value
for key, value in defaults.items()
if key != "COOKIES_STR" and value and value != "your_cookies_here"
}
def set_env_value(env_path, key, value):
path = Path(env_path)
try:
lines = path.read_text(encoding="utf-8-sig", errors="replace").splitlines()
except FileNotFoundError:
lines = []
replaced = False
updated_lines = []
for raw_line in lines:
line = raw_line.lstrip("\ufeff")
if line.startswith(f"{key}="):
updated_lines.append(f"{key}={value}")
replaced = True
else:
updated_lines.append(line)
if not replaced:
updated_lines.append(f"{key}={value}")
existing_keys = {
line.split("=", 1)[0]
for line in updated_lines
if "=" in line
}
for default_key, default_value in default_env_values(path).items():
if default_key not in existing_keys:
updated_lines.append(f"{default_key}={default_value}")
path.write_text("\n".join(updated_lines).rstrip() + "\n", encoding="utf-8")
def truthy(value):
return str(value or "").strip().lower() in {"1", "true", "yes", "on", "y"}
def cookie_sync_config(root=ROOT):
pairs = read_env_pairs(Path(root) / ".env")
enabled = truthy(pairs.get("AUTO_COOKIE_SYNC_ENABLED", os.getenv("AUTO_COOKIE_SYNC_ENABLED", "")))
debug_url = (
pairs.get("CHROME_DEBUG_URL")
or pairs.get("COOKIE_SYNC_DEBUG_URL")
or os.getenv("CHROME_DEBUG_URL")
or os.getenv("COOKIE_SYNC_DEBUG_URL")
or DEFAULT_DEBUG_URL
)
raw_interval = pairs.get("AUTO_COOKIE_SYNC_INTERVAL_SECONDS", os.getenv("AUTO_COOKIE_SYNC_INTERVAL_SECONDS", "300"))
raw_retry = pairs.get("AUTO_COOKIE_SYNC_RETRY_SECONDS", os.getenv("AUTO_COOKIE_SYNC_RETRY_SECONDS", "60"))
try:
interval_seconds = max(60, int(raw_interval))
except ValueError:
interval_seconds = 300
try:
retry_seconds = max(30, int(raw_retry))
except ValueError:
retry_seconds = 60
return {
"enabled": enabled,
"debug_url": debug_url,
"interval_seconds": interval_seconds,
"retry_seconds": retry_seconds,
}
def sync_cookie_from_browser_once(root=ROOT, fetch_cookie=fetch_best_cookie_header, restart_func=None):
root = Path(root)
config = cookie_sync_config(root)
env_path = root / ".env"
pairs = read_env_pairs(env_path)
current_cookie = pairs.get("COOKIES_STR", "")
now = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
try:
candidate_cookie = (fetch_cookie(config["debug_url"]) or "").strip()
except Exception as exc:
return {
"ok": False,
"changed": False,
"message": f"读取 Chrome Cookie 失败: {exc}",
"last_run": now,
"debug_url": config["debug_url"],
}
merged_cookie = merge_cookie_headers(current_cookie, candidate_cookie)
summary = summarize_cookie(merged_cookie)
if not cookie_is_usable(merged_cookie):
return {
"ok": False,
"changed": False,
"message": "Chrome 里读到的 Cookie 不完整,需要包含 unb 和 _m_h5_tk",
"last_run": now,
"debug_url": config["debug_url"],
"cookie": summary,
}
if not should_replace_cookie(current_cookie, merged_cookie):
return {
"ok": True,
"changed": False,
"message": "Cookie 没有变化",
"last_run": now,
"debug_url": config["debug_url"],
"cookie": summary,
}
set_env_value(env_path, "COOKIES_STR", merged_cookie)
restart_result = (restart_func or restart_service)()
return {
"ok": bool(restart_result.get("ok")),
"changed": True,
"message": "Cookie 已从浏览器同步并重启 Agent",
"last_run": now,
"debug_url": config["debug_url"],
"cookie": summary,
"restart": restart_result,
}
def agent_should_restart_for_cookie(root=ROOT):
if IS_WINDOWS:
service = windows_service_status(Path(root))
return service.get("needs_cookie") or not service.get("running")
service = parse_launchctl_status(current_launchctl_output())
return not service.get("running")
def agent_requires_validation_cookie(root=ROOT):
root = Path(root)
agent_logs = tail_lines(root / "logs" / ("agent.err.log" if IS_WINDOWS else "launchd.err.log"), 180)
out_logs = tail_lines(root / "logs" / ("agent.out.log" if IS_WINDOWS else "launchd.out.log"), 80)
joined = "\n".join(agent_logs + out_logs)
return "RGV587_ERROR" in joined or "FAIL_SYS_USER_VALIDATE" in joined
def accept_browser_cookie_sync(
cookie,
root=ROOT,
restart_func=None,
should_restart_func=None,
validation_cookie_required_func=None,
):
cookie = (cookie or "").strip()
now = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
root = Path(root)
env_path = root / ".env"
current_cookie = read_env_pairs(env_path).get("COOKIES_STR", "")
merged_cookie = merge_cookie_headers(current_cookie, cookie)
summary = summarize_cookie(merged_cookie)
if not cookie_is_usable(merged_cookie):
return {
"ok": False,
"changed": False,
"restarted": False,
"message": "浏览器扩展发来的 Cookie 不完整,需要包含 unb 和 _m_h5_tk",
"last_run": now,
"cookie": summary,
}
if not should_replace_cookie(current_cookie, merged_cookie):
return {
"ok": True,
"changed": False,
"restarted": False,
"message": "浏览器 Cookie 没有变化",
"last_run": now,
"cookie": summary,
}
set_env_value(env_path, "COOKIES_STR", merged_cookie)
should_restart = (should_restart_func or (lambda: agent_should_restart_for_cookie(root)))()
validation_cookie_required = (
validation_cookie_required_func
or (lambda: agent_requires_validation_cookie(root))
)()
result = {
"ok": True,
"changed": True,
"restarted": False,
"message": "浏览器 Cookie 已保存",
"last_run": now,
"cookie": summary,
}
if should_restart and validation_cookie_required and not summary.get("has_x5sec"):
result["message"] = "浏览器 Cookie 已保存,但仍缺少 x5sec,暂不重启 Agent"
elif should_restart:
restart_result = (restart_func or restart_service)()
result["restart"] = restart_result
result["restarted"] = bool(restart_result.get("ok"))
result["ok"] = bool(restart_result.get("ok"))
result["message"] = "浏览器 Cookie 已保存,并已重启 Agent"
return result
def start_cookie_sync_worker():
global COOKIE_SYNC_THREAD
if COOKIE_SYNC_THREAD and COOKIE_SYNC_THREAD.is_alive():
return
def loop():
while True:
config = cookie_sync_config()
COOKIE_SYNC_STATE.update(config)
if not config["enabled"]:
COOKIE_SYNC_STATE["running"] = False
time.sleep(60)
continue
COOKIE_SYNC_STATE["running"] = True
result = sync_cookie_from_browser_once()
COOKIE_SYNC_STATE["last_run"] = result.get("last_run")
COOKIE_SYNC_STATE["last_result"] = result
time.sleep(config["interval_seconds"] if result.get("ok") else config["retry_seconds"])
COOKIE_SYNC_THREAD = threading.Thread(target=loop, name="cookie-sync", daemon=True)
COOKIE_SYNC_THREAD.start()
def read_recent_messages(db_path=DB_PATH, limit=30):
if not Path(db_path).exists():
return []
conn = sqlite3.connect(db_path)
conn.row_factory = sqlite3.Row
try:
rows = conn.execute(
"""
SELECT id, timestamp, chat_id, user_id, item_id, role, content
FROM messages
ORDER BY id DESC
LIMIT ?
""",
(limit,),
).fetchall()
return [dict(row) for row in rows]
except sqlite3.Error:
return []
finally:
conn.close()
def get_table_count(db_path, table_name):
if not Path(db_path).exists():
return 0
conn = sqlite3.connect(db_path)
try:
row = conn.execute(f"SELECT COUNT(*) FROM {table_name}").fetchone()
return int(row[0]) if row else 0
except sqlite3.Error:
return 0
finally:
conn.close()
def get_db_stats(db_path=DB_PATH):
return {
"message_count": get_table_count(db_path, "messages"),
"item_count": get_table_count(db_path, "items"),
"bargain_chat_count": get_table_count(db_path, "chat_bargain_counts"),
"db_size_bytes": Path(db_path).stat().st_size if Path(db_path).exists() else 0,
}
def format_command_result(result):
return {
"ok": result.returncode == 0,
"returncode": result.returncode,
"stdout": result.stdout[-2000:],
"stderr": result.stderr[-2000:],
}
def windows_process_snapshot():
script = r"""
$items = Get-CimInstance Win32_Process |
Where-Object { $_.Name -in @('python.exe','ollama.exe') } |
Select-Object ProcessId,ParentProcessId,Name,ExecutablePath,CommandLine
$items | ConvertTo-Json -Compress
"""
result = powershell(script)
if result.returncode != 0 or not result.stdout.strip():
return []
try:
data = json.loads(result.stdout)
except json.JSONDecodeError:
return []
if isinstance(data, dict):
return [data]
return data if isinstance(data, list) else []
def detect_needs_cookie(agent_logs, out_logs):
joined = "\n".join((agent_logs or [])[-120:] + (out_logs or [])[-40:])
markers = ["FAIL_SYS_USER_VALIDATE", "RGV587_ERROR", "新的Cookie", "Cookie字符串", "Cookie已失效"]
return any(marker in joined for marker in markers)
def windows_service_status(root=ROOT):
root_text = str(root).lower()
processes = windows_process_snapshot()
agent_processes = []
ollama_processes = []
for process in processes:
command_line = str(process.get("CommandLine") or "")
executable = str(process.get("ExecutablePath") or "")
name = str(process.get("Name") or "")
if name.lower() == "python.exe" and "main.py" in command_line and root_text in (command_line + executable).lower():
agent_processes.append(process)
if name.lower() == "ollama.exe" and " serve" in f" {command_line} ":
ollama_processes.append(process)
agent_parent_ids = {
int(process["ParentProcessId"])
for process in agent_processes
if process.get("ParentProcessId") is not None
}
leaf_agent_processes = [
process for process in agent_processes
if process.get("ProcessId") is not None and int(process["ProcessId"]) not in agent_parent_ids
]
if leaf_agent_processes:
agent_processes = leaf_agent_processes
agent_logs = tail_lines(root / "logs" / "agent.err.log", 180)
out_logs = tail_lines(root / "logs" / "agent.out.log", 60)
pids = [int(process["ProcessId"]) for process in agent_processes if process.get("ProcessId") is not None]
needs_cookie = detect_needs_cookie(agent_logs, out_logs)
state = "needs_cookie" if needs_cookie else ("running" if pids else "stopped")
return {
"state": state,
"pid": pids[0] if pids else None,
"pids": pids,
"runs": len([line for line in tail_lines(root / "logs" / "agent-launch.log", 500) if "started pid" in line]),
"running": bool(pids),
"needs_cookie": needs_cookie,
"task_name": AGENT_TASK_NAME,
"ollama_pids": [int(process["ProcessId"]) for process in ollama_processes if process.get("ProcessId") is not None],
}
def disabled_proxy_opener():
return build_opener(ProxyHandler({}))
def http_json(url, body=None, timeout=8):
data = None
headers = {"Accept": "application/json"}
method = "GET"
if body is not None:
data = json.dumps(body, ensure_ascii=False).encode("utf-8")
headers["Content-Type"] = "application/json"
method = "POST"
request = Request(url, data=data, headers=headers, method=method)
with disabled_proxy_opener().open(request, timeout=timeout) as response:
return json.loads(response.read().decode("utf-8", errors="replace"))
def ollama_status():
try:
version = http_json(f"{OLLAMA_URL}/api/version", timeout=3).get("version", "")
return {"running": True, "version": version, "url": OLLAMA_URL}
except (HTTPError, URLError, TimeoutError, OSError, json.JSONDecodeError) as exc:
return {"running": False, "version": "", "url": OLLAMA_URL, "error": str(exc)}
def test_ollama_model(prompt="Reply with exactly: OK"):
config = read_env_pairs(ROOT / ".env")
model_name = config.get("MODEL_NAME", "qwen2.5:3b-instruct")
base_url = config.get("MODEL_BASE_URL", f"{OLLAMA_URL}/v1").rstrip("/")
body = {
"model": model_name,
"stream": False,
"messages": [{"role": "user", "content": prompt}],
}
try:
result = http_json(f"{base_url}/chat/completions", body=body, timeout=90)
content = result.get("choices", [{}])[0].get("message", {}).get("content", "")
return {"ok": True, "model": model_name, "content": content}
except Exception as exc:
return {"ok": False, "model": model_name, "error": str(exc)}
def collect_logs(root=ROOT):
log_dir = Path(root) / "logs"
if IS_WINDOWS:
return {
"agent": tail_lines(log_dir / "agent.err.log", 180),
"agent_output": tail_lines(log_dir / "agent.out.log", 80),
"agent_launch": tail_lines(log_dir / "agent-launch.log", 80),
"ollama": tail_lines(log_dir / "ollama.log", 80),
"dashboard": tail_lines(log_dir / "dashboard.err.log", 80),
}
return {
"agent": tail_lines(log_dir / "launchd.err.log", 180),
"agent_output": tail_lines(log_dir / "launchd.out.log", 80),
"agent_launch": tail_lines(log_dir / "monitor-wrapper.log", 80),
"ollama": [],
"dashboard": [],
}
def build_overview(root=ROOT, launchctl_output=None, now=None):
root = Path(root)
if IS_WINDOWS:
service = windows_service_status(root)
else:
launchctl_text = launchctl_output if launchctl_output is not None else current_launchctl_output()
service = parse_launchctl_status(launchctl_text)
config = read_safe_config(root / ".env")
return {
"generated_at": now or datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
"platform": "windows" if IS_WINDOWS else "macos",
"service": service,
"ollama": ollama_status(),
"config": config,
"cookie_sync": dict(COOKIE_SYNC_STATE),
"stats": get_db_stats(root / "data" / "chat_history.db"),
"logs": collect_logs(root),
"messages": read_recent_messages(root / "data" / "chat_history.db", 40),
}
def restart_service(runner=run_command, user_id=None):
if IS_WINDOWS:
stop_service()
result = runner(["schtasks", "/Run", "/TN", AGENT_TASK_NAME], timeout=15)
return format_command_result(result)
uid = os.getuid() if user_id is None else user_id
target = f"gui/{uid}/{SERVICE_LABEL}"
result = runner(["launchctl", "kickstart", "-k", target], timeout=15)
if result.returncode == 0:
return format_command_result(result)
bootstrap_result = runner(["launchctl", "bootstrap", f"gui/{uid}", str(SERVICE_PLIST)], timeout=15)
if bootstrap_result.returncode != 0 and "already bootstrapped" not in bootstrap_result.stderr:
return format_command_result(bootstrap_result)
return format_command_result(runner(["launchctl", "kickstart", "-k", target], timeout=15))
def stop_windows_agent_processes():
script = rf"""
$root = {json.dumps(str(ROOT))}
Get-CimInstance Win32_Process |
Where-Object {{
$_.Name -eq 'python.exe' -and
$_.CommandLine -like '*main.py*' -and
(
($_.ExecutablePath -and $_.ExecutablePath.ToLower().StartsWith($root.ToLower())) -or
($_.CommandLine -and $_.CommandLine.ToLower().Contains($root.ToLower()))
)
}} |
ForEach-Object {{ Stop-Process -Id $_.ProcessId -Force }}
"""
return powershell(script)
def stop_service(runner=run_command, user_id=None):
if IS_WINDOWS:
runner(["schtasks", "/End", "/TN", AGENT_TASK_NAME], timeout=10)
return format_command_result(stop_windows_agent_processes())
uid = os.getuid() if user_id is None else user_id
result = runner(["launchctl", "bootout", f"gui/{uid}", str(SERVICE_PLIST)], timeout=15)
return format_command_result(result)
def restart_ollama():
if not IS_WINDOWS:
return {"ok": False, "message": "当前只支持 Windows 上重启 Ollama"}
run_command(["schtasks", "/End", "/TN", OLLAMA_TASK_NAME], timeout=10)
result = run_command(["schtasks", "/Run", "/TN", OLLAMA_TASK_NAME], timeout=15)
return format_command_result(result)
def update_cookie(cookie):
cookie = (cookie or "").strip()
if len(cookie) < 80 or "=" not in cookie:
return {"ok": False, "message": "Cookie 看起来不完整,请复制浏览器请求里的完整 Cookie 字符串"}
set_env_value(ROOT / ".env", "COOKIES_STR", cookie)
return {"ok": True, "message": "Cookie 已保存"}
def perform_service_action(action):
if action == "restart":
return restart_service()
if action == "stop":
return stop_service()
if action == "restart_ollama":
return restart_ollama()
return {"ok": False, "message": "未知操作"}
def html_page():
return f"""<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>闲鱼自动发货看板</title>
<style>{CSS}</style>
</head>
<body>
<div class="app-shell">
<aside class="sidebar">
<div class="brand">
<div class="brand-mark">闲</div>
<div>
<strong>闲鱼托管</strong>
<span>AutoAgent Console</span>
</div>
</div>
<nav class="side-nav" aria-label="主导航">
<button class="nav-item active" data-view="overview" type="button">总览</button>
<button class="nav-item" data-view="items" type="button">商品策略</button>
<button class="nav-item" data-view="prompts" type="button">全局提示词</button>
<button class="nav-item" data-view="messages" type="button">最近对话</button>
<button class="nav-item" data-view="logs" type="button">运行日志</button>
<button class="nav-item" data-view="settings" type="button">设置</button>
</nav>
<div class="sidebar-foot">
<span>本地模型</span>
<strong id="sidebarModelName">-</strong>
</div>
</aside>
<div class="main-area">
<header class="topbar">
<div>
<h1 id="pageTitle">总览</h1>
<p id="pageSubtitle">运行状态、消息量和托管服务概况</p>
</div>
<div class="top-status">
<span id="statusDot" class="dot"></span>
<strong id="statusText">读取中</strong>
<span id="updatedAt"></span>
<code id="pidText">PID -</code>
</div>
<div class="actions">
<button id="refreshBtn" type="button">刷新</button>
<button id="testModelBtn" type="button">测试模型</button>
<button id="restartAgentBtn" type="button">重启 Agent</button>
<button id="restartOllamaBtn" type="button">重启 Ollama</button>
<button id="stopAgentBtn" type="button" class="danger">停止 Agent</button>
</div>
</header>
<main class="content">
<section class="page-view active" data-page="overview">
<section class="metrics" id="metrics"></section>
<section class="overview-grid">
<article class="panel">
<div class="panel-head">
<h2>服务状态</h2>
<span id="overviewPlatform">Windows 托管</span>
</div>
<div class="panel-body status-list">
<div><span>Agent</span><strong id="overviewAgent">读取中</strong></div>
<div><span>Cookie</span><strong id="overviewCookie">读取中</strong></div>
<div><span>Ollama</span><strong id="overviewOllama">读取中</strong></div>
<div><span>数据库</span><strong id="overviewDb">-</strong></div>
</div>
</article>
<article class="panel">
<div class="panel-head">
<h2>模型状态</h2>
<span id="modelName">-</span>
</div>
<div class="panel-body model-box">
<div><span>接口</span><code id="modelBase">-</code></div>
<div><span>Ollama</span><strong id="ollamaStatus">读取中</strong></div>
<pre id="modelResult">点击“测试模型”确认本地模型回复。</pre>
</div>
</article>
</section>
</section>
<section class="page-view" data-page="items">
<section class="workspace two-column">
<aside class="panel item-list-panel">
<div class="panel-head">
<h2>商品列表</h2>
<button id="reloadItemsBtn" type="button">刷新商品</button>
</div>
<div class="list-toolbar">
<input id="itemSearch" type="search" placeholder="搜索商品标题或ID">
<select id="itemSelect" class="hidden-select" aria-hidden="true" tabindex="-1"></select>
<span id="itemCountText">0 个商品</span>
</div>
<div id="itemList" class="item-list"></div>
</aside>
<article class="panel item-detail-panel">
<div class="panel-head">
<div>
<h2 id="itemDetailTitle">商品专属策略</h2>
<span id="itemDetailSub">选择一个商品后编辑它的自动发货内容和咨询口径</span>
</div>
<div class="prompt-actions">
<button id="saveItemBtn" type="button">保存当前商品策略</button>
</div>
</div>
<div class="panel-body">
<div class="item-summary" id="itemSummary">读取中...</div>
<div class="strategy-banner">
<strong>付款后自动发货只绑定到这个商品 ID</strong>
<span id="itemScopeText">-</span>
</div>
<label class="check-row">
<input id="itemEnabled" type="checkbox" checked>
<span>启用该商品自动发货和专属回复</span>
</label>
<div class="item-edit-grid">
<label>
<span>付款后自动发货内容</span>
<textarea id="itemDeliveryEditor" class="product-editor" spellcheck="false" placeholder="买家付款后,检测到“等待卖家发货”时会直接发送这里的内容。可以填写百度网盘链接、提取码、查看说明和售后提示。"></textarea>
</label>
<label>
<span>咨询回复提示词</span>
<textarea id="itemPromptEditor" class="product-editor" spellcheck="false" placeholder="例如:只回答当前商品相关问题;不要承诺实物快递;未付款前不要泄露网盘链接;用户问发货时说明付款后系统发送。"></textarea>
</label>
</div>
<div class="form-actions">
<span id="itemMeta"></span>
<span id="itemResult"></span>
</div>
</div>
</article>
</section>
</section>
<section class="page-view" data-page="prompts">
<article class="panel prompt-panel">
<div class="panel-head">
<div>
<h2>全局回复策略 / 提示词</h2>
<span>这里控制所有商品的默认话术边界</span>