blob: f90450c82aeae0d2525fa59c3acacd56296aee2b [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.
*/
//! Native application consent and logical app controls. No physical outcome is inferred here.
use crate::{ContentBlob, DriverClaim, Head};
use maka_agent_facts::{durable::*, interaction::*};
use maka_event_log::{
StoreError,
connection::Query,
root_store::{DataChange, DataWriter},
writeback::{Notification, Prepared, Statement},
};
use maka_plugin_core::operation::RecoveryRef;
use maka_sandbox::workspace::PermissionBasis;
use rusqlite::Connection;
use serde::{Deserialize, Serialize};
pub(crate) mod sql;
pub(crate) use sql::pin_run;
/// Immutable observation from the actual native adapter, not model arguments.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct Subject {
pub activity: ComputerAppActivity,
pub basis: PermissionBasis,
pub allow_always: bool,
pub target: AuthorizationObligation,
pub operation: RecoveryRef,
/// Exact native discovery/protocol metadata; persisted and pinned with SubjectObserved.
pub capture: ContentRef,
}
/// Canonical metadata of an already bound native producer. This is not a capability.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct NativeSource {
pub execution: ExecutionIdentity,
pub target: AuthorizationObligation,
pub original: RecoveryRef,
pub native_epoch: String,
pub generation: String,
pub operation: String,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
#[expect(
clippy::large_enum_variant,
reason = "Native observations are serialized into facts; keep their owned metadata inline instead of adding a payload allocation"
)]
pub enum Fact {
NativeSourceBound {
source: NativeSource,
},
NativeTurnInterrupted {
binding: FactId,
},
SubjectObserved {
subject: Subject,
},
AppStopRequested {
source_operation: String,
},
AppAuthorized {
source_operation: String,
request: Option<String>,
basis: PermissionBasis,
},
ProfileGrantRevoked {
source_operation: String,
},
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Change {
pub id: FactId,
pub at: UnixMillis,
pub fact: Fact,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ActivityState {
pub subject: Subject,
pub stopped: bool,
pub authorized: bool,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum Consent {
Absent,
Once { request: String },
Session { request: String },
Profile { request: String },
FullAccess,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Status {
pub stopped: bool,
pub authority_revision: u64,
pub consent: Consent,
}
#[derive(Clone)]
pub struct ComputerStore {
data: DataWriter,
}
impl ComputerStore {
pub fn new(data: DataWriter) -> Self {
Self { data }
}
pub fn same_root(&self, writer: &DataWriter) -> bool {
self.data.same_root(writer)
}
pub fn subscribe(&self) -> Result<tokio::sync::watch::Receiver<()>, StoreError> {
self.data.subscribe_changes()
}
pub async fn subject(
&self,
session: &str,
operation: &str,
) -> Result<Option<Subject>, StoreError> {
self.data
.query(ReadSubject(session.into(), operation.into()))
.await
}
pub async fn activities(
&self,
session: &str,
owner: &RunOwner,
) -> Result<Vec<ActivityState>, StoreError> {
self.data
.query(ReadActivities(session.into(), owner.clone()))
.await
}
pub async fn status(&self, session: &str, operation: &str) -> Result<Status, StoreError> {
self.data
.query(ReadStatus(session.into(), operation.into()))
.await
}
/// Only fresh domain facts use a current driver. Root physical resources have independent custody.
pub async fn append(
&self,
claim: &DriverClaim,
head: Head,
change: Change,
contents: Vec<ContentBlob>,
) -> Result<bool, StoreError> {
self.data
.write(DriverWrite {
data: self.data.clone(),
claim: claim.clone(),
head,
change,
contents,
})
.await
}
/// The human supplies only an observed operation identity. SQL derives its original Run and app.
pub fn prepare_stop(
&self,
session: &str,
operation: &str,
id: FactId,
at: UnixMillis,
) -> DataChange {
self.data.prepare(Control {
session: session.into(),
operation: operation.into(),
id,
at,
revoke: false,
})
}
pub fn prepare_revoke(
&self,
session: &str,
operation: &str,
id: FactId,
at: UnixMillis,
) -> DataChange {
self.data.prepare(Control {
session: session.into(),
operation: operation.into(),
id,
at,
revoke: true,
})
}
/// Observe an original producer after its initiating call has completed or
/// its driver claim has changed. This never admits another native action.
pub async fn native_interrupted(
&self,
execution: &ExecutionIdentity,
binding: FactId,
id: FactId,
at: UnixMillis,
) -> Result<bool, StoreError> {
self.data
.write(NativeInterruptionWrite {
execution: execution.clone(),
binding,
id,
at,
})
.await
}
pub async fn native_turn_interrupted(
&self,
execution: &ExecutionIdentity,
) -> Result<bool, StoreError> {
self.data.query(ReadNativeFence(execution.clone())).await
}
pub async fn rebuild(&self) -> Result<(), StoreError> {
self.data.write(Rebuild).await
}
}
struct DriverWrite {
data: DataWriter,
claim: DriverClaim,
head: Head,
change: Change,
contents: Vec<ContentBlob>,
}
impl Statement for DriverWrite {
type Value = bool;
type Output = bool;
fn execute(&self, c: &Connection) -> Result<Prepared<bool>, StoreError> {
self.claim.with_current(&self.data, || {
let session = sql::append(
c,
self.claim.run(),
Some(self.head),
self.change.clone(),
self.contents.clone(),
true,
)?;
Ok(Prepared {
value: session.is_some(),
changed: session.is_some(),
notification: session.map_or(Notification::NONE, |s| {
Notification::METADATA.with_sessions([s])
}),
})
})
}
fn committed(inserted: bool) -> bool {
inserted
}
fn isolated_rejection(e: &StoreError) -> bool {
rejection(e)
}
}
struct NativeInterruptionWrite {
execution: ExecutionIdentity,
binding: FactId,
id: FactId,
at: UnixMillis,
}
impl Statement for NativeInterruptionWrite {
type Value = bool;
type Output = bool;
fn execute(&self, c: &Connection) -> Result<Prepared<bool>, StoreError> {
sql::verify_native_binding(c, &self.execution, self.binding)?;
let session = sql::append(
c,
self.execution.run_id,
None,
Change {
id: self.id,
at: self.at,
fact: Fact::NativeTurnInterrupted {
binding: self.binding,
},
},
vec![],
false,
)?;
Ok(Prepared {
value: session.is_some(),
changed: session.is_some(),
notification: session.map_or(Notification::NONE, |s| {
Notification::METADATA.with_sessions([s])
}),
})
}
fn committed(inserted: bool) -> bool {
inserted
}
fn isolated_rejection(e: &StoreError) -> bool {
rejection(e)
}
}
struct ReadNativeFence(ExecutionIdentity);
impl Query for ReadNativeFence {
type Output = bool;
fn execute(self, c: &Connection) -> Result<bool, StoreError> {
sql::native_turn_interrupted(c, &self.0)
}
}
struct Control {
session: String,
operation: String,
id: FactId,
at: UnixMillis,
revoke: bool,
}
impl Statement for Control {
type Value = ();
type Output = ();
fn execute(&self, c: &Connection) -> Result<Prepared<()>, StoreError> {
let subject = sql::subject(c, &self.session, &self.operation)?
.ok_or_else(|| crate::store::invalid("computer source operation missing"))?;
let fact = if self.revoke {
Fact::ProfileGrantRevoked {
source_operation: self.operation.clone(),
}
} else {
Fact::AppStopRequested {
source_operation: self.operation.clone(),
}
};
let session = sql::append(
c,
subject.activity.execution.run_id,
None,
Change {
id: self.id,
at: self.at,
fact,
},
vec![],
false,
)?;
Ok(Prepared {
value: (),
changed: session.is_some(),
notification: session.map_or(Notification::NONE, |s| {
Notification::METADATA.with_sessions([s])
}),
})
}
fn committed(_: ()) {}
fn isolated_rejection(e: &StoreError) -> bool {
rejection(e)
}
}
fn rejection(e: &StoreError) -> bool {
matches!(
e,
StoreError::InvalidTransition(_)
| StoreError::RevisionConflict { .. }
| StoreError::EventConflict
)
}
struct ReadSubject(String, String);
impl Query for ReadSubject {
type Output = Option<Subject>;
fn execute(self, c: &Connection) -> Result<Self::Output, StoreError> {
sql::subject(c, &self.0, &self.1)
}
}
struct ReadActivities(String, RunOwner);
impl Query for ReadActivities {
type Output = Vec<ActivityState>;
fn execute(self, c: &Connection) -> Result<Self::Output, StoreError> {
sql::activities(c, &self.0, &self.1)
}
}
struct ReadStatus(String, String);
impl Query for ReadStatus {
type Output = Status;
fn execute(self, c: &Connection) -> Result<Self::Output, StoreError> {
sql::status(c, &self.0, &self.1)
}
}
struct Rebuild;
impl Statement for Rebuild {
type Value = ();
type Output = ();
fn execute(&self, c: &Connection) -> Result<Prepared<()>, StoreError> {
let sessions: Vec<String> = c
.prepare_cached(
"SELECT r.session FROM agent_computer_activities a JOIN agent_runs r ON r.run=a.run
UNION SELECT r.session FROM agent_computer_facts f JOIN agent_runs r ON r.run=f.run",
)?
.query_map([], |row| row.get(0))?
.collect::<Result<_, _>>()?;
sql::rebuild(c)?;
Ok(Prepared {
value: (),
changed: true,
notification: Notification::METADATA.with_sessions(sessions),
})
}
fn committed(_: ()) {}
fn isolated_rejection(error: &StoreError) -> bool {
rejection(error)
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::store::stop_tests::{open, spec};
use crate::{Admission, ContentBlob, Head};
use maka_agent_facts::{
durable::{
AuthorizationObligation, ExecutionIdentity, FactId, ModelAttemptId, ToolKey, UnixMillis,
},
interaction::{
ComputerAppActivity, ComputerAppDecision, ComputerAppDisplay, ComputerAppPlatform,
GrantCapability, GrantScope, GrantTarget, InteractionOutcome, InteractionRecord,
InteractionRequest,
},
model::{ModelToolCall, ToolInput},
tool_call::tool_use_id,
};
use maka_plugin_core::{
composition::InstanceId,
contract::Transport,
deployment::DeploymentRef,
operation::{RecoveryContract, RecoveryProtocol, RecoveryRef},
};
use rusqlite::{Connection, params};
use uuid::Uuid;
struct SeedSession(String, maka_sandbox::workspace::PermissionBasis);
impl Statement for SeedSession {
type Value = ();
type Output = ();
fn execute(&self, c: &Connection) -> Result<Prepared<()>, StoreError> {
let binding = self.1.binding;
c.execute(
"INSERT OR IGNORE INTO workspace_bindings(id,owner_scope,selection_digest,workspace_json,permission_epoch,metadata_epoch) VALUES(?,'scope','digest','{}',?,0)",
params![binding.id.to_string(), binding.permission_epoch as i64],
)?;
let config = serde_json::json!({
"workspace": maka_sandbox::workspace::BindingRef {
id: binding.id,
permission_epoch_at_attach: binding.permission_epoch,
metadata_epoch_at_attach: 0,
},
"boundary_revision": self.1.boundary_revision,
"permissions": { "access": "workspace_write" },
});
c.execute(
"INSERT INTO session_control(id,fingerprint,revision,created_at,updated_at,archived,configuration) VALUES(?,'fp',1,1,1,0,?)",
params![self.0, config.to_string()],
)?;
Ok(Prepared {
value: (),
changed: true,
notification: Notification::NONE,
})
}
fn committed(_: ()) {}
fn isolated_rejection(_: &StoreError) -> bool {
false
}
}
struct SeedTool(RunId, crate::fold::Tool);
impl Statement for SeedTool {
type Value = ();
type Output = ();
fn execute(&self, c: &Connection) -> Result<Prepared<()>, StoreError> {
c.execute(
"INSERT INTO agent_tools(run,key,pending,body) VALUES(?,?,1,?)",
params![
self.0.to_string(),
crate::fold::tool_key(&self.1.key),
serde_json::to_string(&self.1)?,
],
)?;
Ok(Prepared {
value: (),
changed: true,
notification: Notification::NONE,
})
}
fn committed(_: ()) {}
fn isolated_rejection(_: &StoreError) -> bool {
false
}
}
#[tokio::test]
async fn authorized_activity_stays_pinned_across_subsequent_subject_observed() {
let dir = tempfile::tempdir().unwrap();
let (root, store) = open(dir.path(), true).await;
let data = root.data_writer().unwrap();
let (mut run_spec, contents) = spec();
run_spec.session_id = "computer-activity-stability".into();
run_spec.memory_admission = maka_agent_facts::memory::MemoryAdmission::Disabled;
data.write(SeedSession(
run_spec.session_id.clone(),
run_spec.permission_basis,
))
.await
.unwrap();
let admission = Admission::new(run_spec.clone(), UnixMillis(10), contents);
store.admit(admission.clone()).await.unwrap();
let view = store.frontier(admission.run()).await.unwrap();
let claim = store.claim(admission.run()).await.unwrap();
let execution = ExecutionIdentity {
session_id: run_spec.session_id.clone(),
turn_id: run_spec.turn_id.clone(),
run_id: admission.run(),
};
let target = GrantTarget {
provider_id: "computer".into(),
contract_id: "computer_app".into(),
server_id: "local".into(),
tool_name: "cua".into(),
capability: GrantCapability::ComputerUse,
scope: GrantScope::ComputerApp {
platform: ComputerAppPlatform::Macos,
application_id: "com.apple.TextEdit".into(),
},
};
let display = ComputerAppDisplay {
name: "TextEdit".into(),
app_path: "/System/Applications/TextEdit.app".into(),
risk: None,
warning: None,
};
let basis = run_spec.permission_basis;
let tool_key = ToolKey {
attempt: ModelAttemptId::new(),
call: "call-1".into(),
};
let recovery_ref = RecoveryRef {
source: DeploymentRef {
state_domain: "a".repeat(64),
deployment: run_spec.owner.deployment,
revision: 1,
},
namespace: InstanceId(vec![Uuid::new_v4()]),
export: "computer".into(),
method: "exec".into(),
operation: Uuid::new_v4(),
fingerprint: format!("sha256-{}", "0".repeat(64)),
contract: RecoveryContract {
name: "computer.exec".into(),
version: 1,
transport: Transport::Local,
digest: format!("sha256-{}", "0".repeat(64)),
},
recovery: RecoveryProtocol::JournalV1,
};
data.write(SeedTool(
admission.run(),
crate::fold::Tool {
key: tool_key.clone(),
call: ModelToolCall {
id: "call-1".into(),
name: "cua".into(),
input: ToolInput::Json(serde_json::json!({})),
provider_options: None,
provider_executed: false,
},
decision: None,
approval_refusal: None,
original: Some(recovery_ref.clone()),
receipt: None,
provider_result: None,
local_returned: None,
host_returned: None,
prohibited_before_host: None,
admitted: true,
accepted: None,
},
))
.await
.unwrap();
let make_subject = |op: &str, blob: &ContentBlob| Subject {
activity: ComputerAppActivity {
execution: execution.clone(),
operation_id: op.to_owned(),
target: target.clone(),
display: display.clone(),
},
basis,
allow_always: true,
target: AuthorizationObligation::Tool {
tool: tool_key.clone(),
},
operation: recovery_ref.clone(),
capture: blob.reference().clone(),
};
// Observe op-1, then op-2 before either is authorized (simulates concurrent/queued ops).
let blob1 = ContentBlob::json(&serde_json::json!({"op": 1})).unwrap();
store
.computer()
.append(
&claim,
Head::from(&view),
Change {
id: FactId::new(),
at: UnixMillis(11),
fact: Fact::SubjectObserved {
subject: make_subject("op-1", &blob1),
},
},
vec![blob1],
)
.await
.unwrap();
let blob2 = ContentBlob::json(&serde_json::json!({"op": 2})).unwrap();
store
.computer()
.append(
&claim,
Head::from(&view),
Change {
id: FactId::new(),
at: UnixMillis(12),
fact: Fact::SubjectObserved {
subject: make_subject("op-2", &blob2),
},
},
vec![blob2],
)
.await
.unwrap();
// Grant session consent and authorize op-1 first.
let t_id = tool_use_id(admission.run(), &crate::fold::tool_key(&tool_key));
store
.interactions()
.establish(
&claim,
Head::from(&view),
InteractionRecord {
request_id: "req-1".into(),
execution: execution.clone(),
created_at: 13,
request: InteractionRequest::ComputerApp {
tool_use_id: t_id,
native_operation_id: "op-1".into(),
target: target.clone(),
basis,
display: display.clone(),
allow_always: true,
authority_revision: 0,
},
outcome: None,
},
None,
vec![],
)
.await
.unwrap();
store
.interactions()
.commit_outcome(
&run_spec.session_id,
"req-1",
InteractionOutcome::ComputerAppDecision {
decision: ComputerAppDecision::Session,
committed_at: 14,
},
)
.await
.unwrap();
store
.computer()
.append(
&claim,
Head::from(&view),
Change {
id: FactId::new(),
at: UnixMillis(15),
fact: Fact::AppAuthorized {
source_operation: "op-1".into(),
request: Some("req-1".into()),
basis,
},
},
vec![],
)
.await
.unwrap();
let after_auth = store
.computer()
.activities(&run_spec.session_id, &run_spec.owner)
.await
.unwrap();
assert_eq!(after_auth.len(), 1);
assert!(after_auth[0].authorized);
assert_eq!(after_auth[0].subject.activity.operation_id, "op-1");
// Subsequent SubjectObserved for op-3 (before its AppAuthorized) must NOT flicker authorized=false.
let blob3 = ContentBlob::json(&serde_json::json!({"op": 3})).unwrap();
store
.computer()
.append(
&claim,
Head::from(&view),
Change {
id: FactId::new(),
at: UnixMillis(16),
fact: Fact::SubjectObserved {
subject: make_subject("op-3", &blob3),
},
},
vec![blob3],
)
.await
.unwrap();
let after_next_observed = store
.computer()
.activities(&run_spec.session_id, &run_spec.owner)
.await
.unwrap();
assert_eq!(after_next_observed.len(), 1);
assert!(after_next_observed[0].authorized);
assert_eq!(after_next_observed[0].subject.activity.operation_id, "op-1");
// Rebuild preserves the exact same authorized activity.
store.computer().rebuild().await.unwrap();
let after_rebuild = store
.computer()
.activities(&run_spec.session_id, &run_spec.owner)
.await
.unwrap();
assert_eq!(after_rebuild.len(), 1);
assert!(after_rebuild[0].authorized);
assert_eq!(after_rebuild[0].subject.activity.operation_id, "op-1");
}
}