blob: 1fafc28813fe5873c8a70244c09afcbd4ca4ff77 [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.
*/
//! File-driven reusable Agent Role definitions and immutable session snapshots.
use crate::contract::{BackendPreference, WorkspaceAccess, WorkspaceSelection};
use crate::executor::Selection as ExecutorSelection;
use maka_agent_facts::execution::ThinkingLevel;
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
/// Lowercase ASCII role slug matching `<slug>.md` inside an agents directory.
#[derive(
Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize, JsonSchema,
)]
#[serde(transparent)]
pub struct RoleSlug(#[schemars(length(min = 1, max = 64))] pub String);
impl RoleSlug {
pub fn parse(raw: &str) -> Result<Self, &'static str> {
let trimmed = raw.trim();
if trimmed.is_empty() || trimmed.len() > 64 {
return Err("invalid_role_slug");
}
let mut chars = trimmed.chars();
let Some(first) = chars.next() else {
return Err("invalid_role_slug");
};
if !first.is_ascii_lowercase() && !first.is_ascii_digit() {
return Err("invalid_role_slug");
}
if !chars.all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-' || c == '_') {
return Err("invalid_role_slug");
}
Ok(Self(trimmed.to_owned()))
}
pub fn as_str(&self) -> &str {
&self.0
}
/// Derive a valid deterministic slug from a human-readable display name.
pub fn from_name(name: &str) -> Self {
let mut slug = String::new();
let mut last_dash = true;
for ch in name.trim().chars() {
let lower = ch.to_ascii_lowercase();
if lower.is_ascii_lowercase() || lower.is_ascii_digit() {
slug.push(lower);
last_dash = false;
} else if !last_dash && !slug.is_empty() {
slug.push('-');
last_dash = true;
}
if slug.len() >= 48 {
break;
}
}
while slug.ends_with('-') {
slug.pop();
}
if Self::parse(&slug).is_ok() {
return Self(slug);
}
// Deterministic fallback for non-ASCII names (e.g. pure CJK).
let mut hash: u64 = 0xcbf29ce484222325;
for byte in name.as_bytes() {
hash ^= u64::from(*byte);
hash = hash.wrapping_mul(0x100000001b3);
}
Self(format!("role-{hash:08x}"))
}
}
impl std::fmt::Display for RoleSlug {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(&self.0)
}
}
/// Standard user/project role directories ordered from highest to lowest precedence.
#[derive(
Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize, JsonSchema,
)]
pub enum RoleLocation {
#[serde(rename = "project:maka")]
ProjectMaka,
#[serde(rename = "project:agents")]
ProjectAgents,
#[serde(rename = "user:maka")]
UserMaka,
#[serde(rename = "user:agents")]
UserAgents,
}
impl RoleLocation {
pub const ALL: [Self; 4] = [
Self::ProjectMaka,
Self::ProjectAgents,
Self::UserMaka,
Self::UserAgents,
];
pub fn scope(self) -> RoleScope {
match self {
Self::ProjectMaka | Self::ProjectAgents => RoleScope::Project,
Self::UserMaka | Self::UserAgents => RoleScope::User,
}
}
pub fn is_project(self) -> bool {
matches!(self.scope(), RoleScope::Project)
}
pub fn root_dir(self) -> &'static str {
match self {
Self::ProjectMaka | Self::UserMaka => ".maka",
Self::ProjectAgents | Self::UserAgents => ".agents",
}
}
pub fn directory(self) -> &'static str {
match self {
Self::ProjectMaka | Self::UserMaka => ".maka/agents",
Self::ProjectAgents | Self::UserAgents => ".agents/agents",
}
}
pub fn display_path(self, slug: &RoleSlug) -> String {
match self.scope() {
RoleScope::Project => format!("{}/{}.md", self.directory(), slug.as_str()),
RoleScope::User => format!("~/{}/{}.md", self.directory(), slug.as_str()),
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum RoleScope {
Project,
User,
}
/// Safe declarative workspace access bound for a role.
/// Role files can narrow permissions but can never escalate beyond the caller/Host ceiling.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum RolePermissions {
#[default]
Inherit,
ReadOnly,
WorkspaceWrite,
}
impl RolePermissions {
/// Apply this role's declarative bound without ever escalating past `ceiling`.
pub fn clip(self, ceiling: WorkspaceAccess) -> WorkspaceAccess {
match self {
Self::Inherit => ceiling,
Self::ReadOnly => WorkspaceAccess::ReadOnly,
Self::WorkspaceWrite => match ceiling {
WorkspaceAccess::ReadOnly => WorkspaceAccess::ReadOnly,
WorkspaceAccess::WorkspaceWrite | WorkspaceAccess::DangerFullAccess => {
WorkspaceAccess::WorkspaceWrite
}
},
}
}
}
/// Default workspace isolation strategy when creating a session from this role.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum RoleWorkspace {
#[default]
Same,
Worktree,
}
/// Optional execution target declared in a role file.
/// Supports both native models (portable connection slug or ID) and external executors.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(tag = "kind", rename_all = "camelCase", deny_unknown_fields)]
pub enum RoleBackend {
Model {
/// Connection slug (preferred for portability) or connection ID.
connection: String,
#[serde(rename = "modelId")]
model_id: String,
#[serde(
default,
skip_serializing_if = "Option::is_none",
rename = "serviceTier"
)]
service_tier: Option<String>,
#[serde(
default,
skip_serializing_if = "Option::is_none",
rename = "thinkingLevel"
)]
thinking_level: Option<ThinkingLevel>,
},
Executor {
selection: ExecutorSelection,
},
}
/// Human-readable resolution of a role's optional backend for UIs and prompts.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct RoleBackendDisplay {
pub label: String,
pub source_name: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub thinking_level: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub service_tier: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub backend: Option<BackendPreference>,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(tag = "kind", rename_all = "camelCase", deny_unknown_fields)]
pub enum RoleAvailability {
Available,
Disabled,
BackendUnavailable,
ThinkingLevelUnavailable,
InvalidFile { message: String },
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct RoleSummary {
pub slug: RoleSlug,
pub location: RoleLocation,
pub scope: RoleScope,
pub path: String,
pub name: String,
pub description: String,
pub enabled: bool,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub backend: Option<RoleBackend>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub backend_display: Option<RoleBackendDisplay>,
pub permissions: RolePermissions,
pub workspace: RoleWorkspace,
#[serde(default)]
pub skills: Vec<String>,
pub availability: RoleAvailability,
#[serde(default)]
pub overridden: bool,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct RoleDetail {
pub summary: RoleSummary,
pub instruction: String,
pub digest: String,
}
#[derive(Clone, Debug, Default, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct RolesRead {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub session_id: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub workspace: Option<WorkspaceSelection>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct RolesView {
pub revision: u64,
pub roles: Vec<RoleSummary>,
pub writable_locations: Vec<RoleLocation>,
}
#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct RoleRead {
pub slug: RoleSlug,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub location: Option<RoleLocation>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub session_id: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub workspace: Option<WorkspaceSelection>,
}
#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct RoleSave {
pub slug: RoleSlug,
pub location: RoleLocation,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub session_id: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub workspace: Option<WorkspaceSelection>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub expected_digest: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub rename_from: Option<RoleSlug>,
pub name: String,
#[serde(default)]
pub description: String,
#[serde(default)]
pub instruction: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub backend: Option<RoleBackend>,
#[serde(default)]
pub permissions: RolePermissions,
#[serde(default)]
pub workspace_mode: RoleWorkspace,
#[serde(default)]
pub skills: Vec<String>,
#[serde(default = "default_enabled")]
pub enabled: bool,
}
fn default_enabled() -> bool {
true
}
#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct RoleDelete {
pub slug: RoleSlug,
pub location: RoleLocation,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub session_id: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub workspace: Option<WorkspaceSelection>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub expected_digest: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(
tag = "kind",
rename_all = "camelCase",
rename_all_fields = "camelCase",
deny_unknown_fields
)]
pub enum RoleResult {
Saved {
role: RoleDetail,
},
Deleted {
slug: RoleSlug,
location: RoleLocation,
},
NotFound,
Conflict {
actual_digest: String,
},
SlugConflict,
InvalidInput {
field: String,
},
LocationUnavailable,
PermissionDenied,
BackendUnavailable,
ThinkingLevelUnavailable,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "camelCase")]
pub enum AgentRoleToolAction {
List,
Read,
Save,
Delete,
}
/// Lean agent-facing tool input for reading or managing file-driven Agent Roles.
#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct AgentRoleToolInput {
pub action: AgentRoleToolAction,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub slug: Option<RoleSlug>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub location: Option<RoleLocation>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub expected_digest: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub rename_from: Option<RoleSlug>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
#[serde(default)]
pub description: String,
#[serde(default)]
pub instruction: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub backend: Option<RoleBackend>,
#[serde(default)]
pub permissions: RolePermissions,
#[serde(default)]
pub workspace_mode: RoleWorkspace,
#[serde(default)]
pub skills: Vec<String>,
#[serde(default = "default_enabled")]
pub enabled: bool,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(
tag = "kind",
rename_all = "camelCase",
rename_all_fields = "camelCase",
deny_unknown_fields
)]
pub enum AgentRoleToolOutput {
Listed {
roles: Vec<RoleSummary>,
writable_locations: Vec<RoleLocation>,
},
Read {
role: Option<RoleDetail>,
},
Result {
result: RoleResult,
},
}
/// Immutable role snapshot frozen when a session is created from a Role.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct AppliedRole {
pub slug: RoleSlug,
pub name: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub location: Option<RoleLocation>,
#[serde(default)]
pub description: String,
#[serde(default)]
pub instruction: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub backend: Option<BackendPreference>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub backend_label: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub backend_source_name: Option<String>,
#[serde(default)]
pub permissions: RolePermissions,
#[serde(default)]
pub workspace: RoleWorkspace,
#[serde(default)]
pub skills: Vec<String>,
}