workspace.py 1.5 KB

1234567891011121314151617181920212223242526272829303132333435
  1. """按服务端会话身份映射文件根,虚拟路径保持不变。"""
  2. import hashlib
  3. from pathlib import Path
  4. import config
  5. def session_root(user_name: str, session_id: str) -> Path:
  6. # 哈希避免用户名或外部 ID 成为路径片段;不迁移旧共享文件以免猜错归属。
  7. user_key = hashlib.sha256(user_name.encode()).hexdigest()
  8. session_key = hashlib.sha256(session_id.encode()).hexdigest()
  9. root = config.ROOT / "data" / "workspaces" / user_key / session_key
  10. root.mkdir(parents=True, exist_ok=True)
  11. return root
  12. def backend_for_runtime(runtime):
  13. from deepagents.backends import CompositeBackend, FilesystemBackend
  14. from langgraph.config import get_config
  15. # 文件工具传 ToolRuntime;模型中间件传不含 config 的 Runtime。
  16. runtime_config = getattr(runtime, "config", None)
  17. if runtime_config is None:
  18. runtime_config = get_config()
  19. configurable = runtime_config.get("configurable", {})
  20. user = configurable.get("workspace_user")
  21. session = configurable.get("workspace_session")
  22. if not user or not session:
  23. raise ValueError("文件后端缺少服务端会话身份")
  24. root = session_root(user, session)
  25. for directory in ("workspace", "conversation_history"):
  26. (root / directory).mkdir(exist_ok=True)
  27. return CompositeBackend(
  28. default=FilesystemBackend(root_dir=root, virtual_mode=True),
  29. routes={"/skills/": FilesystemBackend(root_dir=config.ROOT / "skills", virtual_mode=True)},
  30. )