mirror of
https://wget.la/https://github.com/leookun/cursor-byok
synced 2026-12-01 01:05:10 +08:00
Merge remote-tracking branch 'origin/main' into pr-385-merge
# Conflicts: # server/tests/interrupt.rs
This commit is contained in:
commit
4c3fe230ce
333 files changed
+14679
-48321
No files matched your search
@@ -146,6 +146,37 @@ async fn decode_part<T: Message + Default>(
|
||||
.map_err(|error| Error::Protocol(format!("invalid {name} context Blob: {error}")))
|
||||
}
|
||||
|
||||
/// 把本地 md 规则目录(rules 服务的存储)合并进请求上下文,
|
||||
/// 使 BYOK 运行在 IDE 未携带这些规则时也能消费它们。
|
||||
/// 与 IDE 已发规则按内容去重;读取失败只告警,不影响运行。
|
||||
pub fn merge_local_rules(context: &mut pb::RequestContext, rules_dir: &Path) {
|
||||
let records = match crate::cursor::services::knowledge::RuleStore::open(rules_dir.into())
|
||||
.and_then(|store| store.list())
|
||||
{
|
||||
Ok(records) => records,
|
||||
Err(error) => {
|
||||
tracing::warn!(%error, "cannot read local rules; continuing without them");
|
||||
return;
|
||||
}
|
||||
};
|
||||
let existing = context
|
||||
.rules
|
||||
.iter()
|
||||
.chain(context.non_file_rules.iter())
|
||||
.map(|rule| rule.content.trim().to_owned())
|
||||
.chain(context.cloud_rule.iter().map(|rule| rule.trim().to_owned()))
|
||||
.collect::<HashSet<_>>();
|
||||
for record in records {
|
||||
if record.knowledge.trim().is_empty() || existing.contains(record.knowledge.trim()) {
|
||||
continue;
|
||||
}
|
||||
context.non_file_rules.push(pb::CursorRule {
|
||||
content: record.knowledge,
|
||||
..Default::default()
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
pub fn request_context(request: &pb::AgentRunRequest) -> Option<&pb::RequestContext> {
|
||||
let action = request.action.as_ref()?;
|
||||
action
|
||||
@@ -563,3 +594,48 @@ fn xml(value: &str) -> String {
|
||||
.replace('<', "<")
|
||||
.replace('>', ">")
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn rule(content: &str) -> pb::CursorRule {
|
||||
pb::CursorRule {
|
||||
content: content.into(),
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn merge_local_rules_appends_and_dedupes_by_content() {
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
std::fs::write(directory.path().join("a.md"), "shared rule").unwrap();
|
||||
std::fs::write(directory.path().join("b.md"), "local only rule").unwrap();
|
||||
std::fs::write(directory.path().join("c.md"), " \n").unwrap();
|
||||
|
||||
let mut context = pb::RequestContext {
|
||||
non_file_rules: vec![rule(" shared rule ")],
|
||||
..Default::default()
|
||||
};
|
||||
merge_local_rules(&mut context, directory.path());
|
||||
|
||||
let contents = context
|
||||
.non_file_rules
|
||||
.iter()
|
||||
.map(|rule| rule.content.as_str())
|
||||
.collect::<Vec<_>>();
|
||||
assert_eq!(
|
||||
contents,
|
||||
[" shared rule ", "local only rule"],
|
||||
"IDE-sent duplicate is kept once and blank local rules are skipped"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn merge_local_rules_survives_a_missing_directory() {
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let mut context = pb::RequestContext::default();
|
||||
merge_local_rules(&mut context, &directory.path().join("nested/rules"));
|
||||
assert!(context.non_file_rules.is_empty());
|
||||
}
|
||||
}
|
||||
@@ -51,6 +51,7 @@ pub(crate) struct PrepareDependencies<'a> {
|
||||
pub checkpoint: &'a CheckpointBuilder,
|
||||
pub blob_sync: &'a BlobSynchronizer,
|
||||
pub context_sync: &'a RequestContextSynchronizer,
|
||||
pub local_rules_dir: Option<&'a std::path::Path>,
|
||||
}
|
||||
|
||||
pub(crate) async fn prepare(
|
||||
@@ -64,6 +65,7 @@ pub(crate) async fn prepare(
|
||||
checkpoint,
|
||||
blob_sync,
|
||||
context_sync,
|
||||
local_rules_dir,
|
||||
} = dependencies;
|
||||
checkpoint
|
||||
.import_prefetched(&request.pre_fetched_blobs)
|
||||
@@ -119,7 +121,11 @@ pub(crate) async fn prepare(
|
||||
.artifact("history_projection", "byok_server", &encoded, summary)
|
||||
.await;
|
||||
}
|
||||
let request_context = context::hydrate(request, context_sync).await?;
|
||||
let mut request_context = context::hydrate(request, context_sync).await?;
|
||||
if let Some(rules_dir) = local_rules_dir {
|
||||
context::merge_local_rules(&mut request_context, rules_dir);
|
||||
}
|
||||
let request_context = request_context;
|
||||
let ActionProjection {
|
||||
mode: mode_number,
|
||||
mut turn_user,
|
||||
|
||||
@@ -343,7 +343,14 @@ impl ConversationOutput {
|
||||
let call = calls.get_mut(&index).ok_or_else(|| {
|
||||
Error::Protocol(format!("unknown completed tool index: {index}"))
|
||||
})?;
|
||||
call.arguments = serde_json::from_str(&call.arguments_text)?;
|
||||
// A tool call with no arguments streams no argument text.
|
||||
// Treat empty text as an empty object, matching the model
|
||||
// cycle, instead of failing the run on `from_str("")`.
|
||||
call.arguments = if call.arguments_text.trim().is_empty() {
|
||||
serde_json::json!({})
|
||||
} else {
|
||||
serde_json::from_str(&call.arguments_text)?
|
||||
};
|
||||
}
|
||||
RunEvent::Usage(usage) => {
|
||||
if !self.context.compacting {
|
||||
|
||||
@@ -26,6 +26,8 @@ pub(crate) struct ConversationDependencies {
|
||||
pub provider: Arc<dyn Provider>,
|
||||
pub compiler: PromptCompiler,
|
||||
pub web_cache: WebCache,
|
||||
/// 本地 rules 服务的 md 存储目录;编译请求上下文时合并其中的规则。
|
||||
pub local_rules_dir: Option<std::path::PathBuf>,
|
||||
}
|
||||
|
||||
struct RegistryInner {
|
||||
@@ -47,6 +49,7 @@ impl ConversationRegistry {
|
||||
provider: Arc<dyn Provider>,
|
||||
compiler: PromptCompiler,
|
||||
web_cache: WebCache,
|
||||
local_rules_dir: Option<std::path::PathBuf>,
|
||||
) -> Self {
|
||||
Self {
|
||||
inner: Arc::new(RegistryInner {
|
||||
@@ -58,6 +61,7 @@ impl ConversationRegistry {
|
||||
provider,
|
||||
compiler,
|
||||
web_cache,
|
||||
local_rules_dir,
|
||||
},
|
||||
}),
|
||||
}
|
||||
|
||||
@@ -471,6 +471,7 @@ fn spawn_run_request(
|
||||
checkpoint: &checkpoint,
|
||||
blob_sync: &blob_sync,
|
||||
context_sync: &context_sync,
|
||||
local_rules_dir: dependencies.local_rules_dir.as_deref(),
|
||||
},
|
||||
) => prepared,
|
||||
};
|
||||
|
||||
@@ -254,7 +254,7 @@ async fn forward_or(
|
||||
match proxy::forward_buffered(&upstream, request).await {
|
||||
Ok(response) if response.status.is_success() => Ok(response.into_response()),
|
||||
Ok(response) => {
|
||||
tracing::warn!(status = %response.status, "Cursor identity upstream rejected request; using local identity");
|
||||
tracing::debug!(status = %response.status, "Cursor identity upstream rejected request; using local identity");
|
||||
fallback()
|
||||
}
|
||||
Err(error) => {
|
||||
|
||||
@@ -0,0 +1,356 @@
|
||||
//! Serves Cursor user rules: upstream-first with an offline markdown cache.
|
||||
//!
|
||||
//! 每个请求先回放离线日志再尝试上游;上游成功时把结果写穿到本地镜像,
|
||||
//! 上游不可达时降级为本地 md 存储并记录日志等待回放。
|
||||
mod store;
|
||||
mod sync;
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use axum::{
|
||||
body::{to_bytes, Body, Bytes},
|
||||
extract::Extension,
|
||||
http::{header, Request, Response},
|
||||
};
|
||||
use prost::Message;
|
||||
|
||||
use crate::{api::cursor::proxy, config, cursor::protocol::connect, Result};
|
||||
|
||||
pub(crate) use store::{RuleRecord, RuleStore};
|
||||
|
||||
#[derive(Clone, PartialEq, Message)]
|
||||
pub(crate) struct KnowledgeBaseAddRequest {
|
||||
#[prost(string, tag = "1")]
|
||||
knowledge: String,
|
||||
#[prost(string, tag = "2")]
|
||||
title: String,
|
||||
#[prost(string, tag = "3")]
|
||||
git_origin: String,
|
||||
#[prost(string, optional, tag = "4")]
|
||||
composer_id: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Clone, PartialEq, Message)]
|
||||
pub(crate) struct KnowledgeBaseAddResponse {
|
||||
#[prost(bool, tag = "1")]
|
||||
success: bool,
|
||||
#[prost(string, tag = "2")]
|
||||
id: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, PartialEq, Message)]
|
||||
pub(crate) struct KnowledgeBaseListRequest {
|
||||
#[prost(int32, optional, tag = "1")]
|
||||
limit: Option<i32>,
|
||||
#[prost(string, optional, tag = "2")]
|
||||
git_origin: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Clone, PartialEq, Message)]
|
||||
pub(crate) struct KnowledgeBaseListResponse {
|
||||
#[prost(bool, tag = "1")]
|
||||
success: bool,
|
||||
#[prost(message, repeated, tag = "2")]
|
||||
all_results: Vec<KnowledgeBaseListItem>,
|
||||
}
|
||||
|
||||
#[derive(Clone, PartialEq, Message)]
|
||||
pub(crate) struct KnowledgeBaseListItem {
|
||||
#[prost(string, tag = "1")]
|
||||
id: String,
|
||||
#[prost(string, tag = "2")]
|
||||
knowledge: String,
|
||||
#[prost(string, tag = "3")]
|
||||
title: String,
|
||||
#[prost(string, tag = "4")]
|
||||
created_at: String,
|
||||
#[prost(bool, tag = "5")]
|
||||
is_generated: bool,
|
||||
}
|
||||
|
||||
#[derive(Clone, PartialEq, Message)]
|
||||
pub(crate) struct KnowledgeBaseUpdateRequest {
|
||||
#[prost(string, tag = "1")]
|
||||
id: String,
|
||||
#[prost(string, tag = "2")]
|
||||
knowledge: String,
|
||||
#[prost(string, tag = "3")]
|
||||
title: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, PartialEq, Message)]
|
||||
pub(crate) struct KnowledgeBaseUpdateResponse {
|
||||
#[prost(bool, tag = "1")]
|
||||
success: bool,
|
||||
}
|
||||
|
||||
#[derive(Clone, PartialEq, Message)]
|
||||
pub(crate) struct KnowledgeBaseRemoveRequest {
|
||||
#[prost(string, tag = "1")]
|
||||
id: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, PartialEq, Message)]
|
||||
pub(crate) struct KnowledgeBaseRemoveResponse {
|
||||
#[prost(bool, tag = "1")]
|
||||
success: bool,
|
||||
}
|
||||
|
||||
/// 规则存储与并发锁;经 axum Extension 注入四个 handler。
|
||||
#[derive(Clone)]
|
||||
pub struct KnowledgeService {
|
||||
inner: Arc<Inner>,
|
||||
}
|
||||
|
||||
struct Inner {
|
||||
store: RuleStore,
|
||||
lock: tokio::sync::Mutex<()>,
|
||||
}
|
||||
|
||||
impl KnowledgeService {
|
||||
pub fn managed() -> Result<Self> {
|
||||
Self::with_root(config::managed_data_dir()?.join("rules"))
|
||||
}
|
||||
|
||||
/// 指定存储根目录构造;managed() 与集成测试共用。
|
||||
pub fn with_root(root: std::path::PathBuf) -> Result<Self> {
|
||||
Ok(Self {
|
||||
inner: Arc::new(Inner {
|
||||
store: RuleStore::open(root)?,
|
||||
lock: tokio::sync::Mutex::new(()),
|
||||
}),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn add(
|
||||
Extension(upstream): Extension<proxy::CursorProxy>,
|
||||
Extension(service): Extension<KnowledgeService>,
|
||||
request: Request<Body>,
|
||||
) -> Result<Response<Body>> {
|
||||
let (parts, body) = buffered(request).await?;
|
||||
let message: KnowledgeBaseAddRequest = connect::decode_unary(&body)?;
|
||||
let _guard = service.inner.lock.lock().await;
|
||||
let store = &service.inner.store;
|
||||
|
||||
if sync::replay(&upstream, &parts.headers, store).await? {
|
||||
match proxy::forward_buffered(&upstream, Request::from_parts(parts, Body::from(body))).await
|
||||
{
|
||||
Ok(response) if response.status.is_success() => {
|
||||
if let Ok(reply) = connect::decode_unary::<KnowledgeBaseAddResponse>(&response.body)
|
||||
{
|
||||
if reply.success && !reply.id.is_empty() {
|
||||
store.upsert(&RuleRecord {
|
||||
id: reply.id,
|
||||
knowledge: message.knowledge,
|
||||
title: message.title,
|
||||
created_at: now(),
|
||||
is_generated: false,
|
||||
git_origin: message.git_origin,
|
||||
})?;
|
||||
}
|
||||
}
|
||||
return Ok(response.into_response());
|
||||
}
|
||||
Ok(response) => {
|
||||
tracing::warn!(status = %response.status, "rules upstream rejected add; storing locally");
|
||||
}
|
||||
Err(error) => {
|
||||
tracing::warn!(%error, "rules upstream unavailable for add; storing locally");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let id = format!("{}{}", store::LOCAL_ID_PREFIX, uuid::Uuid::new_v4());
|
||||
store.upsert(&RuleRecord {
|
||||
id: id.clone(),
|
||||
knowledge: message.knowledge,
|
||||
title: message.title,
|
||||
created_at: now(),
|
||||
is_generated: false,
|
||||
git_origin: message.git_origin,
|
||||
})?;
|
||||
store.record_add(&id)?;
|
||||
proto(KnowledgeBaseAddResponse { success: true, id })
|
||||
}
|
||||
|
||||
pub async fn list(
|
||||
Extension(upstream): Extension<proxy::CursorProxy>,
|
||||
Extension(service): Extension<KnowledgeService>,
|
||||
request: Request<Body>,
|
||||
) -> Result<Response<Body>> {
|
||||
let (parts, body) = buffered(request).await?;
|
||||
let message: KnowledgeBaseListRequest = connect::decode_unary(&body)?;
|
||||
let _guard = service.inner.lock.lock().await;
|
||||
let store = &service.inner.store;
|
||||
let git_origin = message.git_origin.unwrap_or_default();
|
||||
|
||||
if sync::replay(&upstream, &parts.headers, store).await? {
|
||||
match proxy::forward_buffered(&upstream, Request::from_parts(parts, Body::from(body))).await
|
||||
{
|
||||
Ok(response) if response.status.is_success() => {
|
||||
if let Ok(reply) =
|
||||
connect::decode_unary::<KnowledgeBaseListResponse>(&response.body)
|
||||
{
|
||||
// 带 git_origin 过滤的列表只是子集,整体覆盖会误删其他规则。
|
||||
if reply.success && git_origin.is_empty() {
|
||||
sync::mirror(store, reply.all_results)?;
|
||||
}
|
||||
}
|
||||
return Ok(response.into_response());
|
||||
}
|
||||
Ok(response) => {
|
||||
tracing::warn!(status = %response.status, "rules upstream rejected list; serving local cache");
|
||||
}
|
||||
Err(error) => {
|
||||
tracing::warn!(%error, "rules upstream unavailable for list; serving local cache");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let mut records = store.list()?;
|
||||
if !git_origin.is_empty() {
|
||||
records.retain(|record| record.git_origin == git_origin);
|
||||
}
|
||||
if let Some(limit) = message.limit {
|
||||
if limit >= 0 {
|
||||
records.truncate(limit as usize);
|
||||
}
|
||||
}
|
||||
proto(KnowledgeBaseListResponse {
|
||||
success: true,
|
||||
all_results: records
|
||||
.into_iter()
|
||||
.map(|record| KnowledgeBaseListItem {
|
||||
id: record.id,
|
||||
knowledge: record.knowledge,
|
||||
title: record.title,
|
||||
created_at: record.created_at,
|
||||
is_generated: record.is_generated,
|
||||
})
|
||||
.collect(),
|
||||
})
|
||||
}
|
||||
|
||||
pub async fn update(
|
||||
Extension(upstream): Extension<proxy::CursorProxy>,
|
||||
Extension(service): Extension<KnowledgeService>,
|
||||
request: Request<Body>,
|
||||
) -> Result<Response<Body>> {
|
||||
let (parts, body) = buffered(request).await?;
|
||||
let message: KnowledgeBaseUpdateRequest = connect::decode_unary(&body)?;
|
||||
let _guard = service.inner.lock.lock().await;
|
||||
let store = &service.inner.store;
|
||||
|
||||
if sync::replay(&upstream, &parts.headers, store).await? {
|
||||
match proxy::forward_buffered(&upstream, Request::from_parts(parts, Body::from(body))).await
|
||||
{
|
||||
Ok(response) if response.status.is_success() => {
|
||||
if let Ok(reply) =
|
||||
connect::decode_unary::<KnowledgeBaseUpdateResponse>(&response.body)
|
||||
{
|
||||
if reply.success {
|
||||
let existing = store.get(&message.id)?;
|
||||
store.upsert(&RuleRecord {
|
||||
id: message.id,
|
||||
knowledge: message.knowledge,
|
||||
title: message.title,
|
||||
created_at: existing
|
||||
.as_ref()
|
||||
.map_or_else(now, |record| record.created_at.clone()),
|
||||
is_generated: existing
|
||||
.as_ref()
|
||||
.is_some_and(|record| record.is_generated),
|
||||
git_origin: existing
|
||||
.map(|record| record.git_origin)
|
||||
.unwrap_or_default(),
|
||||
})?;
|
||||
}
|
||||
}
|
||||
return Ok(response.into_response());
|
||||
}
|
||||
Ok(response) => {
|
||||
tracing::warn!(status = %response.status, "rules upstream rejected update; storing locally");
|
||||
}
|
||||
Err(error) => {
|
||||
tracing::warn!(%error, "rules upstream unavailable for update; storing locally");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let Some(mut record) = store.get(&message.id)? else {
|
||||
return proto(KnowledgeBaseUpdateResponse { success: false });
|
||||
};
|
||||
record.knowledge = message.knowledge;
|
||||
record.title = message.title;
|
||||
store.upsert(&record)?;
|
||||
store.record_update(&message.id)?;
|
||||
proto(KnowledgeBaseUpdateResponse { success: true })
|
||||
}
|
||||
|
||||
pub async fn remove(
|
||||
Extension(upstream): Extension<proxy::CursorProxy>,
|
||||
Extension(service): Extension<KnowledgeService>,
|
||||
request: Request<Body>,
|
||||
) -> Result<Response<Body>> {
|
||||
let (parts, body) = buffered(request).await?;
|
||||
let message: KnowledgeBaseRemoveRequest = connect::decode_unary(&body)?;
|
||||
let _guard = service.inner.lock.lock().await;
|
||||
let store = &service.inner.store;
|
||||
|
||||
if sync::replay(&upstream, &parts.headers, store).await? {
|
||||
match proxy::forward_buffered(&upstream, Request::from_parts(parts, Body::from(body))).await
|
||||
{
|
||||
Ok(response) if response.status.is_success() => {
|
||||
if let Ok(reply) =
|
||||
connect::decode_unary::<KnowledgeBaseRemoveResponse>(&response.body)
|
||||
{
|
||||
if reply.success {
|
||||
store.remove(&message.id)?;
|
||||
}
|
||||
}
|
||||
return Ok(response.into_response());
|
||||
}
|
||||
Ok(response) => {
|
||||
tracing::warn!(status = %response.status, "rules upstream rejected remove; removing locally");
|
||||
}
|
||||
Err(error) => {
|
||||
tracing::warn!(%error, "rules upstream unavailable for remove; removing locally");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
store.remove(&message.id)?;
|
||||
store.record_remove(&message.id)?;
|
||||
proto(KnowledgeBaseRemoveResponse { success: true })
|
||||
}
|
||||
|
||||
async fn buffered(request: Request<Body>) -> Result<(axum::http::request::Parts, Bytes)> {
|
||||
let (parts, body) = request.into_parts();
|
||||
let body = to_bytes(body, usize::MAX)
|
||||
.await
|
||||
.map_err(|error| crate::Error::Protocol(format!("cannot read request body: {error}")))?;
|
||||
Ok((parts, body))
|
||||
}
|
||||
|
||||
fn now() -> String {
|
||||
chrono::Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Millis, true)
|
||||
}
|
||||
|
||||
fn proto(message: impl Message) -> Result<Response<Body>> {
|
||||
let body = message.encode_to_vec();
|
||||
let length = body.len();
|
||||
let mut response = Response::new(Body::from(body));
|
||||
response.headers_mut().insert(
|
||||
header::CONTENT_TYPE,
|
||||
axum::http::HeaderValue::from_static("application/proto"),
|
||||
);
|
||||
response.headers_mut().insert(
|
||||
header::CONTENT_LENGTH,
|
||||
length
|
||||
.to_string()
|
||||
.parse()
|
||||
.expect("body length is always a valid header value"),
|
||||
);
|
||||
Ok(response)
|
||||
}
|
||||
@@ -0,0 +1,487 @@
|
||||
//! Persists rules as markdown files with a JSON metadata sidecar.
|
||||
use std::{
|
||||
collections::BTreeMap,
|
||||
path::{Path, PathBuf},
|
||||
};
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::{Error, Result};
|
||||
|
||||
const META_FILE: &str = "meta.json";
|
||||
const RULE_EXTENSION: &str = "md";
|
||||
pub const LOCAL_ID_PREFIX: &str = "local-";
|
||||
|
||||
/// 一条规则的完整视图:knowledge 来自 md 文件,其余字段来自 meta.json。
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct RuleRecord {
|
||||
pub id: String,
|
||||
pub knowledge: String,
|
||||
pub title: String,
|
||||
pub created_at: String,
|
||||
pub is_generated: bool,
|
||||
pub git_origin: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum JournalOp {
|
||||
Add,
|
||||
Update,
|
||||
Remove,
|
||||
}
|
||||
|
||||
/// 离线期间未同步到上游的一次变更。
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct JournalEntry {
|
||||
pub op: JournalOp,
|
||||
pub id: String,
|
||||
}
|
||||
|
||||
#[derive(Default, Serialize, Deserialize)]
|
||||
struct Meta {
|
||||
#[serde(default)]
|
||||
rules: BTreeMap<String, RuleMeta>,
|
||||
#[serde(default)]
|
||||
journal: Vec<JournalEntry>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Default, Serialize, Deserialize)]
|
||||
struct RuleMeta {
|
||||
#[serde(default)]
|
||||
title: String,
|
||||
#[serde(default)]
|
||||
created_at: String,
|
||||
#[serde(default)]
|
||||
is_generated: bool,
|
||||
#[serde(default)]
|
||||
git_origin: String,
|
||||
}
|
||||
|
||||
/// md 文件为核心的规则存储;调用方需自行串行化并发访问。
|
||||
pub struct RuleStore {
|
||||
root: PathBuf,
|
||||
}
|
||||
|
||||
impl RuleStore {
|
||||
pub fn open(root: PathBuf) -> Result<Self> {
|
||||
std::fs::create_dir_all(&root)?;
|
||||
Ok(Self { root })
|
||||
}
|
||||
|
||||
pub fn list(&self) -> Result<Vec<RuleRecord>> {
|
||||
let meta = self.read_meta();
|
||||
let mut records = Vec::new();
|
||||
for entry in std::fs::read_dir(&self.root)? {
|
||||
let path = entry?.path();
|
||||
if path.extension().and_then(|value| value.to_str()) != Some(RULE_EXTENSION) {
|
||||
continue;
|
||||
}
|
||||
let Some(id) = path.file_stem().and_then(|value| value.to_str()) else {
|
||||
continue;
|
||||
};
|
||||
if validate_id(id).is_err() {
|
||||
continue;
|
||||
}
|
||||
let knowledge = std::fs::read_to_string(&path)?;
|
||||
records.push(assemble(id, knowledge, meta.rules.get(id), &path));
|
||||
}
|
||||
records.sort_by(|left, right| {
|
||||
timestamp(&right.created_at)
|
||||
.cmp(×tamp(&left.created_at))
|
||||
.then_with(|| left.id.cmp(&right.id))
|
||||
});
|
||||
Ok(records)
|
||||
}
|
||||
|
||||
pub fn get(&self, id: &str) -> Result<Option<RuleRecord>> {
|
||||
validate_id(id)?;
|
||||
let path = self.rule_path(id);
|
||||
let knowledge = match std::fs::read_to_string(&path) {
|
||||
Ok(knowledge) => knowledge,
|
||||
Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None),
|
||||
Err(error) => return Err(error.into()),
|
||||
};
|
||||
let meta = self.read_meta();
|
||||
Ok(Some(assemble(id, knowledge, meta.rules.get(id), &path)))
|
||||
}
|
||||
|
||||
pub fn upsert(&self, record: &RuleRecord) -> Result<()> {
|
||||
validate_id(&record.id)?;
|
||||
write_atomic(&self.rule_path(&record.id), record.knowledge.as_bytes())?;
|
||||
let mut meta = self.read_meta();
|
||||
meta.rules.insert(record.id.clone(), rule_meta(record));
|
||||
self.write_meta(&meta)
|
||||
}
|
||||
|
||||
pub fn remove(&self, id: &str) -> Result<()> {
|
||||
validate_id(id)?;
|
||||
remove_file_if_exists(&self.rule_path(id))?;
|
||||
let mut meta = self.read_meta();
|
||||
if meta.rules.remove(id).is_some() {
|
||||
self.write_meta(&meta)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// 离线新增的规则在上游落地后,把本地临时 id 换成上游分配的真实 id。
|
||||
pub fn promote(&self, old_id: &str, new_id: &str) -> Result<()> {
|
||||
validate_id(old_id)?;
|
||||
validate_id(new_id)?;
|
||||
let source = self.rule_path(old_id);
|
||||
let target = self.rule_path(new_id);
|
||||
#[cfg(windows)]
|
||||
remove_file_if_exists(&target)?;
|
||||
std::fs::rename(&source, &target)?;
|
||||
let mut meta = self.read_meta();
|
||||
if let Some(rule) = meta.rules.remove(old_id) {
|
||||
meta.rules.insert(new_id.into(), rule);
|
||||
}
|
||||
for entry in &mut meta.journal {
|
||||
if entry.id == old_id {
|
||||
entry.id = new_id.into();
|
||||
}
|
||||
}
|
||||
self.write_meta(&meta)
|
||||
}
|
||||
|
||||
/// 用上游的完整列表覆盖本地镜像;仅应在日志为空(已全部回放)时调用。
|
||||
pub fn replace_all(&self, records: &[RuleRecord]) -> Result<()> {
|
||||
let mut meta = self.read_meta();
|
||||
meta.rules.clear();
|
||||
for record in records {
|
||||
validate_id(&record.id)?;
|
||||
write_atomic(&self.rule_path(&record.id), record.knowledge.as_bytes())?;
|
||||
meta.rules.insert(record.id.clone(), rule_meta(record));
|
||||
}
|
||||
for entry in std::fs::read_dir(&self.root)? {
|
||||
let path = entry?.path();
|
||||
if path.extension().and_then(|value| value.to_str()) != Some(RULE_EXTENSION) {
|
||||
continue;
|
||||
}
|
||||
let keep = path
|
||||
.file_stem()
|
||||
.and_then(|value| value.to_str())
|
||||
.is_some_and(|id| meta.rules.contains_key(id));
|
||||
if !keep {
|
||||
remove_file_if_exists(&path)?;
|
||||
}
|
||||
}
|
||||
self.write_meta(&meta)
|
||||
}
|
||||
|
||||
pub fn journal_front(&self) -> Result<Option<JournalEntry>> {
|
||||
Ok(self.read_meta().journal.first().cloned())
|
||||
}
|
||||
|
||||
pub fn pop_journal(&self) -> Result<()> {
|
||||
let mut meta = self.read_meta();
|
||||
if !meta.journal.is_empty() {
|
||||
meta.journal.remove(0);
|
||||
self.write_meta(&meta)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn record_add(&self, id: &str) -> Result<()> {
|
||||
let mut meta = self.read_meta();
|
||||
meta.journal.push(JournalEntry {
|
||||
op: JournalOp::Add,
|
||||
id: id.into(),
|
||||
});
|
||||
self.write_meta(&meta)
|
||||
}
|
||||
|
||||
pub fn record_update(&self, id: &str) -> Result<()> {
|
||||
let mut meta = self.read_meta();
|
||||
if journal_contains(&meta.journal, id, JournalOp::Add) {
|
||||
// 回放 add 时会读取最新内容,无需单独的 update 日志。
|
||||
return Ok(());
|
||||
}
|
||||
let op = if id.starts_with(LOCAL_ID_PREFIX) {
|
||||
// 本地临时 id 没有对应的 add 日志(如镜像覆盖后的残留),按新增回放。
|
||||
JournalOp::Add
|
||||
} else {
|
||||
JournalOp::Update
|
||||
};
|
||||
if !journal_contains(&meta.journal, id, op) {
|
||||
meta.journal.push(JournalEntry { op, id: id.into() });
|
||||
self.write_meta(&meta)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn record_remove(&self, id: &str) -> Result<()> {
|
||||
let mut meta = self.read_meta();
|
||||
let never_synced = journal_contains(&meta.journal, id, JournalOp::Add);
|
||||
meta.journal.retain(|entry| entry.id != id);
|
||||
if !never_synced && !id.starts_with(LOCAL_ID_PREFIX) {
|
||||
meta.journal.push(JournalEntry {
|
||||
op: JournalOp::Remove,
|
||||
id: id.into(),
|
||||
});
|
||||
}
|
||||
self.write_meta(&meta)
|
||||
}
|
||||
|
||||
fn rule_path(&self, id: &str) -> PathBuf {
|
||||
self.root.join(format!("{id}.{RULE_EXTENSION}"))
|
||||
}
|
||||
|
||||
fn meta_path(&self) -> PathBuf {
|
||||
self.root.join(META_FILE)
|
||||
}
|
||||
|
||||
fn read_meta(&self) -> Meta {
|
||||
match std::fs::read(self.meta_path()) {
|
||||
Ok(bytes) => serde_json::from_slice(&bytes).unwrap_or_else(|error| {
|
||||
tracing::warn!(%error, "rules meta.json is corrupt; starting from empty metadata");
|
||||
Meta::default()
|
||||
}),
|
||||
Err(_) => Meta::default(),
|
||||
}
|
||||
}
|
||||
|
||||
fn write_meta(&self, meta: &Meta) -> Result<()> {
|
||||
write_atomic(&self.meta_path(), &serde_json::to_vec_pretty(meta)?)
|
||||
}
|
||||
}
|
||||
|
||||
fn assemble(id: &str, knowledge: String, meta: Option<&RuleMeta>, path: &Path) -> RuleRecord {
|
||||
match meta {
|
||||
Some(meta) => RuleRecord {
|
||||
id: id.into(),
|
||||
knowledge,
|
||||
title: meta.title.clone(),
|
||||
created_at: meta.created_at.clone(),
|
||||
is_generated: meta.is_generated,
|
||||
git_origin: meta.git_origin.clone(),
|
||||
},
|
||||
// 用户手放的 md 文件没有元数据,用文件名当标题、修改时间当创建时间。
|
||||
None => RuleRecord {
|
||||
id: id.into(),
|
||||
knowledge,
|
||||
title: id.into(),
|
||||
created_at: file_modified_at(path),
|
||||
is_generated: false,
|
||||
git_origin: String::new(),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
fn rule_meta(record: &RuleRecord) -> RuleMeta {
|
||||
RuleMeta {
|
||||
title: record.title.clone(),
|
||||
created_at: record.created_at.clone(),
|
||||
is_generated: record.is_generated,
|
||||
git_origin: record.git_origin.clone(),
|
||||
}
|
||||
}
|
||||
|
||||
fn journal_contains(journal: &[JournalEntry], id: &str, op: JournalOp) -> bool {
|
||||
journal.iter().any(|entry| entry.id == id && entry.op == op)
|
||||
}
|
||||
|
||||
fn timestamp(created_at: &str) -> i64 {
|
||||
chrono::DateTime::parse_from_rfc3339(created_at)
|
||||
.map(|time| time.timestamp_millis())
|
||||
.unwrap_or(0)
|
||||
}
|
||||
|
||||
fn file_modified_at(path: &Path) -> String {
|
||||
let modified = std::fs::metadata(path)
|
||||
.and_then(|meta| meta.modified())
|
||||
.unwrap_or_else(|_| std::time::SystemTime::now());
|
||||
chrono::DateTime::<chrono::Utc>::from(modified)
|
||||
.to_rfc3339_opts(chrono::SecondsFormat::Millis, true)
|
||||
}
|
||||
|
||||
fn validate_id(id: &str) -> Result<()> {
|
||||
if id.is_empty()
|
||||
|| id.len() > 128
|
||||
|| !id
|
||||
.bytes()
|
||||
.all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_'))
|
||||
{
|
||||
return Err(Error::Protocol(format!("invalid rule id: {id:?}")));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn remove_file_if_exists(path: &Path) -> Result<()> {
|
||||
match std::fs::remove_file(path) {
|
||||
Ok(()) => Ok(()),
|
||||
Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(()),
|
||||
Err(error) => Err(error.into()),
|
||||
}
|
||||
}
|
||||
|
||||
fn write_atomic(path: &Path, bytes: &[u8]) -> Result<()> {
|
||||
use std::io::Write;
|
||||
let directory = path.parent().expect("rule path has a parent");
|
||||
let temporary = directory.join(format!(".{}.tmp", uuid::Uuid::new_v4()));
|
||||
let mut file = std::fs::File::create(&temporary)?;
|
||||
file.write_all(bytes)?;
|
||||
file.sync_all()?;
|
||||
drop(file);
|
||||
#[cfg(windows)]
|
||||
remove_file_if_exists(path)?;
|
||||
std::fs::rename(&temporary, path).inspect_err(|_| {
|
||||
let _ = std::fs::remove_file(&temporary);
|
||||
})?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn record(id: &str, knowledge: &str, created_at: &str) -> RuleRecord {
|
||||
RuleRecord {
|
||||
id: id.into(),
|
||||
knowledge: knowledge.into(),
|
||||
title: format!("title-{id}"),
|
||||
created_at: created_at.into(),
|
||||
is_generated: false,
|
||||
git_origin: String::new(),
|
||||
}
|
||||
}
|
||||
|
||||
fn journal(store: &RuleStore) -> Vec<JournalEntry> {
|
||||
store.read_meta().journal
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn upserts_lists_and_removes_rules() {
|
||||
let root = tempfile::tempdir().unwrap();
|
||||
let store = RuleStore::open(root.path().join("rules")).unwrap();
|
||||
store
|
||||
.upsert(&record("100", "older", "2026-01-01T00:00:00.000Z"))
|
||||
.unwrap();
|
||||
store
|
||||
.upsert(&record("200", "newer", "2026-02-01T00:00:00.000Z"))
|
||||
.unwrap();
|
||||
|
||||
let listed = store.list().unwrap();
|
||||
assert_eq!(
|
||||
listed
|
||||
.iter()
|
||||
.map(|rule| rule.id.as_str())
|
||||
.collect::<Vec<_>>(),
|
||||
["200", "100"],
|
||||
"list is sorted by created_at descending"
|
||||
);
|
||||
assert_eq!(listed[0].knowledge, "newer");
|
||||
assert_eq!(listed[0].title, "title-200");
|
||||
|
||||
store.remove("200").unwrap();
|
||||
assert!(store.get("200").unwrap().is_none());
|
||||
assert_eq!(store.list().unwrap().len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_path_traversal_ids() {
|
||||
let root = tempfile::tempdir().unwrap();
|
||||
let store = RuleStore::open(root.path().join("rules")).unwrap();
|
||||
assert!(store.get("../escape").is_err());
|
||||
assert!(store.get("a/b").is_err());
|
||||
assert!(store.get("").is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn compacts_offline_journal() {
|
||||
let root = tempfile::tempdir().unwrap();
|
||||
let store = RuleStore::open(root.path().join("rules")).unwrap();
|
||||
|
||||
// 离线新增后再更新:回放 add 即可携带最新内容,不产生 update 日志。
|
||||
store
|
||||
.upsert(&record("local-a", "v1", "2026-01-01T00:00:00.000Z"))
|
||||
.unwrap();
|
||||
store.record_add("local-a").unwrap();
|
||||
store.record_update("local-a").unwrap();
|
||||
assert_eq!(
|
||||
journal(&store),
|
||||
vec![JournalEntry {
|
||||
op: JournalOp::Add,
|
||||
id: "local-a".into()
|
||||
}]
|
||||
);
|
||||
|
||||
// 离线新增后又删除:上游从未见过它,日志清空。
|
||||
store.record_remove("local-a").unwrap();
|
||||
assert!(journal(&store).is_empty());
|
||||
|
||||
// 更新上游已有规则:多次更新合并为一条;删除后 update 日志被顶替。
|
||||
store.record_update("42").unwrap();
|
||||
store.record_update("42").unwrap();
|
||||
assert_eq!(
|
||||
journal(&store),
|
||||
vec![JournalEntry {
|
||||
op: JournalOp::Update,
|
||||
id: "42".into()
|
||||
}]
|
||||
);
|
||||
store.record_remove("42").unwrap();
|
||||
assert_eq!(
|
||||
journal(&store),
|
||||
vec![JournalEntry {
|
||||
op: JournalOp::Remove,
|
||||
id: "42".into()
|
||||
}]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn promote_renames_rule_and_journal_ids() {
|
||||
let root = tempfile::tempdir().unwrap();
|
||||
let store = RuleStore::open(root.path().join("rules")).unwrap();
|
||||
store
|
||||
.upsert(&record("local-a", "content", "2026-01-01T00:00:00.000Z"))
|
||||
.unwrap();
|
||||
store.record_add("local-a").unwrap();
|
||||
|
||||
store.promote("local-a", "17353272").unwrap();
|
||||
|
||||
assert!(store.get("local-a").unwrap().is_none());
|
||||
let promoted = store.get("17353272").unwrap().unwrap();
|
||||
assert_eq!(promoted.knowledge, "content");
|
||||
assert_eq!(promoted.title, "title-local-a");
|
||||
assert_eq!(journal(&store)[0].id, "17353272");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn replace_all_mirrors_upstream_state() {
|
||||
let root = tempfile::tempdir().unwrap();
|
||||
let store = RuleStore::open(root.path().join("rules")).unwrap();
|
||||
store
|
||||
.upsert(&record("stale", "gone soon", "2026-01-01T00:00:00.000Z"))
|
||||
.unwrap();
|
||||
|
||||
store
|
||||
.replace_all(&[record(
|
||||
"17353272",
|
||||
"from upstream",
|
||||
"2026-02-01T00:00:00.000Z",
|
||||
)])
|
||||
.unwrap();
|
||||
|
||||
let listed = store.list().unwrap();
|
||||
assert_eq!(listed.len(), 1);
|
||||
assert_eq!(listed[0].id, "17353272");
|
||||
assert_eq!(listed[0].knowledge, "from upstream");
|
||||
assert!(store.get("stale").unwrap().is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lists_hand_written_markdown_without_metadata() {
|
||||
let root = tempfile::tempdir().unwrap();
|
||||
let store = RuleStore::open(root.path().join("rules")).unwrap();
|
||||
std::fs::write(root.path().join("rules/manual_rule.md"), "hand written").unwrap();
|
||||
|
||||
let listed = store.list().unwrap();
|
||||
assert_eq!(listed.len(), 1);
|
||||
assert_eq!(listed[0].id, "manual_rule");
|
||||
assert_eq!(listed[0].title, "manual_rule");
|
||||
assert_eq!(listed[0].knowledge, "hand written");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,184 @@
|
||||
//! Replays the offline journal to upstream and mirrors upstream list state.
|
||||
use axum::{
|
||||
body::{Body, Bytes},
|
||||
http::{header, HeaderMap, HeaderValue, Method, Request},
|
||||
};
|
||||
use prost::Message;
|
||||
|
||||
use crate::{api::cursor::proxy, cursor::protocol::connect, Result};
|
||||
|
||||
use super::{
|
||||
store::{JournalOp, RuleRecord, RuleStore},
|
||||
KnowledgeBaseAddRequest, KnowledgeBaseAddResponse, KnowledgeBaseListItem,
|
||||
KnowledgeBaseRemoveRequest, KnowledgeBaseRemoveResponse, KnowledgeBaseUpdateRequest,
|
||||
KnowledgeBaseUpdateResponse,
|
||||
};
|
||||
|
||||
const ADD_PATH: &str = "/aiserver.v1.AiService/KnowledgeBaseAdd";
|
||||
const UPDATE_PATH: &str = "/aiserver.v1.AiService/KnowledgeBaseUpdate";
|
||||
const REMOVE_PATH: &str = "/aiserver.v1.AiService/KnowledgeBaseRemove";
|
||||
|
||||
/// 逐条把离线日志推送到上游。返回 true 表示日志已清空(上游可用),
|
||||
/// false 表示上游不可达,剩余日志保留、调用方应降级到本地。
|
||||
pub async fn replay(
|
||||
upstream: &proxy::CursorProxy,
|
||||
headers: &HeaderMap,
|
||||
store: &RuleStore,
|
||||
) -> Result<bool> {
|
||||
while let Some(entry) = store.journal_front()? {
|
||||
let advanced = match entry.op {
|
||||
JournalOp::Add => replay_add(upstream, headers, store, &entry.id).await?,
|
||||
JournalOp::Update => replay_update(upstream, headers, store, &entry.id).await?,
|
||||
JournalOp::Remove => replay_remove(upstream, headers, store, &entry.id).await?,
|
||||
};
|
||||
if !advanced {
|
||||
return Ok(false);
|
||||
}
|
||||
}
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
/// 用上游返回的完整列表覆盖本地镜像。仅应在日志已清空时调用。
|
||||
pub fn mirror(store: &RuleStore, items: Vec<KnowledgeBaseListItem>) -> Result<()> {
|
||||
let records = items
|
||||
.into_iter()
|
||||
.map(|item| RuleRecord {
|
||||
id: item.id,
|
||||
knowledge: item.knowledge,
|
||||
title: item.title,
|
||||
created_at: item.created_at,
|
||||
is_generated: item.is_generated,
|
||||
git_origin: String::new(),
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
store.replace_all(&records)
|
||||
}
|
||||
|
||||
async fn replay_add(
|
||||
upstream: &proxy::CursorProxy,
|
||||
headers: &HeaderMap,
|
||||
store: &RuleStore,
|
||||
id: &str,
|
||||
) -> Result<bool> {
|
||||
let Some(record) = store.get(id)? else {
|
||||
// 规则文件已不在(被手动删除等),日志作废。
|
||||
store.pop_journal()?;
|
||||
return Ok(true);
|
||||
};
|
||||
let message = KnowledgeBaseAddRequest {
|
||||
knowledge: record.knowledge,
|
||||
title: record.title,
|
||||
git_origin: record.git_origin,
|
||||
composer_id: None,
|
||||
};
|
||||
let Some(body) = send(upstream, headers, ADD_PATH, &message).await else {
|
||||
return Ok(false);
|
||||
};
|
||||
let Ok(reply) = connect::decode_unary::<KnowledgeBaseAddResponse>(&body) else {
|
||||
return Ok(false);
|
||||
};
|
||||
if !reply.success || reply.id.is_empty() {
|
||||
tracing::warn!(
|
||||
id,
|
||||
"rules upstream declined replayed add; dropping journal entry"
|
||||
);
|
||||
store.pop_journal()?;
|
||||
return Ok(true);
|
||||
}
|
||||
store.promote(id, &reply.id)?;
|
||||
store.pop_journal()?;
|
||||
tracing::info!(
|
||||
local_id = id,
|
||||
upstream_id = reply.id,
|
||||
"replayed offline rule add to upstream"
|
||||
);
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
async fn replay_update(
|
||||
upstream: &proxy::CursorProxy,
|
||||
headers: &HeaderMap,
|
||||
store: &RuleStore,
|
||||
id: &str,
|
||||
) -> Result<bool> {
|
||||
let Some(record) = store.get(id)? else {
|
||||
store.pop_journal()?;
|
||||
return Ok(true);
|
||||
};
|
||||
let message = KnowledgeBaseUpdateRequest {
|
||||
id: id.into(),
|
||||
knowledge: record.knowledge,
|
||||
title: record.title,
|
||||
};
|
||||
let Some(body) = send(upstream, headers, UPDATE_PATH, &message).await else {
|
||||
return Ok(false);
|
||||
};
|
||||
let Ok(reply) = connect::decode_unary::<KnowledgeBaseUpdateResponse>(&body) else {
|
||||
return Ok(false);
|
||||
};
|
||||
if !reply.success {
|
||||
tracing::warn!(
|
||||
id,
|
||||
"rules upstream declined replayed update; dropping journal entry"
|
||||
);
|
||||
}
|
||||
store.pop_journal()?;
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
async fn replay_remove(
|
||||
upstream: &proxy::CursorProxy,
|
||||
headers: &HeaderMap,
|
||||
store: &RuleStore,
|
||||
id: &str,
|
||||
) -> Result<bool> {
|
||||
let message = KnowledgeBaseRemoveRequest { id: id.into() };
|
||||
let Some(body) = send(upstream, headers, REMOVE_PATH, &message).await else {
|
||||
return Ok(false);
|
||||
};
|
||||
let Ok(reply) = connect::decode_unary::<KnowledgeBaseRemoveResponse>(&body) else {
|
||||
return Ok(false);
|
||||
};
|
||||
if !reply.success {
|
||||
tracing::warn!(
|
||||
id,
|
||||
"rules upstream declined replayed remove; dropping journal entry"
|
||||
);
|
||||
}
|
||||
store.pop_journal()?;
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
/// 以当前请求的头为模板向上游发起一次 unary RPC。
|
||||
/// 成功(2xx)返回响应体;不可达或被拒绝返回 None,由调用方保留日志。
|
||||
async fn send(
|
||||
upstream: &proxy::CursorProxy,
|
||||
template: &HeaderMap,
|
||||
path: &str,
|
||||
message: &impl Message,
|
||||
) -> Option<Bytes> {
|
||||
let mut headers = template.clone();
|
||||
// 模板里的上游 URL 头指向原始 RPC 路径,必须移除才能命中回放路径。
|
||||
headers.remove(proxy::UPSTREAM_URL_HEADER);
|
||||
headers.remove(header::CONTENT_LENGTH);
|
||||
headers.insert(
|
||||
header::CONTENT_TYPE,
|
||||
HeaderValue::from_static("application/proto"),
|
||||
);
|
||||
let mut request = Request::new(Body::from(message.encode_to_vec()));
|
||||
*request.method_mut() = Method::POST;
|
||||
*request.uri_mut() = path.parse().expect("replay path is a valid URI");
|
||||
*request.headers_mut() = headers;
|
||||
|
||||
match proxy::forward_buffered(upstream, request).await {
|
||||
Ok(response) if response.status.is_success() => Some(response.body),
|
||||
Ok(response) => {
|
||||
tracing::warn!(path, status = %response.status, "rules journal replay rejected by upstream");
|
||||
None
|
||||
}
|
||||
Err(error) => {
|
||||
tracing::warn!(path, %error, "rules journal replay cannot reach upstream");
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -4,6 +4,7 @@ pub mod account;
|
||||
pub mod analytics;
|
||||
pub mod blob_sync;
|
||||
pub mod context_sync;
|
||||
pub mod knowledge;
|
||||
pub mod model_catalog;
|
||||
pub mod observability;
|
||||
pub mod tab;
|
||||
|
||||
@@ -10,7 +10,8 @@ use prost::Message;
|
||||
use crate::{
|
||||
api::cursor::proxy::{self, CursorProxy},
|
||||
cursor::{protocol::proto::agent::v1 as agent, transport::TransportRegistry},
|
||||
model::{format_token_count, parse_token_count, ModelConfig, ModelType},
|
||||
model::{format_token_count, parse_token_count, ModelConfig},
|
||||
plugin::PluginModelDescriptor,
|
||||
Error, Result,
|
||||
};
|
||||
|
||||
@@ -186,9 +187,10 @@ struct UsableModelsAddition {
|
||||
models: Vec<agent::ModelDetails>,
|
||||
}
|
||||
|
||||
const CONTEXTS: [(&str, &str); 4] = [
|
||||
const CONTEXTS: [(&str, &str); 5] = [
|
||||
("200k", "200K"),
|
||||
("356k", "356K"),
|
||||
("500k", "500K"),
|
||||
("800k", "800K"),
|
||||
("1m", "1M"),
|
||||
];
|
||||
@@ -201,12 +203,12 @@ const EFFORTS: [(&str, &str); 5] = [
|
||||
];
|
||||
const DEFAULT_CONTEXT: &str = "200k";
|
||||
|
||||
fn context_options(model: &ModelConfig) -> Vec<(String, String)> {
|
||||
fn context_options(context_window_tokens: Option<u64>) -> Vec<(String, String)> {
|
||||
let mut contexts = CONTEXTS
|
||||
.into_iter()
|
||||
.map(|(value, display_name)| (value.to_owned(), display_name.to_owned()))
|
||||
.collect::<Vec<_>>();
|
||||
if let Some(tokens) = model.context_window_tokens {
|
||||
if let Some(tokens) = context_window_tokens {
|
||||
let value = tokens.to_string();
|
||||
let duplicate = contexts
|
||||
.iter()
|
||||
@@ -224,15 +226,22 @@ pub async fn available_models(
|
||||
request: Request<Body>,
|
||||
) -> Result<Response<Body>> {
|
||||
let models = registry.store().models().await?;
|
||||
let plugin_models = match registry.plugins() {
|
||||
Some(plugins) => plugins.configured_models().await,
|
||||
None => Vec::new(),
|
||||
};
|
||||
tracing::info!(
|
||||
model_count = models.len(),
|
||||
plugin_model_count = plugin_models.len(),
|
||||
"appending BYOK models to Cursor AvailableModels"
|
||||
);
|
||||
let available_models = models.iter().map(available_model).collect::<Vec<_>>();
|
||||
let mut available_models = models.iter().map(available_model).collect::<Vec<_>>();
|
||||
available_models.extend(plugin_models.iter().map(available_plugin_model));
|
||||
let local = AvailableModelsAddition {
|
||||
model_names: models
|
||||
.iter()
|
||||
.map(|model| model.model_hash.clone())
|
||||
.chain(plugin_models.iter().map(|model| model.id.clone()))
|
||||
.collect(),
|
||||
models: available_models,
|
||||
}
|
||||
@@ -252,12 +261,21 @@ pub async fn usable_models(
|
||||
request: Request<Body>,
|
||||
) -> Result<Response<Body>> {
|
||||
let models = registry.store().models().await?;
|
||||
let plugin_models = match registry.plugins() {
|
||||
Some(plugins) => plugins.configured_models().await,
|
||||
None => Vec::new(),
|
||||
};
|
||||
tracing::info!(
|
||||
model_count = models.len(),
|
||||
plugin_model_count = plugin_models.len(),
|
||||
"appending BYOK models to Cursor GetUsableModels"
|
||||
);
|
||||
let local = UsableModelsAddition {
|
||||
models: models.iter().map(usable_model).collect(),
|
||||
models: models
|
||||
.iter()
|
||||
.map(usable_model)
|
||||
.chain(plugin_models.iter().map(usable_plugin_model))
|
||||
.collect(),
|
||||
}
|
||||
.encode_to_vec();
|
||||
match proxy::forward_buffered(&proxy, request).await {
|
||||
@@ -319,13 +337,19 @@ fn unary_payload(body: &Bytes) -> Result<(bool, &[u8])> {
|
||||
}
|
||||
|
||||
fn available_model(model: &ModelConfig) -> AvailableModel {
|
||||
let contexts = context_options(model);
|
||||
let variants = model_variants(model, &contexts);
|
||||
let contexts = context_options(model.context_window_tokens);
|
||||
let tooltip = model_tooltip(model);
|
||||
let variants = model_variants(
|
||||
&model.model_hash,
|
||||
&model.display_name,
|
||||
&tooltip,
|
||||
&contexts,
|
||||
true,
|
||||
);
|
||||
let legacy_slugs = variants
|
||||
.iter()
|
||||
.filter_map(|variant| variant.legacy_slug.clone())
|
||||
.collect();
|
||||
let tooltip = model_tooltip(model);
|
||||
AvailableModel {
|
||||
name: model.model_hash.clone(),
|
||||
default_on: true,
|
||||
@@ -344,7 +368,7 @@ fn available_model(model: &ModelConfig) -> AvailableModel {
|
||||
inputbox_short_model_name: Some(model.display_name.clone()),
|
||||
supports_sandboxing: Some(true),
|
||||
supports_cmd_k: Some(false),
|
||||
parameter_definitions: model_parameters(&contexts),
|
||||
parameter_definitions: model_parameters(&contexts, true),
|
||||
variants,
|
||||
legacy_slugs,
|
||||
named_model_section_index: Some(1),
|
||||
@@ -354,37 +378,49 @@ fn available_model(model: &ModelConfig) -> AvailableModel {
|
||||
display_name: "Cursor".into(),
|
||||
}),
|
||||
model_picker_badges: vec![ModelPickerBadge {
|
||||
label: match model.model_type {
|
||||
ModelType::OpenAi => "OpenAI".into(),
|
||||
ModelType::Anthropic => "Anthropic".into(),
|
||||
},
|
||||
label: model
|
||||
.group_name
|
||||
.clone()
|
||||
.unwrap_or_else(|| provider_host(&model.base_url)),
|
||||
variant: 1,
|
||||
dismiss_on_selection: false,
|
||||
}],
|
||||
}
|
||||
}
|
||||
|
||||
fn model_parameters(contexts: &[(String, String)]) -> Vec<ModelParameterDefinition> {
|
||||
vec![
|
||||
ModelParameterDefinition {
|
||||
id: "context".into(),
|
||||
name: "Context".into(),
|
||||
markdown_tooltip: Some("Context size used to trigger conversation compaction.".into()),
|
||||
parameter_type: Some(ModelParameterType {
|
||||
boolean_parameter: None,
|
||||
enum_parameter: Some(EnumParameter {
|
||||
values: contexts
|
||||
.iter()
|
||||
.map(|(value, display_name)| EnumParameterValue {
|
||||
value: value.clone(),
|
||||
display_name: Some(display_name.clone()),
|
||||
})
|
||||
.collect(),
|
||||
}),
|
||||
/// 徽章回退标签:base_url 的主机名。入库时已校验为带主机的 HTTP(S) URL,
|
||||
/// 解析失败仅是理论分支,此时原样返回 base_url。
|
||||
fn provider_host(base_url: &str) -> String {
|
||||
reqwest::Url::parse(base_url.trim())
|
||||
.ok()
|
||||
.and_then(|url| url.host_str().map(str::to_lowercase))
|
||||
.unwrap_or_else(|| base_url.trim().into())
|
||||
}
|
||||
|
||||
fn model_parameters(
|
||||
contexts: &[(String, String)],
|
||||
thinking: bool,
|
||||
) -> Vec<ModelParameterDefinition> {
|
||||
let mut parameters = vec![ModelParameterDefinition {
|
||||
id: "context".into(),
|
||||
name: "Context".into(),
|
||||
markdown_tooltip: Some("Context size used to trigger conversation compaction.".into()),
|
||||
parameter_type: Some(ModelParameterType {
|
||||
boolean_parameter: None,
|
||||
enum_parameter: Some(EnumParameter {
|
||||
values: contexts
|
||||
.iter()
|
||||
.map(|(value, display_name)| EnumParameterValue {
|
||||
value: value.clone(),
|
||||
display_name: Some(display_name.clone()),
|
||||
})
|
||||
.collect(),
|
||||
}),
|
||||
is_cycleable_by_hotkey: Some(false),
|
||||
},
|
||||
ModelParameterDefinition {
|
||||
}),
|
||||
is_cycleable_by_hotkey: Some(false),
|
||||
}];
|
||||
if thinking {
|
||||
parameters.push(ModelParameterDefinition {
|
||||
id: "reasoning".into(),
|
||||
name: "Effort".into(),
|
||||
markdown_tooltip: Some("Effort the model uses to generate its response.".into()),
|
||||
@@ -401,44 +437,64 @@ fn model_parameters(contexts: &[(String, String)]) -> Vec<ModelParameterDefiniti
|
||||
}),
|
||||
}),
|
||||
is_cycleable_by_hotkey: Some(true),
|
||||
},
|
||||
ModelParameterDefinition {
|
||||
id: "fast".into(),
|
||||
name: "Fast".into(),
|
||||
markdown_tooltip: Some("Significantly faster but consumes more usage".into()),
|
||||
parameter_type: Some(ModelParameterType {
|
||||
boolean_parameter: Some(BooleanParameter {
|
||||
values: vec![
|
||||
BooleanParameterValue {
|
||||
value: "false".into(),
|
||||
display_name: None,
|
||||
increases_model_cost: None,
|
||||
},
|
||||
BooleanParameterValue {
|
||||
value: "true".into(),
|
||||
display_name: Some("Fast".into()),
|
||||
increases_model_cost: Some(true),
|
||||
},
|
||||
],
|
||||
}),
|
||||
enum_parameter: None,
|
||||
});
|
||||
}
|
||||
parameters.push(ModelParameterDefinition {
|
||||
id: "fast".into(),
|
||||
name: "Fast".into(),
|
||||
markdown_tooltip: Some("Significantly faster but consumes more usage".into()),
|
||||
parameter_type: Some(ModelParameterType {
|
||||
boolean_parameter: Some(BooleanParameter {
|
||||
values: vec![
|
||||
BooleanParameterValue {
|
||||
value: "false".into(),
|
||||
display_name: None,
|
||||
increases_model_cost: None,
|
||||
},
|
||||
BooleanParameterValue {
|
||||
value: "true".into(),
|
||||
display_name: Some("Fast".into()),
|
||||
increases_model_cost: Some(true),
|
||||
},
|
||||
],
|
||||
}),
|
||||
is_cycleable_by_hotkey: Some(false),
|
||||
},
|
||||
]
|
||||
enum_parameter: None,
|
||||
}),
|
||||
is_cycleable_by_hotkey: Some(false),
|
||||
});
|
||||
parameters
|
||||
}
|
||||
|
||||
fn model_variants(model: &ModelConfig, contexts: &[(String, String)]) -> Vec<ModelVariant> {
|
||||
let mut variants = Vec::with_capacity(contexts.len() * EFFORTS.len() * 2);
|
||||
fn model_variants(
|
||||
name: &str,
|
||||
display_name: &str,
|
||||
tooltip: &TooltipData,
|
||||
contexts: &[(String, String)],
|
||||
thinking: bool,
|
||||
) -> Vec<ModelVariant> {
|
||||
// 非思考模型没有 Effort 轴,变体网格只剩 Context × Fast。
|
||||
let efforts: &[Option<(&str, &str)>] = if thinking {
|
||||
&[
|
||||
Some(EFFORTS[0]),
|
||||
Some(EFFORTS[1]),
|
||||
Some(EFFORTS[2]),
|
||||
Some(EFFORTS[3]),
|
||||
Some(EFFORTS[4]),
|
||||
]
|
||||
} else {
|
||||
&[None]
|
||||
};
|
||||
let mut variants = Vec::with_capacity(contexts.len() * efforts.len() * 2);
|
||||
for (context, context_name) in contexts {
|
||||
for (effort, effort_name) in EFFORTS {
|
||||
for effort in efforts {
|
||||
for fast in [false, true] {
|
||||
variants.push(model_variant(
|
||||
model,
|
||||
name,
|
||||
display_name,
|
||||
tooltip,
|
||||
context,
|
||||
context_name,
|
||||
effort,
|
||||
effort_name,
|
||||
*effort,
|
||||
fast,
|
||||
));
|
||||
}
|
||||
@@ -448,55 +504,67 @@ fn model_variants(model: &ModelConfig, contexts: &[(String, String)]) -> Vec<Mod
|
||||
}
|
||||
|
||||
fn model_variant(
|
||||
model: &ModelConfig,
|
||||
name: &str,
|
||||
display_name: &str,
|
||||
tooltip: &TooltipData,
|
||||
context: &str,
|
||||
context_name: &str,
|
||||
effort: &str,
|
||||
effort_name: &str,
|
||||
effort: Option<(&str, &str)>,
|
||||
fast: bool,
|
||||
) -> ModelVariant {
|
||||
let mut suffix = Vec::with_capacity(3);
|
||||
if context != DEFAULT_CONTEXT {
|
||||
suffix.push(context_name);
|
||||
}
|
||||
suffix.push(effort_name);
|
||||
if let Some((_, effort_name)) = effort {
|
||||
suffix.push(effort_name);
|
||||
}
|
||||
if fast {
|
||||
suffix.push("Fast");
|
||||
}
|
||||
let suffix = suffix.join(" ");
|
||||
let display_name = format!(
|
||||
"{} <span style=\"color: var(--cursor-text-tertiary);\">{suffix}</span>",
|
||||
model.display_name
|
||||
);
|
||||
let is_default = context == DEFAULT_CONTEXT && effort == "high" && !fast;
|
||||
let display_name = if suffix.is_empty() {
|
||||
display_name.to_owned()
|
||||
} else {
|
||||
format!(
|
||||
"{display_name} <span style=\"color: var(--cursor-text-tertiary);\">{suffix}</span>"
|
||||
)
|
||||
};
|
||||
let is_default =
|
||||
context == DEFAULT_CONTEXT && !fast && effort.is_none_or(|(effort, _)| effort == "high");
|
||||
let mut parameter_values = vec![ModelParameterValue {
|
||||
id: "context".into(),
|
||||
value: context.into(),
|
||||
}];
|
||||
if let Some((effort, _)) = effort {
|
||||
parameter_values.push(ModelParameterValue {
|
||||
id: "reasoning".into(),
|
||||
value: effort.into(),
|
||||
});
|
||||
}
|
||||
parameter_values.push(ModelParameterValue {
|
||||
id: "fast".into(),
|
||||
value: fast.to_string(),
|
||||
});
|
||||
ModelVariant {
|
||||
parameter_values: vec![
|
||||
ModelParameterValue {
|
||||
id: "context".into(),
|
||||
value: context.into(),
|
||||
},
|
||||
ModelParameterValue {
|
||||
id: "reasoning".into(),
|
||||
value: effort.into(),
|
||||
},
|
||||
ModelParameterValue {
|
||||
id: "fast".into(),
|
||||
value: fast.to_string(),
|
||||
},
|
||||
],
|
||||
parameter_values,
|
||||
display_name: display_name.clone(),
|
||||
is_max_mode: false,
|
||||
is_default_max_config: is_default.then_some(true),
|
||||
is_default_non_max_config: is_default.then_some(true),
|
||||
tooltip_data: Some(model_tooltip(model)),
|
||||
tooltip_data: Some(tooltip.clone()),
|
||||
display_name_outside_picker: Some(display_name),
|
||||
variant_string_representation: Some(format!(
|
||||
"{}[context={context},reasoning={effort},fast={fast}]",
|
||||
model.model_hash
|
||||
)),
|
||||
variant_string_representation: Some(match effort {
|
||||
Some((effort, _)) => {
|
||||
format!("{name}[context={context},reasoning={effort},fast={fast}]")
|
||||
}
|
||||
None => format!("{name}[context={context},fast={fast}]"),
|
||||
}),
|
||||
legacy_slug: Some(format!(
|
||||
"{}-{context}-{effort}{}",
|
||||
model.model_hash,
|
||||
"{name}-{context}{}{}",
|
||||
effort
|
||||
.map(|(effort, _)| format!("-{effort}"))
|
||||
.unwrap_or_default(),
|
||||
if fast { "-fast" } else { "" }
|
||||
)),
|
||||
}
|
||||
@@ -508,6 +576,63 @@ fn model_tooltip(model: &ModelConfig) -> TooltipData {
|
||||
}
|
||||
}
|
||||
|
||||
fn available_plugin_model(model: &PluginModelDescriptor) -> AvailableModel {
|
||||
let tooltip = TooltipData {
|
||||
markdown_content: model.description.clone(),
|
||||
};
|
||||
// Effort 与上下文档位由宿主统一提供,与内置模型一致;插件不再声明这两项。
|
||||
let contexts = context_options(None);
|
||||
let variants = model_variants(&model.id, &model.display_name, &tooltip, &contexts, true);
|
||||
let legacy_slugs = variants
|
||||
.iter()
|
||||
.filter_map(|variant| variant.legacy_slug.clone())
|
||||
.collect();
|
||||
AvailableModel {
|
||||
name: model.id.clone(),
|
||||
default_on: true,
|
||||
supports_agent: Some(true),
|
||||
degradation_status: Some(0),
|
||||
tooltip_data: Some(tooltip.clone()),
|
||||
supports_thinking: Some(true),
|
||||
supports_images: Some(model.images),
|
||||
supports_max_mode: Some(false),
|
||||
client_display_name: Some(model.display_name.clone()),
|
||||
server_model_name: Some(model.id.clone()),
|
||||
supports_non_max_mode: Some(true),
|
||||
tooltip_data_for_max_mode: Some(tooltip.clone()),
|
||||
is_recommended_for_background_composer: Some(false),
|
||||
supports_plan_mode: Some(true),
|
||||
inputbox_short_model_name: Some(model.display_name.clone()),
|
||||
supports_sandboxing: Some(true),
|
||||
supports_cmd_k: Some(false),
|
||||
parameter_definitions: model_parameters(&contexts, true),
|
||||
variants,
|
||||
legacy_slugs,
|
||||
named_model_section_index: Some(1),
|
||||
vendor_name: Some(model.provider_type.clone()),
|
||||
vendor: Some(AvailableModelVendor {
|
||||
id: 6,
|
||||
display_name: model.provider_type.clone(),
|
||||
}),
|
||||
model_picker_badges: vec![ModelPickerBadge {
|
||||
label: model.plugin_name.clone(),
|
||||
variant: 1,
|
||||
dismiss_on_selection: false,
|
||||
}],
|
||||
}
|
||||
}
|
||||
|
||||
fn usable_plugin_model(model: &PluginModelDescriptor) -> agent::ModelDetails {
|
||||
agent::ModelDetails {
|
||||
model_id: model.id.clone(),
|
||||
display_model_id: model.id.clone(),
|
||||
display_name: model.display_name.clone(),
|
||||
display_name_short: model.display_name.clone(),
|
||||
thinking_details: Some(agent::ThinkingDetails::default()),
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
fn usable_model(model: &ModelConfig) -> agent::ModelDetails {
|
||||
agent::ModelDetails {
|
||||
model_id: model.model_hash.clone(),
|
||||
|
||||
@@ -167,7 +167,7 @@ pub fn tool_completed(call: &ToolCall, completion: &ToolCompletion) -> pb::Agent
|
||||
pub fn tool_placeholder(name: &str, call_id: &str) -> Result<pb::ToolCall> {
|
||||
use pb::tool_call::Tool;
|
||||
let tool = match normalized(name).as_str() {
|
||||
"shell" => Tool::ShellToolCall(pb::ShellToolCall::default()),
|
||||
"shell" | "bash" => Tool::ShellToolCall(pb::ShellToolCall::default()),
|
||||
"delete" => Tool::DeleteToolCall(pb::DeleteToolCall::default()),
|
||||
"glob" => Tool::GlobToolCall(pb::GlobToolCall::default()),
|
||||
"grep" => Tool::GrepToolCall(pb::GrepToolCall::default()),
|
||||
@@ -527,3 +527,23 @@ fn now_ms() -> u64 {
|
||||
.unwrap_or_default()
|
||||
.as_millis() as u64
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::tool_placeholder;
|
||||
use crate::cursor::protocol::proto::agent::v1 as pb;
|
||||
|
||||
#[test]
|
||||
fn bash_renders_as_a_shell_placeholder() {
|
||||
// The dispatcher treats `bash`/`Bash` as a Shell alias, so the streaming
|
||||
// placeholder must too; otherwise a `Bash` tool call aborts the turn with
|
||||
// `unsupported tool: bash` before it ever runs.
|
||||
for name in ["shell", "Shell", "bash", "Bash"] {
|
||||
let tool = tool_placeholder(name, "call-1").unwrap().tool;
|
||||
assert!(
|
||||
matches!(tool, Some(pb::tool_call::Tool::ShellToolCall(_))),
|
||||
"{name} should render as a Shell tool"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -35,7 +35,7 @@ pub fn request(id: u32, call: &ToolCall, context: &ExecContext) -> Result<pb::Ag
|
||||
.map(|v| v as i32)
|
||||
};
|
||||
let message = match normalize(&call.name).as_str() {
|
||||
"shell" => {
|
||||
"shell" | "bash" => {
|
||||
let command = string("command")?;
|
||||
let (simple_commands, parsing_result) = shell_command_metadata(&command);
|
||||
Message::ShellStreamArgs(pb::ShellArgs {
|
||||
@@ -520,3 +520,37 @@ fn prost_value(value: &Value) -> prost_types::Value {
|
||||
};
|
||||
ProstValue { kind: Some(kind) }
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use serde_json::json;
|
||||
|
||||
use super::request;
|
||||
use crate::cursor::protocol::proto::agent::v1 as pb;
|
||||
use crate::cursor::tools::runtime::ExecContext;
|
||||
use crate::model::ToolCall;
|
||||
|
||||
#[test]
|
||||
fn bash_is_encoded_as_a_shell_exec_request() {
|
||||
// The dispatcher routes `bash`/`Bash` to the shell executor, so the
|
||||
// request codec must encode it as a Shell stream instead of erroring
|
||||
// with `tool bash is not executed through ExecServerMessage`.
|
||||
let call = ToolCall {
|
||||
index: 0,
|
||||
call_id: "call-1".into(),
|
||||
model_call_id: "model-1".into(),
|
||||
name: "Bash".into(),
|
||||
arguments_text: String::new(),
|
||||
arguments: json!({ "command": "ls -la" }),
|
||||
};
|
||||
let message = request(1, &call, &ExecContext::default()).unwrap();
|
||||
let Some(pb::agent_server_message::Message::ExecServerMessage(exec)) = message.message
|
||||
else {
|
||||
panic!("expected an ExecServerMessage");
|
||||
};
|
||||
let Some(pb::exec_server_message::Message::ShellStreamArgs(args)) = exec.message else {
|
||||
panic!("expected ShellStreamArgs");
|
||||
};
|
||||
assert_eq!(args.command, "ls -la");
|
||||
}
|
||||
}
|
||||
@@ -144,7 +144,8 @@ pub async fn stream_closed(id: u32, pending: &CursorToolRuntime) -> Result<Optio
|
||||
return Ok(None);
|
||||
};
|
||||
let error = "Cursor Exec stream closed before returning a terminal result";
|
||||
if entry.call.name.eq_ignore_ascii_case("Shell") {
|
||||
if entry.call.name.eq_ignore_ascii_case("Shell") || entry.call.name.eq_ignore_ascii_case("Bash")
|
||||
{
|
||||
let command = entry
|
||||
.call
|
||||
.arguments
|
||||
|
||||
@@ -183,6 +183,9 @@ fn edit_notebook(call: &ToolCall, before: &str) -> std::result::Result<String, S
|
||||
.unwrap_or_default();
|
||||
let old =
|
||||
normalize_newlines(&string(call, "old_string").map_err(|error| error.to_string())?);
|
||||
if old.is_empty() {
|
||||
return Err("old_string must not be empty".into());
|
||||
}
|
||||
let occurrences = source.match_indices(&old).count();
|
||||
let edited = match occurrences {
|
||||
0 => return Err("old_string was not found in the notebook cell".into()),
|
||||
@@ -241,3 +244,49 @@ fn normalized(value: &str) -> String {
|
||||
.flat_map(char::to_lowercase)
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use serde_json::json;
|
||||
|
||||
use super::edit_notebook;
|
||||
use crate::model::ToolCall;
|
||||
|
||||
fn notebook_call(old_string: &str) -> ToolCall {
|
||||
ToolCall {
|
||||
index: 0,
|
||||
call_id: "call".into(),
|
||||
model_call_id: "model".into(),
|
||||
name: "EditNotebook".into(),
|
||||
arguments_text: String::new(),
|
||||
arguments: json!({
|
||||
"target_notebook": "/notebook.ipynb",
|
||||
"cell_idx": 0,
|
||||
"old_string": old_string,
|
||||
"new_string": "replacement",
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
fn single_cell_notebook() -> String {
|
||||
json!({
|
||||
"cells": [{"cell_type": "code", "source": ["print('hi')\n"]}],
|
||||
})
|
||||
.to_string()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn edit_notebook_rejects_empty_old_string() {
|
||||
// StrReplace rejects an empty old_string; EditNotebook must do the same
|
||||
// instead of prepending new_string (empty cell) or reporting a
|
||||
// misleading "not unique" error (non-empty cell).
|
||||
let error = edit_notebook(¬ebook_call(""), &single_cell_notebook()).unwrap_err();
|
||||
assert_eq!(error, "old_string must not be empty");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn edit_notebook_replaces_a_unique_old_string() {
|
||||
let edited = edit_notebook(¬ebook_call("hi"), &single_cell_notebook()).unwrap();
|
||||
assert!(edited.contains("print('replacement')"));
|
||||
}
|
||||
}
|
||||
@@ -9,6 +9,7 @@ use crate::{
|
||||
conversation::ConversationRegistry, prompting::PromptCompiler,
|
||||
services::observability::CursorTraceRecorder,
|
||||
},
|
||||
plugin::PluginRegistry,
|
||||
provider::Provider,
|
||||
search::WebCache,
|
||||
store::Store,
|
||||
@@ -28,6 +29,7 @@ struct RegistryInner {
|
||||
route_changed: Notify,
|
||||
store: Store,
|
||||
web_cache: WebCache,
|
||||
plugins: Option<PluginRegistry>,
|
||||
conversations: ConversationRegistry,
|
||||
}
|
||||
|
||||
@@ -47,6 +49,52 @@ impl TransportRegistry {
|
||||
provider: Arc<dyn Provider>,
|
||||
compiler: PromptCompiler,
|
||||
web_cache: WebCache,
|
||||
) -> Self {
|
||||
Self::build(store, provider, compiler, web_cache, None, None)
|
||||
}
|
||||
|
||||
/// 附带本地 rules 目录的构造;编译请求上下文时会合并该目录下的 md 规则。
|
||||
pub fn with_local_rules(
|
||||
store: Store,
|
||||
provider: Arc<dyn Provider>,
|
||||
compiler: PromptCompiler,
|
||||
local_rules_dir: std::path::PathBuf,
|
||||
) -> Self {
|
||||
Self::build(
|
||||
store,
|
||||
provider,
|
||||
compiler,
|
||||
WebCache::default(),
|
||||
None,
|
||||
Some(local_rules_dir),
|
||||
)
|
||||
}
|
||||
|
||||
pub fn with_plugins(
|
||||
store: Store,
|
||||
provider: Arc<dyn Provider>,
|
||||
compiler: PromptCompiler,
|
||||
web_cache: WebCache,
|
||||
plugins: PluginRegistry,
|
||||
local_rules_dir: std::path::PathBuf,
|
||||
) -> Self {
|
||||
Self::build(
|
||||
store,
|
||||
provider,
|
||||
compiler,
|
||||
web_cache,
|
||||
Some(plugins),
|
||||
Some(local_rules_dir),
|
||||
)
|
||||
}
|
||||
|
||||
fn build(
|
||||
store: Store,
|
||||
provider: Arc<dyn Provider>,
|
||||
compiler: PromptCompiler,
|
||||
web_cache: WebCache,
|
||||
plugins: Option<PluginRegistry>,
|
||||
local_rules_dir: Option<std::path::PathBuf>,
|
||||
) -> Self {
|
||||
Self {
|
||||
inner: Arc::new(RegistryInner {
|
||||
@@ -58,9 +106,11 @@ impl TransportRegistry {
|
||||
provider,
|
||||
compiler,
|
||||
web_cache.clone(),
|
||||
local_rules_dir,
|
||||
),
|
||||
store,
|
||||
web_cache,
|
||||
plugins,
|
||||
}),
|
||||
}
|
||||
}
|
||||
@@ -73,6 +123,10 @@ impl TransportRegistry {
|
||||
&self.inner.web_cache
|
||||
}
|
||||
|
||||
pub fn plugins(&self) -> Option<&PluginRegistry> {
|
||||
self.inner.plugins.as_ref()
|
||||
}
|
||||
|
||||
pub fn conversations(&self) -> &ConversationRegistry {
|
||||
&self.inner.conversations
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user