feat(memory): add progressive wiki and drain Dream history (#4477)

This commit is contained in:
chengyongru authored and GitHub committed 2026-11-18 16:28:43 +08:00
1 parent 9ccf3b6214
commit 74d070f699
40 files changed
+1513 -738

No files matched your search

+43 -14
View File
@@ -71,6 +71,7 @@ class ContextBuilder:
BOOTSTRAP_FILES = ["AGENTS.md", "SOUL.md", "USER.md"]
_SKIPPABLE_DEFAULTS = {"AGENTS.md", "USER.md"}
_MEMORY_SKILLS = frozenset({"memory"})
def __init__(self, workspace: Path, timezone: str | None = None, disabled_skills: list[str] | None = None):
self.workspace = workspace
@@ -85,16 +86,19 @@ class ContextBuilder:
session_summary: SessionSummary | None = None,
workspace: Path | None = None,
include_memory: bool = True,
has_cron: bool = True,
) -> str:
"""Build the system prompt from identity, bootstrap files, memory, and skills."""
root = workspace or self.workspace
parts = [self._get_identity(channel=channel, workspace=root)]
parts = [self._get_identity(channel=channel, workspace=root, include_memory=include_memory)]
bootstrap = self._load_bootstrap_files(root)
bootstrap = self._load_bootstrap_files(root, include_memory=include_memory)
if bootstrap:
parts.append(bootstrap)
parts.append(render_template("agent/tool_contract.md", track_source=True))
parts.append(render_template(
"agent/tool_contract.md", track_source=True, has_cron=has_cron, include_memory=include_memory,
))
project_path = root.expanduser().resolve()
if project_path != self.workspace.expanduser().resolve():
@@ -112,15 +116,16 @@ class ContextBuilder:
elif self.memory.memory_file.is_file():
record_source(self.memory.memory_file, "", loaded=False)
excluded_skills = self._excluded_skills(include_memory=include_memory, has_cron=has_cron)
with self.skills.snapshot():
active_skills = self.skills.get_always_skills()
active_skills = self.skills.get_always_skills(exclude=excluded_skills)
if active_skills:
active_content = self.skills.load_skills_for_context(active_skills)
if active_content:
parts.append(f"# Active Skills\n\n{active_content}")
skills_summary = self.skills.build_skills_summary(
exclude=set(active_skills),
exclude=set(active_skills).union(excluded_skills),
workspace=root,
)
if skills_summary:
@@ -135,7 +140,9 @@ class ContextBuilder:
return "\n\n---\n\n".join(parts)
def _get_identity(self, channel: str | None = None, workspace: Path | None = None) -> str:
def _get_identity(
self, channel: str | None = None, workspace: Path | None = None, *, include_memory: bool = True,
) -> str:
root = workspace or self.workspace
workspace_path = str(root.expanduser().resolve())
agent_workspace_path = str(self.workspace.expanduser().resolve())
@@ -147,6 +154,7 @@ class ContextBuilder:
track_source=True,
workspace_path=workspace_path,
agent_workspace_path=agent_workspace_path,
include_memory=include_memory,
runtime=runtime,
platform_policy=render_template("agent/platform_policy.md", system=system),
channel=channel or "",
@@ -175,14 +183,11 @@ class ContextBuilder:
return _to_blocks(left) + _to_blocks(right)
def _load_bootstrap_files(self, workspace: Path | None = None) -> str:
def _load_bootstrap_files(self, workspace: Path | None = None, *, include_memory: bool = True) -> str:
parts: list[str] = []
project_root = workspace or self.workspace
sources = [
("AGENTS.md", project_root),
("SOUL.md", self.workspace),
("USER.md", self.workspace),
]
sources = [("AGENTS.md", workspace or self.workspace)]
if include_memory:
sources.extend([("SOUL.md", self.workspace), ("USER.md", self.workspace)])
for filename, root in sources:
file_path = root / filename
@@ -226,6 +231,7 @@ class ContextBuilder:
runtime_context_blocks: Sequence[RuntimeContextBlock] | None = None,
workspace: Path | None = None,
include_memory: bool = True,
has_cron: bool = True,
) -> list[dict[str, Any]]:
"""Compatibility wrapper for callers that need merged adjacent roles."""
messages = self.build_transcript(
@@ -240,6 +246,7 @@ class ContextBuilder:
channel=channel,
workspace=workspace,
include_memory=include_memory,
has_cron=has_cron,
)
if current_message is None:
return messages
@@ -266,6 +273,7 @@ class ContextBuilder:
channel: str | None = None,
workspace: Path | None = None,
include_memory: bool = True,
has_cron: bool = True,
) -> list[dict[str, Any]]:
"""Build a model transcript while preserving the fresh-turn boundary."""
root = workspace or self.workspace
@@ -276,6 +284,7 @@ class ContextBuilder:
session_summary=transcript.session_summary,
workspace=root,
include_memory=include_memory,
has_cron=has_cron,
)
messages: list[dict[str, Any]] = [
{"role": "system", "content": system_prompt},
@@ -289,12 +298,28 @@ class ContextBuilder:
media=list(transcript.media) if transcript.media else None,
current_role=transcript.current_role,
runtime_context_blocks=transcript.runtime_context_blocks,
include_memory=include_memory,
has_cron=has_cron,
)
if transcript.input_metadata:
current["_meta"] = {**current.get("_meta", {}), **transcript.input_metadata}
messages.append(current)
return messages
@classmethod
def _excluded_skills(cls, *, include_memory: bool, has_cron: bool) -> set[str]:
excluded: set[str] = set() if include_memory else set(cls._MEMORY_SKILLS)
if not has_cron:
excluded.add("cron")
return excluded
def build_explicit_skill_context(
self, text: str, *, include_memory: bool, has_cron: bool,
) -> RuntimeContextBlock | None:
return self.skills.build_explicit_skill_runtime_context(
text, exclude=self._excluded_skills(include_memory=include_memory, has_cron=has_cron),
)
def build_current_message(
self,
current_message: str,
@@ -302,13 +327,17 @@ class ContextBuilder:
media: list[str] | None = None,
current_role: str = "user",
runtime_context_blocks: Sequence[RuntimeContextBlock] | None = None,
include_memory: bool = True,
has_cron: bool = True,
) -> dict[str, Any]:
"""Build only the fresh turn message without merging it into history."""
content = self.build_user_content(current_message, image_paths=media)
blocks: list[RuntimeContextBlock] = []
if current_role == "user":
blocks.extend(runtime_context_blocks or ())
skill_context = self.skills.build_explicit_skill_runtime_context(current_message)
skill_context = self.build_explicit_skill_context(
current_message, include_memory=include_memory, has_cron=has_cron,
)
if skill_context is not None and skill_context not in blocks:
blocks.append(skill_context)
merged, runtime_context_meta = append_runtime_context(content, blocks)
+67
View File
@@ -0,0 +1,67 @@
"""Shared manual and scheduled Dream execution over a bounded history snapshot."""
from __future__ import annotations
from dataclasses import dataclass
from typing import TYPE_CHECKING, Any
from loguru import logger
from nanobot.agent.memory import MemoryStore
if TYPE_CHECKING:
from nanobot.agent.loop import AgentLoop
@dataclass
class DreamResult:
had_input: bool = False
changed: bool = False
error: str | None = None
commit_sha: str | None = None
async def run_dream(loop: AgentLoop, *, commit_prefix: str) -> DreamResult:
"""Run one Dream over the pending journal range, serializing writers."""
store = loop.context.memory
result = DreamResult()
async def silent(*_args: Any, **_kwargs: Any) -> None:
pass
async with store.dream_lock:
try:
history = store.build_dream_prompt()
if history is not None:
result.had_input = True
prompt, last_cursor = history
response = await loop.process_direct(
prompt,
session_key=MemoryStore.dream_session_key(),
ephemeral=True,
tools=store.build_dream_tools(),
on_progress=silent,
runtime=loop.dream_runtime(),
)
if MemoryStore.dream_run_completed(response):
store.set_last_dream_cursor(last_cursor)
else:
result.error = MemoryStore.dream_incompletion_reason(response)
except Exception as exc:
result.error = str(exc)
logger.exception("Dream failed")
finally:
try:
diff = store.dream_content_diff()
result.changed = bool(diff)
if diff and store.git.is_initialized():
result.commit_sha = store.git.auto_commit(
MemoryStore.build_dream_commit_message(commit_prefix, diff),
)
store.compact_history()
except Exception as exc:
failure = f"Memory finalization failed: {exc}"
result.error = f"{result.error}; {failure}" if result.error else failure
logger.exception("Dream memory finalization failed")
await loop.sessions.state.prune_dream_sessions()
return result
+53 -7
View File
@@ -62,6 +62,7 @@ from nanobot.command.router import CommandExpansion, command_text
from nanobot.config.network import NetworkConfig
from nanobot.config.schema import AgentDefaults, ModelPresetConfig
from nanobot.events import NO_EVENTS, AgentEvent, EventSink
from nanobot.execution.files import exclude_file_paths
from nanobot.llm_usage.context import source_from_request
from nanobot.providers.base import LLMProvider, LLMUsage, ProviderConversationState
from nanobot.providers.factory import ProviderSnapshot
@@ -390,7 +391,7 @@ class AgentLoop:
self.consolidator = Consolidator(
store=self.context.memory,
sessions=self.sessions,
build_messages=self.context.build_messages,
build_messages=self._build_compaction_messages,
get_tool_definitions=self.tools.get_definitions,
resolve_prompt_context=PersistedPromptContextResolver(
workspace_scopes=self.workspace_scopes,
@@ -672,6 +673,24 @@ class AgentLoop:
logger.info("Registered {} tools: {}", len(registered), registered)
def _build_compaction_messages(
self,
*,
history: list[dict[str, Any]],
current_message: str | None,
channel: str | None = None,
session_summary: SessionSummary | None = None,
workspace: Path | None = None,
) -> list[dict[str, Any]]:
return self.context.build_messages(
history=history,
current_message=current_message,
channel=channel,
session_summary=session_summary,
workspace=workspace,
has_cron=self.tools.has("cron"),
)
def register_runtime_context_provider(
self,
provider: RuntimeContextProvider,
@@ -813,16 +832,19 @@ class AgentLoop:
self,
ctx: TurnContext,
) -> list[RuntimeContextBlock]:
assert ctx.request_context is not None
assert ctx.request_context is not None and ctx.session is not None
return await self._resolve_runtime_context_for_request(
ctx.request_context,
ctx.tools if ctx.tools is not None else self.tools,
include_memory=ctx.session.policy.persist,
)
async def _resolve_runtime_context_for_request(
self,
request: RequestContext,
tools: ToolRegistry,
*,
include_memory: bool,
) -> list[RuntimeContextBlock]:
providers = [
*tools.get_runtime_context_providers(),
@@ -832,7 +854,10 @@ class AgentLoop:
blocks.extend(await resolve_runtime_context(providers, request))
text = request.original_user_text or ""
skill_context = (
await self.runner.prepare_prompt(self.context.skills.build_explicit_skill_runtime_context, text)
await self.runner.prepare_prompt(
self.context.build_explicit_skill_context, text,
include_memory=include_memory, has_cron=tools.has("cron"),
)
if "$" in text else None
)
if skill_context is not None and skill_context not in blocks:
@@ -1071,7 +1096,9 @@ class AgentLoop:
workspace_scope=request.workspace_scope,
log_content=request.log_content,
)
blocks = await self._resolve_runtime_context_for_request(pending_request, tools)
blocks = await self._resolve_runtime_context_for_request(
pending_request, tools, include_memory=session is None or session.policy.persist,
)
row["content"], runtime_marker = append_runtime_context(user_content, blocks)
if runtime_marker is not None:
row["_meta"][RUNTIME_CONTEXT_MESSAGE_META] = runtime_marker
@@ -1150,11 +1177,15 @@ class AgentLoop:
message_metadata=_prompt_scope_metadata(request_metadata),
session_metadata=_prompt_scope_metadata(session.metadata) if session is not None else None,
)
include_memory = session is None or session.policy.persist
effective_tools = tools if tools is not None else self.tools
has_cron = effective_tools.has("cron")
transcript_builder = partial(
self.context.build_transcript,
channel=request_ctx.channel,
workspace=effective_scope.project_path,
include_memory=session.policy.persist if session is not None else True,
include_memory=include_memory,
has_cron=has_cron,
)
if initial_message is not None and turn_continuation.internal_continuation_inbound(initial_message.metadata):
build_transcript = transcript_builder
@@ -1185,13 +1216,23 @@ class AgentLoop:
and (session is None or session.policy.persist)
),
)
effective_tools = tools if tools is not None else self.tools
with ExitStack() as turn_scope_stack:
turn_scope_stack.callback(
reset_file_states, bind_file_states(self._file_state_store.for_session(active_session_key)),
)
turn_scope_stack.callback(reset_request_context, bind_request_context(request_ctx))
turn_scope_stack.callback(reset_workspace_scope, bind_workspace_scope(effective_scope))
if not include_memory:
memory = self.context.memory
skills = self.context.skills
turn_scope_stack.enter_context(exclude_file_paths(
memory.soul_file, memory.user_file, memory.memory_dir,
skills.workspace_skills / "memory", skills.builtin_skills / "memory",
))
if not has_cron:
turn_scope_stack.enter_context(exclude_file_paths(
self.workspace / "HEARTBEAT.md", writes_only=True,
))
execution_scope: ExecutionScope | None = None
if self.execution_policy is not None:
execution_scope = turn_scope_stack.enter_context(self.execution_policy.scope(
@@ -1696,7 +1737,10 @@ class AgentLoop:
await self._pending_queues.join_controls()
# A scan can schedule archival while shutdown waits for it.
while self._background_tasks:
await asyncio.gather(*self._background_tasks, return_exceptions=True)
tasks = tuple(self._background_tasks)
await asyncio.gather(*tasks, return_exceptions=True)
# Already-complete tasks may return before their done callbacks run.
self._background_tasks.difference_update(tasks)
except BaseException as exc:
errors.append(exc)
finally:
@@ -2145,6 +2189,8 @@ class AgentLoop:
ctx.msg.content,
media=ctx.msg.media if ctx.kind is TurnKind.USER and ctx.msg.media else None,
runtime_context_blocks=ctx.runtime_context_blocks,
include_memory=session.policy.persist,
has_cron=(ctx.tools if ctx.tools is not None else self.tools).has("cron"),
)
task_id = ctx.msg.metadata.get("subagent_task_id") if is_subagent else None
already_staged = False
+51 -41
View File
@@ -18,6 +18,7 @@ from uuid import uuid4
from loguru import logger
from nanobot.config.paths import DREAM_CURSOR_PATH, MEMORY_CURSOR_PATH, MEMORY_JOURNAL_PATH
from nanobot.events import NO_EVENTS, CompactionReason, ContextCompactionEvent, EventSink
from nanobot.llm_usage.context import llm_usage_source
from nanobot.providers.base import LLMResponse, ProviderConversationState
@@ -25,7 +26,7 @@ from nanobot.providers.conversation_state import ProviderConversationStateContro
from nanobot.runtime_context import public_history_messages
from nanobot.session.manager import Session, SessionManager
from nanobot.session.summary import is_summary_checkpoint, session_summary_from_metadata
from nanobot.utils.gitstore import GitStore
from nanobot.utils.gitstore import MEMORY_CONTENT_PATHS, MEMORY_WIKI_PATH, GitStore
from nanobot.utils.helpers import (
atomic_write_lines,
build_assistant_message,
@@ -50,13 +51,9 @@ if TYPE_CHECKING:
class MemoryStore:
"""Pure file I/O for memory files: MEMORY.md, history.jsonl, SOUL.md, USER.md."""
"""File I/O for the memory journal, resident memory, and on-demand wiki."""
_DEFAULT_MAX_HISTORY = 1000
# Durable files whose real working-tree delta grounds Dream commit messages.
# Deliberately excludes memory/.dream_cursor so progress bookkeeping never
# appears as a durable-memory edit in the audit record.
_DREAM_CONTENT_PATHS = ("SOUL.md", "USER.md", "memory/MEMORY.md")
_LEGACY_ENTRY_START_RE = re.compile(r"^\[(\d{4}-\d{2}-\d{2}[^\]]*)\]\s*")
_LEGACY_TIMESTAMP_RE = re.compile(r"^\[(\d{4}-\d{2}-\d{2} \d{2}:\d{2})\]\s*")
_LEGACY_RAW_MESSAGE_RE = re.compile(
@@ -68,20 +65,20 @@ class MemoryStore:
self.max_history_entries = max_history_entries
self.memory_dir = ensure_dir(workspace / "memory")
self.memory_file = self.memory_dir / "MEMORY.md"
self.history_file = self.memory_dir / "history.jsonl"
self.wiki_dir = workspace / MEMORY_WIKI_PATH
self.history_file = workspace / MEMORY_JOURNAL_PATH
self.legacy_history_file = self.memory_dir / "HISTORY.md"
self.soul_file = workspace / "SOUL.md"
self.user_file = workspace / "USER.md"
self._cursor_file = self.memory_dir / ".cursor"
self._dream_cursor_file = self.memory_dir / ".dream_cursor"
self._cursor_file = workspace / MEMORY_CURSOR_PATH
self._dream_cursor_file = workspace / DREAM_CURSOR_PATH
self._corruption_logged = False
self._malformed_entry_logged = False
self._oversize_logged = False
self._dream_prompt_oversize_logged = False
self._append_lock = threading.Lock()
self._git = GitStore(workspace, tracked_files=[
"SOUL.md", "USER.md", "memory/MEMORY.md", "memory/.dream_cursor",
])
self.dream_lock = asyncio.Lock()
self._git = GitStore.for_memory(workspace)
self._maybe_migrate_legacy_history()
@property
@@ -317,10 +314,10 @@ class MemoryStore:
return None
return value
def _iter_valid_entries(self) -> Iterator[tuple[dict[str, Any], int]]:
def _iter_valid_entries(self) -> Iterator[tuple[range, dict[str, Any], int]]:
poisoned: Any = None
malformed_cursor: int | None = None
for entry in self._read_entries():
for lines, entry in self._iter_entries():
raw = entry.get("cursor")
if raw is None:
continue
@@ -331,7 +328,7 @@ class MemoryStore:
if not self._valid_history_payload(entry):
malformed_cursor = cursor
continue
yield entry, cursor
yield lines, entry, cursor
if poisoned is not None and not self._corruption_logged:
self._corruption_logged = True
logger.warning(
@@ -372,7 +369,7 @@ class MemoryStore:
if cursor_counter is not None:
if last_cursor is not None:
return max(cursor_counter, last_cursor) + 1
max_history_cursor = max((c for _, c in self._iter_valid_entries()), default=0)
max_history_cursor = max((c for _, _, c in self._iter_valid_entries()), default=0)
return max(cursor_counter, max_history_cursor) + 1
# Fast path: trust the tail when intact. Otherwise scan the whole
@@ -380,11 +377,11 @@ class MemoryStore:
# invariant was broken by external writes.
if last_cursor is not None:
return last_cursor + 1
return max((c for _, c in self._iter_valid_entries()), default=0) + 1
return max((c for _, _, c in self._iter_valid_entries()), default=0) + 1
def read_unprocessed_history(self, since_cursor: int) -> list[dict[str, Any]]:
"""Return history entries with a valid cursor > *since_cursor*."""
return [e for e, c in self._iter_valid_entries() if c > since_cursor]
return [e for _, e, c in self._iter_valid_entries() if c > since_cursor]
def compact_history(self) -> None:
"""Drop oldest processed entries without discarding pending Dream input."""
@@ -417,11 +414,15 @@ class MemoryStore:
self._write_entries(kept)
def _read_entries(self) -> list[dict[str, Any]]:
entries: list[dict[str, Any]] = []
def _iter_entries(self) -> Iterator[tuple[range, dict[str, Any]]]:
with suppress(FileNotFoundError):
with open(self.history_file, "r", encoding="utf-8") as f:
line_number = 1
for line in f:
# Match read_file's splitlines, including Unicode separators
# that JSON leaves unescaped inside string values.
lines = range(line_number, line_number + len(line.splitlines()))
line_number = lines.stop
line = line.strip()
if line:
try:
@@ -429,9 +430,10 @@ class MemoryStore:
except json.JSONDecodeError:
continue
if isinstance(parsed, dict):
entries.append(cast(dict[str, Any], parsed))
yield lines, cast(dict[str, Any], parsed)
return entries
def _read_entries(self) -> list[dict[str, Any]]:
return [entry for _, entry in self._iter_entries()]
def _read_last_entry(self) -> dict[str, Any] | None:
try:
@@ -503,27 +505,30 @@ class MemoryStore:
return text
return self.default_dream_prompt()
def build_dream_prompt(self, *, max_entries: int = 20) -> tuple[str, int] | None:
"""Build the Dream prompt with unprocessed history context.
def build_dream_prompt(self) -> tuple[str, int] | None:
"""Describe the pending journal range for one file-reading Dream task.
Returns ``(prompt, last_cursor)`` or ``None`` if nothing to process.
The current contents of the durable memory files (SOUL.md, USER.md,
memory/MEMORY.md) reach Dream through the normal agent system context.
Appends preserve these read_file line numbers. Dream is serialized, and
history compaction runs only after the task finishes reading its range.
"""
last_cursor = self.get_last_dream_cursor()
entries = self.read_unprocessed_history(since_cursor=last_cursor)
if not entries:
since_cursor = self.get_last_dream_cursor()
with self._append_lock:
pending = [
(lines, cursor)
for lines, _, cursor in self._iter_valid_entries()
if cursor > since_cursor
]
if not pending:
return None
batch = entries[:max_entries]
history_text = "\n".join(
f"[{e['timestamp']}] {truncate_text(e['content'], 1000)}"
for e in batch
last_cursor = max(cursor for _, cursor in pending)
history_prompt = render_template(
"agent/dream_history.md", strip=True,
path=str(self.history_file.resolve()),
start_line=pending[0][0].start, end_line=pending[-1][0].stop - 1,
count=len(pending), since_cursor=since_cursor, last_cursor=last_cursor,
)
template = self._dream_template()
prompt = f"{template}\n\n## Conversation History\n{history_text}"
return (prompt, batch[-1]["cursor"])
return f"{self._dream_template()}\n\n{history_prompt}", last_cursor
def dream_content_diff(self) -> str:
"""Structured summary of uncommitted changes to the durable memory files.
@@ -533,7 +538,9 @@ class MemoryStore:
"""
if not self._git.is_initialized():
return ""
return self._git.summarize_working_tree(list(self._DREAM_CONTENT_PATHS))
return self._git.summarize_working_tree(
list(MEMORY_CONTENT_PATHS), directories=[MEMORY_WIKI_PATH],
)
def build_dream_tools(self) -> ToolRegistry:
"""Build the restricted tool registry used by Dream runs."""
@@ -561,18 +568,21 @@ class MemoryStore:
tools.register(EditFileTool(
workspace=workspace,
allowed_dir=skills_dir,
extra_write_allowed_dirs=[self.wiki_dir],
extra_write_allowed_files=editable_files,
file_states=file_states,
))
tools.register(ApplyPatchTool(
workspace=workspace,
allowed_dir=skills_dir,
extra_write_allowed_dirs=[self.wiki_dir],
extra_write_allowed_files=editable_files,
file_states=file_states,
))
tools.register(WriteFileTool(
workspace=workspace,
allowed_dir=skills_dir,
extra_write_allowed_dirs=[self.wiki_dir],
extra_write_allowed_files=editable_files,
file_states=file_states,
))
@@ -675,8 +685,8 @@ class MemoryStore:
@staticmethod
def dream_session_key() -> str:
"""Return a unique session key for a Dream run, e.g. ``dream:20260528-100000``."""
return f"dream:{datetime.now():%Y%m%d-%H%M%S}"
"""Give every batch its own session, including batches in the same second."""
return f"dream:{datetime.now():%Y%m%d-%H%M%S}-{uuid4().hex[:8]}"
@staticmethod
def build_dream_commit_message(prefix: str, diff_body: str) -> str:
+24 -20
View File
@@ -2,7 +2,7 @@ import json
import os
import re
import shutil
from collections.abc import Generator
from collections.abc import Collection, Generator
from contextlib import contextmanager
from contextvars import ContextVar
from dataclasses import dataclass, field
@@ -93,7 +93,9 @@ class SkillsLoader:
entries.append({"name": name, "path": str(skill_file), "source": source})
return entries
def list_skills(self, filter_unavailable: bool = True) -> list[dict[str, str]]:
def list_skills(
self, filter_unavailable: bool = True, *, exclude: Collection[str] = (),
) -> list[dict[str, str]]:
"""
List all available skills.
@@ -104,9 +106,9 @@ class SkillsLoader:
List of skill info dicts with 'name', 'path', 'source'.
"""
with self.snapshot():
return self._list_skills(filter_unavailable)
return self._list_skills(filter_unavailable, exclude)
def _list_skills(self, filter_unavailable: bool) -> list[dict[str, str]]:
def _list_skills(self, filter_unavailable: bool, exclude: Collection[str]) -> list[dict[str, str]]:
snapshot = self._snapshot.get()
if snapshot is not None and snapshot.entries is not None:
skills = snapshot.entries
@@ -114,6 +116,8 @@ class SkillsLoader:
skills = self._discover_skills()
if snapshot is not None:
snapshot.entries = skills
if exclude:
skills = [skill for skill in skills if skill["name"] not in exclude]
if filter_unavailable:
return [skill for skill in skills if self._check_requirements(self._get_skill_meta(skill["name"]))]
return skills
@@ -204,14 +208,14 @@ class SkillsLoader:
]
return "\n\n---\n\n".join(parts)
def get_explicitly_invoked_skills(self, text: str) -> list[str]:
def get_explicitly_invoked_skills(self, text: str, *, exclude: Collection[str] = ()) -> list[str]:
"""Resolve ``$skill-name`` references to enabled, available skills."""
references = list(_SKILL_REFERENCE.finditer(text))
if not references:
return []
available = {
entry["name"]
for entry in self.list_skills(filter_unavailable=True)
for entry in self.list_skills(filter_unavailable=True, exclude=exclude)
}
aliases = self._skill_aliases()
invoked: list[str] = []
@@ -225,16 +229,20 @@ class SkillsLoader:
def build_explicit_skill_runtime_context(
self,
text: str,
*,
exclude: Collection[str] = (),
) -> RuntimeContextBlock | None:
"""Load non-always skills explicitly invoked by the current message."""
with self.snapshot():
return self._build_explicit_skill_runtime_context(text)
return self._build_explicit_skill_runtime_context(text, exclude)
def _build_explicit_skill_runtime_context(self, text: str) -> RuntimeContextBlock | None:
skill_names = self.get_explicitly_invoked_skills(text)
def _build_explicit_skill_runtime_context(
self, text: str, exclude: Collection[str],
) -> RuntimeContextBlock | None:
skill_names = self.get_explicitly_invoked_skills(text, exclude=exclude)
if not skill_names:
return None
always_active = set(self.get_always_skills())
always_active = set(self.get_always_skills(exclude=exclude))
skill_names = [name for name in skill_names if name not in always_active]
content = self.load_skills_for_context(skill_names)
if not content:
@@ -271,7 +279,7 @@ class SkillsLoader:
return self._build_skills_summary(exclude, workspace=workspace)
def _build_skills_summary(self, exclude: set[str] | None, *, workspace: Path | None) -> str:
all_skills = self.list_skills(filter_unavailable=True)
all_skills = self.list_skills(filter_unavailable=True, exclude=exclude or ())
if not all_skills:
return ""
@@ -285,11 +293,7 @@ class SkillsLoader:
("Built-in skills", "builtin", self.builtin_skills),
)
for label, source, root in groups:
entries = [
entry
for entry in all_skills
if entry["source"] == source and (not exclude or entry["name"] not in exclude)
]
entries = [entry for entry in all_skills if entry["source"] == source]
if not entries:
continue
@@ -396,15 +400,15 @@ class SkillsLoader:
raw_meta = self.get_skill_metadata(name) or {}
return self._parse_nanobot_metadata(raw_meta.get("metadata"))
def get_always_skills(self) -> list[str]:
def get_always_skills(self, *, exclude: Collection[str] = ()) -> list[str]:
"""Get skills marked as always=true that meet requirements."""
with self.snapshot():
return self._get_always_skills()
return self._get_always_skills(exclude)
def _get_always_skills(self) -> list[str]:
def _get_always_skills(self, exclude: Collection[str]) -> list[str]:
return [
entry["name"]
for entry in self.list_skills(filter_unavailable=True)
for entry in self.list_skills(filter_unavailable=True, exclude=exclude)
if (meta := self.get_skill_metadata(entry["name"]) or {})
and (
self._parse_nanobot_metadata(meta.get("metadata")).get("always")
+1 -1
View File
@@ -85,7 +85,7 @@ class _FsTool(Tool):
return cls(
workspace=workspace,
allowed_dir=workspace if restricted or sandboxed else None,
extra_read_allowed_dirs=[BUILTIN_SKILLS_DIR, root / "skills"],
extra_read_allowed_dirs=[BUILTIN_SKILLS_DIR, root / "skills", root / "memory" / "wiki"],
extra_read_allowed_files=[root / "memory" / "history.jsonl"],
restrict_to_workspace=restricted,
sandbox_restricts_workspace=sandboxed,