blob: 523696886ef11202c98ea2acbc0f04da37005a50 [file]
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
use super::*;
use maka_event_log::{applications::operations::OperationDispatchScope, root_store::DataWriter};
use stored::resolution::{self, ExtractionCommit, ExtractionGuard};
/// Each stage has one accounting identity within this application operation.
#[derive(Clone, Copy)]
pub(super) enum ExtractionStage {
Proposal = 1,
LocatedProposal,
Audit,
Relation,
}
#[derive(Clone)]
pub(super) struct ExtractionAuthority {
pub(super) guard: ExtractionGuard,
project: Arc<MemoryProject>,
config: Arc<ConfigurationStore>,
writer: DataWriter,
agent_requested: bool,
pub(super) instruction: Option<String>,
route: Arc<std::sync::OnceLock<crate::model::AcceptedModel>>,
pub(super) deadline: tokio::time::Instant,
}
impl ExtractionAuthority {
pub(super) fn authorize_route(
&self,
selected: &crate::model::AcceptedModel,
) -> Result<(), String> {
if self
.route
.get_or_init(|| selected.clone())
.same_execution_route(selected)
{
Ok(())
} else {
Err("agent_memory_extraction_model_route_changed".into())
}
}
pub(super) async fn check(&self) -> Result<(), String> {
let policy = self
.config
.runtime_policy()
.await
.map_err(|e| e.to_string())?;
if !policy.policy.memory.enabled
|| (self.agent_requested && !policy.policy.memory.agent_read_enabled)
{
return Err("agent_memory_extraction_policy_changed".into());
}
self.writer
.query(self.guard.clone())
.await
.map_err(|e| e.to_string())?;
let project = self.project.clone();
let location = self.guard.source.location.clone();
tokio::task::spawn_blocking(move || project.verify(&location))
.await
.map_err(|e| e.to_string())?
}
}
pub(super) struct ConversationCommand {
pub(super) model: crate::model::AcceptedModel,
pub(super) organize_instruction: Option<String>,
}
impl Owner {
pub(super) async fn extraction_writer(
self: &Arc<Self>,
call: &Scope,
) -> Result<DataWriter, String> {
let owner = self.clone();
let call = call.clone();
tokio::task::spawn_blocking(move || owner.memory_data(&call))
.await
.map_err(|e| e.to_string())?
}
pub(crate) async fn extract_memories(
self: &Arc<Self>,
input: ExtractMemories,
operation: &RecoveryRef,
scope: &Scope,
dispatch: OperationDispatchScope,
) -> Result<NativeMutation<MemoryBatchResult>, String> {
management(scope)?;
let writer = self.extraction_writer(scope).await?;
self.extract_memories_authorized(input, writer, None, operation, scope, dispatch)
.await
}
pub(super) async fn extract_memories_authorized(
self: &Arc<Self>,
input: ExtractMemories,
writer: DataWriter,
command: Option<ConversationCommand>,
operation: &RecoveryRef,
scope: &Scope,
dispatch: OperationDispatchScope,
) -> Result<NativeMutation<MemoryBatchResult>, String> {
let operation = operation.clone();
self.resource_work(scope, move |owner, call| {
Box::pin(async move {
owner
.prepare_extraction(input, writer, command, &operation, &call, dispatch)
.await
})
})
.await
}
async fn prepare_extraction(
self: &Arc<Self>,
input: ExtractMemories,
writer: DataWriter,
command: Option<ConversationCommand>,
operation: &RecoveryRef,
call: &Scope,
dispatch: OperationDispatchScope,
) -> Result<NativeMutation<MemoryBatchResult>, String> {
if matches!(&input.scope, MemoryScope::Project {session_id} if session_id != &input.session_id)
{
return Err("agent_memory_evidence_scope".into());
}
let session = self.scoped_session(call, &input.session_id).await?;
let config = &session.configuration;
if session.archived
|| config.incognito
|| config.parent_session_id.is_some()
|| config.tools.is_some()
|| self.bot.is(&input.session_id)
|| maka_agent_state::room::RoomStore::new(writer.clone(), self.run_owner())
.exists(&input.session_id)
.await
.map_err(|e| e.to_string())?
{
return Err("agent_memory_ordinary_session_required".into());
}
let policy = self
.configuration
.runtime_policy()
.await
.map_err(|e| e.to_string())?;
if !policy.policy.memory.enabled
|| (call.identity.agent().is_some() && !policy.policy.memory.agent_read_enabled)
{
return Err("agent_memory_disabled".into());
}
let (source, project) = self
.observed_project_scope(&input.session_id, config)
.await?;
let destination = match input.scope {
MemoryScope::Personal => self.memory_scope(MemoryScope::Personal).await?,
MemoryScope::Project { .. } => source.clone(),
};
let history = self
.durable
.with_data_writer(writer.clone())
.map_err(|e| e.to_string())?
.session_history(self.run_owner(), input.session_id.clone());
let cut = history
.capture_at(input.range.through_sequence)
.await
.map_err(|e| e.to_string())?;
let after = input.range.after_sequence;
if after > cut.through_sequence {
return Err("agent_memory_invalid_range".into());
}
maka_agent_state::recall::ensure_session_caught_up_through(
&writer,
&cut.owner,
&cut.session,
Some(cut.through_sequence),
Some(&call.cancellation),
)
.await
.map_err(|e| e.to_string())?;
let (route, instruction) = match command {
Some(command) => (
std::sync::OnceLock::from(command.model),
command.organize_instruction,
),
None => (std::sync::OnceLock::new(), None),
};
// Older steering records identify the sender, but a former Bot's background Run
// cannot prove it received the message during the Session's ordinary lifetime.
let background_steering_basis =
(!self.has_bot_history(&input.session_id).await?).then(|| config.permission_basis());
let mut authority = ExtractionAuthority {
project: Arc::new(project),
guard: ExtractionGuard {
source,
destination,
destination_revision: None,
history: stored::extraction::Guard {
cut,
after,
background_steering_basis,
},
},
config: self.configuration.clone(),
writer: writer.clone(),
agent_requested: call.identity.agent().is_some(),
instruction,
route: Arc::new(route),
deadline: tokio::time::Instant::now() + Duration::from_secs(120),
};
let generation = extraction::Generation {
owner: self,
call,
input: &input,
operation,
dispatch: &dispatch,
};
let reviewed = generation.extract(&mut authority, &writer).await?;
let (writes, grants): (Vec<_>, Vec<_>) = reviewed.into_iter().unzip();
let plan = if writes.is_empty() {
None
} else {
let snapshot = writer
.query(resolution::Inspect {
scope: authority.guard.destination.clone(),
writes: writes.clone(),
})
.await
.map_err(|e| e.to_string())?;
authority.guard.destination_revision = Some(snapshot.revision);
let comparisons = snapshot.comparisons(&writes);
let unresolved = comparisons.unresolved();
let judgments = if unresolved.is_empty() {
Vec::new()
} else {
let mut candidates = BTreeMap::new();
let mut inputs = BTreeMap::new();
for &(row, column) in &unresolved {
inputs.insert(row, &writes[row]);
if let Some(candidate) = snapshot.candidates.get(column) {
candidates.insert(column, serde_json::json!({"body":candidate.body,"metadata":candidate.metadata,"latestObservedAt":candidate.latest_observed_at}));
} else {
let prior = column - snapshot.candidates.len();
inputs.insert(prior, &writes[prior]);
}
}
let prompt = serde_json::json!({"pairs":unresolved,"storedCount":snapshot.candidates.len(),"candidates":candidates,"writes":inputs,"intent":input.intent}).to_string();
generation
.parse(
&authority,
ExtractionStage::Relation,
include_str!("extraction-relations.md"),
prompt,
|judgments: &Vec<resolution::Judgment>| judgments.len() == unresolved.len(),
)
.await?
};
Some(resolution::Commit {
scope: authority.guard.destination.clone(),
source_scopes: vec![authority.guard.source.clone()],
decisions: comparisons.complete(judgments).map_err(|e| e.to_string())?,
snapshot,
writes,
operation: operation.operation,
at: i64::try_from(now()).map_err(|e| e.to_string())?,
})
};
authority.check().await?;
if call.cancellation.is_cancelled() || self.stop.is_cancelled() {
return Err("agent_memory_extraction_cancelled".into());
}
let location = authority.guard.source.location.clone();
let project = authority.project;
let commit = ExtractionCommit {
verify_project: Box::new(move || {
project
.verify(&location)
.map_err(maka_event_log::StoreError::InvalidTransition)
}),
plan,
grants,
guard: authority.guard,
cancellation: call.cancellation.clone(),
};
let change = tokio::task::spawn_blocking(move || writer.prepare_result(|_| Ok(commit)))
.await
.map_err(|e| e.to_string())?
.map_err(|e| e.to_string())?;
Ok(NativeMutation::Computed { change })
}
}