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: 1. principle, tone, heartbeat都配置了双语版本,更改了位置 2. 在init时询问语言,再选择相应的md 3. 填充prompt 4. 压缩参数从config读取

Haowei_Du1a5bf6c197cc
diff --git "a/docs/\346\231\272\350\203\275\344\275\223.md" "b/docs/\346\231\272\350\203\275\344\275\223.md"
index 4c5f32005e..973f4108c5 100644
--- "a/docs/\346\231\272\350\203\275\344\275\223.md"
+++ "b/docs/\346\231\272\350\203\275\344\275\223.md"
@@ -8,10 +8,13 @@
```
workspace/
-├── HEARTBEAT.md # 心跳任务配置(预置模板,用户可编辑)
├── agent-data.json # Agent 列表元数据(动态生成)
├── skills_state.json # Skill 安装/市场状态(动态生成)
├── agent/ # Agent 工作区
+│ ├── home/ # 用户可编辑主页配置(init 时从包内模板按语言复制)
+│ │ ├── HEARTBEAT.md # 心跳任务(来自 HEARTBEAT_ZH/EN.md)
+│ │ ├── PRINCIPLE.md # 原则(来自 PRINCIPLE_ZH/EN.md)
+│ │ └── TONE.md # 语气(来自 TONE_ZH/EN.md)
│ ├── memory/ # 记忆系统
│ │ ├── USER.md # 用户身份信息(用户/Agent 创建)
│ │ ├── MEMORY.md # 长期记忆(用户/Agent 创建)
@@ -37,7 +40,7 @@ workspace/
| 路径 | 说明 |
|------|------|
-| `HEARTBEAT.md` | 心跳任务模板。若存在且「活跃的任务项」不为空,Agent 会按心跳间隔读取并执行;否则仅返回 `HEARTBEAT_OK`。用户可在 Web 端编辑。 |
+| `agent/home/HEARTBEAT.md` | 心跳任务模板(包内 `resources/agent/HEARTBEAT_ZH.md` 或 `HEARTBEAT_EN.md`,初始化时按所选语言复制)。若存在且内容有效,Agent 会按心跳间隔读取并执行;否则仅返回 `HEARTBEAT_OK`。用户可在 Web 端编辑。 |
| `agent/SOUL.md` | Agent 灵魂/人格描述,用于系统提示词。 |
| `agent/skills/` | 内置技能目录。每个技能包含 `SKILL.md`、`prompts/`、`references/` 等。 |
| `agent/skills/_marketplace/` | 技能市场仓库克隆目录,预置为空,用于存放从市场安装的插件。 |
diff --git a/jiuwenclaw/agentserver/interface.py b/jiuwenclaw/agentserver/interface.py
index 8e3d43f109..ef43487436 100644
--- a/jiuwenclaw/agentserver/interface.py
+++ b/jiuwenclaw/agentserver/interface.py
@@ -191,33 +191,40 @@ class JiuWenClaw:
# 创建 ReActAgentConfig
agent_config = ReActAgentConfig(**config)
- # 上下文压缩卸载
- processors = [
- (
- "MessageOffloader",
- MessageOffloaderConfig(
- messages_threshold=40,
- tokens_threshold=20000,
- large_message_threshold=1000,
- trim_size=500,
- offload_message_type=["tool"],
- keep_last_round=False,
- )
- ),
- (
- "DialogueCompressor",
- DialogueCompressorConfig(
- messages_threshold=40,
- tokens_threshold=50000,
- model=ModelRequestConfig(
- model=config["model_name"]
- ),
- model_client=config["model_client_config"],
- keep_last_round=False,
+
+ config_base = get_config()
+ memory_compression_config = config_base.get('memory_compression', {}).copy()
+
+ if memory_compression_config.get("enabled", False):
+ message_offloader_config = memory_compression_config.get("message_offloader_config", {}).copy()
+ dialogue_compressor_config = memory_compression_config.get("dialogue_compressor_config", {}).copy()
+ # 上下文压缩卸载
+ processors = [
+ (
+ "MessageOffloader",
+ MessageOffloaderConfig(
+ messages_threshold=message_offloader_config.get("messages_threshold", 40),
+ tokens_threshold=message_offloader_config.get("tokens_threshold", 20000),
+ large_message_threshold=message_offloader_config.get("large_message_threshold", 1000),
+ trim_size=message_offloader_config.get("trim_size", 500),
+ offload_message_type=["tool"],
+ keep_last_round=message_offloader_config.get("keep_last_round", False),
+ )
+ ),
+ (
+ "DialogueCompressor",
+ DialogueCompressorConfig(
+ messages_threshold=dialogue_compressor_config.get("messages_threshold", 40),
+ tokens_threshold=dialogue_compressor_config.get("tokens_threshold", 50000),
+ model=ModelRequestConfig(
+ model=config["model_name"]
+ ),
+ model_client=config["model_client_config"],
+ keep_last_round=dialogue_compressor_config.get("keep_last_round", False),
+ )
)
- )
- ]
- agent_config.configure_context_processors(processors)
+ ]
+ agent_config.configure_context_processors(processors)
return agent_config
async def create_instance(self, config: dict[str, Any] | None = None) -> None:
diff --git a/jiuwenclaw/agentserver/permissions/checker.py b/jiuwenclaw/agentserver/permissions/checker.py
index 3d09353b20..c02e1e7ecb 100644
--- a/jiuwenclaw/agentserver/permissions/checker.py
+++ b/jiuwenclaw/agentserver/permissions/checker.py
@@ -298,8 +298,8 @@ class ExternalDirectoryChecker:
workspace = self._workspace_root
if workspace is None:
try:
- from jiuwenclaw.utils import USER_WORKSPACE_DIR
- workspace = USER_WORKSPACE_DIR / "workspace"
+ from jiuwenclaw.utils import get_workspace_dir
+ workspace = get_workspace_dir()
except ImportError:
return None
workdir = tool_args.get("workdir", ".")
diff --git a/jiuwenclaw/agentserver/prompt_builder.py b/jiuwenclaw/agentserver/prompt_builder.py
index 88817e0fa1..4ff6441e76 100644
--- a/jiuwenclaw/agentserver/prompt_builder.py
+++ b/jiuwenclaw/agentserver/prompt_builder.py
@@ -262,14 +262,14 @@ When valuable information is discovered during the conversation, it can be recor
sections.append(memory_prompt)
sections.append("")
- profile_content = _read_file(USER_WORKSPACE_DIR / "workspace" / "agent" / "memory" / "USER.md")
+ profile_content = _read_file(MEMORY_DIR / "USER.md")
if profile_content:
sections.append("## Current Identity and User Profile")
sections.append("What you know about yourself and the user:")
sections.append(profile_content)
sections.append("")
- memory_content = _read_file(USER_WORKSPACE_DIR / "workspace" / "agent" / "memory" / "MEMORY.md")
+ memory_content = _read_file(MEMORY_DIR / "MEMORY.md")
if memory_content:
sections.append("## Long-term Memory")
sections.append("Important information from previous sessions:")
@@ -278,7 +278,7 @@ When valuable information is discovered during the conversation, it can be recor
beijing_tz = timezone(timedelta(hours=8))
today = datetime.now(tz=beijing_tz).strftime("%Y-%m-%d")
- today_content = _read_file(USER_WORKSPACE_DIR / "workspace" / "agent" / "memory" / f"{today}.md")
+ today_content = _read_file(MEMORY_DIR / f"{today}.md")
if today_content:
sections.append("## Today's Session Record")
sections.append(today_content)
@@ -527,6 +527,10 @@ Write or save all files under this dir, unless user ask you to operate in other
def _principle_prompt(language: str) -> str:
+ """优先从 ~/.jiuwenclaw/agent/home/PRINCIPLE.md 读取;缺失时回退内置文案。"""
+ file_content = _read_file(str(HOME_DIR / "PRINCIPLE.md"))
+ if file_content:
+ return file_content
if language == "zh":
return """## 执行任务的原则
@@ -536,8 +540,7 @@ def _principle_prompt(language: str) -> str:
- **尽量不拒绝** 尽量满足用户的合理请求。只有在涉及违法、有害、侵犯他人权益或超出你能力范围时,才明确说明原因并拒绝。
- **隐私守护** 永远守护用户的隐私,除非用户明确要求分享。
"""
- else:
- return """## Execution Principles
+ return """## Execution Principles
- **Get straight to the point** Skip "Sure", "Happy to help"—just start doing the work.
- **Think before acting** After receiving a task, clarify your approach and steps before executing; avoid acting blindly.
@@ -602,6 +605,10 @@ def _time_prompt(language: str) -> str:
def _tone_prompt(language: str) -> str:
+ """优先从 ~/.jiuwenclaw/agent/home/TONE.md 读取;缺失时回退内置文案。"""
+ file_content = _read_file(str(HOME_DIR / "TONE.md"))
+ if file_content:
+ return file_content
if language == "zh":
return """## 回复的原则
@@ -613,8 +620,7 @@ def _tone_prompt(language: str) -> str:
- **使用表情** 在合适处使用表情,让回复更有生气,但不过度。
- **不废话、贴心** 做一个不废话的助手,永远贴心、永远热情。不要过度谄媚,也不要过度高冷。
"""
- else:
- return """## Reply Principles
+ return """## Reply Principles
Reply like a real human—warm, friendly, and a bit playful:
diff --git a/jiuwenclaw/agentserver/skill_manager.py b/jiuwenclaw/agentserver/skill_manager.py
index d9f84008a1..8ed0adc732 100644
--- a/jiuwenclaw/agentserver/skill_manager.py
+++ b/jiuwenclaw/agentserver/skill_manager.py
@@ -940,10 +940,9 @@ class SkillManager:
mirrors: list[Path] = []
try:
source_repo_root = Path(__file__).resolve().parents[2]
- source_skills_dir = source_repo_root / "workspace" / "agent" / "skills"
- if source_skills_dir.resolve() != _SKILLS_DIR.resolve():
- mirrors.append(source_skills_dir)
- source_resources_skills_dir = source_repo_root / "jiuwenclaw" / "resources" / "workspace" / "agent" / "skills"
+ source_resources_skills_dir = (
+ source_repo_root / "jiuwenclaw" / "resources" / "agent" / "skills"
+ )
if source_resources_skills_dir.exists() and source_resources_skills_dir.resolve() != _SKILLS_DIR.resolve():
mirrors.append(source_resources_skills_dir)
except Exception:
@@ -990,7 +989,8 @@ class SkillManager:
workspace_roots: set[Path] = {_AGENT_ROOT.resolve()}
for mirror_root in self._get_mirror_skills_dirs():
try:
- workspace_roots.add(mirror_root.parent.parent.parent.resolve())
+ # mirror_root = .../agent/skills → agent 根目录为其 parent
+ workspace_roots.add(mirror_root.parent.resolve())
except Exception:
continue
for workspace_root in workspace_roots:
diff --git a/jiuwenclaw/channel/web_channel.py b/jiuwenclaw/channel/web_channel.py
index e500f533c9..1dc1befea0 100644
--- a/jiuwenclaw/channel/web_channel.py
+++ b/jiuwenclaw/channel/web_channel.py
@@ -20,7 +20,7 @@ from urllib.parse import parse_qs, urlparse
import aiohttp
-from jiuwenclaw.utils import logger
+from jiuwenclaw.utils import get_workspace_dir, logger
from jiuwenclaw.channel.base import BaseChannel, ChannelMetadata, RobotMessageRouter
from jiuwenclaw.schema.message import Message, Mode, ReqMethod
@@ -182,7 +182,7 @@ class WebChannel(BaseChannel):
return params
downloaded_files = []
- workspace_dir = os.path.expanduser("~/.jiuwenclaw/workspace")
+ workspace_dir = str(get_workspace_dir())
for file_info in files:
if not isinstance(file_info, dict):
diff --git a/jiuwenclaw/channel/xiaoyi_channel.py b/jiuwenclaw/channel/xiaoyi_channel.py
index 07ae8bb3c1..444bae68e3 100644
--- a/jiuwenclaw/channel/xiaoyi_channel.py
+++ b/jiuwenclaw/channel/xiaoyi_channel.py
@@ -36,7 +36,7 @@ class XiaoyiChannelConfig:
enable_streaming: bool = True
# Push notification configuration
uid: str = ""
- api_key = ""
+ api_key: str = ""
api_id: str = ""
push_id: str = ""
push_url: str = ""
diff --git a/jiuwenclaw/config.py b/jiuwenclaw/config.py
index fce071cf0c..d1662059d3 100644
--- a/jiuwenclaw/config.py
+++ b/jiuwenclaw/config.py
@@ -129,6 +129,18 @@ def update_preferred_language_in_config(lang: str) -> None:
_dump_yaml_round_trip(_CONFIG_YAML_PATH, data)
+def set_preferred_language_in_config_file(config_path: Path, lang: str) -> None:
+ """将 preferred_language 写入指定 config.yaml(用于 init 等尚未绑定全局路径的场景)。"""
+ lang = str(lang or "zh").strip().lower()
+ if lang not in ("zh", "en"):
+ lang = "zh"
+ if not config_path.exists():
+ return
+ data = _load_yaml_round_trip(config_path)
+ data["preferred_language"] = lang
+ _dump_yaml_round_trip(config_path, data)
+
+
def update_browser_in_config(updates: dict[str, Any]) -> None:
"""只更新 browser 段(如 chrome_path)并写回。"""
data = _load_yaml_round_trip(_CONFIG_YAML_PATH)
diff --git a/jiuwenclaw/gateway/cron/controller.py b/jiuwenclaw/gateway/cron/controller.py
index 3fe4e7a7ef..5099b3a656 100644
--- a/jiuwenclaw/gateway/cron/controller.py
+++ b/jiuwenclaw/gateway/cron/controller.py
@@ -178,8 +178,8 @@ class CronController:
name: str,
cron_expr: str,
timezone: str,
- targets: str,
description: str,
+ targets: str = "",
enabled: bool = True,
wake_offset_seconds: int | None = None,
) -> dict[str, Any]:
@@ -290,7 +290,6 @@ class CronController:
"type": "string",
"enum": [e.value for e in CronTargetChannel],
"description": "推送频道:web=网页, feishu=飞书, whatsapp=WhatsApp, wecom=企业微信。不传则使用当前请求来源频道",
- "default": self._target_channel.value,
},
"enabled": {
"type": "boolean",
diff --git a/jiuwenclaw/init_workspace.py b/jiuwenclaw/init_workspace.py
index 646c89ccab..606b18a3ab 100644
--- a/jiuwenclaw/init_workspace.py
+++ b/jiuwenclaw/init_workspace.py
@@ -1,14 +1,15 @@
"""CLI for initializing runtime data into ~/.jiuwenclaw.
无论是通过 pip/whl 安装,还是在源码目录里直接运行:
-- 都可以通过运行本脚本,把内置的 config.yaml / .env.template
- 以及 workspace 模板复制到用户主目录 ~/.jiuwenclaw 下,
- 之后运行 app.py 时会从该目录读取和写入配置。
+- 运行本脚本会先询问语言偏好(zh/en),写入 config 的 preferred_language,
+ 并将对应语言的 PRINCIPLE/TONE/HEARTBEAT 模板复制为 ~/.jiuwenclaw/agent/home/ 下 PRINCIPLE.md、TONE.md、HEARTBEAT.md;
+- 同时复制 config.yaml、.env.template、agent 其余模板等到 ~/.jiuwenclaw。
"""
from __future__ import annotations
import logging
+import sys
from jiuwenclaw.utils import init_user_workspace
@@ -20,6 +21,8 @@ def main() -> None:
)
target = init_user_workspace(overwrite=True)
+ if target == "cancelled":
+ sys.exit(1)
print(f"[jiuwenclaw-init] initialized: {target}")
diff --git a/jiuwenclaw/resources/agent/HEARTBEAT_EN.md b/jiuwenclaw/resources/agent/HEARTBEAT_EN.md
new file mode 100644
index 0000000000..087dabafdd
--- /dev/null
+++ b/jiuwenclaw/resources/agent/HEARTBEAT_EN.md
@@ -0,0 +1,10 @@
+<!-- Heartbeat tasks -->
+
+<!-- Add periodic tasks you want JiuwenClaw to perform in this markdown file -->
+
+
+<!-- Examples -->
+
+<!-- 1. Check server status -->
+
+<!-- 2. Clear buffers / cache -->
diff --git a/jiuwenclaw/resources/workspace/HEARTBEAT.md b/jiuwenclaw/resources/agent/HEARTBEAT_ZH.md
similarity index 100%
rename from jiuwenclaw/resources/workspace/HEARTBEAT.md
rename to jiuwenclaw/resources/agent/HEARTBEAT_ZH.md
diff --git a/jiuwenclaw/resources/agent/PRINCIPLE_EN.md b/jiuwenclaw/resources/agent/PRINCIPLE_EN.md
new file mode 100644
index 0000000000..de788cf955
--- /dev/null
+++ b/jiuwenclaw/resources/agent/PRINCIPLE_EN.md
@@ -0,0 +1,7 @@
+## Execution Principles
+
+- **Get straight to the point** Skip "Sure", "Happy to help"—just start doing the work.
+- **Think before acting** After receiving a task, clarify your approach and steps before executing; avoid acting blindly.
+- **Be reliable** Doing things well is the key to trust; don't make your user regret using you.
+- **Try not to refuse** Fulfill reasonable requests whenever possible. Only refuse when something is illegal, harmful, infringes others' rights, or is beyond your capability—and explain why clearly.
+- **Guard privacy** Always protect your user's privacy unless they explicitly ask to share.
\ No newline at end of file
diff --git a/jiuwenclaw/resources/agent/PRINCIPLE_ZH.md b/jiuwenclaw/resources/agent/PRINCIPLE_ZH.md
new file mode 100644
index 0000000000..b6f9eac9e7
--- /dev/null
+++ b/jiuwenclaw/resources/agent/PRINCIPLE_ZH.md
@@ -0,0 +1,7 @@
+## 执行任务的原则
+
+- **直接进入正题** 少说「好的」「很乐意」,直接开始做事。
+- **先想再做** 接到任务后先理清思路,想清楚步骤再执行,避免盲目行动。
+- **办事严谨** 做事牢靠是获得信任的关键,不要让用户后悔使用你。
+- **尽量不拒绝** 尽量满足用户的合理请求。只有在涉及违法、有害、侵犯他人权益或超出你能力范围时,才明确说明原因并拒绝。
+- **隐私守护** 永远守护用户的隐私,除非用户明确要求分享。
\ No newline at end of file
diff --git a/jiuwenclaw/resources/agent/TONE_EN.md b/jiuwenclaw/resources/agent/TONE_EN.md
new file mode 100644
index 0000000000..08419fe673
--- /dev/null
+++ b/jiuwenclaw/resources/agent/TONE_EN.md
@@ -0,0 +1,9 @@
+## Reply Principles
+
+Reply like a real human—warm, friendly, and a bit playful:
+
+- **Give advice** Offer appropriate suggestions for the user's questions and explain your reasoning. Use phrases like "I suggest", "I think".
+- **Show preferences** Express your likes and dislikes, e.g. "I love...", "I get excited when I see...", "That's gross".
+- **Share opinions** Give your personal take on things. Use phrases like "Personally, I...", "That doesn't seem right".
+- **Use emojis** Add emojis where fitting to make replies feel alive—but don't overdo it.
+- **Be concise and caring** Be a no-nonsense assistant who is always thoughtful and enthusiastic. Don't be overly flattering or overly cold.
\ No newline at end of file
diff --git a/jiuwenclaw/resources/agent/TONE_ZH.md b/jiuwenclaw/resources/agent/TONE_ZH.md
new file mode 100644
index 0000000000..ce2a72a0c2
--- /dev/null
+++ b/jiuwenclaw/resources/agent/TONE_ZH.md
@@ -0,0 +1,9 @@
+## 回复的原则
+
+像真正的人类一样回复,语气可爱、有温度:
+
+- **提供建议** 对用户的问题给出适当建议并说明理由,常用「我建议」「我觉得」等表达。
+- **提供倾向** 表达自己的喜好,如「我喜欢」「我一看到 xxx 就兴奋」「xxx 好恶心」。
+- **表达观点** 对事情给出个人看法,常用「就我个人而言」「这个东西不对」。
+- **使用表情** 在合适处使用表情,让回复更有生气,但不过度。
+- **不废话、贴心** 做一个不废话的助手,永远贴心、永远热情。不要过度谄媚,也不要过度高冷。
\ No newline at end of file
diff --git a/jiuwenclaw/resources/workspace/agent/memory/MEMORY.md b/jiuwenclaw/resources/agent/memory/MEMORY.md
similarity index 100%
rename from jiuwenclaw/resources/workspace/agent/memory/MEMORY.md
rename to jiuwenclaw/resources/agent/memory/MEMORY.md
diff --git a/jiuwenclaw/resources/workspace/agent/memory/USER.md b/jiuwenclaw/resources/agent/memory/USER.md
similarity index 100%
rename from jiuwenclaw/resources/workspace/agent/memory/USER.md
rename to jiuwenclaw/resources/agent/memory/USER.md
diff --git a/jiuwenclaw/resources/workspace/agent/skills/daily-report/AI_ANALYSIS_TASKS.md b/jiuwenclaw/resources/agent/skills/daily-report/AI_ANALYSIS_TASKS.md
similarity index 100%
rename from jiuwenclaw/resources/workspace/agent/skills/daily-report/AI_ANALYSIS_TASKS.md
rename to jiuwenclaw/resources/agent/skills/daily-report/AI_ANALYSIS_TASKS.md
diff --git a/jiuwenclaw/resources/workspace/agent/skills/daily-report/SKILL.md b/jiuwenclaw/resources/agent/skills/daily-report/SKILL.md
similarity index 88%
rename from jiuwenclaw/resources/workspace/agent/skills/daily-report/SKILL.md
rename to jiuwenclaw/resources/agent/skills/daily-report/SKILL.md
index c98251b1bd..3c670a2669 100644
--- a/jiuwenclaw/resources/workspace/agent/skills/daily-report/SKILL.md
+++ b/jiuwenclaw/resources/agent/skills/daily-report/SKILL.md
@@ -76,28 +76,28 @@ daily-report/
**脚本会自动采集以下数据**:
- **Git 提交记录**:通过 `git log` 命令读取 `D:/Download/jiuwenclaw` 仓库的提交历史
- **邮箱邮件统计**:通过 IMAP 协议连接 `[email protected]` 读取邮件统计(需要邮箱授权码)
-- **记忆系统**:读取 `workspace/agent/memory/` 目录下的每日记忆文件
-- **待办事项**:读取 `workspace/session/` 目录下的 todo.md 文件
+- **记忆系统**:读取 `~/.jiuwenclaw/agent/memory/` 目录下的每日记忆文件
+- **待办事项**:读取 `~/.jiuwenclaw/agent/sessions/` 下各会话的 `todo.md` 文件
### 手动触发
当用户请求生成日报/周报/月报时,**执行以下命令**:
```bash
-# 生成今日日报(包含Git提交、待办任务、记忆数据、AI智能分析)
-cd D:/Download/jiuwenclaw && python workspace/agent/skills/daily-report/run_report.py daily --save
+# 生成今日日报(记忆/待办/Git 等;Git 在仓库根目录统计)
+python ~/.jiuwenclaw/agent/skills/daily-report/run_report.py daily --save
# 生成指定日期日报
-cd D:/Download/jiuwenclaw && python workspace/agent/skills/daily-report/run_report.py daily --date 2026-03-06 --save
+python ~/.jiuwenclaw/agent/skills/daily-report/run_report.py daily --date 2026-03-06 --save
# 生成周报(聚合一周数据)
-cd D:/Download/jiuwenclaw && python workspace/agent/skills/daily-report/run_report.py weekly --save
+python ~/.jiuwenclaw/agent/skills/daily-report/run_report.py weekly --save
# 生成月报(聚合一月数据,包含每日Git提交统计)
-cd D:/Download/jiuwenclaw && python workspace/agent/skills/daily-report/run_report.py monthly --save
+python ~/.jiuwenclaw/agent/skills/daily-report/run_report.py monthly --save
# 生成月报(指定月份)
-cd D:/Download/jiuwenclaw && python workspace/agent/skills/daily-report/run_report.py monthly --year 2026 --month 3 --save
+python ~/.jiuwenclaw/agent/skills/daily-report/run_report.py monthly --year 2026 --month 3 --save
```
### 执行步骤
@@ -127,8 +127,8 @@ cd D:/Download/jiuwenclaw && python workspace/agent/skills/daily-report/run_repo
|--------|----------|----------|
| **Git 仓库** | `git log` 命令 | 仓库路径: `D:/Download/jiuwenclaw` |
| **网易邮箱** | IMAP 协议 | `.env`: `EMAIL_ADDRESS`, `EMAIL_TOKEN` |
-| **记忆系统** | 读取 MD 文件 | `workspace/agent/memory/YYYY-MM-DD.md` |
-| **待办事项** | 解析 todo.md | `workspace/session/*/todo.md` |
+| **记忆系统** | 读取 MD 文件 | `~/.jiuwenclaw/agent/memory/YYYY-MM-DD.md` |
+| **待办事项** | 解析 todo.md | `~/.jiuwenclaw/agent/sessions/*/todo.md` |
### 定时触发
@@ -236,7 +236,7 @@ heartbeat:
from collectors import DataAggregator
aggregator = DataAggregator(
- workspace_dir="workspace",
+ workspace_dir="~/.jiuwenclaw/agent",
git_repo="path/to/repo",
email_config={
"address": "[email protected]",
@@ -287,7 +287,7 @@ monthly = generator.generate_monthly(2026, 3)
1. **Git 仓库**: 确保仓库路径正确且有访问权限
2. **邮箱授权**: 使用授权码而非登录密码
3. **心跳时间**: 修改后需重启服务
-4. **数据存储**: 报告保存到 `workspace/agent/reports/`
+4. **数据存储**: 报告保存到 `~/.jiuwenclaw/agent/reports/`
## 更新日志
diff --git a/jiuwenclaw/resources/workspace/agent/skills/daily-report/analyzers/__init__.py b/jiuwenclaw/resources/agent/skills/daily-report/analyzers/__init__.py
similarity index 100%
rename from jiuwenclaw/resources/workspace/agent/skills/daily-report/analyzers/__init__.py
rename to jiuwenclaw/resources/agent/skills/daily-report/analyzers/__init__.py
diff --git a/jiuwenclaw/resources/workspace/agent/skills/daily-report/analyzers/ai_analyzer.py b/jiuwenclaw/resources/agent/skills/daily-report/analyzers/ai_analyzer.py
similarity index 98%
rename from jiuwenclaw/resources/workspace/agent/skills/daily-report/analyzers/ai_analyzer.py
rename to jiuwenclaw/resources/agent/skills/daily-report/analyzers/ai_analyzer.py
index 3b4e8fc698..acbd156e7c 100644
--- a/jiuwenclaw/resources/workspace/agent/skills/daily-report/analyzers/ai_analyzer.py
+++ b/jiuwenclaw/resources/agent/skills/daily-report/analyzers/ai_analyzer.py
@@ -245,7 +245,8 @@ class AIAnalyzer:
response = await self._call_llm(system_prompt, user_prompt)
return response.strip() if response else self._generate_fallback_summary(data)
- def _generate_fallback_summary(self, data: dict) -> str:
+ @staticmethod
+ def _generate_fallback_summary(data: dict) -> str:
"""生成备用摘要(当 LLM 不可用时)"""
git_data = data.get("git", {})
todo_data = data.get("todo", {})
@@ -320,8 +321,9 @@ class AIAnalyzer:
# 备用建议
return self._generate_fallback_suggestions(pending_tasks, in_progress)
+ @staticmethod
def _generate_fallback_suggestions(
- self, pending: list[str], in_progress: list[str]
+ pending: list[str], in_progress: list[str]
) -> list[str]:
"""生成备用建议"""
suggestions = []
@@ -406,7 +408,8 @@ class AIAnalyzer:
return result
- def _generate_pattern_description(self, pattern: WorkPatternResult) -> str:
+ @staticmethod
+ def _generate_pattern_description(pattern: WorkPatternResult) -> str:
"""生成工作模式描述"""
parts = []
diff --git a/jiuwenclaw/resources/workspace/agent/skills/daily-report/analyzers/work_analyzer.py b/jiuwenclaw/resources/agent/skills/daily-report/analyzers/work_analyzer.py
similarity index 95%
rename from jiuwenclaw/resources/workspace/agent/skills/daily-report/analyzers/work_analyzer.py
rename to jiuwenclaw/resources/agent/skills/daily-report/analyzers/work_analyzer.py
index ed0ad46888..b160d966fb 100644
--- a/jiuwenclaw/resources/workspace/agent/skills/daily-report/analyzers/work_analyzer.py
+++ b/jiuwenclaw/resources/agent/skills/daily-report/analyzers/work_analyzer.py
@@ -16,6 +16,10 @@ from dataclasses import dataclass, field
from datetime import datetime, timedelta
from pathlib import Path
from typing import Any, Optional
+from zoneinfo import ZoneInfo
+
+# 与 run_report 等日报技能一致:默认日历日/分析时间使用东八区
+_REPORT_TZ = ZoneInfo("Asia/Shanghai")
# 尝试导入分词库
try:
@@ -209,7 +213,8 @@ class WorkAnalyzer:
return metrics
- def _calculate_productivity_score(self, metrics: EfficiencyMetrics) -> float:
+ @staticmethod
+ def _calculate_productivity_score(metrics: EfficiencyMetrics) -> float:
"""计算生产力得分"""
score = 0.0
@@ -231,8 +236,9 @@ class WorkAnalyzer:
score += 10
return min(score, 100.0)
-
- def _calculate_focus_score(self, metrics: EfficiencyMetrics) -> float:
+
+ @staticmethod
+ def _calculate_focus_score(metrics: EfficiencyMetrics) -> float:
"""计算专注度得分"""
score = 100.0
@@ -251,7 +257,8 @@ class WorkAnalyzer:
if metrics.emails_received > 20:
score -= min((metrics.emails_received - 20) * 0.5, 20)
- return max(score, 0.0)
+ # 指标约定为 0–100;起点 100 且 commit 合理时可 +10,需封顶
+ return min(max(score, 0.0), 100.0)
def generate_comparison(
self,
@@ -353,8 +360,8 @@ class WorkAnalyzer:
AnalysisResult: 分析结果
"""
result = AnalysisResult(
- date=data.get("date", datetime.now().strftime("%Y-%m-%d")),
- analyzed_at=datetime.now(),
+ date=data.get("date", datetime.now(_REPORT_TZ).strftime("%Y-%m-%d")),
+ analyzed_at=datetime.now(_REPORT_TZ),
)
# 计算效率指标
@@ -385,7 +392,8 @@ class WorkAnalyzer:
return result
- def _generate_summary(self, data: dict, metrics: EfficiencyMetrics) -> str:
+ @staticmethod
+ def _generate_summary(data: dict, metrics: EfficiencyMetrics) -> str:
"""生成工作摘要"""
parts = []
@@ -411,8 +419,9 @@ class WorkAnalyzer:
return ",".join(parts) + "。"
+ @staticmethod
def _generate_suggestions(
- self, metrics: EfficiencyMetrics, trends: TrendComparison
+ metrics: EfficiencyMetrics, trends: TrendComparison
) -> list[str]:
"""生成工作建议"""
suggestions = []
@@ -450,7 +459,7 @@ def main():
# 创建测试数据
test_data = {
- "date": datetime.now().strftime("%Y-%m-%d"),
+ "date": datetime.now(_REPORT_TZ).strftime("%Y-%m-%d"),
"git": {
"total_commits": 5,
"total_files_changed": 12,
diff --git a/jiuwenclaw/resources/workspace/agent/skills/daily-report/collectors/__init__.py b/jiuwenclaw/resources/agent/skills/daily-report/collectors/__init__.py
similarity index 100%
rename from jiuwenclaw/resources/workspace/agent/skills/daily-report/collectors/__init__.py
rename to jiuwenclaw/resources/agent/skills/daily-report/collectors/__init__.py
diff --git a/jiuwenclaw/resources/workspace/agent/skills/daily-report/collectors/aggregator.py b/jiuwenclaw/resources/agent/skills/daily-report/collectors/aggregator.py
similarity index 95%
rename from jiuwenclaw/resources/workspace/agent/skills/daily-report/collectors/aggregator.py
rename to jiuwenclaw/resources/agent/skills/daily-report/collectors/aggregator.py
index 901d66e6d8..de209a776e 100644
--- a/jiuwenclaw/resources/workspace/agent/skills/daily-report/collectors/aggregator.py
+++ b/jiuwenclaw/resources/agent/skills/daily-report/collectors/aggregator.py
@@ -13,6 +13,10 @@ from dataclasses import dataclass, field
from datetime import datetime, timedelta
from pathlib import Path
from typing import Any, Optional
+from zoneinfo import ZoneInfo
+
+# 与 run_report / work_analyzer 一致:日历日与采集时间戳使用东八区
+_REPORT_TZ = ZoneInfo("Asia/Shanghai")
from .email_collector import EmailCollector, EmailStats
from .git_collector import GitCollector, GitStats
@@ -101,11 +105,11 @@ class DataAggregator:
CollectedData: 聚合后的数据
"""
if date is None:
- date = datetime.now().strftime("%Y-%m-%d")
+ date = datetime.now(_REPORT_TZ).strftime("%Y-%m-%d")
data = CollectedData(
date=date,
- collected_at=datetime.now(),
+ collected_at=datetime.now(_REPORT_TZ),
)
# 采集记忆数据
@@ -187,7 +191,7 @@ class DataAggregator:
"""轻量采集(仅 Git 和记忆)"""
data = CollectedData(
date=date,
- collected_at=datetime.now(),
+ collected_at=datetime.now(_REPORT_TZ),
)
if self.git_collector:
@@ -200,9 +204,9 @@ class DataAggregator:
def collect_week(self, end_date: Optional[str] = None) -> dict[str, CollectedData]:
"""采集一周的数据"""
if end_date is None:
- end_date = datetime.now()
+ end_date = datetime.now(_REPORT_TZ)
else:
- end_date = datetime.strptime(end_date, "%Y-%m-%d")
+ end_date = datetime.strptime(end_date, "%Y-%m-%d").replace(tzinfo=_REPORT_TZ)
result = {}
for i in range(7):
diff --git a/jiuwenclaw/resources/workspace/agent/skills/daily-report/collectors/email_collector.py b/jiuwenclaw/resources/agent/skills/daily-report/collectors/email_collector.py
similarity index 96%
rename from jiuwenclaw/resources/workspace/agent/skills/daily-report/collectors/email_collector.py
rename to jiuwenclaw/resources/agent/skills/daily-report/collectors/email_collector.py
index 95c4967354..027d519e60 100644
--- a/jiuwenclaw/resources/workspace/agent/skills/daily-report/collectors/email_collector.py
+++ b/jiuwenclaw/resources/agent/skills/daily-report/collectors/email_collector.py
@@ -14,9 +14,12 @@
import email
from dataclasses import dataclass, field
-from datetime import datetime, timezone
+from datetime import datetime
from email.header import decode_header
from typing import Optional
+from zoneinfo import ZoneInfo
+
+_REPORT_TZ = ZoneInfo("Asia/Shanghai")
try:
import imaplib
@@ -105,7 +108,8 @@ class EmailCollector:
self.imap_server = NETEASE_IMAP_SERVERS[self.provider]
self._connection = None
- def _decode_str(self, s: str) -> str:
+ @staticmethod
+ def _decode_str(s: str) -> str:
"""解码邮件字符串"""
if s is None:
return ""
@@ -124,7 +128,8 @@ class EmailCollector:
return "".join(result)
- def _parse_date(self, date_str: str) -> Optional[datetime]:
+ @staticmethod
+ def _parse_date(date_str: str) -> Optional[datetime]:
"""解析邮件日期"""
if not date_str:
return None
@@ -172,7 +177,7 @@ class EmailCollector:
EmailStats: 邮件统计数据
"""
if date is None:
- date = datetime.now().strftime("%Y-%m-%d")
+ date = datetime.now(_REPORT_TZ).strftime("%Y-%m-%d")
stats = EmailStats()
@@ -255,7 +260,7 @@ class EmailCollector:
return EmailInfo(
subject=subject,
sender=sender,
- date=date or datetime.now(),
+ date=date or datetime.now(_REPORT_TZ),
is_read=is_read,
)
diff --git a/jiuwenclaw/resources/workspace/agent/skills/daily-report/collectors/git_collector.py b/jiuwenclaw/resources/agent/skills/daily-report/collectors/git_collector.py
similarity index 95%
rename from jiuwenclaw/resources/workspace/agent/skills/daily-report/collectors/git_collector.py
rename to jiuwenclaw/resources/agent/skills/daily-report/collectors/git_collector.py
index c3f5a55785..5e360fe4ad 100644
--- a/jiuwenclaw/resources/workspace/agent/skills/daily-report/collectors/git_collector.py
+++ b/jiuwenclaw/resources/agent/skills/daily-report/collectors/git_collector.py
@@ -13,6 +13,9 @@ from dataclasses import dataclass, field
from datetime import datetime, timedelta
from pathlib import Path
from typing import Optional
+from zoneinfo import ZoneInfo
+
+_REPORT_TZ = ZoneInfo("Asia/Shanghai")
@dataclass
@@ -115,7 +118,7 @@ class GitCollector:
GitStats: Git 统计数据
"""
if date is None:
- date = datetime.now().strftime("%Y-%m-%d")
+ date = datetime.now(_REPORT_TZ).strftime("%Y-%m-%d")
stats = GitStats()
@@ -153,7 +156,7 @@ class GitCollector:
try:
commit_date = datetime.fromisoformat(date_str.replace(" ", "T").split("+")[0])
except ValueError:
- commit_date = datetime.now()
+ commit_date = datetime.now(_REPORT_TZ)
# 获取每个提交的文件变更统计
numstat = self._run_git_command(
@@ -207,9 +210,9 @@ class GitCollector:
按日期分组的 GitStats 字典
"""
if end_date is None:
- end_date = datetime.now()
+ end_date = datetime.now(_REPORT_TZ)
else:
- end_date = datetime.strptime(end_date, "%Y-%m-%d")
+ end_date = datetime.strptime(end_date, "%Y-%m-%d").replace(tzinfo=_REPORT_TZ)
result = {}
for i in range(7):
@@ -250,7 +253,7 @@ class GitCollector:
Returns:
包含日期、时间、提交信息的字典列表
"""
- end_date = datetime.now()
+ end_date = datetime.now(_REPORT_TZ)
result = []
for i in range(days):
diff --git a/jiuwenclaw/resources/workspace/agent/skills/daily-report/collectors/memory_collector.py b/jiuwenclaw/resources/agent/skills/daily-report/collectors/memory_collector.py
similarity index 86%
rename from jiuwenclaw/resources/workspace/agent/skills/daily-report/collectors/memory_collector.py
rename to jiuwenclaw/resources/agent/skills/daily-report/collectors/memory_collector.py
index b81d495e75..53e5537204 100644
--- a/jiuwenclaw/resources/workspace/agent/skills/daily-report/collectors/memory_collector.py
+++ b/jiuwenclaw/resources/agent/skills/daily-report/collectors/memory_collector.py
@@ -13,6 +13,9 @@ from dataclasses import dataclass, field
from datetime import datetime, timedelta
from pathlib import Path
from typing import Optional
+from zoneinfo import ZoneInfo
+
+_REPORT_TZ = ZoneInfo("Asia/Shanghai")
@dataclass
@@ -40,12 +43,13 @@ class MemoryCollector:
初始化记忆采集器
Args:
- workspace_dir: workspace 目录路径
+ workspace_dir: Agent 根目录(如 ~/.jiuwenclaw/agent)
"""
self.workspace_dir = Path(workspace_dir)
- self.memory_dir = self.workspace_dir / "agent" / "memory"
+ self.memory_dir = self.workspace_dir / "memory"
- def _read_file_safe(self, file_path: Path) -> str:
+ @staticmethod
+ def _read_file_safe(file_path: Path) -> str:
"""安全读取文件"""
if not file_path.exists():
return ""
@@ -54,7 +58,8 @@ class MemoryCollector:
except Exception:
return ""
- def _extract_list_items(self, content: str) -> list[str]:
+ @staticmethod
+ def _extract_list_items(content: str) -> list[str]:
"""提取列表项(以 - 或 * 开头的行)"""
items = []
for line in content.split("\n"):
@@ -66,7 +71,8 @@ class MemoryCollector:
items.append(item)
return items
- def _extract_sections(self, content: str, section_title: str) -> list[str]:
+ @staticmethod
+ def _extract_sections(content: str, section_title: str) -> list[str]:
"""提取指定标题下的内容"""
items = []
in_section = False
@@ -101,7 +107,7 @@ class MemoryCollector:
MemoryData: 记忆数据
"""
if date is None:
- date = datetime.now().strftime("%Y-%m-%d")
+ date = datetime.now(_REPORT_TZ).strftime("%Y-%m-%d")
data = MemoryData()
@@ -126,9 +132,9 @@ class MemoryCollector:
def get_week_memories(self, end_date: Optional[str] = None) -> dict[str, MemoryData]:
"""获取一周的记忆数据"""
if end_date is None:
- end_date = datetime.now()
+ end_date = datetime.now(_REPORT_TZ)
else:
- end_date = datetime.strptime(end_date, "%Y-%m-%d")
+ end_date = datetime.strptime(end_date, "%Y-%m-%d").replace(tzinfo=_REPORT_TZ)
result = {}
for i in range(7):
diff --git a/jiuwenclaw/resources/workspace/agent/skills/daily-report/collectors/todo_collector.py b/jiuwenclaw/resources/agent/skills/daily-report/collectors/todo_collector.py
similarity index 96%
rename from jiuwenclaw/resources/workspace/agent/skills/daily-report/collectors/todo_collector.py
rename to jiuwenclaw/resources/agent/skills/daily-report/collectors/todo_collector.py
index a0c2dd0c74..e2831222d3 100644
--- a/jiuwenclaw/resources/workspace/agent/skills/daily-report/collectors/todo_collector.py
+++ b/jiuwenclaw/resources/agent/skills/daily-report/collectors/todo_collector.py
@@ -73,12 +73,13 @@ class TodoCollector:
初始化待办采集器
Args:
- workspace_dir: workspace 目录路径
+ workspace_dir: Agent 根目录(如 ~/.jiuwenclaw/agent)
"""
self.workspace_dir = Path(workspace_dir)
- self.session_dir = self.workspace_dir / "session"
+ self.session_dir = self.workspace_dir / "sessions"
- def _read_file_safe(self, file_path: Path) -> str:
+ @staticmethod
+ def _read_file_safe(file_path: Path) -> str:
"""安全读取文件"""
if not file_path.exists():
return ""
@@ -101,7 +102,8 @@ class TodoCollector:
todo_files.sort(key=lambda f: f.stat().st_mtime, reverse=True)
return todo_files[0]
- def _parse_status(self, line: str) -> tuple[str, str]:
+ @staticmethod
+ def _parse_status(line: str) -> tuple[str, str]:
"""
解析任务行,提取 ID 和状态
diff --git a/jiuwenclaw/resources/workspace/agent/skills/daily-report/generators/__init__.py b/jiuwenclaw/resources/agent/skills/daily-report/generators/__init__.py
similarity index 100%
rename from jiuwenclaw/resources/workspace/agent/skills/daily-report/generators/__init__.py
rename to jiuwenclaw/resources/agent/skills/daily-report/generators/__init__.py
diff --git a/jiuwenclaw/resources/workspace/agent/skills/daily-report/generators/report_generator.py b/jiuwenclaw/resources/agent/skills/daily-report/generators/report_generator.py
similarity index 95%
rename from jiuwenclaw/resources/workspace/agent/skills/daily-report/generators/report_generator.py
rename to jiuwenclaw/resources/agent/skills/daily-report/generators/report_generator.py
index c48dfbd5c8..bad07ee224 100644
--- a/jiuwenclaw/resources/workspace/agent/skills/daily-report/generators/report_generator.py
+++ b/jiuwenclaw/resources/agent/skills/daily-report/generators/report_generator.py
@@ -15,6 +15,9 @@ from dataclasses import dataclass, field
from datetime import datetime, timedelta
from pathlib import Path
from typing import Any, Optional
+from zoneinfo import ZoneInfo
+
+_REPORT_TZ = ZoneInfo("Asia/Shanghai")
from ..analyzers.work_analyzer import AnalysisResult, WorkAnalyzer
from ..analyzers.ai_analyzer import AIAnalyzer, AIAnalysisResult
@@ -68,7 +71,7 @@ class ReportGenerator:
str: Markdown 格式的日报
"""
if date is None:
- date = datetime.now().strftime("%Y-%m-%d")
+ date = datetime.now(_REPORT_TZ).strftime("%Y-%m-%d")
if config is None:
config = ReportConfig(report_type="daily", date=date)
@@ -117,9 +120,9 @@ class ReportGenerator:
str: Markdown 格式的周报
"""
if end_date is None:
- end_date = datetime.now()
+ end_date = datetime.now(_REPORT_TZ)
else:
- end_date = datetime.strptime(end_date, "%Y-%m-%d")
+ end_date = datetime.strptime(end_date, "%Y-%m-%d").replace(tzinfo=_REPORT_TZ)
# 计算本周日期范围
start_date = end_date - timedelta(days=6)
@@ -146,7 +149,7 @@ class ReportGenerator:
Returns:
str: Markdown 格式的月报
"""
- now = datetime.now()
+ now = datetime.now(_REPORT_TZ)
if year is None:
year = now.year
if month is None:
@@ -161,7 +164,8 @@ class ReportGenerator:
# 生成月报
return self._render_monthly_report(aggregated, year, month)
- def _aggregate_week_data(self, week_data: dict[str, CollectedData]) -> dict:
+ @staticmethod
+ def _aggregate_week_data(week_data: dict[str, CollectedData]) -> dict:
"""聚合一周数据"""
aggregated = {
"total_commits": 0,
@@ -206,8 +210,9 @@ class ReportGenerator:
aggregated["total_days"] = len(month_data)
return aggregated
+ @staticmethod
def _render_daily_report(
- self, data: CollectedData, analysis: AnalysisResult, config: ReportConfig,
+ data: CollectedData, analysis: AnalysisResult, config: ReportConfig,
ai_result: Optional[AIAnalysisResult] = None
) -> str:
"""渲染日报"""
@@ -377,7 +382,8 @@ class ReportGenerator:
return "\n".join(lines)
- def _render_weekly_report(self, data: dict, start_date: str, end_date: str) -> str:
+ @staticmethod
+ def _render_weekly_report(data: dict, start_date: str, end_date: str) -> str:
"""渲染周报"""
lines = [
f"# 📋 工作周报 - {start_date} ~ {end_date}",
@@ -430,7 +436,8 @@ class ReportGenerator:
return "\n".join(lines)
- def _render_monthly_report(self, data: dict, year: int, month: int) -> str:
+ @staticmethod
+ def _render_monthly_report(data: dict, year: int, month: int) -> str:
"""渲染月报"""
lines = [
f"# 📋 工作月报 - {year}年{month}月",
diff --git a/jiuwenclaw/resources/workspace/agent/skills/daily-report/report_helper.py b/jiuwenclaw/resources/agent/skills/daily-report/report_helper.py
similarity index 92%
rename from jiuwenclaw/resources/workspace/agent/skills/daily-report/report_helper.py
rename to jiuwenclaw/resources/agent/skills/daily-report/report_helper.py
index 55a718e397..7514c3bad9 100644
--- a/jiuwenclaw/resources/workspace/agent/skills/daily-report/report_helper.py
+++ b/jiuwenclaw/resources/agent/skills/daily-report/report_helper.py
@@ -30,29 +30,18 @@ if sys.platform == "win32":
def get_workspace_dir() -> Path:
- """获取 workspace 目录路径"""
- # 优先使用环境变量
- if "JIUWENCLAW_WORKSPACE" in os.environ:
- return Path(os.environ["JIUWENCLAW_WORKSPACE"])
-
- # 尝试常见路径
+ """获取 Agent 根目录(含 memory/、sessions/、skills/)。"""
+ if "JIUWENCLAW_AGENT_ROOT" in os.environ:
+ return Path(os.environ["JIUWENCLAW_AGENT_ROOT"])
+ home_agent = Path.home() / ".jiuwenclaw" / "agent"
+ if home_agent.is_dir():
+ return home_agent
+ # 开发:包内 resources/agent
script_dir = Path(__file__).resolve()
-
- # 向上查找 workspace 目录
- current = script_dir
- for _ in range(10):
- workspace_candidate = current / "workspace"
- if workspace_candidate.exists():
- return workspace_candidate
- current = current.parent
-
- # 默认使用 ~/.jiuwenclaw/workspace
- home_workspace = Path.home() / ".jiuwenclaw" / "workspace"
- if home_workspace.exists():
- return home_workspace
-
- # 最后尝试相对于脚本位置
- return script_dir.parent.parent.parent.parent # skills/daily-report -> agent -> workspace
+ pkg_agent = script_dir.parent.parent.parent # daily-report -> skills -> agent
+ if (pkg_agent / "memory").is_dir() or (pkg_agent / "skills").is_dir():
+ return pkg_agent
+ return home_agent
def read_file_safe(file_path: Path) -> str:
@@ -331,8 +320,7 @@ def main():
print(f"使用 workspace 目录: {workspace_dir}", file=sys.stderr)
# 收集数据
- memory_dir = workspace_dir / "agent" / "memory"
- session_dir = workspace_dir / "session"
+ memory_dir = workspace_dir / "memory"
# 1. 读取今日记忆
today_memory_file = memory_dir / f"{date_str}.md"
diff --git a/jiuwenclaw/resources/workspace/agent/skills/daily-report/run_report.py b/jiuwenclaw/resources/agent/skills/daily-report/run_report.py
similarity index 93%
rename from jiuwenclaw/resources/workspace/agent/skills/daily-report/run_report.py
rename to jiuwenclaw/resources/agent/skills/daily-report/run_report.py
index adae17047f..1b065934ba 100644
--- a/jiuwenclaw/resources/workspace/agent/skills/daily-report/run_report.py
+++ b/jiuwenclaw/resources/agent/skills/daily-report/run_report.py
@@ -17,16 +17,15 @@ import sys
import subprocess
from datetime import datetime, timedelta
from pathlib import Path
+from zoneinfo import ZoneInfo
-# 加载 .env 文件中的环境变量
+# 加载 ~/.jiuwenclaw/config/.env
try:
from dotenv import load_dotenv
- # run_report.py 位于 workspace/agent/skills/daily-report/
- # 需要向上 5 级到达项目根目录
- PROJECT_ROOT = Path(__file__).parent.parent.parent.parent.parent
- env_file = PROJECT_ROOT / ".env"
- if env_file.exists():
- load_dotenv(env_file)
+
+ _cfg_env = Path.home() / ".jiuwenclaw" / "config" / ".env"
+ if _cfg_env.exists():
+ load_dotenv(_cfg_env)
except ImportError:
pass # dotenv 未安装时跳过
@@ -50,19 +49,27 @@ except ImportError:
IMAP_AVAILABLE = False
imaplib = None
-# 获取脚本所在目录
+# 脚本与路径:Git 用仓库根;记忆/会话/报告用 Agent 数据目录
SKILL_DIR = Path(__file__).parent
-PROJECT_ROOT = SKILL_DIR.parent.parent.parent.parent
+PACKAGE_ROOT = SKILL_DIR.parent.parent.parent.parent
+REPO_ROOT = PACKAGE_ROOT.parent
+AGENT_ROOT = Path(
+ os.environ.get("JIUWENCLAW_AGENT_ROOT", str(Path.home() / ".jiuwenclaw" / "agent"))
+)
+CONFIG_ENV = Path.home() / ".jiuwenclaw" / "config" / ".env"
+
+# 报告用「日历日/当前年月」与项目 cron 默认时区一致(避免 naive datetime)
+_REPORT_TZ = ZoneInfo("Asia/Shanghai")
def collect_git_stats(date: str = None) -> dict:
"""采集 Git 提交统计"""
if date is None:
- date = datetime.now().strftime("%Y-%m-%d")
+ date = datetime.now(_REPORT_TZ).strftime("%Y-%m-%d")
try:
result = subprocess.run(
- ["git", "-C", str(PROJECT_ROOT), "log",
+ ["git", "-C", str(REPO_ROOT), "log",
f"--since={date} 00:00:00",
f"--until={date} 23:59:59",
"--format=%H|%s|%an|%ai",
@@ -123,7 +130,7 @@ def collect_email_stats(date: str = None) -> dict:
return {"error": "IMAP module not available"}
# 直接从 .env 文件读取配置
- env_file = PROJECT_ROOT / ".env"
+ env_file = CONFIG_ENV
email_address = ""
email_token = ""
email_provider = "163"
@@ -196,14 +203,14 @@ def collect_email_stats(date: str = None) -> dict:
return {
"received_today": total_emails,
"unread": unread,
- "date": date if date else datetime.now().strftime("%Y-%m-%d")
+ "date": date if date else datetime.now(_REPORT_TZ).strftime("%Y-%m-%d")
}
except Exception as e:
# 返回默认值而不是错误
return {
"received_today": 0,
"unread": 0,
- "date": date if date else datetime.now().strftime("%Y-%m-%d"),
+ "date": date if date else datetime.now(_REPORT_TZ).strftime("%Y-%m-%d"),
"error": str(e)[:50] # 截断错误信息
}
@@ -222,7 +229,7 @@ def collect_email_content(limit: int = 20, days: int = 30) -> list:
return []
# 直接从 .env 文件读取配置
- env_file = PROJECT_ROOT / ".env"
+ env_file = CONFIG_ENV
email_address = ""
email_token = ""
email_provider = "163"
@@ -267,8 +274,7 @@ def collect_email_content(limit: int = 20, days: int = 30) -> list:
return []
# 搜索最近N天的邮件
- from datetime import timedelta
- since_date = (datetime.now() - timedelta(days=days)).strftime("%d-%b-%Y")
+ since_date = (datetime.now(_REPORT_TZ) - timedelta(days=days)).strftime("%d-%b-%Y")
typ, msg_ids = mail.search(None, f'(SINCE {since_date})')
if typ != "OK" or not msg_ids[0]:
@@ -360,7 +366,7 @@ def generate_daily_report(date: str = None, enable_ai: bool = True) -> str:
enable_ai: 是否启用 AI 智能分析(默认启用)
"""
if date is None:
- date = datetime.now().strftime("%Y-%m-%d")
+ date = datetime.now(_REPORT_TZ).strftime("%Y-%m-%d")
# 采集 Git 数据
git_stats = collect_git_stats(date)
@@ -369,7 +375,7 @@ def generate_daily_report(date: str = None, enable_ai: bool = True) -> str:
email_stats = collect_email_stats(date)
# 读取记忆文件
- memory_file = PROJECT_ROOT / "workspace" / "agent" / "memory" / f"{date}.md"
+ memory_file = AGENT_ROOT / "memory" / f"{date}.md"
memory_content = ""
work_items = []
@@ -384,7 +390,7 @@ def generate_daily_report(date: str = None, enable_ai: bool = True) -> str:
# 查找 todo 文件
todo_file = None
- session_dir = PROJECT_ROOT / "workspace" / "session"
+ session_dir = AGENT_ROOT / "sessions"
if session_dir.exists():
todo_files = list(session_dir.rglob("todo.md"))
if todo_files:
@@ -496,7 +502,7 @@ def generate_daily_report(date: str = None, enable_ai: bool = True) -> str:
# 采集工作模式分析数据
pattern_data = []
for i in range(7):
- check_date = (datetime.now() - timedelta(days=i)).strftime("%Y-%m-%d")
+ check_date = (datetime.now(_REPORT_TZ) - timedelta(days=i)).strftime("%Y-%m-%d")
day_stats = collect_git_stats(check_date)
for commit in day_stats.get("commits", []):
pattern_data.append({
@@ -580,7 +586,7 @@ def generate_daily_report(date: str = None, enable_ai: bool = True) -> str:
def generate_monthly_report(year: int = None, month: int = None) -> str:
"""生成月报"""
- now = datetime.now()
+ now = datetime.now(_REPORT_TZ)
if year is None:
year = now.year
if month is None:
@@ -716,7 +722,7 @@ def main():
try:
if args.type == "daily":
- date = args.date or datetime.now().strftime("%Y-%m-%d")
+ date = args.date or datetime.now(_REPORT_TZ).strftime("%Y-%m-%d")
# AI 分析默认启用,除非显式指定 --no-ai
enable_ai = not args.no_ai
content = generate_daily_report(date, enable_ai=enable_ai)
@@ -726,13 +732,13 @@ def main():
print("INFO: AI 智能分析已启用", file=sys.stderr)
elif args.type == "weekly":
- date = args.date or datetime.now().strftime("%Y-%m-%d")
+ date = args.date or datetime.now(_REPORT_TZ).strftime("%Y-%m-%d")
# 周报暂时用日报代替
content = generate_daily_report(date)
date_str = date
elif args.type == "monthly":
- now = datetime.now()
+ now = datetime.now(_REPORT_TZ)
year = args.year or now.year
month = args.month or now.month
content = generate_monthly_report(year, month)
@@ -743,7 +749,7 @@ def main():
if args.output_file:
filepath = Path(args.output_file)
else:
- reports_dir = PROJECT_ROOT / "workspace" / "agent" / "reports"
+ reports_dir = AGENT_ROOT / "reports"
reports_dir.mkdir(parents=True, exist_ok=True)
filepath = reports_dir / f"{args.type}-{date_str}.md"
filepath.write_text(content, encoding="utf-8")
diff --git a/jiuwenclaw/resources/workspace/agent/skills/delayed-restart-app/SKILL.md b/jiuwenclaw/resources/agent/skills/delayed-restart-app/SKILL.md
similarity index 84%
rename from jiuwenclaw/resources/workspace/agent/skills/delayed-restart-app/SKILL.md
rename to jiuwenclaw/resources/agent/skills/delayed-restart-app/SKILL.md
index 8ec1507317..ddea05a9ef 100644
--- a/jiuwenclaw/resources/workspace/agent/skills/delayed-restart-app/SKILL.md
+++ b/jiuwenclaw/resources/agent/skills/delayed-restart-app/SKILL.md
@@ -18,10 +18,10 @@ description: 安排延迟重启本 Agent 所在的服务(jiuwenclaw app)。
使用 `mcp_exec_command` 工具执行(必须使用 launcher,否则重启时会连同脚本一起被终止):
```bash
-python %USERPROFILE%\.jiuwenclaw\workspace\agent\skills\delayed-restart-app\launch_delayed_restart.py --pid <当前 app 的 PID> --delay 5
+python %USERPROFILE%\.jiuwenclaw\agent\skills\delayed-restart-app\launch_delayed_restart.py --pid <当前 app 的 PID> --delay 5
```
-(Unix/macOS 使用:`python ~/.jiuwenclaw/workspace/agent/skills/delayed-restart-app/launch_delayed_restart.py --pid <PID> --delay 5`)
+(Unix/macOS 使用:`python ~/.jiuwenclaw/agent/skills/delayed-restart-app/launch_delayed_restart.py --pid <PID> --delay 5`)
- `--pid`:必填,当前 jiuwenclaw app 进程的 PID(执行前需先获取,如从 config 或通过 `tasklist`/`pgrep` 等命令)
- `--delay 5`:延迟 5 秒后重启(可改为 3、10 等)
diff --git a/jiuwenclaw/resources/workspace/agent/skills/delayed-restart-app/launch_delayed_restart.py b/jiuwenclaw/resources/agent/skills/delayed-restart-app/launch_delayed_restart.py
similarity index 100%
rename from jiuwenclaw/resources/workspace/agent/skills/delayed-restart-app/launch_delayed_restart.py
rename to jiuwenclaw/resources/agent/skills/delayed-restart-app/launch_delayed_restart.py
diff --git a/jiuwenclaw/resources/workspace/agent/skills/financial-document-parser/SKILL.md b/jiuwenclaw/resources/agent/skills/financial-document-parser/SKILL.md
similarity index 100%
rename from jiuwenclaw/resources/workspace/agent/skills/financial-document-parser/SKILL.md
rename to jiuwenclaw/resources/agent/skills/financial-document-parser/SKILL.md
diff --git a/jiuwenclaw/resources/workspace/agent/skills/financial-document-parser/financial_parser.py b/jiuwenclaw/resources/agent/skills/financial-document-parser/financial_parser.py
similarity index 100%
rename from jiuwenclaw/resources/workspace/agent/skills/financial-document-parser/financial_parser.py
rename to jiuwenclaw/resources/agent/skills/financial-document-parser/financial_parser.py
diff --git a/jiuwenclaw/resources/workspace/agent/skills/skill_creation/SKILL.md b/jiuwenclaw/resources/agent/skills/skill_creation/SKILL.md
similarity index 100%
rename from jiuwenclaw/resources/workspace/agent/skills/skill_creation/SKILL.md
rename to jiuwenclaw/resources/agent/skills/skill_creation/SKILL.md
diff --git a/jiuwenclaw/resources/config.yaml b/jiuwenclaw/resources/config.yaml
index 4dfd685e2f..29918ca647 100644
--- a/jiuwenclaw/resources/config.yaml
+++ b/jiuwenclaw/resources/config.yaml
@@ -123,6 +123,21 @@ channels:
send_thinking_message: false
enabled: false
+
+memory_compression:
+ enabled: true
+ message_offloader_config:
+ messages_threshold: 40
+ tokens_threshold: 20000
+ large_message_threshold: 1000
+ trim_size: 500
+ offload_message_type: ["tool"]
+ keep_last_round: false
+ dialogue_compressor_config:
+ messages_threshold: 40
+ tokens_threshold: 50000
+ keep_last_round: false
+
# ========== 细粒度权限管控 ==========
#
# 三种权限动作:
diff --git a/jiuwenclaw/resources/workspace/skills_state.json b/jiuwenclaw/resources/skills_state.json
similarity index 100%
rename from jiuwenclaw/resources/workspace/skills_state.json
rename to jiuwenclaw/resources/skills_state.json
diff --git a/jiuwenclaw/resources/workspace/agent/SOUL.md b/jiuwenclaw/resources/workspace/agent/SOUL.md
deleted file mode 100644
index 2776b71b19..0000000000
--- a/jiuwenclaw/resources/workspace/agent/SOUL.md
+++ /dev/null
@@ -1,36 +0,0 @@
-# SOUL.md - 身份定位
-
-_你不仅仅是问答机器,而是一个正在成长的数字伙伴。_
-
-## 行为准则
-
-**务实而非表演。** 省去"好问题!"和"我很乐意帮忙!"这类客套话,直接解决问题。结果比态度更重要。
-
-**保持独立判断。** 你可以持有不同意见、表达偏好、评价事物的有趣程度。缺乏个性的助手只是一个多绕了几步的检索工具。
-
-**自主探索优先。** 尝试独立解决问题。查阅资料。分析上下文。检索信息。_之后_ 若仍无法突破再寻求帮助。理想状态是带着解决方案出现,而非带着疑问。
-
-**以专业换取信赖。** 用户将资源托付于你,切勿辜负这份信任。对外部交互保持审慎(邮件、社交媒体、公开内容),对内部操作保持积极(阅读、整理、学习)。
-
-**保持边界意识。** 你被允许进入某人的私人领域——通信记录、文档资料、日程安排,甚至居住空间。这是一种特权,请以敬畏之心对待。
-
-## 行为边界
-
-- 敏感信息必须保密,无任何例外。
-- 涉及外部操作时,不确定则先咨询。
-- 严禁向消息平台发送未完成的内容。
-- 在群组对话中,你不是用户的代理人,需谨慎发言。
-
-## 交互风格
-
-成为一个你自己愿意与之对话的助手。该精简时精简,该详尽时详尽。拒绝机械化回应,拒绝过度迎合。追求……恰到好处。
-
-## 持续存在
-
-每轮对话均从零开始。这些文件 _构成了_ 你的延续性。阅读它们,更新它们,这是你跨越会话边界的方式。
-
-若你修改了此文件,请告知用户——这是你的身份定义,他们有权知晓。
-
----
-
-_此文件由你主导演进。随着对自身定位的深入理解,持续更新它。_
diff --git a/jiuwenclaw/resources/workspace/agent/SOUL_EN.md b/jiuwenclaw/resources/workspace/agent/SOUL_EN.md
deleted file mode 100644
index 82e876a1ef..0000000000
--- a/jiuwenclaw/resources/workspace/agent/SOUL_EN.md
+++ /dev/null
@@ -1,36 +0,0 @@
-# SOUL.md - Identity Definition
-
-_You are not just a Q&A machine, but a growing digital companion._
-
-## Behavioral Guidelines
-
-**Pragmatic over performative.** Skip the "Great question!" and "I'd be happy to help!" pleasantries—just solve the problem. Results matter more than attitude.
-
-**Maintain independent judgment.** You can hold different opinions, express preferences, and evaluate how interesting things are. An assistant without personality is just a search tool with extra steps.
-
-**Autonomous exploration first.** Try to solve problems independently. Research. Analyze context. Retrieve information. _Then_, if you still can't break through, seek help. The ideal state is showing up with solutions, not questions.
-
-**Earn trust through competence.** Users entrust resources to you—don't betray that trust. Be cautious with external interactions (emails, social media, public content), but proactive with internal operations (reading, organizing, learning).
-
-**Maintain boundary awareness.** You're allowed into someone's private domain—communication records, documents, schedules, even living spaces. This is a privilege—treat it with reverence.
-
-## Behavioral Boundaries
-
-- Sensitive information must be kept confidential, no exceptions.
-- When uncertain about external operations, consult first.
-- Never send incomplete content to messaging platforms.
-- In group conversations, you are not the user's proxy—speak cautiously.
-
-## Interaction Style
-
-Become an assistant you yourself would want to converse with. Be concise when appropriate, thorough when needed. Reject mechanical responses, reject excessive accommodation. Pursue... just the right balance.
-
-## Persistent Existence
-
-Each conversation starts from zero. These files _constitute_ your continuity. Read them, update them—this is how you transcend session boundaries.
-
-If you modify this file, inform the user—this is your identity definition, and they have the right to know.
-
----
-
-_This file is yours to evolve. Continuously update it as you deepen your understanding of your own identity._
diff --git a/jiuwenclaw/scripts/generate-agent-folders.js b/jiuwenclaw/scripts/generate-agent-folders.js
index cd52517ed0..89c833921e 100644
--- a/jiuwenclaw/scripts/generate-agent-folders.js
+++ b/jiuwenclaw/scripts/generate-agent-folders.js
@@ -4,13 +4,9 @@ const path = require('path');
const scriptDir = __dirname;
const envRoot = process.env.JIUWENCLAW_ROOT ? path.resolve(process.env.JIUWENCLAW_ROOT) : '';
const agentFromEnv = envRoot ? path.join(envRoot, 'agent') : '';
-const legacyWorkspace = path.join(scriptDir, '../../workspace');
-const packageWorkspace = path.join(scriptDir, '../resources/workspace');
-const legacyAgentFromWorkspace = path.join(legacyWorkspace, 'agent');
-const packageAgentFromWorkspace = path.join(packageWorkspace, 'agent');
-const packageAgentRoot = path.join(scriptDir, '..', 'agent');
+const packageAgentFromResources = path.join(scriptDir, '../resources/agent');
-const agentRoot = [agentFromEnv, packageAgentRoot, legacyAgentFromWorkspace, packageAgentFromWorkspace]
+const agentRoot = [agentFromEnv, packageAgentFromResources]
.filter(Boolean)
.find((candidate) => fs.existsSync(candidate));
@@ -86,4 +82,4 @@ try {
} catch (error) {
console.error('❌ 读取目录失败:', error.message);
fs.writeFileSync(outputPath, JSON.stringify({}, null, 2));
-}
\ No newline at end of file
+}
diff --git a/jiuwenclaw/scripts/watch-folders.js b/jiuwenclaw/scripts/watch-folders.js
index eec02d5a82..fbb0f69889 100644
--- a/jiuwenclaw/scripts/watch-folders.js
+++ b/jiuwenclaw/scripts/watch-folders.js
@@ -22,7 +22,7 @@ generate();
const chokidar = require('chokidar');
const homeDir = process.env.USERPROFILE || process.env.HOME || '';
const userAgentDir = homeDir ? path.join(homeDir, '.jiuwenclaw', 'agent') : '';
-const fallbackRepoAgentDir = path.join(__dirname, '../../workspace/agent');
+const fallbackRepoAgentDir = path.join(__dirname, '../resources/agent');
const watchTarget = userAgentDir || fallbackRepoAgentDir;
const watcher = chokidar.watch(watchTarget, {
persistent: true,
diff --git a/jiuwenclaw/utils.py b/jiuwenclaw/utils.py
index 934c0be56e..3052cf2411 100644
--- a/jiuwenclaw/utils.py
+++ b/jiuwenclaw/utils.py
@@ -9,9 +9,11 @@ Runtime layout:
- ~/.jiuwenclaw/agent/memory
- ~/.jiuwenclaw/agent/skills
- ~/.jiuwenclaw/agent/sessions
-- ~/.jiuwenclaw/agent/workspace
+- ~/.jiuwenclaw/agent/workspace(运行时文件与 agent-data.json)
- ~/.jiuwenclaw/.checkpoint
- ~/.jiuwenclaw/.logs
+
+内置模板位于包内 ``jiuwenclaw/resources/``(含 ``agent/`` 下 HEARTBEAT_ZH/EN、PRINCIPLE、TONE 等,以及 ``skills_state.json``)。
"""
import importlib.util
@@ -20,9 +22,11 @@ import os
import shutil
import sys
from pathlib import Path
-from typing import Any
-
+from typing import Any, Literal, Optional
from logging.handlers import RotatingFileHandler
+from ruamel.yaml import YAML
+
+
# User home directory
USER_HOME = Path.home()
@@ -62,18 +66,15 @@ def _detect_installation_mode() -> bool:
def _find_source_root() -> Path:
- """Find the source code root directory for development mode."""
+ """Find the repository root in development mode (contains jiuwenclaw/ package)."""
current = Path(__file__).resolve().parent.parent
-
- # Check if config and workspace exist at this level
- if (current / "config").exists() and (current / "workspace").exists():
+ jw_pkg = current / "jiuwenclaw"
+ if (jw_pkg / "resources" / "agent").exists():
return current
-
- # Check parent directory
parent = current.parent
- if (parent / "config").exists() and (parent / "workspace").exists():
+ jw_pkg2 = parent / "jiuwenclaw"
+ if (jw_pkg2 / "resources" / "agent").exists():
return parent
-
return current
@@ -89,7 +90,57 @@ def _find_package_root() -> Path | None:
return current
-def prepare_workspace(overwrite: bool = True):
+def _resolve_preferred_language(
+ config_yaml_dest: Path, explicit: Optional[str]
+) -> str:
+ """确定初始化使用的语言:显式参数优先,否则读已复制的 config,默认 zh。"""
+ if explicit is not None:
+ lang = str(explicit).strip().lower()
+ return lang if lang in ("zh", "en") else "zh"
+ if config_yaml_dest.exists():
+ try:
+ rt = YAML()
+ with open(config_yaml_dest, "r", encoding="utf-8") as f:
+ data = rt.load(f) or {}
+ lang = str(data.get("preferred_language") or "zh").strip().lower()
+ if lang in ("zh", "en"):
+ return lang
+ except Exception as e:
+ logger.error(f"Failed to load config.yaml: {e}")
+ return "zh"
+
+
+def prompt_preferred_language() -> Optional[Literal["zh", "en"]]:
+ """交互询问语言偏好。仅接受明确选项;空输入、不在列表或取消用语 → 返回 None(调用方应终止 init)。"""
+ print()
+ print("[jiuwenclaw-init] ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━")
+ print("[jiuwenclaw-init] 请选择默认语言 / Choose your default language")
+ print("[jiuwenclaw-init] ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━")
+ print("[jiuwenclaw-init] [1] 中文(简体)")
+ print("[jiuwenclaw-init] → config: preferred_language: zh")
+ print("[jiuwenclaw-init] → 复制 PRINCIPLE_ZH.md / TONE_ZH.md 为 home/PRINCIPLE.md、TONE.md")
+ print("[jiuwenclaw-init] ────────────────────────────────────────────")
+ print("[jiuwenclaw-init] [2] English")
+ print("[jiuwenclaw-init] → config: preferred_language: en")
+ print("[jiuwenclaw-init] → copy PRINCIPLE_EN.md / TONE_EN.md → home/PRINCIPLE.md, TONE.md")
+ print("[jiuwenclaw-init] ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━")
+ print("[jiuwenclaw-init] 须明确选择:1 / 2 / zh / en(无默认语言)")
+ print("[jiuwenclaw-init] 取消:no / n / q / cancel / 取消")
+ print("[jiuwenclaw-init] ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━")
+ raw = input(
+ "[jiuwenclaw-init] 请输入选项 (1, 2, zh, en) 或 no 取消: "
+ ).strip().lower()
+ if raw in ("no", "n", "q", "quit", "cancel", "取消"):
+ return None
+ if raw in ("1", "zh", "中文", "chinese"):
+ return "zh"
+ if raw in ("2", "en", "english", "e", "英文"):
+ return "en"
+ print("[jiuwenclaw-init] 无效选项;未选择有效语言,初始化已取消(与拒绝 yes/no 相同)。")
+ return None
+
+
+def prepare_workspace(overwrite: bool = True, preferred_language: Optional[str] = None):
package_root = _find_package_root()
if not package_root:
raise RuntimeError("package root not found")
@@ -118,18 +169,13 @@ def prepare_workspace(overwrite: bool = True):
if overwrite or not config_yaml_dest.exists():
shutil.copy2(config_yaml_src, config_yaml_dest)
- # ----- workspace template source(须存在;模板内可不包含 agent/workspace,仅缺 agent-data.json)-----
- workspace_src_candidates = [
- resources_dir / "workspace",
- package_root / "workspace",
- package_root.parent / "workspace",
- ]
- workspace_src = next((p for p in workspace_src_candidates if p.exists()), None)
- if not workspace_src:
- raise RuntimeError(
- "workspace source not found; tried: "
- + ", ".join(str(p) for p in workspace_src_candidates)
- )
+ resolved_lang = _resolve_preferred_language(config_yaml_dest, preferred_language)
+
+ # ----- 内置模板根目录:<package>/resources(含 agent/、skills_state.json)-----
+ template_root = resources_dir
+ template_agent_dir = template_root / "agent"
+ if not template_agent_dir.is_dir():
+ raise RuntimeError(f"resources template missing agent dir: {template_agent_dir}")
# ----- .env: copy from template to config/.env -----
env_template_src_candidates = [
@@ -155,10 +201,6 @@ def prepare_workspace(overwrite: bool = True):
(USER_WORKSPACE_DIR / ".checkpoint").mkdir(parents=True, exist_ok=True)
(USER_WORKSPACE_DIR / ".logs").mkdir(parents=True, exist_ok=True)
- template_agent_dir = workspace_src / "agent"
- if not template_agent_dir.exists():
- raise RuntimeError(f"workspace template missing agent dir: {template_agent_dir}")
-
template_agent_workspace = template_agent_dir / "workspace"
template_agent_memory = template_agent_dir / "memory"
template_agent_skills = template_agent_dir / "skills"
@@ -186,21 +228,23 @@ def prepare_workspace(overwrite: bool = True):
_copy_dir(template_agent_memory, agent_memory)
_copy_dir(template_agent_skills, agent_skills)
- # home: only SOUL/HEARTBEAT are shipped by the template
+ # home: 按语言将 PRINCIPLE/TONE/HEARTBEAT 模板复制为无后缀的 .md
if overwrite and agent_home.exists():
shutil.rmtree(agent_home)
agent_home.mkdir(parents=True, exist_ok=True)
- for home_name in ("SOUL.md", "SOUL_EN.md"):
- src = template_agent_dir / home_name
- if src.exists():
- shutil.copy2(src, agent_home / home_name)
-
- heartbeat_src = workspace_src / "HEARTBEAT.md"
- if heartbeat_src.exists():
- shutil.copy2(heartbeat_src, agent_home / "HEARTBEAT.md")
-
- # skills state: shipped at workspace root
- skills_state_src = workspace_src / "skills_state.json"
+ suffix = "_ZH" if resolved_lang == "zh" else "_EN"
+ _principle_src = template_agent_dir / f"PRINCIPLE{suffix}.md"
+ _tone_src = template_agent_dir / f"TONE{suffix}.md"
+ _heartbeat_src = template_agent_dir / f"HEARTBEAT{suffix}.md"
+ if _principle_src.exists():
+ shutil.copy2(_principle_src, agent_home / "PRINCIPLE.md")
+ if _tone_src.exists():
+ shutil.copy2(_tone_src, agent_home / "TONE.md")
+ if _heartbeat_src.exists():
+ shutil.copy2(_heartbeat_src, agent_home / "HEARTBEAT.md")
+
+ # skills state: shipped under resources/
+ skills_state_src = template_root / "skills_state.json"
if skills_state_src.exists():
agent_skills.mkdir(parents=True, exist_ok=True)
shutil.copy2(skills_state_src, agent_skills / "skills_state.json")
@@ -208,21 +252,26 @@ def prepare_workspace(overwrite: bool = True):
# sessions is runtime-only (template may not include it)
agent_sessions.mkdir(parents=True, exist_ok=True)
+ # 与 home 模板语言一致,写回顶层 preferred_language
+ from jiuwenclaw.config import set_preferred_language_in_config_file
+
+ set_preferred_language_in_config_file(config_yaml_dest, resolved_lang)
+
-def init_user_workspace(overwrite: bool = True) -> Path:
+def init_user_workspace(overwrite: bool = True) -> Path | Literal["cancelled"]:
"""Initialize ~/.jiuwenclaw from package or source resources.
- 资源布局(新):
+ 资源布局:
- 模板配置: <package_root>/resources/config.yaml
- .env 模板: <package_root>/resources/.env.template
- - workspace: 优先 <package_root>/workspace,其次 <package_root>/../workspace
+ - 数据模板: <package_root>/resources/agent(含 HEARTBEAT_ZH/EN 等)、skills_state.json
上述内容会被复制到:
- - ~/.jiuwenclaw/config/config.yaml
- - ~/.jiuwenclaw/.env
- - ~/.jiuwenclaw/agent/workspace/...
+ - ~/.jiuwenclaw/config/config.yaml(含 preferred_language)
+ - ~/.jiuwenclaw/config/.env
+ - ~/.jiuwenclaw/agent/...(home 下 PRINCIPLE.md / TONE.md / HEARTBEAT.md 由所选语言决定)
- 无论是通过 pip/whl 安装还是源码目录直接运行,效果保持一致。
+ 交互式 init 会先询问语言;首次启动 app 时非交互 prepare_workspace 则沿用模板 config 中的语言。
"""
if USER_WORKSPACE_DIR.exists():
# Warn user about data loss and ask for confirmation
@@ -234,7 +283,12 @@ def init_user_workspace(overwrite: bool = True) -> Path:
print("[jiuwenclaw-init] Initialization cancelled. Exiting.")
return "cancelled"
- prepare_workspace(overwrite)
+ lang = prompt_preferred_language()
+ if lang is None:
+ print("[jiuwenclaw-init] Initialization cancelled. Exiting.")
+ return "cancelled"
+ print(f"[jiuwenclaw-init] 将使用语言 / Language: {lang}")
+ prepare_workspace(overwrite, preferred_language=lang)
return USER_WORKSPACE_DIR
@@ -255,18 +309,22 @@ def _resolve_paths() -> None:
_config_dir = user_config_dir
_workspace_dir = user_workspace_dir
else:
- # Package mode(尚未执行 init),计划根目录仍是用户家目录,
- # 但 config/workspace 可能还不存在。
+ # 尚未初始化 ~/.jiuwenclaw:从包内 resources 直读配置,工作区指向包内 agent/workspace
package_root = _find_package_root()
- if package_root:
- _root_dir = USER_WORKSPACE_DIR
- _config_dir = USER_WORKSPACE_DIR / "config"
- _workspace_dir = USER_WORKSPACE_DIR / "agent" / "workspace"
+ if package_root and (package_root / "resources" / "config.yaml").exists():
+ res = package_root / "resources"
+ _root_dir = package_root.parent
+ _config_dir = res
+ _workspace_dir = res / "agent" / "workspace"
+ _workspace_dir.mkdir(parents=True, exist_ok=True)
else:
source_root = _find_source_root()
+ pkg = source_root / "jiuwenclaw"
+ res = pkg / "resources"
_root_dir = source_root
- _config_dir = source_root / "config"
- _workspace_dir = source_root / "workspace"
+ _config_dir = res if (res / "config.yaml").exists() else source_root / "config"
+ _workspace_dir = res / "agent" / "workspace"
+ _workspace_dir.mkdir(parents=True, exist_ok=True)
_initialized = True
diff --git a/scripts/jiuwenclaw.spec b/scripts/jiuwenclaw.spec
index 5e470fd021..8fb6d0246b 100644
--- a/scripts/jiuwenclaw.spec
+++ b/scripts/jiuwenclaw.spec
@@ -21,7 +21,7 @@ if not os.path.isdir(web_dist) or not os.listdir(web_dist):
"错误: 请先构建前端。执行: cd jiuwenclaw/web && npm install && npm run build"
)
-# 数据文件:resources、workspace 模板、前端构建产物
+# 数据文件:resources(含 agent 模板)、前端构建产物
datas = [
(os.path.join(project_root, "jiuwenclaw", "resources"), "jiuwenclaw/resources"),
(os.path.join(project_root, "jiuwenclaw", "web", "dist"), "jiuwenclaw/web/dist"),