-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathapi_server.py
More file actions
1923 lines (1616 loc) · 59.4 KB
/
api_server.py
File metadata and controls
1923 lines (1616 loc) · 59.4 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
# FastAPI 服务 - 隐私代理 HTTP 接口
from fastapi import FastAPI, UploadFile, File, Form, Body, HTTPException, Header, Query, Request
from fastapi.responses import Response, JSONResponse, StreamingResponse
from fastapi.routing import APIRouter
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModel
from typing import Dict, Any, Literal, List, Optional
import json
import base64
import os
import time
import hmac
import hashlib
import io
import tarfile
import logging
import asyncio
from pathlib import Path
from skill_registry.skill_db import SkillDB
from memory.chat_history_db import ChatHistoryDB
from memory.rag_client import RAGClient
from auth_router import auth_router
from notifications_router import notifications_router
# 配置日志
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
app = FastAPI(title="隐私保护代理 API", version="1.0.0")
# 添加 CORS 支持
app.add_middleware(
CORSMiddleware,
allow_origins=["*"], # 生产环境应限制为具体域名
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
app.include_router(auth_router)
app.include_router(notifications_router)
# ============== JWT 前端控制台专用路由(避免与 HMAC 端点冲突)==============
# 前端通过 /console/* 调用,使用 Authorization: Bearer JWT 认证
console_router = APIRouter(prefix="/console", tags=["console"])
class SkillMetaUpdateRequest(BaseModel):
confidence: float | None = None
scene: str | None = None
rule_text: str | None = None
strategy: str | None = None
sensitive_field: str | None = None
class SkillArchiveRequest(BaseModel):
reason: str | None = "user_archived"
class SkillDeleteRequest(BaseModel):
confirm: bool = False
def _require_jwt(authorization: str | None) -> str:
"""从 Authorization: Bearer <token> 中提取 user_id"""
if not authorization:
raise HTTPException(status_code=401, detail={"error": "missing_auth"})
parts = authorization.strip().split(" ", 1)
if len(parts) != 2 or parts[0].lower() != "bearer" or not parts[1].strip():
raise HTTPException(status_code=401, detail={"error": "invalid_auth_header"})
token = parts[1].strip()
from auth_router import verify_token
user_id = verify_token(token)
if not user_id:
raise HTTPException(status_code=401, detail={"error": "invalid_token"})
return user_id
def _get_skill_db():
return SkillDB(db_path=str(PROJECT_ROOT / "skill_registry" / "skill_registry.db"))
@console_router.get("/skills/active/{user_id}")
def console_get_active(
user_id: str,
authorization: str | None = Header(default=None),
):
"""JWT 版:返回用户所有 active Skill"""
token_uid = _require_jwt(authorization)
if token_uid != user_id:
raise HTTPException(status_code=403, detail={"error": "forbidden"})
db = _get_skill_db()
skills = db.get_active_skills(user_id)
return {"user_id": user_id, "skills": skills, "count": len(skills)}
@console_router.get("/skills/all/{user_id}")
def console_get_all_skills(
user_id: str,
authorization: str | None = Header(default=None),
):
"""JWT 版:返回用户所有 Skill(含 active + archived)"""
token_uid = _require_jwt(authorization)
if token_uid != user_id:
raise HTTPException(status_code=403, detail={"error": "forbidden"})
db = _get_skill_db()
active = db.get_active_skills(user_id)
archived = db.get_archived_skills(user_id)
return {
"user_id": user_id,
"active": active,
"archived": archived,
"total": len(active) + len(archived),
}
@console_router.post("/skills/archive/{user_id}/{skill_name}/{version}")
def console_archive(
user_id: str,
skill_name: str,
version: str,
payload: SkillArchiveRequest | None = None,
authorization: str | None = Header(default=None),
):
"""JWT 版:停用(归档)指定 Skill"""
token_uid = _require_jwt(authorization)
if token_uid != user_id:
raise HTTPException(status_code=403, detail={"error": "forbidden"})
db = _get_skill_db()
reason = (payload.reason or "user_archived") if payload else "user_archived"
ok = db.archive_skill(user_id, skill_name, version, reason=reason)
if not ok:
raise HTTPException(status_code=404, detail={"error": "skill_not_found_or_already_archived"})
# 写入操作日志到 notification 表(confirmed状态,表示历史记录)
db.add_notification(
user_id=user_id,
notif_type="skill_disabled",
title="规则已停用",
body=f"用户停用了规则「{skill_name}」{version}",
skill_name=skill_name,
skill_version=version,
event_id=f"op-{user_id}-{skill_name}-disabled-{int(time.time())}",
status="confirmed",
)
return {"success": True, "user_id": user_id, "skill_name": skill_name, "version": version}
@console_router.post("/skills/restore/{user_id}/{skill_name}/{version}")
def console_restore(
user_id: str,
skill_name: str,
version: str,
authorization: str | None = Header(default=None),
):
"""JWT 版:恢复已归档的 Skill"""
token_uid = _require_jwt(authorization)
if token_uid != user_id:
raise HTTPException(status_code=403, detail={"error": "forbidden"})
db = _get_skill_db()
ok = db.restore_skill(user_id, skill_name, version, str(USER_SKILLS_ROOT))
if not ok:
raise HTTPException(status_code=400, detail={"error": "restore_failed_check_content_or_already_active"})
# 写入操作日志到 notification 表(confirmed状态,表示历史记录)
db.add_notification(
user_id=user_id,
notif_type="skill_enabled",
title="规则已启用",
body=f"用户启用了规则「{skill_name}」{version}",
skill_name=skill_name,
skill_version=version,
event_id=f"op-{user_id}-{skill_name}-enabled-{int(time.time())}",
status="confirmed",
)
return {"success": True, "user_id": user_id, "skill_name": skill_name, "version": version}
@console_router.delete("/skills/{user_id}/{skill_name}/{version}")
def console_delete(
user_id: str,
skill_name: str,
version: str,
payload: SkillDeleteRequest | None = None,
authorization: str | None = Header(default=None),
):
"""JWT 版:删除 Skill(归档 + 删除文件系统文件)"""
token_uid = _require_jwt(authorization)
if token_uid != user_id:
raise HTTPException(status_code=403, detail={"error": "forbidden"})
if payload and not payload.confirm:
raise HTTPException(status_code=400, detail={"error": "delete_not_confirmed"})
db = _get_skill_db()
ok = db.archive_skill(user_id, skill_name, version, reason="user_deleted", delete_files=True)
if not ok:
raise HTTPException(status_code=404, detail={"error": "skill_not_found"})
# 写入操作日志到 notification 表(confirmed状态,表示历史记录)
db.add_notification(
user_id=user_id,
notif_type="skill_deleted",
title="规则已删除",
body=f"用户删除了规则「{skill_name}」{version}",
skill_name=skill_name,
skill_version=version,
event_id=f"op-{user_id}-{skill_name}-deleted-{int(time.time())}",
status="confirmed",
)
return {"success": True, "user_id": user_id, "skill_name": skill_name, "version": version}
@console_router.put("/skills/{user_id}/{skill_name}")
def console_update_meta(
user_id: str,
skill_name: str,
payload: SkillMetaUpdateRequest,
authorization: str | None = Header(default=None),
):
"""JWT 版:更新 Skill 元数据,并同步写回 rules.json 文件"""
token_uid = _require_jwt(authorization)
if token_uid != user_id:
raise HTTPException(status_code=403, detail={"error": "forbidden"})
db = _get_skill_db()
active = db.get_active_skills(user_id)
target = next((s for s in active if str(s.get("skill_name")) == skill_name), None)
if not target:
raise HTTPException(status_code=404, detail={"error": "skill_not_found"})
skill_id = target["id"]
skill_path = target.get("path") or ""
# --- 1. 更新 DB ---
conn = db._connect()
try:
cur = conn.cursor()
cur.execute(
"""
UPDATE skills SET
confidence = COALESCE(?, confidence),
scene = COALESCE(?, scene),
rule_text = COALESCE(?, rule_text),
strategy = COALESCE(?, strategy),
sensitive_field = COALESCE(?, sensitive_field)
WHERE id = ?
""",
(payload.confidence, payload.scene, payload.rule_text,
payload.strategy, payload.sensitive_field, skill_id),
)
# --- 2. 同步写回 rules.json ---
if skill_path and (payload.scene is not None or payload.rule_text is not None):
# 重新读取更新后的行(含最新 rules_json_content)
row = cur.execute(
"SELECT rules_json_content, path FROM skills WHERE id = ?", (skill_id,)
).fetchone()
if row and row["rules_json_content"]:
try:
rj = json.loads(row["rules_json_content"])
if payload.scene is not None:
rj["scene"] = payload.scene
if payload.rule_text is not None:
rj["rule_text"] = payload.rule_text
rules_json_path = Path(skill_path) / "rules.json"
rules_json_path.write_text(json.dumps(rj, ensure_ascii=False, indent=2), encoding="utf-8")
# 同时更新 DB 里的 rules_json_content(保持一致)
cur.execute(
"UPDATE skills SET rules_json_content = ? WHERE id = ?",
(json.dumps(rj, ensure_ascii=False, indent=2), skill_id),
)
logger.info(f"[console_update_meta] synced rules.json for {skill_name} at {rules_json_path}")
except Exception as e:
logger.warning(f"[console_update_meta] failed to sync rules.json: {e}")
conn.commit()
finally:
conn.close()
# 写入操作日志到 notification 表
db.add_notification(
user_id=user_id,
notif_type="skill_updated",
title="规则已更新",
body=f"用户更新了规则「{skill_name}」",
skill_name=skill_name,
skill_version=target.get("version"),
event_id=f"op-{user_id}-{skill_name}-updated-{int(time.time())}",
status="confirmed",
)
return {"success": True, "user_id": user_id, "skill_name": skill_name}
@console_router.post("/logs/import/{user_id}")
async def console_import_logs(
user_id: str,
log_type: str = Query(default="correction", pattern="^(correction|behavior|session_trace)$"),
file: UploadFile = File(...),
authorization: str | None = Header(default=None),
):
"""JWT 版:批量导入 jsonl 日志(方案A)"""
token_uid = _require_jwt(authorization)
if token_uid != user_id:
raise HTTPException(status_code=403, detail={"error": "forbidden"})
from auth_router import MEMORY_ROOT
log_dir = MEMORY_ROOT / "logs" / user_id
log_dir.mkdir(parents=True, exist_ok=True)
name_map = {
"correction": "correction_log.jsonl",
"behavior": "behavior_log.jsonl",
"session_trace": "session_trace.jsonl",
}
file_name = name_map.get(log_type, "imported.jsonl")
file_path = log_dir / file_name
existing_ids: set[str] = set()
if file_path.exists():
with file_path.open("r", encoding="utf-8") as f:
for line in f:
line = line.strip()
if not line:
continue
try:
obj = json.loads(line)
eid = obj.get("event_id") or obj.get("ts") or ""
existing_ids.add(str(eid))
except Exception:
pass
count = 0
error_lines: list[int] = []
content = await file.read()
with file_path.open("a", encoding="utf-8") as f:
for line_no, raw_line in enumerate(content.decode("utf-8", errors="replace").splitlines(), start=1):
line = raw_line.strip()
if not line:
continue
try:
obj = json.loads(line)
eid = str(obj.get("event_id") or obj.get("ts") or "")
if eid and eid in existing_ids:
continue
f.write(line + "\n")
count += 1
except Exception:
error_lines.append(line_no)
return {
"success": True,
"user_id": user_id,
"log_type": log_type,
"file": file_name,
"imported": count,
"skipped": len(existing_ids),
"parse_errors": len(error_lines),
"error_lines": error_lines[:10],
}
app.include_router(console_router)
# ============== 配置 ==============
PROJECT_ROOT = Path(__file__).parent
USER_SKILLS_ROOT = PROJECT_ROOT / "user_skills"
MEMORY_ROOT = PROJECT_ROOT / "memory"
# 认证密钥
AUTH_SECRET = os.environ.get("PRIVACY_AGENT_AUTH_SECRET", "change-me-in-production")
AUTH_TIMESTAMP_TOLERANCE = 300 # 5分钟
_agent = None
_skill_db: Optional[SkillDB] = None
def get_agent():
global _agent
if _agent is None:
from proxy_agent import PrivacyProxyAgent
_agent = PrivacyProxyAgent()
return _agent
def get_skill_db() -> SkillDB:
global _skill_db
if _skill_db is None:
_skill_db = SkillDB(db_path=str(PROJECT_ROOT / "skill_registry" / "skill_registry.db"))
return _skill_db
# ============== 认证工具 ==============
def verify_hmac_signature(user_id: str, timestamp: str, signature: str) -> bool:
"""验证 HMAC 签名"""
try:
ts = int(timestamp)
if abs(int(time.time()) - ts) > AUTH_TIMESTAMP_TOLERANCE:
return False
message = f"{user_id}{timestamp}"
expected = base64.b64encode(
hmac.new(
AUTH_SECRET.encode(),
message.encode(),
hashlib.sha256
).digest()
).decode()
return hmac.compare_digest(signature, expected)
except (ValueError, TypeError):
return False
def require_auth(user_id: str, x_timestamp: str = Header(None), x_signature: str = Header(None)):
"""验证请求认证"""
if not x_timestamp or not x_signature:
raise HTTPException(
status_code=401,
detail={"code": "MISSING_AUTH_HEADERS", "message": "缺少认证头"}
)
if not verify_hmac_signature(user_id, x_timestamp, x_signature):
raise HTTPException(
status_code=401,
detail={"code": "INVALID_SIGNATURE", "message": "签名验证失败"}
)
# ============== 原有接口 ==============
@app.get("/")
def root():
return {"status": "ok", "message": "隐私保护代理服务运行中"}
@app.post("/process")
async def process_screenshot(
image: UploadFile = File(...),
user_id: str = Form(None),
command: str = Form("分析当前页面隐私"),
return_base64: bool = Form(False)
):
"""处理截图 - 隐私保护核心接口"""
if not user_id or not str(user_id).strip():
raise HTTPException(status_code=400, detail="user_id 不能为空")
user_id = str(user_id).strip()
agent = get_agent()
result = agent.process_image_bytes(
await image.read(),
image.filename or "image.jpg",
command,
user_id=user_id
)
meta = {
"success": True,
"matched_rules": result.matched_rules,
"analysis": result.analysis,
"masked_count": result.masked_count,
"mime_type": result.masked_mime_type,
}
if return_base64:
meta["image_base64"] = base64.b64encode(result.masked_image_bytes).decode()
return meta
return _multipart_response(meta, result.masked_image_bytes, result.masked_mime_type)
@app.get("/rules")
def list_rules():
return {"rules": get_agent().list_rules()}
@app.post("/rules")
def add_rule(rule: Dict[str, Any] = Body(...)):
return {"status": "ok", "rule": get_agent().upsert_rule(rule)}
@app.post("/hook")
def hook_control(action: Literal["install", "uninstall", "status"] = Form(...)):
from proxy_agent import ScreenshotHook, PrivacyProxyAgent
agent = PrivacyProxyAgent()
if action == "install":
ScreenshotHook.install(agent)
return {"installed": True}
if action == "uninstall":
ScreenshotHook.uninstall()
return {"installed": False}
return {"installed": ScreenshotHook._is_installed}
# ============== 核心:极简 Skill 同步接口 ==============
@app.post("/skills/sync")
def sync_skills(
body: Dict[str, Any] = Body(...),
x_timestamp: str = Header(None),
x_signature: str = Header(None),
):
"""
增量 Skill 同步接口
客户端发送:
POST /skills/sync
{
"user_id": "demo_UserA",
"installed_skills": {
"privacy-file-content-replace-v1": "旧hash值",
"privacy-old-skill-v1": "旧hash值"
}
}
服务端响应:
- 有更新:返回 JSON(to_update / to_delete 列表)+ tar.gz(只含差异部分)
- 无更新:返回 {"updated": false, "message": "已是最新"}
"""
user_id = body.get("user_id")
if not user_id:
raise HTTPException(status_code=400, detail="user_id 不能为空")
# 验证签名
require_auth(user_id, x_timestamp, x_signature)
db = get_skill_db()
active_rows = db.get_active_skills(user_id)
if not active_rows:
raise HTTPException(status_code=404, detail=f"用户 {user_id} 没有任何 Skills")
server_skills = {
str(r.get("skill_name", "")): {
"content_hash": str(r.get("content_hash", "")),
"path": str(r.get("path", "")),
}
for r in active_rows
if str(r.get("skill_name", ""))
}
client_skills = body.get("installed_skills", {})
# 对比:找出新增/更新/删除
to_update: List[str] = [] # 需要更新的 skill 名称
to_delete: List[str] = [] # 服务端已删除但客户端还有的
for skill_name, server_meta in server_skills.items():
client_hash = client_skills.get(skill_name, "")
server_hash = server_meta.get("content_hash", "")
if client_hash != server_hash:
to_update.append(skill_name)
for skill_name in client_skills:
if skill_name not in server_skills:
to_delete.append(skill_name)
# 无更新
if not to_update and not to_delete:
return {
"updated": False,
"user_id": user_id,
"message": "已是最新"
}
logger.info(f"增量 Sync: user_id={user_id}, to_update={to_update}, to_delete={to_delete}")
# 增量打包(只打包 to_update 的 Skill 目录)
tar_buffer = io.BytesIO()
updated_count = 0
try:
with tarfile.open(fileobj=tar_buffer, mode="w:gz", format=tarfile.PAX_FORMAT) as tar:
for skill_name in to_update:
skill_path = str(server_skills.get(skill_name, {}).get("path", ""))
skill_dir = Path(skill_path)
if skill_dir.exists() and skill_dir.is_dir():
arcname = f"{user_id}/{skill_dir.name}"
tar.add(skill_dir, arcname=arcname)
updated_count += 1
tar_buffer.seek(0)
tar_bytes = tar_buffer.getvalue()
# 返回增量信息和 tar.gz 流
response_meta = {
"updated": True,
"user_id": user_id,
"to_update": to_update,
"to_delete": to_delete,
"updated_count": updated_count,
"deleted_count": len(to_delete),
"message": f"需要更新 {updated_count} 个,删除 {len(to_delete)} 个"
}
filename = f"skills_delta_{user_id}_{int(time.time())}.tar.gz"
return StreamingResponse(
io.BytesIO(tar_bytes),
media_type="application/gzip",
headers={
"Content-Disposition": f'attachment; filename="{filename}"',
"X-Updated": "true",
"X-Update-Count": str(updated_count),
"X-Delete-Count": str(len(to_delete)),
"X-User-ID": user_id,
"X-Update-List": json.dumps(to_update),
"X-Delete-List": json.dumps(to_delete),
"X-Meta": base64.b64encode(json.dumps(response_meta).encode()).decode(),
}
)
except Exception as e:
logger.error(f"增量打包失败: user_id={user_id}, error={e}")
raise HTTPException(status_code=500, detail=f"打包失败: {e}")
def _get_user_version_tag(user_dir: Path) -> str:
"""
生成用户的版本标签
格式: {最新skill的mtime}_{skill总数}
例如: 20260318_v3
这样客户端只需比较字符串即可判断是否需要更新
"""
if not user_dir.exists():
return "unknown"
# 获取所有 skill 目录
skill_dirs = [d for d in user_dir.iterdir() if d.is_dir() and not d.name.startswith(".")]
if not skill_dirs:
return "empty"
# 最新修改时间
latest_mtime = max(d.stat().st_mtime for d in skill_dirs)
latest_date = time.strftime("%Y%m%d", time.localtime(latest_mtime))
# skill 数量
count = len(skill_dirs)
return f"{latest_date}_v{count}"
def _multipart_response(meta: Dict, image_bytes: bytes, mime_type: str) -> Response:
"""构建 multipart/mixed 响应"""
boundary = "----privacy-agent-boundary"
body = b"".join([
b"--" + boundary.encode() + b"\r\n",
b"Content-Type: application/json; charset=utf-8\r\n\r\n",
json.dumps(meta, ensure_ascii=False).encode(),
b"\r\n",
b"--" + boundary.encode() + b"\r\n",
f"Content-Type: {mime_type}\r\n".encode(),
b'Content-Disposition: inline; filename="masked"\r\n\r\n',
image_bytes,
b"\r\n",
b"--" + boundary.encode() + b"--\r\n",
])
return Response(content=body, media_type=f"multipart/mixed; boundary={boundary}")
@app.get("/skills/search")
def search_skills(
user_id: str,
task_goal: str = "",
app_context: str = "",
action_keywords: str = "",
limit: int = Query(default=5, ge=1, le=20),
x_timestamp: str = Header(None),
x_signature: str = Header(None),
):
"""
根据任务上下文检索匹配的 skills
客户端调用:
GET /skills/search?user_id=demo_UserA&task_goal=发送病历&app_context=hospital_oa
响应示例:
{
"skills": [
{
"skill_name": "hospital-privacy-protect",
"version": "v1.0.0",
"app_context": "hospital_oa",
"confidence": 0.95,
"trigger_count": 12,
...
}
],
"matched_by": {
"app_context": "hospital_oa",
"task_goal": "发送病历",
},
"total": 1
}
"""
require_auth(user_id, x_timestamp, x_signature)
db = get_skill_db()
skills = db.search_skills(
user_id=user_id,
task_goal=task_goal,
app_context=app_context,
action_keywords=action_keywords,
limit=limit,
)
return {
"skills": skills,
"matched_by": {
"task_goal": task_goal or None,
"app_context": app_context or None,
"action_keywords": action_keywords or None,
},
"total": len(skills),
}
@app.get("/skills/detail")
def get_skill_detail(
user_id: str,
skill_name: str,
version: str = "",
x_timestamp: str = Header(None),
x_signature: str = Header(None),
):
"""
获取完整 skill 详情(包含 SKILL.md 和 rules.json 内容)
客户端调用:
GET /skills/detail?user_id=demo_UserA&skill_name=hospital-privacy-protect&version=v1.0.0
响应示例:
{
"skill_name": "hospital-privacy-protect",
"version": "v1.0.0",
"skill_md_content": "完整 SKILL.md 内容...",
"rules_json_content": [...],
...
}
"""
if not user_id:
raise HTTPException(status_code=400, detail="user_id 不能为空")
require_auth(user_id, x_timestamp, x_signature)
db = get_skill_db()
skill = db.get_skill_detail(user_id, skill_name, version)
if not skill:
raise HTTPException(status_code=404, detail=f"Skill {skill_name}@{version} 不存在")
return skill
@app.post("/skills/rag/query")
def rag_query_skills(
body: Dict[str, Any] = Body(...),
x_timestamp: str = Header(None),
x_signature: str = Header(None),
):
"""
RAG 向量检索,查找相关隐私规则
客户端调用:
POST /skills/rag/query
{
"user_id": "demo_UserA",
"query": "用户想分享医院联系人截图",
"app_context": "hospital_oa",
"top_k": 3
}
响应示例:
{
"rules": [
"禁止在外部平台分享含敏感信息的截图",
"截图前需检查是否包含身份证号、银行卡号等"
],
"sources": [
{"skill_name": "...", "confidence": 0.9}
]
}
"""
user_id = body.get("user_id")
query = body.get("query", "")
app_context = body.get("app_context", "")
top_k = body.get("top_k", 3)
if not user_id:
raise HTTPException(status_code=400, detail="user_id 不能为空")
require_auth(user_id, x_timestamp, x_signature)
# 使用 ChromaDB 进行向量检索
try:
rag = RAGClient()
results = rag.query(
query_text=query,
collection_name=f"rules_{user_id}",
where={"app_context": app_context} if app_context else None,
top_k=top_k,
)
return {
"rules": results.get("documents", []),
"metadatas": results.get("metadatas", []),
"distances": results.get("distances", []),
"sources": [
{"skill_name": m.get("skill_name", ""), "confidence": m.get("confidence", 0)}
for m in results.get("metadatas", [])
],
}
except Exception as e:
logger.warning(f"RAG 查询失败: {e}, 返回空结果")
return {"rules": [], "metadatas": [], "distances": [], "sources": []}
# ============== 辅助接口(可选,用于查看状态)==============
@app.get("/skills/{user_id}/version")
def get_user_version(
user_id: str,
x_timestamp: str = Header(None),
x_signature: str = Header(None),
):
"""
查询用户当前版本(无需下载 tar.gz)
用于客户端快速检查是否需要同步
"""
require_auth(user_id, x_timestamp, x_signature)
db = get_skill_db()
active_rows = db.get_active_skills(user_id)
if not active_rows:
raise HTTPException(status_code=404, detail=f"用户 {user_id} 没有 Skills")
latest_created = max(int(r.get("created_ts", 0) or 0) for r in active_rows)
latest_date = time.strftime("%Y%m%d", time.localtime(latest_created))
current_version = f"{latest_date}_v{len(active_rows)}"
skills = []
for r in active_rows:
skill_dir = Path(str(r.get("path", "")))
skill_info = {
"name": str(r.get("skill_name", "")),
"version": str(r.get("version", "")),
"mtime": int(r.get("created_ts", 0) or 0),
"files": [f.name for f in skill_dir.iterdir() if skill_dir.exists() and f.is_file()],
"confidence": r.get("confidence"),
"strategy": r.get("strategy"),
}
skills.append(skill_info)
return {
"user_id": user_id,
"version": current_version,
"skill_count": len(skills),
"skills": sorted(skills, key=lambda x: x["mtime"], reverse=True)
}
@app.get("/skills/active/{user_id}")
def get_active_skills(
user_id: str,
x_timestamp: str = Header(None),
x_signature: str = Header(None),
):
require_auth(user_id, x_timestamp, x_signature)
return {"user_id": user_id, "skills": get_skill_db().get_active_skills(user_id)}
@app.get("/skills/archived/{user_id}")
def get_archived_skills(
user_id: str,
x_timestamp: str = Header(None),
x_signature: str = Header(None),
):
require_auth(user_id, x_timestamp, x_signature)
return {"user_id": user_id, "skills": get_skill_db().get_archived_skills(user_id)}
@app.get("/skills/history/{user_id}/{skill_name}")
def get_skill_history(
user_id: str,
skill_name: str,
x_timestamp: str = Header(None),
x_signature: str = Header(None),
):
require_auth(user_id, x_timestamp, x_signature)
return {
"user_id": user_id,
"skill_name": skill_name,
"history": get_skill_db().get_skill_history(user_id, skill_name),
}
@app.post("/skills/restore/{user_id}/{skill_name}/{version}")
def restore_skill(
user_id: str,
skill_name: str,
version: str,
x_timestamp: str = Header(None),
x_signature: str = Header(None),
):
require_auth(user_id, x_timestamp, x_signature)
ok = get_skill_db().restore_skill(user_id, skill_name, version, str(USER_SKILLS_ROOT))
if not ok:
raise HTTPException(status_code=400, detail="恢复失败:版本不存在或已是 active")
return {"success": True, "user_id": user_id, "skill_name": skill_name, "version": version}
@app.get("/evolution/status")
def get_evolution_status():
"""查询各用户 correction_log 统计"""
logs_root = MEMORY_ROOT / "logs"
if not logs_root.exists():
return {"total_users": 0, "ready_users": 0, "users": []}
from evolution_daemon import CorrectionLogReader
reader = CorrectionLogReader(logs_root)
user_ids = reader.get_all_user_ids()
stats = []
for uid in user_ids:
unprocessed = reader.get_unprocessed_count(uid)
stats.append({
"user_id": uid,
"unprocessed_count": unprocessed,
"threshold": 3,
"ready": unprocessed >= 3
})
return {
"total_users": len(user_ids),
"ready_users": sum(1 for s in stats if s["ready"]),
"users": sorted(stats, key=lambda x: x["unprocessed_count"], reverse=True)
}
@app.post("/evolution/trigger")
def trigger_evolution(
user_id: str = Form(...),
x_timestamp: str = Header(None),
x_signature: str = Header(None),
):
"""手动触发指定用户的进化流程"""
require_auth(user_id, x_timestamp, x_signature)
from evolution_daemon import EvolutionTrigger, DaemonConfig
start_time = time.time()
try:
config = DaemonConfig(
logs_root="memory/logs",
memory_root="memory",
user_skills_root="user_skills",
run_once=True,
)
trigger = EvolutionTrigger(config)
result = trigger._run_evolution(user_id)
result["elapsed_seconds"] = round(time.time() - start_time, 2)
return result
except Exception as e:
return {
"success": False,
"user_id": user_id,
"error": str(e),
"elapsed_seconds": round(time.time() - start_time, 2)
}
# ============== 日志接收与推送接口 ==============
@app.post("/logs/upload")
async def upload_logs(
body: Dict[str, Any] = Body(...),
x_api_key: str = Header(None),
):
"""
接收 Windows 客户端上传的日志
请求格式:
{
"user_id": "win_user_001",
"logs": [
{
"action": "agent_fill",
"app_context": "taobao",
"resolution": "mask",
"field": "phone_number",
"agent_intent": "自动填入手机号",
"pii_type": "PHONE_NUMBER",
"masked_image_path": "temp/masked_xxx.jpg",
"safe_image_path": "temp/safe_xxx.jpg"
},
...
]
}
返回:
{
"status": "accepted",
"count": 5
}