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

feat: /memory command support

ldstyle8ca9fd40bcbde
diff --git a/jiuwenclaw/agents/harness/common/memory/forbidden.py b/jiuwenclaw/agents/harness/common/memory/forbidden.py
index 8d3d9be979..e4ab6fec42 100644
--- a/jiuwenclaw/agents/harness/common/memory/forbidden.py
+++ b/jiuwenclaw/agents/harness/common/memory/forbidden.py
@@ -18,7 +18,7 @@ def _get_memory_forbidden_config() -> Dict[str, Any]:
"patterns": forbidden_config.get("patterns", []),
"description": forbidden_config.get("description", {
"zh": "以下内容禁止记忆:密码、API密钥、Secret、Token、信用卡号、身份证号、手机号等敏感信息",
- "en": "The following content is forbidden to remember: passwords, \API keys, secrets, tokens, \
+ "en": "The following content is forbidden to remember: passwords, API keys, secrets, tokens, \
credit card numbers, ID numbers, phone numbers and other sensitive information",
}),
}
diff --git a/jiuwenclaw/agents/harness/common/memory_rpc.py b/jiuwenclaw/agents/harness/common/memory_rpc.py
new file mode 100644
index 0000000000..c43d14bab7
--- /dev/null
+++ b/jiuwenclaw/agents/harness/common/memory_rpc.py
@@ -0,0 +1,421 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
+
+from __future__ import annotations
+
+import logging
+import os
+from pathlib import Path
+from typing import Any
+
+from jiuwenclaw.agents.harness.common.memory import (
+ get_memory_manager,
+ is_memory_enabled,
+)
+from jiuwenclaw.agents.harness.common.memory.config import is_proactive_memory
+from jiuwenclaw.agents.harness.common.memory.external_memory_config import (
+ get_memory_engine,
+ is_external_memory_allowed,
+ get_external_memory_config,
+)
+from jiuwenclaw.agents.harness.common.rails.project_memory import (
+ discover_and_load_memory_files,
+)
+from jiuwenclaw.common.config import get_config
+
+logger = logging.getLogger(__name__)
+
+
+def _is_forbidden_enabled(config: dict[str, Any] | None) -> bool:
+ mem_cfg = (config or {}).get("memory", {}) if isinstance(config, dict) else {}
+ forbidden = mem_cfg.get("forbidden_memory_definition", {})
+ return bool(forbidden.get("enabled", False))
+
+
+def _get_allowed_dirs(workspace: str, project_dir: str | None = None) -> list[str]:
+ allowed_dirs = [
+ os.path.join(workspace, "memory"),
+ os.path.join(workspace, "coding_memory"),
+ os.path.join(workspace, ".jiuwen"),
+ os.path.expanduser("~/.jiuwen"),
+ ]
+ if project_dir:
+ allowed_dirs.append(project_dir)
+ allowed_dirs.append(os.path.join(project_dir, ".jiuwen"))
+ return [os.path.normpath(d) for d in allowed_dirs]
+
+
+def _is_in_allowed_dirs(abs_path: str, workspace: str, project_dir: str | None = None) -> bool:
+ for allowed_dir in _get_allowed_dirs(workspace, project_dir):
+ if abs_path == allowed_dir or abs_path.startswith(allowed_dir + os.sep):
+ return True
+ return False
+
+
+def _validate_edit_path(raw_path: str, workspace: str, project_dir: str | None = None) -> tuple[bool, str]:
+ normalized = raw_path.replace("\\", "/")
+ expanded = os.path.expanduser(normalized)
+
+ if os.path.isabs(expanded):
+ abs_path = os.path.normpath(expanded)
+ else:
+ workspace_resolved = os.path.normpath(os.path.abspath(os.path.join(workspace, expanded)))
+ abs_path = workspace_resolved
+ if project_dir:
+ project_resolved = os.path.normpath(os.path.abspath(os.path.join(project_dir, expanded)))
+ if _is_in_allowed_dirs(project_resolved, workspace, project_dir):
+ abs_path = project_resolved
+
+ if _is_in_allowed_dirs(abs_path, workspace, project_dir):
+ return (True, abs_path)
+
+ basename = os.path.basename(abs_path)
+ if basename in ("JIUWENCLAW.md", "JIUWENCLAW.local.md"):
+ parent = os.path.dirname(abs_path)
+ workspace_norm = os.path.normpath(workspace)
+ if parent == workspace_norm:
+ return (True, abs_path)
+ if project_dir and parent == os.path.normpath(project_dir):
+ return (True, abs_path)
+
+ return (False, f"Path not in allowed memory directories: {raw_path}")
+
+
+def _classify_memory_file(path: str, workspace: str) -> str:
+ if "coding_memory" in path:
+ return "coding"
+ parts = Path(path).parts
+ if "memory" in parts:
+ return "auto"
+ if ".jiuwen" in parts:
+ return "project"
+ if path.endswith(".local.md"):
+ return "local"
+ jiuwen_dir = os.path.expanduser("~/.jiuwen")
+ if path.startswith(jiuwen_dir):
+ return "user"
+ return "project"
+
+
+def _relative_path(abs_path: str, workspace: str, project_dir: str | None = None) -> str:
+ abs_path_norm = os.path.normpath(abs_path)
+ if project_dir:
+ project_dir_norm = os.path.normpath(project_dir)
+ if abs_path_norm.startswith(project_dir_norm + os.sep) or abs_path_norm == project_dir_norm:
+ try:
+ return os.path.relpath(abs_path, project_dir)
+ except ValueError:
+ pass
+ workspace_norm = os.path.normpath(workspace)
+ if abs_path_norm.startswith(workspace_norm + os.sep) or abs_path_norm == workspace_norm:
+ try:
+ return os.path.relpath(abs_path, workspace)
+ except ValueError:
+ pass
+ return abs_path
+
+
+def _safe_stat(path: str) -> dict[str, Any]:
+ try:
+ s = Path(path).stat()
+ return {"size": s.st_size, "mtime": s.st_mtime}
+ except OSError:
+ return {"size": 0, "mtime": 0}
+
+
+def _count_lines(path: str) -> int:
+ try:
+ with open(path, encoding="utf-8", errors="replace") as f:
+ return sum(1 for _ in f)
+ except OSError:
+ return 0
+
+
+def _scan_md_files(directory: str, kind: str, workspace: str, project_dir: str | None = None) -> list[dict[str, Any]]:
+ if not os.path.isdir(directory):
+ return []
+ results: list[dict[str, Any]] = []
+ for entry in sorted(os.scandir(directory), key=lambda e: e.name):
+ if entry.is_file() and entry.name.endswith(".md"):
+ stat = _safe_stat(entry.path)
+ results.append({
+ "path": entry.path,
+ "relative_path": _relative_path(entry.path, workspace, project_dir),
+ "kind": kind,
+ "exists": True,
+ "size": stat["size"],
+ "mtime": stat["mtime"],
+ "lines": _count_lines(entry.path),
+ })
+ return results
+
+
+def _is_code_mode(mode: str) -> bool:
+ return mode.startswith("code")
+
+
+async def handle_memory_list(
+ workspace: str,
+ mode: str,
+ params: dict[str, Any],
+) -> dict[str, Any]:
+ include_project = params.get("include_project", True)
+ additional_dirs = params.get("additional_directories")
+ project_dir = params.get("project_dir")
+
+ files: list[dict[str, Any]] = []
+ seen_paths: set[str] = set()
+
+ if include_project:
+ discover_workspace = project_dir or workspace
+ project_files = discover_and_load_memory_files(
+ workspace=discover_workspace,
+ target_path=discover_workspace,
+ additional_directories=additional_dirs,
+ )
+ for f in project_files:
+ stat = _safe_stat(f.path)
+ files.append({
+ "path": f.path,
+ "relative_path": _relative_path(f.path, workspace, project_dir),
+ "kind": f.kind,
+ "exists": True,
+ "size": stat["size"],
+ "mtime": stat["mtime"],
+ "lines": f.content.count("\n") + 1 if f.content else 0,
+ })
+ seen_paths.add(f.path)
+
+ memory_dir = os.path.join(workspace, "memory")
+ for item in _scan_md_files(memory_dir, "auto", workspace, project_dir):
+ if item["path"] not in seen_paths:
+ files.append(item)
+ seen_paths.add(item["path"])
+
+ coding_dir = os.path.join(workspace, "coding_memory")
+ for item in _scan_md_files(coding_dir, "coding", workspace, project_dir):
+ if item["path"] not in seen_paths:
+ files.append(item)
+ seen_paths.add(item["path"])
+
+ return {"files": files, "mode": mode}
+
+
+async def handle_memory_edit(
+ workspace: str,
+ params: dict[str, Any],
+) -> dict[str, Any]:
+ raw_path = params.get("path", "")
+ project_dir = params.get("project_dir")
+ is_valid, resolved = _validate_edit_path(raw_path, workspace, project_dir)
+
+ if not is_valid:
+ return {
+ "path": raw_path,
+ "exists": False,
+ "content_preview": "",
+ "kind": "unknown",
+ "editable": False,
+ }
+
+ exists = Path(resolved).is_file()
+ content_preview = ""
+ kind = _classify_memory_file(resolved, workspace)
+
+ if exists:
+ try:
+ text = Path(resolved).read_text(encoding="utf-8", errors="replace")
+ lines = text.splitlines()[:20]
+ content_preview = "\n".join(lines)
+ if len(text.splitlines()) > 20:
+ content_preview += "\n... (truncated)"
+ except OSError:
+ pass
+ else:
+ parent = Path(resolved).parent
+ parent.mkdir(parents=True, exist_ok=True)
+ Path(resolved).touch()
+
+ return {
+ "path": resolved,
+ "exists": exists,
+ "content_preview": content_preview,
+ "kind": kind,
+ "editable": True,
+ }
+
+
+async def handle_memory_status(
+ workspace: str,
+ mode: str,
+ params: dict[str, Any],
+) -> dict[str, Any]:
+ detailed = params.get("detailed", False)
+ config = get_config()
+
+ code_mode = _is_code_mode(mode)
+ enabled = is_memory_enabled(mode, config) if not code_mode else True
+ proactive = is_proactive_memory(mode, config) if not code_mode else False
+
+ result: dict[str, Any] = {
+ "current_mode": mode,
+ "storage_mode": config.get("memory", {}).get("mode", "local") if isinstance(config, dict) else "local",
+ "engine": get_memory_engine(config),
+ "enabled": enabled,
+ "proactive": proactive,
+ "forbidden_enabled": _is_forbidden_enabled(config),
+ }
+
+ if detailed:
+ manager = await get_memory_manager(agent_id="default", workspace_dir=workspace)
+ if manager is not None:
+ status = manager.status()
+ result["index"] = {
+ "available": status.get("available", False),
+ "provider": status.get("provider"),
+ "model": status.get("model"),
+ "files_count": status.get("files", 0),
+ "chunks_count": status.get("chunks", 0),
+ "dirty": status.get("dirty", False),
+ "fts": status.get("fts", {}),
+ "vector": status.get("vector", {}),
+ "cache": status.get("cache", {}),
+ }
+
+ project_dir = params.get("project_dir")
+ discover_workspace = project_dir or workspace
+ project_files = discover_and_load_memory_files(
+ workspace=discover_workspace,
+ target_path=discover_workspace,
+ )
+ total_chars = sum(len(f.content) for f in project_files)
+ result["project_memory"] = {
+ "files_count": len(project_files),
+ "total_chars": total_chars,
+ "max_chars": 60_000,
+ }
+ if project_dir:
+ result["project_memory"]["project_dir"] = project_dir
+
+ coding_dir = os.path.join(workspace, "coding_memory")
+ coding_files = _scan_md_files(coding_dir, "coding", workspace)
+ coding_total_chars = 0
+ for cf in coding_files:
+ try:
+ text = Path(cf["path"]).read_text(encoding="utf-8", errors="replace")
+ coding_total_chars += len(text)
+ except OSError:
+ pass
+ result["coding_memory"] = {
+ "files_count": len(coding_files),
+ "total_chars": coding_total_chars,
+ "dir": coding_dir if os.path.isdir(coding_dir) else "",
+ }
+
+ memory_dir = os.path.join(workspace, "memory")
+ auto_files = _scan_md_files(memory_dir, "auto", workspace)
+ auto_total_chars = 0
+ for af in auto_files:
+ try:
+ text = Path(af["path"]).read_text(encoding="utf-8", errors="replace")
+ auto_total_chars += len(text)
+ except OSError:
+ pass
+ result["auto_memory"] = {
+ "files_count": len(auto_files),
+ "total_chars": auto_total_chars,
+ "dir": memory_dir if os.path.isdir(memory_dir) else "",
+ }
+
+ engine = get_memory_engine(config)
+ if engine in ("external", "both"):
+ ext_cfg = get_external_memory_config(config)
+ result["external_memory"] = {
+ "provider": ext_cfg.get("provider", "unknown") if ext_cfg else "unknown",
+ "enabled": is_external_memory_allowed(config),
+ }
+
+ return result
+
+
+async def handle_memory_toggle(
+ workspace: str,
+ mode: str,
+ params: dict[str, Any],
+) -> dict[str, Any]:
+ from jiuwenclaw.common.config import update_memory_forbidden_enabled_in_config
+
+ key = params.get("key", "")
+ config = get_config()
+
+ if key == "memory_forbidden_enabled":
+ old = _is_forbidden_enabled(config)
+ new = not old
+ update_memory_forbidden_enabled_in_config(new)
+ return {
+ "key": key,
+ "old_value": old,
+ "new_value": new,
+ "mode_affected": "global",
+ "needs_restart": True,
+ }
+
+ if key == "memory_enabled":
+ old = is_memory_enabled(mode, config)
+ new = not old
+ _update_mode_memory_config(mode, "enabled", new)
+ return {
+ "key": key,
+ "old_value": old,
+ "new_value": new,
+ "mode_affected": mode,
+ "needs_restart": True,
+ }
+
+ if key == "memory_proactive":
+ old = is_proactive_memory(mode, config)
+ new = not old
+ _update_mode_memory_config(mode, "is_proactive", new)
+ return {
+ "key": key,
+ "old_value": old,
+ "new_value": new,
+ "mode_affected": mode,
+ "needs_restart": True,
+ }
+
+ return {
+ "key": key,
+ "old_value": False,
+ "new_value": False,
+ "mode_affected": "",
+ "needs_restart": False,
+ }
+
+
+def _update_mode_memory_config(mode: str, field: str, value: bool) -> None:
+ from jiuwenclaw.common.config import _load_yaml_round_trip, _dump_yaml_round_trip, _CONFIG_YAML_PATH
+
+ data = _load_yaml_round_trip(_CONFIG_YAML_PATH)
+ modes = data.setdefault("modes", {})
+ agent = modes.setdefault("agent", {})
+ mode_node = agent.setdefault(mode, {})
+ memory = mode_node.setdefault("memory", {})
+ memory[field] = value
+ _dump_yaml_round_trip(_CONFIG_YAML_PATH, data)
+
+
+async def handle_memory_open(
+ workspace: str,
+ params: dict[str, Any],
+) -> dict[str, Any]:
+ project_dir = params.get("project_dir")
+ result: dict[str, Any] = {
+ "memory_dir": os.path.join(workspace, "memory"),
+ "project_memory_dir": workspace,
+ }
+ if project_dir:
+ result["project_dir"] = project_dir
+ coding_dir = os.path.join(workspace, "coding_memory")
+ if os.path.isdir(coding_dir):
+ result["coding_memory_dir"] = coding_dir
+ return result
diff --git a/jiuwenclaw/agents/harness/common/prompt/prompt_builder.py b/jiuwenclaw/agents/harness/common/prompt/prompt_builder.py
index 4a8a819fc0..98898109dd 100644
--- a/jiuwenclaw/agents/harness/common/prompt/prompt_builder.py
+++ b/jiuwenclaw/agents/harness/common/prompt/prompt_builder.py
@@ -770,7 +770,7 @@ def _identity_prompt(language: str) -> PromptSection:
| 删除目录 | `rmdir folder` 或 PowerShell `Remove-Item -Recurse folder` | `rm -rf folder` |
| 查找文件 | `dir /s pattern` 或 PowerShell `Get-ChildItem -Recurse -Filter pattern` | `find . -name pattern` |
-**特别注意**:Windows 的 `mkdir` 不支持 `-p` 参数!在 Windows 上使用 `mkdir -p folder` 会错误创建名为 `-p` 的目录。如需创建嵌套目录,请使用 PowerShell `New-Item -ItemType Directory -Path "parent/child" -Force`,或使用 cmd 分步创建 `mkdir parent && mkdir parent\child`。
+**特别注意**:Windows 的 `mkdir` 不支持 `-p` 参数!在 Windows 上使用 `mkdir -p folder` 会错误创建名为 `-p` 的目录。如需创建嵌套目录,请使用 PowerShell `New-Item -ItemType Directory -Path "parent/child" -Force`,或使用 cmd 分步创建 `mkdir parent && mkdir parent\\child`。
## 输出文件放置规范
执行用户任务时产生的生成产物(如代码文件、文档、数据文件等),若用户未指定存放位置,请遵循以下规则:
@@ -830,7 +830,7 @@ Common command differences:
| Delete directory | `rmdir folder` or PowerShell `Remove-Item -Recurse folder` | `rm -rf folder` |
| Find file | `dir /s pattern` or PowerShell `Get-ChildItem -Recurse -Filter pattern` | `find . -name pattern` |
-**WARNING**: Windows `mkdir` does NOT support the `-p` flag! Using `mkdir -p folder` on Windows will incorrectly create a directory named `-p`. To create nested directories on Windows, use either PowerShell `New-Item -ItemType Directory -Path "parent/child" -Force` or cmd with step-by-step creation `mkdir parent && mkdir parent\child`.
+**WARNING**: Windows `mkdir` does NOT support the `-p` flag! Using `mkdir -p folder` on Windows will incorrectly create a directory named `-p`. To create nested directories on Windows, use either PowerShell `New-Item -ItemType Directory -Path "parent/child" -Force` or cmd with step-by-step creation `mkdir parent && mkdir parent\\child`.
## Output File Placement
Generated artifacts (code files, documents, data files, etc.) produced during user task execution should follow these placement rules unless the user specifies otherwise:
diff --git a/jiuwenclaw/channels/tui/frontend/src/core/commands/builtins/memory.ts b/jiuwenclaw/channels/tui/frontend/src/core/commands/builtins/memory.ts
new file mode 100644
index 0000000000..47a5d48132
--- /dev/null
+++ b/jiuwenclaw/channels/tui/frontend/src/core/commands/builtins/memory.ts
@@ -0,0 +1,660 @@
+import { addError, addInfo, makeItem } from "../helpers.js";
+import { CommandKind, type SlashCommand } from "../types.js";
+import { getEditorInfo } from "../../utils/editor.js";
+
+interface MemoryFile {
+ path: string;
+ relative_path: string;
+ kind: string;
+ exists: boolean;
+ size: number;
+ mtime: number;
+ lines: number;
+}
+
+interface MemoryEditResult {
+ path: string;
+ exists: boolean;
+ content_preview: string;
+ kind: string;
+ editable: boolean;
+}
+
+interface MemoryStatusResult {
+ current_mode: string;
+ storage_mode: string;
+ engine: string;
+ enabled: boolean;
+ proactive: boolean;
+ forbidden_enabled: boolean;
+ index?: {
+ available: boolean;
+ provider?: string | null;
+ model?: string | null;
+ files_count: number;
+ chunks_count: number;
+ dirty: boolean;
+ fts: Record<string, unknown>;
+ vector: Record<string, unknown>;
+ cache: Record<string, unknown>;
+ };
+ project_memory?: {
+ files_count: number;
+ total_chars: number;
+ max_chars: number;
+ project_dir?: string;
+ };
+ coding_memory?: {
+ files_count: number;
+ total_chars: number;
+ dir: string;
+ };
+ auto_memory?: {
+ files_count: number;
+ total_chars: number;
+ dir: string;
+ };
+ external_memory?: {
+ provider: string;
+ enabled: boolean;
+ };
+}
+
+interface MemoryToggleResult {
+ key: string;
+ old_value: boolean;
+ new_value: boolean;
+ mode_affected: string;
+ needs_restart: boolean;
+}
+
+interface MemoryOpenResult {
+ memory_dir: string;
+ project_memory_dir: string;
+ project_dir?: string;
+ coding_memory_dir?: string;
+}
+
+function formatSize(bytes: number): string {
+ if (bytes < 1024) return `${bytes} B`;
+ if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
+ return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
+}
+
+function formatTime(mtime: number): string {
+ if (!mtime) return "";
+ const diff = Date.now() / 1000 - mtime;
+ if (diff < 60) return "just now";
+ if (diff < 3600) return `${Math.floor(diff / 60)}m ago`;
+ if (diff < 86400) return `${Math.floor(diff / 3600)}h ago`;
+ return `${Math.floor(diff / 86400)}d ago`;
+}
+
+function modeToShort(mode: string): string {
+ if (mode.startsWith("code")) return "code";
+ return mode.replace("agent.", "");
+}
+
+async function showMemoryOverview(ctx: import("../types.js").CommandContext): Promise<void> {
+ const mode = modeToShort(ctx.mode);
+ try {
+ const payload = await ctx.request<MemoryStatusResult>("memory.status", {
+ detailed: true,
+ mode,
+ });
+
+ const items: { label: string; value: string; description?: string }[] = [];
+
+ items.push({ label: "Mode", value: payload.current_mode });
+ items.push({ label: "Engine", value: `${payload.engine} (${payload.storage_mode})` });
+ items.push({ label: "Enabled", value: payload.enabled ? "✓ on" : "✗ off" });
+ items.push({ label: "Proactive", value: payload.proactive ? "✓ on" : "✗ off" });
+ items.push({ label: "Forbidden Filter", value: payload.forbidden_enabled ? "✓ on" : "✗ off" });
+
+ if (payload.index) {
+ items.push({
+ label: "Index",
+ value: `Files: ${payload.index.files_count} Chunks: ${payload.index.chunks_count}`,
+ description: `FTS: ${payload.index.fts?.available ? "✓" : "✗"} Vector: ${payload.index.vector?.available ? "✓" : "✗"}`,
+ });
+ }
+
+ if (payload.project_memory) {
+ items.push({
+ label: "Project Memory",
+ value: `${payload.project_memory.files_count} files`,
+ description: `${payload.project_memory.total_chars} / ${payload.project_memory.max_chars} chars`,
+ });
+ if (payload.project_memory.project_dir) {
+ items.push({
+ label: "Project Dir",
+ value: payload.project_memory.project_dir,
+ });
+ }
+ }
+
+ if (payload.coding_memory) {
+ items.push({
+ label: "Coding Memory",
+ value: `${payload.coding_memory.files_count} files`,
+ description: `${payload.coding_memory.total_chars} chars`,
+ });
+ }
+
+ if (payload.auto_memory) {
+ items.push({
+ label: "Auto Memory",
+ value: `${payload.auto_memory.files_count} files`,
+ description: `${payload.auto_memory.total_chars} chars`,
+ });
+ }
+
+ if (payload.external_memory) {
+ items.push({
+ label: "External Memory",
+ value: `${payload.external_memory.provider} ${payload.external_memory.enabled ? "✓" : "✗"}`,
+ });
+ }
+
+ ctx.addItem(
+ makeItem(ctx.sessionId, "info", "Memory Status", "m", {
+ view: "kv",
+ title: "Memory",
+ items,
+ }),
+ );
+
+ ctx.addItem(
+ addInfo(
+ ctx.sessionId,
+ "Usage: /memory list|edit|status|toggle|open",
+ "i",
+ ),
+ );
+ } catch (err) {
+ ctx.addItem(
+ addError(ctx.sessionId, `Failed to get memory status: ${err instanceof Error ? err.message : String(err)}`),
+ );
+ }
+}
+
+async function listMemory(ctx: import("../types.js").CommandContext): Promise<void> {
+ const mode = modeToShort(ctx.mode);
+ try {
+ const payload = await ctx.request<{ files: MemoryFile[] }>("memory.list", {
+ mode,
+ });
+ const files = payload.files ?? [];
+
+ if (files.length === 0) {
+ ctx.addItem(addInfo(ctx.sessionId, "No memory files found.", "m"));
+ return;
+ }
+
+ const items = files.map((f) => ({
+ label: f.relative_path,
+ value: f.kind,
+ description: `${formatSize(f.size)} · ${f.lines} lines · ${formatTime(f.mtime)}`,
+ }));
+
+ ctx.addItem(
+ makeItem(ctx.sessionId, "info", `${files.length} memory files`, "m", {
+ view: "list",
+ title: "Memory Files",
+ items,
+ }),
+ );
+ } catch (err) {
+ ctx.addItem(
+ addError(ctx.sessionId, `Failed to list memory files: ${err instanceof Error ? err.message : String(err)}`),
+ );
+ }
+}
+
+async function editMemory(
+ ctx: import("../types.js").CommandContext,
+ args: string,
+): Promise<void> {
+ const targetPath = args.trim();
+
+ if (!targetPath) {
+ await editMemoryInteractive(ctx);
+ return;
+ }
+
+ await editMemoryByPath(ctx, targetPath);
+}
+
+async function editMemoryInteractive(
+ ctx: import("../types.js").CommandContext,
+): Promise<void> {
+ const mode = modeToShort(ctx.mode);
+
+ try {
+ const payload = await ctx.request<{ files: MemoryFile[] }>("memory.list", {
+ mode,
+ });
+ const files = payload.files ?? [];
+
+ if (files.length === 0) {
+ ctx.addItem(addInfo(ctx.sessionId, "No memory files to edit.", "m"));
+ return;
+ }
+
+ const options = files.map((f) => ({
+ label: f.relative_path,
+ description: `${f.kind} · ${f.lines} lines${f.exists ? "" : " (new)"}`,
+ }));
+
+ let selectedLabel: string | undefined;
+ try {
+ const [answer] = await ctx.askQuestions(
+ [
+ {
+ header: "Edit Memory",
+ question: "Select a memory file to edit:",
+ options,
+ },
+ ],
+ "local_command_memory_edit",
+ );
+ selectedLabel = answer?.selected_options?.[0];
+ } catch {
+ ctx.addItem(addInfo(ctx.sessionId, "Cancelled memory editing.", "i"));
+ return;
+ }
+
+ if (!selectedLabel) {
+ ctx.addItem(addInfo(ctx.sessionId, "Cancelled memory editing.", "i"));
+ return;
+ }
+
+ const selectedFile = files.find(
+ (f) => f.relative_path === selectedLabel || f.path === selectedLabel,
+ );
+
+ if (!selectedFile) {
+ ctx.addItem(addError(ctx.sessionId, `Could not find selected file: ${selectedLabel}`));
+ return;
+ }
+
+ await editMemoryByPath(ctx, selectedFile.path);
+ } catch (err) {
+ ctx.addItem(
+ addError(ctx.sessionId, `Failed to list files for edit: ${err instanceof Error ? err.message : String(err)}`),
+ );
+ }
+}
+
+async function editMemoryByPath(
+ ctx: import("../types.js").CommandContext,
+ path: string,
+): Promise<void> {
+ try {
+ const payload = await ctx.request<MemoryEditResult>("memory.edit", { path });
+
+ if (!payload.editable) {
+ ctx.addItem(addError(ctx.sessionId, `Cannot edit: ${path} — path not in allowed memory directories.`));
+ return;
+ }
+
+ if (ctx.openInEditor) {
+ ctx.openInEditor(payload.path);
+
+ const { source, value } = getEditorInfo();
+ const editorHint = source !== "default"
+ ? `(${source}="${value}")`
+ : "(default: vi)";
+
+ ctx.addItem(
+ addInfo(
+ ctx.sessionId,
+ `Finished editing ${payload.path} ${editorHint}`,
+ "m",
+ ),
+ );
+ } else {
+ ctx.addItem(
+ addInfo(
+ ctx.sessionId,
+ `Edit with: $EDITOR ${payload.path}`,
+ "i",
+ ),
+ );
+ }
+ } catch (err) {
+ ctx.addItem(
+ addError(ctx.sessionId, `Failed to edit memory file: ${err instanceof Error ? err.message : String(err)}`),
+ );
+ }
+}
+
+async function showMemoryStatus(
+ ctx: import("../types.js").CommandContext,
+): Promise<void> {
+ const mode = modeToShort(ctx.mode);
+ try {
+ const payload = await ctx.request<MemoryStatusResult>("memory.status", {
+ detailed: true,
+ mode,
+ });
+
+ const items: { label: string; value: string; description?: string }[] = [];
+
+ items.push({ label: "Current Mode", value: payload.current_mode });
+ items.push({ label: "Storage Mode", value: payload.storage_mode });
+ items.push({ label: "Engine", value: payload.engine });
+ items.push({ label: "Enabled", value: payload.enabled ? "✓ on" : "✗ off" });
+ items.push({ label: "Proactive", value: payload.proactive ? "✓ on" : "✗ off" });
+ items.push({ label: "Forbidden Filter", value: payload.forbidden_enabled ? "✓ on" : "✗ off" });
+
+ if (payload.index) {
+ items.push({ label: "Index Available", value: payload.index.available ? "✓" : "✗" });
+ items.push({ label: "Embedding Provider", value: payload.index.provider ?? "N/A" });
+ items.push({ label: "Embedding Model", value: payload.index.model ?? "N/A" });
+ items.push({ label: "Files Indexed", value: String(payload.index.files_count) });
+ items.push({ label: "Chunks", value: String(payload.index.chunks_count) });
+ items.push({ label: "Dirty", value: payload.index.dirty ? "yes" : "no" });
+ const ftsInfo = payload.index.fts as { enabled?: boolean; available?: boolean; error?: string } | undefined;
+ const vecInfo = payload.index.vector as { enabled?: boolean; available?: boolean; dims?: number; error?: string } | undefined;
+ const cacheInfo = payload.index.cache as { enabled?: boolean; entries?: number } | undefined;
+ items.push({
+ label: "FTS5",
+ value: ftsInfo?.available ? "✓ enabled" : "✗ disabled",
+ description: ftsInfo?.error,
+ });
+ items.push({
+ label: "Vector",
+ value: vecInfo?.available ? `✓ enabled (dims: ${vecInfo.dims ?? "?"})` : "✗ disabled",
+ description: vecInfo?.error,
+ });
+ items.push({
+ label: "Cache",
+ value: cacheInfo?.enabled ? `✓ ${cacheInfo.entries ?? 0} entries` : "✗ disabled",
+ });
+ }
+
+ if (payload.project_memory) {
+ items.push({
+ label: "Project Memory Files",
+ value: String(payload.project_memory.files_count),
+ });
+ items.push({
+ label: "Project Memory Chars",
+ value: `${payload.project_memory.total_chars} / ${payload.project_memory.max_chars}`,
+ });
+ if (payload.project_memory.project_dir) {
+ items.push({
+ label: "Project Dir",
+ value: payload.project_memory.project_dir,
+ });
+ }
+ }
+
+ if (payload.coding_memory) {
+ items.push({
+ label: "Coding Memory Files",
+ value: String(payload.coding_memory.files_count),
+ });
+ items.push({
+ label: "Coding Memory Chars",
+ value: String(payload.coding_memory.total_chars),
+ });
+ if (payload.coding_memory.dir) {
+ items.push({
+ label: "Coding Memory Dir",
+ value: payload.coding_memory.dir,
+ });
+ }
+ }
+
+ if (payload.auto_memory) {
+ items.push({
+ label: "Auto Memory Files",
+ value: String(payload.auto_memory.files_count),
+ });
+ items.push({
+ label: "Auto Memory Chars",
+ value: String(payload.auto_memory.total_chars),
+ });
+ if (payload.auto_memory.dir) {
+ items.push({
+ label: "Auto Memory Dir",
+ value: payload.auto_memory.dir,
+ });
+ }
+ }
+
+ if (payload.external_memory) {
+ items.push({
+ label: "External Memory",
+ value: `${payload.external_memory.provider} ${payload.external_memory.enabled ? "✓" : "✗"}`,
+ });
+ }
+
+ ctx.addItem(
+ makeItem(ctx.sessionId, "info", "Memory Status (detailed)", "m", {
+ view: "kv",
+ title: "Memory Status",
+ items,
+ }),
+ );
+ } catch (err) {
+ ctx.addItem(
+ addError(ctx.sessionId, `Failed to get memory status: ${err instanceof Error ? err.message : String(err)}`),
+ );
+ }
+}
+
+const TOGGLE_KEYS = [
+ { key: "memory_enabled", label: "Enabled", config_path: "modes.agent.<mode>.memory.enabled" },
+ { key: "memory_proactive", label: "Proactive", config_path: "modes.agent.<mode>.memory.is_proactive" },
+ { key: "memory_forbidden_enabled", label: "Forbidden Filter", config_path: "memory.forbidden_memory_definition.enabled" },
+];
+
+async function toggleMemory(
+ ctx: import("../types.js").CommandContext,
+ args: string,
+): Promise<void> {
+ const key = args.trim();
+
+ if (!key) {
+ await showToggleList(ctx);
+ return;
+ }
+
+ await toggleByKey(ctx, key);
+}
+
+async function showToggleList(
+ ctx: import("../types.js").CommandContext,
+): Promise<void> {
+ const mode = modeToShort(ctx.mode);
+ try {
+ const payload = await ctx.request<MemoryStatusResult>("memory.status", {
+ mode,
+ });
+
+ const items = TOGGLE_KEYS.map((t) => {
+ let current: boolean;
+ if (t.key === "memory_enabled") current = payload.enabled;
+ else if (t.key === "memory_proactive") current = payload.proactive;
+ else current = payload.forbidden_enabled;
+
+ return {
+ label: t.key,
+ value: `${t.label} ${current ? "✓ on" : "✗ off"}`,
+ description: t.config_path,
+ };
+ });
+
+ ctx.addItem(
+ makeItem(ctx.sessionId, "info", "Memory Toggles", "m", {
+ view: "kv",
+ title: "Memory Toggles",
+ items,
+ }),
+ );
+
+ ctx.addItem(
+ addInfo(
+ ctx.sessionId,
+ `Usage: /memory toggle <key> (affects mode: ${mode})`,
+ "i",
+ ),
+ );
+ } catch (err) {
+ ctx.addItem(
+ addError(ctx.sessionId, `Failed to get toggle status: ${err instanceof Error ? err.message : String(err)}`),
+ );
+ }
+}
+
+async function toggleByKey(
+ ctx: import("../types.js").CommandContext,
+ key: string,
+): Promise<void> {
+ const validKeys = TOGGLE_KEYS.map((t) => t.key);
+ if (!validKeys.includes(key)) {
+ ctx.addItem(
+ addError(ctx.sessionId, `Unknown toggle key: ${key}. Valid keys: ${validKeys.join(", ")}`),
+ );
+ return;
+ }
+
+ const mode = modeToShort(ctx.mode);
+ try {
+ const payload = await ctx.request<MemoryToggleResult>("memory.toggle", {
+ key,
+ mode,
+ });
+
+ const label = TOGGLE_KEYS.find((t) => t.key === key)?.label ?? key;
+ ctx.addItem(
+ addInfo(
+ ctx.sessionId,
+ `${label}: ${payload.old_value ? "on" : "off"} → ${payload.new_value ? "on" : "off"}${payload.needs_restart ? " (restart session to apply)" : ""}`,
+ "m",
+ ),
+ );
+ } catch (err) {
+ ctx.addItem(
+ addError(ctx.sessionId, `Toggle failed: ${err instanceof Error ? err.message : String(err)}`),
+ );
+ }
+}
+
+async function openMemoryDir(
+ ctx: import("../types.js").CommandContext,
+): Promise<void> {
+ try {
+ const payload = await ctx.request<MemoryOpenResult>("memory.open", {});
+
+ const items: { label: string; value: string }[] = [];
+ items.push({ label: "Memory Dir", value: payload.memory_dir });
+ items.push({ label: "Project Dir", value: payload.project_memory_dir });
+ if (payload.project_dir) {
+ items.push({ label: "User Project Dir", value: payload.project_dir });
+ }
+ if (payload.coding_memory_dir) {
+ items.push({ label: "Coding Memory Dir", value: payload.coding_memory_dir });
+ }
+
+ ctx.addItem(
+ makeItem(ctx.sessionId, "info", "Memory Directories", "m", {
+ view: "kv",
+ title: "Memory Open",
+ items,
+ }),
+ );
+
+ ctx.addItem(
+ addInfo(
+ ctx.sessionId,
+ `Open with: open ${payload.memory_dir} (macOS) | xdg-open ${payload.memory_dir} (Linux)`,
+ "i",
+ ),
+ );
+ } catch (err) {
+ ctx.addItem(
+ addError(ctx.sessionId, `Failed to get memory directories: ${err instanceof Error ? err.message : String(err)}`),
+ );
+ }
+}
+
+export function createMemoryCommand(): SlashCommand {
+ return {
+ name: "memory",
+ altNames: ["mem"],
+ description: "Edit memory files (list, edit, status, toggle, open)",
+ usage: "/memory [list|edit|status|toggle|open] [args]",
+ example: "/memory edit",
+ kind: CommandKind.BUILT_IN,
+ takesArgs: true,
+ action: async (ctx) => {
+ await editMemoryInteractive(ctx);
+ },
+ completion: async () => {
+ return ["list", "edit", "status", "toggle", "open"];
+ },
+ subCommands: [
+ {
+ name: "list",
+ description: "List all memory files",
+ usage: "/memory list",
+ example: "/memory list",
+ kind: CommandKind.BUILT_IN,
+ takesArgs: false,
+ action: async (ctx) => {
+ await listMemory(ctx);
+ },
+ },
+ {
+ name: "edit",
+ description: "Edit a memory file (interactive selection if no path given)",
+ usage: "/memory edit [path]",
+ example: "/memory edit memory/MEMORY.md",
+ kind: CommandKind.BUILT_IN,
+ takesArgs: true,
+ action: async (ctx, args) => {
+ await editMemory(ctx, args);
+ },
+ completion: async () => ["memory/MEMORY.md", "coding_memory/MEMORY.md"],
+ },
+ {
+ name: "status",
+ description: "Show detailed memory system status",
+ usage: "/memory status",
+ example: "/memory status",
+ kind: CommandKind.BUILT_IN,
+ takesArgs: false,
+ action: async (ctx) => {
+ await showMemoryStatus(ctx);
+ },
+ },
+ {
+ name: "toggle",
+ description: "Toggle memory settings (memory_enabled, memory_proactive, memory_forbidden_enabled)",
+ usage: "/memory toggle [key]",
+ example: "/memory toggle memory_enabled",
+ kind: CommandKind.BUILT_IN,
+ takesArgs: true,
+ action: async (ctx, args) => {
+ await toggleMemory(ctx, args);
+ },
+ completion: async () => ["memory_enabled", "memory_proactive", "memory_forbidden_enabled"],
+ },
+ {
+ name: "open",
+ description: "Show memory directory paths",
+ usage: "/memory open",
+ example: "/memory open",
+ kind: CommandKind.BUILT_IN,
+ takesArgs: false,
+ action: async (ctx) => {
+ await openMemoryDir(ctx);
+ },
+ },
+ ],
+ };
+}
diff --git a/jiuwenclaw/channels/tui/frontend/src/core/commands/registry.ts b/jiuwenclaw/channels/tui/frontend/src/core/commands/registry.ts
index 61d837b91e..5f5aa8809c 100644
--- a/jiuwenclaw/channels/tui/frontend/src/core/commands/registry.ts
+++ b/jiuwenclaw/channels/tui/frontend/src/core/commands/registry.ts
@@ -18,6 +18,7 @@ import { createHotkeyCommand } from "./builtins/hotkey.js";
import { createInitCommand } from "./builtins/init.js";
import { createModelCommand } from "./builtins/model.js";
import { createMcpCommand } from "./builtins/mcp.js";
+import { createMemoryCommand } from "./builtins/memory.js";
import { createModeCommand } from "./builtins/mode.js";
import { createPermissionsCommand } from "./builtins/permissions.js";
import { createPlanCommand } from "./builtins/plan.js";
@@ -57,6 +58,7 @@ export function createBuiltinCommands(): SlashCommand[] {
createThemeCommand(),
createWorkspaceCommand(),
createHotkeyCommand(),
+ createMemoryCommand(),
];
return commands;
diff --git a/jiuwenclaw/channels/tui/frontend/src/core/commands/types.ts b/jiuwenclaw/channels/tui/frontend/src/core/commands/types.ts
index 649f31ad16..3a4c42eca1 100644
--- a/jiuwenclaw/channels/tui/frontend/src/core/commands/types.ts
+++ b/jiuwenclaw/channels/tui/frontend/src/core/commands/types.ts
@@ -73,6 +73,7 @@ export interface CommandContext {
focusKey?: string,
configPayload?: Record<string, unknown> & { schema?: ConfigItemSchema[] },
) => void;
+ openInEditor?: (filePath: string) => void;
}
export interface SlashCommand {
diff --git a/jiuwenclaw/channels/tui/frontend/src/ui/app-screen.ts b/jiuwenclaw/channels/tui/frontend/src/ui/app-screen.ts
index 68ad3a58e8..ec028bd5ea 100644
--- a/jiuwenclaw/channels/tui/frontend/src/ui/app-screen.ts
+++ b/jiuwenclaw/channels/tui/frontend/src/ui/app-screen.ts
@@ -10,9 +10,10 @@ import {
TUI,
matchesKey,
} from "@mariozechner/pi-tui";
-import { statSync } from "node:fs";
import { spawnSync } from "node:child_process";
+import { statSync } from "node:fs";
import type { CliPiAppState } from "../app-state.js";
+import { openFileInEditor as openInExternalEditor } from "../core/utils/editor.js";
import {
extractAttachmentsFromText,
extractFilePathsFromPaste,
@@ -788,6 +789,9 @@ export class AppScreen implements Component, Focusable {
enterConfigEditor: (focusKey, configPayload) => {
this.openConfigEditor(focusKey, configPayload);
},
+ openInEditor: (filePath: string) => {
+ openInExternalEditor(this.tui, filePath);
+ },
});
} finally {
this.clearPendingSubmittedInput();
diff --git a/jiuwenclaw/cli/src/core/utils/editor.ts b/jiuwenclaw/cli/src/core/utils/editor.ts
new file mode 100644
index 0000000000..2a74cfe6b0
--- /dev/null
+++ b/jiuwenclaw/cli/src/core/utils/editor.ts
@@ -0,0 +1,130 @@
+import { spawnSync, type SpawnSyncOptions, type SpawnSyncReturns } from "node:child_process";
+import { basename } from "node:path";
+import type { TUI } from "@mariozechner/pi-tui";
+
+const GUI_EDITORS = [
+ "code",
+ "cursor",
+ "windsurf",
+ "codium",
+ "subl",
+ "atom",
+ "notepad",
+ "notepad++",
+ "gedit",
+ "kate",
+ "mousepad",
+];
+
+const GUI_EDITOR_WAIT_FLAGS: Record<string, string[]> = {
+ code: ["-w"],
+ cursor: ["-w"],
+ windsurf: ["-w"],
+ codium: ["-w"],
+ subl: ["--wait"],
+ atom: ["--wait"],
+};
+
+export function getExternalEditor(): string {
+ if (process.env.VISUAL?.trim()) return process.env.VISUAL.trim();
+ if (process.env.EDITOR?.trim()) return process.env.EDITOR.trim();
+ if (process.platform === "win32") return "start /wait notepad";
+ return "vi";
+}
+
+export function getEditorInfo(): { source: string; value: string } {
+ if (process.env.VISUAL) return { source: "$VISUAL", value: process.env.VISUAL };
+ if (process.env.EDITOR) return { source: "$EDITOR", value: process.env.EDITOR };
+ return {
+ source: "default",
+ value: process.platform === "win32" ? "start /wait notepad" : "vi",
+ };
+}
+
+export function isGuiEditor(editor: string): boolean {
+ const base = basename(editor.split(" ")[0] ?? "");
+ return GUI_EDITORS.some((gui) => base.includes(gui));
+}
+
+export function parseEditorCommand(editor: string): { cmd: string; args: string[] } {
+ const parts = editor.split(/\s+/);
+ const cmd = parts[0];
+ const baseArgs = parts.slice(1);
+
+ const waitArgs = GUI_EDITOR_WAIT_FLAGS[cmd];
+ if (waitArgs && !baseArgs.some((a) => waitArgs.includes(a))) {
+ return { cmd, args: [...waitArgs, ...baseArgs] };
+ }
+
+ return { cmd, args: baseArgs };
+}
+
+function spawnFailed(result: SpawnSyncReturns<string | Buffer>): boolean {
+ return result.status !== 0 || result.error != null;
+}
+
+export function openFileInEditor(tui: TUI, filePath: string): void {
+ const editor = getExternalEditor();
+ const { cmd, args } = parseEditorCommand(editor);
+ const gui = isGuiEditor(editor);
+
+ tui.stop();
+
+ try {
+ if (!gui) {
+ process.stdout.write("\x1b[?1049h");
+ process.stdout.write("\x1b[2J\x1b[H");
+ process.stdout.write("\x1b[?25h");
+
+ if (process.stdin.setRawMode) {
+ process.stdin.setRawMode(false);
+ }
+ process.stdin.resume();
+ }
+
+ const result = spawnEditor(cmd, args, filePath);
+ if (spawnFailed(result)) {
+ spawnFallback(filePath);
+ }
+ } finally {
+ if (!gui) {
+ process.stdout.write("\x1b[?1049l");
+ }
+
+ tui.start();
+ tui.requestRender(true);
+ }
+}
+
+function spawnEditor(cmd: string, args: string[], filePath: string): SpawnSyncReturns<string | Buffer> {
+ const spawnOptions: SpawnSyncOptions = { stdio: "inherit" };
+ const fullArgs = [...args, filePath];
+
+ if (process.platform === "win32") {
+ if (cmd === "start") {
+ // Windows start command: start /wait "title" program args
+ // An empty title "" prevents the first quoted arg from being treated as window title
+ // /wait must remain unquoted — it's a flag, not an argument
+ const waitFlag = fullArgs[0] === "/wait" ? "/wait " : "";
+ const programArgs = waitFlag ? fullArgs.slice(1) : fullArgs;
+ const quoted = programArgs.map((a) => `"${a}"`).join(" ");
+ return spawnSync(`start ${waitFlag}"" ${quoted}`, { ...spawnOptions, shell: true });
+ }
+ // shell: true required for .cmd/.bat files (code.cmd, cursor.cmd)
+ const quoted = fullArgs.map((a) => `"${a}"`).join(" ");
+ return spawnSync(`${cmd} ${quoted}`, { ...spawnOptions, shell: true });
+ }
+
+ // POSIX: direct argv spawn — no shell, prevents command injection
+ return spawnSync(cmd, fullArgs, spawnOptions);
+}
+
+function spawnFallback(filePath: string): SpawnSyncReturns<string | Buffer> {
+ const spawnOptions: SpawnSyncOptions = { stdio: "inherit" };
+
+ if (process.platform === "win32") {
+ return spawnSync(`start /wait "" notepad "${filePath}"`, { ...spawnOptions, shell: true });
+ }
+
+ return spawnSync("vi", [filePath], spawnOptions);
+}
\ No newline at end of file
diff --git a/jiuwenclaw/gateway/channel_manager/tui/tui_connect.py b/jiuwenclaw/gateway/channel_manager/tui/tui_connect.py
index 5401cce72b..c5923df9aa 100644
--- a/jiuwenclaw/gateway/channel_manager/tui/tui_connect.py
+++ b/jiuwenclaw/gateway/channel_manager/tui/tui_connect.py
@@ -1343,6 +1343,91 @@ def register_cli_handlers(bind: CliHandlersBindParams) -> None:
channel.register_local_handler(path, "history.get", _history_get)
channel.register_local_handler(path, "command.model", _command_model)
+ # ── Memory RPC handlers ────────────────────────────────────────────
+ from jiuwenclaw.agents.harness.common.memory_rpc import (
+ handle_memory_list,
+ handle_memory_edit,
+ handle_memory_status,
+ handle_memory_toggle,
+ handle_memory_open,
+ )
+ from jiuwenclaw.common.utils import get_agent_workspace_dir
+
+ def _resolve_project_dir(params):
+ trusted_dirs = params.get("trusted_dirs")
+ if isinstance(trusted_dirs, list) and trusted_dirs:
+ return str(trusted_dirs[0])
+ cwd = params.get("cwd")
+ if isinstance(cwd, str) and cwd:
+ return cwd
+ return None
+
+ async def _memory_list(ws, req_id, params, session_id):
+ workspace = str(get_agent_workspace_dir())
+ mode = params.get("mode", "plan")
+ project_dir = _resolve_project_dir(params)
+ if project_dir:
+ params = {**params, "project_dir": project_dir}
+ try:
+ result = await handle_memory_list(workspace, mode, params)
+ await channel.send_response(ws, req_id, ok=True, payload=result)
+ except Exception as exc:
+ logger.warning("[memory.list] %s", exc)
+ await channel.send_response(ws, req_id, ok=False, error=str(exc), code="INTERNAL_ERROR")
+
+ async def _memory_edit(ws, req_id, params, session_id):
+ workspace = str(get_agent_workspace_dir())
+ project_dir = _resolve_project_dir(params)
+ if project_dir:
+ params = {**params, "project_dir": project_dir}
+ try:
+ result = await handle_memory_edit(workspace, params)
+ await channel.send_response(ws, req_id, ok=True, payload=result)
+ except Exception as exc:
+ logger.warning("[memory.edit] %s", exc)
+ await channel.send_response(ws, req_id, ok=False, error=str(exc), code="INTERNAL_ERROR")
+
+ async def _memory_status(ws, req_id, params, session_id):
+ workspace = str(get_agent_workspace_dir())
+ mode = params.get("mode", "plan")
+ project_dir = _resolve_project_dir(params)
+ if project_dir:
+ params = {**params, "project_dir": project_dir}
+ try:
+ result = await handle_memory_status(workspace, mode, params)
+ await channel.send_response(ws, req_id, ok=True, payload=result)
+ except Exception as exc:
+ logger.warning("[memory.status] %s", exc)
+ await channel.send_response(ws, req_id, ok=False, error=str(exc), code="INTERNAL_ERROR")
+
+ async def _memory_toggle(ws, req_id, params, session_id):
+ workspace = str(get_agent_workspace_dir())
+ mode = params.get("mode", "plan")
+ try:
+ result = await handle_memory_toggle(workspace, mode, params)
+ await channel.send_response(ws, req_id, ok=True, payload=result)
+ except Exception as exc:
+ logger.warning("[memory.toggle] %s", exc)
+ await channel.send_response(ws, req_id, ok=False, error=str(exc), code="INTERNAL_ERROR")
+
+ async def _memory_open(ws, req_id, params, session_id):
+ workspace = str(get_agent_workspace_dir())
+ project_dir = _resolve_project_dir(params)
+ if project_dir:
+ params = {**params, "project_dir": project_dir}
+ try:
+ result = await handle_memory_open(workspace, params)
+ await channel.send_response(ws, req_id, ok=True, payload=result)
+ except Exception as exc:
+ logger.warning("[memory.open] %s", exc)
+ await channel.send_response(ws, req_id, ok=False, error=str(exc), code="INTERNAL_ERROR")
+
+ channel.register_local_handler(path, "memory.list", _memory_list)
+ channel.register_local_handler(path, "memory.edit", _memory_edit)
+ channel.register_local_handler(path, "memory.status", _memory_status)
+ channel.register_local_handler(path, "memory.toggle", _memory_toggle)
+ channel.register_local_handler(path, "memory.open", _memory_open)
+
def build_cli_route_binding(bind: CliRouteBindParams) -> GatewayRouteBinding:
def _install(channel: Any) -> None: