Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
15 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 4 additions & 3 deletions crates/dim-agent-capabilities/src/hooks/sources.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,15 +35,16 @@ impl serde::Serialize for HookSourceId {
}

/// Whether a source's document was read, absent or refused.
#[derive(Clone, Debug, PartialEq, Eq)]
#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize)]
#[serde(rename_all = "camelCase")]
pub enum HookSourceState {
Ok,
Missing,
Invalid(String),
}

/// One source as the port returns it.
#[derive(Clone, Debug)]
#[derive(Clone, Debug, serde::Serialize)]
pub struct HookSourceSnapshot {
pub id: HookSourceId,
/// Where the document lives: the user file, the project file, or a
Expand All @@ -57,7 +58,7 @@ pub struct HookSourceSnapshot {
}

/// Every effective source of one working directory, in catalog order.
#[derive(Clone, Debug, Default)]
#[derive(Clone, Debug, Default, serde::Serialize)]
pub struct HookSourcesSnapshot {
pub sources: Vec<HookSourceSnapshot>,
}
Expand Down
10 changes: 5 additions & 5 deletions crates/dim-agent-scheduler/src/methods.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ use dim_app_server::{
ProcessActivity,
methods::ManagementMethods,
plugin_files::FileScope,
settings::{BusinessDocument, SettingsError, SettingsService},
settings::{BusinessDocument, RegisteredDocument, Settings, SettingsError},
};
use jiff::{SignedDuration, Timestamp};
use rutis::Ctx;
Expand All @@ -43,7 +43,7 @@ pub(crate) type DeliveryHolds =
pub struct SchedulerPlugin {
activity: Key<ProcessActivity>,
pub(crate) deliveries: DeliveryHolds,
settings: Key<SettingsService>,
settings: Key<Settings>,
files: Key<dim_app_server::plugin_files::PluginFiles>,
methods: Key<ManagementMethods>,
sessions: Key<dyn HostDispatch>,
Expand Down Expand Up @@ -113,7 +113,7 @@ impl DynPlugin for SchedulerPlugin {
let files = ctx.require_at(&self.files)?.open(ctx)?;
let methods = ctx.require_at(&self.methods)?;
let sessions = ctx.require_at(&self.sessions)?;
settings.register::<crate::document::ScheduleDocument>(ctx)?;
let settings = settings.register_document::<crate::document::ScheduleDocument>(ctx)?;
let shared = Arc::new(Shared {
ctx: ctx.clone(),
activity,
Expand Down Expand Up @@ -352,7 +352,7 @@ pub(crate) struct Shared {
pub(crate) clock: Arc<dyn Clock>,
pub(crate) deliveries: DeliveryHolds,
pub(crate) sessions: Arc<dyn HostDispatch>,
pub(crate) settings: Arc<SettingsService>,
pub(crate) settings: Arc<RegisteredDocument<crate::document::ScheduleDocument>>,
pub(crate) files: Arc<FileScope>,
/// Serializes retention passes, so a pass never deletes what another reads.
pub(crate) pruning: tokio::sync::Mutex<()>,
Expand Down Expand Up @@ -527,7 +527,7 @@ pub(crate) async fn read_document(
> {
shared
.settings
.read::<crate::document::ScheduleDocument>(SettingsScope::User, cancel)
.read(SettingsScope::User, cancel)
.await
.map_err(read_failure)
}
Expand Down
2 changes: 1 addition & 1 deletion crates/dim-app-server/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,7 @@ not add automatic retry or recovery. See the [CLI submission contract](../../doc
SettingsService reads and updates generic `BusinessDocument` values with per-source
CAS. Business owners define and validate their payloads: MCP types live in
`mcp/config.rs`, and the Skills owner supplies the existing `SkillSettingsHost`.
Each owner registers its sources in its `apply` (`SettingsService::register`, or
Each owner registers its sources in its `apply` (`Settings::register_document` for a native `BusinessDocument`, or
`register` on the named `settings` service); a source is served only while its
owner is loaded, and its stored document stays when the owner unloads.
Settings owns source persistence, not approvals or business management methods.
Expand Down
8 changes: 4 additions & 4 deletions crates/dim-app-server/src/agents.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use crate::{
ProcessActivity, ProcessHold, ServerConfig,
protocol::{AgentInfo, CreateWorktree, SessionOrigin},
settings::SettingsService,
settings::Settings,
storage::{PreparedWorktree, SessionMetadataService, SessionStore, SqliteStorage, Store},
worktrees::{CreatedWorktree, ManagedWorktrees, WorktreeError},
};
Expand Down Expand Up @@ -393,7 +393,7 @@ pub struct AgentIndex {
records: Option<Arc<SqliteStorage>>,
session_store: Option<Arc<Store>>,
session_metadata: Option<Arc<SessionMetadataService>>,
settings: Option<Arc<SettingsService>>,
settings: Option<Arc<Settings>>,
stopping: CancellationToken,
/// Notified once an `idle` call on this generation is admitted and
/// waiting on its branch. Feature `testing` only.
Expand Down Expand Up @@ -2142,7 +2142,7 @@ pub(crate) struct AgentsPlugin {
/// Native storage only with a database.
stored: Option<StoredKeys>,
/// Settings only with local execution.
settings: Option<Key<SettingsService>>,
settings: Option<Key<Settings>>,
loader: Key<Loader>,
directory: Key<AgentDirectory>,
activity: Key<ProcessActivity>,
Expand All @@ -2163,7 +2163,7 @@ impl AgentsPlugin {
.transpose()?,
settings: config
.local_execution()
.then(|| names.key::<SettingsService>())
.then(|| names.key::<Settings>())
.transpose()?,
loader: names.key()?,
directory: Key::of(),
Expand Down
2 changes: 1 addition & 1 deletion crates/dim-app-server/src/cli.rs
Original file line number Diff line number Diff line change
Expand Up @@ -585,7 +585,7 @@ pub fn run_with(
dim_agent_capabilities::timeline_tree::BranchToolConfig::default(),
);
permission_rules::install(&mut builder);
hooks_settings::install(&mut builder, config.product_home.clone());
hooks_settings::install(&mut builder);
dim_agent_capabilities::hooks::install(&mut builder);
crate::session_grants::install(&mut builder);
dim_agent_capabilities::file_access::install(&mut builder);
Expand Down
28 changes: 13 additions & 15 deletions crates/dim-app-server/src/collaboration.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,9 @@ mod pending;
pub use approvals::ApprovalDestination;

use crate::agents::{AgentIndex, AgentProfile, SessionRestored, UnloadedSessionDeleted};
use crate::collaboration_model_policy::ModelPolicy;
use crate::collaboration_model_policy::{CollaborationModelPolicy, ModelPolicy};
use crate::protocol::SessionOrigin;
use crate::settings::{SettingsScope, SettingsService};
use crate::settings::{Settings, SettingsError};
use dim_agent_capabilities::{
context_block,
host::{
Expand Down Expand Up @@ -230,7 +230,7 @@ pub struct Collaboration {
index: Arc<AgentIndex>,
directory: Arc<CollaborationDirectory>,
/// The subagent model policy's source; local execution only.
settings: Option<Arc<SettingsService>>,
policy_owner: Option<Ctx>,
tasks: TaskTracker,
stop: CancellationToken,
#[cfg(feature = "testing")]
Expand Down Expand Up @@ -279,14 +279,15 @@ impl Collaboration {
.as_ref()
.and_then(|model| model.metadata.as_ref())
.is_some_and(|metadata| metadata.startup.is_some());
let policy = match &self.settings {
let policy = match &self.policy_owner {
_ if startup => ModelPolicy::Inherit {},
Some(settings) => {
settings
.read::<ModelPolicy>(SettingsScope::User, &self.stop)
Some(ctx) => {
ctx.get::<CollaborationModelPolicy>()
.ok_or_else(|| member_create_failed(SettingsError::UnknownSource.to_string()))?
.read(&self.stop)
.await
.map_err(|error| member_create_failed(error.to_string()))?
.document
.policy
}
None => ModelPolicy::Agent {},
};
Expand Down Expand Up @@ -719,7 +720,7 @@ impl Collaboration {
/// with it, and the Session and branch parts it registers.
pub(crate) struct CollaborationPlugin {
/// The subagent model policy's source; local execution only, as Agents.
settings: Option<Key<SettingsService>>,
settings: Option<Key<Settings>>,
index: Key<AgentIndex>,
directory: Key<CollaborationDirectory>,
parts: Key<dim_agent_runtime::PartRegistry>,
Expand All @@ -728,7 +729,7 @@ impl CollaborationPlugin {
pub fn new(names: &Names<'_>, local_execution: bool) -> rutis::Result<Self> {
Ok(Self {
settings: local_execution
.then(|| names.key::<SettingsService>())
.then(|| names.key::<Settings>())
.transpose()?,
index: names.key()?,
directory: names.key()?,
Expand All @@ -754,14 +755,11 @@ impl DynPlugin for CollaborationPlugin {
let index = ctx.require_at(&self.index)?;
let directory = ctx.require_at(&self.directory)?;
let parts = ctx.require_at(&self.parts)?;
let settings = match &self.settings {
Some(settings) => Some(ctx.require_at(settings)?),
None => None,
};
let policy_owner = self.settings.as_ref().map(|_| ctx.clone());
let service = Arc::new(Collaboration {
index,
directory,
settings,
policy_owner,
tasks: TaskTracker::new(),
stop: CancellationToken::new(),
#[cfg(feature = "testing")]
Expand Down
80 changes: 65 additions & 15 deletions crates/dim-app-server/src/collaboration_model_policy.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
use crate::{
methods::ManagementMethods,
protocol::Empty,
settings::{BusinessDocument, SettingsError, SettingsScope, SettingsService},
settings::{BusinessDocument, RegisteredDocument, Settings, SettingsError, SettingsScope},
};
use dim_agent_capabilities::methods::{
Interruption, MethodCall, MethodDecl, RpcError, params, reply,
Expand Down Expand Up @@ -73,15 +73,65 @@ struct SetPolicy {
policy: ModelPolicy,
}
#[derive(Serialize)]
struct PolicyView {
pub(crate) struct PolicyView {
revision: String,
policy: ModelPolicy,
pub(crate) policy: ModelPolicy,
}
#[derive(Serialize)]
struct Revision {
revision: String,
}

#[derive(Clone)]
pub(crate) struct CollaborationModelPolicy(Arc<RegisteredDocument<ModelPolicy>>);

impl CollaborationModelPolicy {
pub(crate) async fn read(
&self,
cancel: &tokio_util::sync::CancellationToken,
) -> crate::settings::Result<PolicyView> {
let snapshot = self.0.read(SettingsScope::User, cancel).await?;
Ok(PolicyView {
revision: snapshot.revision,
policy: snapshot.document,
})
}
}

impl rutis_bridge::session::HostDispatch for CollaborationModelPolicy {
fn methods(&self) -> Option<serde_json::Value> {
Some(serde_json::json!({"read":"async"}))
}
fn invoke(
&self,
method: &str,
args: rutis_bridge::session::Value,
) -> rutis_bridge::session::Reply {
use rutis_bridge::session::{Error, Value};
if method != "read" {
return Err(Error::value(format!(
"unknown collaborationModelPolicy method {method}"
)));
}
let (_request,): (Empty,) = serde_json::from_value(args.json()?)
.map_err(|_| Error::value("expected one empty request"))?;
let owner = self.clone();
Ok(Value::future(async move {
let cancel = tokio_util::sync::CancellationToken::new();
let _guard = cancel.clone().drop_guard();
let view = owner.read(&cancel).await.map_err(|error| {
rutis_bridge::exports::failure(
"collaborationModelPolicy",
error.code(),
error.to_string(),
None,
)
})?;
rutis_bridge::session::arg(&view)
}))
}
}

fn error(error: SettingsError) -> RpcError {
let kind = match &error {
SettingsError::Closed => return RpcError::reloading(),
Expand All @@ -95,7 +145,7 @@ fn error(error: SettingsError) -> RpcError {
/// Process owner of the `collaboration` source and its management methods,
/// apart from Collaboration so it reloads without unloading Rpc.
pub struct CollaborationModelPolicyPlugin {
settings: Key<SettingsService>,
settings: Key<Settings>,
methods: Key<ManagementMethods>,
}
impl CollaborationModelPolicyPlugin {
Expand All @@ -117,7 +167,13 @@ impl DynPlugin for CollaborationModelPolicyPlugin {
Box::pin(async move {
let settings = ctx.require_at(&self.settings)?;
let methods = ctx.require_at(&self.methods)?;
settings.register::<ModelPolicy>(ctx)?;
let settings = settings.register_document::<ModelPolicy>(ctx)?;
let owner = Arc::new(CollaborationModelPolicy(settings));
ctx.provide_as::<CollaborationModelPolicy>(owner.clone())?;
ctx.provide_at::<dyn rutis_bridge::session::HostDispatch>(
rutis_bridge::session::host_key("collaborationModelPolicy"),
owner.clone(),
)?;
methods.register(
ctx,
"collaboration",
Expand All @@ -140,26 +196,20 @@ impl DynPlugin for CollaborationModelPolicyPlugin {
params: value,
..
} = call;
let settings = settings.clone();
let owner = owner.clone();
Box::pin(async move {
match method.as_str() {
"collaboration.model_policy" => {
let _: Empty = params(value)?;
let snapshot = settings
.read::<ModelPolicy>(SettingsScope::User, &stopping)
.await
.map_err(error)?;
reply(PolicyView {
revision: snapshot.revision,
policy: snapshot.document,
})
reply(owner.read(&stopping).await.map_err(error)?)
}
"collaboration.set_model_policy" => {
let p: SetPolicy = params(value)?;
if let Err(SettingsError::Invalid(reason)) = p.policy.validate() {
return Err(RpcError::invalid(reason));
}
let snapshot = settings
let snapshot = owner
.0
.update(
SettingsScope::User,
&p.expected_revision,
Expand Down
Loading