refactor: rebuild desktop app with Tauri

This commit is contained in:
leookun committed 2026-08-24 02:49:00 +08:00
1 parent a3ec2a0dfc
commit 4053a7fb20
808 files changed
+87359 -181491

No files matched your search

+207
View File
@@ -0,0 +1,207 @@
use std::{path::Path, sync::OnceLock};
use crate::{model::ToolDefinition, Error, Result};
use super::catalog::Catalog;
static EMBEDDED_PROMPTS: include_dir::Dir<'_> =
include_dir::include_dir!("$CARGO_MANIFEST_DIR/prompt/cursor");
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum Mode {
Agent,
Ask,
Plan,
Debug,
Multitask,
Subagent,
Compaction,
}
impl Mode {
pub fn parse(value: &str) -> Result<Self> {
match value.to_ascii_lowercase().as_str() {
"agent" => Ok(Self::Agent),
"ask" => Ok(Self::Ask),
"plan" => Ok(Self::Plan),
"debug" => Ok(Self::Debug),
"multitask" => Ok(Self::Multitask),
"subagent" => Ok(Self::Subagent),
"compaction" => Ok(Self::Compaction),
other => Err(Error::Config(format!("unknown prompt mode: {other}"))),
}
}
fn name(self) -> &'static str {
match self {
Self::Agent => "agent",
Self::Ask => "ask",
Self::Plan => "plan",
Self::Debug => "debug",
Self::Multitask => "multitask",
Self::Subagent => "subagent",
Self::Compaction => "compaction",
}
}
fn index(self) -> usize {
match self {
Self::Agent => 0,
Self::Ask => 1,
Self::Plan => 2,
Self::Debug => 3,
Self::Multitask => 4,
Self::Subagent => 5,
Self::Compaction => 6,
}
}
}
#[derive(Clone, Debug)]
pub struct ModeAssets {
pub prompt: String,
pub runtime: String,
pub tools: Vec<ToolDefinition>,
}
#[derive(Clone, Debug)]
pub struct PromptAssets {
modes: [ModeAssets; 7],
}
impl PromptAssets {
pub fn load(root: &Path) -> Result<Self> {
Self::read(|path| {
let path = root.join(path);
path.exists()
.then(|| std::fs::read_to_string(path).map_err(Error::from))
.transpose()
})
}
pub fn embedded() -> Result<Self> {
Self::read(|path| {
EMBEDDED_PROMPTS
.get_file(path)
.map(|file| {
file.contents_utf8()
.map(str::to_string)
.ok_or_else(|| Error::Config(format!("prompt asset is not UTF-8: {path}")))
})
.transpose()
})
}
fn read(mut asset: impl FnMut(&str) -> Result<Option<String>>) -> Result<Self> {
let catalog = Catalog::parse(
&asset("tools.json")?
.ok_or_else(|| Error::Config("missing Cursor tools.json".into()))?,
)?;
let mut modes = Vec::with_capacity(7);
for mode in [
Mode::Agent,
Mode::Ask,
Mode::Plan,
Mode::Debug,
Mode::Multitask,
Mode::Subagent,
Mode::Compaction,
] {
let prompt = asset(&format!("{}/prompt.md", mode.name()))?
.ok_or_else(|| Error::Config(format!("missing prompt for {mode:?}")))?;
let runtime = asset(&format!("{}/runtime.md", mode.name()))?
.ok_or_else(|| Error::Config(format!("missing runtime template for {mode:?}")))?;
validate_runtime_template(mode, &runtime)?;
let manifest = asset(&format!("modes/{}.json", mode.name()))?
.ok_or_else(|| Error::Config(format!("missing manifest for {mode:?}")))?;
let tools = catalog.select_json(&manifest)?;
modes.push(ModeAssets {
prompt,
runtime,
tools,
});
}
Ok(Self {
modes: modes
.try_into()
.map_err(|_| Error::Config("incomplete Cursor prompt mode catalog".into()))?,
})
}
pub fn mode(&self, mode: Mode) -> &ModeAssets {
&self.modes[mode.index()]
}
}
const RUNTIME_VARIABLES: &[&str] = &[
"REQUEST_CONTEXT",
"OPEN_FILES",
"SELECTED_CONTEXT",
"ACTION_CONTEXT",
"TIMESTAMP",
"USER_QUERY",
"DEBUG_SERVER_ENDPOINT",
"DEBUG_LOG_PATH",
"DEBUG_SESSION_ID",
];
fn validate_runtime_template(mode: Mode, template: &str) -> Result<()> {
let expression = runtime_expression();
for capture in expression.captures_iter(template) {
let name = &capture[1];
if !RUNTIME_VARIABLES.contains(&name) {
return Err(Error::Config(format!(
"unknown variable in {mode:?} runtime template: {name}"
)));
}
}
for required in ["TIMESTAMP", "USER_QUERY"] {
let token = format!("{{{{{required}}}}}");
if !template.contains(&token) {
return Err(Error::Config(format!(
"{mode:?} runtime template is missing {token}"
)));
}
}
let stripped = expression.replace_all(template, "");
if stripped.contains("{{") || stripped.contains("}}") {
return Err(Error::Config(format!(
"malformed placeholder in {mode:?} runtime template"
)));
}
Ok(())
}
pub(super) fn runtime_expression() -> &'static regex::Regex {
static EXPRESSION: OnceLock<regex::Regex> = OnceLock::new();
EXPRESSION.get_or_init(|| {
regex::Regex::new(r"\{\{([A-Z_]+)\}\}").expect("valid runtime placeholder expression")
})
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn direct_semble_tools_are_available_in_every_working_mode() {
let assets = PromptAssets::embedded().unwrap();
for mode in [
Mode::Agent,
Mode::Ask,
Mode::Plan,
Mode::Debug,
Mode::Multitask,
Mode::Subagent,
] {
let names = assets
.mode(mode)
.tools
.iter()
.map(|tool| tool.name.as_str())
.collect::<Vec<_>>();
assert!(names.contains(&"SembleSearch"), "missing in {mode:?}");
assert!(names.contains(&"SembleFindRelated"), "missing in {mode:?}");
}
}
}
+93
View File
@@ -0,0 +1,93 @@
use std::collections::HashMap;
use serde::Deserialize;
use serde_json::Value;
use crate::{model::ToolDefinition, Error, Result};
#[derive(Deserialize)]
struct Manifest {
tools: Vec<ManifestTool>,
}
#[derive(Deserialize)]
#[serde(untagged)]
enum ManifestTool {
Name(String),
Variant { name: String, variant: String },
}
pub(super) struct Catalog {
tools: HashMap<String, ToolDefinition>,
variants: HashMap<String, ToolDefinition>,
}
impl Catalog {
pub(super) fn parse(json: &str) -> Result<Self> {
let value: Value = serde_json::from_str(json)?;
let tools = value
.get("tools")
.and_then(Value::as_array)
.ok_or_else(|| Error::Config("tools.json is missing tools".into()))?
.iter()
.map(parse_tool)
.map(|result| result.map(|tool| (tool.name.clone(), tool)))
.collect::<Result<HashMap<_, _>>>()?;
let variants = value
.get("variants")
.and_then(Value::as_object)
.into_iter()
.flat_map(|variants| variants.iter())
.map(|(name, value)| parse_tool(value).map(|tool| (name.clone(), tool)))
.collect::<Result<HashMap<_, _>>>()?;
Ok(Self { tools, variants })
}
pub(super) fn select_json(&self, manifest: &str) -> Result<Vec<ToolDefinition>> {
let manifest: Manifest = serde_json::from_str(manifest)?;
self.select(&manifest)
}
fn select(&self, manifest: &Manifest) -> Result<Vec<ToolDefinition>> {
manifest
.tools
.iter()
.map(|entry| match entry {
ManifestTool::Name(name) => self.tools.get(name).cloned().ok_or_else(|| {
Error::Config(format!("tool manifest references unknown schema: {name}"))
}),
ManifestTool::Variant { name, variant } => self
.variants
.get(&format!("{name}.{variant}"))
.cloned()
.ok_or_else(|| {
Error::Config(format!(
"tool manifest references unknown variant: {name}.{variant}"
))
}),
})
.collect()
}
}
fn parse_tool(tool: &Value) -> Result<ToolDefinition> {
let function = tool
.get("function")
.ok_or_else(|| Error::Config("tool is missing function".into()))?;
Ok(ToolDefinition {
name: function
.get("name")
.and_then(Value::as_str)
.ok_or_else(|| Error::Config("tool is missing name".into()))?
.into(),
description: function
.get("description")
.and_then(Value::as_str)
.ok_or_else(|| Error::Config("tool is missing description".into()))?
.into(),
parameters: function
.get("parameters")
.cloned()
.ok_or_else(|| Error::Config("tool is missing parameters".into()))?,
})
}
+93
View File
@@ -0,0 +1,93 @@
use std::collections::BTreeMap;
use crate::{
model::{ModelSpec, PromptSpec, ToolDefinition},
Error, Result,
};
use super::{assets::runtime_expression, Mode, PromptAssets};
#[derive(Clone)]
pub struct PromptCompiler {
assets: PromptAssets,
}
impl PromptCompiler {
pub fn new(assets: PromptAssets) -> Self {
Self { assets }
}
pub fn runtime_message(&self, mode: Mode, values: &BTreeMap<&str, String>) -> Result<String> {
render(&self.assets.mode(mode).runtime, values)
}
pub fn prompt_spec(
&self,
mode: Mode,
model: &ModelSpec,
dynamic_tools: &[ToolDefinition],
suppress_subagent_progress: bool,
) -> Result<PromptSpec> {
let mut tools = self.tools(mode, suppress_subagent_progress);
let mut dynamic_tools = dynamic_tools.to_vec();
dynamic_tools.sort_by(|left, right| left.name.cmp(&right.name));
append_dynamic_tools(&mut tools, dynamic_tools)?;
if !model.supports_image_generation {
tools.retain(|tool| tool.name != "GenerateImage");
}
let fake_model_name = model
.display_name
.as_deref()
.unwrap_or(model.model_id.as_str());
Ok(PromptSpec {
instructions: self
.assets
.mode(mode)
.prompt
.replace("{{FAKE_MODEL_NAME}}", fake_model_name),
tools,
})
}
fn tools(&self, mode: Mode, suppress_subagent_progress: bool) -> Vec<ToolDefinition> {
let mut tools = self.assets.mode(mode).tools.clone();
if mode == Mode::Subagent && suppress_subagent_progress {
tools.retain(|tool| tool.name != "UpdateCurrentStep");
}
tools
}
}
fn render(template: &str, values: &BTreeMap<&str, String>) -> Result<String> {
let expression = runtime_expression();
let mut output = String::with_capacity(template.len());
let mut cursor = 0;
for capture in expression.captures_iter(template) {
let token = capture.get(0).expect("runtime template token");
let name = &capture[1];
let value = values
.get(name)
.ok_or_else(|| Error::Protocol(format!("runtime template value is missing: {name}")))?;
output.push_str(&template[cursor..token.start()]);
output.push_str(value);
cursor = token.end();
}
output.push_str(&template[cursor..]);
Ok(output.trim().to_string())
}
fn append_dynamic_tools(
tools: &mut Vec<ToolDefinition>,
additions: Vec<ToolDefinition>,
) -> Result<()> {
for tool in additions {
if tools.iter().any(|existing| existing.name == tool.name) {
return Err(Error::Protocol(format!(
"dynamic MCP tool conflicts with a mode tool: {}",
tool.name
)));
}
tools.push(tool);
}
Ok(())
}
@@ -0,0 +1,47 @@
use serde::{Deserialize, Serialize};
use serde_json::Value;
use crate::model::{CanonicalMessage, MessageContent};
#[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq)]
pub struct DerivedState {
pub todos: Option<Value>,
pub plan: Option<Value>,
}
pub fn fold_derived_state(messages: &[CanonicalMessage]) -> DerivedState {
let mut state = DerivedState::default();
let mut calls = std::collections::HashMap::<String, (String, Value)>::new();
for message in messages {
match &message.content {
MessageContent::Assistant { tool_calls, .. } => {
for call in tool_calls {
calls.insert(
call.call_id.clone(),
(call.name.clone(), call.arguments.clone()),
);
}
}
MessageContent::ToolResult(result) if !result.is_error => {
let Some((name, input)) = calls.get(&result.call_id).cloned() else {
continue;
};
match normalize(&name).as_str() {
"todowrite" | "updatetodos" => state.todos = Some(input),
"createplan" | "updateplan" | "writeplan" => state.plan = Some(input),
_ => {}
}
}
_ => {}
}
}
state
}
fn normalize(value: &str) -> String {
value
.chars()
.filter(|character| character.is_ascii_alphanumeric())
.flat_map(char::to_lowercase)
.collect()
}
+8
View File
@@ -0,0 +1,8 @@
mod assets;
mod catalog;
mod compiler;
mod derived_state;
pub use assets::*;
pub use compiler::*;
pub use derived_state::*;