566 lines
28 KiB
Rust
566 lines
28 KiB
Rust
|
|
//! 計畫 (/plan): the bot looks before it acts. 「/plan 要做的事」 puts the bot's chat in planning:
|
|||
|
|
//! it may only look (read files, search, read web pages, take screenshots) and ask the person
|
|||
|
|
//! (問題卡), then hands in a plan with `submit_plan`. The person answers on a card: 開始照計畫做
|
|||
|
|
//! (the turn goes on with every tool, now following the plan), a change in their own words (it
|
|||
|
|
//! revises and hands it in again), or 先不要 (the plan is dropped, nothing was done). While it
|
|||
|
|
//! works it keeps the steps current with `update_plan`, and the line above the input shows where
|
|||
|
|
//! it is. Like Claude Code's plan mode (read-only until the plan is approved), Cursor's Plan
|
|||
|
|
//! Mode (questions first, a plan with to-dos) and Codex's `update_plan` (one step in progress at
|
|||
|
|
//! a time, the whole list each time).
|
|||
|
|
//!
|
|||
|
|
//! The plan lives on the brain, on the bot (`Bot::plan`); screens and the phone show it. Nothing
|
|||
|
|
//! here draws or runs anything: the command, the plan's state, the two tools, what the model is
|
|||
|
|
//! told and how the person's answer is read. The window wires it in (app/plan_ui.rs), the turn
|
|||
|
|
//! keeps to it (agent.rs).
|
|||
|
|
|
|||
|
|
use serde::{Deserialize, Serialize};
|
|||
|
|
use serde_json::{json, Value};
|
|||
|
|
|
|||
|
|
/// Longest task after 「/plan」 (like /goal's condition).
|
|||
|
|
pub const MAX_TASK_CHARS: usize = 4_000;
|
|||
|
|
/// Most steps in a plan: more than this is a project, not a plan to approve in one look.
|
|||
|
|
pub const MAX_STEPS: usize = 20;
|
|||
|
|
/// A step's title, at most (a line, not a paragraph).
|
|||
|
|
pub const MAX_TITLE_CHARS: usize = 160;
|
|||
|
|
/// A step's detail, the plan's notes and its check, at most.
|
|||
|
|
const MAX_TEXT_CHARS: usize = 1_500;
|
|||
|
|
/// Plans handed in again after a change before it says the back-and-forth is long.
|
|||
|
|
pub const MANY_REVISIONS: u32 = 5;
|
|||
|
|
|
|||
|
|
/// The bot hands its plan in.
|
|||
|
|
pub const SUBMIT_TOOL: &str = "submit_plan";
|
|||
|
|
/// The bot keeps the steps of an approved plan current.
|
|||
|
|
pub const UPDATE_TOOL: &str = "update_plan";
|
|||
|
|
|
|||
|
|
/// The card's question and its two choices (anything typed instead is a change).
|
|||
|
|
pub const QUESTION: &str = "照這個計畫做嗎?";
|
|||
|
|
pub const APPROVE: &str = "開始照計畫做";
|
|||
|
|
pub const NOT_NOW: &str = "先不要";
|
|||
|
|
|
|||
|
|
/// Where a plan is.
|
|||
|
|
#[derive(Clone, Copy, Serialize, Deserialize, Debug, PartialEq, Eq, Default)]
|
|||
|
|
#[serde(rename_all = "snake_case")]
|
|||
|
|
pub enum Stage {
|
|||
|
|
/// Looking and writing the plan: only the tools that look.
|
|||
|
|
#[default]
|
|||
|
|
Drafting,
|
|||
|
|
/// Approved: every tool, following the plan.
|
|||
|
|
Doing,
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
/// One step's state (Codex's update_plan: pending, in_progress, completed).
|
|||
|
|
#[derive(Clone, Copy, Serialize, Deserialize, Debug, PartialEq, Eq, Default)]
|
|||
|
|
#[serde(rename_all = "snake_case")]
|
|||
|
|
pub enum Status {
|
|||
|
|
#[default]
|
|||
|
|
Pending,
|
|||
|
|
InProgress,
|
|||
|
|
Done,
|
|||
|
|
/// Not needed after all (the bot says why when it skips one).
|
|||
|
|
Skipped,
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
#[derive(Clone, Serialize, Deserialize, Debug, PartialEq, Default)]
|
|||
|
|
pub struct Step {
|
|||
|
|
pub title: String,
|
|||
|
|
#[serde(default)]
|
|||
|
|
pub status: Status,
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
/// A bot's plan, kept on the bot (it survives restarts).
|
|||
|
|
#[derive(Clone, Serialize, Deserialize, Debug, PartialEq, Default)]
|
|||
|
|
pub struct Plan {
|
|||
|
|
/// What 「/plan …」 asked for.
|
|||
|
|
pub task: String,
|
|||
|
|
/// When it was asked (ms).
|
|||
|
|
pub since: i64,
|
|||
|
|
#[serde(default)]
|
|||
|
|
pub stage: Stage,
|
|||
|
|
/// The approved plan's steps, as the bot last left them.
|
|||
|
|
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
|||
|
|
pub steps: Vec<Step>,
|
|||
|
|
/// Plans handed in so far that the person sent back with a change.
|
|||
|
|
#[serde(default)]
|
|||
|
|
pub revisions: u32,
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
impl Plan {
|
|||
|
|
pub fn new(task: &str, since: i64) -> Plan {
|
|||
|
|
Plan { task: task.trim().to_string(), since, ..Default::default() }
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
pub fn done(&self) -> usize {
|
|||
|
|
self.steps.iter().filter(|s| matches!(s.status, Status::Done | Status::Skipped)).count()
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
/// Every step done (or skipped).
|
|||
|
|
pub fn finished(&self) -> bool {
|
|||
|
|
self.stage == Stage::Doing && !self.steps.is_empty() && self.done() == self.steps.len()
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
/// The step it is on: the one in progress, else the next one waiting.
|
|||
|
|
pub fn current(&self) -> Option<&Step> {
|
|||
|
|
self.steps.iter().find(|s| s.status == Status::InProgress).or_else(|| self.steps.iter().find(|s| s.status == Status::Pending))
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
/// What a turn tells the window about its plan (it keeps `Bot::plan`).
|
|||
|
|
#[derive(Clone, Debug, PartialEq)]
|
|||
|
|
pub enum Event {
|
|||
|
|
/// 開始照計畫做: these are the steps now.
|
|||
|
|
Approved(Vec<Step>),
|
|||
|
|
/// 先不要 (or the card skipped): the plan is dropped.
|
|||
|
|
NotNow,
|
|||
|
|
/// Sent back with a change (on the card, or a message instead).
|
|||
|
|
Changed,
|
|||
|
|
/// `update_plan`: the steps as they stand.
|
|||
|
|
Progress(Vec<Step>),
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
/// What 「/plan …」 asks for.
|
|||
|
|
#[derive(Debug, PartialEq)]
|
|||
|
|
pub enum Command {
|
|||
|
|
/// 「/plan」: how it stands.
|
|||
|
|
Status,
|
|||
|
|
/// 「/plan clear」 (stop, off, reset, none, cancel, 清除, 取消, 停止).
|
|||
|
|
Clear,
|
|||
|
|
/// 「/plan 要做的事」: look first, then hand in a plan.
|
|||
|
|
Start(String),
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
/// 「/plan」, 「/plan clear」 or 「/plan 要做的事」; None for anything else (「/plans」 too).
|
|||
|
|
pub fn command(text: &str) -> Option<Command> {
|
|||
|
|
let rest = text.trim().strip_prefix("/plan")?;
|
|||
|
|
if rest.chars().next().is_some_and(|c| !c.is_whitespace()) {
|
|||
|
|
return None;
|
|||
|
|
}
|
|||
|
|
let arg = rest.trim();
|
|||
|
|
Some(match arg.to_lowercase().as_str() {
|
|||
|
|
"" => Command::Status,
|
|||
|
|
"clear" | "stop" | "off" | "reset" | "none" | "cancel" | "清除" | "取消" | "停止" => Command::Clear,
|
|||
|
|
_ => Command::Start(arg.to_string()),
|
|||
|
|
})
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
// ---------- the plan handed in ----------
|
|||
|
|
|
|||
|
|
/// One step as handed in.
|
|||
|
|
#[derive(Clone, Debug, PartialEq, Default)]
|
|||
|
|
pub struct DraftStep {
|
|||
|
|
pub title: String,
|
|||
|
|
pub detail: String,
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
/// `submit_plan`'s arguments, checked.
|
|||
|
|
#[derive(Clone, Debug, PartialEq, Default)]
|
|||
|
|
pub struct Draft {
|
|||
|
|
pub summary: String,
|
|||
|
|
pub steps: Vec<DraftStep>,
|
|||
|
|
/// How it will show the result is right (the last thing it does).
|
|||
|
|
pub check: String,
|
|||
|
|
/// Assumptions, risks, what it found that matters.
|
|||
|
|
pub notes: String,
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
impl Draft {
|
|||
|
|
/// The steps to follow, the first one under way (one call less for the bot: tracking cost
|
|||
|
|
/// Manus a third of its actions).
|
|||
|
|
pub fn steps(&self) -> Vec<Step> {
|
|||
|
|
self.steps.iter().enumerate().map(|(i, s)| Step { title: s.title.clone(), status: if i == 0 { Status::InProgress } else { Status::Pending } }).collect()
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
fn cut(s: &str, n: usize) -> String {
|
|||
|
|
let s = s.trim();
|
|||
|
|
if s.chars().count() <= n {
|
|||
|
|
s.to_string()
|
|||
|
|
} else {
|
|||
|
|
format!("{}…", s.chars().take(n).collect::<String>())
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
/// `submit_plan`'s arguments (a JSON object; steps as objects or plain lines).
|
|||
|
|
pub fn parse_draft(args: &str) -> Result<Draft, String> {
|
|||
|
|
let v: Value = serde_json::from_str(args).map_err(|_| "submit_plan 的參數不是 JSON 物件。".to_string())?;
|
|||
|
|
let text = |k: &str| v[k].as_str().map(|s| cut(s, MAX_TEXT_CHARS)).unwrap_or_default();
|
|||
|
|
let steps: Vec<DraftStep> = v["steps"]
|
|||
|
|
.as_array()
|
|||
|
|
.into_iter()
|
|||
|
|
.flatten()
|
|||
|
|
.filter_map(|s| match s {
|
|||
|
|
Value::String(t) => Some(DraftStep { title: cut(t, MAX_TITLE_CHARS), detail: String::new() }),
|
|||
|
|
Value::Object(_) => Some(DraftStep { title: cut(s["title"].as_str().unwrap_or(""), MAX_TITLE_CHARS), detail: cut(s["detail"].as_str().unwrap_or(""), MAX_TEXT_CHARS) }),
|
|||
|
|
_ => None,
|
|||
|
|
})
|
|||
|
|
.filter(|s| !s.title.is_empty())
|
|||
|
|
.collect();
|
|||
|
|
let d = Draft { summary: text("summary"), steps, check: text("check"), notes: text("notes") };
|
|||
|
|
if d.summary.is_empty() {
|
|||
|
|
return Err("submit_plan 需要 summary:一兩句話說要做什麼、做完是什麼樣子。".into());
|
|||
|
|
}
|
|||
|
|
if d.steps.is_empty() {
|
|||
|
|
return Err("submit_plan 需要 steps:照順序列出要做的步驟(每步一行標題,必要時加 detail)。".into());
|
|||
|
|
}
|
|||
|
|
if d.steps.len() > MAX_STEPS {
|
|||
|
|
return Err(format!("計畫有 {} 步,太多了(最多 {MAX_STEPS} 步):把小步驟合併,一步是一個看得到的結果。", d.steps.len()));
|
|||
|
|
}
|
|||
|
|
Ok(d)
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
/// The card the person answers (a 問題卡: the window, a screen and the phone all draw it).
|
|||
|
|
pub fn approval_card() -> String {
|
|||
|
|
crate::ask::to_json(&[crate::ask::Question { question: QUESTION.into(), options: vec![APPROVE.into(), NOT_NOW.into()], multiple: false, default: String::new() }])
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
/// What the person said on the card.
|
|||
|
|
#[derive(Debug, PartialEq)]
|
|||
|
|
pub enum Decision {
|
|||
|
|
Approve,
|
|||
|
|
NotNow,
|
|||
|
|
/// Their own words: what to change.
|
|||
|
|
Change(String),
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
/// The card's answer (as it travels back: a JSON list, one string per question).
|
|||
|
|
pub fn decide(answer: &str) -> Decision {
|
|||
|
|
let a = crate::ask::answers_of(answer).into_iter().next().unwrap_or_default();
|
|||
|
|
let a = a.trim();
|
|||
|
|
if a == APPROVE {
|
|||
|
|
Decision::Approve
|
|||
|
|
} else if a.is_empty() || a == NOT_NOW {
|
|||
|
|
Decision::NotNow
|
|||
|
|
} else {
|
|||
|
|
Decision::Change(a.to_string())
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
/// How the results of `submit_plan` begin (the card reads its state from them).
|
|||
|
|
const APPROVED_HEAD: &str = "使用者按了「開始照計畫做」";
|
|||
|
|
const NOT_NOW_HEAD: &str = "使用者選了「先不要」";
|
|||
|
|
const CHANGE_HEAD: &str = "使用者還沒核准,他要修改計畫";
|
|||
|
|
const WROTE_HEAD: &str = "使用者沒有按卡片";
|
|||
|
|
|
|||
|
|
/// What the bot reads after 開始照計畫做 (every tool is there from the next step on).
|
|||
|
|
pub fn approved_result(steps: &[Step]) -> String {
|
|||
|
|
format!(
|
|||
|
|
"{APPROVED_HEAD},計畫核准了。現在所有工具都能用了,接著在這一輪照計畫做(第 1 步已經標成進行中):\n{}\n每做完一步用 update_plan 更新一次:同一次把它標 done、下一步標 in_progress。",
|
|||
|
|
checklist(steps)
|
|||
|
|
)
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
/// How a plan handed in stands, from its step's result (None: still waiting on the card).
|
|||
|
|
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
|||
|
|
pub enum Outcome {
|
|||
|
|
Waiting,
|
|||
|
|
Approved,
|
|||
|
|
Changed,
|
|||
|
|
NotNow,
|
|||
|
|
/// Not a plan (its arguments were wrong): nothing to show.
|
|||
|
|
Refused,
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
pub fn outcome(result: Option<&str>) -> Outcome {
|
|||
|
|
match result {
|
|||
|
|
None => Outcome::Waiting,
|
|||
|
|
Some(r) if r.starts_with(APPROVED_HEAD) => Outcome::Approved,
|
|||
|
|
Some(r) if r.starts_with(NOT_NOW_HEAD) => Outcome::NotNow,
|
|||
|
|
Some(r) if r.starts_with(CHANGE_HEAD) || r.starts_with(WROTE_HEAD) => Outcome::Changed,
|
|||
|
|
Some(_) => Outcome::Refused,
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
pub const NOT_NOW_RESULT: &str = "使用者選了「先不要」:這個計畫先不做,計畫模式結束了。不要動手做任何事;簡短回一句就好(例如計畫留在上面,之後要做再說),等他下一步指示。";
|
|||
|
|
|
|||
|
|
/// What the bot reads after the person wrote a change on the card.
|
|||
|
|
pub fn change_result(words: &str, revisions: u32) -> String {
|
|||
|
|
let long = if revisions >= MANY_REVISIONS { format!("(已經改了 {revisions} 次:這次改完,如果還有沒說清楚的取捨,先用 ask_person 一次問清楚再交。)") } else { String::new() };
|
|||
|
|
format!("{CHANGE_HEAD}:「{words}」\n照他的意見調整(需要的話再查),再用 submit_plan 交出修改後的完整計畫。還不能動手。{long}")
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
pub const WROTE_INSTEAD_RESULT: &str = "使用者沒有按卡片,而是傳了訊息(就在下面)。照他說的調整計畫,再用 submit_plan 交出來;他在卡片上按「開始照計畫做」才算核准,在那之前還不能動手。";
|
|||
|
|
|
|||
|
|
/// A step that does something, asked for before the plan is approved.
|
|||
|
|
pub const NOT_YET: &str = "計畫模式:計畫還沒核准,現在只能查看、不能動手(這一步沒有執行)。先把需要的資料查清楚,再用 submit_plan 交出計畫;使用者核准之後才能做。";
|
|||
|
|
|
|||
|
|
// ---------- following it ----------
|
|||
|
|
|
|||
|
|
fn status_of(s: &str) -> Option<Status> {
|
|||
|
|
Some(match s.trim().to_lowercase().as_str() {
|
|||
|
|
"pending" | "todo" | "not_started" => Status::Pending,
|
|||
|
|
"in_progress" | "doing" | "active" | "started" => Status::InProgress,
|
|||
|
|
"done" | "completed" | "complete" => Status::Done,
|
|||
|
|
"skipped" | "skip" | "cancelled" | "canceled" => Status::Skipped,
|
|||
|
|
_ => return None,
|
|||
|
|
})
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
/// `update_plan`'s arguments: the whole list, each step with its status. Only one step may be in
|
|||
|
|
/// progress: the first one named so keeps it, later ones wait.
|
|||
|
|
pub fn parse_progress(args: &str) -> Result<Vec<Step>, String> {
|
|||
|
|
let v: Value = serde_json::from_str(args).map_err(|_| "update_plan 的參數不是 JSON 物件。".to_string())?;
|
|||
|
|
let mut steps = vec![];
|
|||
|
|
for s in v["steps"].as_array().into_iter().flatten() {
|
|||
|
|
let title = cut(s["title"].as_str().unwrap_or(""), MAX_TITLE_CHARS);
|
|||
|
|
if title.is_empty() {
|
|||
|
|
continue;
|
|||
|
|
}
|
|||
|
|
let status = match s["status"].as_str() {
|
|||
|
|
None => Status::Pending,
|
|||
|
|
Some(x) => status_of(x).ok_or_else(|| format!("「{title}」的 status「{x}」看不懂:用 pending、in_progress、done 或 skipped。"))?,
|
|||
|
|
};
|
|||
|
|
steps.push(Step { title, status });
|
|||
|
|
}
|
|||
|
|
if steps.is_empty() {
|
|||
|
|
return Err("update_plan 需要 steps:整份清單,每步有 title 和 status(pending、in_progress、done、skipped)。".into());
|
|||
|
|
}
|
|||
|
|
if steps.len() > MAX_STEPS {
|
|||
|
|
return Err(format!("計畫最多 {MAX_STEPS} 步。"));
|
|||
|
|
}
|
|||
|
|
let mut seen = false;
|
|||
|
|
for s in steps.iter_mut().filter(|s| s.status == Status::InProgress) {
|
|||
|
|
if seen {
|
|||
|
|
s.status = Status::Pending;
|
|||
|
|
}
|
|||
|
|
seen = true;
|
|||
|
|
}
|
|||
|
|
Ok(steps)
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
/// What the bot reads after `update_plan`.
|
|||
|
|
pub fn progress_result(steps: &[Step]) -> String {
|
|||
|
|
let p = Plan { stage: Stage::Doing, steps: steps.to_vec(), ..Default::default() };
|
|||
|
|
if p.finished() {
|
|||
|
|
return format!("進度已更新:{} 步全部完成。最後檢查成果(實際的輸出、檔案、畫面),再用一段話跟使用者回報結果。", steps.len());
|
|||
|
|
}
|
|||
|
|
let now = p.current().map(|s| format!(";接下來:{}", s.title)).unwrap_or_default();
|
|||
|
|
format!("進度已更新:{}/{} 完成{now}。", p.done(), steps.len())
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
/// The steps as a short checklist (✓ done, ▸ in progress, ○ waiting, – skipped).
|
|||
|
|
pub fn checklist(steps: &[Step]) -> String {
|
|||
|
|
steps
|
|||
|
|
.iter()
|
|||
|
|
.enumerate()
|
|||
|
|
.map(|(i, s)| {
|
|||
|
|
let mark = match s.status {
|
|||
|
|
Status::Done => "✓",
|
|||
|
|
Status::InProgress => "▸",
|
|||
|
|
Status::Pending => "○",
|
|||
|
|
Status::Skipped => "–",
|
|||
|
|
};
|
|||
|
|
format!("{mark} {}. {}", i + 1, s.title)
|
|||
|
|
})
|
|||
|
|
.collect::<Vec<_>>()
|
|||
|
|
.join("\n")
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
// ---------- what the model is told ----------
|
|||
|
|
|
|||
|
|
/// The system prompt's last part while the plan is being written.
|
|||
|
|
pub fn drafting_block(p: &Plan) -> String {
|
|||
|
|
format!(
|
|||
|
|
"\n\n〔計畫模式〕使用者用 /plan 要你先規劃、他核准後才動手。要做的事:「{}」\n\
|
|||
|
|
現在只能看、不能改:可以讀檔、列資料夾、搜尋、看網頁(web_fetch、browser 的 open/read)、截圖、查記憶和技能、用 anybot_guide 查 AnyBot 怎麼用;執行指令、改檔案、點擊或打字、送出、改設定都會被擋下。\n\
|
|||
|
|
1. 先自己查清楚現況(相關的檔案、網頁、設定、之前的對話),找出真正要改的地方和限制。查得到的就不要問。\n\
|
|||
|
|
2. 有使用者才能決定的取捨(會影響結果、沒有明顯最好的選擇),用 ask_person 一次問完,最多 3 題,每題 2 到 4 個選項、你建議的放第一個。沒有就不要問。他略過問題卡,就用你建議的選項,寫進 notes 當假設。\n\
|
|||
|
|
3. 用 {SUBMIT_TOOL} 交出計畫:只寫你建議的那一個做法(不要列好幾個方案讓他挑);summary 一兩句話說要做什麼、做完是什麼樣子;steps 照順序,通常 3 到 7 步,每步是一個看得到的結果(不是「研究一下」),寫清楚動到哪裡(檔案、網頁、帳號、哪台電腦);最後一步是驗證;check 寫怎麼證明做對了;notes 寫你的假設、風險、會花錢或對外送出、不能復原的地方。計畫要根據你查到的事實,寧可短而對:錯的計畫比沒有計畫更糟。不要在訊息裡把計畫再寫一次,卡片會顯示。\n\
|
|||
|
|
4. 使用者按「{APPROVE}」後,工具就會打開,你在同一輪接著做;他寫了修改,就照著改完再交一次。",
|
|||
|
|
p.task
|
|||
|
|
)
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
/// The system prompt's last part while the approved plan is being carried out.
|
|||
|
|
pub fn doing_block(p: &Plan) -> String {
|
|||
|
|
format!(
|
|||
|
|
"\n\n〔照計畫做〕使用者核准了這個計畫(要做的事:「{}」)。目前進度:\n{}\n\
|
|||
|
|
照順序做,同一時間只有一步是 in_progress。每做完一步用 {UPDATE_TOOL} 更新一次(傳整份清單:同一次把它標 done、下一步標 in_progress);不用每個小動作都更新。\n\
|
|||
|
|
做的時候發現計畫和實際不符(檔案不一樣、多了或少了步驟),用 {UPDATE_TOOL} 改清單,並在訊息裡說一句為什麼,不要默默偏離;要換做法、會多花很多錢或時間、或有風險的大改,先用 ask_person 問。\n\
|
|||
|
|
全部做完:用實際的結果(指令輸出、檔案內容、畫面)檢查,再用一段話回報做了什麼、怎麼確認的、還有什麼沒做。",
|
|||
|
|
p.task,
|
|||
|
|
checklist(&p.steps)
|
|||
|
|
)
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
/// The system prompt's last part for this plan, by where it is.
|
|||
|
|
pub fn block(p: &Plan) -> String {
|
|||
|
|
match p.stage {
|
|||
|
|
Stage::Drafting => drafting_block(p),
|
|||
|
|
Stage::Doing => doing_block(p),
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
// ---------- the tools ----------
|
|||
|
|
|
|||
|
|
pub fn submit_spec() -> Value {
|
|||
|
|
json!({"name": SUBMIT_TOOL,
|
|||
|
|
"description": "Hand in your plan for the person to approve (plan mode, after 「/plan」). Use it once you have looked into everything you need; the chat shows the plan as a card with 「開始照計畫做」 and a field to ask for changes, and the turn waits. If they approve, every tool is available from your next step and you carry out the plan in the same turn; if they write a change, revise and call this again with the whole plan; if they say 先不要, stop. Don't repeat the plan in your message.",
|
|||
|
|
"parameters": {"type": "object", "properties": {
|
|||
|
|
"summary": {"type": "string", "description": "One or two sentences in the person's language: what you will do and what it looks like when done."},
|
|||
|
|
"steps": {"type": "array", "description": "The steps in order, 3–7 usually (at most 20): only the approach you recommend. Each is one visible result, naming what it touches (file, page, account, computer). The last one checks the work.",
|
|||
|
|
"items": {"type": "object", "properties": {
|
|||
|
|
"title": {"type": "string", "description": "The step in one short line."},
|
|||
|
|
"detail": {"type": "string", "description": "Only when needed: how, or what exactly changes."}},
|
|||
|
|
"required": ["title"]}},
|
|||
|
|
"check": {"type": "string", "description": "How you will show it worked (a test, a command's output, the page as it looks)."},
|
|||
|
|
"notes": {"type": "string", "description": "Assumptions, risks, anything that costs money, sends something out or can't be undone."}},
|
|||
|
|
"required": ["summary", "steps"]}})
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
pub fn update_spec() -> Value {
|
|||
|
|
json!({"name": UPDATE_TOOL,
|
|||
|
|
"description": "Keep the approved plan's steps current, so the person sees where you are. Send the whole list every time, each step with its status: pending, in_progress (only one at a time), done or skipped. Call it once per finished step: mark that one done and the next in_progress in the same call (not for every small action). If the plan has to change (a step was wrong, one is missing), send the changed list and say why in your message.",
|
|||
|
|
"parameters": {"type": "object", "properties": {
|
|||
|
|
"steps": {"type": "array", "items": {"type": "object", "properties": {
|
|||
|
|
"title": {"type": "string"},
|
|||
|
|
"status": {"type": "string", "enum": ["pending", "in_progress", "done", "skipped"]}},
|
|||
|
|
"required": ["title", "status"]}}},
|
|||
|
|
"required": ["steps"]}})
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
// ---------- what the person sees ----------
|
|||
|
|
|
|||
|
|
/// 「/plan」 with nothing after it.
|
|||
|
|
pub fn status(p: Option<&Plan>) -> String {
|
|||
|
|
let Some(p) = p else { return "沒有計畫。用「/plan 要做的事」讓它先查清楚、寫出計畫給你核准,核准後才動手。".into() };
|
|||
|
|
match p.stage {
|
|||
|
|
Stage::Drafting => format!("正在規劃:{}\n還沒動手:它在查資料、寫計畫,交出來後由你決定要不要照著做。不要了就用 /plan clear。", p.task),
|
|||
|
|
Stage::Doing => format!("照計畫做:{}\n{}/{} 步完成\n{}", p.task, p.done(), p.steps.len(), checklist(&p.steps)),
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
/// The one line above the input while there is a plan.
|
|||
|
|
pub fn bar_text(p: &Plan) -> String {
|
|||
|
|
match p.stage {
|
|||
|
|
Stage::Drafting => "計畫模式 · 只查資料、寫計畫,你核准後才動手".into(),
|
|||
|
|
Stage::Doing => match p.current() {
|
|||
|
|
Some(s) => format!("照計畫做 · {}/{} · {}", p.done(), p.steps.len(), s.title),
|
|||
|
|
None => format!("照計畫做 · {}/{}", p.done(), p.steps.len()),
|
|||
|
|
},
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
/// The line left in the chat when every step is done.
|
|||
|
|
pub fn finished_note(p: &Plan) -> String {
|
|||
|
|
let skipped = p.steps.iter().filter(|s| s.status == Status::Skipped).count();
|
|||
|
|
if skipped > 0 {
|
|||
|
|
format!("計畫完成:{} 步做完({skipped} 步略過)。", p.steps.len() - skipped)
|
|||
|
|
} else {
|
|||
|
|
format!("計畫完成:{} 步都做完了。", p.steps.len())
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
/// `submit_plan`'s arguments for the phone and a screen's card: the plan, and how it stands.
|
|||
|
|
pub fn card_json(args: &str) -> Value {
|
|||
|
|
match parse_draft(args) {
|
|||
|
|
Ok(d) => json!({"summary": d.summary, "steps": d.steps.iter().map(|s| json!({"title": s.title, "detail": s.detail})).collect::<Vec<_>>(), "check": d.check, "notes": d.notes}),
|
|||
|
|
Err(_) => Value::Null,
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
#[cfg(test)]
|
|||
|
|
mod tests {
|
|||
|
|
use super::*;
|
|||
|
|
|
|||
|
|
#[test]
|
|||
|
|
fn the_command_reads_like_goal() {
|
|||
|
|
assert_eq!(command("/plan"), Some(Command::Status));
|
|||
|
|
assert_eq!(command(" /plan "), Some(Command::Status));
|
|||
|
|
assert_eq!(command("/plan clear"), Some(Command::Clear));
|
|||
|
|
assert_eq!(command("/plan 取消"), Some(Command::Clear));
|
|||
|
|
assert_eq!(command("/plan STOP"), Some(Command::Clear));
|
|||
|
|
assert_eq!(command("/plan 把部落格搬到新主機"), Some(Command::Start("把部落格搬到新主機".into())));
|
|||
|
|
assert_eq!(command("/plan\n多行\n任務"), Some(Command::Start("多行\n任務".into())));
|
|||
|
|
assert_eq!(command("/plans"), None);
|
|||
|
|
assert_eq!(command("/planning 什麼"), None);
|
|||
|
|
assert_eq!(command("先 /plan 一下"), None);
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
#[test]
|
|||
|
|
fn a_plan_needs_a_summary_and_steps() {
|
|||
|
|
assert!(parse_draft("nope").is_err());
|
|||
|
|
assert!(parse_draft(r#"{"steps": [{"title": "a"}]}"#).unwrap_err().contains("summary"));
|
|||
|
|
assert!(parse_draft(r#"{"summary": "s", "steps": []}"#).unwrap_err().contains("steps"));
|
|||
|
|
assert!(parse_draft(r#"{"summary": "s", "steps": [{"title": " "}]}"#).unwrap_err().contains("steps"));
|
|||
|
|
let many: Vec<Value> = (0..=MAX_STEPS).map(|i| json!({"title": format!("步驟 {i}")})).collect();
|
|||
|
|
assert!(parse_draft(&json!({"summary": "s", "steps": many}).to_string()).unwrap_err().contains("太多"));
|
|||
|
|
// Plain lines are steps too; long titles are cut to a line.
|
|||
|
|
let d = parse_draft(&json!({"summary": " 搬家 ", "steps": ["備份", {"title": "x".repeat(400), "detail": "細節"}], "check": "打開網站"}).to_string()).unwrap();
|
|||
|
|
assert_eq!(d.summary, "搬家");
|
|||
|
|
assert_eq!(d.steps[0], DraftStep { title: "備份".into(), detail: String::new() });
|
|||
|
|
assert_eq!(d.steps[1].title.chars().count(), MAX_TITLE_CHARS + 1);
|
|||
|
|
assert_eq!(d.steps[1].detail, "細節");
|
|||
|
|
assert_eq!(d.steps().iter().map(|s| s.status).collect::<Vec<_>>(), vec![Status::InProgress, Status::Pending]);
|
|||
|
|
assert_eq!(d.check, "打開網站");
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
#[test]
|
|||
|
|
fn the_card_answer_decides() {
|
|||
|
|
assert_eq!(decide(&json!([APPROVE]).to_string()), Decision::Approve);
|
|||
|
|
assert_eq!(decide(&json!([NOT_NOW]).to_string()), Decision::NotNow);
|
|||
|
|
assert_eq!(decide(&json!([""]).to_string()), Decision::NotNow);
|
|||
|
|
assert_eq!(decide(&json!(["第 3 步先備份資料庫"]).to_string()), Decision::Change("第 3 步先備份資料庫".into()));
|
|||
|
|
// An answer that isn't a list (an older card) is read as the words themselves.
|
|||
|
|
assert_eq!(decide(APPROVE), Decision::Approve);
|
|||
|
|
let card = crate::ask::parse(&format!("{{\"questions\": {}}}", approval_card())).unwrap();
|
|||
|
|
assert_eq!(card[0].question, QUESTION);
|
|||
|
|
assert_eq!(card[0].options, vec![APPROVE.to_string(), NOT_NOW.to_string()]);
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
#[test]
|
|||
|
|
fn the_card_reads_how_the_plan_stands_from_its_result() {
|
|||
|
|
let steps = vec![Step { title: "a".into(), status: Status::InProgress }];
|
|||
|
|
assert_eq!(outcome(None), Outcome::Waiting);
|
|||
|
|
assert_eq!(outcome(Some(&approved_result(&steps))), Outcome::Approved);
|
|||
|
|
assert_eq!(outcome(Some(NOT_NOW_RESULT)), Outcome::NotNow);
|
|||
|
|
assert_eq!(outcome(Some(&change_result("改", 1))), Outcome::Changed);
|
|||
|
|
assert_eq!(outcome(Some(WROTE_INSTEAD_RESULT)), Outcome::Changed);
|
|||
|
|
assert_eq!(outcome(Some("submit_plan 需要 steps")), Outcome::Refused);
|
|||
|
|
assert!(change_result("改", MANY_REVISIONS).contains("ask_person"));
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
#[test]
|
|||
|
|
fn progress_keeps_one_step_in_progress() {
|
|||
|
|
let steps = parse_progress(&json!({"steps": [{"title": "a", "status": "completed"}, {"title": "b", "status": "in_progress"}, {"title": "c", "status": "doing"}, {"title": "d"}]}).to_string()).unwrap();
|
|||
|
|
assert_eq!(steps.iter().map(|s| s.status).collect::<Vec<_>>(), vec![Status::Done, Status::InProgress, Status::Pending, Status::Pending]);
|
|||
|
|
assert!(parse_progress(r#"{"steps": [{"title": "a", "status": "maybe"}]}"#).unwrap_err().contains("maybe"));
|
|||
|
|
assert!(parse_progress(r#"{"steps": []}"#).is_err());
|
|||
|
|
let r = progress_result(&steps);
|
|||
|
|
assert!(r.contains("1/4") && r.contains("接下來:b"), "{r}");
|
|||
|
|
let all: Vec<Step> = steps.iter().map(|s| Step { status: Status::Done, ..s.clone() }).collect();
|
|||
|
|
assert!(progress_result(&all).contains("全部完成"));
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
#[test]
|
|||
|
|
fn where_it_stands_reads_in_one_line() {
|
|||
|
|
let mut p = Plan::new("搬部落格", 1);
|
|||
|
|
assert!(!p.finished());
|
|||
|
|
assert!(bar_text(&p).starts_with("計畫模式"));
|
|||
|
|
assert!(block(&p).contains("〔計畫模式〕") && block(&p).contains("搬部落格") && block(&p).contains(SUBMIT_TOOL));
|
|||
|
|
p.stage = Stage::Doing;
|
|||
|
|
p.steps = vec![Step { title: "備份".into(), status: Status::Done }, Step { title: "搬檔案".into(), status: Status::InProgress }, Step { title: "檢查".into(), status: Status::Pending }];
|
|||
|
|
assert_eq!(bar_text(&p), "照計畫做 · 1/3 · 搬檔案");
|
|||
|
|
assert!(block(&p).contains("〔照計畫做〕") && block(&p).contains("✓ 1. 備份\n▸ 2. 搬檔案\n○ 3. 檢查"));
|
|||
|
|
assert!(status(Some(&p)).contains("1/3 步完成"));
|
|||
|
|
assert!(status(None).contains("/plan"));
|
|||
|
|
for s in p.steps.iter_mut() {
|
|||
|
|
s.status = Status::Done;
|
|||
|
|
}
|
|||
|
|
p.steps[2].status = Status::Skipped;
|
|||
|
|
assert!(p.finished());
|
|||
|
|
assert_eq!(finished_note(&p), "計畫完成:2 步做完(1 步略過)。");
|
|||
|
|
// Old state files (no plan fields yet) still read.
|
|||
|
|
let old: Plan = serde_json::from_str(r#"{"task": "t", "since": 5}"#).unwrap();
|
|||
|
|
assert_eq!((old.stage, old.steps.len(), old.revisions), (Stage::Drafting, 0, 0));
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
#[test]
|
|||
|
|
fn the_tools_name_their_arguments() {
|
|||
|
|
assert_eq!(submit_spec()["name"], SUBMIT_TOOL);
|
|||
|
|
assert_eq!(update_spec()["name"], UPDATE_TOOL);
|
|||
|
|
assert_eq!(submit_spec()["parameters"]["required"], json!(["summary", "steps"]));
|
|||
|
|
assert_eq!(update_spec()["parameters"]["properties"]["steps"]["items"]["properties"]["status"]["enum"], json!(["pending", "in_progress", "done", "skipped"]));
|
|||
|
|
assert!(card_json(r#"{"summary": "s", "steps": ["a"]}"#)["steps"][0]["title"] == "a");
|
|||
|
|
assert!(card_json("{}").is_null());
|
|||
|
|
}
|
|||
|
|
}
|