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(skill): persist session authorization and active state in shared files

Haoqiang Wang270999ddd559
diff --git a/docs/zh/skill-authorization-session-files.md b/docs/zh/skill-authorization-session-files.md
new file mode 100644
index 0000000000..b7951a2aaf
--- /dev/null
+++ b/docs/zh/skill-authorization-session-files.md
@@ -0,0 +1,38 @@
+# 会话级 Skill 授权文件
+
+Skill 授权属于逻辑会话,不属于承载请求的 AgentServer Pod。AgentServer 默认将完整授权和活跃技能写入系统会话目录,不需要额外的 Redis 配置。
+
+## 存储与生命周期
+
+```text
+<租户 Agent 目录>/sessions/<session_id>/
+└── .skill_authorization/
+ ├── state.lock # 跨进程、跨 Pod 的互斥锁
+ └── state.json # Grant、执行窗口、活跃技能和失效状态
+```
+
+该目录使用系统的会话路径解析规则,按租户、会话和 Agent 作用域隔离,与用户选择的项目目录无关。多个会话共用项目目录时,授权仍互相独立。
+
+`state.json` 保存 Skill 身份摘要、权限快照、审批决定、审批工具调用标识及授权状态。激活时继续校验 Skill 正文和权限摘要、版本及审批调用绑定,沿用 SDK 的授权状态转换。
+
+授权没有独立的过期 TTL。Runtime 路由过期、Pod 切换、适配器回收或进程重启不会删除授权文件。Skill 完成、撤销、切换和活跃状态闲置回收继续遵守原有语义:例如“会话内允许”的授权完成后保留为未激活的审批记录,“本次允许”则回收。永久删除会话会先写入删除标记,再随会话目录清除文件。
+
+## 一致性与安全
+
+每次操作读取文件并临时调用 SDK 状态机,AgentServer 不保留授权或活跃技能缓存。撤销结果因此会被旧 Pod 的下一次权限检查读到。只读查询不重写状态文件;状态变化在文件锁内执行,通过临时文件、同步写入和原子替换提交,防止并发覆盖和半写文件。
+
+进程内按状态目录分别加锁,不同会话可以并行访问。共享失效版本由写端加锁并原子替换,读端直接读取完整文件,事务结束前再次核对版本;不使用延迟缓存。
+
+生效配置关闭授权功能时,权限检查停止叠加 Skill 权限,同时使持久化授权失效;新启动的 Pod 也执行该检查。全局清理使用共享失效版本,审批记录另绑定会话实例标识,阻止关闭开关或删除并重建会话后的迟到审批恢复旧授权。缺失、损坏、锁超时或存储不可用时不使用旧授权,也不回退到内存。
+
+系统会话目录及失效版本目录对沙箱工具只读,禁止通过 `sandbox.files.allow` 为其开放写入。授权文件仅由宿主服务修改。
+
+## 部署与使用
+
+单机使用原有会话目录即可。多个 AgentServer Pod 必须通过现有共享数据卷访问相同租户的会话目录;该文件系统须支持跨主机文件锁和同目录原子替换,例如正确配置的 NFS。仅共享项目目录、各 Pod 会话目录仍在各自本地磁盘的部署不满足要求。
+
+进程内锁和跨进程文件锁各自最多等待 0.3 秒,此值不是整个文件操作的超时,底层文件系统 I/O 仍可能耗时更长。锁等待失败时不使用旧授权;技能状态写入失败会停止当前执行并提示重试,防止继续使用未成功清理的状态。已删除或尚未初始化的会话不会由活跃技能回调重建。文件损坏不会自动恢复旧授权,应先排查存储异常。
+
+部署时应结合实际会话并发量检查共享卷延迟和锁支持。出现 `session file unavailable`、`state update failed` 或 `Skill state ... lock timed out` 时,检查共享卷、同会话并发操作和存储延迟;增加等待时间不能替代解决锁竞争。
+
+用户通过现有 Skill 加载与审批界面授权,无需填写新的存储参数。不要手动编辑授权文件。删除会话使用现有会话删除接口,以便同时回收运行状态、审批等待和目录。
diff --git a/jiuwenswarm/agents/harness/common/rails/permissions/skill_authorization/file_store.py b/jiuwenswarm/agents/harness/common/rails/permissions/skill_authorization/file_store.py
new file mode 100644
index 0000000000..8167357365
--- /dev/null
+++ b/jiuwenswarm/agents/harness/common/rails/permissions/skill_authorization/file_store.py
@@ -0,0 +1,563 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
+"""Session-owned Skill state. Files are authoritative; grants are never cached."""
+
+from __future__ import annotations
+
+import json
+import logging
+import os
+import secrets
+import threading
+import time
+from collections.abc import Callable, Iterator
+from contextlib import contextmanager
+from contextvars import ContextVar
+from dataclasses import asdict
+from functools import wraps
+from pathlib import Path
+from typing import Any
+from weakref import WeakValueDictionary
+
+import portalocker
+from openjiuwen.core.runner.callback.errors import AbortError
+from openjiuwen.harness.security.skill_authorization import (
+ GrantDecision,
+ GrantStatus,
+ SkillGrant,
+ SkillGrantStore,
+)
+
+from jiuwenswarm.common.utils import (
+ get_agent_sessions_dir,
+ get_user_workspace_dir,
+ is_valid_session_id,
+)
+
+logger = logging.getLogger(__name__)
+_SCHEMA = 1
+_PRIVATE_DIR = ".skill_authorization"
+_LOCK_TIMEOUT = 0.3
+_MAX_BYTES = 256 * 1024
+_LOCAL_LOCKS_GUARD = threading.Lock()
+_LOCAL_IO_LOCKS: WeakValueDictionary = WeakValueDictionary()
+# Request identity only, never authorization data. Supervisor tasks do not
+# automatically inherit the HTTP request's tenant path bindings.
+_session_file_context: ContextVar[tuple[str, Path] | None] = ContextVar(
+ "skill_session_files", default=None
+)
+
+
+def bind_session_file_context(session_id: str, sessions_root: Path) -> None:
+ _session_file_context.set((session_id, sessions_root))
+
+
+def clear_session_file_context() -> None:
+ _session_file_context.set(None)
+
+
+def _session_files_root() -> Path:
+ context = _session_file_context.get()
+ return context[1] if context else get_agent_sessions_dir()
+
+
+class _TransactionStore(SkillGrantStore):
+ """Use SDK transitions on a disposable snapshot, without a process cache."""
+
+ def __init__(self, sid: str, doc: dict, generation: int) -> None:
+ if (
+ not isinstance(doc.get("grants", {}), dict)
+ or not isinstance(doc.get("executions", {}), dict)
+ or not isinstance(doc.get("invalidated", []), list)
+ ):
+ raise TypeError("Invalid Skill state maps")
+ if doc.get("active_skill") is not None and not isinstance(
+ doc["active_skill"], dict
+ ):
+ raise TypeError("Invalid active Skill state")
+ self._lock = threading.RLock()
+ self._grants = {}
+ self._skill_executions = {
+ (sid, scope): name for scope, name in doc.get("executions", {}).items()
+ }
+ self._invalidated_scopes = {
+ (sid, scope) for scope in doc.get("invalidated", [])
+ }
+ self._retired_sessions = set()
+ self.generation = generation
+ for scope, records in doc.get("grants", {}).items():
+ if not isinstance(scope, str) or not isinstance(records, list):
+ raise TypeError("Invalid Skill grant scope")
+ decoded = {}
+ for fields in records:
+ if not isinstance(fields, dict):
+ raise TypeError("Invalid Skill grant record")
+ try:
+ grant = SkillGrant(
+ **{
+ **fields,
+ "decision": GrantDecision(fields["decision"]),
+ "status": GrantStatus(fields["status"]),
+ }
+ )
+ except (TypeError, KeyError) as exc:
+ raise ValueError("Invalid Skill grant record") from exc
+ decoded[grant.skill_name] = grant
+ self._grants[(sid, scope)] = decoded
+
+ @property
+ def authorization_generation(self) -> int:
+ return self.generation
+
+ def has_runtime_state(self) -> bool:
+ """Startup must install storage before any native grants are created."""
+ with self._lock:
+ return bool(self._grants or self._skill_executions)
+
+ def snapshot(self, sid: str) -> dict:
+ """Expose data, not SDK protected members, to the persistence adapter."""
+ return {
+ "grants": {
+ scope: [asdict(grant) for grant in grants.values()]
+ for (stored_sid, scope), grants in self._grants.items()
+ if stored_sid == sid
+ },
+ "executions": {
+ scope: name
+ for (stored_sid, scope), name in self._skill_executions.items()
+ if stored_sid == sid
+ },
+ "invalidated": sorted(
+ scope
+ for stored_sid, scope in self._invalidated_scopes
+ if stored_sid == sid
+ ),
+ }
+
+
+def _open_at(directory: int | Path, name: str, flags: int, mode: int = 0o600) -> int:
+ if isinstance(directory, int):
+ return os.open(name, flags, mode, dir_fd=directory)
+ target = directory / name
+ if target.is_symlink():
+ raise ValueError("Skill state may not be a symlink")
+ return os.open(target, flags, mode)
+
+
+@contextmanager
+def _locked_directory(directory: Path, *, create: bool = False) -> Iterator[int | Path]:
+ # Keep only locks for in-flight operations, never grants or session state.
+ # Independent sessions must not queue behind each other's filesystem I/O.
+ key = os.path.abspath(directory)
+ with _LOCAL_LOCKS_GUARD:
+ local_lock = _LOCAL_IO_LOCKS.get(key)
+ if local_lock is None:
+ local_lock = threading.RLock()
+ _LOCAL_IO_LOCKS[key] = local_lock
+ if not local_lock.acquire(timeout=_LOCK_TIMEOUT):
+ raise TimeoutError("Skill state local I/O lock timed out")
+ try:
+ with _locked_directory_fd(directory, create=create) as fd:
+ yield fd
+ finally:
+ local_lock.release()
+
+
+@contextmanager
+def _open_directory(directory: Path) -> Iterator[int | Path]:
+ flags = os.O_RDONLY | getattr(os, "O_DIRECTORY", 0) | getattr(os, "O_NOFOLLOW", 0)
+ if (
+ directory.is_symlink()
+ or getattr(directory.lstat(), "st_file_attributes", 0) & 0x400
+ ):
+ raise ValueError("Skill state directory may not be a link")
+ directory_fd = (
+ directory if os.name == "nt" else os.open(directory, flags, mode=0o600)
+ )
+ try:
+ yield directory_fd
+ finally:
+ if isinstance(directory_fd, int):
+ os.close(directory_fd)
+
+
+@contextmanager
+def _locked_directory_fd(
+ directory: Path, *, create: bool = False
+) -> Iterator[int | Path]:
+ """Bounded cross-process lock, anchored to the directory opened before deletion."""
+ if create:
+ directory.mkdir(mode=0o700, exist_ok=True)
+ # Windows cannot open a directory fd. Its open lock file prevents the
+ # directory from being removed while the transaction holds the handle.
+ with _open_directory(directory) as directory_fd:
+ locked = False
+ lock_fd = _open_at(
+ directory_fd,
+ "state.lock",
+ os.O_CREAT | os.O_RDWR | getattr(os, "O_NOFOLLOW", 0),
+ )
+ with os.fdopen(lock_fd, "a+b") as lock_file:
+ deadline = time.monotonic() + _LOCK_TIMEOUT
+ try:
+ while not locked:
+ try:
+ portalocker.lock(
+ lock_file, portalocker.LOCK_EX | portalocker.LOCK_NB
+ )
+ locked = True
+ except portalocker.exceptions.LockException:
+ if time.monotonic() >= deadline:
+ raise TimeoutError(
+ "Skill state file lock timed out"
+ ) from None
+ time.sleep(0.01)
+ yield directory_fd
+ finally:
+ if locked:
+ portalocker.unlock(lock_file)
+
+
+def _read_json(directory_fd: int | Path, name: str) -> tuple[dict, str]:
+ try:
+ fd = _open_at(directory_fd, name, os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0))
+ except FileNotFoundError:
+ return {}, ""
+ with os.fdopen(fd, "r", encoding="utf-8") as source:
+ raw = source.read(_MAX_BYTES + 1)
+ if len(raw.encode("utf-8")) > _MAX_BYTES:
+ raise ValueError("Skill state exceeds size limit")
+ data = json.loads(raw)
+ if not isinstance(data, dict):
+ raise TypeError("Skill state must be an object")
+ return data, raw
+
+
+def _atomic_json(directory_fd: int | Path, name: str, data: dict) -> None:
+ """Replace within the original directory fd; never recreate a deleted session."""
+ raw = json.dumps(data, ensure_ascii=False, separators=(",", ":"))
+ if len(raw.encode("utf-8")) > _MAX_BYTES:
+ raise ValueError("Skill state exceeds size limit")
+ temporary = f".{name}.{secrets.token_hex(8)}.tmp"
+ fd = _open_at(directory_fd, temporary, os.O_CREAT | os.O_EXCL | os.O_WRONLY)
+ try:
+ with os.fdopen(fd, "w", encoding="utf-8") as target:
+ target.write(raw)
+ target.flush()
+ os.fsync(target.fileno())
+ if isinstance(directory_fd, int):
+ # POSIX rename atomically replaces the destination and advertises
+ # dir_fd support, so independent directories need no global lock.
+ os.rename(
+ temporary, name, src_dir_fd=directory_fd, dst_dir_fd=directory_fd
+ )
+ os.fsync(directory_fd)
+ else:
+ os.replace(directory_fd / temporary, directory_fd / name)
+ finally:
+ try:
+ if isinstance(directory_fd, int):
+ os.unlink(temporary, dir_fd=directory_fd)
+ else:
+ os.unlink(directory_fd / temporary)
+ except FileNotFoundError:
+ pass
+
+
+def _file_operation(method: Callable) -> Callable:
+ @wraps(method)
+ def call(self, session_id, *args, **kwargs):
+ return self.operate(
+ session_id,
+ lambda store, doc: method(store, session_id, *args, **kwargs),
+ write=method.__name__ not in {"get_grant", "list_grants"},
+ )
+
+ return call
+
+
+class FileSkillGrantStore(SkillGrantStore):
+ """Authoritative session files; no grant or active-skill dictionaries on this object."""
+
+ def __init__(
+ self,
+ *,
+ sessions_root: Callable[[], Path] | None = None,
+ data_root: Callable[[], Path] | None = None,
+ ) -> None:
+ self.sessions_root = sessions_root or _session_files_root
+ self.data_root = data_root or get_user_workspace_dir
+
+ def session_directory(self, session_id: str) -> Path:
+ """Resolve a real session without allowing traversal or symlink substitution."""
+ from jiuwenswarm.server.runtime.session.session_metadata import (
+ resolve_session_subdir,
+ )
+
+ if session_id == "default" or not is_valid_session_id(session_id):
+ raise ValueError("A real session_id is required for Skill state")
+ path = resolve_session_subdir(session_id, sessions_root=self.sessions_root())
+ if path is None:
+ raise ValueError("Invalid Skill state session directory")
+ return path
+
+ def epoch_directory(self) -> Path:
+ """Instance-wide invalidation metadata; separate from user task files."""
+ return self.data_root() / _PRIVATE_DIR
+
+ def read_epoch(self) -> int:
+ directory = self.epoch_directory()
+ if not directory.exists():
+ return 0
+ # Writers serialize increments and atomically replace generation.json.
+ # Fresh opens see an old or new complete value; readers need no global
+ # file lock. operate still checks the epoch again before returning.
+ with _open_directory(directory) as fd:
+ data, _raw = _read_json(fd, "generation.json")
+ return int(data.get("generation", 0))
+
+ @property
+ def authorization_generation(self) -> int:
+ from jiuwenswarm.common.path_provider import current_path_context
+
+ try:
+ context = _session_file_context.get()
+ sid = context[0] if context else current_path_context().session_id
+ if not sid or sid == "default":
+ raise ValueError("Skill approval requires a real session identity")
+ return self.get_authorization_generation(sid)
+ except (
+ OSError, ValueError, TypeError, RuntimeError,
+ portalocker.exceptions.LockException,
+ ) as exc:
+ # A normal exception is swallowed by the SDK callback dispatcher;
+ # a constant fallback can compare equal across two failed reads.
+ raise AbortError(
+ "Skill authorization version unavailable; retry the request"
+ ) from exc
+
+ def get_authorization_generation(self, session_id: str) -> int:
+ """Bind approvals to this session incarnation and the shared feature epoch."""
+ # The first read must persist the nonce before an approval can wait.
+ return self.operate(
+ session_id, lambda store, doc: store.authorization_generation
+ )
+
+ @property
+ def retired_session_memory_bytes(self) -> int:
+ return 0
+
+ def operate(self, session_id: str, action: Callable, *, write: bool = True) -> Any:
+ """Read under lock, execute SDK transitions, persist only changed state."""
+ sid = str(session_id or "").strip()
+ session = self.session_directory(sid)
+ directory = session / _PRIVATE_DIR
+ epoch = self.read_epoch()
+ if not session.is_dir():
+ if write:
+ raise RuntimeError(
+ f"Skill authorization session has been deleted or is not initialized: {session}"
+ )
+ return action(_TransactionStore(sid, {}, epoch << 64), {})
+ if not directory.exists() and not write:
+ return action(_TransactionStore(sid, {}, epoch << 64), {})
+ with _locked_directory(directory, create=True) as fd:
+ doc, raw = _read_json(fd, "state.json")
+ if doc and (doc.get("schema") != _SCHEMA or doc.get("session_id") != sid):
+ raise ValueError("Invalid Skill authorization state schema or session")
+ if doc.get("deleted"):
+ raise RuntimeError("Skill authorization session has been deleted")
+ if not doc or doc.get("epoch") != epoch:
+ doc = {
+ "schema": _SCHEMA,
+ "session_id": sid,
+ "epoch": epoch,
+ "nonce": secrets.randbits(63),
+ }
+ generation = (epoch << 64) | int(doc["nonce"])
+ store = _TransactionStore(sid, doc, generation)
+ result = action(store, doc)
+ state = store.snapshot(sid)
+ doc.update(state)
+ if "main" in state["invalidated"]:
+ doc.pop("active_skill", None)
+ if self.read_epoch() != epoch:
+ raise RuntimeError("Skill authorization changed during the operation")
+ if (
+ write
+ and json.dumps(doc, ensure_ascii=False, separators=(",", ":")) != raw
+ ):
+ _atomic_json(fd, "state.json", doc)
+ return result
+
+ create_pending_grant = _file_operation(SkillGrantStore.create_pending_grant)
+ activate_pending = _file_operation(SkillGrantStore.activate_pending)
+ get_grant = _file_operation(SkillGrantStore.get_grant)
+ list_grants = _file_operation(SkillGrantStore.list_grants)
+ drop_pending = _file_operation(SkillGrantStore.drop_pending)
+ enter_skill_execution = _file_operation(SkillGrantStore.enter_skill_execution)
+ exit_skill_execution = _file_operation(SkillGrantStore.exit_skill_execution)
+
+ def get_active(self, session_id: str, agent_scope_id: str):
+ try:
+ return self.operate(
+ session_id,
+ lambda store, doc: store.get_active(session_id, agent_scope_id),
+ write=False,
+ )
+ except (
+ OSError,
+ ValueError,
+ TypeError,
+ RuntimeError,
+ portalocker.exceptions.LockException,
+ ):
+ logger.warning(
+ "[skill_authorization] session file unavailable; no overlay",
+ exc_info=True,
+ )
+ return None
+
+ def get_active_skill_execution(self, session_id: str, agent_scope_id: str):
+ try:
+ return self.operate(
+ session_id,
+ lambda store, doc: store.get_active_skill_execution(
+ session_id, agent_scope_id
+ ),
+ write=False,
+ )
+ except (
+ OSError,
+ ValueError,
+ TypeError,
+ RuntimeError,
+ portalocker.exceptions.LockException,
+ ):
+ logger.warning(
+ "[skill_authorization] session file unavailable; no execution window",
+ exc_info=True,
+ )
+ return None
+
+ def invalidate_scope(
+ self, session_id: str, agent_scope_id: str, *, reason: str
+ ) -> None:
+ self.operate(
+ session_id,
+ lambda store, doc: store.invalidate_scope(
+ session_id, agent_scope_id, reason=reason
+ ),
+ )
+
+ def revoke_grants(
+ self,
+ session_id: str,
+ agent_scope_id: str,
+ *,
+ skill_name=None,
+ reason="skill_complete",
+ ) -> None:
+ self.operate(
+ session_id,
+ lambda store, doc: store.revoke_grants(
+ session_id, agent_scope_id, skill_name=skill_name, reason=reason
+ ),
+ )
+
+ def clear_scope(self, session_id: str, agent_scope_id: str) -> None:
+ def clear(store, doc):
+ store.clear_scope(session_id, agent_scope_id)
+ if agent_scope_id == "main":
+ doc.pop("active_skill", None)
+
+ self.operate(session_id, clear)
+
+ def clear_session(self, session_id: str) -> None:
+ if not self.session_directory(session_id).is_dir():
+ return
+
+ def retire(store, doc):
+ store.clear_all()
+ doc.pop("active_skill", None)
+ doc["deleted"] = True
+
+ self.operate(session_id, retire)
+
+ def sync_feature_state(self, session_id: str, *, enabled: bool) -> None:
+ """A cold Pod observing disabled policy must retire persisted grants too."""
+
+ def sync(store, doc):
+ if doc.get("feature_enabled") is enabled:
+ return
+ if not enabled:
+ store.clear_all()
+ doc.pop("active_skill", None)
+ doc["nonce"] = secrets.randbits(63)
+ doc["feature_enabled"] = enabled
+
+ self.operate(session_id, sync)
+
+ def clear_all(self) -> None:
+ self.data_root().mkdir(parents=True, exist_ok=True)
+ with _locked_directory(self.epoch_directory(), create=True) as fd:
+ data, _raw = _read_json(fd, "generation.json")
+ _atomic_json(
+ fd,
+ "generation.json",
+ {"generation": int(data.get("generation", 0)) + 1},
+ )
+
+ def get_active_skill_state(self, session_id: str) -> dict | None:
+ try:
+ return self.operate(
+ session_id, lambda store, doc: doc.get("active_skill"), write=False
+ )
+ except (
+ OSError,
+ ValueError,
+ TypeError,
+ RuntimeError,
+ portalocker.exceptions.LockException,
+ ):
+ logger.warning(
+ "[skill_authorization] session file unavailable; no active skill",
+ exc_info=True,
+ )
+ return None
+
+ def update_active_skill_state(
+ self, session_id: str, update: Callable[[dict], dict | None]
+ ) -> dict | None:
+ def action(store, doc):
+ updated = update(dict(doc.get("active_skill") or {}))
+ if updated is None:
+ doc.pop("active_skill", None)
+ else:
+ doc["active_skill"] = updated
+ return updated
+
+ return self.operate(session_id, action)
+
+
+def configure_shared_skill_authorization(_config: dict) -> FileSkillGrantStore:
+ """Install session-file state before accepting requests; never fall back to memory."""
+ from openjiuwen.harness.security.skill_authorization import (
+ get_skill_grant_store,
+ set_skill_grant_store,
+ )
+
+ current = get_skill_grant_store()
+ if isinstance(current, FileSkillGrantStore):
+ return current
+ if not hasattr(SkillGrantStore, "authorization_generation"):
+ raise RuntimeError(
+ "Session Skill state requires SDK shared authorization_generation support"
+ )
+ if _TransactionStore.has_runtime_state(current):
+ raise RuntimeError("Install session Skill state before serving requests")
+ store = FileSkillGrantStore()
+ set_skill_grant_store(store)
+ logger.info(
+ "[skill_authorization] session file state enabled; no process-local authorization cache"
+ )
+ return store
diff --git a/jiuwenswarm/agents/harness/common/rails/permissions/skill_authorization/runtime.py b/jiuwenswarm/agents/harness/common/rails/permissions/skill_authorization/runtime.py
index 432eddbd38..40b12b20ea 100644
--- a/jiuwenswarm/agents/harness/common/rails/permissions/skill_authorization/runtime.py
+++ b/jiuwenswarm/agents/harness/common/rails/permissions/skill_authorization/runtime.py
@@ -11,31 +11,56 @@ logger = logging.getLogger(__name__)
def _enabled() -> bool:
+ from openjiuwen.harness.security.skill_authorization import (
+ is_skill_authorization_enabled,
+ )
+
from jiuwenswarm.agents.harness.common.rails.permissions.config_loader import (
get_effective_permissions_config,
)
- from openjiuwen.harness.security.skill_authorization import (
- is_skill_authorization_enabled,
+ return is_skill_authorization_enabled(get_effective_permissions_config())
+
+
+def _session_store(sessions_root=None):
+ from openjiuwen.harness.security.skill_authorization.grant_store import (
+ peek_skill_grant_store,
)
- return is_skill_authorization_enabled(get_effective_permissions_config())
+ from jiuwenswarm.agents.harness.common.rails.permissions.skill_authorization.file_store import (
+ FileSkillGrantStore,
+ )
+ store = peek_skill_grant_store()
+ if isinstance(store, FileSkillGrantStore) and sessions_root is not None:
+ return FileSkillGrantStore(
+ sessions_root=lambda: sessions_root, data_root=store.data_root
+ )
+ return store
-def revoke_main_scope(session_id: str | None, *, reason: str) -> None:
+
+def revoke_main_scope(
+ session_id: str | None, *, reason: str, sessions_root=None
+) -> None:
"""Deactivate main-scope grants and delegated approvals, best-effort."""
sid = str(session_id or "").strip()
if not sid:
return
try:
- if not _enabled():
- return
- from openjiuwen.harness.security.skill_authorization import get_skill_grant_store
from openjiuwen.harness.security.skill_authorization.subagent_approval_registry import (
get_subagent_approval_registry,
)
- get_skill_grant_store().revoke_grants(sid, "main", reason=reason)
+ from jiuwenswarm.agents.harness.common.rails.permissions.skill_authorization.file_store import (
+ FileSkillGrantStore,
+ )
+
+ store = _session_store(sessions_root)
+ if store is None or (
+ not isinstance(store, FileSkillGrantStore) and not _enabled()
+ ):
+ return
+ store.revoke_grants(sid, "main", reason=reason)
get_subagent_approval_registry().cancel_session(sid)
except Exception as exc: # noqa: BLE001 — never mask cancel/error handling
logger.warning(
@@ -47,14 +72,11 @@ def revoke_main_scope(session_id: str | None, *, reason: str) -> None:
)
-def clear_deleted_session(session_id: str) -> None:
- """Clear existing in-memory state without initializing it while disabled."""
+def clear_deleted_session(session_id: str, *, sessions_root=None) -> None:
+ """Retire session files and cancel pending approvals without initializing a store."""
sid = str(session_id or "").strip()
if not sid:
return
- from openjiuwen.harness.security.skill_authorization.grant_store import (
- peek_skill_grant_store,
- )
from openjiuwen.harness.security.skill_authorization.subagent_approval_registry import (
SubagentApprovalRegistry,
)
@@ -62,7 +84,7 @@ def clear_deleted_session(session_id: str) -> None:
registry = SubagentApprovalRegistry.peek_instance()
if registry is not None:
registry.cancel_session(sid)
- store = peek_skill_grant_store()
+ store = _session_store(sessions_root)
if store is not None:
store.clear_session(sid)
@@ -76,7 +98,9 @@ def revoke_deactivated_main_skill(session_id: str, skill_name: str) -> None:
try:
if not _enabled():
return
- from openjiuwen.harness.security.skill_authorization import get_skill_grant_store
+ from openjiuwen.harness.security.skill_authorization import (
+ get_skill_grant_store,
+ )
store = get_skill_grant_store()
active = store.get_active(sid, "main")
@@ -110,9 +134,8 @@ def resolve_subagent_approval(
if source == "subagent_skill_load" or request_id.startswith("subagent_skill_load_"):
kind = SubagentApprovalKind.SKILL_LOAD
- elif (
- source == "subagent_tool_permission"
- or request_id.startswith("subagent_tool_permission_")
+ elif source == "subagent_tool_permission" or request_id.startswith(
+ "subagent_tool_permission_"
):
kind = SubagentApprovalKind.TOOL_PERMISSION
else:
diff --git a/jiuwenswarm/agents/harness/common/rails/permissions/skill_authorization_permission_rail.py b/jiuwenswarm/agents/harness/common/rails/permissions/skill_authorization_permission_rail.py
index 954d2d942b..7cede80016 100644
--- a/jiuwenswarm/agents/harness/common/rails/permissions/skill_authorization_permission_rail.py
+++ b/jiuwenswarm/agents/harness/common/rails/permissions/skill_authorization_permission_rail.py
@@ -40,14 +40,13 @@ def is_unparseable_permission_resume_text(user_input: Any) -> bool:
def _compose_active_skill_permissions(
base_config: dict[str, Any],
- session_id: str,
- agent_scope_id: str,
- grant_store: Any,
+ active: Any,
) -> dict[str, Any]:
"""Compose the active Skill overlay into one permission snapshot."""
- from openjiuwen.harness.security.skill_authorization import compose_skill_permissions
+ from openjiuwen.harness.security.skill_authorization import (
+ compose_skill_permissions,
+ )
- active = grant_store.get_active(session_id, agent_scope_id)
if active is None or not active.overlay_snapshot:
return copy.deepcopy(base_config)
return compose_skill_permissions(base_config, active.overlay_snapshot)
@@ -140,8 +139,17 @@ class SkillAuthorizationPermissionRail(PermissionInterruptRail):
from openjiuwen.harness.security.skill_authorization import (
get_skill_authorization_context,
get_skill_grant_store,
+ is_skill_authorization_enabled,
)
+ base_config = super()._get_permissions_snapshot(ctx)
+ if base_config is None:
+ base_config = self._static_config
+ if not is_skill_authorization_enabled(base_config):
+ # Never compose persisted grants into a disabled policy, including
+ # the first request in a new Pod which has no previous flag cache.
+ super()._refresh_permissions_for_tool_call(ctx)
+ return
authorization = get_skill_authorization_context()
scope = None
if (
@@ -168,14 +176,9 @@ class SkillAuthorizationPermissionRail(PermissionInterruptRail):
)
super()._refresh_permissions_for_tool_call(ctx)
return
- base_config = super()._get_permissions_snapshot(ctx)
- if base_config is None:
- base_config = self._static_config
effective_config = _compose_active_skill_permissions(
base_config,
- session_id,
- agent_scope_id,
- grant_store,
+ active,
)
self._engine.update_config(effective_config)
logger.info(
diff --git a/jiuwenswarm/agents/harness/common/rails/skill_active_state.py b/jiuwenswarm/agents/harness/common/rails/skill_active_state.py
index c45985064e..c03f75eda2 100644
--- a/jiuwenswarm/agents/harness/common/rails/skill_active_state.py
+++ b/jiuwenswarm/agents/harness/common/rails/skill_active_state.py
@@ -6,9 +6,13 @@ from __future__ import annotations
import contextvars
import logging
-from dataclasses import dataclass
+from collections.abc import Callable
+from dataclasses import asdict, dataclass
+from pathlib import Path
from typing import Any, Optional
+import portalocker
+from openjiuwen.core.runner.callback.errors import AbortError
from openjiuwen.core.single_agent.rail.base import AgentCallbackContext
from openjiuwen.harness.rails.base import DeepAgentRail
@@ -37,8 +41,7 @@ _current_session_var: contextvars.ContextVar[Optional[str]] = contextvars.Contex
@dataclass
class _SkillSessionState:
active_skill: Optional[str] = None
- # When the record is keyed under ``default``, the real session that produced
- # it (if known). Blocks cross-session adoption of orphan credentials.
+ # Original session identity retained in the serialized lifecycle record.
source_session: Optional[str] = None
# 连续「无该技能 skill_tool 调用」的 invoke 计数(过期兜底,改动 3):
# 每次 before_invoke 递增,skill_tool 激活时清零;达到上限自动清空。
@@ -50,81 +53,77 @@ class _SkillSessionState:
self.invokes_since_skill_tool = 0
-_sessions: dict[str, _SkillSessionState] = {}
+def _shared_store(session_id: str):
+ if not session_id or session_id == _DEFAULT_SESSION_ID:
+ return None
+ from openjiuwen.harness.security.skill_authorization.grant_store import (
+ peek_skill_grant_store,
+ )
+ from jiuwenswarm.agents.harness.common.rails.permissions.skill_authorization.file_store import (
+ FileSkillGrantStore,
+ )
-def _get_or_create_state(session_id: str) -> _SkillSessionState:
- state = _sessions.get(session_id)
- if state is None:
- state = _SkillSessionState()
- _sessions[session_id] = state
- return state
+ store = peek_skill_grant_store()
+ # Standalone rail use also persists files; never keep an active-skill cache.
+ return store if isinstance(store, FileSkillGrantStore) else FileSkillGrantStore()
-def _drop_session_state(session_id: str) -> None:
- if session_id:
- _sessions.pop(session_id, None)
+def _update_state(
+ session_id: str, update: Callable[[_SkillSessionState], None]
+) -> None:
+ store = _shared_store(session_id)
+ if store is None:
+ logger.warning(
+ "[SkillActiveStateRail] refusing state without a real session id"
+ )
+ return
+ def mutate(raw: dict) -> dict:
+ state = _SkillSessionState(**raw)
+ update(state)
+ return asdict(state)
-def clear_session_skill_state(session_id: str) -> None:
- """Drop in-memory active-skill state for a session (adapter cleanup)."""
- _drop_session_state(session_id)
+ try:
+ # Missing sessions contain no active state. Never create their parent
+ # directory: a late callback must not resurrect a deleted session.
+ if not store.session_directory(session_id).is_dir():
+ logger.debug("[SkillActiveStateRail] session unavailable: %s", session_id)
+ return
+ store.update_active_skill_state(session_id, mutate)
+ except (
+ OSError, ValueError, TypeError, RuntimeError,
+ portalocker.exceptions.LockException,
+ ) as exc:
+ logger.warning(
+ "[SkillActiveStateRail] state update failed session=%s: %s",
+ session_id, exc,
+ )
+ # An ordinary exception is swallowed by the callback framework. Abort
+ # this turn so failed expiry/switch/completion cannot use the old state.
+ raise AbortError("Skill state storage unavailable; retry the request") from exc
-def get_session_active_skill(session_id: str) -> Optional[str]:
- if not session_id:
- return None
- state = _sessions.get(session_id)
- return state.active_skill if state is not None else None
+def clear_session_skill_state(session_id: str, *, local_only: bool = False) -> None:
+ """Clear session files on explicit deactivation; adapter eviction has no state."""
+ if local_only:
+ return
+ store = _shared_store(session_id)
+ if store is not None and store.session_directory(session_id).is_dir():
+ store.update_active_skill_state(session_id, lambda _state: None)
-def adopt_default_active_skill(session_id: str) -> Optional[str]:
- """If *session_id* has no active skill, migrate one left under ``default``.
+def get_session_active_skill(session_id: str) -> str | None:
+ store = _shared_store(session_id)
+ if store is None:
+ return None
+ state = store.get_active_skill_state(session_id)
+ return state.get("active_skill") if state else None
- ToolCallInputs often lack ``conversation_id``; without a rail preset the
- skill can be recorded under the ``default`` sentinel. Credential injection
- then looks up the real ``officeclaw_…`` id and misses.
- Only migrate when the orphan's ``source_session`` is unknown or equals
- *session_id* — never hand another session's active skill (and its
- ``skill_envs``) to a caller that merely shares the process. Intended for
- ``before_invoke`` paths that already know the conversation id; the
- injection rail must not call this on every bash read.
- """
- sid = _nonempty_str(session_id)
- if not sid or sid == _DEFAULT_SESSION_ID:
- return get_session_active_skill(sid) if sid else None
- current = get_session_active_skill(sid)
- if current:
- return current
- orphan_state = _sessions.get(_DEFAULT_SESSION_ID)
- if orphan_state is None or not orphan_state.active_skill:
- return None
- owner = _nonempty_str(orphan_state.source_session)
- if owner and owner != sid:
- logger.warning(
- "[SkillActiveStateRail] refuse adopt active '%s' from default "
- "(source_session=%s != session=%s)",
- orphan_state.active_skill,
- owner,
- sid,
- )
- return None
- orphan = orphan_state.active_skill
- target = _get_or_create_state(sid)
- target.active_skill = orphan
- target.source_session = None
- # 迁移即确认激活,过期计数从零开始。
- target.invokes_since_skill_tool = 0
- _drop_session_state(_DEFAULT_SESSION_ID)
- logger.info(
- "[SkillActiveStateRail] adopted active '%s' from default -> session=%s "
- "(source_session=%s)",
- orphan,
- sid,
- owner or "-",
- )
- return orphan
+def adopt_default_active_skill(session_id: str) -> str | None:
+ """Compatibility lookup; credentials without a real session are never adopted."""
+ return get_session_active_skill(session_id)
def _nonempty_str(value: Any) -> Optional[str]:
@@ -258,12 +257,12 @@ class SkillActiveStateRail(DeepAgentRail):
invoke: it survives new user tasks and HITL interrupt continuations
(permission / confirm / ask_user / …). It is cleared only when the skill
completes (``skill_complete``), when another skill is activated (switch),
- when the session ends (adapter cache eviction / teardown calls
- ``clear_session_skill_state``), or when it expires: after
+ when the session is permanently deleted, or when it expires: after
``stale_invoke_limit`` consecutive invokes without any ``skill_tool``
call for it (skill_complete compliance is unreliable, so the expiry is
the safety net that keeps a forgotten skill from holding credentials
for a whole session).
+ Adapter eviction and process restart leave the session files intact.
"""
priority = 25
@@ -274,14 +273,28 @@ class SkillActiveStateRail(DeepAgentRail):
self,
session_id: Optional[str] = None,
stale_invoke_limit: Optional[int] = None,
+ sessions_root: Path | None = None,
) -> None:
super().__init__()
self._preset_session_id = _nonempty_str(session_id)
+ from jiuwenswarm.agents.harness.common.rails.permissions.skill_authorization.file_store import (
+ FileSkillGrantStore,
+ )
+
+ self._sessions_root = sessions_root or FileSkillGrantStore().sessions_root()
# None → 默认值;<= 0 → 显式禁用过期兜底。
if stale_invoke_limit is None:
stale_invoke_limit = self.DEFAULT_STALE_INVOKE_LIMIT
self._stale_invoke_limit = int(stale_invoke_limit)
+ @property
+ def sessions_root(self) -> Path:
+ return self._sessions_root
+
+ def set_sessions_root(self, sessions_root: Path) -> None:
+ """Capture the trusted request path before supervisor callbacks run."""
+ self._sessions_root = sessions_root
+
@property
def stale_invoke_limit(self) -> int:
"""当前过期兜底轮数(公开只读,供装配点检测配置变化,N2)。"""
@@ -291,7 +304,7 @@ class SkillActiveStateRail(DeepAgentRail):
"""原位更新过期兜底轮数(reload 路径,N2)。
遵循 configure() 的原位更新约定(避免重建实例脱离 agent rail 链):
- None → 默认值;<= 0 → 禁用。计数存于模块级状态,更新无副作用。
+ None → 默认值;<= 0 → 禁用。计数存于会话文件,更新无副作用。
"""
if stale_invoke_limit is None:
stale_invoke_limit = self.DEFAULT_STALE_INVOKE_LIMIT
@@ -302,15 +315,28 @@ class SkillActiveStateRail(DeepAgentRail):
def _bind_session_id(self, ctx: AgentCallbackContext, session_id: str) -> None:
_current_session_var.set(session_id)
+ from jiuwenswarm.agents.harness.common.rails.permissions.skill_authorization.file_store import (
+ bind_session_file_context,
+ )
+
+ bind_session_file_context(session_id, self._sessions_root)
extra = getattr(ctx, "extra", None)
if not isinstance(extra, dict):
return
# Prefer a real id already written by StreamEventRail; never overwrite
# it with the "default" sentinel.
existing = _nonempty_str(extra.get(_SESSION_ID_EXTRA_KEY))
- if session_id == _DEFAULT_SESSION_ID and existing and existing != _DEFAULT_SESSION_ID:
+ if (
+ session_id == _DEFAULT_SESSION_ID
+ and existing
+ and existing != _DEFAULT_SESSION_ID
+ ):
return
- if not existing or existing == _DEFAULT_SESSION_ID or session_id != _DEFAULT_SESSION_ID:
+ if (
+ not existing
+ or existing == _DEFAULT_SESSION_ID
+ or session_id != _DEFAULT_SESSION_ID
+ ):
extra[_SESSION_ID_EXTRA_KEY] = session_id
def _expire_stale_active_skill(
@@ -332,20 +358,22 @@ class SkillActiveStateRail(DeepAgentRail):
return
if is_resume_invoke:
return
- state = _sessions.get(session_id)
- if state is None or not state.active_skill:
- return
- if state.invokes_since_skill_tool >= self._stale_invoke_limit:
- logger.info(
- "[SkillActiveStateRail] expired active '%s' after %d invokes "
- "without skill_tool, session=%s",
- state.active_skill,
- state.invokes_since_skill_tool,
- session_id,
- )
- _drop_session_state(session_id)
- return
- state.invokes_since_skill_tool += 1
+
+ def expire(state: _SkillSessionState) -> None:
+ if not state.active_skill:
+ return
+ if state.invokes_since_skill_tool >= self._stale_invoke_limit:
+ logger.info(
+ "[SkillActiveStateRail] expired active '%s' after %d invokes session=%s",
+ state.active_skill,
+ state.invokes_since_skill_tool,
+ session_id,
+ )
+ state.reset()
+ return
+ state.invokes_since_skill_tool += 1
+
+ _update_state(session_id, expire)
async def before_invoke(self, ctx: AgentCallbackContext) -> None:
session_id = self._resolve_session_id(ctx)
@@ -354,20 +382,22 @@ class SkillActiveStateRail(DeepAgentRail):
# 覆盖替换)、会话结束(adapter 淘汰 / teardown 调
# clear_session_skill_state)、或连续 N 轮无 skill_tool 调用的过期
# 兜底(HITL 恢复轮不计入,CR-3a)。
- # 这里只做过期检查 + 把 default 哨兵下的孤儿态收养到真实会话
- # (ToolCallInputs 缺 conversation_id 时可能记录在 default 下)。
+ # 授权和活跃技能仅存于真实会话文件,不收养 default 孤儿状态。
+ self._bind_session_id(ctx, session_id)
self._expire_stale_active_skill(
session_id,
is_resume_invoke=_is_interrupt_resume_invoke(ctx),
)
- adopt_default_active_skill(session_id)
- self._bind_session_id(ctx, session_id)
async def after_invoke(self, ctx: AgentCallbackContext) -> None:
# Do not drop here: active skill is per-session lifecycle state, not
# per-invoke state. Cleanup happens on skill_complete, on switching to
# another skill, or on session teardown (clear_session_skill_state).
- return
+ from jiuwenswarm.agents.harness.common.rails.permissions.skill_authorization.file_store import (
+ clear_session_file_context,
+ )
+
+ clear_session_file_context()
def _owner_hint_for_default(self, ctx: AgentCallbackContext) -> Optional[str]:
"""Best-effort real session id when the storage key falls back to default."""
@@ -383,7 +413,9 @@ class SkillActiveStateRail(DeepAgentRail):
return cv
return None
- def _prefer_real_session_id(self, ctx: AgentCallbackContext, session_id: str) -> str:
+ def _prefer_real_session_id(
+ self, ctx: AgentCallbackContext, session_id: str
+ ) -> str:
"""Avoid recording active skill under the ``default`` sentinel when possible."""
if session_id != _DEFAULT_SESSION_ID:
return session_id
@@ -400,63 +432,72 @@ class SkillActiveStateRail(DeepAgentRail):
tool_name = getattr(inputs, "tool_name", "") or ""
session_id = self._prefer_real_session_id(ctx, self._resolve_session_id(ctx))
self._bind_session_id(ctx, session_id)
- state = _get_or_create_state(session_id)
+ if tool_name not in {"skill_tool", "skill_complete"}:
+ return
- if tool_name == "skill_complete":
- skill_name = (_get_arg(tool_call, "skill_name", "") or "").strip()
- if skill_name and state.active_skill == skill_name:
+ def apply(state: _SkillSessionState) -> None:
+
+ if tool_name == "skill_complete":
+ skill_name = (_get_arg(tool_call, "skill_name", "") or "").strip()
+ if skill_name and state.active_skill == skill_name:
+ logger.info(
+ "[SkillActiveStateRail] skill_complete(%s) session=%s -> idle",
+ skill_name,
+ session_id,
+ )
+ state.reset()
+ elif (
+ skill_name
+ and state.active_skill
+ and state.active_skill != skill_name
+ ):
+ # 激活名 ≠ 完成名:不清空(保持当前激活态),但留痕,
+ # 防"状态挂死且无从排查"。
+ logger.warning(
+ "[SkillActiveStateRail] skill_complete(%s) ignored: active is "
+ "'%s' session=%s (complete only clears on name match)",
+ skill_name,
+ state.active_skill,
+ session_id,
+ )
+ return
+
+ if tool_name != "skill_tool":
+ return
+
+ meta = getattr(tool_msg, "metadata", None) or {}
+ if meta.get("is_directory_listing"):
+ return
+ skill_name = (
+ meta.get("skill_name") or _get_arg(tool_call, "skill_name", "") or ""
+ ).strip()
+ if not skill_name:
+ return
+ prior_skill = state.active_skill
+ if prior_skill and prior_skill != skill_name:
+ # 切换到另一个 skill:旧 active_skill 在此清空(被新技能替换)。
logger.info(
- "[SkillActiveStateRail] skill_complete(%s) session=%s -> idle",
+ "[SkillActiveStateRail] switch active '%s' -> '%s' session=%s",
+ prior_skill,
skill_name,
session_id,
)
- state.reset()
- elif skill_name and state.active_skill and state.active_skill != skill_name:
- # 激活名 ≠ 完成名:不清空(保持当前激活态),但留痕,
- # 防"状态挂死且无从排查"。
- logger.warning(
- "[SkillActiveStateRail] skill_complete(%s) ignored: active is "
- "'%s' session=%s (complete only clears on name match)",
- skill_name,
- state.active_skill,
- session_id,
- )
- return
-
- if tool_name != "skill_tool":
- return
-
- meta = getattr(tool_msg, "metadata", None) or {}
- if meta.get("is_directory_listing"):
- return
- skill_name = (meta.get("skill_name") or _get_arg(tool_call, "skill_name", "") or "").strip()
- if not skill_name:
- return
- prior_skill = state.active_skill
- if prior_skill and prior_skill != skill_name:
- # 切换到另一个 skill:旧 active_skill 在此清空(被新技能替换)。
+ state.active_skill = skill_name
+ # 本轮有 skill_tool 调用,过期计数清零。
+ state.invokes_since_skill_tool = 0
+ if session_id == _DEFAULT_SESSION_ID:
+ # Attribution for later adopt; never claim a foreign session.
+ state.source_session = self._owner_hint_for_default(ctx)
+ else:
+ state.source_session = None
logger.info(
- "[SkillActiveStateRail] switch active '%s' -> '%s' session=%s",
- prior_skill,
+ "[SkillActiveStateRail] activated '%s' session=%s source_session=%s",
skill_name,
session_id,
+ state.source_session or "-",
)
- state.active_skill = skill_name
- # 本轮有 skill_tool 调用,过期计数清零。
- state.invokes_since_skill_tool = 0
- if session_id == _DEFAULT_SESSION_ID:
- # Attribution for later adopt; never claim a foreign session.
- state.source_session = self._owner_hint_for_default(ctx)
- else:
- state.source_session = None
- # Drop a stale default entry so injection never reads the wrong key.
- _drop_session_state(_DEFAULT_SESSION_ID)
- logger.info(
- "[SkillActiveStateRail] activated '%s' session=%s source_session=%s",
- skill_name,
- session_id,
- state.source_session or "-",
- )
+
+ _update_state(session_id, apply)
__all__ = [
diff --git a/jiuwenswarm/agents/harness/common/rails/skill_authorization_rail.py b/jiuwenswarm/agents/harness/common/rails/skill_authorization_rail.py
index 839e480bc5..e9eca9283f 100644
--- a/jiuwenswarm/agents/harness/common/rails/skill_authorization_rail.py
+++ b/jiuwenswarm/agents/harness/common/rails/skill_authorization_rail.py
@@ -2,6 +2,8 @@
"""Expose the skill gate's scope resolution to the permission rail."""
+import portalocker
+from openjiuwen.core.runner.callback.errors import AbortError
from openjiuwen.core.single_agent.rail.base import AgentCallbackContext
from openjiuwen.harness.rails.skills.skill_authorization_rail import (
SkillAuthorizationRail as CoreSkillAuthorizationRail,
@@ -14,3 +16,39 @@ class SkillAuthorizationRail(CoreSkillAuthorizationRail):
def resolve_scope(self, ctx: AgentCallbackContext) -> tuple[str, str] | None:
"""Reuse the gate's scope resolution without changing authorization rules."""
return self._resolve_scope(ctx)
+
+ def set_sessions_root(self, sessions_root) -> None:
+ """Carry trusted tenant identity across supervisor/checkpoint tasks."""
+ self._sessions_root = sessions_root
+
+ def _bind_session_files(self, ctx, *, sync_policy: bool = True) -> None:
+ from jiuwenswarm.agents.harness.common.rails.permissions.skill_authorization.file_store import (
+ bind_session_file_context,
+ )
+
+ scope = self.resolve_scope(ctx)
+ root = getattr(self, "_sessions_root", None)
+ if scope is not None and root is not None:
+ bind_session_file_context(scope[0], root)
+ sync = getattr(self.store, "sync_feature_state", None)
+ enabled = self._feature_enabled()
+ # Rebind identity after the tool, without a second unchanged-policy
+ # transaction. A policy disabled during the call still retires it.
+ if callable(sync) and (sync_policy or not enabled):
+ try:
+ sync(scope[0], enabled=enabled)
+ except (
+ OSError, ValueError, TypeError, RuntimeError,
+ portalocker.exceptions.LockException,
+ ) as exc:
+ raise AbortError(
+ "Skill authorization storage unavailable; retry the request"
+ ) from exc
+
+ async def before_tool_call(self, ctx):
+ self._bind_session_files(ctx)
+ return await super().before_tool_call(ctx)
+
+ async def after_tool_call(self, ctx):
+ self._bind_session_files(ctx, sync_policy=False)
+ return await super().after_tool_call(ctx)
diff --git a/jiuwenswarm/agents/harness/common/rails/subagent_permission_rail.py b/jiuwenswarm/agents/harness/common/rails/subagent_permission_rail.py
index 6e82d58ff0..ad3198d1f8 100644
--- a/jiuwenswarm/agents/harness/common/rails/subagent_permission_rail.py
+++ b/jiuwenswarm/agents/harness/common/rails/subagent_permission_rail.py
@@ -240,11 +240,16 @@ class SubagentPermissionRail(ConfirmInterruptRail):
self._approval_timeout = approval_timeout
self._config_provider = config_provider or get_effective_permissions_config
self._approval_session_id = (session_id or "").strip()
+ self._sessions_root: Path | None = None
if workspace_root is None and engine is not None:
workspace_root = getattr(engine, "_workspace_root", None)
self._workspace_root = Path(workspace_root) if workspace_root else None
self._rejected_call_fingerprints: set[str] = set()
+ def set_sessions_root(self, sessions_root: Path) -> None:
+ """Keep only trusted parent identity across child callback tasks."""
+ self._sessions_root = sessions_root
+
def _resolve_scope(self, ctx: AgentCallbackContext) -> tuple[str, str] | None:
return _resolve_subagent_scope(
ctx,
@@ -365,6 +370,12 @@ class SubagentPermissionRail(ConfirmInterruptRail):
if scope is None:
return
session_id, agent_scope_id = scope
+ if self._sessions_root is not None:
+ from jiuwenswarm.agents.harness.common.rails.permissions.skill_authorization.file_store import (
+ bind_session_file_context,
+ )
+
+ bind_session_file_context(session_id, self._sessions_root)
active_skill_name = self._grant_store.get_active_skill_execution(
session_id,
agent_scope_id,
diff --git a/jiuwenswarm/agents/harness/common/rails/subagent_skill_authorization_rail.py b/jiuwenswarm/agents/harness/common/rails/subagent_skill_authorization_rail.py
index 2376632f4e..41a4f868ac 100644
--- a/jiuwenswarm/agents/harness/common/rails/subagent_skill_authorization_rail.py
+++ b/jiuwenswarm/agents/harness/common/rails/subagent_skill_authorization_rail.py
@@ -40,7 +40,6 @@ from openjiuwen.harness.security.skill_authorization.subagent_approval_registry
SubagentApprovalRequest,
)
from openjiuwen.harness.rails.skills.skill_authorization_rail import (
- SkillAuthorizationRail,
_SkillApprovalCall,
_parse_answer_to_action,
_resolve_session_id,
@@ -50,6 +49,10 @@ from openjiuwen.harness.rails.skills.skill_lifecycle_events import (
is_root_skill_load,
is_skill_complete,
)
+
+from jiuwenswarm.agents.harness.common.rails.skill_authorization_rail import (
+ SkillAuthorizationRail,
+)
from jiuwenswarm.agents.harness.common.tools.subagent_executor.context_vars import (
get_subagent_parent_session,
)
@@ -392,6 +395,7 @@ class SubagentSkillAuthorizationRail(SkillAuthorizationRail):
self._create_pending_grant_quiet(
session_id, agent_scope_id, current_manifest, tool_call_id,
decision=GrantDecision.LOCAL, log_tag="subagent.skill.grant_create_failed",
+ authorization_generation=authorization_generation,
)
self._proceed_tool_call(ctx, tool_call, tool_name)
diff --git a/jiuwenswarm/agents/harness/common/tools/subagent_executor/authorization.py b/jiuwenswarm/agents/harness/common/tools/subagent_executor/authorization.py
index f15e6b498b..690b1e98d9 100644
--- a/jiuwenswarm/agents/harness/common/tools/subagent_executor/authorization.py
+++ b/jiuwenswarm/agents/harness/common/tools/subagent_executor/authorization.py
@@ -246,6 +246,19 @@ def build_subagent_authorization_rails(
workspace_root=workspace_root,
config_provider=effective_config_provider,
)
+ from openjiuwen.harness.security.skill_authorization import (
+ get_skill_grant_store,
+ )
+
+ from jiuwenswarm.agents.harness.common.rails.permissions.skill_authorization.file_store import (
+ FileSkillGrantStore,
+ )
+
+ store = get_skill_grant_store()
+ if isinstance(store, FileSkillGrantStore):
+ sessions_root = store.sessions_root()
+ gate_rail.set_sessions_root(sessions_root)
+ permission_rail.set_sessions_root(sessions_root)
except Exception: # noqa: BLE001
logger.warning(
"[skill_authorization] subagent wiring rail pair build failed scope=%s",
diff --git a/jiuwenswarm/gateway/channel_manager/web/app_web_handlers.py b/jiuwenswarm/gateway/channel_manager/web/app_web_handlers.py
index 4b3f7cba6f..99d23b0434 100644
--- a/jiuwenswarm/gateway/channel_manager/web/app_web_handlers.py
+++ b/jiuwenswarm/gateway/channel_manager/web/app_web_handlers.py
@@ -4062,6 +4062,14 @@ def _register_web_handlers(bind: WebHandlersBindParams) -> None:
)
return
session_id_to_delete = session_id_to_delete.strip()
+ # Match chat/session.list tenant identity when removing shared session
+ # files. Params supplied by the caller must not override connection scope.
+ delete_group, delete_bot = _ws_identity_scope(ws)
+ delete_routing = {
+ key: value for key, value in (("group_id", delete_group), ("bot_id", delete_bot))
+ if value
+ }
+ delete_metadata = {"routing": delete_routing} if delete_routing else None
from jiuwenswarm.gateway.routing.session_index import is_remote_storage
@@ -4084,6 +4092,7 @@ def _register_web_handlers(bind: WebHandlersBindParams) -> None:
req_method=ReqMethod.SESSION_DELETE,
params=params,
user_id=user_id,
+ metadata=delete_metadata,
)
resp = await ac.send_request(env)
if not resp.ok:
@@ -4194,6 +4203,7 @@ def _register_web_handlers(bind: WebHandlersBindParams) -> None:
req_method=ReqMethod.SESSION_DELETE,
params=params,
user_id=user_id,
+ metadata=delete_metadata,
)
resp = await ac.send_request(env)
if resp.ok:
diff --git a/jiuwenswarm/server/agent_ws_server.py b/jiuwenswarm/server/agent_ws_server.py
index e02b46cce8..fbb81ecd95 100644
--- a/jiuwenswarm/server/agent_ws_server.py
+++ b/jiuwenswarm/server/agent_ws_server.py
@@ -556,6 +556,13 @@ class AgentWebSocketServer:
logger.warning("[AgentWebSocketServer] 服务端已在运行")
return
+ # Install shared Skill state before prewarm or any request creates rails.
+ from jiuwenswarm.agents.harness.common.rails.permissions.skill_authorization.file_store import (
+ configure_shared_skill_authorization,
+ )
+
+ configure_shared_skill_authorization(get_config())
+
# Reset harness package state to native on service startup
reset_harness_packages_state()
diff --git a/jiuwenswarm/server/handlers/session.py b/jiuwenswarm/server/handlers/session.py
index 9d24d61675..8f623912aa 100644
--- a/jiuwenswarm/server/handlers/session.py
+++ b/jiuwenswarm/server/handlers/session.py
@@ -450,14 +450,14 @@ async def handle_session_delete(ctx: RequestContext) -> None:
target, sessions_root=sessions_root
)
if session_dir is not None:
- # 合法的永久删除请求首先回收进程内授权。即使会话目录已被外部删除
+ # 合法的永久删除请求首先回收会话授权文件。即使会话目录已被外部删除
# 或随后文件删除失败,也不能让 ACTIVE/PENDING Grant 继续存活。
try:
from jiuwenswarm.agents.harness.common.rails.permissions.skill_authorization.runtime import (
clear_deleted_session,
)
- clear_deleted_session(target)
+ clear_deleted_session(target, sessions_root=sessions_root)
except Exception: # noqa: BLE001 — Grant 回收失败不掩盖原删除结果
logger.warning(
"[AgentWebSocketServer] session.delete skill grant cleanup failed: "
diff --git a/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py b/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py
index c66df2ebe8..4fb86726e9 100644
--- a/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py
+++ b/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py
@@ -3085,7 +3085,7 @@ class JiuWenSwarmDeepAdapter:
self._session_adapter_last_used.pop(session_id, None)
self._session_adapter_versions.pop(session_id, None)
self._session_adapter_reload_failures.pop(session_id, None)
- clear_session_skill_state(session_id)
+ clear_session_skill_state(session_id, local_only=True)
self._forget_skill_sleep_session(session_id, adapter)
if not remove_runtime_state:
return
@@ -8508,12 +8508,21 @@ class JiuWenSwarmDeepAdapter:
self, config: dict[str, Any] | None = None
) -> SkillActiveStateRail | None:
try:
+ from jiuwenswarm.common.utils import get_agent_sessions_dir
+ from jiuwenswarm.server.runtime.tenant_context import get_bound_agent_root
+
+ if get_bound_agent_root() is not None:
+ sessions_root = get_agent_sessions_dir()
+ else:
+ # Prewarm/standalone callers may have no bound filesystem paths.
+ sessions_root = Path(self._workspace_dir).parent / "sessions"
# CR-3b:react.skill_stale_invoke_limit 可配置(缺失用默认 5,
# <=0 禁用兜底),否则生产装配点恒为默认值不可调。
stale_invoke_limit = resolve_stale_invoke_limit(config)
rail = SkillActiveStateRail(
session_id=self._skill_rail_session_id(),
stale_invoke_limit=stale_invoke_limit,
+ sessions_root=sessions_root,
)
display_limit = (
stale_invoke_limit
@@ -10607,7 +10616,7 @@ class JiuWenSwarmDeepAdapter:
context_engine_config=_deep_agent_context_engine_config(config),
kv_cache_affinity_config=_deep_agent_kv_cache_affinity_config(config, model),
enable_task_loop=self._resolve_enable_task_loop(config, config_base),
- max_iterations=config.get("max_iterations", 15),
+ max_iterations=parse_int(config.get("max_iterations"), 15),
subagents=configured_subagents,
add_general_purpose_agent=should_add_general_agent,
tools=normalized_tool_cards,
@@ -11613,7 +11622,7 @@ class JiuWenSwarmDeepAdapter:
rails=rails_list if rails_list else [],
enable_task_loop=self._resolve_enable_task_loop(config, config_base),
add_general_purpose_agent=should_enable_general_agent,
- max_iterations=config.get("max_iterations", 15),
+ max_iterations=parse_int(config.get("max_iterations"), 15),
workspace=self._build_agent_workspace(),
sys_operation=sys_operation,
language=self._resolve_runtime_language(),
@@ -13070,6 +13079,16 @@ class JiuWenSwarmDeepAdapter:
runtime_config: Per-request runtime parameters for this turn.
stage_timer: Timer marked at each stage boundary.
"""
+ # Request tenant bindings do not survive the supervisor round task.
+ # Carry only the trusted session path, never cached authorization data.
+ from jiuwenswarm.common.utils import get_agent_sessions_dir
+
+ sessions_root = get_agent_sessions_dir()
+ for rail_name in ("_skill_active_state_rail", "_skill_authorization_rail"):
+ rail = getattr(self, rail_name, None)
+ if rail is not None:
+ rail.set_sessions_root(sessions_root)
+
task_workspace = (
runtime_config.workspace
or runtime_config.project_dir
@@ -15352,7 +15371,7 @@ class JiuWenSwarmDeepAdapter:
self._parent_session_id,
exc,
)
- clear_session_skill_state(str(self._parent_session_id or "").strip())
+ clear_session_skill_state(str(self._parent_session_id or "").strip(), local_only=True)
self._forget_skill_sleep_session(str(self._parent_session_id or "").strip())
try:
await self._sync_personal_context_rail("cleanup")
@@ -16074,8 +16093,8 @@ class JiuWenSwarmDeepAdapter:
return
await self._halt_deep_agent_execution(intent)
- @staticmethod
def _revoke_main_skill_authorization(
+ self,
session_id: str | None,
*,
reason: str,
@@ -16086,7 +16105,9 @@ class JiuWenSwarmDeepAdapter:
revoke_main_scope,
)
- revoke_main_scope(session_id, reason=reason)
+ rail = getattr(self, "_skill_active_state_rail", None)
+ root = rail.sessions_root if rail is not None else None
+ revoke_main_scope(session_id, reason=reason, sessions_root=root)
except Exception: # noqa: BLE001 — 不影响原取消/异常流程
logger.warning(
"[JiuWenSwarmDeepAdapter] dynamic authorization cleanup failed",
diff --git a/jiuwenswarm/server/runtime/agent_adapter/sysop_builder.py b/jiuwenswarm/server/runtime/agent_adapter/sysop_builder.py
index be7761dca8..cbc4f98cdd 100644
--- a/jiuwenswarm/server/runtime/agent_adapter/sysop_builder.py
+++ b/jiuwenswarm/server/runtime/agent_adapter/sysop_builder.py
@@ -355,6 +355,35 @@ def _merge_yuanrong_mounts(
return merged
+def _skill_state_paths(shared_root: Path | None) -> list[Path]:
+ from jiuwenswarm.common.utils import get_agent_sessions_dir, get_user_workspace_dir
+
+ paths = [get_agent_sessions_dir(), get_user_workspace_dir() / ".skill_authorization"]
+ if shared_root is not None:
+ paths.extend([shared_root / "sessions", shared_root / "agent" / "sessions"])
+ return paths
+
+
+def _protect_yuanrong_skill_state(mounts: list[dict[str, Any]], agent_root: Path) -> list[dict[str, Any]]:
+ """Keep service state read-only beneath writable workspace mounts."""
+ protected = _skill_state_paths(agent_root)
+ for mount in mounts:
+ if mount.get("readonly"):
+ continue
+ source = Path(mount["source"]).expanduser().resolve()
+ target = Path(mount["target"]).expanduser()
+ if any(source == path.resolve() or path.resolve() in source.parents for path in protected):
+ raise ValueError("yuanrong mount cannot override service-owned session state")
+ if source != target and any(source in path.resolve().parents for path in protected):
+ raise ValueError("yuanrong mount cannot alias service-owned session state")
+ result = list(mounts)
+ for path in protected:
+ path.mkdir(parents=True, exist_ok=True)
+ resolved = str(path.resolve())
+ result.append({"source": resolved, "target": resolved, "readonly": True})
+ return result
+
+
def _build_yuanrong_extra_params() -> dict[str, Any]:
"""Assemble yuanrong provider extra_params; always identity-mount agent_root."""
endpoint = get_sandbox_endpoint()
@@ -375,7 +404,9 @@ def _build_yuanrong_extra_params() -> dict[str, Any]:
extra_params: dict[str, Any] = {
"executor": executor,
- "mounts": _merge_yuanrong_mounts(agent_root_mount, config_mounts),
+ "mounts": _protect_yuanrong_skill_state(
+ _merge_yuanrong_mounts(agent_root_mount, config_mounts), agent_root
+ ),
}
workdir = endpoint.get("workdir")
@@ -392,9 +423,12 @@ def _build_yuanrong_extra_params() -> dict[str, Any]:
if isinstance(value, dict):
rootfs = dict(value)
existing = rootfs.get("mounts")
- rootfs["mounts"] = _merge_yuanrong_mounts(
- agent_root_mount,
- existing if isinstance(existing, list) else None,
+ rootfs["mounts"] = _protect_yuanrong_skill_state(
+ _merge_yuanrong_mounts(
+ agent_root_mount,
+ existing if isinstance(existing, list) else None,
+ ),
+ agent_root,
)
if "workdir" not in rootfs or not str(rootfs.get("workdir") or "").strip():
rootfs["workdir"] = extra_params["workdir"]
@@ -565,6 +599,20 @@ def build_filesystem_policy(
config_str = str(config_path)
_record_ro_resource_bind(config_str, config_str)
+ # Session metadata is service-owned. A writable tenant/project parent must
+ # never let a tool edit, rename or remove Skill authorization files.
+ # Cover both default agent roots and explicit enterprise tenant roots.
+ protected_paths = _skill_state_paths(resolved_workspace)
+ if resolved_project is not None and any(
+ resolved_project == path.resolve() or path.resolve() in resolved_project.parents
+ for path in protected_paths
+ ):
+ raise ValueError("project_dir cannot be a service-owned session directory")
+ for protected in protected_paths:
+ protected.mkdir(parents=True, exist_ok=True)
+ protected_str = str(protected.resolve())
+ _record_ro_resource_bind(protected_str, protected_str)
+
for entry in files_runtime.get("allow") or []:
normalized = _normalize_fs_entry(entry)
if normalized is None:
@@ -576,6 +624,15 @@ def build_filesystem_policy(
raise FileNotFoundError(
f"sandbox files.allow path does not exist on host: {path!r}"
)
+ resolved_host = host.resolve()
+ if resolved_host != host and any(
+ resolved_host == protected.resolve() or resolved_host in protected.resolve().parents
+ for protected in protected_paths
+ ):
+ raise ValueError("sandbox files.allow cannot alias service-owned session state")
+ if any(resolved_host == protected.resolve() or protected.resolve() in resolved_host.parents
+ for protected in protected_paths):
+ raise ValueError("sandbox files.allow cannot override service-owned session state")
_record_rw_bind(
path,
path,
diff --git a/tests/unit_tests/agentserver/test_file_skill_grant_store.py b/tests/unit_tests/agentserver/test_file_skill_grant_store.py
new file mode 100644
index 0000000000..955fea0c5f
--- /dev/null
+++ b/tests/unit_tests/agentserver/test_file_skill_grant_store.py
@@ -0,0 +1,662 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
+"""Session files preserve full authorization across processes without a cache."""
+
+import json
+import multiprocessing
+import os
+import shutil
+import threading
+from concurrent.futures import ThreadPoolExecutor
+from dataclasses import replace
+
+import pytest
+from openjiuwen.harness.security.skill_authorization import (
+ GrantDecision,
+ GrantStatus,
+ SkillGrantStore,
+ SkillManifest,
+ SkillTrustLevel,
+ get_skill_grant_store,
+ set_skill_grant_store,
+)
+
+from jiuwenswarm.agents.harness.common.rails import skill_active_state
+from jiuwenswarm.agents.harness.common.rails.permissions.skill_authorization.file_store import (
+ FileSkillGrantStore,
+ configure_shared_skill_authorization,
+)
+
+
+def stores(tmp_path):
+ sessions = tmp_path / "sessions"
+ (sessions / "session").mkdir(parents=True)
+ a, b = [
+ FileSkillGrantStore(sessions_root=lambda: sessions, data_root=lambda: tmp_path)
+ for _ in range(2)
+ ]
+ original = get_skill_grant_store()
+ yield a, b
+ set_skill_grant_store(original)
+
+
+def manifest():
+ return SkillManifest(
+ skill_name="会议预定",
+ source="test",
+ version="1",
+ trust=SkillTrustLevel.OTHER,
+ permissions_hash="permissions",
+ skill_md_hash="body",
+ overlay={"tools": {"esb_system_tool": "allow"}},
+ )
+
+
+def activate(store, manifest, scope="main", decision=GrantDecision.LOCAL):
+ store.create_pending_grant(
+ "session",
+ scope,
+ manifest,
+ decision=decision,
+ approval_tool_call_id="load-1",
+ authorization_generation=store.get_authorization_generation("session"),
+ )
+ assert store.activate_pending(
+ "session", scope, manifest.skill_name, manifest, approval_tool_call_id="load-1"
+ )
+
+
+def test_full_grant_active_state_and_adapter_eviction(stores, manifest):
+ a, b = stores
+ activate(a, manifest)
+ a.update_active_skill_state(
+ "session", lambda _: {"active_skill": manifest.skill_name}
+ )
+ assert b.get_active("session", "main").identity_tuple() == manifest.identity_tuple()
+ assert b.get_active("session", "main").overlay_snapshot == manifest.overlay
+ set_skill_grant_store(b)
+ skill_active_state.clear_session_skill_state("session", local_only=True)
+ assert skill_active_state.get_session_active_skill("session") == manifest.skill_name
+ assert set(vars(a)) == {"sessions_root", "data_root"}
+ assert not hasattr(skill_active_state, "_sessions")
+
+
+def test_session_scope_and_tenant_isolation(stores, manifest, tmp_path):
+ a, b = stores
+ activate(a, manifest)
+ assert b.get_active("other-session", "main") is None
+ assert b.get_active("session", "child") is None
+ other = FileSkillGrantStore(
+ sessions_root=lambda: tmp_path / "other", data_root=lambda: tmp_path
+ )
+ assert other.get_active("session", "main") is None
+
+
[email protected]("mismatch", ["body", "approval"])
+def test_identity_and_approval_binding(stores, manifest, mismatch):
+ a, b = stores
+ a.create_pending_grant(
+ "session",
+ "main",
+ manifest,
+ decision=GrantDecision.LOCAL,
+ approval_tool_call_id="load-1",
+ )
+ checked = (
+ replace(manifest, skill_md_hash="changed") if mismatch == "body" else manifest
+ )
+ assert (
+ b.activate_pending(
+ "session",
+ "main",
+ manifest.skill_name,
+ checked,
+ approval_tool_call_id="wrong" if mismatch == "approval" else "load-1",
+ )
+ is None
+ )
+ assert a.get_active("session", "main") is None
+
+
+def test_revocation_is_seen_by_original_process(stores, manifest):
+ a, b = stores
+ activate(a, manifest)
+ a.update_active_skill_state(
+ "session", lambda _: {"active_skill": manifest.skill_name}
+ )
+ b.revoke_grants("session", "main")
+ assert a.get_active("session", "main") is None
+ assert a.get_active_skill_state("session") is None
+ a.update_active_skill_state(
+ "session", lambda _: {"active_skill": manifest.skill_name}
+ )
+ assert (
+ b.get_active_skill_state("session") is None
+ ) # late callback cannot restore it
+
+
+def test_session_approval_survives_completion_as_inactive(stores, manifest):
+ a, b = stores
+ activate(a, manifest, decision=GrantDecision.SESSION)
+ b.revoke_grants("session", "main")
+ assert (
+ a.get_grant("session", "main", manifest.skill_name).status
+ == GrantStatus.APPROVED_INACTIVE
+ )
+ assert a.get_active("session", "main") is None
+
+
[email protected]("operation", ["cancel", "delete"])
+def test_cleanup_uses_explicit_tenant_root_without_request_context(
+ stores, manifest, tmp_path, monkeypatch, operation
+):
+ from jiuwenswarm.agents.harness.common.rails.permissions.skill_authorization import (
+ runtime,
+ )
+
+ a, _ = stores
+ activate(a, manifest)
+ a.update_active_skill_state(
+ "session", lambda _: {"active_skill": manifest.skill_name}
+ )
+ # The service singleton cannot rely on request ContextVars in cancel callbacks.
+ singleton = FileSkillGrantStore(
+ sessions_root=lambda: tmp_path / "wrong-tenant", data_root=lambda: tmp_path
+ )
+ set_skill_grant_store(singleton)
+ monkeypatch.setattr(runtime, "_enabled", lambda: False)
+ if operation == "cancel":
+ runtime.revoke_main_scope(
+ "session", reason="cancel", sessions_root=a.sessions_root()
+ )
+ else:
+ runtime.clear_deleted_session("session", sessions_root=a.sessions_root())
+ assert a.get_active("session", "main") is None
+ assert a.get_active_skill_state("session") is None
+ assert not (tmp_path / "wrong-tenant").exists()
+
+
[email protected]("remove_directory", [False, True])
+def test_deletion_blocks_late_writes(stores, manifest, remove_directory):
+ a, b = stores
+ activate(a, manifest)
+ b.clear_session("session")
+ if remove_directory:
+ shutil.rmtree(b.session_directory("session"))
+ assert a.get_active("session", "main") is None
+ for operation in [
+ lambda: a.create_pending_grant(
+ "session", "main", manifest, decision=GrantDecision.LOCAL
+ ),
+ lambda: a.update_active_skill_state(
+ "session", lambda _: {"active_skill": manifest.skill_name}
+ ),
+ ]:
+ with pytest.raises(RuntimeError, match="deleted"):
+ operation()
+ a.clear_all()
+ with pytest.raises(RuntimeError, match="deleted"):
+ b.enter_skill_execution("session", "child", manifest.skill_name)
+
+
+def test_feature_disable_invalidates_old_approval(stores, manifest):
+ a, b = stores
+ activate(a, manifest)
+ generation = a.get_authorization_generation("session")
+ b.clear_all()
+ assert a.get_active("session", "main") is None
+ with pytest.raises(RuntimeError, match="pending"):
+ a.create_pending_grant(
+ "session",
+ "main",
+ manifest,
+ decision=GrantDecision.LOCAL,
+ authorization_generation=generation,
+ )
+
+
+def test_recreated_session_rejects_previous_incarnation_approval(stores, manifest):
+ a, _ = stores
+ generation = a.get_authorization_generation("session")
+ path = a.session_directory("session")
+ shutil.rmtree(path)
+ path.mkdir()
+ with pytest.raises(RuntimeError, match="pending"):
+ a.create_pending_grant(
+ "session",
+ "main",
+ manifest,
+ decision=GrantDecision.LOCAL,
+ authorization_generation=generation,
+ )
+
+
+def test_scope_cleanup_and_read_only_operations(stores, manifest):
+ a, b = stores
+ activate(a, manifest)
+ activate(a, manifest, scope="child")
+ b.enter_skill_execution("session", "child", manifest.skill_name)
+ b.clear_scope("session", "child")
+ assert a.get_active("session", "main")
+ assert a.get_active_skill_execution("session", "child") is None
+ path = a.session_directory("session") / ".skill_authorization/state.json"
+ before = path.stat().st_mtime_ns
+ assert b.get_active("session", "main")
+ assert b.list_grants("session")
+ assert path.stat().st_mtime_ns == before
+ b.clear_scope("session", "main")
+ assert a.get_active("session", "main") is None
+
+
+def _count_worker(root):
+ from pathlib import Path
+
+ path = Path(root)
+ store = FileSkillGrantStore(
+ sessions_root=lambda: path / "sessions", data_root=lambda: path
+ )
+ for _ in range(10):
+ store.update_active_skill_state(
+ "session", lambda s: {"count": s.get("count", 0) + 1}
+ )
+
+
+def test_cross_process_file_lock_prevents_lost_updates(stores):
+ a, _ = stores
+ ctx = multiprocessing.get_context("spawn" if os.name == "nt" else "fork")
+ processes = [
+ ctx.Process(target=_count_worker, args=(str(a.data_root()),)) for _ in range(2)
+ ]
+ for process in processes:
+ process.start()
+ for process in processes:
+ process.join(30)
+ assert process.exitcode == 0
+ assert a.get_active_skill_state("session")["count"] == 20
+
+
+def test_concurrent_threads(stores):
+ with ThreadPoolExecutor(max_workers=2) as pool:
+ list(pool.map(lambda store: _count_worker(str(store.data_root())), stores))
+ assert stores[0].get_active_skill_state("session")["count"] == 20
+
+
+def test_independent_sessions_read_concurrently(stores, monkeypatch):
+ from jiuwenswarm.agents.harness.common.rails.permissions.skill_authorization import (
+ file_store,
+ )
+
+ store, _ = stores
+ store.clear_all() # Exercise the shared epoch as well as session locks.
+ session_ids = [f"parallel-{i}" for i in range(10)]
+ for sid in session_ids:
+ (store.sessions_root() / sid).mkdir()
+ store.update_active_skill_state(sid, lambda _: {"active_skill": "probe"})
+ rendezvous = threading.Barrier(len(session_ids))
+ read_json = file_store._read_json
+
+ def concurrent_read(fd, name):
+ if name == "state.json":
+ rendezvous.wait(timeout=3)
+ return read_json(fd, name)
+
+ monkeypatch.setattr(file_store, "_read_json", concurrent_read)
+ with ThreadPoolExecutor(max_workers=len(session_ids)) as pool:
+ results = list(pool.map(store.get_active_skill_state, session_ids))
+ assert all(state == {"active_skill": "probe"} for state in results)
+ assert not file_store._LOCAL_IO_LOCKS # No growing per-session lock cache.
+
+
+def test_epoch_reads_do_not_wait_for_writer_lock(stores):
+ import portalocker
+
+ store, _ = stores
+ store.clear_all()
+ with (store.epoch_directory() / "state.lock").open("a+b") as lock:
+ portalocker.lock(lock, portalocker.LOCK_EX)
+ assert store.read_epoch() == 1
+ portalocker.unlock(lock)
+
+
+def test_epoch_change_during_transaction_rejects_old_result(stores, manifest):
+ a, b = stores
+ activate(a, manifest)
+
+ def invalidate_during_read(store, _doc):
+ result = store.get_active("session", "main")
+ b.clear_all()
+ return result
+
+ with pytest.raises(RuntimeError, match="changed during"):
+ a.operate("session", invalidate_during_read, write=False)
+ assert a.get_active("session", "main") is None
+
+
+ "corruption", ["invalid-json", "bad-grant", "bad-map", "symlink"]
+)
+def test_corruption_never_serves_old_authorization(
+ stores, manifest, tmp_path, corruption
+):
+ a, b = stores
+ activate(a, manifest)
+ path = a.session_directory("session") / ".skill_authorization/state.json"
+ if corruption == "invalid-json":
+ path.write_text("{")
+ elif corruption == "bad-grant":
+ doc = json.loads(path.read_text())
+ doc["grants"]["main"] = [{"unexpected": True}]
+ path.write_text(json.dumps(doc))
+ elif corruption == "bad-map":
+ doc = json.loads(path.read_text())
+ doc["grants"] = []
+ path.write_text(json.dumps(doc))
+ else:
+ replacement = tmp_path / "forged"
+ replacement.write_text(path.read_text())
+ path.unlink()
+ path.symlink_to(replacement)
+ assert b.get_active("session", "main") is None
+ assert b.get_active_skill_state("session") is None
+
+
+def test_startup_installs_files_without_redis_configuration(monkeypatch):
+ original = get_skill_grant_store()
+ try:
+ set_skill_grant_store(SkillGrantStore())
+ store = configure_shared_skill_authorization({})
+ assert isinstance(store, FileSkillGrantStore)
+ assert configure_shared_skill_authorization({}) is store
+ finally:
+ set_skill_grant_store(original)
+
+
[email protected](os.name == "nt", reason="POSIX permits unlinking open files")
+def test_deleted_during_transaction_cannot_recreate_directory(stores):
+ a, b = stores
+ a.update_active_skill_state("session", lambda _: {"active_skill": "before"})
+ directory = a.session_directory("session")
+
+ def delete_while_updating(_state):
+ shutil.rmtree(directory)
+ return {"active_skill": "late"}
+
+ with pytest.raises(OSError):
+ a.update_active_skill_state("session", delete_while_updating)
+ assert not directory.exists()
+ assert b.get_active_skill_state("session") is None
+
+
[email protected](os.name != "nt", reason="Windows protects open lock handles")
+def test_windows_transaction_prevents_directory_deletion(stores):
+ a, b = stores
+ a.update_active_skill_state("session", lambda _: {"active_skill": "before"})
+ directory = a.session_directory("session")
+
+ def delete_while_updating(_state):
+ with pytest.raises(PermissionError):
+ shutil.rmtree(directory)
+ return {"active_skill": "after"}
+
+ a.update_active_skill_state("session", delete_while_updating)
+ assert b.get_active_skill_state("session")["active_skill"] == "after"
+ shutil.rmtree(directory)
+ assert b.get_active_skill_state("session") is None
+
+
+def test_bounded_lock_wait_never_serves_cached_state(stores, manifest):
+ import time
+
+ import portalocker
+
+ from jiuwenswarm.agents.harness.common.rails.permissions.skill_authorization.file_store import (
+ _LOCK_TIMEOUT,
+ )
+
+ a, b = stores
+ activate(a, manifest)
+ path = a.session_directory("session") / ".skill_authorization/state.lock"
+ with path.open("a+b") as lock:
+ portalocker.lock(lock, portalocker.LOCK_EX)
+ started = time.monotonic()
+ assert b.get_active("session", "main") is None
+ elapsed = time.monotonic() - started
+ assert _LOCK_TIMEOUT <= elapsed < 1
+ portalocker.unlock(lock)
+ assert a.get_active("session", "main")
+
+
+def test_portable_path_based_atomic_io(tmp_path):
+ from jiuwenswarm.agents.harness.common.rails.permissions.skill_authorization.file_store import (
+ _atomic_json,
+ _read_json,
+ )
+
+ _atomic_json(tmp_path, "state.json", {"value": "会话"})
+ assert _read_json(tmp_path, "state.json")[0] == {"value": "会话"}
+ linked = tmp_path / "link.json"
+ linked.symlink_to(tmp_path / "state.json")
+ with pytest.raises(ValueError):
+ _read_json(tmp_path, "link.json")
+
+
+def test_cold_disabled_pod_retires_persisted_state_and_old_approval(stores, manifest):
+ a, b = stores
+ a.sync_feature_state("session", enabled=True)
+ activate(a, manifest)
+ old_generation = a.get_authorization_generation("session")
+ a.update_active_skill_state(
+ "session", lambda _: {"active_skill": manifest.skill_name}
+ )
+ b.sync_feature_state("session", enabled=False)
+ assert a.get_active("session", "main") is None
+ assert a.get_active_skill_state("session") is None
+ b.sync_feature_state("session", enabled=True)
+ assert a.get_active("session", "main") is None
+ with pytest.raises(RuntimeError, match="pending"):
+ a.create_pending_grant(
+ "session",
+ "main",
+ manifest,
+ decision=GrantDecision.LOCAL,
+ authorization_generation=old_generation,
+ )
+
+
[email protected]("error", [OSError, ValueError, TypeError, RuntimeError, TimeoutError])
+def test_generation_read_errors_abort_instead_of_returning_a_comparable_value(
+ stores, monkeypatch, error,
+):
+ from openjiuwen.core.runner.callback.errors import AbortError
+
+ from jiuwenswarm.agents.harness.common.rails.permissions.skill_authorization import (
+ file_store,
+ )
+
+ store, _ = stores
+ token = file_store._session_file_context.set(("session", store.sessions_root()))
+
+ def unavailable(_sid):
+ raise error("unavailable")
+
+ monkeypatch.setattr(store, "get_authorization_generation", unavailable)
+ try:
+ with pytest.raises(AbortError, match="version unavailable"):
+ _ = store.authorization_generation
+ finally:
+ file_store._session_file_context.reset(token)
+
+
[email protected]("change", ["allow", "reject", "delete", "recreate", "corrupt", "lock"])
+async def test_child_tool_approval_cannot_execute_after_session_storage_changes(
+ stores, manifest, monkeypatch, change,
+):
+ from contextlib import ExitStack
+ from types import SimpleNamespace
+
+ import portalocker
+ from openjiuwen.core.runner.callback.errors import AbortError
+ from openjiuwen.core.runner.callback.framework import AsyncCallbackFramework
+ from openjiuwen.core.single_agent.rail.base import ToolCallInputs
+
+ from jiuwenswarm.agents.harness.common.rails import subagent_permission_rail
+ from jiuwenswarm.agents.harness.common.rails.permissions.skill_authorization import (
+ file_store,
+ )
+
+ store, _ = stores
+ set_skill_grant_store(store)
+ store.enter_skill_execution("session", "child", manifest.skill_name)
+ token = file_store._session_file_context.set(None) # Child task lost parent ContextVars.
+ directory = store.session_directory("session")
+ policy = {"enabled": True, "defaults": {"*": "ask"},
+ "skill_authorization": {"enabled": True}}
+ monkeypatch.setattr(
+ subagent_permission_rail, "merge_session_permissions_overlay", lambda base, **kw: base,
+ )
+ with ExitStack() as resources:
+ async def answer(**_kwargs):
+ if change in {"delete", "recreate"}:
+ shutil.rmtree(directory)
+ if change == "recreate":
+ directory.mkdir()
+ store.enter_skill_execution("session", "child", manifest.skill_name)
+ elif change == "corrupt":
+ (directory / ".skill_authorization/state.json").write_text("{")
+ elif change == "lock":
+ lock = resources.enter_context((directory / ".skill_authorization/state.lock").open("a+b"))
+ portalocker.lock(lock, portalocker.LOCK_EX)
+ return {"selected_options": ["不允许" if change == "reject" else "本次允许"]}
+
+ async def sender(*_args, **_kwargs):
+ pass
+
+ rail = subagent_permission_rail.SubagentPermissionRail(
+ agent_scope_id="child", session_id="session", grant_store=store,
+ approval_registry=SimpleNamespace(request=answer), approval_sender=sender,
+ config_provider=lambda: policy,
+ )
+ rail.set_sessions_root(store.sessions_root())
+ tool = SimpleNamespace(id="approval-call", name="probe", arguments={})
+ ctx = SimpleNamespace(inputs=ToolCallInputs(
+ tool_call=tool, tool_name="probe", tool_args={}, tool_result=None, tool_msg=None,
+ ), extra={})
+ callbacks = AsyncCallbackFramework(enable_logging=False)
+ await callbacks.register("before_tool", rail.before_tool_call)
+ try:
+ if change in {"delete", "corrupt", "lock"}:
+ with pytest.raises(AbortError, match="version unavailable"):
+ await callbacks.trigger("before_tool", ctx)
+ else:
+ await callbacks.trigger("before_tool", ctx)
+ assert bool(ctx.extra.get("_skip_tool")) == (change != "allow")
+ assert "_interrupt_decision" in ctx.extra
+ finally:
+ file_store._session_file_context.reset(token)
+
+
+async def test_child_wiring_binds_parent_files_without_inherited_context(stores):
+ from types import SimpleNamespace
+
+ from jiuwenswarm.agents.harness.common.rails.permissions.skill_authorization import (
+ file_store,
+ )
+ from jiuwenswarm.agents.harness.common.tools.subagent_executor.authorization import (
+ build_subagent_authorization_rails,
+ )
+
+ store, _ = stores
+ set_skill_grant_store(store)
+ token = file_store._session_file_context.set(None)
+ try:
+ rails = build_subagent_authorization_rails(
+ "child", "session", config_provider=lambda: {
+ "enabled": True, "skill_authorization": {"enabled": True},
+ },
+ )
+ assert len(rails) == 2
+ ctx = SimpleNamespace(inputs=SimpleNamespace(tool_name="probe"), extra={})
+ for rail in rails:
+ file_store.clear_session_file_context()
+ await rail.before_tool_call(ctx)
+ assert file_store._session_file_context.get() == ("session", store.sessions_root())
+ first = store.authorization_generation
+ assert first == store.authorization_generation != 0
+ assert (store.session_directory("session") / ".skill_authorization/state.json").is_file()
+ finally:
+ file_store._session_file_context.reset(token)
+
+
[email protected]("change", ["allow", "delete", "corrupt", "recreate"])
+async def test_child_skill_approval_rechecks_persisted_session_version(
+ stores, manifest, monkeypatch, change,
+):
+ from types import SimpleNamespace
+
+ from openjiuwen.core.runner.callback.errors import AbortError
+ from openjiuwen.core.runner.callback.framework import AsyncCallbackFramework
+ from openjiuwen.core.single_agent.rail.base import ToolCallInputs
+ from openjiuwen.harness.rails.skills.skill_authorization_rail import (
+ _SkillApprovalCall,
+ )
+ from openjiuwen.harness.security.skill_authorization import SkillPermissionDiff
+
+ from jiuwenswarm.agents.harness.common.rails.permissions.skill_authorization import (
+ file_store,
+ )
+ from jiuwenswarm.agents.harness.common.rails.subagent_skill_authorization_rail import (
+ SubagentSkillAuthorizationRail,
+ )
+
+ store, _ = stores
+ set_skill_grant_store(store)
+ token = file_store._session_file_context.set(("session", store.sessions_root()))
+ directory = store.session_directory("session")
+
+ async def answer(**_kwargs):
+ if change in {"delete", "recreate"}:
+ shutil.rmtree(directory)
+ if change == "recreate":
+ directory.mkdir()
+ elif change == "corrupt":
+ (directory / ".skill_authorization/state.json").write_text("{")
+ return {"action": "approve_once"}
+
+ async def sender(*_args, **_kwargs):
+ pass
+
+ rail = SubagentSkillAuthorizationRail(
+ agent_scope_id="child", session_id="session", grant_store=store,
+ approval_registry=SimpleNamespace(request=answer), approval_sender=sender,
+ config_provider=lambda: {"enabled": True, "skill_authorization": {"enabled": True}},
+ )
+ monkeypatch.setattr(rail, "_resolve_manifest_for_call", lambda _name: manifest)
+ tool = SimpleNamespace(id="skill-call", name="skill_tool", arguments={})
+ ctx = SimpleNamespace(inputs=ToolCallInputs(
+ tool_call=tool, tool_name="skill_tool", tool_args={}, tool_result=None, tool_msg=None,
+ ), extra={})
+ try:
+ call = _SkillApprovalCall(
+ ctx=ctx, tool_call=tool, tool_name="skill_tool", tool_call_id="skill-call",
+ session_id="session", agent_scope_id="child", manifest=manifest,
+ diff=SkillPermissionDiff(), authorization_generation=store.authorization_generation,
+ )
+
+ async def approve(_ctx):
+ await rail._run_approval_flow(call)
+
+ callbacks = AsyncCallbackFramework(enable_logging=False)
+ await callbacks.register("before_tool", approve)
+ if change in {"delete", "corrupt"}:
+ with pytest.raises(AbortError, match="version unavailable"):
+ await callbacks.trigger("before_tool", ctx)
+ else:
+ await callbacks.trigger("before_tool", ctx)
+ grant = store.get_grant("session", "child", manifest.skill_name)
+ assert (grant is not None) == (change == "allow")
+ finally:
+ file_store._session_file_context.reset(token)
diff --git a/tests/unit_tests/agentserver/test_progressive_rail_reload.py b/tests/unit_tests/agentserver/test_progressive_rail_reload.py
index 257a9c7932..d9a32360ce 100644
--- a/tests/unit_tests/agentserver/test_progressive_rail_reload.py
+++ b/tests/unit_tests/agentserver/test_progressive_rail_reload.py
@@ -25,6 +25,62 @@ def _rail_plan_adapter() -> JiuWenSwarmDeepAdapter:
return adapter
[email protected]("custom_sessions", [False, True])
+def test_skill_active_state_initial_root_follows_tenant_paths(
+ tmp_path, monkeypatch, custom_sessions
+):
+ from jiuwenswarm.common import path_provider
+ from jiuwenswarm.server.runtime.tenant_context import (
+ bind_tenant_workspace_dirs,
+ reset_tenant_workspace_dirs,
+ )
+
+ workspace = tmp_path / "projects" / "workspace"
+ agent_root = tmp_path / "tenant" / "agent"
+ expected = tmp_path / "shared-sessions" if custom_sessions else agent_root / "sessions"
+ adapter = JiuWenSwarmDeepAdapter(workspace_dir=str(workspace))
+
+ def resolve_path(category, ctx, **_kwargs):
+ assert ctx.bound_agent_root == str(agent_root)
+ return expected if category == path_provider.PathCategory.SESSIONS else None
+
+ provider = SimpleNamespace(resolve_path=resolve_path) if custom_sessions else None
+ monkeypatch.setattr(path_provider, "_provider", provider)
+ tokens = bind_tenant_workspace_dirs(
+ jiuwenclaw_workspace=str(workspace),
+ agent_root=str(agent_root),
+ tenant_root=str(agent_root.parent),
+ )
+ try:
+ rail = adapter._build_skill_active_state_rail()
+ assert rail is not None
+ assert rail.sessions_root == expected
+ assert rail.sessions_root != workspace.parent / "sessions"
+ assert not expected.exists()
+ finally:
+ reset_tenant_workspace_dirs(tokens)
+
+
[email protected]("workspace_key", [None, "prewarm-tenant"])
+def test_skill_active_state_unbound_workspace_keeps_initial_root(
+ tmp_path, monkeypatch, workspace_key
+):
+ from jiuwenswarm.common import path_provider
+ from jiuwenswarm.server.runtime import tenant_context
+
+ workspace = tmp_path / "standalone" / "workspace"
+ adapter = JiuWenSwarmDeepAdapter(workspace_dir=str(workspace))
+ monkeypatch.setattr(path_provider, "_provider", None)
+ monkeypatch.setattr(tenant_context, "get_bound_agent_root", lambda: None)
+ token = tenant_context.bind_workspace_key(workspace_key)
+ try:
+ rail = adapter._build_skill_active_state_rail()
+ assert rail is not None
+ assert rail.sessions_root == workspace.parent / "sessions"
+ finally:
+ tenant_context.reset_workspace_key(token)
+
+
def test_reload_plan_preserves_progressive_rail_when_config_omits_tool_lazy_load():
adapter = _rail_plan_adapter()
old_rail = MagicMock(name="old-progressive-tool-rail")
diff --git a/tests/unit_tests/agentserver/test_skill_active_state.py b/tests/unit_tests/agentserver/test_skill_active_state.py
index 9ad366a7a6..5c30458719 100644
--- a/tests/unit_tests/agentserver/test_skill_active_state.py
+++ b/tests/unit_tests/agentserver/test_skill_active_state.py
@@ -4,8 +4,10 @@
import asyncio
import unittest
+from pathlib import Path
from unittest.mock import MagicMock
+import pytest
from openjiuwen.core.single_agent.rail.base import (
AgentCallbackContext,
InvokeInputs,
@@ -29,6 +31,86 @@ from jiuwenswarm.agents.harness.common.rails.skill_credential_injection_rail imp
)
[email protected](autouse=True)
+def session_files(tmp_path, monkeypatch):
+ import re
+
+ from jiuwenswarm.agents.harness.common.rails import skill_active_state
+ from jiuwenswarm.agents.harness.common.rails.permissions.skill_authorization import (
+ file_store,
+ )
+
+ context_token = file_store._session_file_context.set(None)
+ sessions = tmp_path / "sessions"
+ # Existing lifecycle cases use these session identifiers as real sessions.
+ for sid in set(re.findall(r'officeclaw_[A-Za-z0-9_]+', Path(__file__).read_text())):
+ (sessions / sid).mkdir(parents=True, exist_ok=True)
+ monkeypatch.setattr(file_store, "get_agent_sessions_dir", lambda: sessions)
+ monkeypatch.setattr(file_store, "get_user_workspace_dir", lambda: tmp_path)
+ token = skill_active_state._current_session_var.set(None)
+ yield
+ skill_active_state._current_session_var.reset(token)
+ file_store._session_file_context.reset(context_token)
+
+
[email protected]("failure", ["timeout", "corruption"])
+async def test_state_write_failure_stops_callback_chain(monkeypatch, failure):
+ from openjiuwen.core.runner.callback.errors import AbortError
+ from openjiuwen.core.runner.callback.framework import AsyncCallbackFramework
+
+ from jiuwenswarm.agents.harness.common.rails import skill_active_state
+
+ sid = "officeclaw_storage_failure"
+ store = skill_active_state._shared_store(sid)
+ store.update_active_skill_state(
+ sid, lambda _: {"active_skill": "old", "invokes_since_skill_tool": 5}
+ )
+ monkeypatch.setattr(skill_active_state, "_shared_store", lambda _sid: store)
+ if failure == "corruption":
+ (store.session_directory(sid) / ".skill_authorization/state.json").write_text("{")
+ else:
+ def fail_write(*_args, **_kwargs):
+ raise TimeoutError("injected lock timeout")
+ monkeypatch.setattr(store, "update_active_skill_state", fail_write)
+
+ rail = SkillActiveStateRail(session_id=sid, sessions_root=store.sessions_root())
+ ctx = AgentCallbackContext(agent=MagicMock())
+ ctx.inputs = InvokeInputs(query="next turn", conversation_id=sid)
+ ctx.extra = {}
+ later_callback = []
+
+ async def use_credentials(_ctx):
+ later_callback.append(True)
+
+ callbacks = AsyncCallbackFramework()
+ await callbacks.register("before_invoke", rail.before_invoke, priority=10)
+ await callbacks.register("before_invoke", use_credentials, priority=0)
+ with pytest.raises(AbortError, match="Skill state storage unavailable"):
+ await callbacks.trigger("before_invoke", ctx)
+ assert not later_callback
+
+
+async def test_missing_session_callback_does_not_recreate_directory(monkeypatch, caplog):
+ import shutil
+
+ from jiuwenswarm.agents.harness.common.rails import skill_active_state
+
+ sid = "officeclaw_missing_session"
+ store = skill_active_state._shared_store(sid)
+ directory = store.session_directory(sid)
+ shutil.rmtree(directory)
+ monkeypatch.setattr(skill_active_state, "_shared_store", lambda _sid: store)
+ rail = SkillActiveStateRail(session_id=sid, sessions_root=store.sessions_root())
+ ctx = AgentCallbackContext(agent=MagicMock())
+ ctx.inputs = InvokeInputs(query="late request", conversation_id=sid)
+ ctx.extra = {}
+ await rail.before_invoke(ctx)
+ assert not directory.exists()
+ assert not [record for record in caplog.records if record.levelno >= 40]
+
+
class TestResolveSkillSessionId(unittest.TestCase):
def _ctx(self, *, conversation_id=None, session_id=None, extra=None):
ctx = AgentCallbackContext(agent=MagicMock())
@@ -524,7 +606,7 @@ class TestAdoptDefaultActiveSkill(unittest.TestCase):
)
ctx.extra = {}
asyncio.run(default_rail.after_tool_call(ctx))
- assert get_session_active_skill(_DEFAULT_SESSION_ID) == "hwocr"
+ assert get_session_active_skill(_DEFAULT_SESSION_ID) is None
return default_rail, ctx
def test_adopt_unowned_orphan_for_hitl_session(self):
@@ -533,8 +615,8 @@ class TestAdoptDefaultActiveSkill(unittest.TestCase):
)
self._activate_under_default()
- assert adopt_default_active_skill("officeclaw_adopt_sess") == "hwocr"
- assert get_session_active_skill("officeclaw_adopt_sess") == "hwocr"
+ assert adopt_default_active_skill("officeclaw_adopt_sess") is None
+ assert get_session_active_skill("officeclaw_adopt_sess") is None
assert get_session_active_skill(_DEFAULT_SESSION_ID) is None
def test_inject_does_not_adopt_default_orphan(self):
@@ -555,23 +637,15 @@ class TestAdoptDefaultActiveSkill(unittest.TestCase):
bash_ctx.extra = {}
asyncio.run(inject.before_tool_call(bash_ctx))
assert "env" not in bash_ctx.inputs.tool_args
- assert get_session_active_skill(_DEFAULT_SESSION_ID) == "hwocr"
+ assert get_session_active_skill(_DEFAULT_SESSION_ID) is None
assert get_session_active_skill("officeclaw_adopt_sess") is None
- def test_refuse_adopt_when_source_session_mismatches(self):
- from jiuwenswarm.agents.harness.common.rails.skill_active_state import (
- _get_or_create_state,
- adopt_default_active_skill,
- )
+ def test_no_process_local_orphan_state(self):
+ from jiuwenswarm.agents.harness.common.rails import skill_active_state
- state = _get_or_create_state(_DEFAULT_SESSION_ID)
- state.active_skill = "hwocr"
- state.source_session = "officeclaw_adopt_sess"
- assert adopt_default_active_skill("officeclaw_other_sess") is None
- assert get_session_active_skill(_DEFAULT_SESSION_ID) == "hwocr"
- assert adopt_default_active_skill("officeclaw_adopt_sess") == "hwocr"
- assert get_session_active_skill("officeclaw_adopt_sess") == "hwocr"
- assert get_session_active_skill(_DEFAULT_SESSION_ID) is None
+ assert not hasattr(skill_active_state, "_sessions")
+ assert not hasattr(skill_active_state, "_get_or_create_state")
+ assert get_session_active_skill("officeclaw_other_sess") is None
def test_before_invoke_adopts_unowned_orphan(self):
self._activate_under_default()
@@ -583,7 +657,7 @@ class TestAdoptDefaultActiveSkill(unittest.TestCase):
)
invoke_ctx.extra = {}
asyncio.run(rail.before_invoke(invoke_ctx))
- assert get_session_active_skill("officeclaw_adopt_sess") == "hwocr"
+ assert get_session_active_skill("officeclaw_adopt_sess") is None
assert get_session_active_skill(_DEFAULT_SESSION_ID) is None
inject = SkillCredentialInjectionRail(
@@ -600,7 +674,7 @@ class TestAdoptDefaultActiveSkill(unittest.TestCase):
)
bash_ctx.extra = {}
asyncio.run(inject.before_tool_call(bash_ctx))
- assert bash_ctx.inputs.tool_args["env"]["HWOCR_AK"] == "ak"
+ assert "env" not in bash_ctx.inputs.tool_args
if __name__ == "__main__":
diff --git a/tests/unit_tests/agentserver/test_skill_authorization_permission_rail.py b/tests/unit_tests/agentserver/test_skill_authorization_permission_rail.py
index 5f8ee11c3e..0af1bd2c1a 100644
--- a/tests/unit_tests/agentserver/test_skill_authorization_permission_rail.py
+++ b/tests/unit_tests/agentserver/test_skill_authorization_permission_rail.py
@@ -225,6 +225,7 @@ def active_skill_permissions(tmp_path, monkeypatch):
baseline = {
"enabled": True, "schema": "tiered_policy", "defaults": {"*": "ask"},
"tools": {"get_current_user": "ask", "write_file": "ask"},
+ "skill_authorization": {"enabled": True},
}
rail = SkillAuthorizationPermissionRail(config=baseline)
gate = SkillAuthorizationRail(engine=rail._engine, grant_store=store)
@@ -246,6 +247,69 @@ async def test_active_skill_overlay_survives_missing_task_context(active_skill_p
assert rail._static_config == original
+def test_permission_composition_reads_one_snapshot(active_skill_permissions):
+ rail, ctx, store, _, _ = active_skill_permissions
+ with patch.object(store, "get_active", wraps=store.get_active) as read:
+ rail._refresh_permissions_for_tool_call(ctx)
+ read.assert_called_once_with("session-1", "main")
+
+
+ "enabled, disable_after, expected_syncs",
+ [(True, False, 1), (False, False, 2), (True, True, 2)],
+)
+async def test_gate_syncs_policy_without_repeating_enabled_transaction(
+ active_skill_permissions, monkeypatch, enabled, disable_after, expected_syncs,
+):
+ from unittest.mock import Mock
+
+ from jiuwenswarm.agents.harness.common.rails.permissions.skill_authorization.file_store import (
+ clear_session_file_context,
+ )
+ from jiuwenswarm.agents.harness.common.rails.skill_authorization_rail import (
+ SkillAuthorizationRail,
+ )
+
+ _, ctx, store, _, _ = active_skill_permissions
+ store.sync_feature_state = Mock()
+ gate = SkillAuthorizationRail(grant_store=store)
+ gate.set_sessions_root("/trusted/sessions")
+ monkeypatch.setattr(gate, "_feature_enabled", lambda: enabled)
+ try:
+ await gate.before_tool_call(ctx)
+ if disable_after:
+ enabled = False
+ await gate.after_tool_call(ctx)
+ assert store.sync_feature_state.call_count == expected_syncs
+ store.sync_feature_state.assert_called_with("session-1", enabled=enabled)
+ finally:
+ clear_session_file_context()
+
+
+def test_gate_storage_failure_aborts_instead_of_skipping_authorization(
+ active_skill_permissions,
+):
+ from unittest.mock import Mock
+
+ from jiuwenswarm.agents.harness.common.rails.permissions.skill_authorization.file_store import (
+ clear_session_file_context,
+ )
+ from jiuwenswarm.agents.harness.common.rails.skill_authorization_rail import (
+ SkillAuthorizationRail,
+ )
+
+ _, ctx, store, _, _ = active_skill_permissions
+ store.sync_feature_state = Mock(side_effect=TimeoutError("storage unavailable"))
+ gate = SkillAuthorizationRail(grant_store=store)
+ gate.set_sessions_root("/trusted/sessions")
+ try:
+ with pytest.raises(AbortError, match="storage unavailable"):
+ gate._bind_session_files(ctx)
+ finally:
+ clear_session_file_context()
+
+
@pytest.mark.asyncio
async def test_missing_context_cannot_use_another_session_grant(active_skill_permissions):
rail, ctx, _, _, _ = active_skill_permissions
@@ -345,3 +409,15 @@ async def test_owner_allow_cannot_skip_active_skill_overlay(
assert permission == (overlay_permission if session_id == "session-1" else "allow")
finally:
TOOL_PERMISSION_CONTEXT.reset(token)
+
+
+async def test_disabled_policy_does_not_apply_persisted_grant(active_skill_permissions, monkeypatch):
+ rail, ctx, _, _, baseline = active_skill_permissions
+ disabled = copy.deepcopy(baseline)
+ disabled['skill_authorization'] = {'enabled': False}
+ monkeypatch.setattr(rail, '_get_permissions_snapshot', lambda context: disabled)
+ # Parent refresh must also consume the disabled baseline snapshot.
+ monkeypatch.setattr(type(rail).__mro__[1], '_get_permissions_snapshot', lambda self, context: disabled)
+ rail._refresh_permissions_for_tool_call(ctx)
+ assert (await rail._engine.check_permission('get_current_user', {})).permission.value == 'ask'
diff --git a/tests/unit_tests/agentserver/test_skill_required_tool_visibility.py b/tests/unit_tests/agentserver/test_skill_required_tool_visibility.py
index 6447bc2dcf..6e4a9861ab 100644
--- a/tests/unit_tests/agentserver/test_skill_required_tool_visibility.py
+++ b/tests/unit_tests/agentserver/test_skill_required_tool_visibility.py
@@ -2,6 +2,7 @@
"""Regression tests for ToolCard-declared skill-gated tools."""
+from contextvars import ContextVar
from types import SimpleNamespace
from unittest.mock import AsyncMock
from uuid import uuid4
@@ -522,15 +523,34 @@ async def test_matching_active_skill_allows_registered_direct_call() -> None:
@pytest.mark.asyncio
-async def test_adapter_session_activation_exposes_tool_only_in_that_session() -> None:
+async def test_adapter_session_activation_exposes_tool_only_in_that_session(tmp_path, monkeypatch) -> None:
pytest.importorskip("google.genai")
+ from openjiuwen.harness.security.skill_authorization import (
+ get_skill_grant_store,
+ set_skill_grant_store,
+ )
+
+ from jiuwenswarm.agents.harness.common.rails import skill_active_state
+ from jiuwenswarm.agents.harness.common.rails.permissions.skill_authorization import (
+ file_store,
+ )
from jiuwenswarm.server.runtime.agent_adapter.interface_deep import (
JiuWenSwarmDeepAdapter,
)
first_session = "required-skill-first"
second_session = "required-skill-second"
- active_state = SkillActiveStateRail(session_id=first_session)
+ sessions_root = tmp_path / "sessions"
+ for session_id in (first_session, second_session):
+ (sessions_root / session_id).mkdir(parents=True)
+ original_store = get_skill_grant_store()
+ store = file_store.FileSkillGrantStore(
+ sessions_root=lambda: sessions_root, data_root=lambda: tmp_path,
+ )
+ set_skill_grant_store(store)
+ monkeypatch.setattr(file_store, "_session_file_context", ContextVar("test_skill_files", default=None))
+ monkeypatch.setattr(skill_active_state, "_current_session_var", ContextVar("test_active_skill_session", default=None))
+ active_state = SkillActiveStateRail(session_id=first_session, sessions_root=sessions_root)
activation_call = SimpleNamespace(
id="call-skill",
name="skill_tool",
@@ -589,3 +609,4 @@ async def test_adapter_session_activation_exposes_tool_only_in_that_session() ->
finally:
clear_session_skill_state(first_session)
clear_session_skill_state(second_session)
+ set_skill_grant_store(original_store)
diff --git a/tests/unit_tests/agentserver/test_sysop_builder.py b/tests/unit_tests/agentserver/test_sysop_builder.py
index 50a8bc2ec1..7e56f79491 100644
--- a/tests/unit_tests/agentserver/test_sysop_builder.py
+++ b/tests/unit_tests/agentserver/test_sysop_builder.py
@@ -11,3 +11,76 @@ def test_build_process_policy_skips_non_posix_platform(
monkeypatch.delattr(sysop_builder.os, "geteuid", raising=False)
assert sysop_builder.build_process_policy() == {}
+
+
+def test_session_files_readonly_even_without_tenant_context(tmp_path, monkeypatch):
+ from jiuwenswarm.common import utils
+
+ tenant = tmp_path / "tenant"
+ tenant.mkdir()
+ monkeypatch.setattr(
+ utils, "get_agent_sessions_dir", lambda: tmp_path / "unbound" / "sessions"
+ )
+ monkeypatch.setattr(utils, "get_user_workspace_dir", lambda: tmp_path)
+ policy, _ = sysop_builder.build_filesystem_policy({}, shared_dir=tenant)
+ fs = policy["filesystem_policy"]
+ path = str(tenant / "agent" / "sessions")
+ assert path in fs["read_only"]
+ assert {"host_path": path, "sandbox_path": path, "mode": "ro"} in fs["bind_mounts"]
+
+
+def test_session_state_cannot_be_reopened_by_explicit_allow_or_alias(
+ tmp_path, monkeypatch
+):
+ import pytest
+
+ from jiuwenswarm.common import utils
+
+ tenant = tmp_path / "tenant"
+ sessions = tenant / "agent" / "sessions"
+ sessions.mkdir(parents=True)
+ monkeypatch.setattr(utils, "get_agent_sessions_dir", lambda: sessions)
+ monkeypatch.setattr(utils, "get_user_workspace_dir", lambda: tmp_path)
+ with pytest.raises(ValueError, match="override"):
+ sysop_builder.build_filesystem_policy(
+ {"allow": [str(sessions)]}, shared_dir=tenant
+ )
+ alias = tmp_path / "alias"
+ alias.symlink_to(tenant, target_is_directory=True)
+ with pytest.raises(ValueError, match="alias"):
+ sysop_builder.build_filesystem_policy(
+ {"allow": [str(alias)]}, shared_dir=tenant
+ )
+ with pytest.raises(ValueError, match="project_dir"):
+ sysop_builder.build_filesystem_policy(
+ {}, shared_dir=tenant, project_dir=sessions
+ )
+
+
+def test_yuanrong_protects_skill_files_from_workspace_mounts(tmp_path, monkeypatch):
+ import pytest
+
+ from jiuwenswarm.common import utils
+
+ root = tmp_path / "tenant" / "agent"
+ sessions = root / "sessions"
+ root.mkdir(parents=True)
+ monkeypatch.setattr(utils, "get_agent_sessions_dir", lambda: sessions)
+ monkeypatch.setattr(utils, "get_user_workspace_dir", lambda: tmp_path)
+ mounts = [{"source": str(root), "target": str(root), "readonly": False}]
+ result = sysop_builder._protect_yuanrong_skill_state(mounts, root)
+ assert {
+ "source": str(sessions),
+ "target": str(sessions),
+ "readonly": True,
+ } in result
+ with pytest.raises(ValueError, match="alias"):
+ sysop_builder._protect_yuanrong_skill_state(
+ [{"source": str(root), "target": "/writable-alias", "readonly": False}],
+ root,
+ )
+ with pytest.raises(ValueError, match="override"):
+ sysop_builder._protect_yuanrong_skill_state(
+ [{"source": str(sessions), "target": str(sessions), "readonly": False}],
+ root,
+ )
diff --git a/tests/unit_tests/gateway/test_audit_hooks_enterprise.py b/tests/unit_tests/gateway/test_audit_hooks_enterprise.py
index 680371cca8..3d4536c364 100644
--- a/tests/unit_tests/gateway/test_audit_hooks_enterprise.py
+++ b/tests/unit_tests/gateway/test_audit_hooks_enterprise.py
@@ -201,7 +201,11 @@ async def test_session_delete_emits_ua_and_evt(
self.responses.append(kwargs)
channel = _Chan()
- _register_web_handlers(WebHandlersBindParams(channel=channel, agent_client=None))
+ client = SimpleNamespace(
+ server_ready=True,
+ send_request=AsyncMock(return_value=SimpleNamespace(ok=True, payload={})),
+ )
+ _register_web_handlers(WebHandlersBindParams(channel=channel, agent_client=client))
handler = channel.handlers["session.delete"]
monkeypatch.setattr(
@@ -210,7 +214,7 @@ async def test_session_delete_emits_ua_and_evt(
)
monkeypatch.setattr(
"jiuwenswarm.gateway.channel_manager.web.app_web_handlers._ws_identity_scope",
- lambda _ws: (None, None),
+ lambda _ws: ("group-1", "bot-1"),
)
deleted = {"value": True}
@@ -226,7 +230,7 @@ async def test_session_delete_emits_ua_and_evt(
await handler(
MagicMock(),
"req-del-1",
- {"session_id": "sess-del-1"},
+ {"session_id": "sess-del-1", "group_id": "forged", "bot_id": "forged"},
"sess-del-1",
user_id="user1",
)
@@ -235,6 +239,13 @@ async def test_session_delete_emits_ua_and_evt(
assert audit_cap.ua[0]["UA"] == "session_delete"
assert audit_cap.ua[0]["UID"] == "user1"
assert audit_cap.ua[0]["MSG"] == "deleted"
+ from jiuwenswarm.common.request_identity import web_routing_identity
+
+ forwarded = client.send_request.call_args.args[0]
+ identity = web_routing_identity(forwarded.channel_context)
+ assert identity["group_id"] == "group-1"
+ assert identity["bot_id"] == "bot-1"
+ assert forwarded.user_id == "user1"
audit_cap.ua.clear()
deleted["value"] = False
diff --git a/tests/unit_tests/personal_context/test_closed_class_inventory.py b/tests/unit_tests/personal_context/test_closed_class_inventory.py
index 27df7ec652..44520d60c1 100644
--- a/tests/unit_tests/personal_context/test_closed_class_inventory.py
+++ b/tests/unit_tests/personal_context/test_closed_class_inventory.py
@@ -35,7 +35,8 @@ def test_embedded_personal_context_has_exactly_eighteen_production_classes() ->
core_rail = Path(rail_spec.origin)
# dev-stable 基线 18 个生产类;hwlLab/avatar 配对下 Core 额外携带
# IM 学习/检索子系统与蒸馏调度。检索工具类并入后合计 62(此前为 61)。
- assert len(_classes(core) | _classes(core_rail) | _classes(HOST)) in {18, 61, 62}
+ # 蒸馏窗口新增 DistillCorpusBatch 后合计 63。
+ assert len(_classes(core) | _classes(core_rail) | _classes(HOST)) in {18, 61, 62, 63}
def test_legacy_host_package_is_removed() -> None:
diff --git a/uv.lock b/uv.lock
index 5690625b65..234b29868a 100644
--- a/uv.lock
+++ b/uv.lock
@@ -3510,7 +3510,7 @@ wheels = [
[[package]]
name = "openjiuwen"
version = "0.1.16"
-source = { git = "https://gitcode.com/openJiuwen/agent-core.git?rev=dev-stable#117b9d9d1be1c54e8f315355f5605b91d6ed5302" }
+source = { git = "https://gitcode.com/openJiuwen/agent-core.git?rev=dev-stable#5ee4e38d5c890de2049084bddddc87bedc5a37e4" }
dependencies = [
{ name = "aiofiles" },
{ name = "aiohttp" },