j-cli 12.9.54

A fast CLI tool for alias management, daily reports, and productivity
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
use crate::command::chat::constants::{
    DEFAULT_MAX_CONTEXT_TOKENS, DEFAULT_MAX_HISTORY_MESSAGES, DEFAULT_MAX_TOOL_ROUNDS,
};
use crate::command::chat::context::compact::CompactConfig;
use crate::config::YamlConfig;
use crate::error;
use crate::theme::ThemeName;
use serde::{Deserialize, Serialize};
use std::fs;
use std::path::PathBuf;

/// 单个模型提供方配置
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct ModelProvider {
    /// 显示名称(如 "GPT-4o", "DeepSeek-V3")
    pub name: String,
    /// API Base URL(如 "https://api.openai.com/v1")
    pub api_base: String,
    /// API Key
    pub api_key: String,
    /// 模型名称(如 "gpt-4o", "deepseek-chat")
    pub model: String,
    /// 是否支持视觉/多模态(默认 false)
    #[serde(default)]
    pub supports_vision: bool,
}

/// 思考指示器动画风格
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(rename_all = "snake_case")]
pub enum ThinkingStyle {
    /// Braille 点阵旋转(默认)
    #[default]
    Braille,
    /// 经典圆点(原版 ◍ + 颜色脉冲)
    Classic,
    /// 圆环呼吸(渐变大小)
    Pulse,
    /// 三点波浪
    Wave,
    /// 光标闪烁
    Blink,
    /// 渐变彗星(拖尾字符密度渐变)
    Comet,
}

impl ThinkingStyle {
    /// 所有可能值,用于 config panel 循环切换
    pub const ALL: &[ThinkingStyle] = &[
        ThinkingStyle::Braille,
        ThinkingStyle::Classic,
        ThinkingStyle::Pulse,
        ThinkingStyle::Wave,
        ThinkingStyle::Blink,
        ThinkingStyle::Comet,
    ];

    /// 显示名称(中文)
    pub fn display_name(&self) -> &'static str {
        match self {
            Self::Braille => "旋转点阵",
            Self::Classic => "经典圆点",
            Self::Pulse => "呼吸圆点",
            Self::Wave => "波浪三连",
            Self::Blink => "闪烁光标",
            Self::Comet => "渐变彗星",
        }
    }

    /// 序列化名称
    pub fn as_str(&self) -> &'static str {
        match self {
            Self::Braille => "braille",
            Self::Classic => "classic",
            Self::Pulse => "pulse",
            Self::Wave => "wave",
            Self::Blink => "blink",
            Self::Comet => "comet",
        }
    }

    /// 从字符串解析,支持英文标识和中文名
    pub fn parse(s: &str) -> Self {
        match s.trim().to_lowercase().as_str() {
            "braille" => Self::Braille,
            "classic" => Self::Classic,
            "pulse" => Self::Pulse,
            "wave" => Self::Wave,
            "blink" => Self::Blink,
            "comet" => Self::Comet,
            // 中文名映射
            "旋转点阵" => Self::Braille,
            "经典圆点" => Self::Classic,
            "呼吸圆点" => Self::Pulse,
            "波浪三连" => Self::Wave,
            "闪烁光标" => Self::Blink,
            "渐变彗星" => Self::Comet,
            _ => Self::default(),
        }
    }

    /// 切换到下一个风格
    pub fn next(&self) -> Self {
        let idx = Self::ALL.iter().position(|s| s == self).unwrap_or(0);
        Self::ALL[(idx + 1) % Self::ALL.len()]
    }

    /// 基于 tick(每 100ms 递增 1)返回当前帧的显示字符
    pub fn frame(&self, tick: u64) -> &'static str {
        match self {
            Self::Braille => {
                const FRAMES: &[&str] = &["", "", "", "", "", "", "", "", "", ""];
                FRAMES[(tick as usize) % FRAMES.len()]
            }
            Self::Classic => "",
            Self::Pulse => {
                const FRAMES: &[&str] = &["·", "", "", "", "", "", "", "", "", ""];
                FRAMES[(tick as usize) % FRAMES.len()]
            }
            Self::Wave => {
                const FRAMES: &[&str] = &["● · ·", "· ● ·", "· · ●", "· ● ·"];
                FRAMES[(tick as usize) % FRAMES.len()]
            }
            Self::Blink => {
                const FRAMES: &[&str] = &["", " "];
                FRAMES[(tick as usize / 5) % FRAMES.len()]
            }
            Self::Comet => {
                // 宽度 13 的轨道上,密度渐变的 "██▓▒░" 彗星左右来回弹跳(ping-pong)
                const FRAMES: &[&str] = &[
                    "██▓▒░        ",
                    " ██▓▒░       ",
                    "  ██▓▒░      ",
                    "   ██▓▒░     ",
                    "    ██▓▒░    ",
                    "     ██▓▒░   ",
                    "      ██▓▒░  ",
                    "       ██▓▒░ ",
                    "        ██▓▒░",
                    "       ██▓▒░ ",
                    "      ██▓▒░  ",
                    "     ██▓▒░   ",
                    "    ██▓▒░    ",
                    "   ██▓▒░     ",
                    "  ██▓▒░      ",
                    " ██▓▒░       ",
                ];
                FRAMES[(tick as usize) % FRAMES.len()]
            }
        }
    }
}

/// Agent 配置
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct AgentConfig {
    /// 模型提供方列表
    #[serde(default)]
    pub providers: Vec<ModelProvider>,
    /// 当前选中的 provider 索引
    #[serde(default)]
    pub active_index: usize,
    /// 系统提示词(可选)
    #[serde(default)]
    pub system_prompt: Option<String>,
    /// 发送给 API 的历史消息数量限制(默认 20 条,避免 token 消耗过大)
    #[serde(default = "default_max_history_messages")]
    pub max_history_messages: usize,
    /// 上下文 token 预算(优先级选择时的 token 上限,默认 100K)
    #[serde(default = "default_max_context_tokens")]
    pub max_context_tokens: usize,
    /// 主题名称(dark / light / midnight)
    #[serde(default)]
    pub theme: ThemeName,
    /// 是否启用工具调用(默认关闭)
    #[serde(default)]
    pub tools_enabled: bool,
    /// 工具调用最大轮数(默认 10,防止无限循环)
    #[serde(default = "default_max_tool_rounds")]
    pub max_tool_rounds: usize,
    /// 回复风格(可选)
    #[serde(default)]
    pub style: Option<String>,
    /// 工具确认超时秒数(0 表示不超时,需手动确认;>0 则超时后自动执行)
    #[serde(default)]
    pub tool_confirm_timeout: u64,
    /// 被禁用的工具名称列表(tools_enabled=true 时,此列表中的工具不会发送给 LLM)
    #[serde(default)]
    pub disabled_tools: Vec<String>,
    /// 被禁用的 skill 名称列表(列表中的 skill 不会包含在系统提示词中)
    #[serde(default)]
    pub disabled_skills: Vec<String>,
    /// 被禁用的 command 名称列表
    #[serde(default)]
    pub disabled_commands: Vec<String>,
    /// 被禁用的 hook 标识列表(格式:`source:unique_id`,如 `user:my_hook`、`session:0`)
    #[serde(default)]
    pub disabled_hooks: Vec<String>,
    /// Context compact 配置
    #[serde(default)]
    pub compact: CompactConfig,
    /// 启动时是否自动恢复最近的 session
    #[serde(default)]
    pub auto_restore_session: bool,
    /// 思考指示器动画风格
    #[serde(default)]
    pub thinking_style: ThinkingStyle,
}

fn default_max_history_messages() -> usize {
    DEFAULT_MAX_HISTORY_MESSAGES
}

fn default_max_context_tokens() -> usize {
    DEFAULT_MAX_CONTEXT_TOKENS
}

fn default_max_tool_rounds() -> usize {
    DEFAULT_MAX_TOOL_ROUNDS
}

/// 获取 agent 数据目录: ~/.jdata/agent/data/
pub fn agent_data_dir() -> PathBuf {
    let dir = YamlConfig::data_dir().join("agent").join("data");
    let _ = fs::create_dir_all(&dir);
    dir
}

/// 获取 agent 配置文件路径
pub fn agent_config_path() -> PathBuf {
    agent_data_dir().join("agent_config.json")
}

/// 获取系统提示词文件路径
pub fn system_prompt_path() -> PathBuf {
    agent_data_dir().join("system_prompt.md")
}

/// 获取回复风格文件路径
pub fn style_path() -> PathBuf {
    agent_data_dir().join("style.md")
}

/// 获取记忆文件路径
pub fn memory_path() -> PathBuf {
    agent_data_dir().join("memory.md")
}

/// 获取灵魂文件路径
pub fn soul_path() -> PathBuf {
    agent_data_dir().join("soul.md")
}

/// 加载 Agent 配置
pub fn load_agent_config() -> AgentConfig {
    let path = agent_config_path();
    if !path.exists() {
        return AgentConfig::default();
    }
    match fs::read_to_string(&path) {
        Ok(content) => serde_json::from_str(&content).unwrap_or_else(|e| {
            error!("✖️ 解析 agent_config.json 失败: {}", e);
            AgentConfig::default()
        }),
        Err(e) => {
            error!("✖️ 读取 agent_config.json 失败: {}", e);
            AgentConfig::default()
        }
    }
}

/// 保存 Agent 配置
pub fn save_agent_config(config: &AgentConfig) -> bool {
    let path = agent_config_path();
    if let Some(parent) = path.parent() {
        let _ = fs::create_dir_all(parent);
    }
    // system_prompt 和 style 统一存放在独立文件,不再写入 agent_config.json
    let mut config_to_save = config.clone();
    config_to_save.system_prompt = None;
    config_to_save.style = None;
    match serde_json::to_string_pretty(&config_to_save) {
        Ok(json) => match fs::write(&path, json) {
            Ok(_) => true,
            Err(e) => {
                error!("✖️ 保存 agent_config.json 失败: {}", e);
                false
            }
        },
        Err(e) => {
            error!("✖️ 序列化 agent 配置失败: {}", e);
            false
        }
    }
}

/// 加载系统提示词(来自独立文件)
pub fn load_system_prompt() -> Option<String> {
    let path = system_prompt_path();
    if !path.exists() {
        return None;
    }
    match fs::read_to_string(path) {
        Ok(content) => {
            let trimmed = content.trim();
            if trimmed.is_empty() {
                None
            } else {
                Some(trimmed.to_string())
            }
        }
        Err(e) => {
            error!("✖️ 读取 system_prompt.md 失败: {}", e);
            None
        }
    }
}

/// 保存系统提示词到独立文件(空字符串会删除文件)
pub fn save_system_prompt(prompt: &str) -> bool {
    let path = system_prompt_path();
    if let Some(parent) = path.parent() {
        let _ = fs::create_dir_all(parent);
    }

    let trimmed = prompt.trim();
    if trimmed.is_empty() {
        return match fs::remove_file(&path) {
            Ok(_) => true,
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => true,
            Err(e) => {
                error!("✖️ 删除 system_prompt.md 失败: {}", e);
                false
            }
        };
    }

    match fs::write(path, trimmed) {
        Ok(_) => true,
        Err(e) => {
            error!("✖️ 保存 system_prompt.md 失败: {}", e);
            false
        }
    }
}

/// 加载回复风格(来自独立文件)
pub fn load_style() -> Option<String> {
    let path = style_path();
    if !path.exists() {
        return None;
    }
    match fs::read_to_string(path) {
        Ok(content) => {
            let trimmed = content.trim();
            if trimmed.is_empty() {
                None
            } else {
                Some(trimmed.to_string())
            }
        }
        Err(e) => {
            error!("✖️ 读取 style.md 失败: {}", e);
            None
        }
    }
}

/// 保存回复风格到独立文件(空字符串会删除文件)
pub fn save_style(style: &str) -> bool {
    let path = style_path();
    if let Some(parent) = path.parent() {
        let _ = fs::create_dir_all(parent);
    }

    let trimmed = style.trim();
    if trimmed.is_empty() {
        return match fs::remove_file(&path) {
            Ok(_) => true,
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => true,
            Err(e) => {
                error!("✖️ 删除 style.md 失败: {}", e);
                false
            }
        };
    }

    match fs::write(path, trimmed) {
        Ok(_) => true,
        Err(e) => {
            error!("✖️ 保存 style.md 失败: {}", e);
            false
        }
    }
}

/// 加载记忆(来自独立文件)
pub fn load_memory() -> Option<String> {
    let path = memory_path();
    if !path.exists() {
        return None;
    }
    match fs::read_to_string(path) {
        Ok(content) => {
            let trimmed = content.trim();
            if trimmed.is_empty() {
                None
            } else {
                Some(trimmed.to_string())
            }
        }
        Err(e) => {
            error!("✖️ 读取 memory.md 失败: {}", e);
            None
        }
    }
}

/// 加载灵魂(来自独立文件)
pub fn load_soul() -> Option<String> {
    let path = soul_path();
    if !path.exists() {
        return None;
    }
    match fs::read_to_string(path) {
        Ok(content) => {
            let trimmed = content.trim();
            if trimmed.is_empty() {
                None
            } else {
                Some(trimmed.to_string())
            }
        }
        Err(e) => {
            error!("✖️ 读取 soul.md 失败: {}", e);
            None
        }
    }
}

/// 保存记忆到独立文件
pub fn save_memory(content: &str) -> bool {
    let path = memory_path();
    if let Some(parent) = path.parent() {
        let _ = fs::create_dir_all(parent);
    }
    match fs::write(path, content) {
        Ok(_) => true,
        Err(e) => {
            error!("✖️ 保存 memory.md 失败: {}", e);
            false
        }
    }
}

/// 保存灵魂到独立文件
pub fn save_soul(content: &str) -> bool {
    let path = soul_path();
    if let Some(parent) = path.parent() {
        let _ = fs::create_dir_all(parent);
    }
    match fs::write(path, content) {
        Ok(_) => true,
        Err(e) => {
            error!("✖️ 保存 soul.md 失败: {}", e);
            false
        }
    }
}