Skip to main content

agentmux_srv_core/backend/
agent_skill_files.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! An agent's bound skills, written to its working directory every time its controller starts.
5//!
6//! `agent.open` and the window's launch write the whole config set (startup file, `.mcp.json`, skill
7//! files) when an agent is created. A controller that comes back later (a restart of AgentMux, an
8//! upgrade, a resume of a parked agent, a pane that was only reattached) starts from the block as it
9//! was, so a skill bound, or made to reach every agent, after that first launch never reached the
10//! agent's files until it was launched fresh. Only the skill files are refreshed here: the startup file
11//! and `.mcp.json` carry the agent's keys and its own memory, and a resume must not rewrite them.
12
13use std::collections::HashMap;
14use std::path::Path;
15
16use crate::backend::agent_config::{
17    build_config_files, cleanup_stale_managed_skill_files, managed_skill_file_paths, write_managed_skill_file_manifest,
18};
19use crate::backend::obj::{meta_get_string, MetaMapType};
20use crate::backend::storage::store::Store;
21
22/// The block's agent id: a launch from a definition stamps `agentId`, `agent.open` also `agent:id`.
23fn agent_uid_of(meta: &MetaMapType) -> String {
24    ["agentId", "agent:id"]
25        .iter()
26        .map(|key| meta_get_string(meta, key, ""))
27        .find(|id| !id.is_empty())
28        .unwrap_or_default()
29}
30
31/// Write the skill files the agent of a block with this `meta` is bound to, and remove the ones AgentMux
32/// wrote earlier that it is no longer bound to. Best-effort: a block that is not an agent's, or whose
33/// working directory is gone, is left alone, and a failure is logged, never raised: an agent must start.
34/// Returns how many skill files it wrote.
35pub fn refresh_for_block(meta: &MetaMapType, mstore: &Store, identity_store: &Store) -> usize {
36    let uid = agent_uid_of(meta);
37    let raw_dir = meta_get_string(meta, "cmd:cwd", "");
38    if uid.is_empty() || raw_dir.is_empty() {
39        return 0;
40    }
41    // `agent.open` stores a default folder as `~/.agentmux/agents/<slug>`, unexpanded.
42    let expanded = crate::backend::base::expand_home_dir_safe(&raw_dir);
43    let work_dir = expanded.to_string_lossy().into_owned();
44    let base_path = expanded.as_path();
45    if !base_path.is_dir() {
46        return 0;
47    }
48    let Some(agent) = mstore.agent_def_get(&uid).ok().flatten() else {
49        return 0;
50    };
51    let slug = if agent.slug.is_empty() { agent.id.clone() } else { agent.slug.clone() };
52    let skills = mstore.effective_skills(identity_store, &agent.id);
53    // The same files `agent.open` would write for these skills; only the skill-derived ones are kept.
54    // The name the pane was launched under fills `{{AGENT}}` in a skill, as it did when the files were first written.
55    let launched_name = meta_get_string(meta, "agentName", "");
56    let name = if launched_name.is_empty() { agent.name.as_str() } else { launched_name.as_str() };
57    let mut all = build_config_files(&HashMap::new(), &skills, name, &agent.id, &slug, &work_dir, &agent.provider);
58    all.extend(crate::backend::computer_use_skill::sibling_files(&skills, identity_store));
59    let wanted = managed_skill_file_paths(all.iter().map(|f| f.filename.as_str()));
60    let files: Vec<_> = all.iter().filter(|f| wanted.contains(&f.filename)).collect();
61
62    // A host agent in a folder a container agent can write is given its skills from outside the folder: nothing here
63    // is written into it.
64    if crate::backend::mcp_folder_rule::folder_of(meta).is_some() {
65        let given = files.iter().map(|f| (f.filename.as_str(), f.content.as_str()));
66        if let Err(e) = crate::backend::host_agent_files::refresh_skills(&work_dir, given) {
67            tracing::warn!(agent_id = %agent.id, error = %e, "skill files: could not refresh the skills kept outside the folder");
68        }
69        return 0;
70    }
71    let Ok(wd) = crate::backend::workdir_fs::Workdir::open(base_path) else {
72        tracing::warn!(agent_id = %agent.id, work_dir = %work_dir, "skill files: could not open the working directory");
73        return 0;
74    };
75    cleanup_stale_managed_skill_files(base_path, &wanted);
76    let mut written = 0;
77    for file in files {
78        // Untouched when it already reads the same: the file is read by a CLI that may be about to start.
79        if std::fs::read_to_string(base_path.join(&file.filename)).is_ok_and(|now| now == file.content) {
80            continue;
81        }
82        match wd.write(&file.filename, file.content.as_bytes(), false) {
83            Ok(_) => written += 1,
84            Err(e) => tracing::warn!(agent_id = %agent.id, path = %file.filename, error = %e, "skill files: could not write"),
85        }
86    }
87    write_managed_skill_file_manifest(base_path, &wanted);
88    if written > 0 {
89        tracing::info!(agent_id = %agent.id, written, "skill files: refreshed for a controller start");
90    }
91    written
92}
93
94#[cfg(test)]
95#[path = "agent_skill_files_tests.rs"]
96mod tests;