use std::sync::Arc;
use async_trait::async_trait;
use multicast::cli::Cli;
use multicast::command::{
CommandContext, CommandDef, CommandHandler, McpAnnotations, McpCommandOptions,
};
use multicast::output::CommandResult;
use multicast::schema::{FieldMeta, FieldType};
use serde_json::{Value, json};
use crate::database::{Connection, OptionalExtension, params};
use crate::{State, WorkflowDatabase, WorkflowDatabaseKind, error, field, ok, string_arg};
pub const ARCHETYPES_GROUP_NAME: &str = "archetypes";
const MAX_INSTRUCTIONS_BYTES: usize = 64 * 1024;
const MAX_SCOPE: usize = 256;
#[derive(Debug, Clone)]
pub(crate) struct ShippedArchetype {
pub(crate) name: String,
pub(crate) summary: String,
pub(crate) instructions: String,
pub(crate) scope: Vec<String>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct Archetype {
pub(crate) name: String,
pub(crate) summary: String,
pub(crate) instructions: String,
pub(crate) scope: Vec<String>,
pub(crate) origin: &'static str,
}
impl Archetype {
pub(crate) fn shipped(archetype: &ShippedArchetype) -> Self {
Self {
name: archetype.name.clone(),
summary: archetype.summary.clone(),
instructions: archetype.instructions.clone(),
scope: archetype.scope.clone(),
origin: "shipped",
}
}
pub(crate) fn summary_json(&self) -> Value {
json!({
"name": self.name,
"summary": self.summary,
"origin": self.origin,
"scope": self.scope,
})
}
pub(crate) fn detail_json(&self) -> Value {
let mut data = self.summary_json();
data["instructions"] = Value::String(self.instructions.clone());
data
}
}
pub(crate) const TASK_DESCRIPTION: &str =
"The specific task to focus on; echoed back with the guidance";
pub(crate) fn activation_output_schema() -> Value {
json!({
"type": "object",
"properties": {
"archetype": {"type": "string"},
"origin": {"type": "string", "enum": ["shipped", "saved"]},
"summary": {"type": "string"},
"guidance": {"type": "string"},
"task": {"type": ["string", "null"]},
"tools": {"type": "array", "items": {"type": "object"}},
"workflows": {"type": "array", "items": {"type": "object"}},
"unavailable": {"type": "array", "items": {"type": "string"}}
},
"required": ["archetype", "origin", "summary", "guidance", "task", "tools", "workflows", "unavailable"]
})
}
pub(crate) fn check_definition(
name: &str,
summary: &str,
instructions: &str,
scope: &[String],
) -> Result<(), String> {
if name.trim().is_empty() || name.chars().any(char::is_whitespace) {
return Err("Archetype name must be non-empty and contain no whitespace".into());
}
if summary.trim().is_empty() {
return Err(format!("Archetype '{name}' needs a summary"));
}
if instructions.trim().is_empty() {
return Err(format!("Archetype '{name}' needs instructions"));
}
if instructions.len() > MAX_INSTRUCTIONS_BYTES {
return Err(format!(
"Archetype '{name}' instructions exceed {MAX_INSTRUCTIONS_BYTES} bytes"
));
}
if scope.is_empty() {
return Err(format!(
"Archetype '{name}' must scope at least one command or workflow"
));
}
if scope.len() > MAX_SCOPE {
return Err(format!(
"Archetype '{name}' scopes more than {MAX_SCOPE} entries"
));
}
let mut seen = std::collections::BTreeSet::new();
for entry in scope {
if !seen.insert(entry.as_str()) {
return Err(format!("Archetype '{name}' scopes '{entry}' twice"));
}
}
Ok(())
}
pub(crate) fn parse_scope(value: Option<&Value>) -> Result<Vec<String>, String> {
let entries: Vec<String> = match value {
None | Some(Value::Null) => Vec::new(),
Some(Value::String(text)) => text.split(',').map(str::to_string).collect(),
Some(Value::Array(items)) => items
.iter()
.map(|item| {
item.as_str()
.map(str::to_string)
.ok_or_else(|| "--tools entries must be strings".to_string())
})
.collect::<Result<_, _>>()?,
Some(_) => return Err("--tools must be a comma-separated list".into()),
};
Ok(entries
.into_iter()
.flat_map(|entry| {
entry
.split(',')
.map(|part| part.trim().to_string())
.collect::<Vec<_>>()
})
.filter(|entry| !entry.is_empty())
.collect())
}
pub(crate) struct ArchetypeStore {
connection: Connection,
}
impl ArchetypeStore {
pub(crate) fn from_database(database: Arc<dyn WorkflowDatabase>) -> Result<Self, String> {
Self::initialize(Connection::new(database))
}
fn initialize(connection: Connection) -> Result<Self, String> {
connection
.execute_batch(
"CREATE TABLE IF NOT EXISTS incurs_archetypes(\
name TEXT PRIMARY KEY, summary TEXT NOT NULL, instructions TEXT NOT NULL, \
scope TEXT NOT NULL, created_at INTEGER NOT NULL)",
)
.map_err(|error| error.to_string())?;
Ok(Self { connection })
}
#[cfg(all(feature = "native", not(target_arch = "wasm32")))]
pub(crate) fn open(path: &std::path::Path) -> Result<Self, String> {
if let Some(parent) = path.parent() {
std::fs::create_dir_all(parent)
.map_err(|error| format!("Cannot create archetype store directory: {error}"))?;
}
let connection = Connection::open(path).map_err(|error| error.to_string())?;
Self::initialize(connection)
}
pub(crate) fn list(&self) -> Result<Vec<Archetype>, String> {
let statement = self
.connection
.prepare(
"SELECT name, summary, instructions, scope FROM incurs_archetypes ORDER BY name",
)
.map_err(|error| error.to_string())?;
statement
.query_map(vec![], row_archetype)
.map_err(|error| error.to_string())?
.map(|row| row.map_err(|error| error.to_string()))
.collect()
}
pub(crate) fn get(&self, name: &str) -> Result<Option<Archetype>, String> {
self.connection
.query_row(
"SELECT name, summary, instructions, scope FROM incurs_archetypes WHERE name=?",
params![name],
row_archetype,
)
.optional()
.map_err(|error| error.to_string())
}
pub(crate) fn save(&self, archetype: &Archetype, at: u64) -> Result<(), String> {
let scope = serde_json::to_string(&archetype.scope).map_err(|error| error.to_string())?;
self.connection
.execute(
"INSERT INTO incurs_archetypes(name, summary, instructions, scope, created_at) \
VALUES (?,?,?,?,?) ON CONFLICT(name) DO UPDATE SET \
summary=excluded.summary, instructions=excluded.instructions, scope=excluded.scope",
params![
archetype.name,
archetype.summary,
archetype.instructions,
scope,
at
],
)
.map(|_| ())
.map_err(|error| error.to_string())
}
pub(crate) fn delete(&self, name: &str) -> Result<bool, String> {
self.connection
.execute("DELETE FROM incurs_archetypes WHERE name=?", params![name])
.map(|changed| changed > 0)
.map_err(|error| error.to_string())
}
}
fn row_archetype(row: &crate::database::Row) -> crate::database::Result<Archetype> {
let scope: String = row.get(3)?;
Ok(Archetype {
name: row.get(0)?,
summary: row.get(1)?,
instructions: row.get(2)?,
scope: serde_json::from_str(&scope).map_err(|error| error.to_string())?,
origin: "saved",
})
}
enum ScopeTarget {
Command,
Workflow,
}
impl State {
pub(crate) fn archetype_store(&self) -> Result<&ArchetypeStore, String> {
self.archetype_store
.get_or_init(|| {
if let Some(host) = &self.host {
return host
.database(WorkflowDatabaseKind::Archetypes)
.and_then(ArchetypeStore::from_database);
}
#[cfg(all(feature = "native", not(target_arch = "wasm32")))]
{
ArchetypeStore::open(&self.store_path.with_extension("archetypes.sqlite"))
}
#[cfg(not(all(feature = "native", not(target_arch = "wasm32"))))]
{
Err("A workflow host is required".into())
}
})
.as_ref()
.map_err(Clone::clone)
}
pub(crate) fn catalog_archetypes(&self) -> Result<Vec<Archetype>, String> {
let mut archetypes: Vec<Archetype> =
self.archetypes.values().map(Archetype::shipped).collect();
for saved in self.archetype_store()?.list()? {
if !self.archetypes.contains_key(&saved.name) {
archetypes.push(saved);
}
}
Ok(archetypes)
}
pub(crate) fn resolve_archetype(&self, name: &str) -> Result<Option<Archetype>, String> {
if let Some(archetype) = self.archetypes.get(name) {
return Ok(Some(Archetype::shipped(archetype)));
}
self.archetype_store()?.get(name)
}
async fn scope_target(&self, entry: &str) -> Result<Option<ScopeTarget>, String> {
if self.catalog.get(entry).is_some() {
return Ok(Some(ScopeTarget::Command));
}
Ok(self.resolve(entry).await?.map(|_| ScopeTarget::Workflow))
}
pub(crate) async fn check_saved_scope(&self, scope: &[String]) -> Result<(), String> {
let saved: Vec<String> = self
.archetype_store()?
.list()?
.into_iter()
.map(|archetype| archetype.name)
.collect();
for entry in scope {
if self.archetypes.contains_key(entry) || saved.contains(entry) {
return Err(format!(
"'{entry}' is an archetype; an archetype scopes commands and workflows only"
));
}
if self.scope_target(entry).await?.is_none() {
return Err(format!(
"'{entry}' is not a command or workflow of '{}'",
self.catalog.name()
));
}
}
Ok(())
}
pub(crate) async fn missing_scope(&self, archetype: &Archetype) -> Result<Vec<String>, String> {
let mut missing = Vec::new();
for entry in &archetype.scope {
if self.scope_target(entry).await?.is_none() {
missing.push(entry.clone());
}
}
Ok(missing)
}
pub(crate) async fn activate(
&self,
archetype: &Archetype,
task: Option<&str>,
) -> Result<Value, String> {
let mut tools = Vec::new();
let mut workflows = Vec::new();
let mut unavailable = Vec::new();
for entry in &archetype.scope {
if let Some(definition) = self.catalog.get(entry) {
let mut tool = json!({
"name": definition.name,
"description": definition.description,
"inputSchema": definition.input_schema,
});
if let Some(schema) = &definition.output_schema {
tool["outputSchema"] = schema.clone();
}
if let Some(annotations) = &definition.annotations {
tool["annotations"] = annotations_json(annotations);
}
tools.push(tool);
} else if let Some(workflow) = self.resolve(entry).await? {
workflows.push(json!({
"name": workflow.name,
"description": workflow.description,
"origin": workflow.origin,
"inputSchema": workflow.input_schema,
}));
} else {
unavailable.push(entry.clone());
}
}
Ok(json!({
"archetype": archetype.name,
"origin": archetype.origin,
"summary": archetype.summary,
"guidance": archetype.instructions,
"task": task,
"tools": tools,
"workflows": workflows,
"unavailable": unavailable,
}))
}
}
fn annotations_json(annotations: &McpAnnotations) -> Value {
let mut wire = serde_json::Map::new();
if let Some(title) = &annotations.title {
wire.insert("title".into(), json!(title));
}
for (key, hint) in [
("readOnlyHint", annotations.read_only_hint),
("destructiveHint", annotations.destructive_hint),
("idempotentHint", annotations.idempotent_hint),
("openWorldHint", annotations.open_world_hint),
] {
if let Some(hint) = hint {
wire.insert(key.into(), Value::Bool(hint));
}
}
Value::Object(wire)
}
pub(crate) fn now_ms() -> u64 {
web_time::SystemTime::now()
.duration_since(web_time::UNIX_EPOCH)
.map_or(0, |elapsed| elapsed.as_millis() as u64)
}
fn task_option() -> FieldMeta {
field("task", FieldType::String, false, Some(TASK_DESCRIPTION))
}
fn read_only() -> McpAnnotations {
McpAnnotations {
read_only_hint: Some(true),
destructive_hint: Some(false),
idempotent_hint: Some(true),
open_world_hint: Some(false),
title: None,
}
}
pub(crate) fn shipped_command(state: Arc<State>, archetype: &ShippedArchetype) -> CommandDef {
let mut def = CommandDef::build(
archetype.name.clone(),
ShippedArchetypeHandler {
state,
name: archetype.name.clone(),
},
)
.description(archetype.summary.clone())
.mcp(McpCommandOptions {
enabled: true,
annotations: Some(read_only()),
..McpCommandOptions::default()
})
.done();
def.options_fields = vec![task_option()];
def.output_schema = Some(activation_output_schema());
def
}
struct ShippedArchetypeHandler {
state: Arc<State>,
name: String,
}
#[async_trait]
impl CommandHandler for ShippedArchetypeHandler {
async fn run(&self, ctx: CommandContext) -> CommandResult {
let Some(archetype) = self.state.archetypes.get(&self.name) else {
return archetype_not_found(&self.name);
};
let task = string_arg(&ctx.options, "task");
match self
.state
.activate(&Archetype::shipped(archetype), task)
.await
{
Ok(data) => ok(data),
Err(message) => error("WORKFLOW_HOST_ERROR", message),
}
}
}
fn archetype_not_found(name: &str) -> CommandResult {
error(
"ARCHETYPE_NOT_FOUND",
format!("No archetype named '{name}'"),
)
}
#[derive(Clone, Copy)]
enum ArchetypeAction {
List,
Show,
Activate,
Save,
Delete,
}
struct ArchetypeGroupHandler {
state: Arc<State>,
action: ArchetypeAction,
}
#[async_trait]
impl CommandHandler for ArchetypeGroupHandler {
async fn run(&self, ctx: CommandContext) -> CommandResult {
match self.dispatch(&ctx).await {
Ok(result) => result,
Err(message) => error("WORKFLOW_HOST_ERROR", message),
}
}
}
impl ArchetypeGroupHandler {
async fn dispatch(&self, ctx: &CommandContext) -> Result<CommandResult, String> {
let state = &self.state;
let name = string_arg(&ctx.args, "name").unwrap_or_default();
Ok(match self.action {
ArchetypeAction::List => ok(Value::Array(
state
.catalog_archetypes()?
.iter()
.map(Archetype::summary_json)
.collect(),
)),
ArchetypeAction::Show => match state.resolve_archetype(name)? {
Some(archetype) => ok(archetype.detail_json()),
None => archetype_not_found(name),
},
ArchetypeAction::Activate => match state.resolve_archetype(name)? {
Some(archetype) => ok(state
.activate(&archetype, string_arg(&ctx.options, "task"))
.await?),
None => archetype_not_found(name),
},
ArchetypeAction::Save => {
if state.archetypes.contains_key(name) {
return Ok(error(
"ARCHETYPE_SHIPPED",
format!("'{name}' is a shipped archetype and cannot be replaced"),
));
}
if state.catalog.get(name).is_some() || state.shipped.contains_key(name) {
return Ok(error(
"INVALID_ARCHETYPE",
format!(
"'{name}' is already a command of '{}'",
state.catalog.name()
),
));
}
let scope = match parse_scope(ctx.options.get("tools")) {
Ok(scope) => scope,
Err(message) => return Ok(error("INVALID_ARCHETYPE", message)),
};
let archetype = Archetype {
name: name.to_string(),
summary: string_arg(&ctx.options, "summary")
.unwrap_or_default()
.to_string(),
instructions: string_arg(&ctx.options, "instructions")
.unwrap_or_default()
.to_string(),
scope,
origin: "saved",
};
if let Err(message) = check_definition(
&archetype.name,
&archetype.summary,
&archetype.instructions,
&archetype.scope,
) {
return Ok(error("INVALID_ARCHETYPE", message));
}
if let Err(message) = state.check_saved_scope(&archetype.scope).await {
return Ok(error("INVALID_ARCHETYPE", message));
}
state.archetype_store()?.save(&archetype, now_ms())?;
ok(archetype.detail_json())
}
ArchetypeAction::Delete => {
if state.archetypes.contains_key(name) {
return Ok(error(
"ARCHETYPE_SHIPPED",
format!("'{name}' is a shipped archetype and cannot be deleted"),
));
}
if state.archetype_store()?.delete(name)? {
ok(json!({ "deleted": name }))
} else {
archetype_not_found(name)
}
}
})
}
}
pub(crate) fn group(state: Arc<State>) -> Cli {
let effectful = McpAnnotations {
read_only_hint: Some(false),
destructive_hint: Some(false),
idempotent_hint: Some(true),
open_world_hint: Some(false),
title: None,
};
let destructive = McpAnnotations {
destructive_hint: Some(true),
..effectful.clone()
};
let name_arg = || field("name", FieldType::String, true, Some("Archetype name"));
let command = |name: &str,
action: ArchetypeAction,
description: &str,
annotations: McpAnnotations,
options: Vec<FieldMeta>| {
let destructive = annotations.destructive_hint == Some(true);
let mut def = CommandDef::build(
name,
ArchetypeGroupHandler {
state: state.clone(),
action,
},
)
.description(description)
.mcp(McpCommandOptions {
enabled: true,
annotations: Some(annotations),
..McpCommandOptions::default()
})
.destructive(destructive)
.done();
def.options_fields = options;
def
};
let mut list = command(
"list",
ArchetypeAction::List,
"List shipped and saved archetypes",
read_only(),
Vec::new(),
);
list.args_fields = Vec::new();
let mut show = command(
"show",
ArchetypeAction::Show,
"Show an archetype's summary, instructions, and scope",
read_only(),
Vec::new(),
);
show.args_fields = vec![name_arg()];
let mut activate = command(
"activate",
ArchetypeAction::Activate,
"Focus on a task: return an archetype's guidance and its scoped commands and workflows",
read_only(),
vec![task_option()],
);
activate.args_fields = vec![name_arg()];
activate.output_schema = Some(activation_output_schema());
let mut save = command(
"save",
ArchetypeAction::Save,
"Save an archetype: a summary, instructions, and the commands and workflows it uses",
effectful,
vec![
field(
"summary",
FieldType::String,
true,
Some("One line saying what the archetype is for"),
),
field(
"instructions",
FieldType::String,
true,
Some("Guidance for an agent working on this kind of task"),
),
field(
"tools",
FieldType::Array(Box::new(FieldType::String)),
true,
Some("Commands and workflows in scope, comma-separated"),
),
],
);
save.args_fields = vec![name_arg()];
let mut delete = command(
"delete",
ArchetypeAction::Delete,
"Delete a saved archetype",
destructive,
Vec::new(),
);
delete.args_fields = vec![name_arg()];
let mut group = Cli::create(ARCHETYPES_GROUP_NAME).description(
"Activate a task focus: guidance plus the commands and workflows that task uses",
);
for def in [list, show, activate, save, delete] {
group = group.command(def.name.clone(), def);
}
group
}