feat: initialize server structure and database schema

- Added initial server setup with Cargo.toml defining dependencies and project structure.
- Created build.rs for generating protobuf bindings and validating wire contracts.
- Established database schema with initial migration files for conversations, messages, and runs.
- Introduced tools and prompts for Cursor functionality, enhancing user interaction capabilities.
This commit is contained in:
leookun committed 2026-08-30 01:33:39 +08:00
1 parent d200b3791d
commit 44e2d8057a
206 files changed
+37923 -21

No files matched your search

+180
View File
@@ -0,0 +1,180 @@
//! Loads embedded Cursor Prompt assets.
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] = &[
"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")
})
}
+3
View File
@@ -0,0 +1,3 @@
//! Routes Prompt asset loading through the Tool schema registry.
pub(super) use crate::cursor::tools::registry::ToolRegistry as Catalog;
+94
View File
@@ -0,0 +1,94 @@
//! Compiles stable Prompt specifications for Cursor modes.
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,83 @@
//! Builds deterministic prompt state derived from Conversation context.
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(apply_todo_write(state.todos.take(), input));
}
"createplan" | "updateplan" | "writeplan" => state.plan = Some(input),
_ => {}
}
}
_ => {}
}
}
state
}
fn apply_todo_write(current: Option<Value>, mut input: Value) -> Value {
if !input.get("merge").and_then(Value::as_bool).unwrap_or(false) {
return input;
}
let mut todos = current
.as_ref()
.and_then(|value| value.get("todos"))
.and_then(Value::as_array)
.cloned()
.unwrap_or_default();
let patches = input
.get("todos")
.and_then(Value::as_array)
.cloned()
.unwrap_or_default();
for patch in patches {
let existing = patch.get("id").and_then(Value::as_str).and_then(|id| {
todos
.iter_mut()
.find(|todo| todo.get("id").and_then(Value::as_str) == Some(id))
});
match (existing, patch) {
(Some(Value::Object(todo)), Value::Object(patch)) => todo.extend(patch),
(_, patch) => todos.push(patch),
}
}
if let Some(object) = input.as_object_mut() {
object.insert("merge".into(), Value::Bool(false));
object.insert("todos".into(), Value::Array(todos));
}
input
}
fn normalize(value: &str) -> String {
value
.chars()
.filter(|character| character.is_ascii_alphanumeric())
.flat_map(char::to_lowercase)
.collect()
}
+10
View File
@@ -0,0 +1,10 @@
//! Exposes Cursor Prompt compilation.
mod assets;
mod catalog;
mod compiler;
mod derived_state;
pub use assets::*;
pub use compiler::*;
pub use derived_state::*;