mirror of
https://wget.la/https://github.com/leookun/cursor-byok
synced 2026-12-01 01:05:10 +08:00
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:
1 parent
d200b3791d
commit
44e2d8057a
206 files changed
+37923
-21
No files matched your search
@@ -0,0 +1,108 @@
|
||||
//! Enforces Conversation ownership during concurrent writes.
|
||||
use base64::{engine::general_purpose::STANDARD, Engine};
|
||||
use sha2::{Digest, Sha256};
|
||||
use sqlx::{Row, Sqlite, Transaction};
|
||||
|
||||
use crate::{Error, Result};
|
||||
|
||||
use super::{now_ms, Store};
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
|
||||
pub struct BlobId([u8; 32]);
|
||||
|
||||
impl BlobId {
|
||||
pub fn digest(data: &[u8]) -> Self {
|
||||
Self(Sha256::digest(data).into())
|
||||
}
|
||||
|
||||
pub fn from_bytes(bytes: &[u8]) -> Result<Self> {
|
||||
let value: [u8; 32] = bytes.try_into().map_err(|_| {
|
||||
Error::Protocol(format!("BlobID must be 32 bytes, got {}", bytes.len()))
|
||||
})?;
|
||||
Ok(Self(value))
|
||||
}
|
||||
|
||||
pub fn from_base64(value: &str) -> Result<Self> {
|
||||
let decoded = STANDARD
|
||||
.decode(value)
|
||||
.map_err(|error| Error::Protocol(format!("invalid BlobID base64: {error}")))?;
|
||||
Self::from_bytes(&decoded)
|
||||
}
|
||||
|
||||
pub fn as_bytes(&self) -> &[u8; 32] {
|
||||
&self.0
|
||||
}
|
||||
pub fn to_base64(&self) -> String {
|
||||
STANDARD.encode(self.0)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct BlobEdge {
|
||||
pub child: BlobId,
|
||||
pub field_name: String,
|
||||
}
|
||||
|
||||
impl Store {
|
||||
pub async fn put_blob(&self, data: &[u8], edges: &[BlobEdge]) -> Result<BlobId> {
|
||||
let _write = self.writes.lock().await;
|
||||
let blob_id = BlobId::digest(data);
|
||||
let mut tx = self.pool.begin_with("BEGIN IMMEDIATE").await?;
|
||||
Self::put_blob_tx(&mut tx, &blob_id, data, edges).await?;
|
||||
tx.commit().await?;
|
||||
Ok(blob_id)
|
||||
}
|
||||
|
||||
pub(crate) async fn put_blob_tx(
|
||||
tx: &mut Transaction<'_, Sqlite>,
|
||||
blob_id: &BlobId,
|
||||
data: &[u8],
|
||||
edges: &[BlobEdge],
|
||||
) -> Result<()> {
|
||||
sqlx::query("INSERT OR IGNORE INTO blobs(blob_id, data, created_at_ms) VALUES (?, ?, ?)")
|
||||
.bind(blob_id.as_bytes().as_slice())
|
||||
.bind(data)
|
||||
.bind(now_ms())
|
||||
.execute(&mut **tx)
|
||||
.await?;
|
||||
for edge in edges {
|
||||
sqlx::query(
|
||||
"INSERT OR IGNORE INTO blob_edges(parent_blob_id, child_blob_id, field_name) VALUES (?, ?, ?)",
|
||||
)
|
||||
.bind(blob_id.as_bytes().as_slice())
|
||||
.bind(edge.child.as_bytes().as_slice())
|
||||
.bind(&edge.field_name)
|
||||
.execute(&mut **tx)
|
||||
.await?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn get_blob(&self, blob_id: &BlobId) -> Result<Option<Vec<u8>>> {
|
||||
Ok(sqlx::query("SELECT data FROM blobs WHERE blob_id = ?")
|
||||
.bind(blob_id.as_bytes().as_slice())
|
||||
.fetch_optional(&self.pool)
|
||||
.await?
|
||||
.map(|row| row.get(0)))
|
||||
}
|
||||
|
||||
pub async fn blob_closure(&self, roots: &[BlobId]) -> Result<Vec<BlobId>> {
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
let mut stack = roots.to_vec();
|
||||
while let Some(id) = stack.pop() {
|
||||
if !seen.insert(id.clone()) {
|
||||
continue;
|
||||
}
|
||||
let rows = sqlx::query("SELECT child_blob_id FROM blob_edges WHERE parent_blob_id = ?")
|
||||
.bind(id.as_bytes().as_slice())
|
||||
.fetch_all(&self.pool)
|
||||
.await?;
|
||||
for row in rows {
|
||||
stack.push(BlobId::from_bytes(row.get::<Vec<u8>, _>(0).as_slice())?);
|
||||
}
|
||||
}
|
||||
let mut closure: Vec<_> = seen.into_iter().collect();
|
||||
closure.sort_by(|left, right| left.as_bytes().cmp(right.as_bytes()));
|
||||
Ok(closure)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,373 @@
|
||||
//! Persists immutable internal Conversation checkpoints.
|
||||
use sha2::{Digest, Sha256};
|
||||
use sqlx::{Sqlite, Transaction};
|
||||
|
||||
use crate::{
|
||||
model::{CanonicalMessage, CheckpointId, ConversationId, RunId},
|
||||
Error, Result,
|
||||
};
|
||||
|
||||
use super::{now_ms, Store};
|
||||
|
||||
impl Store {
|
||||
pub async fn ensure_conversation(
|
||||
&self,
|
||||
conversation_id: &ConversationId,
|
||||
) -> Result<CheckpointId> {
|
||||
let _write = self.writes.lock().await;
|
||||
let mut tx = self.pool.begin_with("BEGIN IMMEDIATE").await?;
|
||||
let checkpoint = Self::ensure_conversation_tx(&mut tx, conversation_id).await?;
|
||||
tx.commit().await?;
|
||||
Ok(checkpoint)
|
||||
}
|
||||
|
||||
pub async fn load_checkpoint_messages(
|
||||
&self,
|
||||
checkpoint_id: CheckpointId,
|
||||
) -> Result<Vec<CanonicalMessage>> {
|
||||
let mut tx = self.pool.begin().await?;
|
||||
let messages = Self::load_checkpoint_messages_tx(&mut tx, checkpoint_id.0).await?;
|
||||
tx.commit().await?;
|
||||
Ok(messages)
|
||||
}
|
||||
|
||||
pub async fn checkpoint_parent(
|
||||
&self,
|
||||
checkpoint_id: CheckpointId,
|
||||
) -> Result<Option<CheckpointId>> {
|
||||
let parent = sqlx::query_scalar::<_, Option<i64>>(
|
||||
"SELECT parent_checkpoint_id FROM conversation_checkpoints WHERE checkpoint_id = ?",
|
||||
)
|
||||
.bind(checkpoint_id.0)
|
||||
.fetch_optional(&self.pool)
|
||||
.await?
|
||||
.flatten()
|
||||
.map(CheckpointId);
|
||||
Ok(parent)
|
||||
}
|
||||
|
||||
pub async fn load_current_messages(
|
||||
&self,
|
||||
conversation_id: &ConversationId,
|
||||
) -> Result<Vec<CanonicalMessage>> {
|
||||
let Some(checkpoint_id) = sqlx::query_scalar::<_, i64>(
|
||||
"SELECT current_checkpoint_id FROM conversations WHERE conversation_id = ?",
|
||||
)
|
||||
.bind(conversation_id.as_str())
|
||||
.fetch_optional(&self.pool)
|
||||
.await?
|
||||
else {
|
||||
return Ok(Vec::new());
|
||||
};
|
||||
self.load_checkpoint_messages(CheckpointId(checkpoint_id))
|
||||
.await
|
||||
}
|
||||
|
||||
pub async fn match_checkpoint_prefix(
|
||||
&self,
|
||||
conversation_id: &ConversationId,
|
||||
base_checkpoint_id: CheckpointId,
|
||||
additions: &[CanonicalMessage],
|
||||
) -> Result<(CheckpointId, usize)> {
|
||||
let mut checkpoint = base_checkpoint_id;
|
||||
let mut messages = self.load_checkpoint_messages(checkpoint).await?;
|
||||
for (index, addition) in additions.iter().enumerate() {
|
||||
messages.push(addition.clone());
|
||||
let digest = message_digest(&messages)?;
|
||||
let child = sqlx::query_scalar::<_, i64>(
|
||||
"SELECT checkpoint_id FROM conversation_checkpoints
|
||||
WHERE conversation_id = ? AND parent_checkpoint_id = ? AND state_digest = ?",
|
||||
)
|
||||
.bind(conversation_id.as_str())
|
||||
.bind(checkpoint.0)
|
||||
.bind(digest.as_slice())
|
||||
.fetch_optional(&self.pool)
|
||||
.await?
|
||||
.map(CheckpointId);
|
||||
let Some(child) = child else {
|
||||
return Ok((checkpoint, index));
|
||||
};
|
||||
if self.load_checkpoint_messages(child).await? != messages {
|
||||
return Ok((checkpoint, index));
|
||||
}
|
||||
checkpoint = child;
|
||||
}
|
||||
Ok((checkpoint, additions.len()))
|
||||
}
|
||||
|
||||
pub async fn import_checkpoint(
|
||||
&self,
|
||||
conversation_id: &ConversationId,
|
||||
messages: &[CanonicalMessage],
|
||||
) -> Result<CheckpointId> {
|
||||
let digest = message_digest(messages)?;
|
||||
let _write = self.writes.lock().await;
|
||||
let mut tx = self.pool.begin_with("BEGIN IMMEDIATE").await?;
|
||||
let current = Self::ensure_conversation_tx(&mut tx, conversation_id).await?;
|
||||
if let Some(existing) = sqlx::query_scalar::<_, i64>(
|
||||
"SELECT checkpoint_id FROM conversation_checkpoints
|
||||
WHERE conversation_id = ? AND state_digest = ?",
|
||||
)
|
||||
.bind(conversation_id.as_str())
|
||||
.bind(digest.as_slice())
|
||||
.fetch_optional(&mut *tx)
|
||||
.await?
|
||||
{
|
||||
tx.commit().await?;
|
||||
return Ok(CheckpointId(existing));
|
||||
}
|
||||
|
||||
let current_messages = Self::load_checkpoint_messages_tx(&mut tx, current.0).await?;
|
||||
let (parent, additions) = if messages.starts_with(¤t_messages) {
|
||||
(current, &messages[current_messages.len()..])
|
||||
} else {
|
||||
let root: i64 = sqlx::query_scalar(
|
||||
"SELECT checkpoint_id FROM conversation_checkpoints
|
||||
WHERE conversation_id = ? AND parent_checkpoint_id IS NULL",
|
||||
)
|
||||
.bind(conversation_id.as_str())
|
||||
.fetch_one(&mut *tx)
|
||||
.await?;
|
||||
(CheckpointId(root), messages)
|
||||
};
|
||||
let checkpoint =
|
||||
Self::insert_checkpoint_tx(&mut tx, conversation_id, parent, additions, digest).await?;
|
||||
tx.commit().await?;
|
||||
Ok(checkpoint)
|
||||
}
|
||||
|
||||
pub async fn append_checkpoint(
|
||||
&self,
|
||||
conversation_id: &ConversationId,
|
||||
run_id: &RunId,
|
||||
expected: CheckpointId,
|
||||
additions: &[CanonicalMessage],
|
||||
) -> Result<CheckpointId> {
|
||||
if additions.is_empty() {
|
||||
return Ok(expected);
|
||||
}
|
||||
let mut full = self.load_checkpoint_messages(expected).await?;
|
||||
full.extend_from_slice(additions);
|
||||
let digest = message_digest(&full)?;
|
||||
let _write = self.writes.lock().await;
|
||||
let mut tx = self.pool.begin_with("BEGIN IMMEDIATE").await?;
|
||||
let checkpoint = Self::append_checkpoint_with_digest_tx(
|
||||
&mut tx,
|
||||
conversation_id,
|
||||
run_id,
|
||||
expected,
|
||||
additions,
|
||||
digest,
|
||||
)
|
||||
.await?;
|
||||
tx.commit().await?;
|
||||
Ok(checkpoint)
|
||||
}
|
||||
|
||||
pub async fn replace_checkpoint(
|
||||
&self,
|
||||
conversation_id: &ConversationId,
|
||||
run_id: &RunId,
|
||||
expected: CheckpointId,
|
||||
messages: &[CanonicalMessage],
|
||||
) -> Result<CheckpointId> {
|
||||
let digest = message_digest(messages)?;
|
||||
let _write = self.writes.lock().await;
|
||||
let mut tx = self.pool.begin_with("BEGIN IMMEDIATE").await?;
|
||||
Self::require_active_head_tx(&mut tx, conversation_id, run_id, expected).await?;
|
||||
let root: i64 = sqlx::query_scalar(
|
||||
"SELECT checkpoint_id FROM conversation_checkpoints
|
||||
WHERE conversation_id = ? AND parent_checkpoint_id IS NULL",
|
||||
)
|
||||
.bind(conversation_id.as_str())
|
||||
.fetch_one(&mut *tx)
|
||||
.await?;
|
||||
let checkpoint = Self::insert_checkpoint_tx(
|
||||
&mut tx,
|
||||
conversation_id,
|
||||
CheckpointId(root),
|
||||
messages,
|
||||
digest,
|
||||
)
|
||||
.await?;
|
||||
let updated = sqlx::query(
|
||||
"UPDATE conversations SET current_checkpoint_id = ?, updated_at_ms = ?
|
||||
WHERE conversation_id = ? AND current_checkpoint_id = ? AND active_run_id = ?",
|
||||
)
|
||||
.bind(checkpoint.0)
|
||||
.bind(now_ms())
|
||||
.bind(conversation_id.as_str())
|
||||
.bind(expected.0)
|
||||
.bind(run_id.as_str())
|
||||
.execute(&mut *tx)
|
||||
.await?
|
||||
.rows_affected();
|
||||
if updated != 1 {
|
||||
return Err(Error::Store(format!(
|
||||
"lost active ownership while replacing checkpoint for run {run_id}"
|
||||
)));
|
||||
}
|
||||
sqlx::query("UPDATE runs SET head_checkpoint_id = ?, updated_at_ms = ? WHERE run_id = ?")
|
||||
.bind(checkpoint.0)
|
||||
.bind(now_ms())
|
||||
.bind(run_id.as_str())
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
tx.commit().await?;
|
||||
Ok(checkpoint)
|
||||
}
|
||||
|
||||
pub async fn append_message_once(
|
||||
&self,
|
||||
conversation_id: &ConversationId,
|
||||
run_id: &RunId,
|
||||
expected: CheckpointId,
|
||||
message: &CanonicalMessage,
|
||||
) -> Result<(CheckpointId, bool)> {
|
||||
let existing = self.load_checkpoint_messages(expected).await?;
|
||||
if let Some(existing) = existing.iter().find(|existing| {
|
||||
existing.message_id == message.message_id
|
||||
|| message.runtime_event_id.is_some()
|
||||
&& existing.runtime_event_id == message.runtime_event_id
|
||||
}) {
|
||||
return if existing == message {
|
||||
Ok((expected, false))
|
||||
} else {
|
||||
Err(Error::Store(format!(
|
||||
"message id or runtime event reused with different content: {}",
|
||||
message.message_id
|
||||
)))
|
||||
};
|
||||
}
|
||||
Ok((
|
||||
self.append_checkpoint(
|
||||
conversation_id,
|
||||
run_id,
|
||||
expected,
|
||||
std::slice::from_ref(message),
|
||||
)
|
||||
.await?,
|
||||
true,
|
||||
))
|
||||
}
|
||||
|
||||
pub(crate) async fn append_checkpoint_tx(
|
||||
tx: &mut Transaction<'_, Sqlite>,
|
||||
conversation_id: &ConversationId,
|
||||
run_id: &RunId,
|
||||
expected: CheckpointId,
|
||||
additions: &[CanonicalMessage],
|
||||
) -> Result<CheckpointId> {
|
||||
let mut full = Self::load_checkpoint_messages_tx(tx, expected.0).await?;
|
||||
full.extend_from_slice(additions);
|
||||
let digest = message_digest(&full)?;
|
||||
Self::append_checkpoint_with_digest_tx(
|
||||
tx,
|
||||
conversation_id,
|
||||
run_id,
|
||||
expected,
|
||||
additions,
|
||||
digest,
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
async fn append_checkpoint_with_digest_tx(
|
||||
tx: &mut Transaction<'_, Sqlite>,
|
||||
conversation_id: &ConversationId,
|
||||
run_id: &RunId,
|
||||
expected: CheckpointId,
|
||||
additions: &[CanonicalMessage],
|
||||
digest: [u8; 32],
|
||||
) -> Result<CheckpointId> {
|
||||
Self::require_active_head_tx(tx, conversation_id, run_id, expected).await?;
|
||||
if sqlx::query_scalar::<_, i64>(
|
||||
"SELECT checkpoint_id FROM conversation_checkpoints
|
||||
WHERE conversation_id = ? AND state_digest = ?",
|
||||
)
|
||||
.bind(conversation_id.as_str())
|
||||
.bind(digest.as_slice())
|
||||
.fetch_optional(&mut **tx)
|
||||
.await?
|
||||
.is_some()
|
||||
{
|
||||
return Err(Error::Store(
|
||||
"active append would reuse an existing checkpoint instead of creating a child"
|
||||
.into(),
|
||||
));
|
||||
}
|
||||
let checkpoint =
|
||||
Self::insert_checkpoint_tx(tx, conversation_id, expected, additions, digest).await?;
|
||||
let updated = sqlx::query(
|
||||
"UPDATE conversations SET current_checkpoint_id = ?, updated_at_ms = ?
|
||||
WHERE conversation_id = ? AND current_checkpoint_id = ? AND active_run_id = ?",
|
||||
)
|
||||
.bind(checkpoint.0)
|
||||
.bind(now_ms())
|
||||
.bind(conversation_id.as_str())
|
||||
.bind(expected.0)
|
||||
.bind(run_id.as_str())
|
||||
.execute(&mut **tx)
|
||||
.await?
|
||||
.rows_affected();
|
||||
if updated != 1 {
|
||||
return Err(Error::Store(format!(
|
||||
"lost active ownership while appending checkpoint for run {run_id}"
|
||||
)));
|
||||
}
|
||||
sqlx::query("UPDATE runs SET head_checkpoint_id = ?, updated_at_ms = ? WHERE run_id = ?")
|
||||
.bind(checkpoint.0)
|
||||
.bind(now_ms())
|
||||
.bind(run_id.as_str())
|
||||
.execute(&mut **tx)
|
||||
.await?;
|
||||
Ok(checkpoint)
|
||||
}
|
||||
|
||||
async fn insert_checkpoint_tx(
|
||||
tx: &mut Transaction<'_, Sqlite>,
|
||||
conversation_id: &ConversationId,
|
||||
parent: CheckpointId,
|
||||
additions: &[CanonicalMessage],
|
||||
digest: [u8; 32],
|
||||
) -> Result<CheckpointId> {
|
||||
for message in additions {
|
||||
Self::put_message_tx(tx, conversation_id, message).await?;
|
||||
}
|
||||
let checkpoint = sqlx::query(
|
||||
"INSERT INTO conversation_checkpoints
|
||||
(conversation_id, parent_checkpoint_id, state_digest, created_at_ms)
|
||||
VALUES (?, ?, ?, ?)",
|
||||
)
|
||||
.bind(conversation_id.as_str())
|
||||
.bind(parent.0)
|
||||
.bind(digest.as_slice())
|
||||
.bind(now_ms())
|
||||
.execute(&mut **tx)
|
||||
.await?
|
||||
.last_insert_rowid();
|
||||
for (ordinal, message) in additions.iter().enumerate() {
|
||||
sqlx::query(
|
||||
"INSERT INTO checkpoint_messages(checkpoint_id, ordinal, conversation_id, message_id)
|
||||
VALUES (?, ?, ?, ?)",
|
||||
)
|
||||
.bind(checkpoint)
|
||||
.bind(ordinal as i64)
|
||||
.bind(conversation_id.as_str())
|
||||
.bind(&message.message_id)
|
||||
.execute(&mut **tx)
|
||||
.await?;
|
||||
}
|
||||
Ok(CheckpointId(checkpoint))
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn message_digest(messages: &[CanonicalMessage]) -> Result<[u8; 32]> {
|
||||
let mut hasher = Sha256::new();
|
||||
for message in messages {
|
||||
let bytes = serde_json::to_vec(message)?;
|
||||
hasher.update((bytes.len() as u64).to_be_bytes());
|
||||
hasher.update(bytes);
|
||||
}
|
||||
Ok(hasher.finalize().into())
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
//! Creates, loads, and updates Conversations.
|
||||
use sqlx::{Row, Sqlite, Transaction};
|
||||
|
||||
use crate::{
|
||||
model::{CheckpointId, Conversation, ConversationId, RunId},
|
||||
Error, Result,
|
||||
};
|
||||
|
||||
use super::{now_ms, Store};
|
||||
|
||||
impl Store {
|
||||
pub async fn conversation(
|
||||
&self,
|
||||
conversation_id: &ConversationId,
|
||||
) -> Result<Option<Conversation>> {
|
||||
let row = sqlx::query(
|
||||
"SELECT current_checkpoint_id, active_run_id
|
||||
FROM conversations WHERE conversation_id = ?",
|
||||
)
|
||||
.bind(conversation_id.as_str())
|
||||
.fetch_optional(&self.pool)
|
||||
.await?;
|
||||
Ok(row.map(|row| Conversation {
|
||||
conversation_id: conversation_id.clone(),
|
||||
current_checkpoint_id: CheckpointId(row.get(0)),
|
||||
active_run_id: row.get::<Option<String>, _>(1).map(RunId),
|
||||
}))
|
||||
}
|
||||
|
||||
pub(crate) async fn ensure_conversation_tx(
|
||||
tx: &mut Transaction<'_, Sqlite>,
|
||||
conversation_id: &ConversationId,
|
||||
) -> Result<CheckpointId> {
|
||||
sqlx::query(
|
||||
"INSERT OR IGNORE INTO conversations(conversation_id, updated_at_ms) VALUES (?, ?)",
|
||||
)
|
||||
.bind(conversation_id.as_str())
|
||||
.bind(now_ms())
|
||||
.execute(&mut **tx)
|
||||
.await?;
|
||||
|
||||
let current: Option<i64> = sqlx::query_scalar(
|
||||
"SELECT current_checkpoint_id FROM conversations WHERE conversation_id = ?",
|
||||
)
|
||||
.bind(conversation_id.as_str())
|
||||
.fetch_one(&mut **tx)
|
||||
.await?;
|
||||
if let Some(current) = current {
|
||||
return Ok(CheckpointId(current));
|
||||
}
|
||||
|
||||
let digest = super::checkpoints::message_digest(&[])?;
|
||||
let root = sqlx::query(
|
||||
"INSERT INTO conversation_checkpoints
|
||||
(conversation_id, parent_checkpoint_id, state_digest, created_at_ms)
|
||||
VALUES (?, NULL, ?, ?)",
|
||||
)
|
||||
.bind(conversation_id.as_str())
|
||||
.bind(digest.as_slice())
|
||||
.bind(now_ms())
|
||||
.execute(&mut **tx)
|
||||
.await?
|
||||
.last_insert_rowid();
|
||||
sqlx::query(
|
||||
"UPDATE conversations SET current_checkpoint_id = ?, updated_at_ms = ?
|
||||
WHERE conversation_id = ? AND current_checkpoint_id IS NULL",
|
||||
)
|
||||
.bind(root)
|
||||
.bind(now_ms())
|
||||
.bind(conversation_id.as_str())
|
||||
.execute(&mut **tx)
|
||||
.await?;
|
||||
Ok(CheckpointId(root))
|
||||
}
|
||||
|
||||
pub(crate) async fn require_active_head_tx(
|
||||
tx: &mut Transaction<'_, Sqlite>,
|
||||
conversation_id: &ConversationId,
|
||||
run_id: &RunId,
|
||||
expected: CheckpointId,
|
||||
) -> Result<()> {
|
||||
let row = sqlx::query(
|
||||
"SELECT current_checkpoint_id, active_run_id FROM conversations WHERE conversation_id = ?",
|
||||
)
|
||||
.bind(conversation_id.as_str())
|
||||
.fetch_optional(&mut **tx)
|
||||
.await?;
|
||||
match row {
|
||||
Some(row)
|
||||
if row.get::<Option<i64>, _>(0) == Some(expected.0)
|
||||
&& row.get::<Option<&str>, _>(1) == Some(run_id.as_str()) =>
|
||||
{
|
||||
Ok(())
|
||||
}
|
||||
_ => Err(Error::Store(format!(
|
||||
"run {run_id} no longer owns conversation {conversation_id} at checkpoint {expected}"
|
||||
))),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,328 @@
|
||||
//! Persists Cursor request traces and artifacts.
|
||||
use sqlx::{Row, Sqlite, Transaction};
|
||||
|
||||
use crate::{
|
||||
model::{CursorRunTraceArtifact, CursorRunTraceSummary},
|
||||
Result,
|
||||
};
|
||||
|
||||
use super::{now_ms, BlobId, Store};
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub(crate) struct BufferedCursorTraceChunk {
|
||||
pub(crate) source: String,
|
||||
pub(crate) data: Vec<u8>,
|
||||
}
|
||||
|
||||
impl BufferedCursorTraceChunk {
|
||||
pub(crate) fn new(source: &str, data: &[u8]) -> Self {
|
||||
Self {
|
||||
source: source.into(),
|
||||
data: data.to_vec(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Store {
|
||||
pub async fn start_cursor_trace_if_detailed(
|
||||
&self,
|
||||
request_id: &str,
|
||||
conversation_id: Option<&str>,
|
||||
route: &str,
|
||||
model_id: Option<&str>,
|
||||
) -> Result<bool> {
|
||||
if self.cursor_trace_exists(request_id).await? {
|
||||
return Ok(true);
|
||||
}
|
||||
if !self.detailed_logging().await? {
|
||||
return Ok(false);
|
||||
}
|
||||
let _write = self.writes.lock().await;
|
||||
sqlx::query(
|
||||
"INSERT OR IGNORE INTO cursor_run_traces(
|
||||
request_id, conversation_id, route, model_id, status, received_at_ms
|
||||
) VALUES (?, ?, ?, ?, 'running', ?)",
|
||||
)
|
||||
.bind(request_id)
|
||||
.bind(conversation_id)
|
||||
.bind(route)
|
||||
.bind(model_id)
|
||||
.bind(now_ms())
|
||||
.execute(&self.pool)
|
||||
.await?;
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
pub async fn cursor_trace_exists(&self, request_id: &str) -> Result<bool> {
|
||||
Ok(sqlx::query_scalar::<_, bool>(
|
||||
"SELECT EXISTS(SELECT 1 FROM cursor_run_traces WHERE request_id = ?)",
|
||||
)
|
||||
.bind(request_id)
|
||||
.fetch_one(&self.pool)
|
||||
.await?)
|
||||
}
|
||||
|
||||
pub async fn append_cursor_trace_artifact(
|
||||
&self,
|
||||
request_id: &str,
|
||||
artifact_type: &str,
|
||||
source: &str,
|
||||
data: &[u8],
|
||||
metadata: &serde_json::Value,
|
||||
) -> Result<()> {
|
||||
let metadata_json = serde_json::to_string(metadata)?;
|
||||
let blob_id = BlobId::digest(data);
|
||||
let _write = self.writes.lock().await;
|
||||
let mut tx = self.pool.begin_with("BEGIN IMMEDIATE").await?;
|
||||
Self::put_blob_tx(&mut tx, &blob_id, data, &[]).await?;
|
||||
Self::link_cursor_trace_artifact_tx(
|
||||
&mut tx,
|
||||
request_id,
|
||||
artifact_type,
|
||||
source,
|
||||
&blob_id,
|
||||
&metadata_json,
|
||||
)
|
||||
.await?;
|
||||
tx.commit().await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn link_cursor_trace_artifact(
|
||||
&self,
|
||||
request_id: &str,
|
||||
artifact_type: &str,
|
||||
source: &str,
|
||||
blob_id: &BlobId,
|
||||
metadata: &serde_json::Value,
|
||||
) -> Result<()> {
|
||||
let metadata_json = serde_json::to_string(metadata)?;
|
||||
let _write = self.writes.lock().await;
|
||||
let mut tx = self.pool.begin_with("BEGIN IMMEDIATE").await?;
|
||||
Self::link_cursor_trace_artifact_tx(
|
||||
&mut tx,
|
||||
request_id,
|
||||
artifact_type,
|
||||
source,
|
||||
blob_id,
|
||||
&metadata_json,
|
||||
)
|
||||
.await?;
|
||||
tx.commit().await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn link_cursor_trace_artifact_tx(
|
||||
tx: &mut Transaction<'_, Sqlite>,
|
||||
request_id: &str,
|
||||
artifact_type: &str,
|
||||
source: &str,
|
||||
blob_id: &BlobId,
|
||||
metadata_json: &str,
|
||||
) -> Result<()> {
|
||||
let next: i64 = sqlx::query_scalar(
|
||||
"SELECT COALESCE(MAX(seq), -1) + 1
|
||||
FROM cursor_run_trace_artifacts WHERE request_id = ?",
|
||||
)
|
||||
.bind(request_id)
|
||||
.fetch_one(&mut **tx)
|
||||
.await?;
|
||||
sqlx::query(
|
||||
"INSERT INTO cursor_run_trace_artifacts(
|
||||
request_id, seq, artifact_type, source, blob_id, metadata_json, created_at_ms
|
||||
) VALUES (?, ?, ?, ?, ?, ?, ?)",
|
||||
)
|
||||
.bind(request_id)
|
||||
.bind(next)
|
||||
.bind(artifact_type)
|
||||
.bind(source)
|
||||
.bind(blob_id.as_bytes().as_slice())
|
||||
.bind(metadata_json)
|
||||
.bind(now_ms())
|
||||
.execute(&mut **tx)
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn add_cursor_trace_request_bytes(
|
||||
&self,
|
||||
request_id: &str,
|
||||
bytes: usize,
|
||||
) -> Result<()> {
|
||||
let _write = self.writes.lock().await;
|
||||
sqlx::query(
|
||||
"UPDATE cursor_run_traces
|
||||
SET request_bytes = request_bytes + ? WHERE request_id = ?",
|
||||
)
|
||||
.bind(as_i64(bytes))
|
||||
.bind(request_id)
|
||||
.execute(&self.pool)
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn start_cursor_trace_response(&self, request_id: &str, status: u16) -> Result<()> {
|
||||
let now = now_ms();
|
||||
let _write = self.writes.lock().await;
|
||||
sqlx::query(
|
||||
"UPDATE cursor_run_traces
|
||||
SET status = 'running', http_status = ?,
|
||||
first_response_at_ms = COALESCE(first_response_at_ms, ?),
|
||||
finished_at_ms = NULL, error_message = NULL
|
||||
WHERE request_id = ?",
|
||||
)
|
||||
.bind(status as i64)
|
||||
.bind(now)
|
||||
.bind(request_id)
|
||||
.execute(&self.pool)
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn add_cursor_trace_response_chunk(
|
||||
&self,
|
||||
request_id: &str,
|
||||
source: &str,
|
||||
data: &[u8],
|
||||
) -> Result<()> {
|
||||
self.add_cursor_trace_response_chunks(
|
||||
request_id,
|
||||
&[BufferedCursorTraceChunk::new(source, data)],
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
pub(crate) async fn add_cursor_trace_response_chunks(
|
||||
&self,
|
||||
request_id: &str,
|
||||
chunks: &[BufferedCursorTraceChunk],
|
||||
) -> Result<()> {
|
||||
if chunks.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
let response_bytes = chunks.iter().map(|chunk| chunk.data.len()).sum::<usize>();
|
||||
let _write = self.writes.lock().await;
|
||||
let mut tx = self.pool.begin_with("BEGIN IMMEDIATE").await?;
|
||||
for chunk in chunks {
|
||||
let metadata_json =
|
||||
serde_json::to_string(&serde_json::json!({"byte_count": chunk.data.len()}))?;
|
||||
let blob_id = BlobId::digest(&chunk.data);
|
||||
Self::put_blob_tx(&mut tx, &blob_id, &chunk.data, &[]).await?;
|
||||
Self::link_cursor_trace_artifact_tx(
|
||||
&mut tx,
|
||||
request_id,
|
||||
"run_sse_chunk",
|
||||
&chunk.source,
|
||||
&blob_id,
|
||||
&metadata_json,
|
||||
)
|
||||
.await?;
|
||||
}
|
||||
sqlx::query(
|
||||
"UPDATE cursor_run_traces
|
||||
SET response_bytes = response_bytes + ?,
|
||||
response_event_count = response_event_count + ?,
|
||||
first_response_at_ms = COALESCE(first_response_at_ms, ?)
|
||||
WHERE request_id = ?",
|
||||
)
|
||||
.bind(as_i64(response_bytes))
|
||||
.bind(chunks.len() as i64)
|
||||
.bind(now_ms())
|
||||
.bind(request_id)
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
tx.commit().await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn finish_cursor_trace(&self, request_id: &str, error: Option<&str>) -> Result<()> {
|
||||
let _write = self.writes.lock().await;
|
||||
sqlx::query(
|
||||
"UPDATE cursor_run_traces
|
||||
SET status = ?, finished_at_ms = ?, error_message = ?
|
||||
WHERE request_id = ?",
|
||||
)
|
||||
.bind(if error.is_some() {
|
||||
"error"
|
||||
} else {
|
||||
"completed"
|
||||
})
|
||||
.bind(now_ms())
|
||||
.bind(error)
|
||||
.bind(request_id)
|
||||
.execute(&self.pool)
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn cursor_trace(&self, request_id: &str) -> Result<Option<CursorRunTraceSummary>> {
|
||||
sqlx::query("SELECT * FROM cursor_run_traces WHERE request_id = ?")
|
||||
.bind(request_id)
|
||||
.fetch_optional(&self.pool)
|
||||
.await?
|
||||
.map(trace_from_row)
|
||||
.transpose()
|
||||
}
|
||||
|
||||
pub async fn official_cursor_traces(&self, limit: i64) -> Result<Vec<CursorRunTraceSummary>> {
|
||||
let rows = sqlx::query(
|
||||
"SELECT * FROM cursor_run_traces
|
||||
WHERE route = 'cursor_official'
|
||||
ORDER BY received_at_ms DESC LIMIT ?",
|
||||
)
|
||||
.bind(limit.clamp(1, 500))
|
||||
.fetch_all(&self.pool)
|
||||
.await?;
|
||||
rows.into_iter().map(trace_from_row).collect()
|
||||
}
|
||||
|
||||
pub async fn cursor_trace_artifacts(
|
||||
&self,
|
||||
request_id: &str,
|
||||
) -> Result<Vec<CursorRunTraceArtifact>> {
|
||||
let rows = sqlx::query(
|
||||
"SELECT a.seq, a.artifact_type, a.source, a.metadata_json,
|
||||
a.created_at_ms, b.data
|
||||
FROM cursor_run_trace_artifacts a
|
||||
JOIN blobs b ON b.blob_id = a.blob_id
|
||||
WHERE a.request_id = ? ORDER BY a.seq",
|
||||
)
|
||||
.bind(request_id)
|
||||
.fetch_all(&self.pool)
|
||||
.await?;
|
||||
rows.into_iter()
|
||||
.map(|row| {
|
||||
Ok(CursorRunTraceArtifact {
|
||||
seq: row.try_get("seq")?,
|
||||
artifact_type: row.try_get("artifact_type")?,
|
||||
source: row.try_get("source")?,
|
||||
metadata: serde_json::from_str(row.try_get("metadata_json")?)?,
|
||||
created_at_ms: row.try_get("created_at_ms")?,
|
||||
data: row.try_get("data")?,
|
||||
})
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
}
|
||||
|
||||
fn trace_from_row(row: sqlx::sqlite::SqliteRow) -> Result<CursorRunTraceSummary> {
|
||||
Ok(CursorRunTraceSummary {
|
||||
request_id: row.try_get("request_id")?,
|
||||
conversation_id: row.try_get("conversation_id")?,
|
||||
route: row.try_get("route")?,
|
||||
model_id: row.try_get("model_id")?,
|
||||
status: row.try_get("status")?,
|
||||
request_bytes: row.try_get("request_bytes")?,
|
||||
response_bytes: row.try_get("response_bytes")?,
|
||||
response_event_count: row.try_get("response_event_count")?,
|
||||
http_status: row.try_get("http_status")?,
|
||||
received_at_ms: row.try_get("received_at_ms")?,
|
||||
first_response_at_ms: row.try_get("first_response_at_ms")?,
|
||||
finished_at_ms: row.try_get("finished_at_ms")?,
|
||||
error_message: row.try_get("error_message")?,
|
||||
})
|
||||
}
|
||||
|
||||
fn as_i64(value: usize) -> i64 {
|
||||
value.min(i64::MAX as usize) as i64
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
//! Deduplicates Cursor inputs against their Conversation base.
|
||||
use crate::{
|
||||
model::{CheckpointId, ConversationId},
|
||||
Result,
|
||||
};
|
||||
|
||||
use super::{now_ms, Store};
|
||||
|
||||
impl Store {
|
||||
pub async fn anchor_input(
|
||||
&self,
|
||||
conversation_id: &ConversationId,
|
||||
input_id: &str,
|
||||
base_checkpoint_id: CheckpointId,
|
||||
) -> Result<CheckpointId> {
|
||||
let _write = self.writes.lock().await;
|
||||
let mut tx = self.pool.begin_with("BEGIN IMMEDIATE").await?;
|
||||
sqlx::query(
|
||||
"INSERT INTO input_anchors
|
||||
(conversation_id, input_id, base_checkpoint_id, created_at_ms)
|
||||
VALUES (?, ?, ?, ?)
|
||||
ON CONFLICT(conversation_id, input_id) DO NOTHING",
|
||||
)
|
||||
.bind(conversation_id.as_str())
|
||||
.bind(input_id)
|
||||
.bind(base_checkpoint_id.0)
|
||||
.bind(now_ms())
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
let anchored = sqlx::query_scalar::<_, i64>(
|
||||
"SELECT base_checkpoint_id FROM input_anchors
|
||||
WHERE conversation_id = ? AND input_id = ?",
|
||||
)
|
||||
.bind(conversation_id.as_str())
|
||||
.bind(input_id)
|
||||
.fetch_one(&mut *tx)
|
||||
.await?;
|
||||
tx.commit().await?;
|
||||
Ok(CheckpointId(anchored))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,275 @@
|
||||
//! Imports model definitions from the v0.0.49 YAML configuration.
|
||||
use std::{collections::HashSet, path::Path};
|
||||
|
||||
use serde::Deserialize;
|
||||
|
||||
use crate::{
|
||||
model::{
|
||||
model_hash, normalize_model_input, normalize_request_url, ModelConfigInput, ModelType,
|
||||
OPENAI_CHAT_ENDPOINT, OPENAI_RESPONSES_ENDPOINT,
|
||||
},
|
||||
Error, Result,
|
||||
};
|
||||
|
||||
use super::Store;
|
||||
|
||||
pub struct LegacyModelImportPlan {
|
||||
pub models: Vec<LegacyModelImportEntry>,
|
||||
}
|
||||
|
||||
pub struct LegacyModelImportEntry {
|
||||
pub model_hash: String,
|
||||
pub input: ModelConfigInput,
|
||||
pub existing: bool,
|
||||
}
|
||||
|
||||
pub struct LegacyModelImportOutcome {
|
||||
pub imported: usize,
|
||||
pub skipped: usize,
|
||||
pub total: usize,
|
||||
}
|
||||
|
||||
#[derive(Default, Deserialize)]
|
||||
struct LegacyConfig {
|
||||
#[serde(rename = "modelAdapters", default)]
|
||||
model_adapters: Vec<LegacyModel>,
|
||||
}
|
||||
|
||||
#[derive(Default, Deserialize)]
|
||||
struct LegacyModel {
|
||||
#[serde(default)]
|
||||
sort: i64,
|
||||
#[serde(rename = "displayName", default)]
|
||||
display_name: String,
|
||||
#[serde(rename = "type", default)]
|
||||
model_type: String,
|
||||
#[serde(rename = "baseURL", default)]
|
||||
base_url: String,
|
||||
#[serde(rename = "apiKey", default)]
|
||||
api_key: String,
|
||||
#[serde(rename = "tooltipData", default)]
|
||||
tooltip_data: String,
|
||||
#[serde(rename = "modelID", default)]
|
||||
model_id: String,
|
||||
#[serde(rename = "reasoningEffort", default)]
|
||||
reasoning_effort: String,
|
||||
#[serde(rename = "openAIEndpoint", default)]
|
||||
openai_endpoint: String,
|
||||
#[serde(rename = "openAIExtraParamsEnabled", default)]
|
||||
openai_extra_params_enabled: bool,
|
||||
#[serde(rename = "openAIExtraParamsJSON", default)]
|
||||
openai_extra_params_json: String,
|
||||
#[serde(rename = "customHeadersEnabled", default)]
|
||||
custom_headers_enabled: bool,
|
||||
#[serde(rename = "customHeadersJSON", default)]
|
||||
custom_headers_json: String,
|
||||
#[serde(rename = "anthropicExtraParamsEnabled", default)]
|
||||
anthropic_extra_params_enabled: bool,
|
||||
#[serde(rename = "anthropicExtraParamsJSON", default)]
|
||||
anthropic_extra_params_json: String,
|
||||
#[serde(rename = "contextWindowTokens", default)]
|
||||
context_window_tokens: u64,
|
||||
#[serde(rename = "maxCompletionTokens", default)]
|
||||
max_completion_tokens: u64,
|
||||
#[serde(rename = "anthropicMaxTokens", default)]
|
||||
anthropic_max_tokens: u64,
|
||||
#[serde(rename = "anthropicThinkingEffort", default)]
|
||||
anthropic_thinking_effort: String,
|
||||
#[serde(rename = "thinkingBudgetTokens", default)]
|
||||
thinking_budget_tokens: u64,
|
||||
}
|
||||
|
||||
impl Store {
|
||||
pub async fn preview_v0049_model_config(&self, path: &Path) -> Result<LegacyModelImportPlan> {
|
||||
let inputs = load_v0049_model_config(path)?;
|
||||
let existing = self
|
||||
.models()
|
||||
.await?
|
||||
.into_iter()
|
||||
.map(|model| model.model_hash)
|
||||
.collect::<HashSet<_>>();
|
||||
let mut seen = HashSet::with_capacity(inputs.len());
|
||||
let mut models = Vec::with_capacity(inputs.len());
|
||||
for input in inputs {
|
||||
let input = normalize_model_input(&input)?;
|
||||
let hash = model_hash(&input)?;
|
||||
if seen.insert(hash.clone()) {
|
||||
models.push(LegacyModelImportEntry {
|
||||
existing: existing.contains(&hash),
|
||||
model_hash: hash,
|
||||
input,
|
||||
});
|
||||
}
|
||||
}
|
||||
Ok(LegacyModelImportPlan { models })
|
||||
}
|
||||
|
||||
pub async fn import_v0049_model_config(&self, path: &Path) -> Result<LegacyModelImportOutcome> {
|
||||
let plan = self.preview_v0049_model_config(path).await?;
|
||||
let total = plan.models.len();
|
||||
let missing = plan
|
||||
.models
|
||||
.into_iter()
|
||||
.filter(|model| !model.existing)
|
||||
.map(|model| model.input)
|
||||
.collect::<Vec<_>>();
|
||||
let imported = self.create_models_if_missing(&missing).await?;
|
||||
Ok(LegacyModelImportOutcome {
|
||||
imported,
|
||||
skipped: total - imported,
|
||||
total,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
fn load_v0049_model_config(path: &Path) -> Result<Vec<ModelConfigInput>> {
|
||||
let raw = match std::fs::read(path) {
|
||||
Ok(raw) => raw,
|
||||
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
|
||||
return Err(Error::Config(format!(
|
||||
"v0.0.49 config not found at {}",
|
||||
path.display()
|
||||
)))
|
||||
}
|
||||
Err(error) => return Err(error.into()),
|
||||
};
|
||||
let legacy: LegacyConfig = serde_yaml::from_slice(&raw)
|
||||
.map_err(|error| Error::Config(format!("invalid v0.0.49 config: {error}")))?;
|
||||
if legacy.model_adapters.is_empty() {
|
||||
return Err(Error::Config(
|
||||
"v0.0.49 config contains no model adapters".into(),
|
||||
));
|
||||
}
|
||||
legacy.model_adapters.into_iter().map(model_input).collect()
|
||||
}
|
||||
|
||||
fn model_input(model: LegacyModel) -> Result<ModelConfigInput> {
|
||||
let model_type = match model.model_type.trim().to_ascii_lowercase().as_str() {
|
||||
"openai" => ModelType::OpenAi,
|
||||
"anthropic" => ModelType::Anthropic,
|
||||
value => {
|
||||
return Err(Error::Config(format!(
|
||||
"unsupported v0.0.49 model type: {value}"
|
||||
)))
|
||||
}
|
||||
};
|
||||
let (base_url, openai_endpoint, use_full_url) =
|
||||
legacy_request_configuration(model_type, &model.base_url, &model.openai_endpoint)?;
|
||||
Ok(ModelConfigInput {
|
||||
sort_order: model.sort,
|
||||
display_name: model.display_name.clone(),
|
||||
model_type,
|
||||
base_url,
|
||||
use_full_url,
|
||||
api_key: model.api_key,
|
||||
tooltip_data: if model.tooltip_data.trim().is_empty() {
|
||||
model.display_name
|
||||
} else {
|
||||
model.tooltip_data
|
||||
},
|
||||
model_id: model.model_id,
|
||||
reasoning_effort: optional_string(model.reasoning_effort),
|
||||
openai_endpoint,
|
||||
openai_extra_params_enabled: model.openai_extra_params_enabled,
|
||||
openai_extra_params: enabled_json_object(
|
||||
model_type == ModelType::OpenAi && model.openai_extra_params_enabled,
|
||||
&model.openai_extra_params_json,
|
||||
)?,
|
||||
custom_headers_enabled: model.custom_headers_enabled,
|
||||
custom_headers: enabled_json_object(
|
||||
model.custom_headers_enabled,
|
||||
&model.custom_headers_json,
|
||||
)?,
|
||||
anthropic_extra_params_enabled: model.anthropic_extra_params_enabled,
|
||||
anthropic_extra_params: enabled_json_object(
|
||||
model_type == ModelType::Anthropic && model.anthropic_extra_params_enabled,
|
||||
&model.anthropic_extra_params_json,
|
||||
)?,
|
||||
context_window_tokens: positive(model.context_window_tokens),
|
||||
max_completion_tokens: positive(model.max_completion_tokens),
|
||||
anthropic_max_tokens: positive(model.anthropic_max_tokens),
|
||||
anthropic_thinking_effort: optional_string(model.anthropic_thinking_effort),
|
||||
thinking_budget_tokens: positive(model.thinking_budget_tokens),
|
||||
})
|
||||
}
|
||||
|
||||
fn legacy_request_configuration(
|
||||
model_type: ModelType,
|
||||
base_url: &str,
|
||||
openai_endpoint: &str,
|
||||
) -> Result<(String, String, bool)> {
|
||||
let base_url = normalize_request_url(base_url)?;
|
||||
match model_type {
|
||||
ModelType::Anthropic => {
|
||||
let use_full_url = url_path_ends_with(&base_url, "/messages");
|
||||
Ok((base_url, String::new(), use_full_url))
|
||||
}
|
||||
ModelType::OpenAi => {
|
||||
let detected = openai_protocol_from_url(&base_url);
|
||||
let configured = match openai_endpoint.trim() {
|
||||
"" | OPENAI_RESPONSES_ENDPOINT => OPENAI_RESPONSES_ENDPOINT,
|
||||
OPENAI_CHAT_ENDPOINT => OPENAI_CHAT_ENDPOINT,
|
||||
"/custom" => OPENAI_CHAT_ENDPOINT,
|
||||
value => {
|
||||
return Err(Error::Config(format!(
|
||||
"unsupported v0.0.49 OpenAI endpoint: {value}"
|
||||
)))
|
||||
}
|
||||
};
|
||||
let protocol = detected.unwrap_or(configured);
|
||||
let use_full_url = detected.is_some() || openai_endpoint.trim() == "/custom";
|
||||
Ok((base_url, protocol.into(), use_full_url))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn openai_protocol_from_url(value: &str) -> Option<&'static str> {
|
||||
let url = reqwest::Url::parse(value).ok()?;
|
||||
let path = url.path().trim_end_matches('/');
|
||||
if path.to_ascii_lowercase().ends_with("/responses") {
|
||||
Some(OPENAI_RESPONSES_ENDPOINT)
|
||||
} else if path.to_ascii_lowercase().ends_with("/chat/completions") {
|
||||
Some(OPENAI_CHAT_ENDPOINT)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
fn url_path_ends_with(value: &str, suffix: &str) -> bool {
|
||||
reqwest::Url::parse(value).is_ok_and(|url| {
|
||||
url.path()
|
||||
.trim_end_matches('/')
|
||||
.to_ascii_lowercase()
|
||||
.ends_with(suffix)
|
||||
})
|
||||
}
|
||||
|
||||
fn enabled_json_object(enabled: bool, value: &str) -> Result<serde_json::Value> {
|
||||
if enabled {
|
||||
json_object(value)
|
||||
} else {
|
||||
Ok(serde_json::json!({}))
|
||||
}
|
||||
}
|
||||
|
||||
fn json_object(value: &str) -> Result<serde_json::Value> {
|
||||
if value.trim().is_empty() {
|
||||
return Ok(serde_json::json!({}));
|
||||
}
|
||||
let value: serde_json::Value = serde_json::from_str(value)?;
|
||||
if value.is_object() {
|
||||
Ok(value)
|
||||
} else {
|
||||
Err(Error::Config(
|
||||
"v0.0.49 model JSON fields must be objects".into(),
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
fn positive(value: u64) -> Option<u64> {
|
||||
(value > 0).then_some(value)
|
||||
}
|
||||
|
||||
fn optional_string(value: String) -> Option<String> {
|
||||
(!value.trim().is_empty()).then_some(value)
|
||||
}
|
||||
@@ -0,0 +1,414 @@
|
||||
//! Persists provider call payloads, timing, and usage.
|
||||
use std::str::FromStr;
|
||||
|
||||
use sqlx::Row;
|
||||
|
||||
use crate::{
|
||||
model::{
|
||||
ConversationId, LlmCallRequest, LlmCallResponseChunk, LlmCallSummary, LlmCallUsageAnchor,
|
||||
NewLlmCall, ProviderType, Usage,
|
||||
},
|
||||
Result,
|
||||
};
|
||||
|
||||
use super::{now_ms, Store};
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub(crate) struct BufferedLlmChunk {
|
||||
pub(crate) seq: i64,
|
||||
pub(crate) elapsed_ms: i64,
|
||||
pub(crate) data: Option<Vec<u8>>,
|
||||
pub(crate) byte_count: usize,
|
||||
}
|
||||
|
||||
impl BufferedLlmChunk {
|
||||
pub(crate) fn new(seq: i64, elapsed_ms: i64, data: &[u8]) -> Self {
|
||||
Self {
|
||||
seq,
|
||||
elapsed_ms,
|
||||
data: Some(data.to_vec()),
|
||||
byte_count: data.len(),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn metrics(seq: i64, elapsed_ms: i64, byte_count: usize) -> Self {
|
||||
Self {
|
||||
seq,
|
||||
elapsed_ms,
|
||||
data: None,
|
||||
byte_count,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Store {
|
||||
pub async fn detailed_logging(&self) -> Result<bool> {
|
||||
let value: String = sqlx::query_scalar(
|
||||
"SELECT value_json FROM service_settings WHERE setting_key = 'llm_detailed_logging'",
|
||||
)
|
||||
.fetch_one(&self.pool)
|
||||
.await?;
|
||||
Ok(serde_json::from_str(&value)?)
|
||||
}
|
||||
|
||||
pub async fn set_detailed_logging(&self, enabled: bool) -> Result<()> {
|
||||
let _write = self.writes.lock().await;
|
||||
sqlx::query(
|
||||
"INSERT INTO service_settings(setting_key, value_json, updated_at_ms) VALUES ('llm_detailed_logging', ?, ?) ON CONFLICT(setting_key) DO UPDATE SET value_json = excluded.value_json, updated_at_ms = excluded.updated_at_ms",
|
||||
)
|
||||
.bind(serde_json::to_string(&enabled)?)
|
||||
.bind(now_ms())
|
||||
.execute(&self.pool)
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn start_llm_call(&self, call: &NewLlmCall) -> Result<()> {
|
||||
let _write = self.writes.lock().await;
|
||||
let now = now_ms();
|
||||
sqlx::query(
|
||||
r#"INSERT INTO llm_calls(
|
||||
call_id, run_id, conversation_id, provider_call_index, model_hash,
|
||||
provider_type, provider_url, request_type, request_url, model_id, display_name,
|
||||
reasoning_effort, fast, status,
|
||||
created_at_ms, request_started_at_ms, queue_ms, message_count, tool_count, detailed
|
||||
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'running', ?, ?, 0, ?, ?, ?)"#,
|
||||
)
|
||||
.bind(&call.call_id)
|
||||
.bind(&call.run_id)
|
||||
.bind(&call.conversation_id)
|
||||
.bind(call.provider_call_index)
|
||||
.bind(&call.model_hash)
|
||||
.bind(call.provider_type.as_str())
|
||||
.bind(&call.provider_url)
|
||||
.bind(call.request_type.as_str())
|
||||
.bind(&call.request_url)
|
||||
.bind(&call.model_id)
|
||||
.bind(&call.display_name)
|
||||
.bind(&call.reasoning_effort)
|
||||
.bind(call.fast)
|
||||
.bind(now)
|
||||
.bind(now)
|
||||
.bind(call.message_count as i64)
|
||||
.bind(call.tool_count as i64)
|
||||
.bind(call.detailed)
|
||||
.execute(&self.pool)
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn record_llm_request(
|
||||
&self,
|
||||
call_id: &str,
|
||||
headers: &serde_json::Value,
|
||||
body: &serde_json::Value,
|
||||
detailed: bool,
|
||||
) -> Result<()> {
|
||||
let body_json = serde_json::to_string(body)?;
|
||||
let headers_json = detailed
|
||||
.then(|| serde_json::to_string(headers))
|
||||
.transpose()?;
|
||||
let _write = self.writes.lock().await;
|
||||
let mut transaction = self.pool.begin_with("BEGIN IMMEDIATE").await?;
|
||||
if detailed {
|
||||
sqlx::query("INSERT INTO llm_call_requests(call_id, headers_json, body_json, byte_count) SELECT ?, ?, ?, ? WHERE EXISTS (SELECT 1 FROM llm_calls WHERE call_id = ?)")
|
||||
.bind(call_id)
|
||||
.bind(headers_json)
|
||||
.bind(&body_json)
|
||||
.bind(body_json.len() as i64)
|
||||
.bind(call_id)
|
||||
.execute(&mut *transaction)
|
||||
.await?;
|
||||
}
|
||||
sqlx::query("UPDATE llm_calls SET request_bytes = ? WHERE call_id = ?")
|
||||
.bind(body_json.len() as i64)
|
||||
.bind(call_id)
|
||||
.execute(&mut *transaction)
|
||||
.await?;
|
||||
transaction.commit().await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn record_llm_response_headers(
|
||||
&self,
|
||||
call_id: &str,
|
||||
elapsed_ms: i64,
|
||||
http_status: u16,
|
||||
) -> Result<()> {
|
||||
let _write = self.writes.lock().await;
|
||||
sqlx::query("UPDATE llm_calls SET response_headers_at_ms = ?, ttfb_ms = ?, http_status = ? WHERE call_id = ?")
|
||||
.bind(now_ms())
|
||||
.bind(elapsed_ms)
|
||||
.bind(http_status as i64)
|
||||
.bind(call_id)
|
||||
.execute(&self.pool)
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn record_llm_chunk(
|
||||
&self,
|
||||
call_id: &str,
|
||||
seq: i64,
|
||||
elapsed_ms: i64,
|
||||
data: &[u8],
|
||||
detailed: bool,
|
||||
) -> Result<()> {
|
||||
let chunk = if detailed {
|
||||
BufferedLlmChunk::new(seq, elapsed_ms, data)
|
||||
} else {
|
||||
BufferedLlmChunk::metrics(seq, elapsed_ms, data.len())
|
||||
};
|
||||
self.record_llm_chunks(call_id, &[chunk], detailed).await
|
||||
}
|
||||
|
||||
pub(crate) async fn record_llm_chunks(
|
||||
&self,
|
||||
call_id: &str,
|
||||
chunks: &[BufferedLlmChunk],
|
||||
detailed: bool,
|
||||
) -> Result<()> {
|
||||
if chunks.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
let byte_count = chunks
|
||||
.iter()
|
||||
.map(|chunk| chunk.byte_count as i64)
|
||||
.sum::<i64>();
|
||||
let event_count = chunks.len() as i64;
|
||||
let _write = self.writes.lock().await;
|
||||
let mut transaction = self.pool.begin_with("BEGIN IMMEDIATE").await?;
|
||||
if detailed {
|
||||
for chunk in chunks {
|
||||
let data = chunk.data.as_deref().ok_or_else(|| {
|
||||
crate::Error::Store("detailed LLM chunk is missing payload data".into())
|
||||
})?;
|
||||
sqlx::query("INSERT INTO llm_call_response_chunks(call_id, seq, received_offset_ms, data, byte_count) SELECT ?, ?, ?, ?, ? WHERE EXISTS (SELECT 1 FROM llm_calls WHERE call_id = ?)")
|
||||
.bind(call_id)
|
||||
.bind(chunk.seq)
|
||||
.bind(chunk.elapsed_ms)
|
||||
.bind(data)
|
||||
.bind(chunk.byte_count as i64)
|
||||
.bind(call_id)
|
||||
.execute(&mut *transaction)
|
||||
.await?;
|
||||
}
|
||||
}
|
||||
sqlx::query("UPDATE llm_calls SET first_event_at_ms = COALESCE(first_event_at_ms, ?), response_bytes = response_bytes + ?, stream_event_count = stream_event_count + ? WHERE call_id = ?")
|
||||
.bind(now_ms())
|
||||
.bind(byte_count)
|
||||
.bind(event_count)
|
||||
.bind(call_id)
|
||||
.execute(&mut *transaction)
|
||||
.await?;
|
||||
transaction.commit().await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn record_llm_first_valid_response(
|
||||
&self,
|
||||
call_id: &str,
|
||||
elapsed_ms: i64,
|
||||
) -> Result<()> {
|
||||
let _write = self.writes.lock().await;
|
||||
sqlx::query("UPDATE llm_calls SET first_valid_response_at_ms = COALESCE(first_valid_response_at_ms, ?), ttfr_ms = COALESCE(ttfr_ms, ?) WHERE call_id = ?")
|
||||
.bind(now_ms())
|
||||
.bind(elapsed_ms)
|
||||
.bind(call_id)
|
||||
.execute(&self.pool)
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn record_llm_first_text(&self, call_id: &str, elapsed_ms: i64) -> Result<()> {
|
||||
let _write = self.writes.lock().await;
|
||||
sqlx::query("UPDATE llm_calls SET first_text_at_ms = COALESCE(first_text_at_ms, ?), ttft_ms = COALESCE(ttft_ms, ?) WHERE call_id = ?")
|
||||
.bind(now_ms())
|
||||
.bind(elapsed_ms)
|
||||
.bind(call_id)
|
||||
.execute(&self.pool)
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn record_llm_usage(&self, call_id: &str, usage: Usage) -> Result<()> {
|
||||
let usage_json = serde_json::to_string(&usage)?;
|
||||
let _write = self.writes.lock().await;
|
||||
sqlx::query("UPDATE llm_calls SET input_tokens = ?, output_tokens = ?, total_tokens = ?, cache_read_tokens = ?, cache_write_tokens = ?, reasoning_tokens = ?, usage_json = ? WHERE call_id = ?")
|
||||
.bind(as_i64(usage.input_tokens))
|
||||
.bind(as_i64(usage.output_tokens))
|
||||
.bind(as_i64(usage.total_tokens))
|
||||
.bind(as_i64(usage.cache_read_tokens))
|
||||
.bind(as_i64(usage.cache_write_tokens))
|
||||
.bind(as_i64(usage.reasoning_tokens))
|
||||
.bind(usage_json)
|
||||
.bind(call_id)
|
||||
.execute(&self.pool)
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn finish_llm_call(
|
||||
&self,
|
||||
call_id: &str,
|
||||
status: &str,
|
||||
finish_reason: Option<&str>,
|
||||
elapsed_ms: i64,
|
||||
error_kind: Option<&str>,
|
||||
error_message: Option<&str>,
|
||||
) -> Result<()> {
|
||||
let _write = self.writes.lock().await;
|
||||
sqlx::query("UPDATE llm_calls SET status = ?, finish_reason = ?, finished_at_ms = ?, duration_ms = ?, error_kind = ?, error_message = ? WHERE call_id = ? AND status = 'running'")
|
||||
.bind(status)
|
||||
.bind(finish_reason)
|
||||
.bind(now_ms())
|
||||
.bind(elapsed_ms)
|
||||
.bind(error_kind)
|
||||
.bind(error_message)
|
||||
.bind(call_id)
|
||||
.execute(&self.pool)
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn llm_calls(&self, limit: i64) -> Result<Vec<LlmCallSummary>> {
|
||||
let rows = sqlx::query("SELECT * FROM llm_calls ORDER BY created_at_ms DESC LIMIT ?")
|
||||
.bind(limit.clamp(1, 500))
|
||||
.fetch_all(&self.pool)
|
||||
.await?;
|
||||
rows.into_iter().map(summary_from_row).collect()
|
||||
}
|
||||
|
||||
pub async fn llm_call(&self, call_id: &str) -> Result<Option<LlmCallSummary>> {
|
||||
sqlx::query("SELECT * FROM llm_calls WHERE call_id = ?")
|
||||
.bind(call_id)
|
||||
.fetch_optional(&self.pool)
|
||||
.await?
|
||||
.map(summary_from_row)
|
||||
.transpose()
|
||||
}
|
||||
|
||||
pub(crate) async fn latest_llm_call_usage_anchor(
|
||||
&self,
|
||||
conversation_id: &ConversationId,
|
||||
model_hash: &str,
|
||||
) -> Result<Option<LlmCallUsageAnchor>> {
|
||||
let row = sqlx::query(
|
||||
r#"SELECT request_type, usage_json, message_count, tool_count
|
||||
FROM llm_calls
|
||||
WHERE conversation_id = ?
|
||||
AND model_hash = ?
|
||||
AND status = 'completed'
|
||||
AND input_tokens IS NOT NULL
|
||||
AND usage_json IS NOT NULL
|
||||
ORDER BY rowid DESC
|
||||
LIMIT 1"#,
|
||||
)
|
||||
.bind(conversation_id.as_str())
|
||||
.bind(model_hash)
|
||||
.fetch_optional(&self.pool)
|
||||
.await?;
|
||||
row.map(|row| {
|
||||
let message_count =
|
||||
usize::try_from(row.try_get::<i64, _>("message_count")?).unwrap_or(usize::MAX);
|
||||
let tool_count =
|
||||
usize::try_from(row.try_get::<i64, _>("tool_count")?).unwrap_or(usize::MAX);
|
||||
Ok(LlmCallUsageAnchor {
|
||||
request_type: ProviderType::from_str(row.try_get("request_type")?)?,
|
||||
usage: serde_json::from_str(row.try_get("usage_json")?)?,
|
||||
message_count,
|
||||
tool_count,
|
||||
})
|
||||
})
|
||||
.transpose()
|
||||
}
|
||||
|
||||
pub async fn llm_call_request(&self, call_id: &str) -> Result<Option<LlmCallRequest>> {
|
||||
let row = sqlx::query(
|
||||
"SELECT headers_json, body_json, byte_count FROM llm_call_requests WHERE call_id = ?",
|
||||
)
|
||||
.bind(call_id)
|
||||
.fetch_optional(&self.pool)
|
||||
.await?;
|
||||
row.map(|row| {
|
||||
Ok(LlmCallRequest {
|
||||
headers: serde_json::from_str(row.try_get("headers_json")?)?,
|
||||
body: serde_json::from_str(row.try_get("body_json")?)?,
|
||||
byte_count: row.try_get("byte_count")?,
|
||||
})
|
||||
})
|
||||
.transpose()
|
||||
}
|
||||
|
||||
pub async fn llm_call_chunks(&self, call_id: &str) -> Result<Vec<LlmCallResponseChunk>> {
|
||||
let rows = sqlx::query("SELECT seq, received_offset_ms, data, byte_count FROM llm_call_response_chunks WHERE call_id = ? ORDER BY seq")
|
||||
.bind(call_id)
|
||||
.fetch_all(&self.pool)
|
||||
.await?;
|
||||
rows.into_iter()
|
||||
.map(|row| {
|
||||
Ok(LlmCallResponseChunk {
|
||||
seq: row.try_get("seq")?,
|
||||
received_offset_ms: row.try_get("received_offset_ms")?,
|
||||
data: String::from_utf8_lossy(&row.try_get::<Vec<u8>, _>("data")?).into_owned(),
|
||||
byte_count: row.try_get("byte_count")?,
|
||||
})
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
}
|
||||
|
||||
fn as_i64(value: Option<u64>) -> Option<i64> {
|
||||
value.map(|value| value.min(i64::MAX as u64) as i64)
|
||||
}
|
||||
|
||||
fn summary_from_row(row: sqlx::sqlite::SqliteRow) -> Result<LlmCallSummary> {
|
||||
let usage = row.try_get::<Option<String>, _>("usage_json")?;
|
||||
Ok(LlmCallSummary {
|
||||
call_id: row.try_get("call_id")?,
|
||||
run_id: row.try_get("run_id")?,
|
||||
conversation_id: row.try_get("conversation_id")?,
|
||||
provider_call_index: row.try_get("provider_call_index")?,
|
||||
model_hash: row.try_get("model_hash")?,
|
||||
provider_type: row.try_get("provider_type")?,
|
||||
provider_url: row.try_get("provider_url")?,
|
||||
request_type: row.try_get("request_type")?,
|
||||
request_url: row.try_get("request_url")?,
|
||||
model_id: row.try_get("model_id")?,
|
||||
display_name: row.try_get("display_name")?,
|
||||
reasoning_effort: row.try_get("reasoning_effort")?,
|
||||
fast: Some(row.try_get("fast")?),
|
||||
status: row.try_get("status")?,
|
||||
finish_reason: row.try_get("finish_reason")?,
|
||||
created_at_ms: row.try_get("created_at_ms")?,
|
||||
request_started_at_ms: row.try_get("request_started_at_ms")?,
|
||||
response_headers_at_ms: row.try_get("response_headers_at_ms")?,
|
||||
first_event_at_ms: row.try_get("first_event_at_ms")?,
|
||||
first_text_at_ms: row.try_get("first_text_at_ms")?,
|
||||
first_valid_response_at_ms: row.try_get("first_valid_response_at_ms")?,
|
||||
finished_at_ms: row.try_get("finished_at_ms")?,
|
||||
queue_ms: row.try_get("queue_ms")?,
|
||||
ttfb_ms: row.try_get("ttfb_ms")?,
|
||||
ttft_ms: row.try_get("ttft_ms")?,
|
||||
ttfr_ms: row.try_get("ttfr_ms")?,
|
||||
duration_ms: row.try_get("duration_ms")?,
|
||||
input_tokens: row.try_get("input_tokens")?,
|
||||
output_tokens: row.try_get("output_tokens")?,
|
||||
total_tokens: row.try_get("total_tokens")?,
|
||||
cache_read_tokens: row.try_get("cache_read_tokens")?,
|
||||
cache_write_tokens: row.try_get("cache_write_tokens")?,
|
||||
reasoning_tokens: row.try_get("reasoning_tokens")?,
|
||||
usage: usage
|
||||
.map(|value| serde_json::from_str(&value))
|
||||
.transpose()?,
|
||||
message_count: row.try_get("message_count")?,
|
||||
tool_count: row.try_get("tool_count")?,
|
||||
request_bytes: row.try_get("request_bytes")?,
|
||||
response_bytes: row.try_get("response_bytes")?,
|
||||
stream_event_count: row.try_get("stream_event_count")?,
|
||||
http_status: row.try_get("http_status")?,
|
||||
error_kind: row.try_get("error_kind")?,
|
||||
error_message: row.try_get("error_message")?,
|
||||
detailed: row.try_get("detailed")?,
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,123 @@
|
||||
//! Persists canonical Messages and enforces event idempotency.
|
||||
use sqlx::{Row, Sqlite, Transaction};
|
||||
|
||||
use crate::{
|
||||
model::{CanonicalMessage, ConversationId},
|
||||
Error, Result,
|
||||
};
|
||||
|
||||
use super::{now_ms, Store};
|
||||
|
||||
impl Store {
|
||||
pub async fn message(
|
||||
&self,
|
||||
conversation_id: &ConversationId,
|
||||
message_id: &str,
|
||||
) -> Result<Option<CanonicalMessage>> {
|
||||
let payload: Option<String> = sqlx::query_scalar(
|
||||
"SELECT payload_json FROM messages WHERE conversation_id = ? AND message_id = ?",
|
||||
)
|
||||
.bind(conversation_id.as_str())
|
||||
.bind(message_id)
|
||||
.fetch_optional(&self.pool)
|
||||
.await?;
|
||||
payload
|
||||
.map(|payload| serde_json::from_str(&payload).map_err(Into::into))
|
||||
.transpose()
|
||||
}
|
||||
|
||||
pub(crate) async fn put_message_tx(
|
||||
tx: &mut Transaction<'_, Sqlite>,
|
||||
conversation_id: &ConversationId,
|
||||
message: &CanonicalMessage,
|
||||
) -> Result<()> {
|
||||
let payload = serde_json::to_string(message)?;
|
||||
let inserted = sqlx::query(
|
||||
"INSERT OR IGNORE INTO messages
|
||||
(conversation_id, message_id, role, origin, payload_json, runtime_event_id, created_at_ms)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?)",
|
||||
)
|
||||
.bind(conversation_id.as_str())
|
||||
.bind(&message.message_id)
|
||||
.bind(role_name(&message.role))
|
||||
.bind(origin_name(&message.origin))
|
||||
.bind(&payload)
|
||||
.bind(&message.runtime_event_id)
|
||||
.bind(now_ms())
|
||||
.execute(&mut **tx)
|
||||
.await?
|
||||
.rows_affected()
|
||||
== 1;
|
||||
if inserted {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let existing: Option<String> = sqlx::query_scalar(
|
||||
"SELECT payload_json FROM messages
|
||||
WHERE conversation_id = ? AND (message_id = ? OR runtime_event_id = ?)",
|
||||
)
|
||||
.bind(conversation_id.as_str())
|
||||
.bind(&message.message_id)
|
||||
.bind(&message.runtime_event_id)
|
||||
.fetch_optional(&mut **tx)
|
||||
.await?;
|
||||
match existing {
|
||||
Some(existing) if existing == payload => Ok(()),
|
||||
Some(_) => Err(Error::Store(format!(
|
||||
"message id or runtime event reused with different content: {}",
|
||||
message.message_id
|
||||
))),
|
||||
None => Err(Error::Store(format!(
|
||||
"message insert was ignored without an existing object: {}",
|
||||
message.message_id
|
||||
))),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) async fn load_checkpoint_messages_tx(
|
||||
tx: &mut Transaction<'_, Sqlite>,
|
||||
checkpoint_id: i64,
|
||||
) -> Result<Vec<CanonicalMessage>> {
|
||||
let rows = sqlx::query(
|
||||
"WITH RECURSIVE lineage(checkpoint_id, parent_checkpoint_id, depth) AS (
|
||||
SELECT checkpoint_id, parent_checkpoint_id, 0
|
||||
FROM conversation_checkpoints WHERE checkpoint_id = ?
|
||||
UNION ALL
|
||||
SELECT r.checkpoint_id, r.parent_checkpoint_id, lineage.depth + 1
|
||||
FROM conversation_checkpoints r
|
||||
JOIN lineage ON r.checkpoint_id = lineage.parent_checkpoint_id
|
||||
)
|
||||
SELECT m.payload_json
|
||||
FROM lineage
|
||||
JOIN checkpoint_messages rm ON rm.checkpoint_id = lineage.checkpoint_id
|
||||
JOIN messages m
|
||||
ON m.conversation_id = rm.conversation_id AND m.message_id = rm.message_id
|
||||
ORDER BY lineage.depth DESC, rm.ordinal ASC",
|
||||
)
|
||||
.bind(checkpoint_id)
|
||||
.fetch_all(&mut **tx)
|
||||
.await?;
|
||||
rows.into_iter()
|
||||
.map(|row| serde_json::from_str(row.get::<&str, _>(0)).map_err(Into::into))
|
||||
.collect()
|
||||
}
|
||||
}
|
||||
|
||||
fn role_name(role: &crate::model::Role) -> &'static str {
|
||||
match role {
|
||||
crate::model::Role::System => "system",
|
||||
crate::model::Role::User => "user",
|
||||
crate::model::Role::Assistant => "assistant",
|
||||
crate::model::Role::Tool => "tool",
|
||||
}
|
||||
}
|
||||
|
||||
fn origin_name(origin: &crate::model::Origin) -> &'static str {
|
||||
match origin {
|
||||
crate::model::Origin::Prompt => "prompt",
|
||||
crate::model::Origin::User => "user",
|
||||
crate::model::Origin::Runtime => "runtime",
|
||||
crate::model::Origin::Assistant => "assistant",
|
||||
crate::model::Origin::Tool => "tool",
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
//! Exposes the local persistence interface.
|
||||
mod cas;
|
||||
mod checkpoints;
|
||||
mod conversations;
|
||||
mod cursor_traces;
|
||||
mod input_anchors;
|
||||
mod legacy_config;
|
||||
mod llm_calls;
|
||||
mod messages;
|
||||
mod models;
|
||||
mod overview;
|
||||
mod runs;
|
||||
mod settings;
|
||||
mod sqlite;
|
||||
mod storage;
|
||||
mod tool_rounds;
|
||||
mod writer;
|
||||
|
||||
pub use cas::*;
|
||||
pub(crate) use cursor_traces::BufferedCursorTraceChunk;
|
||||
pub(crate) use llm_calls::BufferedLlmChunk;
|
||||
pub use runs::*;
|
||||
pub use settings::*;
|
||||
pub(crate) use sqlite::now_ms;
|
||||
pub use sqlite::Store;
|
||||
pub use storage::*;
|
||||
pub use tool_rounds::*;
|
||||
@@ -0,0 +1,333 @@
|
||||
//! Persists model and provider configuration.
|
||||
use std::{collections::HashSet, str::FromStr};
|
||||
|
||||
use sqlx::{Row, Sqlite, Transaction};
|
||||
|
||||
use crate::{
|
||||
model::{model_hash, normalize_model_input, ModelConfig, ModelConfigInput, ModelType},
|
||||
Error, Result,
|
||||
};
|
||||
|
||||
use super::{now_ms, Store};
|
||||
|
||||
const MODEL_COLUMNS: &str = r#"
|
||||
model_hash, sort_order, display_name, model_type, base_url, use_full_url, api_key, tooltip_data,
|
||||
model_id, reasoning_effort, openai_endpoint, openai_extra_params_enabled,
|
||||
openai_extra_params_json, custom_headers_enabled, custom_headers_json,
|
||||
anthropic_extra_params_enabled, anthropic_extra_params_json, context_window_tokens,
|
||||
max_completion_tokens, anthropic_max_tokens, anthropic_thinking_effort,
|
||||
thinking_budget_tokens, created_at_ms, updated_at_ms
|
||||
"#;
|
||||
|
||||
impl Store {
|
||||
pub async fn models(&self) -> Result<Vec<ModelConfig>> {
|
||||
let query =
|
||||
format!("SELECT {MODEL_COLUMNS} FROM model_configs ORDER BY sort_order, display_name");
|
||||
sqlx::query(&query)
|
||||
.fetch_all(&self.pool)
|
||||
.await?
|
||||
.into_iter()
|
||||
.map(model_from_row)
|
||||
.collect()
|
||||
}
|
||||
|
||||
pub async fn model(&self, hash: &str) -> Result<Option<ModelConfig>> {
|
||||
let query = format!("SELECT {MODEL_COLUMNS} FROM model_configs WHERE model_hash = ?");
|
||||
sqlx::query(&query)
|
||||
.bind(hash)
|
||||
.fetch_optional(&self.pool)
|
||||
.await?
|
||||
.map(model_from_row)
|
||||
.transpose()
|
||||
}
|
||||
|
||||
pub async fn create_model(&self, input: &ModelConfigInput) -> Result<ModelConfig> {
|
||||
let mut models = self.create_models(std::slice::from_ref(input)).await?;
|
||||
Ok(models.remove(0))
|
||||
}
|
||||
|
||||
pub async fn create_models(&self, inputs: &[ModelConfigInput]) -> Result<Vec<ModelConfig>> {
|
||||
if inputs.is_empty() {
|
||||
return Err(Error::Config("at least one model is required".into()));
|
||||
}
|
||||
let mut normalized = Vec::with_capacity(inputs.len());
|
||||
let mut hashes = HashSet::with_capacity(inputs.len());
|
||||
for input in inputs {
|
||||
let input = normalize_model_input(input)?;
|
||||
let hash = model_hash(&input)?;
|
||||
if !hashes.insert(hash.clone()) {
|
||||
return Err(Error::Config("model configurations must be unique".into()));
|
||||
}
|
||||
normalized.push((hash, input));
|
||||
}
|
||||
let now = now_ms();
|
||||
let _write = self.writes.lock().await;
|
||||
let mut transaction = self.pool.begin().await?;
|
||||
for (hash, input) in &normalized {
|
||||
insert_model(&mut transaction, hash, input, now).await?;
|
||||
}
|
||||
transaction.commit().await?;
|
||||
|
||||
let mut saved = Vec::with_capacity(normalized.len());
|
||||
for (hash, _) in normalized {
|
||||
saved.push(self.model(&hash).await?.expect("inserted model must exist"));
|
||||
}
|
||||
Ok(saved)
|
||||
}
|
||||
|
||||
pub(super) async fn create_models_if_missing(
|
||||
&self,
|
||||
inputs: &[ModelConfigInput],
|
||||
) -> Result<usize> {
|
||||
let mut normalized = Vec::with_capacity(inputs.len());
|
||||
let mut hashes = HashSet::with_capacity(inputs.len());
|
||||
for input in inputs {
|
||||
let input = normalize_model_input(input)?;
|
||||
let hash = model_hash(&input)?;
|
||||
if hashes.insert(hash.clone()) {
|
||||
normalized.push((hash, input));
|
||||
}
|
||||
}
|
||||
let now = now_ms();
|
||||
let _write = self.writes.lock().await;
|
||||
let mut transaction = self.pool.begin().await?;
|
||||
let mut inserted = 0;
|
||||
for (hash, input) in &normalized {
|
||||
inserted += usize::from(
|
||||
insert_model_with_conflict(&mut transaction, hash, input, now, true).await?,
|
||||
);
|
||||
}
|
||||
transaction.commit().await?;
|
||||
Ok(inserted)
|
||||
}
|
||||
|
||||
pub async fn update_model(
|
||||
&self,
|
||||
current_hash: &str,
|
||||
input: &ModelConfigInput,
|
||||
) -> Result<ModelConfig> {
|
||||
let current = self
|
||||
.model(current_hash)
|
||||
.await?
|
||||
.ok_or_else(|| Error::RunNotFound(format!("model {current_hash}")))?;
|
||||
let input = normalize_model_input(input)?;
|
||||
let next_hash = model_hash(&input)?;
|
||||
let now = now_ms();
|
||||
let _write = self.writes.lock().await;
|
||||
let mut transaction = self.pool.begin().await?;
|
||||
if next_hash != current.model_hash {
|
||||
sqlx::query("UPDATE llm_calls SET model_hash = NULL WHERE model_hash = ?")
|
||||
.bind(¤t.model_hash)
|
||||
.execute(&mut *transaction)
|
||||
.await?;
|
||||
}
|
||||
let result = sqlx::query(
|
||||
r#"UPDATE model_configs SET
|
||||
model_hash = ?, sort_order = ?, display_name = ?, model_type = ?, base_url = ?,
|
||||
use_full_url = ?, api_key = ?, tooltip_data = ?, model_id = ?, reasoning_effort = ?,
|
||||
openai_endpoint = ?, openai_extra_params_enabled = ?, openai_extra_params_json = ?,
|
||||
custom_headers_enabled = ?, custom_headers_json = ?,
|
||||
anthropic_extra_params_enabled = ?, anthropic_extra_params_json = ?,
|
||||
context_window_tokens = ?, max_completion_tokens = ?, anthropic_max_tokens = ?,
|
||||
anthropic_thinking_effort = ?, thinking_budget_tokens = ?, updated_at_ms = ?
|
||||
WHERE model_hash = ?"#,
|
||||
)
|
||||
.bind(&next_hash)
|
||||
.bind(input.sort_order)
|
||||
.bind(&input.display_name)
|
||||
.bind(input.model_type.as_str())
|
||||
.bind(&input.base_url)
|
||||
.bind(input.use_full_url)
|
||||
.bind(&input.api_key)
|
||||
.bind(&input.tooltip_data)
|
||||
.bind(&input.model_id)
|
||||
.bind(&input.reasoning_effort)
|
||||
.bind(&input.openai_endpoint)
|
||||
.bind(input.openai_extra_params_enabled)
|
||||
.bind(serde_json::to_string(&input.openai_extra_params)?)
|
||||
.bind(input.custom_headers_enabled)
|
||||
.bind(serde_json::to_string(&input.custom_headers)?)
|
||||
.bind(input.anthropic_extra_params_enabled)
|
||||
.bind(serde_json::to_string(&input.anthropic_extra_params)?)
|
||||
.bind(input.context_window_tokens.map(to_i64).transpose()?)
|
||||
.bind(input.max_completion_tokens.map(to_i64).transpose()?)
|
||||
.bind(input.anthropic_max_tokens.map(to_i64).transpose()?)
|
||||
.bind(&input.anthropic_thinking_effort)
|
||||
.bind(input.thinking_budget_tokens.map(to_i64).transpose()?)
|
||||
.bind(now)
|
||||
.bind(current_hash)
|
||||
.execute(&mut *transaction)
|
||||
.await?;
|
||||
if result.rows_affected() != 1 {
|
||||
return Err(Error::RunNotFound(format!("model {current_hash}")));
|
||||
}
|
||||
transaction.commit().await?;
|
||||
Ok(self
|
||||
.model(&next_hash)
|
||||
.await?
|
||||
.expect("updated model must exist"))
|
||||
}
|
||||
|
||||
pub async fn delete_model(&self, hash: &str) -> Result<()> {
|
||||
let _write = self.writes.lock().await;
|
||||
let mut transaction = self.pool.begin().await?;
|
||||
sqlx::query("UPDATE llm_calls SET model_hash = NULL WHERE model_hash = ?")
|
||||
.bind(hash)
|
||||
.execute(&mut *transaction)
|
||||
.await?;
|
||||
let result = sqlx::query("DELETE FROM model_configs WHERE model_hash = ?")
|
||||
.bind(hash)
|
||||
.execute(&mut *transaction)
|
||||
.await?;
|
||||
if result.rows_affected() != 1 {
|
||||
return Err(Error::RunNotFound(format!("model {hash}")));
|
||||
}
|
||||
transaction.commit().await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn reorder_models(&self, model_hashes: &[String]) -> Result<Vec<ModelConfig>> {
|
||||
let current = self.models().await?;
|
||||
let current_hashes = current
|
||||
.iter()
|
||||
.map(|model| model.model_hash.as_str())
|
||||
.collect::<HashSet<_>>();
|
||||
let requested_hashes = model_hashes
|
||||
.iter()
|
||||
.map(String::as_str)
|
||||
.collect::<HashSet<_>>();
|
||||
if model_hashes.len() != current.len()
|
||||
|| requested_hashes.len() != current.len()
|
||||
|| requested_hashes != current_hashes
|
||||
{
|
||||
return Err(Error::Config(
|
||||
"model configuration changed; refresh and try sorting again".into(),
|
||||
));
|
||||
}
|
||||
|
||||
let now = now_ms();
|
||||
let _write = self.writes.lock().await;
|
||||
let mut transaction = self.pool.begin().await?;
|
||||
for (index, hash) in model_hashes.iter().enumerate() {
|
||||
sqlx::query(
|
||||
"UPDATE model_configs SET sort_order = ?, updated_at_ms = ? WHERE model_hash = ?",
|
||||
)
|
||||
.bind(i64::try_from(index + 1).expect("model order fits in i64"))
|
||||
.bind(now)
|
||||
.bind(hash)
|
||||
.execute(&mut *transaction)
|
||||
.await?;
|
||||
}
|
||||
transaction.commit().await?;
|
||||
self.models().await
|
||||
}
|
||||
}
|
||||
|
||||
async fn insert_model(
|
||||
transaction: &mut Transaction<'_, Sqlite>,
|
||||
hash: &str,
|
||||
input: &ModelConfigInput,
|
||||
now: i64,
|
||||
) -> Result<()> {
|
||||
insert_model_with_conflict(transaction, hash, input, now, false).await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn insert_model_with_conflict(
|
||||
transaction: &mut Transaction<'_, Sqlite>,
|
||||
hash: &str,
|
||||
input: &ModelConfigInput,
|
||||
now: i64,
|
||||
ignore_existing: bool,
|
||||
) -> Result<bool> {
|
||||
let mut statement = String::from(
|
||||
r#"INSERT INTO model_configs(
|
||||
model_hash, sort_order, display_name, model_type, base_url, use_full_url, api_key, tooltip_data,
|
||||
model_id, reasoning_effort, openai_endpoint, openai_extra_params_enabled,
|
||||
openai_extra_params_json, custom_headers_enabled, custom_headers_json,
|
||||
anthropic_extra_params_enabled, anthropic_extra_params_json, context_window_tokens,
|
||||
max_completion_tokens, anthropic_max_tokens, anthropic_thinking_effort,
|
||||
thinking_budget_tokens, created_at_ms, updated_at_ms
|
||||
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"#,
|
||||
);
|
||||
if ignore_existing {
|
||||
statement.push_str(" ON CONFLICT(model_hash) DO NOTHING");
|
||||
}
|
||||
let result = sqlx::query(&statement)
|
||||
.bind(hash)
|
||||
.bind(input.sort_order)
|
||||
.bind(&input.display_name)
|
||||
.bind(input.model_type.as_str())
|
||||
.bind(&input.base_url)
|
||||
.bind(input.use_full_url)
|
||||
.bind(&input.api_key)
|
||||
.bind(&input.tooltip_data)
|
||||
.bind(&input.model_id)
|
||||
.bind(&input.reasoning_effort)
|
||||
.bind(&input.openai_endpoint)
|
||||
.bind(input.openai_extra_params_enabled)
|
||||
.bind(serde_json::to_string(&input.openai_extra_params)?)
|
||||
.bind(input.custom_headers_enabled)
|
||||
.bind(serde_json::to_string(&input.custom_headers)?)
|
||||
.bind(input.anthropic_extra_params_enabled)
|
||||
.bind(serde_json::to_string(&input.anthropic_extra_params)?)
|
||||
.bind(input.context_window_tokens.map(to_i64).transpose()?)
|
||||
.bind(input.max_completion_tokens.map(to_i64).transpose()?)
|
||||
.bind(input.anthropic_max_tokens.map(to_i64).transpose()?)
|
||||
.bind(&input.anthropic_thinking_effort)
|
||||
.bind(input.thinking_budget_tokens.map(to_i64).transpose()?)
|
||||
.bind(now)
|
||||
.bind(now)
|
||||
.execute(&mut **transaction)
|
||||
.await?;
|
||||
Ok(result.rows_affected() == 1)
|
||||
}
|
||||
|
||||
fn model_from_row(row: sqlx::sqlite::SqliteRow) -> Result<ModelConfig> {
|
||||
Ok(ModelConfig {
|
||||
model_hash: row.try_get("model_hash")?,
|
||||
sort_order: row.try_get("sort_order")?,
|
||||
display_name: row.try_get("display_name")?,
|
||||
model_type: ModelType::from_str(row.try_get("model_type")?)?,
|
||||
base_url: row.try_get("base_url")?,
|
||||
use_full_url: row.try_get("use_full_url")?,
|
||||
api_key: row.try_get("api_key")?,
|
||||
tooltip_data: row.try_get("tooltip_data")?,
|
||||
model_id: row.try_get("model_id")?,
|
||||
reasoning_effort: row.try_get("reasoning_effort")?,
|
||||
openai_endpoint: row.try_get("openai_endpoint")?,
|
||||
openai_extra_params_enabled: row.try_get("openai_extra_params_enabled")?,
|
||||
openai_extra_params: serde_json::from_str(
|
||||
row.try_get::<String, _>("openai_extra_params_json")?
|
||||
.as_str(),
|
||||
)?,
|
||||
custom_headers_enabled: row.try_get("custom_headers_enabled")?,
|
||||
custom_headers: serde_json::from_str(
|
||||
row.try_get::<String, _>("custom_headers_json")?.as_str(),
|
||||
)?,
|
||||
anthropic_extra_params_enabled: row.try_get("anthropic_extra_params_enabled")?,
|
||||
anthropic_extra_params: serde_json::from_str(
|
||||
row.try_get::<String, _>("anthropic_extra_params_json")?
|
||||
.as_str(),
|
||||
)?,
|
||||
context_window_tokens: optional_u64(&row, "context_window_tokens")?,
|
||||
max_completion_tokens: optional_u64(&row, "max_completion_tokens")?,
|
||||
anthropic_max_tokens: optional_u64(&row, "anthropic_max_tokens")?,
|
||||
anthropic_thinking_effort: row.try_get("anthropic_thinking_effort")?,
|
||||
thinking_budget_tokens: optional_u64(&row, "thinking_budget_tokens")?,
|
||||
created_at_ms: row.try_get("created_at_ms")?,
|
||||
updated_at_ms: row.try_get("updated_at_ms")?,
|
||||
})
|
||||
}
|
||||
|
||||
fn optional_u64(row: &sqlx::sqlite::SqliteRow, column: &str) -> Result<Option<u64>> {
|
||||
row.try_get::<Option<i64>, _>(column)?
|
||||
.map(|value| {
|
||||
u64::try_from(value).map_err(|_| Error::Config(format!("{column} cannot be negative")))
|
||||
})
|
||||
.transpose()
|
||||
}
|
||||
|
||||
fn to_i64(value: u64) -> Result<i64> {
|
||||
i64::try_from(value).map_err(|_| Error::Config("token value is too large".into()))
|
||||
}
|
||||
@@ -0,0 +1,203 @@
|
||||
//! Provides aggregate data for the control API.
|
||||
//! Efficient database aggregates for the desktop overview.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use chrono::Utc;
|
||||
use sqlx::Row;
|
||||
|
||||
use crate::{
|
||||
model::{Overview, OverviewMetrics, TokenUsageBucket, TokenUsageGranularity},
|
||||
Result,
|
||||
};
|
||||
|
||||
use super::Store;
|
||||
|
||||
const OVERVIEW_DAYS: u64 = 365;
|
||||
const MAX_RANGE_BUCKETS: i64 = 60;
|
||||
const MINUTE_MS: i64 = 60_000;
|
||||
const HOUR_MS: i64 = 60 * MINUTE_MS;
|
||||
const DAY_MS: i64 = 24 * HOUR_MS;
|
||||
|
||||
impl Store {
|
||||
pub async fn overview(
|
||||
&self,
|
||||
start_ms: Option<i64>,
|
||||
end_ms: Option<i64>,
|
||||
model_hashes: Option<&str>,
|
||||
) -> Result<Overview> {
|
||||
let call_row = sqlx::query(
|
||||
"SELECT
|
||||
COUNT(*) AS llm_calls,
|
||||
COALESCE(SUM(status = 'completed'), 0) AS successful_calls,
|
||||
COALESCE(SUM(status != 'completed'), 0) AS failed_calls
|
||||
FROM llm_calls
|
||||
WHERE status != 'running'
|
||||
AND (? IS NULL OR created_at_ms >= ?)
|
||||
AND (? IS NULL OR created_at_ms < ?)
|
||||
AND (? IS NULL OR model_hash IN (SELECT value FROM json_each(?)))",
|
||||
)
|
||||
.bind(start_ms)
|
||||
.bind(start_ms)
|
||||
.bind(end_ms)
|
||||
.bind(end_ms)
|
||||
.bind(model_hashes)
|
||||
.bind(model_hashes)
|
||||
.fetch_one(&self.pool)
|
||||
.await?;
|
||||
let token_row = sqlx::query(&format!(
|
||||
"SELECT
|
||||
COALESCE(SUM({fresh_input}), 0) AS input_tokens,
|
||||
COALESCE(SUM(COALESCE(cache_read_tokens, 0)), 0) AS cache_read_tokens,
|
||||
COALESCE(SUM(COALESCE(cache_write_tokens, 0)), 0) AS cache_write_tokens,
|
||||
COALESCE(SUM(COALESCE(output_tokens, 0)), 0) AS output_tokens
|
||||
FROM llm_calls
|
||||
WHERE (? IS NULL OR created_at_ms >= ?)
|
||||
AND (? IS NULL OR created_at_ms < ?)
|
||||
AND (? IS NULL OR model_hash IN (SELECT value FROM json_each(?)))",
|
||||
fresh_input = fresh_input_sql(),
|
||||
))
|
||||
.bind(start_ms)
|
||||
.bind(start_ms)
|
||||
.bind(end_ms)
|
||||
.bind(end_ms)
|
||||
.bind(model_hashes)
|
||||
.bind(model_hashes)
|
||||
.fetch_one(&self.pool)
|
||||
.await?;
|
||||
|
||||
let input_tokens = non_negative(token_row.try_get("input_tokens")?);
|
||||
let cache_read_tokens = non_negative(token_row.try_get("cache_read_tokens")?);
|
||||
let cache_write_tokens = non_negative(token_row.try_get("cache_write_tokens")?);
|
||||
let output_tokens = non_negative(token_row.try_get("output_tokens")?);
|
||||
let prompt_tokens = saturating_sum(&[input_tokens, cache_read_tokens, cache_write_tokens]);
|
||||
let metrics = OverviewMetrics {
|
||||
llm_calls: call_row.try_get("llm_calls")?,
|
||||
successful_calls: call_row.try_get("successful_calls")?,
|
||||
failed_calls: call_row.try_get("failed_calls")?,
|
||||
token_usage: prompt_tokens.saturating_add(output_tokens),
|
||||
prompt_tokens,
|
||||
input_tokens,
|
||||
cache_read_tokens,
|
||||
cache_write_tokens,
|
||||
output_tokens,
|
||||
};
|
||||
|
||||
let (token_usage_granularity, bucket_ms, series_start_ms, bucket_count) =
|
||||
token_usage_buckets(start_ms, end_ms);
|
||||
let rows = sqlx::query(&format!(
|
||||
"SELECT
|
||||
(created_at_ms / {bucket_ms}) * {bucket_ms} AS bucket_start_ms,
|
||||
COALESCE(SUM({fresh_input}), 0) AS input_tokens,
|
||||
COALESCE(SUM(COALESCE(cache_read_tokens, 0)), 0) AS cache_read_tokens,
|
||||
COALESCE(SUM(COALESCE(cache_write_tokens, 0)), 0) AS cache_write_tokens,
|
||||
COALESCE(SUM(COALESCE(output_tokens, 0)), 0) AS output_tokens
|
||||
FROM llm_calls
|
||||
WHERE created_at_ms >= ?
|
||||
AND (? IS NULL OR created_at_ms < ?)
|
||||
AND (? IS NULL OR model_hash IN (SELECT value FROM json_each(?)))
|
||||
GROUP BY bucket_start_ms
|
||||
ORDER BY bucket_start_ms",
|
||||
fresh_input = fresh_input_sql(),
|
||||
))
|
||||
.bind(start_ms.unwrap_or(series_start_ms).max(series_start_ms))
|
||||
.bind(end_ms)
|
||||
.bind(end_ms)
|
||||
.bind(model_hashes)
|
||||
.bind(model_hashes)
|
||||
.fetch_all(&self.pool)
|
||||
.await?;
|
||||
let mut recorded = rows
|
||||
.into_iter()
|
||||
.map(|row| {
|
||||
let bucket_start_ms: i64 = row.try_get("bucket_start_ms")?;
|
||||
Ok((
|
||||
bucket_start_ms,
|
||||
TokenUsageBucket {
|
||||
bucket_start_ms,
|
||||
input_tokens: non_negative(row.try_get("input_tokens")?),
|
||||
cache_read_tokens: non_negative(row.try_get("cache_read_tokens")?),
|
||||
cache_write_tokens: non_negative(row.try_get("cache_write_tokens")?),
|
||||
output_tokens: non_negative(row.try_get("output_tokens")?),
|
||||
},
|
||||
))
|
||||
})
|
||||
.collect::<Result<BTreeMap<_, _>>>()?;
|
||||
let token_usage_series = (0..bucket_count)
|
||||
.map(|offset| series_start_ms.saturating_add(offset.saturating_mul(bucket_ms)))
|
||||
.map(|bucket_start_ms| {
|
||||
recorded
|
||||
.remove(&bucket_start_ms)
|
||||
.unwrap_or(TokenUsageBucket {
|
||||
bucket_start_ms,
|
||||
..TokenUsageBucket::default()
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
|
||||
Ok(Overview {
|
||||
metrics,
|
||||
token_usage_granularity,
|
||||
token_usage_series,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
fn token_usage_buckets(
|
||||
start_ms: Option<i64>,
|
||||
end_ms: Option<i64>,
|
||||
) -> (TokenUsageGranularity, i64, i64, i64) {
|
||||
if let (Some(start_ms), Some(end_ms)) = (start_ms, end_ms) {
|
||||
let duration_ms = end_ms.saturating_sub(start_ms).max(1);
|
||||
let (granularity, bucket_ms) = if duration_ms <= HOUR_MS {
|
||||
(TokenUsageGranularity::Minute, MINUTE_MS)
|
||||
} else if duration_ms <= MAX_RANGE_BUCKETS * HOUR_MS {
|
||||
(TokenUsageGranularity::Hour, HOUR_MS)
|
||||
} else {
|
||||
(TokenUsageGranularity::Day, DAY_MS)
|
||||
};
|
||||
let last_bucket_ms = end_ms.saturating_sub(1).div_euclid(bucket_ms) * bucket_ms;
|
||||
let first_bucket_ms = start_ms.div_euclid(bucket_ms) * bucket_ms;
|
||||
let bucket_count = ((last_bucket_ms - first_bucket_ms).div_euclid(bucket_ms) + 1)
|
||||
.clamp(1, MAX_RANGE_BUCKETS);
|
||||
let series_start_ms =
|
||||
last_bucket_ms.saturating_sub((bucket_count - 1).saturating_mul(bucket_ms));
|
||||
return (granularity, bucket_ms, series_start_ms, bucket_count);
|
||||
}
|
||||
|
||||
let today_start_ms = Utc::now()
|
||||
.date_naive()
|
||||
.and_hms_opt(0, 0, 0)
|
||||
.map(|value| value.and_utc().timestamp_millis())
|
||||
.unwrap_or(0);
|
||||
let series_start_ms = today_start_ms.saturating_sub(
|
||||
i64::try_from(OVERVIEW_DAYS - 1)
|
||||
.unwrap_or(0)
|
||||
.saturating_mul(DAY_MS),
|
||||
);
|
||||
(
|
||||
TokenUsageGranularity::Day,
|
||||
DAY_MS,
|
||||
series_start_ms,
|
||||
i64::try_from(OVERVIEW_DAYS).unwrap_or(0),
|
||||
)
|
||||
}
|
||||
|
||||
fn fresh_input_sql() -> &'static str {
|
||||
"CASE
|
||||
WHEN request_type = 'anthropic' THEN MAX(0, COALESCE(input_tokens, 0))
|
||||
ELSE MAX(0, COALESCE(input_tokens, 0)
|
||||
- COALESCE(cache_read_tokens, 0)
|
||||
- COALESCE(cache_write_tokens, 0))
|
||||
END"
|
||||
}
|
||||
|
||||
fn non_negative(value: i64) -> i64 {
|
||||
value.max(0)
|
||||
}
|
||||
|
||||
fn saturating_sum(values: &[i64]) -> i64 {
|
||||
values
|
||||
.iter()
|
||||
.fold(0_i64, |total, value| total.saturating_add(*value))
|
||||
}
|
||||
@@ -0,0 +1,276 @@
|
||||
//! Persists Run ownership, status, and provider call progress.
|
||||
use sqlx::Row;
|
||||
|
||||
use crate::{
|
||||
model::{CheckpointId, ConversationId, PreparedRun, RunId, RunKind, Usage},
|
||||
Error, Result,
|
||||
};
|
||||
|
||||
use super::{now_ms, Store};
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum RunStatus {
|
||||
Running,
|
||||
Completed,
|
||||
Cancelled,
|
||||
Failed,
|
||||
}
|
||||
|
||||
impl RunStatus {
|
||||
fn as_str(self) -> &'static str {
|
||||
match self {
|
||||
Self::Running => "running",
|
||||
Self::Completed => "completed",
|
||||
Self::Cancelled => "cancelled",
|
||||
Self::Failed => "failed",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct ClaimedRun {
|
||||
pub run_id: RunId,
|
||||
pub conversation_id: ConversationId,
|
||||
pub head_checkpoint_id: CheckpointId,
|
||||
pub replaced_run_id: Option<RunId>,
|
||||
}
|
||||
|
||||
impl Store {
|
||||
pub async fn claim_run(&self, prepared: &PreparedRun) -> Result<ClaimedRun> {
|
||||
let _write = self.writes.lock().await;
|
||||
let mut tx = self.pool.begin_with("BEGIN IMMEDIATE").await?;
|
||||
let now = now_ms();
|
||||
Self::ensure_conversation_tx(&mut tx, &prepared.conversation_id).await?;
|
||||
let belongs: bool = sqlx::query_scalar(
|
||||
"SELECT EXISTS(
|
||||
SELECT 1 FROM conversation_checkpoints
|
||||
WHERE checkpoint_id = ? AND conversation_id = ?
|
||||
)",
|
||||
)
|
||||
.bind(prepared.base_checkpoint_id.0)
|
||||
.bind(prepared.conversation_id.as_str())
|
||||
.fetch_one(&mut *tx)
|
||||
.await?;
|
||||
if !belongs {
|
||||
return Err(Error::Store(format!(
|
||||
"base checkpoint {} does not belong to conversation {}",
|
||||
prepared.base_checkpoint_id, prepared.conversation_id
|
||||
)));
|
||||
}
|
||||
|
||||
let replaced: Option<String> =
|
||||
sqlx::query_scalar("SELECT active_run_id FROM conversations WHERE conversation_id = ?")
|
||||
.bind(prepared.conversation_id.as_str())
|
||||
.fetch_one(&mut *tx)
|
||||
.await?;
|
||||
if let Some(replaced) = replaced.as_deref() {
|
||||
if replaced != prepared.run_id.as_str() {
|
||||
sqlx::query(
|
||||
"UPDATE runs SET status = 'cancelled', updated_at_ms = ?
|
||||
WHERE run_id = ? AND status = 'running'",
|
||||
)
|
||||
.bind(now)
|
||||
.bind(replaced)
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
sqlx::query(
|
||||
"UPDATE llm_calls SET status = 'cancelled', finished_at_ms = ?,
|
||||
duration_ms = MAX(0, ? - created_at_ms)
|
||||
WHERE run_id = ? AND status = 'running'",
|
||||
)
|
||||
.bind(now)
|
||||
.bind(now)
|
||||
.bind(replaced)
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
}
|
||||
}
|
||||
|
||||
let (parent_run_id, parent_tool_call_id, run_kind, subagent_kind) =
|
||||
run_kind_columns(&prepared.kind);
|
||||
sqlx::query(
|
||||
"INSERT INTO runs
|
||||
(run_id, cursor_request_id, conversation_id, base_checkpoint_id, head_checkpoint_id,
|
||||
parent_run_id, parent_tool_call_id, run_kind, subagent_kind,
|
||||
status, created_at_ms, updated_at_ms)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 'running', ?, ?)",
|
||||
)
|
||||
.bind(prepared.run_id.as_str())
|
||||
.bind(prepared.cursor_request_id.as_deref())
|
||||
.bind(prepared.conversation_id.as_str())
|
||||
.bind(prepared.base_checkpoint_id.0)
|
||||
.bind(prepared.base_checkpoint_id.0)
|
||||
.bind(parent_run_id)
|
||||
.bind(parent_tool_call_id)
|
||||
.bind(run_kind)
|
||||
.bind(subagent_kind)
|
||||
.bind(now)
|
||||
.bind(now)
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
|
||||
sqlx::query(
|
||||
"UPDATE conversations
|
||||
SET current_checkpoint_id = ?, active_run_id = ?, updated_at_ms = ?
|
||||
WHERE conversation_id = ?",
|
||||
)
|
||||
.bind(prepared.base_checkpoint_id.0)
|
||||
.bind(prepared.run_id.as_str())
|
||||
.bind(now)
|
||||
.bind(prepared.conversation_id.as_str())
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
tx.commit().await?;
|
||||
Ok(ClaimedRun {
|
||||
run_id: prepared.run_id.clone(),
|
||||
conversation_id: prepared.conversation_id.clone(),
|
||||
head_checkpoint_id: prepared.base_checkpoint_id,
|
||||
replaced_run_id: replaced
|
||||
.filter(|run| run != prepared.run_id.as_str())
|
||||
.map(RunId),
|
||||
})
|
||||
}
|
||||
|
||||
pub async fn active_run_for_cursor_request(
|
||||
&self,
|
||||
cursor_request_id: &str,
|
||||
) -> Result<Option<RunId>> {
|
||||
let run_id: Option<String> = sqlx::query_scalar(
|
||||
"SELECT run_id FROM runs
|
||||
WHERE cursor_request_id = ? AND status = 'running'
|
||||
ORDER BY created_at_ms DESC
|
||||
LIMIT 1",
|
||||
)
|
||||
.bind(cursor_request_id)
|
||||
.fetch_optional(&self.pool)
|
||||
.await?;
|
||||
Ok(run_id.map(RunId))
|
||||
}
|
||||
|
||||
pub async fn begin_provider_call(&self, run_id: &RunId) -> Result<u64> {
|
||||
let _write = self.writes.lock().await;
|
||||
let index: Option<i64> = sqlx::query_scalar(
|
||||
"UPDATE runs SET provider_call_index = provider_call_index + 1, updated_at_ms = ?
|
||||
WHERE run_id = ? AND status = 'running'
|
||||
RETURNING provider_call_index",
|
||||
)
|
||||
.bind(now_ms())
|
||||
.bind(run_id.as_str())
|
||||
.fetch_optional(&self.pool)
|
||||
.await?;
|
||||
index
|
||||
.map(|index| index as u64)
|
||||
.ok_or_else(|| Error::Store(format!("run is not active: {run_id}")))
|
||||
}
|
||||
|
||||
pub async fn finish_run(
|
||||
&self,
|
||||
run_id: &RunId,
|
||||
status: RunStatus,
|
||||
usage: Option<Usage>,
|
||||
failure: Option<(&str, &str)>,
|
||||
) -> Result<bool> {
|
||||
let usage_json = serde_json::to_string(&usage)?;
|
||||
let _write = self.writes.lock().await;
|
||||
let mut tx = self.pool.begin_with("BEGIN IMMEDIATE").await?;
|
||||
let row = sqlx::query(
|
||||
"SELECT conversation_id, status, failure_category, failure_summary
|
||||
FROM runs WHERE run_id = ?",
|
||||
)
|
||||
.bind(run_id.as_str())
|
||||
.fetch_optional(&mut *tx)
|
||||
.await?;
|
||||
let Some(row) = row else {
|
||||
return Err(Error::RunNotFound(run_id.to_string()));
|
||||
};
|
||||
let conversation_id: String = row.get("conversation_id");
|
||||
let current_status: String = row.get("status");
|
||||
let (requested_category, requested_summary) = failure.unzip();
|
||||
let terminal_status = if current_status == "running" {
|
||||
status.as_str()
|
||||
} else {
|
||||
current_status.as_str()
|
||||
};
|
||||
let stored_category: Option<String> = row.get("failure_category");
|
||||
let stored_summary: Option<String> = row.get("failure_summary");
|
||||
let (category, summary) = if current_status == "running" {
|
||||
(requested_category, requested_summary)
|
||||
} else {
|
||||
(stored_category.as_deref(), stored_summary.as_deref())
|
||||
};
|
||||
let now = now_ms();
|
||||
sqlx::query(
|
||||
"UPDATE runs SET status = ?, turn_usage_json = ?, failure_category = ?,
|
||||
failure_summary = ?, updated_at_ms = ?
|
||||
WHERE run_id = ? AND status = 'running'",
|
||||
)
|
||||
.bind(status.as_str())
|
||||
.bind(usage_json)
|
||||
.bind(category)
|
||||
.bind(summary)
|
||||
.bind(now)
|
||||
.bind(run_id.as_str())
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
let (call_status, call_error_kind, call_error_message) = match terminal_status {
|
||||
"cancelled" => ("cancelled", None, None),
|
||||
"failed" => ("error", category, summary),
|
||||
"completed" => (
|
||||
"error",
|
||||
Some("internal"),
|
||||
Some("Run completed before LLM call reached a terminal state"),
|
||||
),
|
||||
value => {
|
||||
return Err(Error::Store(format!(
|
||||
"cannot finish LLM calls for non-terminal Run status: {value}"
|
||||
)))
|
||||
}
|
||||
};
|
||||
sqlx::query(
|
||||
"UPDATE llm_calls SET status = ?, finished_at_ms = ?,
|
||||
duration_ms = MAX(0, ? - created_at_ms), error_kind = ?, error_message = ?
|
||||
WHERE run_id = ? AND status = 'running'",
|
||||
)
|
||||
.bind(call_status)
|
||||
.bind(now)
|
||||
.bind(now)
|
||||
.bind(call_error_kind)
|
||||
.bind(call_error_message)
|
||||
.bind(run_id.as_str())
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
let released = sqlx::query(
|
||||
"UPDATE conversations SET active_run_id = NULL, updated_at_ms = ?
|
||||
WHERE conversation_id = ? AND active_run_id = ?",
|
||||
)
|
||||
.bind(now)
|
||||
.bind(conversation_id)
|
||||
.bind(run_id.as_str())
|
||||
.execute(&mut *tx)
|
||||
.await?
|
||||
.rows_affected()
|
||||
== 1;
|
||||
tx.commit().await?;
|
||||
Ok(released)
|
||||
}
|
||||
}
|
||||
|
||||
fn run_kind_columns(kind: &RunKind) -> (Option<&str>, Option<&str>, &'static str, Option<String>) {
|
||||
match kind {
|
||||
RunKind::Root => (None, None, "root", None),
|
||||
RunKind::Subagent {
|
||||
parent_run_id,
|
||||
parent_tool_call_id,
|
||||
kind,
|
||||
..
|
||||
} => (
|
||||
Some(parent_run_id.as_str()),
|
||||
Some(parent_tool_call_id.as_str()),
|
||||
"subagent",
|
||||
Some(match kind {
|
||||
crate::model::SubagentKind::GeneralPurpose => "generalPurpose".into(),
|
||||
crate::model::SubagentKind::Named(name) => name.clone(),
|
||||
}),
|
||||
),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,302 @@
|
||||
//! Persists application settings.
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::Result;
|
||||
|
||||
use super::{now_ms, Store};
|
||||
|
||||
const PORT_SETTINGS_KEY: &str = "network_ports";
|
||||
const PROXY_SETTINGS_KEY: &str = "outbound_proxy";
|
||||
const TAB_SETTINGS_KEY: &str = "cursor_tab";
|
||||
const INSTALLATION_ID_KEY: &str = "installation_id";
|
||||
const DESKTOP_SETTINGS_KEY: &str = "desktop_lifecycle";
|
||||
|
||||
pub const PUBLIC_TAB_SERVICE_URL: &str = "https://tab.leokun.cn";
|
||||
|
||||
#[derive(Clone, Copy, Debug, Default, Deserialize, PartialEq, Eq, Serialize)]
|
||||
pub struct PortSettings {
|
||||
pub proxy_port: u16,
|
||||
pub service_port: u16,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Default, Deserialize, PartialEq, Eq, Serialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum ProxyMode {
|
||||
#[default]
|
||||
System,
|
||||
Custom,
|
||||
}
|
||||
|
||||
impl ProxyMode {
|
||||
pub fn is_custom(self) -> bool {
|
||||
self == Self::Custom
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Default, Deserialize, PartialEq, Eq, Serialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum TabMode {
|
||||
#[default]
|
||||
Public,
|
||||
Direct,
|
||||
Custom,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default, Deserialize, PartialEq, Eq, Serialize)]
|
||||
pub struct TabSettings {
|
||||
pub mode: TabMode,
|
||||
pub address: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Deserialize, PartialEq, Eq, Serialize)]
|
||||
pub struct DesktopSettings {
|
||||
#[serde(default)]
|
||||
pub silent_start: bool,
|
||||
#[serde(default = "default_true")]
|
||||
pub show_dock_icon: bool,
|
||||
}
|
||||
|
||||
impl Default for DesktopSettings {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
silent_start: false,
|
||||
show_dock_icon: true,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn default_true() -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
impl TabSettings {
|
||||
pub fn service_url(&self) -> Option<&str> {
|
||||
match self.mode {
|
||||
TabMode::Public => Some(PUBLIC_TAB_SERVICE_URL),
|
||||
TabMode::Direct => None,
|
||||
TabMode::Custom => Some(&self.address),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default, Deserialize, PartialEq, Eq, Serialize)]
|
||||
pub struct ProxySettingsInput {
|
||||
pub mode: ProxyMode,
|
||||
pub address: String,
|
||||
pub auth_enabled: bool,
|
||||
pub username: String,
|
||||
pub password: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize)]
|
||||
pub struct ProxySettings {
|
||||
pub mode: ProxyMode,
|
||||
pub address: String,
|
||||
pub auth_enabled: bool,
|
||||
pub username: String,
|
||||
pub has_password: bool,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default, Deserialize, Serialize)]
|
||||
pub(crate) struct ProxySettingsSecret {
|
||||
pub mode: ProxyMode,
|
||||
pub address: String,
|
||||
pub auth_enabled: bool,
|
||||
pub username: String,
|
||||
pub password: String,
|
||||
}
|
||||
|
||||
impl Store {
|
||||
pub(crate) async fn installation_id(&self) -> Result<String> {
|
||||
let generated = uuid::Uuid::new_v4().to_string();
|
||||
let _write = self.writes.lock().await;
|
||||
sqlx::query(
|
||||
"INSERT INTO service_settings(setting_key, value_json, updated_at_ms) VALUES (?, ?, ?) ON CONFLICT(setting_key) DO NOTHING",
|
||||
)
|
||||
.bind(INSTALLATION_ID_KEY)
|
||||
.bind(serde_json::to_string(&generated)?)
|
||||
.bind(now_ms())
|
||||
.execute(&self.pool)
|
||||
.await?;
|
||||
let value = sqlx::query_scalar::<_, String>(
|
||||
"SELECT value_json FROM service_settings WHERE setting_key = ?",
|
||||
)
|
||||
.bind(INSTALLATION_ID_KEY)
|
||||
.fetch_one(&self.pool)
|
||||
.await?;
|
||||
let installation_id = serde_json::from_str::<String>(&value)?;
|
||||
uuid::Uuid::parse_str(&installation_id).map_err(|error| {
|
||||
crate::Error::Store(format!("invalid persisted installation ID: {error}"))
|
||||
})?;
|
||||
Ok(installation_id)
|
||||
}
|
||||
|
||||
pub(crate) async fn proxy_settings_secret(&self) -> Result<ProxySettingsSecret> {
|
||||
let value = sqlx::query_scalar::<_, String>(
|
||||
"SELECT value_json FROM service_settings WHERE setting_key = ?",
|
||||
)
|
||||
.bind(PROXY_SETTINGS_KEY)
|
||||
.fetch_optional(&self.pool)
|
||||
.await?;
|
||||
value
|
||||
.map(|value| serde_json::from_str(&value).map_err(Into::into))
|
||||
.unwrap_or_else(|| Ok(ProxySettingsSecret::default()))
|
||||
}
|
||||
|
||||
pub async fn proxy_settings(&self) -> Result<ProxySettings> {
|
||||
let settings = self.proxy_settings_secret().await?;
|
||||
Ok(ProxySettings {
|
||||
mode: settings.mode,
|
||||
address: settings.address,
|
||||
auth_enabled: settings.auth_enabled,
|
||||
username: settings.username,
|
||||
has_password: !settings.password.is_empty(),
|
||||
})
|
||||
}
|
||||
|
||||
pub async fn set_proxy_settings(&self, input: ProxySettingsInput) -> Result<ProxySettings> {
|
||||
let existing = self.proxy_settings_secret().await?;
|
||||
let address = input.address.trim().to_owned();
|
||||
if input.mode.is_custom() {
|
||||
let parsed = url::Url::parse(&address)
|
||||
.map_err(|error| crate::Error::Config(format!("invalid proxy address: {error}")))?;
|
||||
if !matches!(parsed.scheme(), "http" | "https" | "socks5" | "socks5h") {
|
||||
return Err(crate::Error::Config(
|
||||
"proxy address must use http, https, socks5, or socks5h".into(),
|
||||
));
|
||||
}
|
||||
reqwest::Proxy::all(&address)?;
|
||||
}
|
||||
let password = if input.auth_enabled {
|
||||
input
|
||||
.password
|
||||
.filter(|password| !password.is_empty())
|
||||
.unwrap_or(existing.password)
|
||||
} else {
|
||||
String::new()
|
||||
};
|
||||
let settings = ProxySettingsSecret {
|
||||
mode: input.mode,
|
||||
address,
|
||||
auth_enabled: input.auth_enabled,
|
||||
username: input.username.trim().to_owned(),
|
||||
password,
|
||||
};
|
||||
let value_json = serde_json::to_string(&settings)?;
|
||||
let _write = self.writes.lock().await;
|
||||
sqlx::query("INSERT INTO service_settings(setting_key, value_json, updated_at_ms) VALUES (?, ?, ?) ON CONFLICT(setting_key) DO UPDATE SET value_json = excluded.value_json, updated_at_ms = excluded.updated_at_ms")
|
||||
.bind(PROXY_SETTINGS_KEY)
|
||||
.bind(value_json)
|
||||
.bind(now_ms())
|
||||
.execute(&self.pool)
|
||||
.await?;
|
||||
self.proxy_settings().await
|
||||
}
|
||||
|
||||
pub async fn tab_settings(&self) -> Result<TabSettings> {
|
||||
let value = sqlx::query_scalar::<_, String>(
|
||||
"SELECT value_json FROM service_settings WHERE setting_key = ?",
|
||||
)
|
||||
.bind(TAB_SETTINGS_KEY)
|
||||
.fetch_optional(&self.pool)
|
||||
.await?;
|
||||
value
|
||||
.map(|value| serde_json::from_str(&value).map_err(Into::into))
|
||||
.unwrap_or_else(|| Ok(TabSettings::default()))
|
||||
}
|
||||
|
||||
pub async fn set_tab_settings(&self, mut settings: TabSettings) -> Result<TabSettings> {
|
||||
settings.address = settings.address.trim().trim_end_matches('/').to_owned();
|
||||
if settings.mode == TabMode::Custom {
|
||||
let parsed = url::Url::parse(&settings.address).map_err(|error| {
|
||||
crate::Error::Config(format!("invalid TAB service address: {error}"))
|
||||
})?;
|
||||
if !matches!(parsed.scheme(), "http" | "https") {
|
||||
return Err(crate::Error::Config(
|
||||
"TAB service address must use http or https".into(),
|
||||
));
|
||||
}
|
||||
if parsed.host_str().is_none()
|
||||
|| parsed.query().is_some()
|
||||
|| parsed.fragment().is_some()
|
||||
{
|
||||
return Err(crate::Error::Config(
|
||||
"TAB service address must be a base URL without a query or fragment".into(),
|
||||
));
|
||||
}
|
||||
}
|
||||
let value_json = serde_json::to_string(&settings)?;
|
||||
let _write = self.writes.lock().await;
|
||||
sqlx::query("INSERT INTO service_settings(setting_key, value_json, updated_at_ms) VALUES (?, ?, ?) ON CONFLICT(setting_key) DO UPDATE SET value_json = excluded.value_json, updated_at_ms = excluded.updated_at_ms")
|
||||
.bind(TAB_SETTINGS_KEY)
|
||||
.bind(value_json)
|
||||
.bind(now_ms())
|
||||
.execute(&self.pool)
|
||||
.await?;
|
||||
Ok(settings)
|
||||
}
|
||||
|
||||
pub async fn port_settings(&self) -> Result<PortSettings> {
|
||||
let value = sqlx::query_scalar::<_, String>(
|
||||
"SELECT value_json FROM service_settings WHERE setting_key = ?",
|
||||
)
|
||||
.bind(PORT_SETTINGS_KEY)
|
||||
.fetch_optional(&self.pool)
|
||||
.await?;
|
||||
value
|
||||
.map(|value| serde_json::from_str(&value).map_err(Into::into))
|
||||
.unwrap_or_else(|| Ok(PortSettings::default()))
|
||||
}
|
||||
|
||||
pub async fn set_port_settings(&self, settings: PortSettings) -> Result<()> {
|
||||
let value_json = serde_json::to_string(&settings)?;
|
||||
let _write = self.writes.lock().await;
|
||||
sqlx::query(
|
||||
"INSERT INTO service_settings(setting_key, value_json, updated_at_ms) VALUES (?, ?, ?) ON CONFLICT(setting_key) DO UPDATE SET value_json = excluded.value_json, updated_at_ms = excluded.updated_at_ms",
|
||||
)
|
||||
.bind(PORT_SETTINGS_KEY)
|
||||
.bind(value_json)
|
||||
.bind(now_ms())
|
||||
.execute(&self.pool)
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn set_service_port(&self, port: u16) -> Result<()> {
|
||||
let mut settings = self.port_settings().await?;
|
||||
settings.service_port = port;
|
||||
self.set_port_settings(settings).await
|
||||
}
|
||||
|
||||
pub async fn set_proxy_port(&self, port: u16) -> Result<()> {
|
||||
let mut settings = self.port_settings().await?;
|
||||
settings.proxy_port = port;
|
||||
self.set_port_settings(settings).await
|
||||
}
|
||||
|
||||
pub async fn desktop_settings(&self) -> Result<DesktopSettings> {
|
||||
let value = sqlx::query_scalar::<_, String>(
|
||||
"SELECT value_json FROM service_settings WHERE setting_key = ?",
|
||||
)
|
||||
.bind(DESKTOP_SETTINGS_KEY)
|
||||
.fetch_optional(&self.pool)
|
||||
.await?;
|
||||
value
|
||||
.map(|value| serde_json::from_str(&value).map_err(Into::into))
|
||||
.unwrap_or_else(|| Ok(DesktopSettings::default()))
|
||||
}
|
||||
|
||||
pub async fn set_desktop_settings(&self, settings: DesktopSettings) -> Result<()> {
|
||||
let value_json = serde_json::to_string(&settings)?;
|
||||
let _write = self.writes.lock().await;
|
||||
sqlx::query(
|
||||
"INSERT INTO service_settings(setting_key, value_json, updated_at_ms) VALUES (?, ?, ?) ON CONFLICT(setting_key) DO UPDATE SET value_json = excluded.value_json, updated_at_ms = excluded.updated_at_ms",
|
||||
)
|
||||
.bind(DESKTOP_SETTINGS_KEY)
|
||||
.bind(value_json)
|
||||
.bind(now_ms())
|
||||
.execute(&self.pool)
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
//! Initializes and configures SQLite storage.
|
||||
use std::{str::FromStr, time::Duration};
|
||||
|
||||
use sqlx::{
|
||||
sqlite::{SqliteConnectOptions, SqliteJournalMode, SqlitePoolOptions, SqliteSynchronous},
|
||||
SqlitePool,
|
||||
};
|
||||
|
||||
use crate::Result;
|
||||
|
||||
use super::writer::WriteCoordinator;
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct Store {
|
||||
pub(crate) pool: SqlitePool,
|
||||
pub(crate) writes: WriteCoordinator,
|
||||
}
|
||||
|
||||
impl Store {
|
||||
pub async fn connect(database_url: &str) -> Result<Self> {
|
||||
let options = SqliteConnectOptions::from_str(database_url)?
|
||||
.create_if_missing(true)
|
||||
.foreign_keys(true)
|
||||
.journal_mode(SqliteJournalMode::Wal)
|
||||
.synchronous(SqliteSynchronous::Full)
|
||||
.busy_timeout(Duration::from_secs(5));
|
||||
let pool = SqlitePoolOptions::new()
|
||||
.max_connections(8)
|
||||
.connect_with(options)
|
||||
.await?;
|
||||
sqlx::migrate!("./migrations").run(&pool).await?;
|
||||
Ok(Self {
|
||||
pool,
|
||||
writes: WriteCoordinator::default(),
|
||||
})
|
||||
}
|
||||
|
||||
pub fn pool(&self) -> &SqlitePool {
|
||||
&self.pool
|
||||
}
|
||||
}
|
||||
|
||||
pub fn now_ms() -> i64 {
|
||||
std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.unwrap_or_default()
|
||||
.as_millis() as i64
|
||||
}
|
||||
@@ -0,0 +1,139 @@
|
||||
//! Persists content-addressed blobs and their edges.
|
||||
//! Storage accounting and cleanup for disposable observability data.
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::Result;
|
||||
|
||||
use super::Store;
|
||||
|
||||
#[derive(Clone, Copy, Debug, Default, Serialize)]
|
||||
pub struct StatisticsStorage {
|
||||
pub bytes: i64,
|
||||
pub call_count: i64,
|
||||
pub trace_count: i64,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Default, Deserialize, Eq, PartialEq)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum StatisticsStorageScope {
|
||||
#[default]
|
||||
Details,
|
||||
All,
|
||||
}
|
||||
|
||||
impl Store {
|
||||
pub async fn statistics_storage(&self) -> Result<StatisticsStorage> {
|
||||
let (bytes, call_count, trace_count) = sqlx::query_as::<_, (i64, i64, i64)>(
|
||||
r#"
|
||||
SELECT
|
||||
COALESCE((
|
||||
SELECT SUM(
|
||||
LENGTH(call_id) + LENGTH(run_id) + LENGTH(conversation_id) +
|
||||
LENGTH(provider_type) + LENGTH(provider_url) + LENGTH(request_type) +
|
||||
LENGTH(request_url) + LENGTH(model_id) + LENGTH(display_name) +
|
||||
LENGTH(status) + COALESCE(LENGTH(finish_reason), 0) +
|
||||
COALESCE(LENGTH(usage_json), 0) + COALESCE(LENGTH(error_kind), 0) +
|
||||
COALESCE(LENGTH(error_message), 0) + 256
|
||||
) FROM llm_calls
|
||||
), 0) +
|
||||
COALESCE((SELECT SUM(LENGTH(headers_json) + LENGTH(body_json) + 24) FROM llm_call_requests), 0) +
|
||||
COALESCE((SELECT SUM(LENGTH(data) + 24) FROM llm_call_response_chunks), 0) +
|
||||
COALESCE((
|
||||
SELECT SUM(
|
||||
LENGTH(request_id) + COALESCE(LENGTH(conversation_id), 0) +
|
||||
LENGTH(route) + COALESCE(LENGTH(model_id), 0) + LENGTH(status) +
|
||||
COALESCE(LENGTH(error_message), 0) + 96
|
||||
) FROM cursor_run_traces
|
||||
), 0) +
|
||||
COALESCE((SELECT SUM(LENGTH(artifact_type) + LENGTH(source) + LENGTH(metadata_json) + 48) FROM cursor_run_trace_artifacts), 0) +
|
||||
COALESCE((SELECT SUM(LENGTH(data)) FROM blobs WHERE blob_id IN (SELECT blob_id FROM cursor_run_trace_artifacts)), 0),
|
||||
(SELECT COUNT(*) FROM llm_calls),
|
||||
(SELECT COUNT(*) FROM cursor_run_traces)
|
||||
"#,
|
||||
)
|
||||
.fetch_one(&self.pool)
|
||||
.await?;
|
||||
|
||||
Ok(StatisticsStorage {
|
||||
bytes,
|
||||
call_count,
|
||||
trace_count,
|
||||
})
|
||||
}
|
||||
|
||||
pub async fn clear_statistics_storage(&self) -> Result<StatisticsStorage> {
|
||||
let _write = self.writes.lock().await;
|
||||
let mut transaction = self.pool.begin().await?;
|
||||
Self::clear_detail_storage_tx(&mut transaction).await?;
|
||||
transaction.commit().await?;
|
||||
self.statistics_storage().await
|
||||
}
|
||||
|
||||
pub async fn clear_all_statistics_storage(&self) -> Result<StatisticsStorage> {
|
||||
let _write = self.writes.lock().await;
|
||||
let mut transaction = self.pool.begin().await?;
|
||||
Self::clear_trace_artifacts_tx(&mut transaction).await?;
|
||||
sqlx::query("DELETE FROM llm_calls")
|
||||
.execute(&mut *transaction)
|
||||
.await?;
|
||||
sqlx::query("DELETE FROM cursor_run_traces")
|
||||
.execute(&mut *transaction)
|
||||
.await?;
|
||||
transaction.commit().await?;
|
||||
self.statistics_storage().await
|
||||
}
|
||||
|
||||
async fn clear_detail_storage_tx(
|
||||
transaction: &mut sqlx::Transaction<'_, sqlx::Sqlite>,
|
||||
) -> Result<()> {
|
||||
sqlx::query("DELETE FROM llm_call_requests")
|
||||
.execute(&mut **transaction)
|
||||
.await?;
|
||||
sqlx::query("DELETE FROM llm_call_response_chunks")
|
||||
.execute(&mut **transaction)
|
||||
.await?;
|
||||
Self::clear_trace_artifacts_tx(transaction).await
|
||||
}
|
||||
|
||||
async fn clear_trace_artifacts_tx(
|
||||
transaction: &mut sqlx::Transaction<'_, sqlx::Sqlite>,
|
||||
) -> Result<()> {
|
||||
sqlx::query(
|
||||
"CREATE TEMP TABLE IF NOT EXISTS clear_statistics_blob_ids(
|
||||
blob_id BLOB PRIMARY KEY
|
||||
)",
|
||||
)
|
||||
.execute(&mut **transaction)
|
||||
.await?;
|
||||
sqlx::query("DELETE FROM clear_statistics_blob_ids")
|
||||
.execute(&mut **transaction)
|
||||
.await?;
|
||||
sqlx::query(
|
||||
"INSERT OR IGNORE INTO clear_statistics_blob_ids(blob_id)
|
||||
SELECT blob_id FROM cursor_run_trace_artifacts",
|
||||
)
|
||||
.execute(&mut **transaction)
|
||||
.await?;
|
||||
sqlx::query("DELETE FROM cursor_run_trace_artifacts")
|
||||
.execute(&mut **transaction)
|
||||
.await?;
|
||||
sqlx::query(
|
||||
"DELETE FROM blobs
|
||||
WHERE blob_id IN (SELECT blob_id FROM clear_statistics_blob_ids)
|
||||
AND NOT EXISTS (
|
||||
SELECT 1 FROM cursor_run_trace_artifacts a WHERE a.blob_id = blobs.blob_id
|
||||
)
|
||||
AND NOT EXISTS (
|
||||
SELECT 1 FROM blob_edges e
|
||||
WHERE e.parent_blob_id = blobs.blob_id OR e.child_blob_id = blobs.blob_id
|
||||
)",
|
||||
)
|
||||
.execute(&mut **transaction)
|
||||
.await?;
|
||||
sqlx::query("DROP TABLE clear_statistics_blob_ids")
|
||||
.execute(&mut **transaction)
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,311 @@
|
||||
//! Persists Tool round calls, results, and settlement state.
|
||||
use sqlx::Row;
|
||||
|
||||
use crate::{
|
||||
model::{
|
||||
CanonicalMessage, CheckpointId, ConversationId, MessageContent, Origin, Role, RunId,
|
||||
ToolCall, ToolCallContent, ToolResult, ToolResultContent, ToolRoundAssistant, ToolRoundId,
|
||||
},
|
||||
Error, Result,
|
||||
};
|
||||
|
||||
use super::{now_ms, Store};
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum ToolRoundStatus {
|
||||
Pending,
|
||||
Settled,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct ToolRoundSnapshot {
|
||||
pub round_id: ToolRoundId,
|
||||
pub run_id: RunId,
|
||||
pub base_checkpoint_id: CheckpointId,
|
||||
pub assistant: ToolRoundAssistant,
|
||||
pub calls: Vec<ToolCall>,
|
||||
pub completed_call_ids: Vec<String>,
|
||||
pub status: ToolRoundStatus,
|
||||
pub version: u64,
|
||||
pub created_at_ms: u64,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct ToolCommit {
|
||||
pub checkpoint_id: CheckpointId,
|
||||
pub tool_round_version: u64,
|
||||
pub completion_seq: u64,
|
||||
pub settled: bool,
|
||||
}
|
||||
|
||||
impl Store {
|
||||
pub async fn create_tool_round(
|
||||
&self,
|
||||
round_id: &ToolRoundId,
|
||||
run_id: &RunId,
|
||||
base_checkpoint_id: CheckpointId,
|
||||
assistant: &ToolRoundAssistant,
|
||||
calls: &[ToolCall],
|
||||
created_at_ms: Option<u64>,
|
||||
) -> Result<()> {
|
||||
if calls.is_empty() {
|
||||
return Err(Error::Store("cannot persist an empty tool round".into()));
|
||||
}
|
||||
let assistant_json = serde_json::to_string(assistant)?;
|
||||
let _write = self.writes.lock().await;
|
||||
let mut tx = self.pool.begin_with("BEGIN IMMEDIATE").await?;
|
||||
let ownership: bool = sqlx::query_scalar(
|
||||
"SELECT EXISTS(
|
||||
SELECT 1 FROM runs r JOIN conversations c USING(conversation_id)
|
||||
WHERE r.run_id = ? AND r.head_checkpoint_id = ?
|
||||
AND r.status = 'running' AND c.active_run_id = r.run_id
|
||||
AND c.current_checkpoint_id = r.head_checkpoint_id
|
||||
)",
|
||||
)
|
||||
.bind(run_id.as_str())
|
||||
.bind(base_checkpoint_id.0)
|
||||
.fetch_one(&mut *tx)
|
||||
.await?;
|
||||
if !ownership {
|
||||
return Err(Error::Store(format!(
|
||||
"run {run_id} cannot start tool round at checkpoint {base_checkpoint_id}"
|
||||
)));
|
||||
}
|
||||
let now = now_ms();
|
||||
let created_at_ms = created_at_ms
|
||||
.map(i64::try_from)
|
||||
.transpose()
|
||||
.map_err(|_| Error::Protocol("tool round timestamp exceeds SQLite INTEGER".into()))?
|
||||
.unwrap_or(now);
|
||||
sqlx::query(
|
||||
"INSERT INTO tool_rounds
|
||||
(round_id, run_id, base_checkpoint_id, assistant_json, status, created_at_ms, updated_at_ms)
|
||||
VALUES (?, ?, ?, ?, 'pending', ?, ?)",
|
||||
)
|
||||
.bind(round_id.as_str())
|
||||
.bind(run_id.as_str())
|
||||
.bind(base_checkpoint_id.0)
|
||||
.bind(assistant_json)
|
||||
.bind(created_at_ms)
|
||||
.bind(now)
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
for call in calls {
|
||||
sqlx::query(
|
||||
"INSERT INTO tool_round_calls
|
||||
(round_id, call_index, call_id, model_call_id, name, arguments_json, status)
|
||||
VALUES (?, ?, ?, ?, ?, ?, 'pending')",
|
||||
)
|
||||
.bind(round_id.as_str())
|
||||
.bind(call.index as i64)
|
||||
.bind(&call.call_id)
|
||||
.bind(&call.model_call_id)
|
||||
.bind(&call.name)
|
||||
.bind(&call.arguments_text)
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
}
|
||||
tx.commit().await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn commit_tool_result(
|
||||
&self,
|
||||
conversation_id: &ConversationId,
|
||||
run_id: &RunId,
|
||||
round_id: &ToolRoundId,
|
||||
result: &ToolResult,
|
||||
) -> Result<ToolCommit> {
|
||||
let _write = self.writes.lock().await;
|
||||
let mut tx = self.pool.begin_with("BEGIN IMMEDIATE").await?;
|
||||
let round = sqlx::query(
|
||||
"SELECT assistant_json, status, version, next_completion_seq
|
||||
FROM tool_rounds WHERE round_id = ? AND run_id = ?",
|
||||
)
|
||||
.bind(round_id.as_str())
|
||||
.bind(run_id.as_str())
|
||||
.fetch_optional(&mut *tx)
|
||||
.await?
|
||||
.ok_or_else(|| Error::Store(format!("unknown tool round: {round_id}")))?;
|
||||
if round.get::<&str, _>(1) != "pending" {
|
||||
return Err(Error::Store(format!(
|
||||
"tool round is already settled: {round_id}"
|
||||
)));
|
||||
}
|
||||
let assistant: ToolRoundAssistant = serde_json::from_str(round.get(0))?;
|
||||
let version: i64 = round.get(2);
|
||||
let completion_seq: i64 = round.get(3);
|
||||
let call = sqlx::query(
|
||||
"SELECT call_index, name, arguments_json, status
|
||||
FROM tool_round_calls WHERE round_id = ? AND call_id = ?",
|
||||
)
|
||||
.bind(round_id.as_str())
|
||||
.bind(&result.call_id)
|
||||
.fetch_optional(&mut *tx)
|
||||
.await?;
|
||||
let Some(call) = call else {
|
||||
tracing::error!(
|
||||
run_id = %run_id,
|
||||
round_id = %round_id,
|
||||
call_id = result.call_id,
|
||||
"unknown tool result"
|
||||
);
|
||||
return Err(Error::Protocol(format!(
|
||||
"unknown tool result call_id: {}",
|
||||
result.call_id
|
||||
)));
|
||||
};
|
||||
if call.get::<&str, _>(3) != "pending" {
|
||||
return Err(Error::Protocol(format!(
|
||||
"duplicate tool result call_id: {}",
|
||||
result.call_id
|
||||
)));
|
||||
}
|
||||
|
||||
let head: i64 = sqlx::query_scalar("SELECT head_checkpoint_id FROM runs WHERE run_id = ?")
|
||||
.bind(run_id.as_str())
|
||||
.fetch_one(&mut *tx)
|
||||
.await?;
|
||||
let call_index = call.get::<i64, _>(0) as usize;
|
||||
let name: String = call.get(1);
|
||||
let arguments_text: String = call.get(2);
|
||||
let arguments = serde_json::from_str(&arguments_text)?;
|
||||
let first = completion_seq == 0;
|
||||
let assistant_message = CanonicalMessage {
|
||||
message_id: format!("{}:{}:assistant", round_id, result.call_id),
|
||||
role: Role::Assistant,
|
||||
origin: Origin::Assistant,
|
||||
content: MessageContent::Assistant {
|
||||
text: if first { assistant.text } else { String::new() },
|
||||
thinking: if first {
|
||||
assistant.thinking
|
||||
} else {
|
||||
String::new()
|
||||
},
|
||||
tool_round_id: Some(round_id.clone()),
|
||||
replay_state: if first { assistant.replay_state } else { None },
|
||||
tool_calls: vec![ToolCallContent {
|
||||
index: call_index,
|
||||
call_id: result.call_id.clone(),
|
||||
name: name.clone(),
|
||||
arguments,
|
||||
}],
|
||||
},
|
||||
runtime_event_id: None,
|
||||
};
|
||||
let result_message = CanonicalMessage {
|
||||
message_id: format!("{}:{}:result", round_id, result.call_id),
|
||||
role: Role::Tool,
|
||||
origin: Origin::Tool,
|
||||
content: MessageContent::ToolResult(ToolResultContent {
|
||||
call_id: result.call_id.clone(),
|
||||
name,
|
||||
content: result.content.clone(),
|
||||
is_error: result.is_error,
|
||||
image: result.image.clone(),
|
||||
provider_parts: Vec::new(),
|
||||
}),
|
||||
runtime_event_id: None,
|
||||
};
|
||||
let checkpoint = Self::append_checkpoint_tx(
|
||||
&mut tx,
|
||||
conversation_id,
|
||||
run_id,
|
||||
CheckpointId(head),
|
||||
&[assistant_message, result_message],
|
||||
)
|
||||
.await?;
|
||||
|
||||
sqlx::query(
|
||||
"UPDATE tool_round_calls SET status = 'completed', completion_seq = ?,
|
||||
result_content = ?, result_is_error = ?, committed_checkpoint_id = ?, completed_at_ms = ?
|
||||
WHERE round_id = ? AND call_id = ? AND status = 'pending'",
|
||||
)
|
||||
.bind(completion_seq)
|
||||
.bind(&result.content)
|
||||
.bind(result.is_error)
|
||||
.bind(checkpoint.0)
|
||||
.bind(now_ms())
|
||||
.bind(round_id.as_str())
|
||||
.bind(&result.call_id)
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
let pending: i64 = sqlx::query_scalar(
|
||||
"SELECT COUNT(*) FROM tool_round_calls WHERE round_id = ? AND status = 'pending'",
|
||||
)
|
||||
.bind(round_id.as_str())
|
||||
.fetch_one(&mut *tx)
|
||||
.await?;
|
||||
let settled = pending == 0;
|
||||
sqlx::query(
|
||||
"UPDATE tool_rounds SET status = ?, version = ?, next_completion_seq = ?, updated_at_ms = ?
|
||||
WHERE round_id = ?",
|
||||
)
|
||||
.bind(if settled { "settled" } else { "pending" })
|
||||
.bind(version + 1)
|
||||
.bind(completion_seq + 1)
|
||||
.bind(now_ms())
|
||||
.bind(round_id.as_str())
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
tx.commit().await?;
|
||||
Ok(ToolCommit {
|
||||
checkpoint_id: checkpoint,
|
||||
tool_round_version: (version + 1) as u64,
|
||||
completion_seq: completion_seq as u64,
|
||||
settled,
|
||||
})
|
||||
}
|
||||
|
||||
pub async fn tool_round(&self, round_id: &ToolRoundId) -> Result<Option<ToolRoundSnapshot>> {
|
||||
let Some(round) = sqlx::query(
|
||||
"SELECT run_id, base_checkpoint_id, assistant_json, status, version, created_at_ms
|
||||
FROM tool_rounds WHERE round_id = ?",
|
||||
)
|
||||
.bind(round_id.as_str())
|
||||
.fetch_optional(&self.pool)
|
||||
.await?
|
||||
else {
|
||||
return Ok(None);
|
||||
};
|
||||
let rows = sqlx::query(
|
||||
"SELECT call_index, call_id, model_call_id, name, arguments_json, status
|
||||
FROM tool_round_calls WHERE round_id = ? ORDER BY call_index",
|
||||
)
|
||||
.bind(round_id.as_str())
|
||||
.fetch_all(&self.pool)
|
||||
.await?;
|
||||
let mut calls = Vec::with_capacity(rows.len());
|
||||
let mut completed = Vec::new();
|
||||
for row in rows {
|
||||
let arguments_text: String = row.get(4);
|
||||
let call_id: String = row.get(1);
|
||||
if row.get::<&str, _>(5) == "completed" {
|
||||
completed.push(call_id.clone());
|
||||
}
|
||||
calls.push(ToolCall {
|
||||
index: row.get::<i64, _>(0) as usize,
|
||||
call_id,
|
||||
model_call_id: row.get(2),
|
||||
name: row.get(3),
|
||||
arguments: serde_json::from_str(&arguments_text)?,
|
||||
arguments_text,
|
||||
});
|
||||
}
|
||||
Ok(Some(ToolRoundSnapshot {
|
||||
round_id: round_id.clone(),
|
||||
run_id: RunId(round.get(0)),
|
||||
base_checkpoint_id: CheckpointId(round.get(1)),
|
||||
assistant: serde_json::from_str(round.get(2))?,
|
||||
calls,
|
||||
completed_call_ids: completed,
|
||||
status: if round.get::<&str, _>(3) == "settled" {
|
||||
ToolRoundStatus::Settled
|
||||
} else {
|
||||
ToolRoundStatus::Pending
|
||||
},
|
||||
version: round.get::<i64, _>(4) as u64,
|
||||
created_at_ms: round.get::<i64, _>(5) as u64,
|
||||
}))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
//! Serializes write transactions that mutate Conversation state.
|
||||
use std::sync::Arc;
|
||||
|
||||
use tokio::sync::{Mutex, MutexGuard};
|
||||
|
||||
#[derive(Clone, Default)]
|
||||
pub(crate) struct WriteCoordinator {
|
||||
lock: Arc<Mutex<()>>,
|
||||
}
|
||||
|
||||
impl WriteCoordinator {
|
||||
pub(crate) async fn lock(&self) -> MutexGuard<'_, ()> {
|
||||
self.lock.lock().await
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user