Skip to content

JiuwenSwarm is an intelligent AI Agent built on openJiuwen. It extends the powerful capabilities of large language models directly to your fingertips through various communication apps you use daily.

Python

fix(agentserver): remove stale prompt attachment loader

guozirui1f9fe55276773
diff --git a/jiuwenswarm/common/utils.py b/jiuwenswarm/common/utils.py
index 6d0d805806..a3f3c60094 100644
--- a/jiuwenswarm/common/utils.py
+++ b/jiuwenswarm/common/utils.py
@@ -2022,8 +2022,19 @@ def get_default_project_session_workspace_dir(session_id: str | None = None) ->
return workspace
+_VALID_SESSION_ID_RE = re.compile(
+ r"^[A-Za-z0-9](?:[A-Za-z0-9_.-]{0,78}[A-Za-z0-9])?$"
+)
+
+
+def is_valid_session_id(session_id: str) -> bool:
+ """Return whether a session id is safe to use as one path component."""
+
+ return _VALID_SESSION_ID_RE.fullmatch(session_id) is not None
+
+
def get_prompt_attachment_dir() -> Path:
- """Get the jiuwenswarm prompt attachment directory path."""
+ """Return the legacy prompt-attachment path without creating it."""
overridden = _dispatch_path(PathCategory.PROMPT_ATTACHMENT)
if overridden is not None:
diff --git a/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py b/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py
index dc76d2ab5b..09004e668b 100644
--- a/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py
+++ b/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py
@@ -383,7 +383,6 @@ from jiuwenswarm.agents.harness.common.rails.permissions.config_loader import (
from jiuwenswarm.server.runtime.session.session_metadata import build_server_push_message
from jiuwenswarm.server.runtime.session.session_history import append_history_record, load_history_records
from jiuwenswarm.server.runtime.skill.skill_manager import SkillManager
-from jiuwenswarm.server.runtime.prompt_attachment_loader import PromptAttachmentLoader
from jiuwenswarm.server.runtime.agent_adapter.evolution_helpers import (
EVOLUTION_ACCEPT_LABELS,
AUTO_REBUILD_SOURCE_MANUAL,
@@ -691,7 +690,6 @@ from jiuwenswarm.common.utils import (
get_checkpoint_dir,
get_default_project_session_workspace_dir,
get_env_file,
- get_prompt_attachment_dir,
get_runtime_state_path,
get_user_workspace_dir,
resolve_tenant_sessions_dir,
@@ -2594,7 +2592,6 @@ class JiuWenSwarmDeepAdapter:
self._context_processor_rail: ContextProcessorRail | None = None
self._runtime_prompt_rail: RuntimePromptRail | None = None
self._response_prompt_rail: ResponsePromptRail | None = None
- self._prompt_attachment_loader: PromptAttachmentLoader | None = None
self._personal_context_rail: PersonalContextRail | None = None
self._personal_context_rail_lock = asyncio.Lock()
self._security_rail: SecurityRail | None = None
@@ -11238,9 +11235,6 @@ class JiuWenSwarmDeepAdapter:
for name in (sync_result.prebuilt_skill_dirs or [])
if str(name).strip()
}
- self._prompt_attachment_loader = PromptAttachmentLoader(self._prompt_attachment_root())
- self._prompt_attachment_loader.ensure_layout()
-
self._log_active_model_on_startup(phase=f"create_instance:{mode}")
try:
model = self._create_model(config_base)
@@ -11509,31 +11503,6 @@ class JiuWenSwarmDeepAdapter:
return True
return False
- async def _sync_prompt_attachments_for_request(self, session_id: str) -> None:
- """Hot-load prompt attachment files for the current request.
-
- Prompt attachment loading must not block the user request path. Failures are
- logged and the original Runner flow continues without attachment injection.
- """
-
- if self._instance is None:
- return
- if self._prompt_attachment_loader is None:
- self._prompt_attachment_loader = PromptAttachmentLoader(self._prompt_attachment_root())
- self._prompt_attachment_loader.ensure_layout()
- try:
- await self._prompt_attachment_loader.sync_to_agent(
- self._instance,
- session_id=session_id,
- )
- except Exception as exc:
- logger.warning("[JiuWenSwarmDeepAdapter] prompt attachment sync skipped: %s", exc)
-
- def _prompt_attachment_root(self) -> Path:
- if self._workspace_dir == str(get_agent_workspace_dir()):
- return get_prompt_attachment_dir()
- return Path(self._workspace_dir) / "prompt_attachment"
-
async def load_user_rails(self) -> None:
"""动态加载用户自定义的 Rail 扩展."""
try:
@@ -19034,7 +19003,6 @@ class JiuWenSwarmDeepAdapter:
inputs,
enable_read_image_multimodal=enable_read_image_multimodal,
)
- await self._sync_prompt_attachments_for_request(session_id)
from jiuwenswarm.agents.harness.common.prompt.user_prompt_builder import (
set_current_multimodal_image_files,
)
@@ -20199,7 +20167,6 @@ class JiuWenSwarmDeepAdapter:
payload=image_tool_fallback_notice,
is_complete=False,
)
- await self._sync_prompt_attachments_for_request(session_id)
from jiuwenswarm.agents.harness.common.prompt.user_prompt_builder import (
set_current_multimodal_image_files,
)
diff --git a/jiuwenswarm/server/runtime/agent_manager.py b/jiuwenswarm/server/runtime/agent_manager.py
index be84f99658..014696dc5e 100644
--- a/jiuwenswarm/server/runtime/agent_manager.py
+++ b/jiuwenswarm/server/runtime/agent_manager.py
@@ -71,7 +71,7 @@ def _session_id_prefix_for_channel(channel_id: str | None) -> str:
"""Path-safe session id prefix; may differ from logical ``channel_id``.
Cron scheduler uses channel ``__cron__`` for routing, but ids like
- ``__cron___{ts}_{uuid}`` fail ``sanitize_session_id`` and cannot be
+ ``__cron___{ts}_{uuid}`` fail the session-id whitelist and cannot be
used as sessions directory names.
"""
channel_key = _normalize_channel_id(channel_id)
diff --git a/jiuwenswarm/server/runtime/prompt_attachment_loader.py b/jiuwenswarm/server/runtime/prompt_attachment_loader.py
deleted file mode 100644
index eaf8c29f51..0000000000
--- a/jiuwenswarm/server/runtime/prompt_attachment_loader.py
+++ /dev/null
@@ -1,620 +0,0 @@
-# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
-"""Prompt attachment directory loader for jiuwenswarm.
-
-This module is the jiuwenswarm-side file hot-load adapter. Before model calls,
-it reads ``.md``/``.txt`` files from the current session's prompt attachment
-directory, converts them into agent-core ``PromptAttachment`` objects, and
-syncs them into the agent's ``PromptAttachmentManager``.
-"""
-from __future__ import annotations
-
-import hashlib
-import logging
-import os
-import re
-import stat
-import threading
-import time
-from pathlib import Path
-from typing import Any, Iterable
-
-from openjiuwen.harness.prompts.prompt_attachment_manager import (
- PromptAttachment,
- PromptAttachmentKind,
-)
-
-
-logger = logging.getLogger(__name__)
-
-SESSION_SOURCE = "jiuwenswarm.prompt_attachment.session"
-DEFAULT_MAX_FILE_CHARS = 12000
-_SAFE_SESSION_CHARS = re.compile(r"[^A-Za-z0-9_.-]+")
-_TEXT_SUFFIXES = frozenset({".md", ".txt"})
-_README_TEXT = """# Prompt Attachment
-
-Files in this directory are injected as dynamic prompt attachments for model calls.
-They are not user-uploaded attachments and are not written to long-term
-conversation history.
-
-Layout:
-- <session_id>/session/: hot-loaded prompt attachment files for one session.
-
-Markdown frontmatter is intentionally small: simple key-value fields and one
-level of metadata map are supported. Arrays, multiline strings, and full YAML
-features are not parsed by this loader.
-"""
-_KIND_BY_STEM = {
- "runtime": PromptAttachmentKind.RUNTIME,
- "request_context": PromptAttachmentKind.RUNTIME,
- "diagnostics": PromptAttachmentKind.DIAGNOSTIC,
- "memory_summary": PromptAttachmentKind.MEMORY,
- "open_files": PromptAttachmentKind.FILE,
-}
-_USER_SOURCE = "jiuwenswarm.prompt_attachment.user"
-_LOCKS_GUARD = threading.Lock()
-_PATH_LOCKS: dict[str, threading.Lock] = {}
-
-
-def _is_relative_to(path: Path, root: Path) -> bool:
- try:
- path.relative_to(root)
- return True
- except ValueError:
- return False
-
-
-def _is_reparse_path(path: Path) -> bool:
- """Return True for symlink, junction, or other Windows reparse-point paths."""
-
- if path.is_symlink():
- return True
- is_junction = getattr(path, "is_junction", None)
- if callable(is_junction) and is_junction():
- return True
- try:
- attrs = getattr(os.lstat(path), "st_file_attributes", 0)
- except OSError:
- return True
- return bool(attrs & getattr(stat, "FILE_ATTRIBUTE_REPARSE_POINT", 0))
-
-
-def _iter_safe_files(session_dir: Path, suffixes: frozenset[str]) -> Iterable[Path]:
- if not session_dir.exists() or not session_dir.is_dir():
- return
- session_root = session_dir.resolve()
- pending = [session_dir]
- while pending:
- current = pending.pop()
- try:
- entries = sorted(current.iterdir(), key=lambda item: item.as_posix())
- except OSError as exc:
- logger.warning("[PromptAttachmentLoader] failed to list prompt attachment directory %s: %s", current, exc)
- continue
- for path in entries:
- try:
- relative = path.relative_to(session_dir)
- except ValueError:
- continue
- if any(part.startswith(".") for part in relative.parts):
- continue
- if _is_reparse_path(path):
- logger.warning("[PromptAttachmentLoader] skip linked prompt attachment path: %s", path)
- continue
- try:
- resolved = path.resolve(strict=True)
- except OSError as exc:
- logger.warning("[PromptAttachmentLoader] failed to resolve prompt attachment path %s: %s", path, exc)
- continue
- if not _is_relative_to(resolved, session_root):
- logger.warning("[PromptAttachmentLoader] skip prompt attachment path outside session: %s", path)
- continue
- if path.is_dir():
- pending.append(path)
- elif path.is_file() and path.suffix.lower() in suffixes:
- yield path
-
-
-def _metadata_with_origin_source(metadata: dict[str, Any], origin_source: str | None) -> dict[str, Any]:
- result = dict(metadata)
- if origin_source and origin_source != SESSION_SOURCE:
- result.setdefault("origin_source", origin_source)
- return result
-
-
-def sanitize_session_id(session_id: str | None) -> str:
- """Return a deterministic path-safe session id."""
-
- raw = str(session_id or "").strip()
- if not raw:
- return "default"
- safe = _SAFE_SESSION_CHARS.sub("_", raw.replace("/", "_").replace("\\", "_")).strip("._-")
- if not safe:
- safe = hashlib.sha256(raw.encode("utf-8")).hexdigest()[:16]
- if safe in {".", ".."}:
- safe = f"session_{hashlib.sha256(raw.encode('utf-8')).hexdigest()[:16]}"
- if len(safe) > 80:
- digest = hashlib.sha256(raw.encode("utf-8")).hexdigest()[:12]
- safe = f"{safe[:67]}_{digest}"
- return safe
-
-
-def _safe_id_part(value: str) -> str:
- raw = str(value or "").strip()
- safe = _SAFE_SESSION_CHARS.sub("_", raw).strip("._-")
- if safe:
- return safe
- return hashlib.sha256(raw.encode("utf-8")).hexdigest()[:12]
-
-
-def _path_lock(path: Path) -> threading.Lock:
- key = str(path.resolve())
- with _LOCKS_GUARD:
- lock = _PATH_LOCKS.get(key)
- if lock is None:
- lock = threading.Lock()
- _PATH_LOCKS[key] = lock
- return lock
-
-
-def _atomic_write_text(path: Path, text: str) -> None:
- path.parent.mkdir(parents=True, exist_ok=True)
- tmp = path.with_name(f".{path.name}.tmp.{os.getpid()}.{threading.get_ident()}")
- tmp.write_text(text, encoding="utf-8")
- os.replace(tmp, path)
-
-
-def _kind_value(kind: PromptAttachmentKind | str) -> str:
- return kind.value if isinstance(kind, PromptAttachmentKind) else str(kind)
-
-
-def _parse_scalar(value: str) -> Any:
- stripped = value.strip()
- if stripped in {"true", "True"}:
- return True
- if stripped in {"false", "False"}:
- return False
- if stripped in {"null", "None", "~"}:
- return None
- try:
- return int(stripped)
- except ValueError:
- return stripped.strip('"').strip("'")
-
-
-def _parse_frontmatter(raw: str) -> tuple[dict[str, Any], str]:
- if not raw.startswith("---\n") and not raw.startswith("---\r\n"):
- return {}, raw
- normalized = raw.replace("\r\n", "\n")
- end = normalized.find("\n---\n", 4)
- if end < 0:
- return {}, raw
- header = normalized[4:end]
- body = normalized[end + len("\n---\n"):]
- if body.startswith("\n"):
- body = body[1:]
- data: dict[str, Any] = {}
- current_map: dict[str, Any] | None = None
- for line in header.splitlines():
- if not line.strip() or line.lstrip().startswith("#"):
- continue
- if line.startswith((" ", "\t")) and current_map is not None and ":" in line:
- key, value = line.strip().split(":", 1)
- current_map[key.strip()] = _parse_scalar(value)
- continue
- current_map = None
- if ":" not in line:
- continue
- key, value = line.split(":", 1)
- key = key.strip()
- if value.strip():
- data[key] = _parse_scalar(value)
- else:
- nested: dict[str, Any] = {}
- data[key] = nested
- current_map = nested
- return data, body
-
-
-def _dump_frontmatter(data: dict[str, Any]) -> str:
- lines = ["---"]
- for key in sorted(data):
- value = data[key]
- if isinstance(value, dict):
- lines.append(f"{key}:")
- for nested_key in sorted(value):
- lines.append(f" {nested_key}: {value[nested_key]}")
- else:
- lines.append(f"{key}: {value}")
- lines.append("---")
- return "\n".join(lines) + "\n\n"
-
-
-def _resolve_from_context(ctx: Any, *names: str) -> str | None:
- for name in names:
- value = getattr(ctx, name, None)
- if value:
- return str(value)
- extra = getattr(ctx, "extra", None)
- if isinstance(extra, dict):
- for name in names:
- value = extra.get(name)
- if value:
- return str(value)
- request = getattr(ctx, "request", None)
- if request is not None:
- for name in names:
- value = getattr(request, name, None)
- if value:
- return str(value)
- session = getattr(ctx, "session", None)
- if session is not None:
- for name in names:
- value = getattr(session, name, None)
- if value:
- return str(value)
- return None
-
-
-class PromptAttachmentFileStore:
- """File CRUD helper for session prompt attachment directories."""
-
- def __init__(self, root: Path | str, *, max_file_chars: int = DEFAULT_MAX_FILE_CHARS) -> None:
- self.root = Path(root)
- self.max_file_chars = max_file_chars
-
- def bind_context(self, ctx: Any) -> "PromptAttachmentContextStore":
- return PromptAttachmentContextStore(self, ctx)
-
- def for_session(self, session_id: str) -> "PromptAttachmentSessionStore":
- return PromptAttachmentSessionStore(self, session_id=session_id)
-
- def add_markdown(
- self,
- *,
- session_id: str,
- content: str,
- name: str | None = None,
- section: str | None = None,
- priority: int = 100,
- kind: PromptAttachmentKind | str = PromptAttachmentKind.TEXT,
- source: str | None = None,
- metadata: dict[str, Any] | None = None,
- ) -> PromptAttachment:
- section_id = _safe_id_part(section) if section else self._section_from_name(name)
- path = self._file_path(session_id=session_id, name=name or section_id, suffix=".md")
- if path.exists():
- raise FileExistsError(f"prompt attachment already exists: {path}")
- frontmatter = self._frontmatter(
- section=section_id,
- priority=priority,
- kind=kind,
- source=source or _USER_SOURCE,
- metadata=metadata,
- )
- with _path_lock(path):
- _atomic_write_text(path, _dump_frontmatter(frontmatter) + content)
- return self._item_from_file(path, session_id=session_id)
-
- def update_markdown(
- self,
- id_or_name: str,
- *,
- session_id: str,
- content: str | None = None,
- priority: int | None = None,
- source: str | None = None,
- kind: PromptAttachmentKind | str | None = None,
- metadata: dict[str, Any] | None = None,
- metadata_replace: bool = False,
- replace: bool = False,
- ) -> PromptAttachment:
- path = self._resolve_id_or_name(id_or_name, session_id=session_id)
- if path is None:
- raise FileNotFoundError(f"prompt attachment does not exist: {id_or_name}")
- with _path_lock(path):
- old_meta, old_content = _parse_frontmatter(path.read_text(encoding="utf-8"))
- next_meta = {} if replace else dict(old_meta)
- if old_meta.get("section") is not None:
- next_meta["section"] = old_meta["section"]
- if priority is not None:
- next_meta["priority"] = priority
- if source is not None:
- next_meta["source"] = source
- if kind is not None:
- next_meta["kind"] = _kind_value(self._coerce_kind(kind))
- if metadata is not None:
- if metadata_replace:
- next_meta["metadata"] = dict(metadata)
- else:
- next_meta["metadata"] = {**dict(next_meta.get("metadata") or {}), **metadata}
- next_content = old_content if content is None else content
- _atomic_write_text(path, _dump_frontmatter(next_meta) + next_content)
- return self._item_from_file(path, session_id=session_id)
-
- def get(self, id_or_name: str, *, session_id: str) -> PromptAttachment | None:
- path = self._resolve_id_or_name(id_or_name, session_id=session_id)
- if path is None:
- return None
- return self._item_from_file(path, session_id=session_id)
-
- def delete(self, id_or_name: str, *, session_id: str) -> bool:
- path = self._resolve_id_or_name(id_or_name, session_id=session_id)
- if path is None:
- return False
- with _path_lock(path):
- if not path.exists():
- return False
- path.unlink()
- return True
-
- def list(self, *, session_id: str) -> list[PromptAttachment]:
- session_dir = self._session_dir(session_id)
- items: list[PromptAttachment] = []
- for path in _iter_safe_files(session_dir, _TEXT_SUFFIXES):
- item = self._item_from_file(path, session_id=session_id)
- if item is not None:
- items.append(item)
- return sorted(items, key=lambda item: (item.priority, item.source or "", item.section))
-
- def _item_from_file(self, path: Path, *, session_id: str) -> PromptAttachment | None:
- raw = self._read_text_file(path, self._session_dir(session_id))
- if raw is None:
- return None
- meta, content = _parse_frontmatter(raw)
- session_dir = self._session_dir(session_id)
- section = _safe_id_part(str(meta.get("section") or self.relative_key(path, session_dir)))
- metadata = _metadata_with_origin_source(dict(meta.get("metadata") or {}), meta.get("source"))
- metadata.update({"path": str(path), "relative_path": path.relative_to(session_dir).as_posix()})
- return PromptAttachment(
- id=self._item_id(session_id=session_id, section=section),
- section=section,
- kind=meta.get("kind") or PromptAttachmentLoader.kind_for_file(path),
- content=content,
- priority=int(meta.get("priority") or 100),
- source=SESSION_SOURCE,
- session_id=session_id,
- metadata=metadata,
- content_kind="text/markdown" if path.suffix.lower() == ".md" else "text/plain",
- )
-
- def _resolve_id_or_name(
- self,
- id_or_name: str,
- *,
- session_id: str,
- ) -> Path | None:
- session_dir = self._session_dir(session_id)
- for path in _iter_safe_files(session_dir, _TEXT_SUFFIXES):
- relative_key = self.relative_key(path, session_dir)
- generated_id = f"session.{sanitize_session_id(session_id)}.{relative_key}"
- if id_or_name in {path.name, path.stem, relative_key, generated_id}:
- return path
- item = self._item_from_file(path, session_id=session_id)
- if item is not None and item.id == id_or_name:
- return path
- return None
-
- def _file_path(self, *, session_id: str, name: str, suffix: str) -> Path:
- relative = self._safe_relative_file_name(name=name, suffix=suffix)
- return self._session_dir(session_id) / relative
-
- def _session_dir(self, session_id: str) -> Path:
- return self.root / sanitize_session_id(session_id) / "session"
-
- @staticmethod
- def _item_id(*, session_id: str, section: str) -> str:
- return f"session.{sanitize_session_id(session_id)}.{_safe_id_part(section)}"
-
- @staticmethod
- def _section_from_name(name: str | None) -> str:
- if not name:
- return _safe_id_part(f"attachment_{time.time_ns()}_{threading.get_ident()}")
- raw_path = Path(name)
- parts = list(raw_path.with_suffix("").parts)
- return ".".join(_safe_id_part(part) for part in parts)
-
- @staticmethod
- def _frontmatter(
- *,
- section: str,
- priority: int,
- kind: PromptAttachmentKind | str,
- source: str,
- metadata: dict[str, Any] | None,
- ) -> dict[str, Any]:
- data: dict[str, Any] = {
- "section": section,
- "priority": priority,
- "kind": _kind_value(kind),
- "source": source,
- }
- if metadata:
- data["metadata"] = dict(metadata)
- return data
-
- def _read_text_file(self, path: Path, session_dir: Path) -> str | None:
- text = path.read_text(encoding="utf-8")
- if not text.strip():
- logger.debug(
- "[PromptAttachmentLoader] skip empty prompt attachment file: %s",
- path.relative_to(session_dir).as_posix(),
- )
- return None
- if self.max_file_chars > 0 and len(text) > self.max_file_chars:
- original_chars = len(text)
- text = text[:self.max_file_chars] + "\n\n[Prompt attachment file truncated by jiuwenswarm loader.]"
- logger.warning(
- "[PromptAttachmentLoader] truncated prompt attachment file: "
- "path=%s original_chars=%s truncated_chars=%s",
- path.relative_to(session_dir).as_posix(),
- original_chars,
- len(text),
- )
- return text
-
- @staticmethod
- def _coerce_kind(kind: PromptAttachmentKind | str) -> PromptAttachmentKind:
- return kind if isinstance(kind, PromptAttachmentKind) else PromptAttachmentKind(str(kind))
-
- @staticmethod
- def _safe_relative_file_name(*, name: str, suffix: str) -> Path:
- raw_name = str(name or "").strip()
- raw_path = Path(raw_name if Path(raw_name).suffix else f"{raw_name}{suffix}")
- if raw_path.is_absolute() or any(part in {"", ".", ".."} for part in raw_path.parts):
- raise ValueError(f"unsafe prompt attachment file name: {name}")
- if any(part.startswith(".") for part in raw_path.parts):
- raise ValueError(f"hidden prompt attachment file names are not supported: {name}")
- if raw_path.suffix.lower() not in _TEXT_SUFFIXES:
- raise ValueError(f"unsupported prompt attachment file suffix: {raw_path.suffix}")
- parts = []
- for index, part in enumerate(raw_path.parts):
- part_path = Path(part)
- if index == len(raw_path.parts) - 1:
- parts.append(f"{_safe_id_part(part_path.stem)}{part_path.suffix.lower()}")
- else:
- parts.append(_safe_id_part(part))
- return Path(*parts)
-
- @staticmethod
- def relative_key(path: Path, session_dir: Path) -> str:
- rel = path.relative_to(session_dir).with_suffix("")
- return ".".join(_safe_id_part(part) for part in rel.parts)
-
-
-class PromptAttachmentContextStore:
- """Context-bound file writer that hides the session id from callers."""
-
- def __init__(self, store: PromptAttachmentFileStore, ctx: Any) -> None:
- self._store = store
- self.session_id = _resolve_from_context(ctx, "session_id", "_session_id", "id") or "default"
-
- def add_markdown(self, **kwargs: Any) -> PromptAttachment:
- return self._store.add_markdown(session_id=self.session_id, **kwargs)
-
- def update_markdown(self, id_or_name: str, **kwargs: Any) -> PromptAttachment:
- return self._store.update_markdown(id_or_name, session_id=self.session_id, **kwargs)
-
- def get(self, id_or_name: str) -> PromptAttachment | None:
- return self._store.get(id_or_name, session_id=self.session_id)
-
- def delete(self, id_or_name: str) -> bool:
- return self._store.delete(id_or_name, session_id=self.session_id)
-
- def list(self) -> list[PromptAttachment]:
- return self._store.list(session_id=self.session_id)
-
-
-class PromptAttachmentSessionStore:
- """Session-bound writer for services that know session_id but not full ctx."""
-
- def __init__(self, store: PromptAttachmentFileStore, *, session_id: str) -> None:
- self._store = store
- self.session_id = session_id
-
- def add_markdown(self, **kwargs: Any) -> PromptAttachment:
- return self._store.add_markdown(session_id=self.session_id, **kwargs)
-
- def update_markdown(self, id_or_name: str, **kwargs: Any) -> PromptAttachment:
- return self._store.update_markdown(id_or_name, session_id=self.session_id, **kwargs)
-
- def get(self, id_or_name: str) -> PromptAttachment | None:
- return self._store.get(id_or_name, session_id=self.session_id)
-
- def delete(self, id_or_name: str) -> bool:
- return self._store.delete(id_or_name, session_id=self.session_id)
-
- def list(self) -> list[PromptAttachment]:
- return self._store.list(session_id=self.session_id)
-
-
-class PromptAttachmentLoader:
- """Load jiuwenswarm prompt attachment files into a DeepAgent manager."""
-
- def __init__(self, root: Path | str, *, max_file_chars: int = DEFAULT_MAX_FILE_CHARS) -> None:
- self.root = Path(root)
- self.max_file_chars = max_file_chars
- self.file_store = PromptAttachmentFileStore(self.root, max_file_chars=max_file_chars)
-
- def bind_context(self, ctx: Any) -> PromptAttachmentContextStore:
- """Return a context-bound file writer facade."""
-
- return self.file_store.bind_context(ctx)
-
- def for_session(self, session_id: str) -> PromptAttachmentSessionStore:
- """Return a session-bound file writer facade."""
-
- return self.file_store.for_session(session_id)
-
- def ensure_layout(self) -> None:
- """Create the root prompt attachment layout."""
-
- self.root.mkdir(parents=True, exist_ok=True)
- readme = self.root / "README.md"
- should_write_readme = True
- if readme.exists():
- try:
- current = readme.read_text(encoding="utf-8")
- should_write_readme = current != _README_TEXT or any(ord(char) >= 128 for char in current)
- except UnicodeDecodeError:
- should_write_readme = True
- if should_write_readme:
- readme.write_text(_README_TEXT, encoding="utf-8")
-
- def load_session_attachments(self, session_id: str) -> list[PromptAttachment]:
- """Load prompt attachments for one jiuwenswarm session."""
-
- return self.file_store.list(session_id=session_id)
-
- async def sync_to_agent(self, agent: Any, *, session_id: str) -> None:
- """Synchronize current prompt attachment files to a DeepAgent instance.
-
- Loader failures are intentionally non-fatal. User requests must continue
- even if one prompt attachment file is unreadable.
- """
-
- try:
- manager = getattr(agent, "prompt_attachment_manager", None)
- if manager is None:
- raise AttributeError("agent.prompt_attachment_manager is unavailable")
- except Exception as exc:
- logger.warning("[PromptAttachmentLoader] failed to get PromptAttachmentManager: %s", exc)
- return
-
- try:
- session_attachments = self.load_session_attachments(session_id)
- except Exception as exc:
- logger.warning("[PromptAttachmentLoader] failed to load prompt attachment directory: %s", exc)
- return
- logger.info(
- "[PromptAttachmentLoader] sync prompt attachments: session_id=%s session=%d",
- session_id,
- len(session_attachments),
- )
-
- try:
- await manager.replace_source(
- source=SESSION_SOURCE,
- prompt_attachments=session_attachments,
- session_id=session_id,
- )
- except Exception as exc:
- logger.warning("[PromptAttachmentLoader] failed to sync session prompt attachments: %s", exc)
-
- @staticmethod
- def kind_for_file(path: Path) -> PromptAttachmentKind:
- return _KIND_BY_STEM.get(path.stem, PromptAttachmentKind.TEXT)
-
- @staticmethod
- def relative_key(path: Path, session_dir: Path) -> str:
- return PromptAttachmentFileStore.relative_key(path, session_dir)
-
-
-__all__ = [
- "DEFAULT_MAX_FILE_CHARS",
- "PromptAttachmentContextStore",
- "PromptAttachmentFileStore",
- "PromptAttachmentLoader",
- "PromptAttachmentSessionStore",
- "SESSION_SOURCE",
- "sanitize_session_id",
-]
diff --git a/jiuwenswarm/server/runtime/session/session_history.py b/jiuwenswarm/server/runtime/session/session_history.py
index cd5fbacaca..f1feeada40 100644
--- a/jiuwenswarm/server/runtime/session/session_history.py
+++ b/jiuwenswarm/server/runtime/session/session_history.py
@@ -15,7 +15,7 @@ from dataclasses import dataclass, field
from pathlib import Path
from typing import Any, Iterable, Tuple
-from jiuwenswarm.common.utils import get_agent_sessions_dir
+from jiuwenswarm.common.utils import get_agent_sessions_dir, is_valid_session_id
logger = logging.getLogger(__name__)
@@ -33,9 +33,6 @@ _LEGACY_HISTORY_FILENAME = "history.json"
_JSONL_HISTORY_FILENAME = "history.jsonl"
_LEGACY_HISTORY_ENV = "JIUWENSWARM_USE_LEGACY_HISTORY_JSON"
_HEARTBEAT_OK = "HEARTBEAT_OK"
-_VALID_SESSION_ID = re.compile(
- r"^[A-Za-z0-9](?:[A-Za-z0-9_.-]{0,78}[A-Za-z0-9])?$"
-)
# Gateway may inline @path as <file-content>...</file-content> before chat.send.
# History should keep the short @path form so jsonl rows stay one physical line
# and refresh UI does not load megabytes of file body.
@@ -102,11 +99,6 @@ def collapse_file_content_blocks(content: str) -> str:
return re.sub(r"\n{3,}", "\n\n", collapsed).strip()
-def is_valid_session_id(session_id: str) -> bool:
- """Return whether a session id is safe to use as one path component."""
-
- return _VALID_SESSION_ID.fullmatch(session_id) is not None
-
# 缓冲层分两组:普通缓冲层(_session_buffer,合并后批量写)与暂留层(_session_pending,
# tool_calls.delta 等对应 chat.tool_call 命中后再决定丢弃/落盘)。
BUFFERABLE_EVENT_TYPES = {
@@ -422,9 +414,7 @@ def resolve_session_dir(
) -> tuple[Path | None, str | None]:
"""安全解析 session 目录路径(防路径遍历)。
- 采用白名单判据:``sanitize_session_id(session_id) == session_id`` 才认为合法,
- 原样使用;否则直接拒绝,根本不拼路径。这样删除类破坏性操作不会因 sanitize 后的
- 字符串(如 ``../config`` -> ``config``)误伤同名合法 session。
+ 采用共享的严格白名单校验,合法值原样使用;否则直接拒绝,根本不拼路径。
再用 ``resolve()`` + ``relative_to`` 做纵深防御,兜底白名单逻辑被绕过的极端情况。
diff --git a/jiuwenswarm/server/runtime/session/session_metadata.py b/jiuwenswarm/server/runtime/session/session_metadata.py
index 657d182bc3..496fd4a371 100644
--- a/jiuwenswarm/server/runtime/session/session_metadata.py
+++ b/jiuwenswarm/server/runtime/session/session_metadata.py
@@ -13,7 +13,11 @@ from pathlib import Path
from typing import Any
from datetime import datetime, timezone
-from jiuwenswarm.common.utils import get_agent_sessions_dir, get_agent_workspace_dir
+from jiuwenswarm.common.utils import (
+ get_agent_sessions_dir,
+ get_agent_workspace_dir,
+ is_valid_session_id,
+)
from jiuwenswarm.common.mode_matrix import NEW_AGENT_CODE_NORMAL, NEW_AGENT_WORK_NORMAL
from jiuwenswarm.server.runtime.session.work_mode import (
DEFAULT_WEB_WORK_MODE,
@@ -416,9 +420,7 @@ def _safe_session_subdir(
stripped = (session_id or "").strip()
if not stripped or "\x00" in stripped:
return None
- from jiuwenswarm.server.runtime.prompt_attachment_loader import sanitize_session_id
-
- if sanitize_session_id(stripped) != stripped:
+ if not is_valid_session_id(stripped):
return None
root = Path(sessions_root) if sessions_root else get_agent_sessions_dir()
try:
diff --git a/tests/unit_tests/agentserver/test_agent_manager_session_cleanup.py b/tests/unit_tests/agentserver/test_agent_manager_session_cleanup.py
index babbfbc53d..8b48b1daf1 100644
--- a/tests/unit_tests/agentserver/test_agent_manager_session_cleanup.py
+++ b/tests/unit_tests/agentserver/test_agent_manager_session_cleanup.py
@@ -364,7 +364,6 @@ async def test_release_subagent_runtime_is_noop_without_existing_adapter() -> No
@pytest.mark.asyncio
async def test_create_session_cron_channel_uses_path_safe_prefix() -> None:
- from jiuwenswarm.server.runtime.prompt_attachment_loader import sanitize_session_id
from jiuwenswarm.server.runtime.session.session_metadata import resolve_session_subdir
manager = AgentManager()
@@ -372,5 +371,4 @@ async def test_create_session_cron_channel_uses_path_safe_prefix() -> None:
assert session_id.startswith("cron_")
assert not session_id.startswith("__cron__")
- assert sanitize_session_id(session_id) == session_id
assert resolve_session_subdir(session_id) is not None
diff --git a/tests/unit_tests/agentserver/test_chat_steering_core_integration.py b/tests/unit_tests/agentserver/test_chat_steering_core_integration.py
index 13e74a4f97..d85c574cda 100644
--- a/tests/unit_tests/agentserver/test_chat_steering_core_integration.py
+++ b/tests/unit_tests/agentserver/test_chat_steering_core_integration.py
@@ -136,7 +136,6 @@ def _isolate_configuration(monkeypatch, adapter, model):
monkeypatch.setattr(adapter, "_apply_model_to_react_agent", lambda *_: None)
monkeypatch.setattr(adapter, "_handle_slash_command", AsyncMock(return_value=None))
monkeypatch.setattr(adapter, "_update_runtime_config", AsyncMock())
- monkeypatch.setattr(adapter, "_sync_prompt_attachments_for_request", AsyncMock())
monkeypatch.setattr(
adapter, "_try_skill_turbo_resume", AsyncMock(return_value=None)
)
diff --git a/tests/unit_tests/agentserver/test_deep_adapter_lazy_root_instance.py b/tests/unit_tests/agentserver/test_deep_adapter_lazy_root_instance.py
index 8ba3cd5e86..20233d2f0d 100644
--- a/tests/unit_tests/agentserver/test_deep_adapter_lazy_root_instance.py
+++ b/tests/unit_tests/agentserver/test_deep_adapter_lazy_root_instance.py
@@ -321,7 +321,6 @@ async def test_root_create_instance_skips_multimodal_skill_and_prompt(
config_base = {"react": {"agent_name": "main_agent"}}
monkeypatch.setattr(interface_deep_module, "get_config", lambda: config_base)
refresh = MagicMock()
- loader_cls = MagicMock()
sync_cls = MagicMock()
adapter._enterprise_config = SimpleNamespace(skill_prebuilt=[{"name": "x"}])
monkeypatch.setattr(adapter, "_merge_enterprise_models_into_config", lambda cfg: cfg)
@@ -337,14 +336,12 @@ async def test_root_create_instance_skips_multimodal_skill_and_prompt(
"_refresh_multimodal_configs",
refresh,
),
- patch.object(interface_deep_module, "PromptAttachmentLoader", loader_cls),
patch.object(interface_deep_module, "SkillPrebuiltSynchronizer", sync_cls),
patch.object(interface_deep_module, "is_skill_prebuilt_tenant", return_value=True),
):
await adapter.create_instance(config_base=config_base)
refresh.assert_not_called()
- loader_cls.assert_not_called()
sync_cls.assert_not_called()
assert adapter._instance is None
assert adapter._config_base_cache["react"]["agent_name"] == "main_agent"
@@ -365,7 +362,6 @@ async def test_root_create_instance_skip_applies_project_and_workspace_overrides
config_base = {"react": {"agent_name": "main_agent"}}
monkeypatch.setattr(interface_deep_module, "get_config", lambda: config_base)
refresh = MagicMock()
- loader_cls = MagicMock()
sync_cls = MagicMock()
adapter._enterprise_config = SimpleNamespace(skill_prebuilt=[{"name": "x"}])
monkeypatch.setattr(adapter, "_merge_enterprise_models_into_config", lambda cfg: cfg)
@@ -381,7 +377,6 @@ async def test_root_create_instance_skip_applies_project_and_workspace_overrides
"_refresh_multimodal_configs",
refresh,
),
- patch.object(interface_deep_module, "PromptAttachmentLoader", loader_cls),
patch.object(interface_deep_module, "SkillPrebuiltSynchronizer", sync_cls),
patch.object(interface_deep_module, "is_skill_prebuilt_tenant", return_value=True),
):
@@ -391,7 +386,6 @@ async def test_root_create_instance_skip_applies_project_and_workspace_overrides
)
refresh.assert_not_called()
- loader_cls.assert_not_called()
sync_cls.assert_not_called()
assert adapter._instance is None
assert adapter._project_dir == project_dir
@@ -402,16 +396,12 @@ async def test_root_create_instance_skip_applies_project_and_workspace_overrides
async def test_session_create_instance_still_refreshes_multimodal(
monkeypatch: pytest.MonkeyPatch,
) -> None:
- """Session adapters still run multimodal / prompt layout before DeepAgent."""
+ """Session adapters still refresh multimodal config before DeepAgent."""
adapter = JiuWenSwarmDeepAdapter()
adapter.mark_as_session_scoped("sess_preamble")
config_base = {"react": {"agent_name": "main_agent"}}
monkeypatch.setattr(interface_deep_module, "get_config", lambda: config_base)
refresh = MagicMock()
- loader = MagicMock()
- loader.ensure_layout = MagicMock()
- loader_cls = MagicMock(return_value=loader)
-
with (
_stub_create_instance_build(),
patch.object(
@@ -419,13 +409,10 @@ async def test_session_create_instance_still_refreshes_multimodal(
"_refresh_multimodal_configs",
refresh,
),
- patch.object(interface_deep_module, "PromptAttachmentLoader", loader_cls),
):
await adapter.create_instance(config_base=config_base)
refresh.assert_called_once()
- loader_cls.assert_called_once()
- loader.ensure_layout.assert_called_once()
assert adapter._instance is not None
@@ -447,11 +434,6 @@ async def test_ensure_instance_after_root_skip_runs_preamble(
"_refresh_multimodal_configs",
refresh,
),
- patch.object(
- interface_deep_module,
- "PromptAttachmentLoader",
- return_value=MagicMock(ensure_layout=MagicMock()),
- ),
):
await adapter.create_instance(
{"agent_name": "cached-agent"},
@@ -518,11 +500,6 @@ async def test_session_skill_prebuilt_sync_uses_create_instance_workspace_dir(
"_refresh_multimodal_configs",
MagicMock(),
),
- patch.object(
- interface_deep_module,
- "PromptAttachmentLoader",
- return_value=MagicMock(ensure_layout=MagicMock()),
- ),
patch.object(interface_deep_module, "SkillPrebuiltSynchronizer", sync_cls),
patch.object(interface_deep_module, "is_skill_prebuilt_tenant", return_value=True),
):
diff --git a/tests/unit_tests/agentserver/test_evolve_command_edges.py b/tests/unit_tests/agentserver/test_evolve_command_edges.py
index 437179e465..8aa2c57a8e 100644
--- a/tests/unit_tests/agentserver/test_evolve_command_edges.py
+++ b/tests/unit_tests/agentserver/test_evolve_command_edges.py
@@ -474,8 +474,6 @@ def _adapter_ready_for_followup_execution(monkeypatch: pytest.MonkeyPatch) -> Ji
monkeypatch.setattr(adapter, "_register_session_agent_task", lambda _session_id: None)
monkeypatch.setattr(adapter, "_unregister_session_agent_task", lambda _session_id: None)
monkeypatch.setattr(adapter, "_unmark_session_active", lambda _session_id, **_kwargs: None)
- monkeypatch.setattr(adapter, "_sync_prompt_attachments_for_request", AsyncMock())
-
async def _noop_update_runtime_config(_runtime_config):
return None
diff --git a/tests/unit_tests/agentserver/test_prompt_attachment_loader.py b/tests/unit_tests/agentserver/test_prompt_attachment_loader.py
deleted file mode 100644
index 4fefadf6a0..0000000000
--- a/tests/unit_tests/agentserver/test_prompt_attachment_loader.py
+++ /dev/null
@@ -1,266 +0,0 @@
-from __future__ import annotations
-
-import os
-from types import SimpleNamespace
-
-import pytest
-
-from openjiuwen.core.foundation.llm import SystemMessage, UserMessage
-from openjiuwen.harness.prompts.prompt_attachment_manager import (
- PromptAttachmentKind,
- PromptAttachmentManager,
-)
-
-from jiuwenswarm.server.runtime.prompt_attachment_loader import (
- SESSION_SOURCE,
- PromptAttachmentLoader,
- sanitize_session_id,
-)
-import jiuwenswarm.server.runtime.prompt_attachment_loader as prompt_attachment_loader_module
-
-
-class FakeDeepAgent:
- def __init__(self) -> None:
- self.prompt_attachment_manager = PromptAttachmentManager()
-
-
-def test_sanitize_session_id_is_path_safe():
- assert sanitize_session_id("") == "default"
- assert sanitize_session_id("default") == "default"
- assert "/" not in sanitize_session_id("../unsafe/session")
- assert "\\" not in sanitize_session_id("a\\b")
- assert sanitize_session_id("..") != ".."
-
-
-def test_loader_ensure_layout_and_loads_stable_order_kind_and_ids(tmp_path):
- root = tmp_path / "prompt_attachment"
- loader = PromptAttachmentLoader(root)
- loader.ensure_layout()
-
- session_dir = root / "sess1" / "session"
- session_dir.mkdir(parents=True)
- (session_dir / "z_note.txt").write_text("z", encoding="utf-8")
- (session_dir / "runtime.md").write_text("runtime", encoding="utf-8")
- (session_dir / "diagnostics.md").write_text("diag", encoding="utf-8")
- (session_dir / ".hidden.md").write_text("hidden", encoding="utf-8")
- (session_dir / "image.png").write_text("ignored", encoding="utf-8")
-
- items = loader.load_session_attachments("sess1")
-
- assert (root / "README.md").exists()
- readme = (root / "README.md").read_text(encoding="utf-8")
- assert "not user-uploaded attachments" in readme
- assert "turn" not in readme.lower()
- assert all(ord(char) < 128 for char in readme)
- assert [item.id for item in items] == [
- "session.sess1.diagnostics",
- "session.sess1.runtime",
- "session.sess1.z_note",
- ]
- assert [item.kind.value if hasattr(item.kind, "value") else item.kind for item in items] == [
- "diagnostic",
- "runtime",
- "text",
- ]
-
-
-def test_loader_skips_empty_files_and_truncates_large_files(tmp_path):
- root = tmp_path / "prompt_attachment"
- loader = PromptAttachmentLoader(root, max_file_chars=5)
- session_dir = root / "sess1" / "session"
- session_dir.mkdir(parents=True)
- (session_dir / "empty.md").write_text(" \n", encoding="utf-8")
- (session_dir / "runtime.md").write_text("x" * 20, encoding="utf-8")
-
- items = loader.load_session_attachments("sess1")
-
- assert [item.id for item in items] == ["session.sess1.runtime"]
- assert items[0].content.startswith("xxxxx")
- assert "truncated by jiuwenswarm loader" in items[0].content
-
-
-def test_context_store_add_update_get_delete_and_list_use_bound_session(tmp_path):
- root = tmp_path / "prompt_attachment"
- loader = PromptAttachmentLoader(root)
- store = loader.bind_context(SimpleNamespace(session_id="sess1"))
- created = store.add_markdown(name="hint.md", content="session hint", priority=42)
-
- updated = store.update_markdown(created.id, content="session hint v2")
- listed = store.list()
-
- assert created.id == "session.sess1.hint"
- assert updated.content == "session hint v2"
- assert updated.priority == 42
- assert store.get(created.id).content == "session hint v2"
- assert [item.id for item in listed] == ["session.sess1.hint"]
- assert store.delete(created.id) is True
- assert store.get(created.id) is None
-
-
-def test_file_store_add_markdown_validates_paths(tmp_path):
- root = tmp_path / "prompt_attachment"
- loader = PromptAttachmentLoader(root)
-
- with pytest.raises(ValueError):
- loader.file_store.add_markdown(session_id="sess1", name="../unsafe.md", content="unsafe")
- with pytest.raises(ValueError):
- loader.file_store.add_markdown(session_id="sess1", name=".hidden.md", content="hidden")
-
-
-def test_update_markdown_preserves_frontmatter_and_merges_metadata(tmp_path):
- root = tmp_path / "prompt_attachment"
- loader = PromptAttachmentLoader(root)
- session_store = loader.for_session("sess1")
- created = session_store.add_markdown(
- name="release.md",
- content="old content",
- priority=80,
- source="external.user",
- metadata={"owner": "qa"},
- )
-
- updated = session_store.update_markdown(
- created.id,
- content="new content",
- metadata={"ticket": "123"},
- )
- loaded = loader.load_session_attachments("sess1")[0]
- raw = (root / "sess1" / "session" / "release.md").read_text(encoding="utf-8")
-
- assert updated.content == "new content"
- assert loaded.priority == 80
- assert loaded.source == SESSION_SOURCE
- assert loaded.metadata["origin_source"] == "external.user"
- assert loaded.metadata["owner"] == "qa"
- assert loaded.metadata["ticket"] == 123
- assert "priority: 80" in raw
- assert "owner: qa" in raw
- assert "ticket: 123" in raw
-
-
-def test_file_store_auto_name_uses_unique_time_ns_and_thread_id(tmp_path):
- root = tmp_path / "prompt_attachment"
- loader = PromptAttachmentLoader(root)
- store = loader.for_session("sess1")
-
- first = store.add_markdown(content="one")
- second = store.add_markdown(content="two")
-
- assert first.id != second.id
- assert [item.content for item in store.list()] == ["one", "two"]
-
-
-def test_loader_skips_symlinked_prompt_attachment_paths(tmp_path):
- root = tmp_path / "prompt_attachment"
- loader = PromptAttachmentLoader(root)
- session_dir = root / "sess1" / "session"
- session_dir.mkdir(parents=True)
- (session_dir / "runtime.md").write_text("inside", encoding="utf-8")
- outside_dir = tmp_path / "outside"
- outside_dir.mkdir()
- (outside_dir / "secret.md").write_text("outside secret", encoding="utf-8")
- link_dir = session_dir / "linked"
- try:
- os.symlink(outside_dir, link_dir, target_is_directory=True)
- except (OSError, NotImplementedError) as exc:
- pytest.skip(f"symlink creation is unavailable: {exc}")
-
- items = loader.load_session_attachments("sess1")
-
- assert [item.content for item in items] == ["inside"]
-
-
-def test_loader_skips_reparse_marked_prompt_attachment_paths(tmp_path, monkeypatch):
- root = tmp_path / "prompt_attachment"
- loader = PromptAttachmentLoader(root)
- session_dir = root / "sess1" / "session"
- linked_dir = session_dir / "linked"
- linked_dir.mkdir(parents=True)
- (linked_dir / "secret.md").write_text("outside secret", encoding="utf-8")
- (session_dir / "runtime.md").write_text("inside", encoding="utf-8")
-
- def fake_is_reparse_path(path):
- return path == linked_dir
-
- monkeypatch.setattr(prompt_attachment_loader_module, "_is_reparse_path", fake_is_reparse_path)
-
- items = loader.load_session_attachments("sess1")
-
- assert [item.content for item in items] == ["inside"]
-
-
-async def test_sync_to_agent_hot_reloads_session_modify_and_delete(tmp_path):
- root = tmp_path / "prompt_attachment"
- loader = PromptAttachmentLoader(root)
- agent = FakeDeepAgent()
- session_dir = root / "sess1" / "session"
- session_dir.mkdir(parents=True)
- runtime_path = session_dir / "runtime.md"
-
- runtime_path.write_text("v1", encoding="utf-8")
- await loader.sync_to_agent(agent, session_id="sess1")
- items = await agent.prompt_attachment_manager.collect_for_session("sess1")
- assert [item.content for item in items] == ["v1"]
-
- runtime_path.write_text("v2", encoding="utf-8")
- await loader.sync_to_agent(agent, session_id="sess1")
- items = await agent.prompt_attachment_manager.collect_for_session("sess1")
- assert [item.content for item in items] == ["v2"]
-
- runtime_path.unlink()
- await loader.sync_to_agent(agent, session_id="sess1")
- items = await agent.prompt_attachment_manager.collect_for_session("sess1")
- assert items == []
-
-
-async def test_file_loaded_attachments_render_and_inject(tmp_path):
- root = tmp_path / "prompt_attachment"
- loader = PromptAttachmentLoader(root)
- agent = FakeDeepAgent()
-
- session_dir = root / "sess1" / "session"
- session_dir.mkdir(parents=True)
- (session_dir / "runtime.md").write_text("SESSION_FILE_MARKER", encoding="utf-8")
-
- await loader.sync_to_agent(agent, session_id="sess1")
- manager = agent.prompt_attachment_manager
- rendered = manager.render(await manager.collect_for_session("sess1"))
- messages = [
- SystemMessage(content="STATIC_SYSTEM_PROMPT"),
- UserMessage(content="original query"),
- ]
-
- injected = manager.inject_messages(messages, rendered)
-
- assert messages[-1].content == "original query"
- assert injected[0].content == "STATIC_SYSTEM_PROMPT"
- assert injected[1].content == "original query"
- assert "SESSION_FILE_MARKER" not in injected[0].content
- assert isinstance(injected[-1], UserMessage)
- assert "original query" not in injected[-1].content
- assert "<system-reminder>" in injected[-1].content
- assert "SESSION_FILE_MARKER" in injected[-1].content
-
-
-async def test_sync_to_agent_read_failure_does_not_block_or_clear_old_state(tmp_path, monkeypatch):
- root = tmp_path / "prompt_attachment"
- loader = PromptAttachmentLoader(root)
- agent = FakeDeepAgent()
- session_dir = root / "sess1" / "session"
- session_dir.mkdir(parents=True)
- (session_dir / "runtime.md").write_text("v1", encoding="utf-8")
-
- await loader.sync_to_agent(agent, session_id="sess1")
- assert await agent.prompt_attachment_manager.list_by_filter(source=SESSION_SOURCE, session_id="sess1")
-
- def fail_list(*args, **kwargs):
- raise OSError("boom")
-
- monkeypatch.setattr(loader, "load_session_attachments", fail_list)
- await loader.sync_to_agent(agent, session_id="sess1")
-
- items = await agent.prompt_attachment_manager.collect_for_session("sess1")
- assert [item.content for item in items] == ["v1"]
diff --git a/tests/unit_tests/agentserver/test_session_history_path_safety.py b/tests/unit_tests/agentserver/test_session_history_path_safety.py
index 431efdbafb..e0e9bcf65e 100644
--- a/tests/unit_tests/agentserver/test_session_history_path_safety.py
+++ b/tests/unit_tests/agentserver/test_session_history_path_safety.py
@@ -63,8 +63,8 @@ def test_create_does_not_mkdir_before_rejecting_traversal(patched_sessions_root,
"""
# 让白名单失效(模拟被绕过),强制走第二道 relative_to 防线
monkeypatch.setattr(
- "jiuwenswarm.server.runtime.prompt_attachment_loader.sanitize_session_id",
- lambda s: s,
+ "jiuwenswarm.server.runtime.session.session_metadata.is_valid_session_id",
+ lambda _s: True,
)
# sessions_root 之外的目标,调用前必须不存在
@@ -138,9 +138,7 @@ def test_whitespace_only_id_rejected(patched_sessions_root):
# ---------------------------------------------------------------------------
-# 纵深防御:白名单被绕过(sanitize 假装放行)时,resolve() 越界校验仍拦截。
-# resolve_session_dir 内部用 `from ... import sanitize_session_id`(函数级 import),
-# 每次调用都重新解析到 prompt_attachment_loader 模块的当前属性,故 patch 模块属性即可生效。
+# 纵深防御:白名单被绕过时,resolve() 越界校验仍拦截。
# ---------------------------------------------------------------------------
def test_second_line_defense_blocks_outside_root(patched_sessions_root, monkeypatch, tmp_path):
@@ -149,16 +147,13 @@ def test_second_line_defense_blocks_outside_root(patched_sessions_root, monkeypa
outside = tmp_path / "outside_target"
outside.mkdir()
- # 让白名单失效:sanitize 原样返回,模拟"白名单被绕过"的假设场景
+ # 让白名单失效,模拟"白名单被绕过"的假设场景
monkeypatch.setattr(
- "jiuwenswarm.server.runtime.prompt_attachment_loader.sanitize_session_id",
- lambda s: s,
+ "jiuwenswarm.server.runtime.session.session_metadata.is_valid_session_id",
+ lambda _s: True,
)
# 确认白名单确实被绕过(否则后续断言无意义)
- from jiuwenswarm.server.runtime.prompt_attachment_loader import sanitize_session_id
- assert sanitize_session_id("../outside_target") == "../outside_target"
-
# 即便白名单放过,../outside_target 解析后落在 sessions_root 之外,必须被拒
p, err = resolve_session_dir("../outside_target")
assert p is None, f"second line of defense failed: {p}"
@@ -196,6 +191,24 @@ def test_dot_and_dotdot_rejected(patched_sessions_root, session_id):
assert err is not None
+ "session_id",
+ [
+ ".hidden",
+ "_hidden",
+ "-hidden",
+ "hidden.",
+ "hidden_",
+ "hidden-",
+ ],
+)
+def test_reserved_edge_character_rejected(patched_sessions_root, session_id):
+ """Keep the legacy rule that ``._-`` may occur only inside a session id."""
+ p, err = resolve_session_dir(session_id)
+ assert p is None
+ assert err == "invalid session_id"
+
+
def test_default_fallback_value_is_accepted(patched_sessions_root):
"""sanitize 的空输入回退值 default 本身是合法 id,应通过。"""
p, err = resolve_session_dir("default")
@@ -234,10 +247,10 @@ def test_max_length_id_accepted(patched_sessions_root):
def test_symlink_escape_blocked(patched_sessions_root, tmp_path, monkeypatch):
"""sessions_root 内建 symlink 指向外部目录,resolve 后必须被拒。"""
# symlink 的链接名合法(字母数字),白名单会放行;重点测第二道防线。
- # 用 monkeypatch 让 sanitize 放行(模拟白名单被绕过),强制走 resolve 越界检查
+ # 用 monkeypatch 让白名单放行,强制走 resolve 越界检查
monkeypatch.setattr(
- "jiuwenswarm.server.runtime.prompt_attachment_loader.sanitize_session_id",
- lambda s: s,
+ "jiuwenswarm.server.runtime.session.session_metadata.is_valid_session_id",
+ lambda _s: True,
)
# 在 sessions_root 之外造一个真实目录(攻击目标)
diff --git a/tests/unit_tests/test_session_metadata.py b/tests/unit_tests/test_session_metadata.py
index f1de808a3a..e0c7fb42cc 100644
--- a/tests/unit_tests/test_session_metadata.py
+++ b/tests/unit_tests/test_session_metadata.py
@@ -2690,7 +2690,7 @@ class TestLegacyWorkspacePrefixRemap:
"""读路径惰性迁移:metadata 中旧前缀被重映射并异步写盘。
直接调用 _apply_metadata_defaults_with_inference 绕开
- sanitize_session_id 的导入链(其依赖 openjiuwen 子模块,
+ session id 白名单校验链路(其依赖运行时模块,
在部分测试环境缺失,与 TestLazyMigrationOnRead 整类的既有
环境性 ERROR 相同,非本用例逻辑问题)。
"""