ziyuan-cli 1.49.1

紫垣 ZiYuan:用中国古代朝廷角色组织多智能体协作的命令行工具,改动须用户审阅批准才写入文件。
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
//! 诏令、模板、驿传与玉玺上限参数解析。

use std::collections::BTreeSet;
use std::env;
use std::error::Error;
use std::io;
use ziyuan_core::{Capability, Department, Office, Seal, TaskId, Template};

use super::Command;

/// `edict --template` 的模板名,以及哪些项由命令行显式给出(其余取模板的)。
#[derive(Debug)]
pub(crate) struct TemplateChoice {
    pub(crate) name: String,
    pub(crate) department: bool,
    pub(crate) tools: bool,
    pub(crate) mcp: bool,
    pub(crate) scope: bool,
}

pub(crate) fn parse_edict(mut args: Vec<String>) -> Result<Command, Box<dyn Error>> {
    const USAGE: &str = "用法: ziyuan edict [--plan] [--template <模板>] [--dept works] [--scope <路径>]... [--tools <工具,…>|none] [--mcp <授权,…>] [--queue] <诏令内容>
  或: ziyuan edict --from-plan <诏令ID> [--scope <路径>]... [--no-tests] [--queue] [补充指示]
  或: ziyuan edict --revise <诏令ID> [--scope <路径>]... [--no-tests] [--queue] [--note <修订指示>] [修订指示]\n  或: ziyuan edict --follow-up <诏令ID> [--dept <部门>] [--scope <路径>]... [--queue] <追问内容>\n  或: ziyuan edict --resume-failed <诏令ID> [--scope <路径>]... [--queue] [--note <补充指示>] [补充指示]";
    let mut department = None;
    let mut queue = false;
    let mut plan_mode = false;
    let mut from_plan: Option<TaskId> = None;
    let mut revise: Option<TaskId> = None;
    let mut follow_up: Option<TaskId> = None;
    let mut resume_failed: Option<TaskId> = None;
    let mut note_flag: Option<String> = None;
    let mut no_tests = false;
    let mut seal = Seal::default();
    let mut scope = Vec::new();
    let (mut template, mut tools_given, mut mcp_given) = (None, false, false);
    while let Some(flag) = args.first().cloned() {
        match flag.as_str() {
            "--queue" => {
                args.remove(0);
                queue = true;
            }
            "--plan" => {
                args.remove(0);
                plan_mode = true;
            }
            "--no-tests" => {
                args.remove(0);
                no_tests = true;
            }
            "--from-plan" => {
                if args.len() < 2 {
                    return Err(USAGE.into());
                }
                args.remove(0);
                let value = args.remove(0);
                from_plan = Some(TaskId(value.parse::<u64>().map_err(|_| USAGE)?));
            }
            "--revise" => {
                if args.len() < 2 {
                    return Err(USAGE.into());
                }
                args.remove(0);
                let value = args.remove(0);
                revise = Some(TaskId(value.parse::<u64>().map_err(|_| USAGE)?));
            }
            "--follow-up" => {
                if args.len() < 2 {
                    return Err(USAGE.into());
                }
                args.remove(0);
                let value = args.remove(0);
                follow_up = Some(TaskId(value.parse::<u64>().map_err(|_| USAGE)?));
            }
            "--resume-failed" => {
                if args.len() < 2 {
                    return Err(USAGE.into());
                }
                args.remove(0);
                let value = args.remove(0);
                resume_failed = Some(TaskId(value.parse::<u64>().map_err(|_| USAGE)?));
            }
            "--note" => {
                if args.len() < 2 {
                    return Err(USAGE.into());
                }
                args.remove(0);
                note_flag = Some(args.remove(0));
            }
            "--dept" | "--scope" | "--tools" | "--template" | "--mcp" => {
                if args.len() < 2 {
                    return Err(USAGE.into());
                }
                args.remove(0);
                let value = args.remove(0);
                match flag.as_str() {
                    "--dept" => department = Some(value.parse::<Department>()?),
                    "--scope" => scope.push(value),
                    "--template" => template = Some(value),
                    "--mcp" => {
                        seal.mcp = parse_mcp(&value);
                        mcp_given = true;
                    }
                    _ => {
                        seal.capabilities = parse_capabilities(&value)?;
                        tools_given = true;
                    }
                }
            }
            _ => break,
        }
    }
    let special_modes = usize::from(from_plan.is_some())
        + usize::from(revise.is_some())
        + usize::from(follow_up.is_some())
        + usize::from(resume_failed.is_some());
    if special_modes > 1 {
        return Err(
            "`--from-plan`、`--revise`、`--follow-up` 与 `--resume-failed` 不能同时使用".into(),
        );
    }
    if let Some(plan) = from_plan {
        if plan_mode
            || template.is_some()
            || department.is_some()
            || tools_given
            || mcp_given
            || note_flag.is_some()
        {
            return Err(
                "`--from-plan` 固定下发工部写诏令,不能同时使用 --plan / --template / --dept / --tools / --mcp / --note"
                    .into(),
            );
        }
        return Ok(Command::EdictFromPlan {
            plan,
            scope,
            run_tests: !no_tests,
            queue,
            extra: args.join(" "),
        });
    }
    if let Some(source) = revise {
        if plan_mode || template.is_some() || department.is_some() || tools_given || mcp_given {
            return Err(
                "`--revise` 固定下发工部修订诏令,不能同时使用 --plan / --template / --dept / --tools / --mcp"
                    .into(),
            );
        }
        let trailing = args.join(" ");
        let note = match (note_flag, trailing.is_empty()) {
            (Some(n), true) => n,
            (Some(n), false) if n.trim().is_empty() => trailing,
            (Some(n), false) => format!("{n}\n{trailing}"),
            (None, _) => trailing,
        };
        return Ok(Command::EdictRevise {
            source,
            scope,
            run_tests: no_tests.then_some(false),
            queue,
            note,
        });
    }
    if let Some(source) = follow_up {
        if plan_mode
            || template.is_some()
            || tools_given
            || mcp_given
            || note_flag.is_some()
            || no_tests
        {
            return Err(
                "`--follow-up` 固定以只读玉玺追查前件实录,不能同时使用 --plan / --template / --tools / --mcp / --note / --no-tests"
                    .into(),
            );
        }
        let question = args.join(" ");
        if question.trim().is_empty() {
            return Err("`--follow-up` 须提供非空的追问内容".into());
        }
        return Ok(Command::EdictFollowUp {
            source,
            department,
            scope,
            queue,
            question,
        });
    }
    if let Some(source) = resume_failed {
        if plan_mode
            || template.is_some()
            || department.is_some()
            || tools_given
            || mcp_given
            || no_tests
        {
            return Err(
                "`--resume-failed` 沿用前次中断诏令的部门与玉玺授权,不能同时使用 --plan / --template / --dept / --tools / --mcp / --no-tests"
                    .into(),
            );
        }
        let trailing = args.join(" ");
        let note = match (note_flag, trailing.is_empty()) {
            (Some(n), true) => n,
            (Some(n), false) if n.trim().is_empty() => trailing,
            (Some(n), false) => format!("{n}\n{trailing}"),
            (None, _) => trailing,
        };
        return Ok(Command::EdictResumeFailed {
            source,
            scope,
            queue,
            note,
        });
    }
    if note_flag.is_some() {
        return Err("`--note` 只能配合 `--revise` 或 `--resume-failed` 使用".into());
    }
    if no_tests {
        return Err("`--no-tests` 只能配合 `--from-plan` 或 `--revise` 使用".into());
    }
    if plan_mode {
        if template.is_some() {
            return Err("`--plan` 已按内置「条陈」模板下诏,不能同时指定 `--template`".into());
        }
        if tools_given && seal.capabilities.iter().any(|c| c.is_works_only()) {
            return Err("条陈阶段只读,不得授予 write_file 或 run_tests".into());
        }
        template = Some(ziyuan_governance::PLAN_TEMPLATE.to_owned());
    }
    let template = template.map(|name| TemplateChoice {
        name,
        department: department.is_some(),
        tools: tools_given,
        mcp: mcp_given,
        scope: !scope.is_empty(),
    });
    if args.is_empty() && template.is_none() {
        return Err(USAGE.into());
    }
    if !scope.is_empty() {
        // 越出项目的路径由治理层拒绝;这里尽早指出不存在的路径。
        let root = env::current_dir()?;
        if let Some(missing) = scope.iter().find(|p| !root.join(p).exists()) {
            return Err(format!("查阅范围不存在: {missing}").into());
        }
        seal.scope = scope;
    }
    let department = if let Some(department) = department {
        department
    } else {
        let combined = args.join(" ").to_lowercase();
        if combined.contains("任免") || combined.contains("官员") || combined.contains("考绩")
        {
            Department::Personnel
        } else {
            Department::Works
        }
    };
    Ok(Command::Edict {
        department,
        text: args.join(" "),
        queue,
        seal,
        template,
    })
}

/// `template`(列出)、`template save <名> [--dept] [--scope]... [--tools] --criteria <甲;乙> <内容>`、
/// `template rm <名>`。
pub(crate) fn parse_template(mut args: Vec<String>) -> Result<Command, Box<dyn Error>> {
    const USAGE: &str = "用法: ziyuan template | template save <名> [--dept works] [--scope <路径>]... [--tools <工具,…>|none] [--mcp <授权,…>] --criteria <甲;乙> <内容> | template rm <名>";
    match args.first().map(String::as_str) {
        None => return Ok(Command::Templates),
        Some("rm") if args.len() == 2 => return Ok(Command::RemoveTemplate(args.remove(1))),
        Some("save") if args.len() >= 2 => {}
        _ => return Err(USAGE.into()),
    }
    args.remove(0);
    let name = args.remove(0);
    let mut template = Template {
        department: Department::Works,
        text: String::new(),
        seal: Seal::default(),
        criteria: Vec::new(),
    };
    let mut scope = Vec::new();
    while let Some(flag) = args.first().cloned() {
        if !matches!(
            flag.as_str(),
            "--dept" | "--scope" | "--tools" | "--mcp" | "--criteria"
        ) {
            break;
        }
        if args.len() < 2 {
            return Err(USAGE.into());
        }
        args.remove(0);
        let value = args.remove(0);
        match flag.as_str() {
            "--dept" => template.department = value.parse()?,
            "--scope" => scope.push(value),
            "--tools" => template.seal.capabilities = parse_capabilities(&value)?,
            "--mcp" => template.seal.mcp = parse_mcp(&value),
            _ => {
                template.criteria = value
                    .split([';', ';'])
                    .map(str::trim)
                    .filter(|c| !c.is_empty())
                    .map(str::to_owned)
                    .collect()
            }
        }
    }
    if !scope.is_empty() {
        template.seal.scope = scope;
    }
    template.text = args.join(" ");
    if template.text.trim().is_empty() || template.criteria.is_empty() {
        return Err(USAGE.into());
    }
    Ok(Command::SaveTemplate { name, template })
}

/// `post [--dept works] [--station 驿站] [--urgent] <内容|->`;`-` 从标准输入读取内容。
pub(crate) fn parse_post(mut args: Vec<String>) -> Result<Command, Box<dyn Error>> {
    const USAGE: &str =
        "用法: ziyuan post [--dept works] [--station 驿站] [--urgent] <内容|-(从标准输入读取)>";
    let (mut department, mut station, mut urgent) = (Department::Works, "驿站".to_owned(), false);
    while let Some(flag) = args.first().cloned() {
        match flag.as_str() {
            "--urgent" => {
                args.remove(0);
                urgent = true;
            }
            "--dept" | "--station" if args.len() >= 2 => {
                args.remove(0);
                let value = args.remove(0);
                if flag == "--dept" {
                    department = value.parse()?;
                } else {
                    station = value;
                }
            }
            "--dept" | "--station" => return Err(USAGE.into()),
            _ => break,
        }
    }
    let text = match args.as_slice() {
        [] => return Err(USAGE.into()),
        [dash] if dash == "-" => {
            let mut text = String::new();
            io::Read::read_to_string(&mut io::stdin(), &mut text)?;
            text.trim().to_owned()
        }
        _ => args.join(" "),
    };
    Ok(Command::Post {
        department,
        station,
        urgent,
        text,
    })
}

/// `ceiling <官职> default`,或 `--scope`/`--tools`(与诏令玉玺同义;未给出的一项不设限)。
pub(crate) fn parse_ceiling(mut args: Vec<String>) -> Result<Command, Box<dyn Error>> {
    const USAGE: &str = "用法: ziyuan ceiling <官职> [--scope <路径>]... [--tools <工具,…>|none] [--mcp <授权,…>|none] | default";
    if args.is_empty() {
        return Err(USAGE.into());
    }
    let office: Office = args.remove(0).parse()?;
    if args == ["default"] {
        return Ok(Command::Ceiling(office, None));
    }
    // 未给 --mcp 时外藩不设限(`*`),诏令仍须逐件授权。
    let mut seal = Seal {
        mcp: ["*".to_owned()].into(),
        ..Seal::default()
    };
    let mut scope = Vec::new();
    for pair in args.chunks(2) {
        match pair {
            [flag, value] if flag == "--scope" => scope.push(value.clone()),
            [flag, value] if flag == "--tools" => seal.capabilities = parse_capabilities(value)?,
            [flag, value] if flag == "--mcp" => seal.mcp = parse_mcp(value),
            _ => return Err(USAGE.into()),
        }
    }
    if args.is_empty() {
        return Err(USAGE.into());
    }
    if !scope.is_empty() {
        seal.scope = scope;
    }
    Ok(Command::Ceiling(office, Some(seal)))
}

/// 外藩授权:`none` 为不授;否则为逗号分隔的 `服务`、`服务/工具` 或 `*`(合法性由治理层校验)。
pub(crate) fn parse_mcp(value: &str) -> BTreeSet<String> {
    if value == "none" {
        return BTreeSet::new();
    }
    value
        .split([',', ','])
        .map(str::trim)
        .filter(|g| !g.is_empty())
        .map(str::to_owned)
        .collect()
}

/// `none` 表示不授予任何工具;否则为逗号分隔的工具名。
pub(crate) fn parse_capabilities(value: &str) -> Result<BTreeSet<Capability>, Box<dyn Error>> {
    if value == "none" {
        return Ok(BTreeSet::new());
    }
    Ok(value
        .split(',')
        .map(str::parse::<Capability>)
        .collect::<Result<_, _>>()?)
}