blob: f0e143f7e42787c4840ce63bfc586bca10b0cb84 [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_agent_engine::prepared_prompt::PreparedPrompt;
use maka_agent_state::session_history::{HistoryCut, SessionHistory};
#[derive(Clone)]
pub(super) enum Denial {
Memory(String),
Other(String),
}
impl Denial {
fn model_error(&self) -> maka_model::ModelError {
let (Self::Memory(message) | Self::Other(message)) = self;
maka_model::ModelError::LocalAuthorization(message.clone())
}
}
pub(super) struct FrozenMaterializer {
pub io: preparation::PreparationIo,
pub resources: ModelPreparationResources,
pub history: SessionHistory,
pub cut: HistoryCut,
pub run: RunId,
pub frozen: FrozenInput,
pub surface: CompositionSurface,
pub request: RequestSpec,
pub access: Arc<crate::owner::RunAccess>,
pub model_source: Arc<Source>,
pub executor: ModelExecutor,
pub provenance: Value,
pub recovery: FrozenRecovery,
pub authorization_failure: Arc<std::sync::Mutex<Option<Denial>>>,
pub provider: maka_model::ProviderConfig,
pub budget: maka_agent_facts::context::PreparedContextBreakdown,
pub memory: Option<Arc<maka_agent_facts::memory::MemoryProjection>>,
pub tool_digest_checked: std::sync::OnceLock<()>,
}
impl FrozenMaterializer {
pub async fn authorize_current(
&self,
cancellation: &CancellationToken,
) -> Result<(), RunError> {
if let Some(failure) = self.authorization_failure.lock().unwrap().clone() {
return Err(RunError::Model(failure.model_error()));
}
let result = tokio::select! {
biased;
_=cancellation.cancelled()=>Err(RunError::Cancelled),
result=async{
let owner = self.access.owner().map_err(RunError::InvalidInput)?;
owner
.require_execution(&self.access.execution().session_id)
.await
.map_err(RunError::InvalidInput)?;
let (current, _authority) = self
.access
.live_authority_fast(
false,
None,
Some(self.access.spec().tool_selection.clone()),
)
.await?;
let selection = match owner.cached_selection_snapshot(&self.access.spec().tool_selection) {
Some(snapshot) => snapshot,
None => {
owner
.selection_snapshot(
&owner.durable,
self.access.execution().run_id,
&self.access.spec().tool_selection,
)
.await?
}
};
if self.tool_digest_checked.get().is_none() {
crate::owner::driver::validate_tool_digest(&self.request, &self.surface)?;
let _ = self.tool_digest_checked.set(());
}
let model = self.model_source.capture().await?;
self.access
.authorize_request_tools_with_live(
&self.request,
&self.surface,
&model,
&current,
selection,
true,
cancellation,
)
.await?;
validate_model_input_policy(&self.provenance,&model)?;
let recovery=&self.recovery;
let binding=self.executor.binding(&model.provider)?;
if self.frozen.accepted!=self.model_source.accepted||!same_adapter(binding.source(),&self.frozen.adapter)
||preparation::route_identity(&model.provider)?!=self.frozen.route_identity
||recovery.protocol!=format!("{PROTOCOL}/recovery")||recovery.version!=VERSION
||recovery.request!=self.request.request||recovery.adapter!=self.frozen.adapter
||recovery.contract!=original_recovery_contract(&binding,&model.provider,&self.surface.tools,self.frozen.operation){
return Err(unsupported("current-frozen-model-dispatch-contract"));
}
self.access
.authorize_request_memory(
&self.request,
&model,
&self.budget,
self.memory.as_deref(),
)
.await
}=>result,
};
match result {
Err(error)
if !matches!(error, RunError::Cancelled) && !error.is_cleanup_unconfirmed() =>
{
self.authorization_failure
.lock()
.unwrap()
.get_or_insert_with(|| match &error {
RunError::FrozenMemoryDenied(message) => Denial::Memory(message.clone()),
_ => Denial::Other(error.to_string()),
});
Err(RunError::Preparation(std::io::Error::new(
std::io::ErrorKind::PermissionDenied,
error,
)))
}
result => result,
}
}
pub async fn build(
&self,
cancellation: &CancellationToken,
prepared: Option<Box<PreparedPrompt>>,
) -> Result<(PreparedPrompt, ModelRequest), RunError> {
let mut prompt = prepared.map(|prepared| *prepared);
let had_prepared = prompt.is_some();
let result = async {
if had_prepared {
// The caller immediately enters executor.stream_with_source, which runs
// source.frozen.authorize() before auth resolution and before any network I/O.
if cancellation.is_cancelled() {
return Err(RunError::Cancelled);
}
} else {
self.authorize_current(cancellation).await?;
}
let source = preparation::ContentSource::Live {
history: &self.history,
cut: &self.cut,
};
if prompt.is_some() {
// The same publication produced these text-only bytes and the retained
// wire. Authenticate its durable refs without decompressing every chunk
// back out of SQLite; wire identity and budget are checked below.
self.frozen
.prompt
.validate()
.map_err(|reason| RunError::InvalidInput(reason.into()))?;
self.history
.verify_prompt_refs(
&self.cut,
self.run,
&self.frozen.prompt,
&self.frozen.prompt_chunks,
)
.await?;
} else {
prompt = Some(
self.frozen
.restore_prompt(
self.io.clone(),
self.resources.clone(),
source,
self.run,
cancellation,
)
.await?
.with_frozen_transport(
self.frozen.instructions.as_deref(),
self.frozen.normalization.clone(),
),
);
}
let prompt = prompt.as_mut().expect("materialized model prompt");
let options = self
.request
.composition
.provider_options
.as_ref()
.ok_or_else(|| unsupported("frozen-provider-options"))?;
let settings = PromptSettings {
operation: self.frozen.operation,
codex: None,
language: self.frozen.language,
provider: &self.provider,
options,
context_window: None,
tool_choice: self.frozen.tool_choice,
};
preparation::prepare_wire(
&settings,
prompt,
&self.surface.tools,
self.request.composition.max_output_tokens,
cancellation,
)
.await?;
let rebuilt = preparation::prepare_request(
&settings,
prompt.clone(),
self.surface.tools.clone(),
preparation::OutputBudget::Frozen(self.request.composition.max_output_tokens),
self.request.accounting.purpose,
None,
)?;
self.frozen.wire.validate(&rebuilt.request.prompt)?;
if rebuilt.context_breakdown != self.budget {
return Err(unsupported("frozen-budget-signature"));
}
if !had_prepared {
self.authorize_current(cancellation).await?;
}
Ok(rebuilt.request)
}
.await;
match result {
Ok(request) => Ok((prompt.expect("materialized model prompt"), request)),
Err(error) => {
if let Some(prompt) = prompt
&& let Err(cleanup) = prompt.close().await
{
return Err(RunError::PreparationCleanup(std::io::Error::other(
FailedCleanup {
original: error,
cleanup,
},
)));
}
Err(error)
}
}
}
}
impl maka_agent_ports::model::FrozenPrompt for FrozenMaterializer {
fn authorize(
&self,
cancellation: CancellationToken,
) -> futures_util::future::BoxFuture<'_, Result<(), maka_model::ModelError>> {
Box::pin(async move {
self.authorize_current(&cancellation)
.await
.map_err(|error| {
self.authorization_failure
.lock()
.unwrap()
.as_ref()
.map(Denial::model_error)
.unwrap_or_else(|| {
if error.is_cleanup_unconfirmed() {
maka_model::ModelError::CleanupUnconfirmed
} else {
maka_model::ModelError::Cancelled
}
})
})
})
}
fn authorization_failure(&self) -> Option<maka_model::ModelError> {
self.authorization_failure
.lock()
.unwrap()
.as_ref()
.map(Denial::model_error)
}
fn open(
&self,
cancellation: CancellationToken,
) -> futures_util::future::BoxFuture<
'_,
Result<maka_agent_ports::model::MaterializedPrompt, maka_model::ModelError>,
> {
Box::pin(async move {
let (prompt, request) = self.build(&cancellation, None).await.map_err(|error| {
if matches!(error, RunError::Cancelled) {
maka_model::ModelError::Cancelled
} else if error.is_cleanup_unconfirmed() {
maka_model::ModelError::CleanupUnconfirmed
} else {
self.authorization_failure
.lock()
.unwrap()
.as_ref()
.map(Denial::model_error)
.unwrap_or_else(|| maka_model::ModelError::Adapter(error.to_string()))
}
})?;
Ok(maka_agent_ports::model::MaterializedPrompt {
prompt: request.prompt,
cleanup: prompt.cleanup(),
})
})
}
}
#[derive(Debug)]
struct FailedCleanup {
original: RunError,
cleanup: std::io::Error,
}
impl std::fmt::Display for FailedCleanup {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(
f,
"{}; materialization cleanup failed: {}",
self.original, self.cleanup
)
}
}
impl std::error::Error for FailedCleanup {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
Some(&self.original)
}
}