mirror of
https://github.com/MindWorkAI/AI-Studio.git
synced 2026-10-07 12:09:40 +00:00
Improved local plugin handling (share, import, delete) (#900)
Build and Release / Read metadata (push) Blocked by required conditions
Build and Release / Sync Flatpak repo (push) Blocked by required conditions
Build and Release / Collect Flatpak artifacts (push) Blocked by required conditions
Build and Release / Build app (${{ matrix.dotnet_runtime }}) (-aarch64-pc-windows-msvc.exe, win-arm64, windows-latest, aarch64-pc-windows-msvc, nsis,updater, nsis) (push) Blocked by required conditions
Build and Release / Build app (${{ matrix.dotnet_runtime }}) (-aarch64-unknown-linux-gnu, linux-arm64, ubuntu-22.04-arm, aarch64-unknown-linux-gnu, appimage,updater, appimage) (push) Blocked by required conditions
Build and Release / Build app (${{ matrix.dotnet_runtime }}) (-x86_64-apple-darwin, osx-x64, macos-latest, x86_64-apple-darwin, dmg,app,updater, dmg) (push) Blocked by required conditions
Build and Release / Build app (${{ matrix.dotnet_runtime }}) (-x86_64-unknown-linux-gnu, linux-x64, ubuntu-22.04, x86_64-unknown-linux-gnu, appimage,updater, appimage) (push) Blocked by required conditions
Build and Release / Prepare & create release (push) Blocked by required conditions
Build and Release / Publish release (push) Blocked by required conditions
Build and Release / Determine run mode (push) Waiting to run
Build and Release / Build app (${{ matrix.dotnet_runtime }}) (-aarch64-apple-darwin, osx-arm64, macos-latest, aarch64-apple-darwin, dmg,app,updater, dmg) (push) Blocked by required conditions
Build and Release / Build app (${{ matrix.dotnet_runtime }}) (-x86_64-pc-windows-msvc.exe, win-x64, windows-latest, x86_64-pc-windows-msvc, nsis,updater, nsis) (push) Blocked by required conditions
Build and Release / Read metadata (push) Blocked by required conditions
Build and Release / Sync Flatpak repo (push) Blocked by required conditions
Build and Release / Collect Flatpak artifacts (push) Blocked by required conditions
Build and Release / Build app (${{ matrix.dotnet_runtime }}) (-aarch64-pc-windows-msvc.exe, win-arm64, windows-latest, aarch64-pc-windows-msvc, nsis,updater, nsis) (push) Blocked by required conditions
Build and Release / Build app (${{ matrix.dotnet_runtime }}) (-aarch64-unknown-linux-gnu, linux-arm64, ubuntu-22.04-arm, aarch64-unknown-linux-gnu, appimage,updater, appimage) (push) Blocked by required conditions
Build and Release / Build app (${{ matrix.dotnet_runtime }}) (-x86_64-apple-darwin, osx-x64, macos-latest, x86_64-apple-darwin, dmg,app,updater, dmg) (push) Blocked by required conditions
Build and Release / Build app (${{ matrix.dotnet_runtime }}) (-x86_64-unknown-linux-gnu, linux-x64, ubuntu-22.04, x86_64-unknown-linux-gnu, appimage,updater, appimage) (push) Blocked by required conditions
Build and Release / Prepare & create release (push) Blocked by required conditions
Build and Release / Publish release (push) Blocked by required conditions
Build and Release / Determine run mode (push) Waiting to run
Build and Release / Build app (${{ matrix.dotnet_runtime }}) (-aarch64-apple-darwin, osx-arm64, macos-latest, aarch64-apple-darwin, dmg,app,updater, dmg) (push) Blocked by required conditions
Build and Release / Build app (${{ matrix.dotnet_runtime }}) (-x86_64-pc-windows-msvc.exe, win-x64, windows-latest, x86_64-pc-windows-msvc, nsis,updater, nsis) (push) Blocked by required conditions
This commit is contained in:
1 parent
0eb747b386
commit
6e143aafaa
47 files changed
+3108
-1480
No files matched your search
@@ -49,6 +49,17 @@ public sealed class PluginConfiguration(bool isInternal, LuaState state, PluginT
|
||||
/// refine it, e.g. per department.
|
||||
/// </remarks>
|
||||
public int Priority { get; } = ReadPriority(state);
|
||||
|
||||
/// <summary>
|
||||
/// How many settings this configuration plugin declares.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// This counts the entries of the Lua SETTINGS table, without the <c>.AllowUserOverride</c>
|
||||
/// companions. We need it for the import preview: a dry run does not lock anything, so the
|
||||
/// number of settings the plugin would take over cannot be read from the managed configuration
|
||||
/// at that point.
|
||||
/// </remarks>
|
||||
public int DeclaredSettingsCount { get; private set; }
|
||||
|
||||
public async Task InitializeAsync(bool dryRun)
|
||||
{
|
||||
@@ -148,6 +159,26 @@ public sealed class PluginConfiguration(bool isInternal, LuaState state, PluginT
|
||||
return 0;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Counts the settings a configuration plugin declares, ignoring the <c>.AllowUserOverride</c>
|
||||
/// companion keys: those refine a setting instead of adding one.
|
||||
/// </summary>
|
||||
private static int CountDeclaredSettings(LuaTable settingsTable)
|
||||
{
|
||||
const string USER_OVERRIDE_SUFFIX = ".AllowUserOverride";
|
||||
|
||||
var count = 0;
|
||||
var previousKey = LuaValue.Nil;
|
||||
while (settingsTable.TryGetNext(previousKey, out var pair))
|
||||
{
|
||||
previousKey = pair.Key;
|
||||
if (pair.Key.TryRead<string>(out var settingName) && !settingName.EndsWith(USER_OVERRIDE_SUFFIX, StringComparison.Ordinal))
|
||||
count++;
|
||||
}
|
||||
|
||||
return count;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Tries to initialize the UI text content of the plugin.
|
||||
/// </summary>
|
||||
@@ -173,6 +204,8 @@ public sealed class PluginConfiguration(bool isInternal, LuaState state, PluginT
|
||||
message = TB("The SETTINGS table does not exist or is not a valid table.");
|
||||
return false;
|
||||
}
|
||||
|
||||
this.DeclaredSettingsCount = CountDeclaredSettings(settingsTable);
|
||||
|
||||
// Config: check for updates, and if so, how often?
|
||||
ManagedConfiguration.TryProcessConfiguration(x => x.App, x => x.UpdateInterval, this.Id, settingsTable, dryRun);
|
||||
@@ -201,6 +234,9 @@ public sealed class PluginConfiguration(bool isInternal, LuaState state, PluginT
|
||||
// Config: allow the user to import plugin archives?
|
||||
ManagedConfiguration.TryProcessConfiguration(x => x.App, x => x.AllowUserToImportPlugins, this.Id, settingsTable, dryRun);
|
||||
|
||||
// Config: allow the user to import configuration plugin archives?
|
||||
ManagedConfiguration.TryProcessConfiguration(x => x.App, x => x.AllowUserToImportConfigurationPlugins, this.Id, settingsTable, dryRun);
|
||||
|
||||
// Config: allow the user to share or export plugins?
|
||||
ManagedConfiguration.TryProcessConfiguration(x => x.App, x => x.AllowUserToSharePlugins, this.Id, settingsTable, dryRun);
|
||||
|
||||
@@ -355,6 +391,28 @@ public sealed class PluginConfiguration(bool isInternal, LuaState state, PluginT
|
||||
if (dryRun)
|
||||
return;
|
||||
|
||||
//
|
||||
// Only a configuration which speaks for an organization may approve assistant plugins: one
|
||||
// deployed by a configuration server, or one staged in the test directory. An approval marks
|
||||
// a plugin as safe without any security audit, and the user interface states that the
|
||||
// organization approved it. No local configuration plugin may make that claim: it would
|
||||
// disable the security audit for arbitrary assistant plugins while telling the user that
|
||||
// their organization vouched for them.
|
||||
//
|
||||
// We decide by the plugin path. The self-declared DEPLOYED_USING_CONFIG_SERVER field would
|
||||
// not do, because any plugin can set it to true.
|
||||
//
|
||||
if (!PluginFactory.IsOrganizationConfigurationPath(this.PluginPath))
|
||||
{
|
||||
if (successful)
|
||||
LOG.LogWarning("The configuration plugin '{ConfigPluginId}' at '{PluginPath}' declares enterprise approvals for assistant plugins, but your organization's IT did not deploy it. Ignoring these approvals: only configuration plugins from a configuration server or from the test directory may approve assistant plugins.", this.Id, this.PluginPath);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
if (PluginFactory.IsEnterpriseTestConfigurationPath(this.PluginPath))
|
||||
LOG.LogWarning("The test configuration plugin '{ConfigPluginId}' at '{PluginPath}' approves assistant plugins. These approvals are valid for this session only: AI Studio empties the test directory on every start.", this.Id, this.PluginPath);
|
||||
|
||||
switch (successful)
|
||||
{
|
||||
case true:
|
||||
|
||||
@@ -34,6 +34,41 @@ public sealed record PluginConfigurationObject
|
||||
/// </summary>
|
||||
public required PluginConfigurationObjectType Type { get; init; } = PluginConfigurationObjectType.NONE;
|
||||
|
||||
/// <summary>
|
||||
/// The name of the configuration object, e.g. the name of a provider.
|
||||
/// </summary>
|
||||
public string Name { get; init; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// Where this configuration object sends data to: the host of a self-hosted provider or data
|
||||
/// source, or the name of the cloud provider. Empty for objects without a destination, such as
|
||||
/// chat templates or profiles.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// We keep this next to the object metadata so the import preview can tell users where a
|
||||
/// configuration would send their prompts before its providers are stored.
|
||||
/// </remarks>
|
||||
public string Endpoint { get; private init; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// Determines the destination of a configuration object for the import preview.
|
||||
/// </summary>
|
||||
private static string DescribeEndpoint(IConfigurationObject configObject) => configObject switch
|
||||
{
|
||||
Settings.Provider { IsSelfHosted: true } provider => provider.Hostname,
|
||||
Settings.Provider provider => Provider.LLMProvidersExtensions.ToName(provider.UsedLLMProvider),
|
||||
|
||||
EmbeddingProvider { IsSelfHosted: true } embeddingProvider => embeddingProvider.Hostname,
|
||||
EmbeddingProvider embeddingProvider => Provider.LLMProvidersExtensions.ToName(embeddingProvider.UsedLLMProvider),
|
||||
|
||||
TranscriptionProvider { IsSelfHosted: true } transcriptionProvider => transcriptionProvider.Hostname,
|
||||
TranscriptionProvider transcriptionProvider => Provider.LLMProvidersExtensions.ToName(transcriptionProvider.UsedLLMProvider),
|
||||
|
||||
DataSourceERI_V1 dataSource => dataSource.Hostname,
|
||||
|
||||
_ => string.Empty,
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// Parses Lua table entries into configuration objects of the specified type, populating the
|
||||
/// provided list with results.
|
||||
@@ -125,6 +160,8 @@ public sealed record PluginConfigurationObject
|
||||
ConfigPluginId = configPluginId,
|
||||
Id = Guid.Parse(configObject.Id),
|
||||
Type = configObjectType,
|
||||
Name = configObject.Name,
|
||||
Endpoint = DescribeEndpoint(configObject),
|
||||
});
|
||||
|
||||
if (dryRun)
|
||||
@@ -214,6 +251,8 @@ public sealed record PluginConfigurationObject
|
||||
ConfigPluginId = configPluginId,
|
||||
Id = Guid.Parse(configObject.Id),
|
||||
Type = PluginConfigurationObjectType.DATA_SOURCE,
|
||||
Name = configObject.Name,
|
||||
Endpoint = DescribeEndpoint(configObject),
|
||||
});
|
||||
|
||||
if (dryRun)
|
||||
@@ -273,10 +312,10 @@ public sealed record PluginConfigurationObject
|
||||
if (!existingObject.IsEnterpriseConfiguration || existingObject.EnterpriseConfigurationPluginId == configPluginId)
|
||||
return true;
|
||||
|
||||
if (!PluginFactory.IsEnterpriseConfigurationPlugin(existingObject.EnterpriseConfigurationPluginId))
|
||||
if (!PluginFactory.IsOrganizationConfigurationPlugin(existingObject.EnterpriseConfigurationPluginId))
|
||||
return true;
|
||||
|
||||
if (PluginFactory.IsEnterpriseConfigurationPlugin(configPluginId))
|
||||
if (PluginFactory.IsOrganizationConfigurationPlugin(configPluginId))
|
||||
return true;
|
||||
|
||||
LOG.LogWarning("The configuration plugin '{ConfigPluginId}' tried to replace the object '{ConfigObjectName}' (id={ConfigObjectId}), which belongs to the configuration plugin '{OwningConfigPluginId}' of your organization. Ignoring the attempt: configurations deployed by your organization's IT take precedence.", configPluginId, existingObject.Name, existingObject.Id, existingObject.EnterpriseConfigurationPluginId);
|
||||
|
||||
@@ -119,13 +119,17 @@ public static partial class PluginFactory
|
||||
//
|
||||
if (AVAILABLE_PLUGINS.FirstOrDefault(candidate => candidate.Id == plugin.Id) is { } duplicatePlugin)
|
||||
{
|
||||
if (!IsEnterpriseConfigurationPath(pluginPath) || IsEnterpriseConfigurationPath(duplicatePlugin.LocalPath))
|
||||
if (GetConfigurationAuthority(pluginPath) <= GetConfigurationAuthority(duplicatePlugin.LocalPath))
|
||||
{
|
||||
LOG.LogWarning($"Ignoring the plugin '{pluginMainFile}': its ID ('{plugin.Id}') is already used by the plugin at '{duplicatePlugin.LocalPath}'. Plugin IDs must be unique. Please remove one of these plugins.");
|
||||
continue;
|
||||
}
|
||||
|
||||
LOG.LogWarning($"Ignoring the plugin at '{duplicatePlugin.LocalPath}': it uses the ID ('{plugin.Id}') of the enterprise configuration plugin at '{pluginPath}'. Plugins deployed by your organization's IT take precedence.");
|
||||
if (IsEnterpriseTestConfigurationPath(pluginPath))
|
||||
LOG.LogWarning($"Ignoring the plugin at '{duplicatePlugin.LocalPath}': it uses the ID ('{plugin.Id}') of the test configuration plugin at '{pluginPath}'. A test configuration takes precedence until AI Studio is restarted.");
|
||||
else
|
||||
LOG.LogWarning($"Ignoring the plugin at '{duplicatePlugin.LocalPath}': it uses the ID ('{plugin.Id}') of the enterprise configuration plugin at '{pluginPath}'. Plugins deployed by your organization's IT take precedence.");
|
||||
|
||||
AVAILABLE_PLUGINS.Remove(duplicatePlugin);
|
||||
}
|
||||
|
||||
@@ -199,6 +203,15 @@ public static partial class PluginFactory
|
||||
// one broken configuration plugin would wipe the entire organization configuration:
|
||||
//
|
||||
var deployedEnterpriseConfigPluginIds = GetDeployedEnterpriseConfigPluginIds();
|
||||
|
||||
//
|
||||
// Test configurations manage settings and objects like a deployed configuration, so those must
|
||||
// not be treated as left over while the test runs. They are only ever loaded, never merely
|
||||
// present: the test directory is emptied on every start.
|
||||
//
|
||||
foreach (var testConfigurationPlugin in AVAILABLE_PLUGINS.Where(plugin => plugin.Type is PluginType.CONFIGURATION && IsEnterpriseTestConfigurationPath(plugin.LocalPath)))
|
||||
deployedEnterpriseConfigPluginIds.Add(testConfigurationPlugin.Id);
|
||||
|
||||
var unloadedEnterpriseConfigPluginIds = deployedEnterpriseConfigPluginIds.Where(x => AVAILABLE_PLUGINS.All(plugin => plugin.Id != x)).ToList();
|
||||
foreach (var unloadedEnterpriseConfigPluginId in unloadedEnterpriseConfigPluginIds)
|
||||
LOG.LogWarning($"The configuration plugin '{unloadedEnterpriseConfigPluginId}' is deployed, but was not loaded. Everything it manages stays unchanged, because the plugin was not removed. Please check the errors above and fix the plugin.");
|
||||
@@ -345,7 +358,10 @@ public static partial class PluginFactory
|
||||
if(type is PluginType.NONE)
|
||||
return new NoPlugin($"TYPE is not a valid plugin type. Valid types are: {CommonTools.GetAllEnumValues<PluginType>()}");
|
||||
|
||||
var isInternal = !string.IsNullOrWhiteSpace(pluginPath) && pluginPath.StartsWith(INTERNAL_PLUGINS_ROOT, StringComparison.OrdinalIgnoreCase);
|
||||
// Whether a plugin is internal is decided by its path, never by the plugin itself. We use the
|
||||
// same nesting check as everywhere else, so that a directory like `.internal-old` next to the
|
||||
// internal plugins does not count as internal:
|
||||
var isInternal = IsPathInside(INTERNAL_PLUGINS_ROOT, pluginPath);
|
||||
switch (type)
|
||||
{
|
||||
case PluginType.LANGUAGE:
|
||||
|
||||
@@ -1,129 +1,90 @@
|
||||
using System.Text.RegularExpressions;
|
||||
|
||||
namespace AIStudio.Tools.PluginSystem;
|
||||
|
||||
public static partial class PluginFactory
|
||||
{
|
||||
private const string REASON_NO_LONGER_REFERENCED = "no longer referenced by active enterprise environments";
|
||||
|
||||
/// <summary>
|
||||
/// Removes the configuration plugins an organization deployed once but does not reference anymore.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// This is how an organization withdraws a configuration: it removes the configuration ID from the
|
||||
/// devices, e.g. through a group policy. The next time AI Studio syncs, the local copy has to go.
|
||||
/// A device which was offline while the policy changed applies the withdrawal when it starts again.
|
||||
/// <br/><br/>
|
||||
/// What an organization deployed is decided by the plugin path alone. We must not ask the plugin
|
||||
/// itself: `DEPLOYED_USING_CONFIG_SERVER` is part of the plugin, so a configuration declaring
|
||||
/// `false` could never be withdrawn again once it was deployed, while it would keep every right of
|
||||
/// an organization configuration, including the approval of assistant plugins.
|
||||
/// </remarks>
|
||||
/// <param name="activeConfigurationIds">The IDs of the enterprise configurations which are currently referenced.</param>
|
||||
public static void RemoveUnreferencedManagedConfigurationPlugins(ISet<Guid> activeConfigurationIds)
|
||||
{
|
||||
if (!IsInitialized)
|
||||
if (!IsInitialized || !Directory.Exists(ENTERPRISE_CONFIGURATION_PLUGINS_ROOT))
|
||||
return;
|
||||
|
||||
var pluginIdsToRemove = new HashSet<Guid>();
|
||||
|
||||
// Case 1: Plugins are already loaded and metadata is available.
|
||||
foreach (var plugin in AVAILABLE_PLUGINS.Where(plugin =>
|
||||
plugin.Type is PluginType.CONFIGURATION &&
|
||||
plugin.IsManagedByConfigServer &&
|
||||
!activeConfigurationIds.Contains(plugin.Id)))
|
||||
pluginIdsToRemove.Add(plugin.Id);
|
||||
|
||||
// Case 2: Startup cleanup before the initial plugin load.
|
||||
// In this case, we inspect the .config directories directly.
|
||||
if (Directory.Exists(ENTERPRISE_CONFIGURATION_PLUGINS_ROOT))
|
||||
foreach (var configurationDirectory in Directory.EnumerateDirectories(ENTERPRISE_CONFIGURATION_PLUGINS_ROOT))
|
||||
{
|
||||
foreach (var pluginDirectory in Directory.EnumerateDirectories(ENTERPRISE_CONFIGURATION_PLUGINS_ROOT))
|
||||
{
|
||||
var directoryName = Path.GetFileName(pluginDirectory);
|
||||
if (!Guid.TryParse(directoryName, out var pluginId))
|
||||
continue;
|
||||
var directoryName = Path.GetFileName(configurationDirectory);
|
||||
|
||||
if (activeConfigurationIds.Contains(pluginId))
|
||||
continue;
|
||||
// A download in flight stages and backs up next to the configuration directories. Those
|
||||
// directories belong to a running update, not to a withdrawn configuration:
|
||||
if (IsTransientDownloadDirectory(directoryName))
|
||||
continue;
|
||||
|
||||
var deployFlag = ReadDeployFlagFromPluginFile(pluginDirectory);
|
||||
var isManagedByConfigServer = deployFlag ?? true;
|
||||
if (!deployFlag.HasValue)
|
||||
LOG.LogWarning($"Configuration plugin '{pluginId}' does not define 'DEPLOYED_USING_CONFIG_SERVER'. Falling back to the plugin path and treating it as managed because it is stored under '{ENTERPRISE_CONFIGURATION_PLUGINS_ROOT}'.");
|
||||
//
|
||||
// A configuration server downloads each configuration into a directory named after its
|
||||
// ID. Any other directory name cannot be referenced by an enterprise environment, so it
|
||||
// has no place here either:
|
||||
//
|
||||
if (Guid.TryParse(directoryName, out var configurationId) && activeConfigurationIds.Contains(configurationId))
|
||||
continue;
|
||||
|
||||
if (isManagedByConfigServer)
|
||||
pluginIdsToRemove.Add(pluginId);
|
||||
}
|
||||
}
|
||||
|
||||
foreach (var pluginId in pluginIdsToRemove)
|
||||
RemovePluginAsync(pluginId, REASON_NO_LONGER_REFERENCED);
|
||||
}
|
||||
|
||||
private static void RemovePluginAsync(Guid pluginId, string reason)
|
||||
{
|
||||
if (!IsInitialized)
|
||||
return;
|
||||
|
||||
LOG.LogWarning("Removing plugin with ID '{PluginId}'. Reason: {Reason}.", pluginId, reason);
|
||||
|
||||
//
|
||||
// Remove the plugin from the available plugins list:
|
||||
//
|
||||
var availablePluginToRemove = AVAILABLE_PLUGINS.FirstOrDefault(p => p.Id == pluginId);
|
||||
if (availablePluginToRemove != null)
|
||||
AVAILABLE_PLUGINS.Remove(availablePluginToRemove);
|
||||
else
|
||||
LOG.LogWarning("No available plugin found with ID '{PluginId}' while removing plugin. Reason: {Reason}.", pluginId, reason);
|
||||
|
||||
//
|
||||
// Remove the plugin from the running plugins list:
|
||||
//
|
||||
var runningPluginToRemove = RUNNING_PLUGINS.FirstOrDefault(p => p.Id == pluginId);
|
||||
if (runningPluginToRemove == null)
|
||||
LOG.LogWarning("No running plugin found with ID '{PluginId}' while removing plugin. Reason: {Reason}.", pluginId, reason);
|
||||
else
|
||||
RUNNING_PLUGINS.Remove(runningPluginToRemove);
|
||||
|
||||
//
|
||||
// Delete the plugin directory:
|
||||
//
|
||||
DeleteConfigurationPluginDirectory(pluginId);
|
||||
|
||||
LOG.LogInformation("Plugin with ID '{PluginId}' removed successfully. Reason: {Reason}.", pluginId, reason);
|
||||
}
|
||||
|
||||
private static bool? ReadDeployFlagFromPluginFile(string pluginDirectory)
|
||||
{
|
||||
try
|
||||
{
|
||||
var pluginFile = Path.Join(pluginDirectory, "plugin.lua");
|
||||
if (!File.Exists(pluginFile))
|
||||
return null;
|
||||
|
||||
var pluginCode = File.ReadAllText(pluginFile);
|
||||
var match = DeployedByConfigServerRegex().Match(pluginCode);
|
||||
if (!match.Success)
|
||||
return null;
|
||||
|
||||
return bool.TryParse(match.Groups[1].Value, out var deployFlag)
|
||||
? deployFlag
|
||||
: null;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
LOG.LogWarning(ex, $"Failed to parse deployment flag from plugin directory '{pluginDirectory}'.");
|
||||
return null;
|
||||
RemoveConfigurationDirectory(configurationDirectory, REASON_NO_LONGER_REFERENCED);
|
||||
}
|
||||
}
|
||||
|
||||
private static void DeleteConfigurationPluginDirectory(Guid pluginId)
|
||||
/// <summary>
|
||||
/// Checks whether a directory below the enterprise configuration directory belongs to a running
|
||||
/// download instead of to an installed configuration.
|
||||
/// </summary>
|
||||
private static bool IsTransientDownloadDirectory(string directoryName) =>
|
||||
directoryName.Contains(".staging-", StringComparison.OrdinalIgnoreCase) ||
|
||||
directoryName.Contains(".backup-", StringComparison.OrdinalIgnoreCase);
|
||||
|
||||
/// <summary>
|
||||
/// Unloads every plugin stored in the given directory and deletes the directory afterwards.
|
||||
/// </summary>
|
||||
private static void RemoveConfigurationDirectory(string configurationDirectory, string reason)
|
||||
{
|
||||
var pluginDirectory = Path.Join(ENTERPRISE_CONFIGURATION_PLUGINS_ROOT, pluginId.ToString());
|
||||
if (!Directory.Exists(pluginDirectory))
|
||||
LOG.LogWarning("Removing the enterprise configuration directory '{Directory}'. Reason: {Reason}.", configurationDirectory, reason);
|
||||
|
||||
//
|
||||
// We collect the plugins by path, not by the ID the directory is named after: a plugin may
|
||||
// declare an ID which differs from its directory name, and a single directory may even hold
|
||||
// several plugins:
|
||||
//
|
||||
foreach (var plugin in AVAILABLE_PLUGINS.Where(plugin => IsPathInside(configurationDirectory, plugin.LocalPath)).ToList())
|
||||
{
|
||||
LOG.LogWarning($"Plugin directory '{pluginDirectory}' does not exist.");
|
||||
return;
|
||||
AVAILABLE_PLUGINS.Remove(plugin);
|
||||
|
||||
if (RUNNING_PLUGINS.FirstOrDefault(runningPlugin => runningPlugin.Id == plugin.Id) is { } runningPluginToRemove)
|
||||
RUNNING_PLUGINS.Remove(runningPluginToRemove);
|
||||
|
||||
LOG.LogInformation("Unloaded the plugin '{PluginName}' ({PluginId}). Reason: {Reason}.", plugin.Name, plugin.Id, reason);
|
||||
}
|
||||
|
||||
if (!Directory.Exists(configurationDirectory))
|
||||
return;
|
||||
|
||||
try
|
||||
{
|
||||
Directory.Delete(pluginDirectory, true);
|
||||
LOG.LogInformation($"Plugin directory '{pluginDirectory}' deleted successfully.");
|
||||
Directory.Delete(configurationDirectory, true);
|
||||
LOG.LogInformation($"Plugin directory '{configurationDirectory}' deleted successfully.");
|
||||
}
|
||||
catch (Exception ex)
|
||||
catch (Exception e)
|
||||
{
|
||||
LOG.LogError(ex, $"Failed to delete plugin directory '{pluginDirectory}'.");
|
||||
LOG.LogError(e, $"Failed to delete plugin directory '{configurationDirectory}'.");
|
||||
}
|
||||
}
|
||||
|
||||
[GeneratedRegex(@"^\s*DEPLOYED_USING_CONFIG_SERVER\s*=\s*(true|false)\s*(?:--.*)?$", RegexOptions.IgnoreCase | RegexOptions.Multiline)]
|
||||
private static partial Regex DeployedByConfigServerRegex();
|
||||
}
|
||||
@@ -110,9 +110,10 @@ public static partial class PluginFactory
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// The configuration plugins an organization deployed go first: they are the baseline for
|
||||
/// everything else. Local configuration plugins follow, so they can add to that baseline instead
|
||||
/// of replacing parts of it. All remaining plugin types write no settings at all, so their rank
|
||||
/// is irrelevant for the outcome.<br/><br/>
|
||||
/// everything else. A test configuration follows, so that an administrator sees their draft take
|
||||
/// effect over the deployed baseline. Local configuration plugins come last, so they can add to
|
||||
/// that baseline instead of replacing parts of it. All remaining plugin types write no settings at
|
||||
/// all, so their rank is irrelevant for the outcome.<br/><br/>
|
||||
/// The rank comes before the declared priority on purpose: a local configuration plugin must not
|
||||
/// be able to jump ahead of an organization by declaring a high priority.
|
||||
/// </remarks>
|
||||
@@ -121,9 +122,10 @@ public static partial class PluginFactory
|
||||
private static int GetStartupRank(IAvailablePlugin plugin) => plugin.Type switch
|
||||
{
|
||||
PluginType.CONFIGURATION when IsEnterpriseConfigurationPath(plugin.LocalPath) => 0,
|
||||
PluginType.CONFIGURATION => 1,
|
||||
PluginType.CONFIGURATION when IsEnterpriseTestConfigurationPath(plugin.LocalPath) => 1,
|
||||
PluginType.CONFIGURATION => 2,
|
||||
|
||||
_ => 2,
|
||||
_ => 3,
|
||||
};
|
||||
|
||||
private static void LogAssistantPluginStartupState()
|
||||
|
||||
@@ -21,9 +21,31 @@ public static partial class PluginFactory
|
||||
/// deploys plugins here, each in a directory named after its configuration ID.
|
||||
/// </remarks>
|
||||
private static string ENTERPRISE_CONFIGURATION_PLUGINS_ROOT = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// The directory administrators use to try out a configuration before their organization deploys it.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Everything stored here acts on behalf of the organization, so that a test behaves like the
|
||||
/// later rollout, including the approval of assistant plugins. In exchange, the directory is
|
||||
/// emptied on every start: a test configuration lives for one session only. It also never gets
|
||||
/// the protection of a deployed configuration, so users can remove or replace it through the user
|
||||
/// interface.
|
||||
/// </remarks>
|
||||
private static string ENTERPRISE_TEST_CONFIGURATION_PLUGINS_ROOT = string.Empty;
|
||||
|
||||
private static string HOT_RELOAD_LOCK_FILE = string.Empty;
|
||||
private static FileSystemWatcher HOT_RELOAD_WATCHER = null!;
|
||||
|
||||
/// <summary>
|
||||
/// How many test configurations were removed while AI Studio was starting.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// The user interface reports this: an administrator who placed a test configuration and restarted
|
||||
/// AI Studio would otherwise face an empty directory without any explanation.
|
||||
/// </remarks>
|
||||
public static int RemovedTestConfigurationsAtStartup { get; private set; }
|
||||
|
||||
public static ILanguagePlugin BaseLanguage { get; private set; } = NoPluginLanguage.INSTANCE;
|
||||
|
||||
public static bool IsInitialized { get; private set; }
|
||||
@@ -75,10 +97,12 @@ public static partial class PluginFactory
|
||||
HOT_RELOAD_LOCK_FILE = Path.Join(PLUGINS_ROOT, ".lock");
|
||||
INTERNAL_PLUGINS_ROOT = Path.Join(PLUGINS_ROOT, ".internal");
|
||||
ENTERPRISE_CONFIGURATION_PLUGINS_ROOT = Path.Join(PLUGINS_ROOT, ".config");
|
||||
|
||||
ENTERPRISE_TEST_CONFIGURATION_PLUGINS_ROOT = Path.Join(PLUGINS_ROOT, ".config-tests");
|
||||
|
||||
if (!Directory.Exists(PLUGINS_ROOT))
|
||||
Directory.CreateDirectory(PLUGINS_ROOT);
|
||||
|
||||
|
||||
ClearTestConfigurationPlugins();
|
||||
HOT_RELOAD_WATCHER = new(PLUGINS_ROOT);
|
||||
IsInitialized = true;
|
||||
LOG.LogInformation("Plugin factory initialized successfully.");
|
||||
@@ -96,20 +120,130 @@ public static partial class PluginFactory
|
||||
/// </remarks>
|
||||
/// <param name="pluginPath">The directory of the plugin.</param>
|
||||
/// <returns>True when the directory is nested in the enterprise configuration directory.</returns>
|
||||
private static bool IsEnterpriseConfigurationPath(string? pluginPath)
|
||||
public static bool IsEnterpriseConfigurationPath(string? pluginPath) => IsPathInside(ENTERPRISE_CONFIGURATION_PLUGINS_ROOT, pluginPath);
|
||||
|
||||
/// <summary>
|
||||
/// Checks whether a plugin directory belongs to the test configuration area.
|
||||
/// </summary>
|
||||
/// <param name="pluginPath">The directory of the plugin.</param>
|
||||
/// <returns>True when the directory is nested in the test configuration directory.</returns>
|
||||
public static bool IsEnterpriseTestConfigurationPath(string? pluginPath) => IsPathInside(ENTERPRISE_TEST_CONFIGURATION_PLUGINS_ROOT, pluginPath);
|
||||
|
||||
/// <summary>
|
||||
/// Checks whether a plugin acts on behalf of an organization, either deployed by a configuration
|
||||
/// server or staged for a test.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Use this wherever a configuration speaks for the organization, e.g. when it approves assistant
|
||||
/// plugins or claims a setting against a local configuration plugin. Do not use it where a
|
||||
/// deployed configuration is protected against the user, e.g. against deletion: an administrator
|
||||
/// must be able to get rid of their own test configuration.
|
||||
/// </remarks>
|
||||
/// <param name="pluginPath">The directory of the plugin.</param>
|
||||
/// <returns>True when the directory belongs to the enterprise or the test configuration area.</returns>
|
||||
public static bool IsOrganizationConfigurationPath(string? pluginPath) => IsEnterpriseConfigurationPath(pluginPath) || IsEnterpriseTestConfigurationPath(pluginPath);
|
||||
|
||||
/// <summary>
|
||||
/// Ranks how much say a configuration plugin has, based on where it is stored. The higher rank
|
||||
/// wins when two configuration plugins claim the same plugin ID.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// A test configuration outranks a deployed one on purpose: an administrator tries out the next
|
||||
/// version of a configuration under the ID it will have later. Local configuration plugins rank
|
||||
/// lowest, so nobody can push aside what an organization deployed.
|
||||
/// </remarks>
|
||||
private static int GetConfigurationAuthority(string? pluginPath)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(pluginPath) || string.IsNullOrWhiteSpace(ENTERPRISE_CONFIGURATION_PLUGINS_ROOT))
|
||||
if (IsEnterpriseTestConfigurationPath(pluginPath))
|
||||
return 2;
|
||||
|
||||
return IsEnterpriseConfigurationPath(pluginPath) ? 1 : 0;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Empties the test configuration directory.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// A test configuration carries the rights of an organization configuration without anybody having
|
||||
/// deployed it. It must therefore never outlive the session it was placed in, and administrators
|
||||
/// get a predictable lifetime instead of a configuration which is swept away at some point.
|
||||
/// </remarks>
|
||||
private static void ClearTestConfigurationPlugins()
|
||||
{
|
||||
RemovedTestConfigurationsAtStartup = 0;
|
||||
try
|
||||
{
|
||||
if (Directory.Exists(ENTERPRISE_TEST_CONFIGURATION_PLUGINS_ROOT))
|
||||
{
|
||||
var removedTestConfigurations = Directory.EnumerateDirectories(ENTERPRISE_TEST_CONFIGURATION_PLUGINS_ROOT).Count();
|
||||
Directory.Delete(ENTERPRISE_TEST_CONFIGURATION_PLUGINS_ROOT, true);
|
||||
RemovedTestConfigurationsAtStartup = removedTestConfigurations;
|
||||
|
||||
if (removedTestConfigurations > 0)
|
||||
LOG.LogWarning($"Removed {removedTestConfigurations} test configuration(s) from '{ENTERPRISE_TEST_CONFIGURATION_PLUGINS_ROOT}'. Test configurations are valid for one session only.");
|
||||
}
|
||||
|
||||
Directory.CreateDirectory(ENTERPRISE_TEST_CONFIGURATION_PLUGINS_ROOT);
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
LOG.LogError(e, $"Failed to empty the test configuration directory '{ENTERPRISE_TEST_CONFIGURATION_PLUGINS_ROOT}'.");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Checks whether a plugin directory is stored below the plugins directory of AI Studio.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Everything that removes or replaces plugin files checks this first, so a plugin directory
|
||||
/// which points somewhere else can never be touched.
|
||||
/// </remarks>
|
||||
/// <param name="pluginPath">The directory of the plugin.</param>
|
||||
/// <returns>True when the directory is nested in the plugins directory.</returns>
|
||||
public static bool IsInsidePluginsRoot(string? pluginPath) => IsPathInside(PLUGINS_ROOT, pluginPath);
|
||||
|
||||
/// <summary>
|
||||
/// Checks whether a plugin directory is the plugins directory itself.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// A `plugin.lua` placed directly in the plugins directory makes that directory the plugin
|
||||
/// directory. Removing or replacing such a plugin means touching its directory, which would take
|
||||
/// every other plugin with it.
|
||||
/// </remarks>
|
||||
/// <param name="pluginPath">The directory of the plugin.</param>
|
||||
/// <returns>True when the directory is the plugins directory.</returns>
|
||||
public static bool IsPluginsRoot(string? pluginPath)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(pluginPath) || string.IsNullOrWhiteSpace(PLUGINS_ROOT))
|
||||
return false;
|
||||
|
||||
try
|
||||
{
|
||||
var configurationRoot = Path.GetFullPath(ENTERPRISE_CONFIGURATION_PLUGINS_ROOT).TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar) + Path.DirectorySeparatorChar;
|
||||
var pluginDirectory = Path.GetFullPath(pluginPath).TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar) + Path.DirectorySeparatorChar;
|
||||
return pluginDirectory.StartsWith(configurationRoot, StringComparison.OrdinalIgnoreCase);
|
||||
var root = Path.GetFullPath(PLUGINS_ROOT).TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar);
|
||||
var pluginDirectory = Path.GetFullPath(pluginPath).TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar);
|
||||
return string.Equals(root, pluginDirectory, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
LOG.LogWarning(e, $"Was not able to check whether the plugin directory '{pluginPath}' belongs to the enterprise configuration directory. Treating it as a local plugin.");
|
||||
LOG.LogWarning(e, $"Was not able to check whether the plugin directory '{pluginPath}' is the plugins directory. Treating it as the plugins directory.");
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
private static bool IsPathInside(string rootDirectory, string? pluginPath)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(pluginPath) || string.IsNullOrWhiteSpace(rootDirectory))
|
||||
return false;
|
||||
|
||||
try
|
||||
{
|
||||
var root = Path.GetFullPath(rootDirectory).TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar) + Path.DirectorySeparatorChar;
|
||||
var pluginDirectory = Path.GetFullPath(pluginPath).TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar) + Path.DirectorySeparatorChar;
|
||||
return pluginDirectory.StartsWith(root, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
LOG.LogWarning(e, $"Was not able to check whether the plugin directory '{pluginPath}' is nested in '{rootDirectory}'. Treating it as unrelated.");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -135,6 +269,27 @@ public static partial class PluginFactory
|
||||
return Directory.Exists(Path.Join(ENTERPRISE_CONFIGURATION_PLUGINS_ROOT, configPluginId.ToString()));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Checks whether a configuration plugin speaks for an organization: either deployed by its IT
|
||||
/// department, or staged as a test configuration.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// A test configuration is only ever loaded, never merely present: it is emptied on every start,
|
||||
/// so there is no unloadable leftover to account for.
|
||||
/// </remarks>
|
||||
/// <param name="configPluginId">The ID of the configuration plugin.</param>
|
||||
/// <returns>True when the plugin speaks for an organization, false when it is local or unknown.</returns>
|
||||
public static bool IsOrganizationConfigurationPlugin(Guid configPluginId)
|
||||
{
|
||||
if (configPluginId == Guid.Empty || !IsInitialized)
|
||||
return false;
|
||||
|
||||
if (IsEnterpriseConfigurationPlugin(configPluginId))
|
||||
return true;
|
||||
|
||||
return AVAILABLE_PLUGINS.Any(plugin => plugin.Id == configPluginId && plugin.Type is PluginType.CONFIGURATION && IsEnterpriseTestConfigurationPath(plugin.LocalPath));
|
||||
}
|
||||
|
||||
private static async Task LockHotReloadAsync()
|
||||
{
|
||||
if (!IsInitialized)
|
||||
|
||||
@@ -1,3 +0,0 @@
|
||||
namespace AIStudio.Tools.Services;
|
||||
|
||||
public sealed record AssistantPluginDeleteResult(bool Success, Guid PluginId, string PluginName, string PluginDirectory, string Issue);
|
||||
@@ -1,852 +0,0 @@
|
||||
using System.Text;
|
||||
using AIStudio.Settings;
|
||||
using AIStudio.Tools.AssistantSessions;
|
||||
using AIStudio.Tools.Media;
|
||||
using AIStudio.Tools.PluginSystem;
|
||||
using AIStudio.Tools.PluginSystem.Assistants;
|
||||
using AIStudio.Tools.Rust;
|
||||
|
||||
namespace AIStudio.Tools.Services;
|
||||
|
||||
public sealed class AssistantPluginInstallService
|
||||
{
|
||||
private static string TB(string fallbackEN) => I18N.I.T(fallbackEN, typeof(AssistantPluginInstallService).Namespace, nameof(AssistantPluginInstallService));
|
||||
|
||||
private const string PLUGIN_FILE_NAME = "plugin.lua";
|
||||
private const string ASSISTANT_BUILDER_DIRECTORY_PREFIX = "assistant-builder";
|
||||
private const string DELETE_BACKUP_DIRECTORY = ".plugin-delete-backups";
|
||||
private const string INSTALL_BACKUP_DIRECTORY = ".plugin-install-backups";
|
||||
private const int DIRECTORY_PREFIX_MAX_LEN = 80;
|
||||
|
||||
private readonly ILogger<AssistantPluginInstallService> logger;
|
||||
private readonly SettingsManager settingsManager;
|
||||
private readonly AssistantSessionService assistantSessionService;
|
||||
private readonly MediaTranscriptionService mediaTranscriptionService;
|
||||
private readonly SemaphoreSlim installSemaphore = new(1, 1);
|
||||
|
||||
private static AssistantPluginInstallResult Error(string issue) => new(false, Guid.Empty, string.Empty, string.Empty, false, issue);
|
||||
|
||||
private static AssistantPluginInstallResult CancelledByUser() => new(false, Guid.Empty, string.Empty, string.Empty, false, string.Empty, true);
|
||||
|
||||
private static AssistantPluginCheckResult CheckError(string issue) => new(false, Guid.Empty, string.Empty, issue);
|
||||
|
||||
private static AssistantPluginDeleteResult DeleteError(IPluginMetadata plugin, string pluginDirectory, string issue) => new(false, plugin.Id, plugin.Name, pluginDirectory, issue);
|
||||
|
||||
private static AssistantPluginUpdateResult UpdateError(IPluginMetadata plugin, string pluginDirectory, string issue) => new(false, plugin.Id, plugin.Name, pluginDirectory, issue);
|
||||
|
||||
public AssistantPluginInstallService(ILogger<AssistantPluginInstallService> logger, SettingsManager settingsManager, AssistantSessionService assistantSessionService, MediaTranscriptionService mediaTranscriptionService)
|
||||
{
|
||||
this.logger = logger;
|
||||
this.settingsManager = settingsManager;
|
||||
this.assistantSessionService = assistantSessionService;
|
||||
this.mediaTranscriptionService = mediaTranscriptionService;
|
||||
this.logger.LogInformation("The assistant plugin install service has been initialized.");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Checks whether a local plugin is an Assistant Builder generated assistant that users may delete.
|
||||
/// </summary>
|
||||
public static bool CanDeleteInstalledAssistant(IAvailablePlugin plugin) => string.IsNullOrWhiteSpace(GetAssistantDeletionEligibilityIssue(plugin));
|
||||
|
||||
/// <summary>
|
||||
/// Checks whether an assistant still owns running or canceling background work.
|
||||
/// </summary>
|
||||
public bool HasActiveAssistantWork(Guid pluginId)
|
||||
{
|
||||
var instanceId = pluginId.ToString();
|
||||
if (this.assistantSessionService.GetSnapshots().Any(snapshot => snapshot.IsActive && string.Equals(snapshot.Key.InstanceId, instanceId, StringComparison.Ordinal)))
|
||||
return true;
|
||||
|
||||
var ownerIdSuffix = $":{instanceId}";
|
||||
return this.mediaTranscriptionService.GetSnapshots().Any(snapshot =>
|
||||
snapshot is { IsBusy: true, Owner.Kind: MediaImportOwnerKind.ASSISTANT } &&
|
||||
snapshot.Owner.Id.EndsWith(ownerIdSuffix, StringComparison.Ordinal));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Checks whether generated Lua assistant plugin code can be loaded and installed.
|
||||
/// The plugin is written to a temporary staging directory and validated through the
|
||||
/// normal plugin loader, but it is not moved into the user plugin directory.
|
||||
/// </summary>
|
||||
/// <param name="lua">The full generated <c>plugin.lua</c> content.</param>
|
||||
/// <param name="token">A cancellation token for file IO and Lua validation.</param>
|
||||
/// <returns>
|
||||
/// Check result that contains success state, plugin metadata, and a user-facing issue when validation failed.
|
||||
/// </returns>
|
||||
public async Task<AssistantPluginCheckResult> CheckInstallabilityAsync(string lua, CancellationToken token)
|
||||
{
|
||||
if (!TryGetAssistantPluginsRoot(out var assistantPluginsRoot, out var rootIssue))
|
||||
return CheckError(rootIssue);
|
||||
|
||||
await this.installSemaphore.WaitAsync(token);
|
||||
var stagingDirectory = string.Empty;
|
||||
try
|
||||
{
|
||||
var validation = await this.ValidateIntoStagingAsync(lua, token);
|
||||
if (!validation.Success || validation.AssistantPlugin is null)
|
||||
return CheckError(validation.Issue);
|
||||
|
||||
stagingDirectory = validation.StagingDirectory;
|
||||
var finalDirectory = DetermineFinalDirectory(assistantPluginsRoot, validation.AssistantPlugin);
|
||||
if (!IsPathInsideDirectory(assistantPluginsRoot, finalDirectory))
|
||||
return CheckError(TB("The resolved plugin directory is outside the assistant plugin directory."));
|
||||
|
||||
return new(true, validation.AssistantPlugin.Id, validation.AssistantPlugin.Name, string.Empty);
|
||||
}
|
||||
finally
|
||||
{
|
||||
this.TryDeleteStagingDirectory(stagingDirectory);
|
||||
this.installSemaphore.Release();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Installs generated Lua assistant plugin code into the user plugin directory.
|
||||
/// Writes the plugin into a temporary staging directory first, validates it through the
|
||||
/// normal plugin loader, then moves into <c>data/plugins/assistants</c>.
|
||||
/// If plugin with same ID already exists, the existing directory is moved
|
||||
/// aside as backup and restored when replacement fails.
|
||||
/// </summary>
|
||||
/// <param name="lua">The full generated <c>plugin.lua</c> content.</param>
|
||||
/// <param name="token">A cancellation token for file IO, Lua validation, and plugin reload.</param>
|
||||
/// <returns>
|
||||
/// Installation result that contains success state, installed plugin metadata, final directory,
|
||||
/// whether an existing plugin was replaced, and user-facing issue when installation failed.
|
||||
/// </returns>
|
||||
public async Task<AssistantPluginInstallResult> InstallAsync(string lua, CancellationToken token)
|
||||
{
|
||||
if (!TryGetAssistantPluginsRoot(out var assistantPluginsRoot, out var rootIssue))
|
||||
return Error(rootIssue);
|
||||
|
||||
await this.installSemaphore.WaitAsync(token);
|
||||
try
|
||||
{
|
||||
var validation = await this.ValidateIntoStagingAsync(lua, token);
|
||||
if (!validation.Success || validation.AssistantPlugin is null)
|
||||
return Error(validation.Issue);
|
||||
|
||||
return await this.InstallStagedAssistantAsync(assistantPluginsRoot, validation, token);
|
||||
}
|
||||
finally
|
||||
{
|
||||
this.installSemaphore.Release();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Installs an assistant plugin archive that contains exactly one <c>plugin.lua</c> file.
|
||||
/// Companion files are validated from and moved with the same staging directory.
|
||||
/// </summary>
|
||||
/// <param name="archivePath">The local <c>.mwplugin</c> or <c>.zip</c> archive path.</param>
|
||||
/// <param name="confirmAsync">
|
||||
/// Asks the user whether the validated archive may be installed. It is called after all checks
|
||||
/// passed and before anything gets written. Returning false aborts the installation.
|
||||
/// </param>
|
||||
/// <param name="token">Cancellation token for extraction, validation, file IO, and plugin reload.</param>
|
||||
/// <returns>Installation result that contains success state, installed plugin metadata, and a user-facing issue when installation failed.</returns>
|
||||
public async Task<AssistantPluginInstallResult> InstallArchiveAsync(string archivePath, Func<PluginImportPreview, Task<bool>> confirmAsync, CancellationToken token)
|
||||
{
|
||||
if (!this.settingsManager.ConfigurationData.App.AllowUserToImportPlugins)
|
||||
return Error(TB("Your organization has disabled importing plugins."));
|
||||
|
||||
if (!FileTypes.IsAllowedPath(archivePath, FileTypes.PLUGIN_ARCHIVE))
|
||||
return Error(TB("Please select a plugin archive with the extension .mwplugin or .zip."));
|
||||
|
||||
if (!File.Exists(archivePath))
|
||||
return Error(TB("The selected plugin archive does not exist."));
|
||||
|
||||
if (!TryGetAssistantPluginsRoot(out var assistantPluginsRoot, out var rootIssue))
|
||||
return Error(rootIssue);
|
||||
|
||||
if (!PluginFactory.IsInitialized)
|
||||
return Error(TB("The plugin system is not initialized yet."));
|
||||
|
||||
await this.installSemaphore.WaitAsync(token);
|
||||
var stagingDirectory = Path.Join(Path.GetTempPath(), $"assistant-plugin-import.staging-{Guid.NewGuid():N}");
|
||||
try
|
||||
{
|
||||
try
|
||||
{
|
||||
token.ThrowIfCancellationRequested();
|
||||
PluginArchive.Extract(archivePath, stagingDirectory);
|
||||
|
||||
var pluginFiles = Directory.EnumerateFiles(stagingDirectory, PLUGIN_FILE_NAME, SearchOption.AllDirectories).ToArray();
|
||||
if (pluginFiles.Length != 1)
|
||||
return Error(TB("The plugin archive must contain exactly one plugin.lua file."));
|
||||
|
||||
var pluginFile = pluginFiles[0];
|
||||
var pluginDirectory = Path.GetDirectoryName(pluginFile)!;
|
||||
var pluginCode = await File.ReadAllTextAsync(pluginFile, Encoding.UTF8, token);
|
||||
var validation = await ValidateAssistantPluginCodeAsync(
|
||||
pluginDirectory,
|
||||
pluginCode.Trim(),
|
||||
TB("Currently, only assistant plugins can be imported."),
|
||||
TB("The imported assistant plugin is invalid. Issue: {0}"),
|
||||
TB("The imported assistant plugin uses the ID of another installed plugin."),
|
||||
token);
|
||||
|
||||
if (!validation.Success || validation.AssistantPlugin is null)
|
||||
return Error(validation.Issue);
|
||||
|
||||
// A plugin the user imports by hand never comes from a config server. We reject such
|
||||
// archives because AI Studio trusts this self-declared flag: an imported plugin
|
||||
// claiming it would be neither replaceable nor deletable through the user interface:
|
||||
if (validation.AssistantPlugin.IsManagedByConfigServer)
|
||||
return Error(TB("This plugin archive declares itself as managed by a config server. Only the IT department of your organization might deploy such plugins."));
|
||||
|
||||
// The archive would replace an existing plugin: reject it when that plugin belongs
|
||||
// to the IT department. We check this before asking the user, so that the
|
||||
// confirmation never offers something we would refuse afterwards anyway:
|
||||
var replacementIssue = GetAssistantReplacementIssue(validation.AssistantPlugin.Id);
|
||||
if (!string.IsNullOrEmpty(replacementIssue))
|
||||
return Error(replacementIssue);
|
||||
|
||||
// Everything is validated, but nothing was written yet. This is the point where the
|
||||
// user decides, because the plugin code comes from an untrusted source:
|
||||
if (!await confirmAsync(CreateImportPreview(validation.AssistantPlugin)))
|
||||
return CancelledByUser();
|
||||
|
||||
return await this.InstallStagedAssistantAsync(assistantPluginsRoot, validation with { StagingDirectory = pluginDirectory }, token);
|
||||
}
|
||||
catch (Exception e) when (e is not OperationCanceledException)
|
||||
{
|
||||
this.logger.LogError(e, "Failed to extract or validate assistant plugin archive '{ArchivePath}'.", archivePath);
|
||||
return Error(string.Format(TB("Unexpected error: {0}"), e.Message));
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
this.TryDeleteStagingDirectory(stagingDirectory);
|
||||
this.installSemaphore.Release();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Checks whether edited assistant plugin code can replace an installed local assistant plugin
|
||||
/// without writing the file.
|
||||
/// </summary>
|
||||
/// <param name="plugin">The installed local assistant plugin to validate against.</param>
|
||||
/// <param name="lua">The edited <c>plugin.lua</c> content.</param>
|
||||
/// <param name="token">Cancellation token for Lua validation.</param>
|
||||
/// <returns>Check result that contains success state, plugin metadata, and a user-facing issue when validation failed.</returns>
|
||||
public async Task<AssistantPluginCheckResult> CheckInstalledAssistantUpdateAsync(IAvailablePlugin plugin, string lua, CancellationToken token)
|
||||
{
|
||||
if (plugin.Type is not PluginType.ASSISTANT)
|
||||
return CheckError(TB("Only assistant plugins can be edited."));
|
||||
|
||||
if (plugin.IsInternal)
|
||||
return CheckError(TB("Internal assistant plugins cannot be edited."));
|
||||
|
||||
if (string.IsNullOrWhiteSpace(plugin.LocalPath))
|
||||
return CheckError(TB("The assistant plugin has no local directory."));
|
||||
|
||||
if (!TryGetAssistantPluginsRoot(out var assistantPluginsRoot, out var rootIssue))
|
||||
return CheckError(rootIssue);
|
||||
|
||||
var pluginDirectory = plugin.LocalPath;
|
||||
if (!IsPathInsideDirectory(assistantPluginsRoot, pluginDirectory) || IsSameDirectory(assistantPluginsRoot, pluginDirectory))
|
||||
return CheckError(TB("The assistant plugin directory is outside the local assistant plugin directory."));
|
||||
|
||||
if (!Directory.Exists(pluginDirectory))
|
||||
return CheckError(TB("The assistant plugin directory does not exist."));
|
||||
|
||||
await this.installSemaphore.WaitAsync(token);
|
||||
try
|
||||
{
|
||||
var validation = await this.ValidateInPluginDirectoryAsync(lua, pluginDirectory, token);
|
||||
if (!validation.Success || validation.AssistantPlugin is null)
|
||||
return CheckError(validation.Issue);
|
||||
|
||||
var assistantPlugin = validation.AssistantPlugin;
|
||||
return assistantPlugin.Id != plugin.Id
|
||||
? CheckError(TB("The edited assistant plugin must keep the same plugin ID."))
|
||||
: new(true, assistantPlugin.Id, assistantPlugin.Name, string.Empty);
|
||||
}
|
||||
finally
|
||||
{
|
||||
this.installSemaphore.Release();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Deletes installed local assistant plugin directories.
|
||||
/// The directory gets moved to a backup dir outside the plugin root so the
|
||||
/// plugin loader cannot discover it during reload. On failure, the directory
|
||||
/// and related assistant settings are restored.
|
||||
/// </summary>
|
||||
/// <param name="plugin">Assistant plugin metadata</param>
|
||||
/// <param name="token">Cancellation token for settings storage and plugin reload</param>
|
||||
/// <returns>
|
||||
/// Delete result that contains success state, deleted plugin metadata, the original plugin directory,
|
||||
/// and a user-facing issue when deletion failed.
|
||||
/// </returns>
|
||||
public async Task<AssistantPluginDeleteResult> DeleteInstalledAssistantAsync(IAvailablePlugin plugin, CancellationToken token)
|
||||
{
|
||||
var eligibilityIssue = GetAssistantDeletionEligibilityIssue(plugin);
|
||||
if (!string.IsNullOrEmpty(eligibilityIssue))
|
||||
return DeleteError(plugin, plugin.LocalPath, eligibilityIssue);
|
||||
|
||||
if (this.HasActiveAssistantWork(plugin.Id))
|
||||
return DeleteError(plugin, plugin.LocalPath, TB("The assistant cannot be deleted while background work is still running."));
|
||||
|
||||
await this.installSemaphore.WaitAsync(token);
|
||||
var pluginDirectory = plugin.LocalPath;
|
||||
var backupDirectory = string.Empty;
|
||||
var wasEnabled = false;
|
||||
var removedAudits = new List<PluginAssistantAudit>();
|
||||
|
||||
try
|
||||
{
|
||||
eligibilityIssue = GetAssistantDeletionEligibilityIssue(plugin);
|
||||
if (!string.IsNullOrEmpty(eligibilityIssue))
|
||||
return DeleteError(plugin, pluginDirectory, eligibilityIssue);
|
||||
|
||||
if (this.HasActiveAssistantWork(plugin.Id))
|
||||
return DeleteError(plugin, pluginDirectory, TB("The assistant cannot be deleted while background work is still running."));
|
||||
|
||||
backupDirectory = CreateDeleteBackupDirectory(plugin);
|
||||
Directory.CreateDirectory(Path.GetDirectoryName(backupDirectory)!);
|
||||
Directory.Move(pluginDirectory, backupDirectory);
|
||||
|
||||
wasEnabled = this.settingsManager.ConfigurationData.EnabledPlugins.Remove(plugin.Id);
|
||||
removedAudits =
|
||||
[
|
||||
.. this.settingsManager.ConfigurationData.AssistantPluginAudits.Where(audit => audit.PluginId == plugin.Id)
|
||||
];
|
||||
|
||||
if (removedAudits.Count > 0)
|
||||
this.settingsManager.ConfigurationData.AssistantPluginAudits.RemoveAll(audit => audit.PluginId == plugin.Id);
|
||||
|
||||
await this.settingsManager.StoreSettings();
|
||||
await PluginFactory.LoadAll(token);
|
||||
|
||||
TryDeleteDirectory(backupDirectory, "assistant plugin delete backup", this.logger);
|
||||
this.logger.LogInformation($"Deleted assistant plugin '{plugin.Name}' ({plugin.Id}) from '{pluginDirectory}'.");
|
||||
return new(true, plugin.Id, plugin.Name, pluginDirectory, string.Empty);
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
this.logger.LogError(e, $"Failed to delete assistant plugin '{plugin.Name}' ({plugin.Id}) from '{pluginDirectory}'.");
|
||||
|
||||
await this.TryRestoreDeletedAssistantPluginAsync(plugin, pluginDirectory, backupDirectory, wasEnabled, removedAudits, token);
|
||||
return DeleteError(plugin, pluginDirectory, string.Format(TB("Unexpected error: {0}"), e.Message));
|
||||
}
|
||||
finally
|
||||
{
|
||||
this.installSemaphore.Release();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Updates installed assistant plugin <c>plugin.lua</c> file.
|
||||
/// The edited Lua code is validated from the provided string before it is written,
|
||||
/// but validation uses existing plugin directory as loader context so
|
||||
/// <c>require(...)</c> can resolve companion files such as <c>icon.lua</c>.
|
||||
/// After successful validation, the current <c>plugin.lua</c> is backed up,
|
||||
/// replaced atomically through a temporary file in the plugin directory, and
|
||||
/// restored when the plugin reload fails.
|
||||
/// </summary>
|
||||
/// <param name="plugin">The installed local assistant plugin to update.</param>
|
||||
/// <param name="lua">The edited <c>plugin.lua</c> content.</param>
|
||||
/// <param name="token">Cancellation token for Lua validation, file IO, and plugin reload.</param>
|
||||
/// <returns>
|
||||
/// Update result that contains success state, updated plugin metadata, the plugin directory,
|
||||
/// and a user-facing issue when the update failed.
|
||||
/// </returns>
|
||||
public async Task<AssistantPluginUpdateResult> UpdateInstalledAssistantAsync(IAvailablePlugin plugin, string lua, CancellationToken token)
|
||||
{
|
||||
if (plugin.Type is not PluginType.ASSISTANT)
|
||||
return UpdateError(plugin, plugin.LocalPath, TB("Only assistant plugins can be edited."));
|
||||
|
||||
if (plugin.IsInternal)
|
||||
return UpdateError(plugin, plugin.LocalPath, TB("Internal assistant plugins cannot be edited."));
|
||||
|
||||
if (string.IsNullOrWhiteSpace(plugin.LocalPath))
|
||||
return UpdateError(plugin, string.Empty, TB("The assistant plugin has no local directory."));
|
||||
|
||||
if (!TryGetAssistantPluginsRoot(out var assistantPluginsRoot, out var rootIssue))
|
||||
return UpdateError(plugin, plugin.LocalPath, rootIssue);
|
||||
|
||||
var pluginDirectory = plugin.LocalPath;
|
||||
if (!IsPathInsideDirectory(assistantPluginsRoot, pluginDirectory) || IsSameDirectory(assistantPluginsRoot, pluginDirectory))
|
||||
return UpdateError(plugin, pluginDirectory, TB("The assistant plugin directory is outside the local assistant plugin directory."));
|
||||
|
||||
if (!Directory.Exists(pluginDirectory))
|
||||
return UpdateError(plugin, pluginDirectory, TB("The assistant plugin directory does not exist."));
|
||||
|
||||
var pluginFile = Path.Join(pluginDirectory, PLUGIN_FILE_NAME);
|
||||
if (!IsPathInsideDirectory(pluginDirectory, pluginFile))
|
||||
return UpdateError(plugin, pluginDirectory, TB("The plugin file is outside the assistant plugin directory."));
|
||||
|
||||
await this.installSemaphore.WaitAsync(token);
|
||||
var tempFile = string.Empty;
|
||||
var backupFile = string.Empty;
|
||||
|
||||
try
|
||||
{
|
||||
var validation = await this.ValidateInPluginDirectoryAsync(lua, pluginDirectory, token);
|
||||
if (!validation.Success || validation.AssistantPlugin is null)
|
||||
return UpdateError(plugin, pluginDirectory, validation.Issue);
|
||||
|
||||
var assistantPlugin = validation.AssistantPlugin;
|
||||
if (assistantPlugin.Id != plugin.Id)
|
||||
return UpdateError(plugin, pluginDirectory, TB("The edited assistant plugin must keep the same plugin ID."));
|
||||
|
||||
var pluginCode = lua.Trim();
|
||||
tempFile = Path.Join(pluginDirectory, $"{PLUGIN_FILE_NAME}.tmp-{Guid.NewGuid():N}");
|
||||
backupFile = Path.Join(pluginDirectory, $"{PLUGIN_FILE_NAME}.backup-{Guid.NewGuid():N}");
|
||||
|
||||
await File.WriteAllTextAsync(tempFile, pluginCode, Encoding.UTF8, token);
|
||||
|
||||
if (File.Exists(pluginFile))
|
||||
File.Replace(tempFile, pluginFile, backupFile);
|
||||
else
|
||||
File.Move(tempFile, pluginFile);
|
||||
|
||||
try
|
||||
{
|
||||
await PluginFactory.LoadAll(token);
|
||||
if (File.Exists(backupFile))
|
||||
File.Delete(backupFile);
|
||||
|
||||
this.logger.LogInformation($"Updated assistant plugin '{assistantPlugin.Name}' ({assistantPlugin.Id}) at '{pluginFile}'.");
|
||||
return new(true, assistantPlugin.Id, assistantPlugin.Name, pluginDirectory, string.Empty);
|
||||
}
|
||||
catch (Exception reloadException)
|
||||
{
|
||||
this.logger.LogError(reloadException, $"Failed to reload plugins after editing assistant plugin '{plugin.Name}' ({plugin.Id}).");
|
||||
await this.TryRestoreEditedAssistantPluginAsync(pluginFile, backupFile, token);
|
||||
return UpdateError(plugin, pluginDirectory, string.Format(TB("Unexpected error: {0}"), reloadException.Message));
|
||||
}
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
this.logger.LogError(e, $"Failed to update assistant plugin '{plugin.Name}' ({plugin.Id}) at '{pluginDirectory}'.");
|
||||
await this.TryRestoreEditedAssistantPluginAsync(pluginFile, backupFile, token);
|
||||
return UpdateError(plugin, pluginDirectory, string.Format(TB("Unexpected error: {0}"), e.Message));
|
||||
}
|
||||
finally
|
||||
{
|
||||
this.TryDeleteFile(tempFile, "assistant plugin edit temp file");
|
||||
|
||||
this.installSemaphore.Release();
|
||||
}
|
||||
}
|
||||
|
||||
private async Task<AssistantPluginInstallResult> InstallStagedAssistantAsync(string assistantPluginsRoot, AssistantPluginValidationResult validation, CancellationToken token)
|
||||
{
|
||||
var stagingDirectory = validation.StagingDirectory;
|
||||
var assistantPlugin = validation.AssistantPlugin!;
|
||||
string? backupDirectory = null;
|
||||
string? finalDirectory = null;
|
||||
var replacedExisting = false;
|
||||
var movedIntoPlace = false;
|
||||
|
||||
try
|
||||
{
|
||||
Directory.CreateDirectory(assistantPluginsRoot);
|
||||
finalDirectory = DetermineFinalDirectory(assistantPluginsRoot, assistantPlugin);
|
||||
if (!IsPathInsideDirectory(assistantPluginsRoot, finalDirectory))
|
||||
return Error(TB("The resolved plugin directory is outside the assistant plugin directory."));
|
||||
|
||||
var replacementIssue = GetAssistantReplacementIssue(assistantPlugin.Id);
|
||||
if (!string.IsNullOrWhiteSpace(replacementIssue))
|
||||
return Error(replacementIssue);
|
||||
|
||||
if (Directory.Exists(finalDirectory))
|
||||
{
|
||||
replacedExisting = true;
|
||||
|
||||
// The backup goes to a directory outside the plugin root, so the plugin loader
|
||||
// cannot discover it during the reload below. Otherwise, the previous version
|
||||
// would be loaded a second time, next to the version we are installing:
|
||||
backupDirectory = CreateInstallBackupDirectory(assistantPlugin);
|
||||
Directory.CreateDirectory(Path.GetDirectoryName(backupDirectory)!);
|
||||
Directory.Move(finalDirectory, backupDirectory);
|
||||
}
|
||||
|
||||
Directory.Move(stagingDirectory, finalDirectory);
|
||||
movedIntoPlace = true;
|
||||
await PluginFactory.LoadAll(token);
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(backupDirectory))
|
||||
TryDeleteDirectory(backupDirectory, "assistant plugin backup", this.logger);
|
||||
|
||||
this.logger.LogInformation("Installed assistant plugin '{PluginName}' ({PluginId}) to '{PluginDirectory}'.", assistantPlugin.Name, assistantPlugin.Id, finalDirectory);
|
||||
return new(true, assistantPlugin.Id, assistantPlugin.Name, finalDirectory, replacedExisting, string.Empty);
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
this.logger.LogError(e, "Failed to install assistant plugin.");
|
||||
|
||||
// Only remove the target directory when this installation actually moved the plugin
|
||||
// there. Otherwise, when moving the previous plugin into the backup directory failed,
|
||||
// we would delete the still intact previous plugin:
|
||||
if (movedIntoPlace && !string.IsNullOrWhiteSpace(finalDirectory) && Directory.Exists(finalDirectory))
|
||||
TryDeleteDirectory(finalDirectory, "failed assistant plugin installation", this.logger);
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(backupDirectory) && Directory.Exists(backupDirectory) && !string.IsNullOrWhiteSpace(finalDirectory) && !Directory.Exists(finalDirectory))
|
||||
{
|
||||
try
|
||||
{
|
||||
Directory.Move(backupDirectory, finalDirectory);
|
||||
await PluginFactory.LoadAll(CancellationToken.None);
|
||||
}
|
||||
catch (Exception restoreException)
|
||||
{
|
||||
this.logger.LogError(restoreException, "Failed to restore the previous assistant plugin after a failed installation.");
|
||||
}
|
||||
}
|
||||
|
||||
return Error(string.Format(TB("Unexpected error: {0}"), e.Message));
|
||||
}
|
||||
finally
|
||||
{
|
||||
this.TryDeleteStagingDirectory(stagingDirectory);
|
||||
}
|
||||
}
|
||||
|
||||
private async Task<AssistantPluginValidationResult> ValidateIntoStagingAsync(string lua, CancellationToken token)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(lua))
|
||||
return AssistantPluginValidationResult.Failure(TB("No Lua plugin code was generated."));
|
||||
|
||||
if (!PluginFactory.IsInitialized)
|
||||
return AssistantPluginValidationResult.Failure(TB("The plugin system is not initialized yet."));
|
||||
|
||||
var pluginCode = lua.Trim();
|
||||
var stagingDirectory = Path.Join(Path.GetTempPath(), $"{ASSISTANT_BUILDER_DIRECTORY_PREFIX}.staging-{Guid.NewGuid():N}");
|
||||
|
||||
try
|
||||
{
|
||||
Directory.CreateDirectory(stagingDirectory);
|
||||
var stagedPluginFile = Path.Join(stagingDirectory, PLUGIN_FILE_NAME);
|
||||
await File.WriteAllTextAsync(stagedPluginFile, pluginCode, Encoding.UTF8, token);
|
||||
|
||||
var validation = await ValidateAssistantPluginCodeAsync(
|
||||
stagingDirectory,
|
||||
pluginCode,
|
||||
TB("The generated plugin is not an assistant plugin. Issue: {0}"),
|
||||
TB("The generated assistant plugin is invalid. Issue: {0}"),
|
||||
TB("The generated assistant plugin uses the ID of another installed plugin."),
|
||||
token);
|
||||
|
||||
if (!validation.Success || validation.AssistantPlugin is null)
|
||||
this.TryDeleteStagingDirectory(stagingDirectory);
|
||||
|
||||
return validation with { StagingDirectory = stagingDirectory };
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
this.logger.LogError(e, "Failed to validate generated assistant plugin.");
|
||||
this.TryDeleteStagingDirectory(stagingDirectory);
|
||||
return AssistantPluginValidationResult.Failure(string.Format(TB("Unexpected error: {0}"), e.Message));
|
||||
}
|
||||
}
|
||||
|
||||
private async Task<AssistantPluginValidationResult> ValidateInPluginDirectoryAsync(string lua, string pluginDirectory, CancellationToken token)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(lua))
|
||||
return AssistantPluginValidationResult.Failure(TB("No Lua plugin code was generated."));
|
||||
|
||||
if (!PluginFactory.IsInitialized)
|
||||
return AssistantPluginValidationResult.Failure(TB("The plugin system is not initialized yet."));
|
||||
|
||||
try
|
||||
{
|
||||
return await ValidateAssistantPluginCodeAsync(
|
||||
pluginDirectory,
|
||||
lua.Trim(),
|
||||
TB("The edited plugin is not an assistant plugin. Issue: {0}"),
|
||||
TB("The edited assistant plugin is invalid. Issue: {0}"),
|
||||
TB("The edited assistant plugin uses the ID of another installed plugin."),
|
||||
token);
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
this.logger.LogError(e, "Failed to validate edited assistant plugin.");
|
||||
return AssistantPluginValidationResult.Failure(string.Format(TB("Unexpected error: {0}"), e.Message));
|
||||
}
|
||||
}
|
||||
|
||||
private static async Task<AssistantPluginValidationResult> ValidateAssistantPluginCodeAsync(string pluginDirectory, string pluginCode,
|
||||
string notAssistantIssue, string invalidAssistantIssue, string conflictingPluginIdIssue, CancellationToken token)
|
||||
{
|
||||
// The plugin is not installed yet: it sits in a staging directory outside the installed
|
||||
// plugins directory. We allow that directory as the module base, so the plugin can load its
|
||||
// own Lua modules, e.g., an icon.lua, while we validate it:
|
||||
var plugin = await PluginFactory.Load(pluginDirectory, pluginCode, token, pluginDirectory);
|
||||
if (plugin is not PluginAssistants assistantPlugin)
|
||||
return AssistantPluginValidationResult.Failure(string.Format(notAssistantIssue, string.Join("; ", plugin.Issues)));
|
||||
|
||||
if (!assistantPlugin.IsValid)
|
||||
return AssistantPluginValidationResult.Failure(string.Format(invalidAssistantIssue, string.Join("; ", assistantPlugin.Issues)));
|
||||
|
||||
// Plugin IDs must be unique across all plugin types: several lookups resolve a plugin by its
|
||||
// ID alone, e.g., the base language plugin in PluginFactory.Starting. An assistant plugin
|
||||
// carrying the ID of a language or configuration plugin would break those lookups. Reusing
|
||||
// the ID of another local assistant plugin stays allowed: that is how updating one works.
|
||||
if (PluginFactory.AvailablePlugins.Any(availablePlugin => availablePlugin.Id == assistantPlugin.Id && (availablePlugin.IsInternal || availablePlugin.Type is not PluginType.ASSISTANT)))
|
||||
return AssistantPluginValidationResult.Failure(conflictingPluginIdIssue);
|
||||
|
||||
return new(true, string.Empty, assistantPlugin, string.Empty);
|
||||
}
|
||||
|
||||
private static bool TryGetAssistantPluginsRoot(out string assistantPluginsRoot, out string issue)
|
||||
{
|
||||
assistantPluginsRoot = string.Empty;
|
||||
issue = string.Empty;
|
||||
|
||||
var dataDirectory = SettingsManager.DataDirectory;
|
||||
if (string.IsNullOrWhiteSpace(dataDirectory))
|
||||
{
|
||||
issue = TB("The AI Studio data directory is not initialized yet.");
|
||||
return false;
|
||||
}
|
||||
|
||||
assistantPluginsRoot = Path.Join(dataDirectory, "plugins", PluginType.ASSISTANT.GetDirectory());
|
||||
return true;
|
||||
}
|
||||
|
||||
private static string GetAssistantDeletionEligibilityIssue(IAvailablePlugin plugin)
|
||||
{
|
||||
if (plugin.Type is not PluginType.ASSISTANT)
|
||||
return TB("Only assistant plugins can be deleted.");
|
||||
|
||||
if (plugin.IsInternal)
|
||||
return TB("Internal assistant plugins cannot be deleted.");
|
||||
|
||||
if (plugin.IsManagedByConfigServer)
|
||||
return TB("Config Server managed assistant plugins cannot be deleted.");
|
||||
|
||||
if (string.IsNullOrWhiteSpace(plugin.LocalPath))
|
||||
return TB("The assistant plugin has no local directory.");
|
||||
|
||||
var assistantPlugin = PluginFactory.RunningPlugins
|
||||
.OfType<PluginAssistants>()
|
||||
.FirstOrDefault(candidate => candidate.Id == plugin.Id && IsSameDirectory(candidate.PluginPath, plugin.LocalPath));
|
||||
|
||||
if (assistantPlugin is null || assistantPlugin.IsInternal || !assistantPlugin.IsAssistantBuilderGenerated)
|
||||
return TB("Only assistants generated by the Assistant Builder can be deleted.");
|
||||
|
||||
if (assistantPlugin.IsManagedByConfigServer)
|
||||
return TB("Config Server managed assistant plugins cannot be deleted.");
|
||||
|
||||
if (!TryGetAssistantPluginsRoot(out var assistantPluginsRoot, out var rootIssue))
|
||||
return rootIssue;
|
||||
|
||||
if (!IsPathInsideDirectory(assistantPluginsRoot, plugin.LocalPath) || IsSameDirectory(assistantPluginsRoot, plugin.LocalPath))
|
||||
return TB("The assistant plugin directory is outside the local assistant plugin directory.");
|
||||
|
||||
return Directory.Exists(plugin.LocalPath)
|
||||
? string.Empty
|
||||
: TB("The assistant plugin directory does not exist.");
|
||||
}
|
||||
|
||||
private void TryDeleteStagingDirectory(string stagingDirectory) => TryDeleteDirectory(stagingDirectory, "assistant plugin staging", this.logger);
|
||||
|
||||
private static string DetermineFinalDirectory(string assistantPluginsRoot, PluginAssistants assistantPlugin)
|
||||
{
|
||||
var existingPlugin = FindReplaceableAssistantPlugin(assistantPlugin.Id);
|
||||
return existingPlugin is not null
|
||||
? existingPlugin.LocalPath
|
||||
: Path.Join(assistantPluginsRoot, CreatePluginDirectoryName(assistantPlugin));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Finds the local assistant plugin that an installation with the given ID would replace.
|
||||
/// </summary>
|
||||
/// <param name="pluginId">The ID of the assistant plugin about to be installed.</param>
|
||||
/// <returns>The plugin that would be replaced, or null when the installation adds a new plugin.</returns>
|
||||
private static IAvailablePlugin? FindReplaceableAssistantPlugin(Guid pluginId) => PluginFactory.AvailablePlugins
|
||||
.OfType<IAvailablePlugin>()
|
||||
.FirstOrDefault(plugin => plugin.Type is PluginType.ASSISTANT && plugin.Id == pluginId && !plugin.IsInternal);
|
||||
|
||||
/// <summary>
|
||||
/// Collects the metadata an archive declares about itself, together with the information about
|
||||
/// the installed plugin it would replace.
|
||||
/// </summary>
|
||||
/// <param name="assistantPlugin">The validated assistant plugin from the archive.</param>
|
||||
/// <returns>The preview shown to the user before the installation starts.</returns>
|
||||
private static PluginImportPreview CreateImportPreview(PluginAssistants assistantPlugin) => new(assistantPlugin, FindReplaceableAssistantPlugin(assistantPlugin.Id));
|
||||
|
||||
/// <summary>
|
||||
/// Checks whether an installation may replace the assistant plugin that currently uses the given ID.
|
||||
/// Plugins deployed by a Config Server belong to the organization's IT, so neither an import nor
|
||||
/// the Assistant Builder may overwrite them.
|
||||
/// </summary>
|
||||
/// <param name="pluginId">The ID of the assistant plugin about to be installed.</param>
|
||||
/// <returns>A user-facing issue when the existing plugin must not be replaced, an empty string otherwise.</returns>
|
||||
private static string GetAssistantReplacementIssue(Guid pluginId)
|
||||
{
|
||||
var existingPlugin = FindReplaceableAssistantPlugin(pluginId);
|
||||
if (existingPlugin is null)
|
||||
return string.Empty;
|
||||
|
||||
if (existingPlugin.IsManagedByConfigServer)
|
||||
return TB("Config server managed assistant plugins cannot be replaced.");
|
||||
|
||||
if (string.IsNullOrWhiteSpace(existingPlugin.LocalPath))
|
||||
return string.Empty;
|
||||
|
||||
// The metadata above and the running plugin read the same Lua field. We check both, though,
|
||||
// just like the deletion path does:
|
||||
var runningPlugin = PluginFactory.RunningPlugins
|
||||
.OfType<PluginAssistants>()
|
||||
.FirstOrDefault(candidate => candidate.Id == pluginId && IsSameDirectory(candidate.PluginPath, existingPlugin.LocalPath));
|
||||
|
||||
return runningPlugin?.IsManagedByConfigServer is true
|
||||
? TB("Config server managed assistant plugins cannot be replaced.")
|
||||
: string.Empty;
|
||||
}
|
||||
|
||||
private static string CreatePluginDirectoryName(PluginAssistants assistantPlugin)
|
||||
{
|
||||
var safeName = CreateSafeDirectoryNamePart(assistantPlugin.Name);
|
||||
return $"{safeName}-{assistantPlugin.Id:N}";
|
||||
}
|
||||
|
||||
private static string CreateSafeDirectoryNamePart(string name)
|
||||
{
|
||||
var sb = new StringBuilder();
|
||||
var invalidChars = Path.GetInvalidFileNameChars().ToHashSet();
|
||||
|
||||
foreach (var character in name.Trim())
|
||||
{
|
||||
if (char.IsLetterOrDigit(character))
|
||||
{
|
||||
sb.Append(char.ToLowerInvariant(character));
|
||||
continue;
|
||||
}
|
||||
|
||||
if (character is '-' or '_' or '.' && !invalidChars.Contains(character))
|
||||
{
|
||||
sb.Append(character);
|
||||
continue;
|
||||
}
|
||||
|
||||
AppendSeparator();
|
||||
}
|
||||
|
||||
var safeName = sb.ToString().Trim('-', '.');
|
||||
if (safeName.Length > DIRECTORY_PREFIX_MAX_LEN)
|
||||
safeName = safeName[..DIRECTORY_PREFIX_MAX_LEN].Trim('-', '.');
|
||||
|
||||
return string.IsNullOrWhiteSpace(safeName)
|
||||
? ASSISTANT_BUILDER_DIRECTORY_PREFIX
|
||||
: safeName;
|
||||
|
||||
void AppendSeparator()
|
||||
{
|
||||
if (sb.Length == 0 || sb[^1] == '-')
|
||||
return;
|
||||
|
||||
sb.Append('-');
|
||||
}
|
||||
}
|
||||
|
||||
private static bool IsPathInsideDirectory(string parentDirectory, string path)
|
||||
{
|
||||
var parentPath = Path.GetFullPath(parentDirectory).TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar) + Path.DirectorySeparatorChar;
|
||||
var childPath = Path.GetFullPath(path).TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar) + Path.DirectorySeparatorChar;
|
||||
return childPath.StartsWith(parentPath, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
private static bool IsSameDirectory(string firstDirectory, string secondDirectory)
|
||||
{
|
||||
var firstPath = Path.GetFullPath(firstDirectory).TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar);
|
||||
var secondPath = Path.GetFullPath(secondDirectory).TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar);
|
||||
return string.Equals(firstPath, secondPath, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
private static string CreateDeleteBackupDirectory(IAvailablePlugin plugin)
|
||||
{
|
||||
var backupRoot = Path.Join(SettingsManager.DataDirectory, DELETE_BACKUP_DIRECTORY);
|
||||
return Path.Join(backupRoot, $"assistant-{plugin.Id:N}-{Guid.NewGuid():N}");
|
||||
}
|
||||
|
||||
private static string CreateInstallBackupDirectory(IPluginMetadata plugin)
|
||||
{
|
||||
var backupRoot = Path.Join(SettingsManager.DataDirectory, INSTALL_BACKUP_DIRECTORY);
|
||||
return Path.Join(backupRoot, $"assistant-{plugin.Id:N}-{Guid.NewGuid():N}");
|
||||
}
|
||||
|
||||
private async Task TryRestoreDeletedAssistantPluginAsync(IAvailablePlugin plugin, string pluginDirectory, string backupDirectory, bool wasEnabled, List<PluginAssistantAudit> removedAudits, CancellationToken token)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (!Directory.Exists(pluginDirectory) && Directory.Exists(backupDirectory))
|
||||
Directory.Move(backupDirectory, pluginDirectory);
|
||||
|
||||
if (wasEnabled && !this.settingsManager.ConfigurationData.EnabledPlugins.Contains(plugin.Id))
|
||||
this.settingsManager.ConfigurationData.EnabledPlugins.Add(plugin.Id);
|
||||
|
||||
if (removedAudits.Count > 0)
|
||||
{
|
||||
this.settingsManager.ConfigurationData.AssistantPluginAudits.RemoveAll(audit => audit.PluginId == plugin.Id);
|
||||
this.settingsManager.ConfigurationData.AssistantPluginAudits.AddRange(removedAudits);
|
||||
}
|
||||
|
||||
await this.settingsManager.StoreSettings();
|
||||
await PluginFactory.LoadAll(token);
|
||||
}
|
||||
catch (Exception restoreException)
|
||||
{
|
||||
this.logger.LogError(restoreException, $"Failed to restore assistant plugin '{plugin.Name}' ({plugin.Id}) after a failed delete.");
|
||||
}
|
||||
}
|
||||
|
||||
private async Task TryRestoreEditedAssistantPluginAsync(string pluginFile, string backupFile, CancellationToken token)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(backupFile) || !File.Exists(backupFile))
|
||||
return;
|
||||
|
||||
if (File.Exists(pluginFile))
|
||||
File.Delete(pluginFile);
|
||||
|
||||
File.Move(backupFile, pluginFile);
|
||||
await PluginFactory.LoadAll(token);
|
||||
}
|
||||
catch (Exception restoreException)
|
||||
{
|
||||
this.logger.LogError(restoreException, $"Failed to restore assistant plugin file '{pluginFile}' after a failed edit.");
|
||||
}
|
||||
}
|
||||
|
||||
private static void TryDeleteDirectory(string directory, string directoryDescription, ILogger logger)
|
||||
{
|
||||
if (!Directory.Exists(directory))
|
||||
return;
|
||||
|
||||
try
|
||||
{
|
||||
Directory.Delete(directory, true);
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
logger.LogError(e, $"Failed to delete {directoryDescription} directory '{directory}'.");
|
||||
}
|
||||
}
|
||||
|
||||
private void TryDeleteFile(string filePath, string fileDescription)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(filePath) || !File.Exists(filePath))
|
||||
return;
|
||||
|
||||
try
|
||||
{
|
||||
File.Delete(filePath);
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
this.logger.LogError(e, $"Failed to delete {fileDescription} '{filePath}'.");
|
||||
}
|
||||
}
|
||||
|
||||
private sealed record AssistantPluginValidationResult(bool Success, string StagingDirectory, PluginAssistants? AssistantPlugin, string Issue)
|
||||
{
|
||||
public static AssistantPluginValidationResult Failure(string issue) => new(false, string.Empty, null, issue);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
namespace AIStudio.Tools.Services;
|
||||
|
||||
/// <summary>
|
||||
/// What deleting a local configuration plugin takes with it, besides the plugin directory itself.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// A configuration plugin owns everything it configured. Removing it therefore removes its providers,
|
||||
/// data sources, chat templates, and profiles, and it resets the settings it had locked. Users cannot
|
||||
/// see any of that on the plugins page, so we show it before they confirm the deletion.
|
||||
/// </remarks>
|
||||
public sealed record ConfigurationPluginDeleteSummary(
|
||||
int LlmProviders,
|
||||
int TranscriptionProviders,
|
||||
int EmbeddingProviders,
|
||||
int DataSources,
|
||||
int ChatTemplates,
|
||||
int Profiles,
|
||||
int DocumentAnalysisPolicies,
|
||||
int LockedSettings,
|
||||
int MandatoryInfos,
|
||||
int Introductions)
|
||||
{
|
||||
/// <summary>
|
||||
/// An empty summary, used when the configuration plugin is not running and we cannot tell what it configured.
|
||||
/// </summary>
|
||||
public static readonly ConfigurationPluginDeleteSummary EMPTY = new(0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
|
||||
|
||||
/// <summary>
|
||||
/// True when the deletion affects anything beyond the plugin directory.
|
||||
/// </summary>
|
||||
public bool HasAnyConsequence =>
|
||||
this.LlmProviders > 0 ||
|
||||
this.TranscriptionProviders > 0 ||
|
||||
this.EmbeddingProviders > 0 ||
|
||||
this.DataSources > 0 ||
|
||||
this.ChatTemplates > 0 ||
|
||||
this.Profiles > 0 ||
|
||||
this.DocumentAnalysisPolicies > 0 ||
|
||||
this.LockedSettings > 0 ||
|
||||
this.MandatoryInfos > 0 ||
|
||||
this.Introductions > 0;
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
using AIStudio.Tools.PluginSystem;
|
||||
|
||||
namespace AIStudio.Tools.Services;
|
||||
|
||||
/// <summary>
|
||||
/// A provider or data source a configuration plugin brings, and where it sends data to.
|
||||
/// </summary>
|
||||
/// <param name="Type">The kind of configuration object.</param>
|
||||
/// <param name="Name">The name the configuration gives it.</param>
|
||||
/// <param name="Endpoint">The host of a self-hosted destination, or the name of the cloud provider.</param>
|
||||
public sealed record ConfigurationPluginDestination(PluginConfigurationObjectType Type, string Name, string Endpoint);
|
||||
@@ -0,0 +1,38 @@
|
||||
namespace AIStudio.Tools.Services;
|
||||
|
||||
/// <summary>
|
||||
/// What a configuration plugin would set up, read from the archive before anything is installed.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// A configuration takes effect the moment it is installed, and it has no on/off switch. The import
|
||||
/// dialog is therefore the only place where users can see what they are about to accept, which is
|
||||
/// why this carries the destinations of providers and data sources and not just their number.
|
||||
/// </remarks>
|
||||
/// <param name="Destinations">The providers and data sources, together with where they send data to.</param>
|
||||
/// <param name="ChatTemplates">How many chat templates the configuration adds.</param>
|
||||
/// <param name="Profiles">How many profiles the configuration adds.</param>
|
||||
/// <param name="DocumentAnalysisPolicies">How many document analysis policies the configuration adds.</param>
|
||||
/// <param name="DeclaredSettings">How many settings the configuration takes over.</param>
|
||||
/// <param name="MandatoryInfos">How many mandatory information texts users must accept.</param>
|
||||
/// <param name="Introductions">How many introductions the configuration adds to the welcome page.</param>
|
||||
public sealed record ConfigurationPluginImportSummary(
|
||||
IReadOnlyList<ConfigurationPluginDestination> Destinations,
|
||||
int ChatTemplates,
|
||||
int Profiles,
|
||||
int DocumentAnalysisPolicies,
|
||||
int DeclaredSettings,
|
||||
int MandatoryInfos,
|
||||
int Introductions)
|
||||
{
|
||||
/// <summary>
|
||||
/// True when the configuration sets up anything at all.
|
||||
/// </summary>
|
||||
public bool HasAnyContent =>
|
||||
this.Destinations.Count > 0 ||
|
||||
this.ChatTemplates > 0 ||
|
||||
this.Profiles > 0 ||
|
||||
this.DocumentAnalysisPolicies > 0 ||
|
||||
this.DeclaredSettings > 0 ||
|
||||
this.MandatoryInfos > 0 ||
|
||||
this.Introductions > 0;
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
namespace AIStudio.Tools.Services;
|
||||
|
||||
public sealed record PluginDeleteResult(bool Success, Guid PluginId, string PluginName, string PluginDirectory, string Issue);
|
||||
@@ -8,7 +8,10 @@ namespace AIStudio.Tools.Services;
|
||||
/// </summary>
|
||||
/// <param name="Plugin">The plugin from the archive, with the metadata it declares about itself.</param>
|
||||
/// <param name="ExistingPlugin">The installed plugin that gets replaced or null when the archive adds a new plugin.</param>
|
||||
public sealed record PluginImportPreview(IPluginMetadata Plugin, IAvailablePlugin? ExistingPlugin)
|
||||
/// <param name="ConfigurationSummary">
|
||||
/// What a configuration plugin would set up. Null for every other plugin type.
|
||||
/// </param>
|
||||
public sealed record PluginImportPreview(IPluginMetadata Plugin, IAvailablePlugin? ExistingPlugin, ConfigurationPluginImportSummary? ConfigurationSummary = null)
|
||||
{
|
||||
/// <summary>
|
||||
/// True when an installed plugin with the same ID gets replaced.
|
||||
|
||||
@@ -0,0 +1,116 @@
|
||||
using System.Text;
|
||||
using AIStudio.Tools.PluginSystem;
|
||||
|
||||
namespace AIStudio.Tools.Services;
|
||||
|
||||
public sealed partial class PluginInstallService
|
||||
{
|
||||
/// <summary>
|
||||
/// Checks whether generated Lua assistant plugin code can be loaded and installed.
|
||||
/// The plugin is written to a temporary staging directory and validated through the
|
||||
/// normal plugin loader, but it is not moved into the user plugin directory.
|
||||
/// </summary>
|
||||
/// <param name="lua">The full generated <c>plugin.lua</c> content.</param>
|
||||
/// <param name="token">A cancellation token for file IO and Lua validation.</param>
|
||||
/// <returns>
|
||||
/// Check result that contains success state, plugin metadata, and a user-facing issue when validation failed.
|
||||
/// </returns>
|
||||
public async Task<AssistantPluginCheckResult> CheckInstallabilityAsync(string lua, CancellationToken token)
|
||||
{
|
||||
if (!TryGetPluginRoot(PluginType.ASSISTANT, out var assistantPluginsRoot, out var rootIssue))
|
||||
return CheckError(rootIssue);
|
||||
|
||||
await this.installSemaphore.WaitAsync(token);
|
||||
var stagingDirectory = string.Empty;
|
||||
try
|
||||
{
|
||||
var validation = await this.ValidateIntoStagingAsync(lua, token);
|
||||
if (!validation.Success || validation.AssistantPlugin is null)
|
||||
return CheckError(validation.Issue);
|
||||
|
||||
stagingDirectory = validation.StagingDirectory;
|
||||
var finalDirectory = DetermineFinalDirectory(assistantPluginsRoot, validation.AssistantPlugin, PluginType.ASSISTANT);
|
||||
if (!IsPathInsideDirectory(assistantPluginsRoot, finalDirectory))
|
||||
return CheckError(TB("The resolved plugin directory is outside the plugin directory."));
|
||||
|
||||
return new(true, validation.AssistantPlugin.Id, validation.AssistantPlugin.Name, string.Empty);
|
||||
}
|
||||
finally
|
||||
{
|
||||
this.TryDeleteStagingDirectory(stagingDirectory);
|
||||
this.installSemaphore.Release();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Installs generated Lua assistant plugin code into the user plugin directory.
|
||||
/// Writes the plugin into a temporary staging directory first, validates it through the
|
||||
/// normal plugin loader, then moves into <c>data/plugins/assistants</c>.
|
||||
/// If plugin with same ID already exists, the existing directory is moved
|
||||
/// aside as backup and restored when replacement fails.
|
||||
/// </summary>
|
||||
/// <param name="lua">The full generated <c>plugin.lua</c> content.</param>
|
||||
/// <param name="token">A cancellation token for file IO, Lua validation, and plugin reload.</param>
|
||||
/// <returns>
|
||||
/// Installation result that contains success state, installed plugin metadata, final directory,
|
||||
/// whether an existing plugin was replaced, and user-facing issue when installation failed.
|
||||
/// </returns>
|
||||
public async Task<AssistantPluginInstallResult> InstallAsync(string lua, CancellationToken token)
|
||||
{
|
||||
if (!TryGetPluginRoot(PluginType.ASSISTANT, out var assistantPluginsRoot, out var rootIssue))
|
||||
return Error(rootIssue);
|
||||
|
||||
await this.installSemaphore.WaitAsync(token);
|
||||
try
|
||||
{
|
||||
var validation = await this.ValidateIntoStagingAsync(lua, token);
|
||||
if (!validation.Success || validation.AssistantPlugin is null)
|
||||
return Error(validation.Issue);
|
||||
|
||||
return await this.InstallStagedPluginAsync(assistantPluginsRoot, validation, PluginType.ASSISTANT, token);
|
||||
}
|
||||
finally
|
||||
{
|
||||
this.installSemaphore.Release();
|
||||
}
|
||||
}
|
||||
|
||||
private async Task<PluginValidationResult> ValidateIntoStagingAsync(string lua, CancellationToken token)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(lua))
|
||||
return PluginValidationResult.Failure(TB("No Lua plugin code was generated."));
|
||||
|
||||
if (!PluginFactory.IsInitialized)
|
||||
return PluginValidationResult.Failure(TB("The plugin system is not initialized yet."));
|
||||
|
||||
var pluginCode = lua.Trim();
|
||||
var stagingDirectory = Path.Join(Path.GetTempPath(), $"{ASSISTANT_BUILDER_DIRECTORY_PREFIX}.staging-{Guid.NewGuid():N}");
|
||||
|
||||
try
|
||||
{
|
||||
Directory.CreateDirectory(stagingDirectory);
|
||||
var stagedPluginFile = Path.Join(stagingDirectory, PLUGIN_FILE_NAME);
|
||||
await File.WriteAllTextAsync(stagedPluginFile, pluginCode, Encoding.UTF8, token);
|
||||
|
||||
var validation = await ValidatePluginCodeAsync(
|
||||
stagingDirectory,
|
||||
pluginCode,
|
||||
[PluginType.ASSISTANT],
|
||||
TB("The generated plugin is not an assistant plugin. Issue: {0}"),
|
||||
TB("The generated assistant plugin is invalid. Issue: {0}"),
|
||||
TB("The generated assistant plugin uses the ID of another installed plugin."),
|
||||
token);
|
||||
|
||||
if (!validation.Success || validation.AssistantPlugin is null)
|
||||
this.TryDeleteStagingDirectory(stagingDirectory);
|
||||
|
||||
return validation with { StagingDirectory = stagingDirectory };
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
this.logger.LogError(e, "Failed to validate generated assistant plugin.");
|
||||
this.TryDeleteStagingDirectory(stagingDirectory);
|
||||
return PluginValidationResult.Failure(string.Format(TB("Unexpected error: {0}"), e.Message));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,283 @@
|
||||
using AIStudio.Settings;
|
||||
using AIStudio.Settings.DataModel;
|
||||
using AIStudio.Tools.Media;
|
||||
using AIStudio.Tools.PluginSystem;
|
||||
using AIStudio.Tools.PluginSystem.Assistants;
|
||||
|
||||
namespace AIStudio.Tools.Services;
|
||||
|
||||
public sealed partial class PluginInstallService
|
||||
{
|
||||
/// <summary>
|
||||
/// The plugin types users may remove through the user interface.
|
||||
/// </summary>
|
||||
private static readonly PluginType[] DELETABLE_PLUGIN_TYPES = [PluginType.ASSISTANT, PluginType.CONFIGURATION, PluginType.LANGUAGE];
|
||||
|
||||
/// <summary>
|
||||
/// Checks whether a plugin is one that users may delete.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// This decides whether the delete action is offered at all. Whether it may run right now is a
|
||||
/// different question: an assistant with running background work stays visible but blocked.
|
||||
/// </remarks>
|
||||
public static bool CanDeletePlugin(IAvailablePlugin plugin) => string.IsNullOrWhiteSpace(GetDeletionEligibilityIssue(plugin));
|
||||
|
||||
/// <summary>
|
||||
/// Collects what deleting a local configuration plugin removes besides the plugin directory.
|
||||
/// </summary>
|
||||
/// <param name="plugin">The configuration plugin about to be deleted.</param>
|
||||
/// <returns>
|
||||
/// The summary shown to the user before the deletion starts. It is empty when the plugin is not
|
||||
/// running, because we cannot tell what an unloadable plugin had configured.
|
||||
/// </returns>
|
||||
public ConfigurationPluginDeleteSummary BuildConfigurationDeleteSummary(IAvailablePlugin plugin)
|
||||
{
|
||||
var configurationPlugin = PluginFactory.RunningPlugins.OfType<PluginConfiguration>().FirstOrDefault(candidate => candidate.Id == plugin.Id);
|
||||
if (configurationPlugin is null)
|
||||
return ConfigurationPluginDeleteSummary.EMPTY;
|
||||
|
||||
var configObjects = configurationPlugin.ConfigObjects.ToList();
|
||||
var configurationData = this.settingsManager.ConfigurationData;
|
||||
|
||||
// Both maps record which configuration plugin manages a setting. Everything this plugin owns
|
||||
// returns to its default value once the plugin is gone:
|
||||
var lockedSettings =
|
||||
configurationData.ManagedLockedConfigurations.Count(entry => entry.Value == plugin.Id) +
|
||||
configurationData.ManagedEditableDefaults.Count(entry => entry.Value.ConfigPluginId == plugin.Id);
|
||||
|
||||
return new(
|
||||
LlmProviders: CountObjects(PluginConfigurationObjectType.LLM_PROVIDER),
|
||||
TranscriptionProviders: CountObjects(PluginConfigurationObjectType.TRANSCRIPTION_PROVIDER),
|
||||
EmbeddingProviders: CountObjects(PluginConfigurationObjectType.EMBEDDING_PROVIDER),
|
||||
DataSources: CountObjects(PluginConfigurationObjectType.DATA_SOURCE),
|
||||
ChatTemplates: CountObjects(PluginConfigurationObjectType.CHAT_TEMPLATE),
|
||||
Profiles: CountObjects(PluginConfigurationObjectType.PROFILE),
|
||||
DocumentAnalysisPolicies: CountObjects(PluginConfigurationObjectType.DOCUMENT_ANALYSIS_POLICY),
|
||||
LockedSettings: lockedSettings,
|
||||
MandatoryInfos: configurationPlugin.MandatoryInfos.Count,
|
||||
Introductions: configurationPlugin.Introductions.Count);
|
||||
|
||||
int CountObjects(PluginConfigurationObjectType type) => configObjects.Count(configObject => configObject.Type == type);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Checks whether an assistant still owns running or canceling background work.
|
||||
/// </summary>
|
||||
public bool HasActiveAssistantWork(Guid pluginId)
|
||||
{
|
||||
var instanceId = pluginId.ToString();
|
||||
if (this.assistantSessionService.GetSnapshots().Any(snapshot => snapshot.IsActive && string.Equals(snapshot.Key.InstanceId, instanceId, StringComparison.Ordinal)))
|
||||
return true;
|
||||
|
||||
var ownerIdSuffix = $":{instanceId}";
|
||||
return this.mediaTranscriptionService.GetSnapshots().Any(snapshot =>
|
||||
snapshot is { IsBusy: true, Owner.Kind: MediaImportOwnerKind.ASSISTANT } &&
|
||||
snapshot.Owner.Id.EndsWith(ownerIdSuffix, StringComparison.Ordinal));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Deletes the directory of a plugin the user installed or placed themselves.
|
||||
/// The directory gets moved to a backup dir outside the plugin root so the plugin loader cannot
|
||||
/// discover it during reload. On failure, the directory and the related settings are restored.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// For a configuration plugin, we do not remove its providers, data sources, chat templates,
|
||||
/// profiles, or locked settings ourselves. The reload does that: it recognizes them as left over
|
||||
/// once their configuration plugin is gone, and it also deletes the related secrets from the OS
|
||||
/// keyring.<br/><br/>
|
||||
/// What the reload cannot recognize as left over is everything the user decided about the plugin
|
||||
/// itself: its activation state, the language choice of a language plugin, and the security audit
|
||||
/// of an assistant. Those are removed here, see ApplyDeleteSideEffects.
|
||||
/// </remarks>
|
||||
/// <param name="plugin">Metadata of the plugin to delete.</param>
|
||||
/// <param name="token">Cancellation token for settings storage and plugin reload.</param>
|
||||
/// <returns>
|
||||
/// Delete result that contains a success state, deleted plugin metadata, the original plugin directory,
|
||||
/// and a user-facing issue when deletion failed.
|
||||
/// </returns>
|
||||
public async Task<PluginDeleteResult> DeletePluginAsync(IAvailablePlugin plugin, CancellationToken token)
|
||||
{
|
||||
var deletionIssue = this.GetDeletionIssue(plugin);
|
||||
if (!string.IsNullOrWhiteSpace(deletionIssue))
|
||||
return DeleteError(plugin, plugin.LocalPath, deletionIssue);
|
||||
|
||||
await this.installSemaphore.WaitAsync(token);
|
||||
var pluginDirectory = plugin.LocalPath;
|
||||
var backupDirectory = string.Empty;
|
||||
var sideEffects = PluginDeleteSideEffects.NONE;
|
||||
|
||||
try
|
||||
{
|
||||
// Check again under the semaphore: another operation might have changed the plugin state
|
||||
// while we were waiting:
|
||||
deletionIssue = this.GetDeletionIssue(plugin);
|
||||
if (!string.IsNullOrWhiteSpace(deletionIssue))
|
||||
return DeleteError(plugin, pluginDirectory, deletionIssue);
|
||||
|
||||
backupDirectory = CreateDeleteBackupDirectory(plugin);
|
||||
Directory.CreateDirectory(Path.GetDirectoryName(backupDirectory)!);
|
||||
Directory.Move(pluginDirectory, backupDirectory);
|
||||
|
||||
sideEffects = this.ApplyDeleteSideEffects(plugin);
|
||||
if (sideEffects.HasChanges)
|
||||
await this.settingsManager.StoreSettings();
|
||||
|
||||
await PluginFactory.LoadAll(token);
|
||||
|
||||
TryDeleteDirectory(backupDirectory, "plugin delete backup", this.logger);
|
||||
this.logger.LogInformation($"Deleted {plugin.Type} plugin '{plugin.Name}' ({plugin.Id}) from '{pluginDirectory}'.");
|
||||
return new(true, plugin.Id, plugin.Name, pluginDirectory, string.Empty);
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
this.logger.LogError(e, $"Failed to delete {plugin.Type} plugin '{plugin.Name}' ({plugin.Id}) from '{pluginDirectory}'.");
|
||||
|
||||
await this.TryRestoreDeletedPluginAsync(plugin, pluginDirectory, backupDirectory, sideEffects, token);
|
||||
return DeleteError(plugin, pluginDirectory, string.Format(TB("Unexpected error: {0}"), e.Message));
|
||||
}
|
||||
finally
|
||||
{
|
||||
this.installSemaphore.Release();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Checks everything that prevents deleting a plugin right now.
|
||||
/// </summary>
|
||||
private string GetDeletionIssue(IAvailablePlugin plugin)
|
||||
{
|
||||
var eligibilityIssue = GetDeletionEligibilityIssue(plugin);
|
||||
if (!string.IsNullOrWhiteSpace(eligibilityIssue))
|
||||
return eligibilityIssue;
|
||||
|
||||
// An assistant must not be pulled away from under a user while it is still working:
|
||||
if (plugin.Type is PluginType.ASSISTANT && this.HasActiveAssistantWork(plugin.Id))
|
||||
return TB("The assistant cannot be deleted while background work is still running.");
|
||||
|
||||
return string.Empty;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Checks whether a plugin is one users may delete at all, regardless of its current state.
|
||||
/// </summary>
|
||||
private static string GetDeletionEligibilityIssue(IAvailablePlugin plugin)
|
||||
{
|
||||
if (!DELETABLE_PLUGIN_TYPES.Contains(plugin.Type))
|
||||
return TB("Only assistant, configuration, and language plugins can be deleted.");
|
||||
|
||||
if (plugin.IsInternal)
|
||||
return TB("Plugins shipped with AI Studio cannot be deleted.");
|
||||
|
||||
if (string.IsNullOrWhiteSpace(plugin.LocalPath))
|
||||
return TB("The plugin has no local directory.");
|
||||
|
||||
//
|
||||
// We decide by the plugin path, not by what a plugin declares about itself. Both
|
||||
// DEPLOYED_USING_CONFIG_SERVER and the Assistant Builder metadata are self-declared: a
|
||||
// locally placed plugin could claim to be deployed by an organization, or simply omit the
|
||||
// builder metadata, and would then be impossible to remove through the user interface, which
|
||||
// is exactly the situation this deletion is meant to resolve.
|
||||
//
|
||||
if (PluginFactory.IsEnterpriseConfigurationPath(plugin.LocalPath))
|
||||
return TB("Plugins deployed by your organization cannot be deleted.");
|
||||
|
||||
if (!PluginFactory.IsInsidePluginsRoot(plugin.LocalPath) || PluginFactory.IsPluginsRoot(plugin.LocalPath))
|
||||
return TB("This individual plugin’s directory is outside the expected plugins directory.");
|
||||
|
||||
return Directory.Exists(plugin.LocalPath) ? string.Empty : TB("The plugin directory does not exist.");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Removes everything the user decided about the plugin, and reports what was removed so a failed
|
||||
/// deletion can put it back.
|
||||
/// </summary>
|
||||
private PluginDeleteSideEffects ApplyDeleteSideEffects(IAvailablePlugin plugin)
|
||||
{
|
||||
var configurationData = this.settingsManager.ConfigurationData;
|
||||
|
||||
//
|
||||
// Nothing removes the activation state of a plugin which is gone. Should the user install
|
||||
// a plugin with the same ID again later, it would start enabled without ever having been
|
||||
// switched on. We ask for removal regardless of the plugin type: a configuration plugin
|
||||
// is never listed there, so this simply does nothing for it:
|
||||
//
|
||||
var wasEnabled = configurationData.EnabledPlugins.Remove(plugin.Id);
|
||||
|
||||
//
|
||||
// When the user had chosen this language plugin, the app would silently fall back to
|
||||
// English while the settings still point to the deleted plugin. We return the language
|
||||
// choice to automatic instead, so the settings stay truthful:
|
||||
//
|
||||
var wasChosenLanguage = plugin.Type is PluginType.LANGUAGE && configurationData.App.LanguagePluginId == plugin.Id;
|
||||
if (wasChosenLanguage)
|
||||
{
|
||||
configurationData.App.LanguageBehavior = LangBehavior.AUTO;
|
||||
configurationData.App.LanguagePluginId = Guid.Empty;
|
||||
}
|
||||
|
||||
//
|
||||
// The security audit belongs to the assistant code we checked. Another assistant installed
|
||||
// under the same ID later is different code, so it must be audited again:
|
||||
//
|
||||
List<PluginAssistantAudit> removedAudits = [];
|
||||
if (plugin.Type is PluginType.ASSISTANT)
|
||||
{
|
||||
removedAudits = [.. configurationData.AssistantPluginAudits.Where(audit => audit.PluginId == plugin.Id)];
|
||||
if (removedAudits.Count > 0)
|
||||
configurationData.AssistantPluginAudits.RemoveAll(audit => audit.PluginId == plugin.Id);
|
||||
}
|
||||
|
||||
return new(wasEnabled, wasChosenLanguage, removedAudits);
|
||||
}
|
||||
|
||||
private static string CreateDeleteBackupDirectory(IAvailablePlugin plugin)
|
||||
{
|
||||
var backupRoot = Path.Join(SettingsManager.DataDirectory, DELETE_BACKUP_DIRECTORY);
|
||||
return Path.Join(backupRoot, $"{plugin.Type.GetDirectory()}-{plugin.Id:N}-{Guid.NewGuid():N}");
|
||||
}
|
||||
|
||||
private async Task TryRestoreDeletedPluginAsync(IAvailablePlugin plugin, string pluginDirectory, string backupDirectory, PluginDeleteSideEffects sideEffects, CancellationToken token)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (!Directory.Exists(pluginDirectory) && Directory.Exists(backupDirectory))
|
||||
Directory.Move(backupDirectory, pluginDirectory);
|
||||
|
||||
var configurationData = this.settingsManager.ConfigurationData;
|
||||
if (sideEffects.WasEnabled && !configurationData.EnabledPlugins.Contains(plugin.Id))
|
||||
configurationData.EnabledPlugins.Add(plugin.Id);
|
||||
|
||||
if (sideEffects.WasChosenLanguage)
|
||||
{
|
||||
configurationData.App.LanguageBehavior = LangBehavior.MANUAL;
|
||||
configurationData.App.LanguagePluginId = plugin.Id;
|
||||
}
|
||||
|
||||
if (sideEffects.RemovedAudits.Count > 0)
|
||||
{
|
||||
configurationData.AssistantPluginAudits.RemoveAll(audit => audit.PluginId == plugin.Id);
|
||||
configurationData.AssistantPluginAudits.AddRange(sideEffects.RemovedAudits);
|
||||
}
|
||||
|
||||
if (sideEffects.HasChanges)
|
||||
await this.settingsManager.StoreSettings();
|
||||
|
||||
// The reload restores everything the plugin configured, because it is back in place:
|
||||
await PluginFactory.LoadAll(token);
|
||||
}
|
||||
catch (Exception restoreException)
|
||||
{
|
||||
this.logger.LogError(restoreException, $"Failed to restore {plugin.Type} plugin '{plugin.Name}' ({plugin.Id}) after a failed delete.");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// What deleting a plugin changed in the settings, so a failed deletion can undo it.
|
||||
/// </summary>
|
||||
private sealed record PluginDeleteSideEffects(bool WasEnabled, bool WasChosenLanguage, List<PluginAssistantAudit> RemovedAudits)
|
||||
{
|
||||
public static readonly PluginDeleteSideEffects NONE = new(false, false, []);
|
||||
|
||||
public bool HasChanges => this.WasEnabled || this.WasChosenLanguage || this.RemovedAudits.Count > 0;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,195 @@
|
||||
using System.Text;
|
||||
using AIStudio.Tools.PluginSystem;
|
||||
|
||||
namespace AIStudio.Tools.Services;
|
||||
|
||||
public sealed partial class PluginInstallService
|
||||
{
|
||||
/// <summary>
|
||||
/// Checks whether edited assistant plugin code can replace an installed local assistant plugin
|
||||
/// without writing the file.
|
||||
/// </summary>
|
||||
/// <param name="plugin">The installed local assistant plugin to validate against.</param>
|
||||
/// <param name="lua">The edited <c>plugin.lua</c> content.</param>
|
||||
/// <param name="token">Cancellation token for Lua validation.</param>
|
||||
/// <returns>Check result that contains success state, plugin metadata, and a user-facing issue when validation failed.</returns>
|
||||
public async Task<AssistantPluginCheckResult> CheckInstalledAssistantUpdateAsync(IAvailablePlugin plugin, string lua, CancellationToken token)
|
||||
{
|
||||
if (plugin.Type is not PluginType.ASSISTANT)
|
||||
return CheckError(TB("Only assistant plugins can be edited."));
|
||||
|
||||
if (plugin.IsInternal)
|
||||
return CheckError(TB("Internal assistant plugins cannot be edited."));
|
||||
|
||||
if (string.IsNullOrWhiteSpace(plugin.LocalPath))
|
||||
return CheckError(TB("The assistant plugin has no local directory."));
|
||||
|
||||
if (!TryGetPluginRoot(PluginType.ASSISTANT, out var assistantPluginsRoot, out var rootIssue))
|
||||
return CheckError(rootIssue);
|
||||
|
||||
var pluginDirectory = plugin.LocalPath;
|
||||
if (!IsPathInsideDirectory(assistantPluginsRoot, pluginDirectory) || IsSameDirectory(assistantPluginsRoot, pluginDirectory))
|
||||
return CheckError(TB("The assistant plugin directory is outside the local assistant plugin directory."));
|
||||
|
||||
if (!Directory.Exists(pluginDirectory))
|
||||
return CheckError(TB("The assistant plugin directory does not exist."));
|
||||
|
||||
await this.installSemaphore.WaitAsync(token);
|
||||
try
|
||||
{
|
||||
var validation = await this.ValidateInPluginDirectoryAsync(lua, pluginDirectory, token);
|
||||
if (!validation.Success || validation.AssistantPlugin is null)
|
||||
return CheckError(validation.Issue);
|
||||
|
||||
var assistantPlugin = validation.AssistantPlugin;
|
||||
return assistantPlugin.Id != plugin.Id
|
||||
? CheckError(TB("The edited assistant plugin must keep the same plugin ID."))
|
||||
: new(true, assistantPlugin.Id, assistantPlugin.Name, string.Empty);
|
||||
}
|
||||
finally
|
||||
{
|
||||
this.installSemaphore.Release();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Updates installed assistant plugin <c>plugin.lua</c> file.
|
||||
/// The edited Lua code is validated from the provided string before it is written,
|
||||
/// but validation uses existing plugin directory as loader context so
|
||||
/// <c>require(...)</c> can resolve companion files such as <c>icon.lua</c>.
|
||||
/// After successful validation, the current <c>plugin.lua</c> is backed up,
|
||||
/// replaced atomically through a temporary file in the plugin directory, and
|
||||
/// restored when the plugin reload fails.
|
||||
/// </summary>
|
||||
/// <param name="plugin">The installed local assistant plugin to update.</param>
|
||||
/// <param name="lua">The edited <c>plugin.lua</c> content.</param>
|
||||
/// <param name="token">Cancellation token for Lua validation, file IO, and plugin reload.</param>
|
||||
/// <returns>
|
||||
/// Update result that contains success state, updated plugin metadata, the plugin directory,
|
||||
/// and a user-facing issue when the update failed.
|
||||
/// </returns>
|
||||
public async Task<AssistantPluginUpdateResult> UpdateInstalledAssistantAsync(IAvailablePlugin plugin, string lua, CancellationToken token)
|
||||
{
|
||||
if (plugin.Type is not PluginType.ASSISTANT)
|
||||
return UpdateError(plugin, plugin.LocalPath, TB("Only assistant plugins can be edited."));
|
||||
|
||||
if (plugin.IsInternal)
|
||||
return UpdateError(plugin, plugin.LocalPath, TB("Internal assistant plugins cannot be edited."));
|
||||
|
||||
if (string.IsNullOrWhiteSpace(plugin.LocalPath))
|
||||
return UpdateError(plugin, string.Empty, TB("The assistant plugin has no local directory."));
|
||||
|
||||
if (!TryGetPluginRoot(PluginType.ASSISTANT, out var assistantPluginsRoot, out var rootIssue))
|
||||
return UpdateError(plugin, plugin.LocalPath, rootIssue);
|
||||
|
||||
var pluginDirectory = plugin.LocalPath;
|
||||
if (!IsPathInsideDirectory(assistantPluginsRoot, pluginDirectory) || IsSameDirectory(assistantPluginsRoot, pluginDirectory))
|
||||
return UpdateError(plugin, pluginDirectory, TB("The assistant plugin directory is outside the local assistant plugin directory."));
|
||||
|
||||
if (!Directory.Exists(pluginDirectory))
|
||||
return UpdateError(plugin, pluginDirectory, TB("The assistant plugin directory does not exist."));
|
||||
|
||||
var pluginFile = Path.Join(pluginDirectory, PLUGIN_FILE_NAME);
|
||||
if (!IsPathInsideDirectory(pluginDirectory, pluginFile))
|
||||
return UpdateError(plugin, pluginDirectory, TB("The plugin file is outside the assistant plugin directory."));
|
||||
|
||||
await this.installSemaphore.WaitAsync(token);
|
||||
var tempFile = string.Empty;
|
||||
var backupFile = string.Empty;
|
||||
|
||||
try
|
||||
{
|
||||
var validation = await this.ValidateInPluginDirectoryAsync(lua, pluginDirectory, token);
|
||||
if (!validation.Success || validation.AssistantPlugin is null)
|
||||
return UpdateError(plugin, pluginDirectory, validation.Issue);
|
||||
|
||||
var assistantPlugin = validation.AssistantPlugin;
|
||||
if (assistantPlugin.Id != plugin.Id)
|
||||
return UpdateError(plugin, pluginDirectory, TB("The edited assistant plugin must keep the same plugin ID."));
|
||||
|
||||
var pluginCode = lua.Trim();
|
||||
tempFile = Path.Join(pluginDirectory, $"{PLUGIN_FILE_NAME}.tmp-{Guid.NewGuid():N}");
|
||||
backupFile = Path.Join(pluginDirectory, $"{PLUGIN_FILE_NAME}.backup-{Guid.NewGuid():N}");
|
||||
|
||||
await File.WriteAllTextAsync(tempFile, pluginCode, Encoding.UTF8, token);
|
||||
|
||||
if (File.Exists(pluginFile))
|
||||
File.Replace(tempFile, pluginFile, backupFile);
|
||||
else
|
||||
File.Move(tempFile, pluginFile);
|
||||
|
||||
try
|
||||
{
|
||||
await PluginFactory.LoadAll(token);
|
||||
if (File.Exists(backupFile))
|
||||
File.Delete(backupFile);
|
||||
|
||||
this.logger.LogInformation($"Updated assistant plugin '{assistantPlugin.Name}' ({assistantPlugin.Id}) at '{pluginFile}'.");
|
||||
return new(true, assistantPlugin.Id, assistantPlugin.Name, pluginDirectory, string.Empty);
|
||||
}
|
||||
catch (Exception reloadException)
|
||||
{
|
||||
this.logger.LogError(reloadException, $"Failed to reload plugins after editing assistant plugin '{plugin.Name}' ({plugin.Id}).");
|
||||
await this.TryRestoreEditedAssistantPluginAsync(pluginFile, backupFile, token);
|
||||
return UpdateError(plugin, pluginDirectory, string.Format(TB("Unexpected error: {0}"), reloadException.Message));
|
||||
}
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
this.logger.LogError(e, $"Failed to update assistant plugin '{plugin.Name}' ({plugin.Id}) at '{pluginDirectory}'.");
|
||||
await this.TryRestoreEditedAssistantPluginAsync(pluginFile, backupFile, token);
|
||||
return UpdateError(plugin, pluginDirectory, string.Format(TB("Unexpected error: {0}"), e.Message));
|
||||
}
|
||||
finally
|
||||
{
|
||||
this.TryDeleteFile(tempFile, "assistant plugin edit temp file");
|
||||
|
||||
this.installSemaphore.Release();
|
||||
}
|
||||
}
|
||||
|
||||
private async Task<PluginValidationResult> ValidateInPluginDirectoryAsync(string lua, string pluginDirectory, CancellationToken token)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(lua))
|
||||
return PluginValidationResult.Failure(TB("No Lua plugin code was generated."));
|
||||
|
||||
if (!PluginFactory.IsInitialized)
|
||||
return PluginValidationResult.Failure(TB("The plugin system is not initialized yet."));
|
||||
|
||||
try
|
||||
{
|
||||
return await ValidatePluginCodeAsync(
|
||||
pluginDirectory,
|
||||
lua.Trim(),
|
||||
[PluginType.ASSISTANT],
|
||||
TB("The edited plugin is not an assistant plugin. Issue: {0}"),
|
||||
TB("The edited assistant plugin is invalid. Issue: {0}"),
|
||||
TB("The edited assistant plugin uses the ID of another installed plugin."),
|
||||
token);
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
this.logger.LogError(e, "Failed to validate edited assistant plugin.");
|
||||
return PluginValidationResult.Failure(string.Format(TB("Unexpected error: {0}"), e.Message));
|
||||
}
|
||||
}
|
||||
|
||||
private async Task TryRestoreEditedAssistantPluginAsync(string pluginFile, string backupFile, CancellationToken token)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(backupFile) || !File.Exists(backupFile))
|
||||
return;
|
||||
|
||||
if (File.Exists(pluginFile))
|
||||
File.Delete(pluginFile);
|
||||
|
||||
File.Move(backupFile, pluginFile);
|
||||
await PluginFactory.LoadAll(token);
|
||||
}
|
||||
catch (Exception restoreException)
|
||||
{
|
||||
this.logger.LogError(restoreException, $"Failed to restore assistant plugin file '{pluginFile}' after a failed edit.");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
namespace AIStudio.Tools.Services;
|
||||
|
||||
public sealed partial class PluginInstallService
|
||||
{
|
||||
private static bool IsPathInsideDirectory(string parentDirectory, string path)
|
||||
{
|
||||
var parentPath = Path.GetFullPath(parentDirectory).TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar) + Path.DirectorySeparatorChar;
|
||||
var childPath = Path.GetFullPath(path).TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar) + Path.DirectorySeparatorChar;
|
||||
return childPath.StartsWith(parentPath, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
private static bool IsSameDirectory(string firstDirectory, string secondDirectory)
|
||||
{
|
||||
var firstPath = Path.GetFullPath(firstDirectory).TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar);
|
||||
var secondPath = Path.GetFullPath(secondDirectory).TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar);
|
||||
return string.Equals(firstPath, secondPath, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
private void TryDeleteStagingDirectory(string stagingDirectory) => TryDeleteDirectory(stagingDirectory, "assistant plugin staging", this.logger);
|
||||
|
||||
private static void TryDeleteDirectory(string directory, string directoryDescription, ILogger logger)
|
||||
{
|
||||
if (!Directory.Exists(directory))
|
||||
return;
|
||||
|
||||
try
|
||||
{
|
||||
Directory.Delete(directory, true);
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
logger.LogError(e, $"Failed to delete {directoryDescription} directory '{directory}'.");
|
||||
}
|
||||
}
|
||||
|
||||
private void TryDeleteFile(string filePath, string fileDescription)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(filePath) || !File.Exists(filePath))
|
||||
return;
|
||||
|
||||
try
|
||||
{
|
||||
File.Delete(filePath);
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
this.logger.LogError(e, $"Failed to delete {fileDescription} '{filePath}'.");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,142 @@
|
||||
using System.Text;
|
||||
using AIStudio.Tools.PluginSystem;
|
||||
using AIStudio.Tools.PluginSystem.Assistants;
|
||||
using AIStudio.Tools.Rust;
|
||||
|
||||
namespace AIStudio.Tools.Services;
|
||||
|
||||
public sealed partial class PluginInstallService
|
||||
{
|
||||
/// <summary>
|
||||
/// The plugin types a user may import from an archive.
|
||||
/// </summary>
|
||||
private static readonly PluginType[] IMPORTABLE_PLUGIN_TYPES = [PluginType.ASSISTANT, PluginType.CONFIGURATION, PluginType.LANGUAGE];
|
||||
|
||||
/// <summary>
|
||||
/// Installs a plugin archive that contains exactly one <c>plugin.lua</c> file.
|
||||
/// Companion files are validated from and moved with the same staging directory.
|
||||
/// </summary>
|
||||
/// <param name="archivePath">The local <c>.mwplugin</c> or <c>.zip</c> archive path.</param>
|
||||
/// <param name="confirmAsync">
|
||||
/// Asks the user whether the validated archive may be installed. It is called after all checks
|
||||
/// passed and before anything gets written. Returning false aborts the installation.
|
||||
/// </param>
|
||||
/// <param name="token">Cancellation token for extraction, validation, file IO, and plugin reload.</param>
|
||||
/// <returns>Installation result that contains success state, installed plugin metadata, and a user-facing issue when installation failed.</returns>
|
||||
public async Task<AssistantPluginInstallResult> InstallArchiveAsync(string archivePath, Func<PluginImportPreview, Task<bool>> confirmAsync, CancellationToken token)
|
||||
{
|
||||
if (!this.settingsManager.ConfigurationData.App.AllowUserToImportPlugins)
|
||||
return Error(TB("Your organization has disabled importing plugins."));
|
||||
|
||||
if (!FileTypes.IsAllowedPath(archivePath, FileTypes.PLUGIN_ARCHIVE))
|
||||
return Error(TB("Please select a plugin archive with the extension .mwplugin or .zip."));
|
||||
|
||||
if (!File.Exists(archivePath))
|
||||
return Error(TB("The selected plugin archive does not exist."));
|
||||
|
||||
if (!PluginFactory.IsInitialized)
|
||||
return Error(TB("The plugin system is not initialized yet."));
|
||||
|
||||
await this.installSemaphore.WaitAsync(token);
|
||||
var stagingDirectory = Path.Join(Path.GetTempPath(), $"plugin-import.staging-{Guid.NewGuid():N}");
|
||||
try
|
||||
{
|
||||
token.ThrowIfCancellationRequested();
|
||||
PluginArchive.Extract(archivePath, stagingDirectory);
|
||||
|
||||
var pluginFiles = Directory.EnumerateFiles(stagingDirectory, PLUGIN_FILE_NAME, SearchOption.AllDirectories).ToArray();
|
||||
if (pluginFiles.Length != 1)
|
||||
return Error(TB("The plugin archive must contain exactly one plugin.lua file."));
|
||||
|
||||
var pluginFile = pluginFiles[0];
|
||||
var pluginDirectory = Path.GetDirectoryName(pluginFile)!;
|
||||
var pluginCode = await File.ReadAllTextAsync(pluginFile, Encoding.UTF8, token);
|
||||
var validation = await ValidatePluginCodeAsync(
|
||||
pluginDirectory,
|
||||
pluginCode.Trim(),
|
||||
IMPORTABLE_PLUGIN_TYPES,
|
||||
TB("Only assistant, configuration, and language plugins can be imported."),
|
||||
TB("The imported plugin is invalid. Issue: {0}"),
|
||||
TB("The imported plugin uses the ID of another installed plugin."),
|
||||
token);
|
||||
|
||||
if (!validation.Success || validation.Plugin is null)
|
||||
return Error(validation.Issue);
|
||||
|
||||
var plugin = validation.Plugin;
|
||||
var eligibilityIssue = this.GetImportEligibilityIssue(plugin);
|
||||
if (!string.IsNullOrEmpty(eligibilityIssue))
|
||||
return Error(eligibilityIssue);
|
||||
|
||||
// The archive would replace an existing plugin: reject it when that plugin belongs
|
||||
// to the IT department. We check this before asking the user, so that the
|
||||
// confirmation never offers something we would refuse afterwards anyway:
|
||||
var replacementIssue = GetReplacementIssue(plugin.Id, plugin.Type);
|
||||
if (!string.IsNullOrEmpty(replacementIssue))
|
||||
return Error(replacementIssue);
|
||||
|
||||
// Local plugins live in the directory of their type, never in the enterprise
|
||||
// configuration directory. Only a config server deploys plugins there:
|
||||
if (!TryGetPluginRoot(plugin.Type, out var pluginRoot, out var rootIssue))
|
||||
return Error(rootIssue);
|
||||
|
||||
// Everything is validated, but nothing was written yet. This is the point where the
|
||||
// user decides, because the plugin code comes from an untrusted source:
|
||||
if (!await confirmAsync(CreateImportPreview(plugin)))
|
||||
return CancelledByUser();
|
||||
|
||||
return await this.InstallStagedPluginAsync(pluginRoot, validation with { StagingDirectory = pluginDirectory }, plugin.Type, token);
|
||||
}
|
||||
catch (Exception e) when (e is not OperationCanceledException)
|
||||
{
|
||||
this.logger.LogError(e, "Failed to extract or validate plugin archive '{ArchivePath}'.", archivePath);
|
||||
return Error(string.Format(TB("Unexpected error: {0}"), e.Message));
|
||||
}
|
||||
finally
|
||||
{
|
||||
this.TryDeleteStagingDirectory(stagingDirectory);
|
||||
this.installSemaphore.Release();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Checks the rules that depend on the type of the plugin inside the archive.
|
||||
/// </summary>
|
||||
/// <param name="plugin">The validated plugin from the archive.</param>
|
||||
/// <returns>A user-facing issue when the archive must not be installed, an empty string otherwise.</returns>
|
||||
private string GetImportEligibilityIssue(PluginBase plugin) => plugin switch
|
||||
{
|
||||
// A plugin the user imports by hand never comes from a config server. We reject such
|
||||
// archives because AI Studio trusts this self-declared flag: an imported plugin claiming it
|
||||
// would be neither replaceable nor deletable through the user interface:
|
||||
PluginAssistants { IsManagedByConfigServer: true } => TB("This plugin archive declares itself as managed by a config server. Only the IT department of your organization might deploy such plugins."),
|
||||
|
||||
PluginConfiguration configurationPlugin => this.GetConfigurationImportEligibilityIssue(configurationPlugin),
|
||||
|
||||
_ => string.Empty,
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// Checks the additional rules for importing a configuration plugin.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// A configuration takes effect immediately and has no on/off switch, so it gets its own
|
||||
/// organization permission on top of the general import permission.
|
||||
/// </remarks>
|
||||
private string GetConfigurationImportEligibilityIssue(PluginConfiguration configurationPlugin)
|
||||
{
|
||||
if (!this.settingsManager.ConfigurationData.App.AllowUserToImportConfigurationPlugins)
|
||||
return TB("Your organization has disabled importing configuration plugins.");
|
||||
|
||||
if (configurationPlugin.DeployedUsingConfigServer is true)
|
||||
return TB("This plugin archive declares itself as managed by a config server. Only the IT department of your organization might deploy such plugins.");
|
||||
|
||||
// Never let an imported configuration take the place of one the organization deployed. This
|
||||
// also covers a deployed configuration which currently cannot be loaded, e.g. because of an
|
||||
// error in its Lua code:
|
||||
if (PluginFactory.IsEnterpriseConfigurationPlugin(configurationPlugin.Id))
|
||||
return TB("Your organization deployed a configuration with the same ID. An imported configuration must not take its place.");
|
||||
|
||||
return string.Empty;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,286 @@
|
||||
using System.Text;
|
||||
using AIStudio.Settings;
|
||||
using AIStudio.Tools.PluginSystem;
|
||||
using AIStudio.Tools.PluginSystem.Assistants;
|
||||
|
||||
namespace AIStudio.Tools.Services;
|
||||
|
||||
public sealed partial class PluginInstallService
|
||||
{
|
||||
private async Task<AssistantPluginInstallResult> InstallStagedPluginAsync(string pluginRoot, PluginValidationResult validation, PluginType pluginType, CancellationToken token)
|
||||
{
|
||||
var stagingDirectory = validation.StagingDirectory;
|
||||
var plugin = validation.Plugin!;
|
||||
string? backupDirectory = null;
|
||||
string? finalDirectory = null;
|
||||
var replacedExisting = false;
|
||||
var movedIntoPlace = false;
|
||||
|
||||
try
|
||||
{
|
||||
Directory.CreateDirectory(pluginRoot);
|
||||
finalDirectory = DetermineFinalDirectory(pluginRoot, plugin, pluginType);
|
||||
if (!IsPathInsideDirectory(pluginRoot, finalDirectory))
|
||||
return Error(TB("The resolved plugin directory is outside the plugin directory."));
|
||||
|
||||
var replacementIssue = GetReplacementIssue(plugin.Id, pluginType);
|
||||
if (!string.IsNullOrWhiteSpace(replacementIssue))
|
||||
return Error(replacementIssue);
|
||||
|
||||
if (Directory.Exists(finalDirectory))
|
||||
{
|
||||
replacedExisting = true;
|
||||
|
||||
// The backup goes to a directory outside the plugin root, so the plugin loader
|
||||
// cannot discover it during the reload below. Otherwise, the previous version
|
||||
// would be loaded a second time, next to the version we are installing:
|
||||
backupDirectory = CreateInstallBackupDirectory(plugin);
|
||||
Directory.CreateDirectory(Path.GetDirectoryName(backupDirectory)!);
|
||||
Directory.Move(finalDirectory, backupDirectory);
|
||||
}
|
||||
|
||||
Directory.Move(stagingDirectory, finalDirectory);
|
||||
movedIntoPlace = true;
|
||||
await PluginFactory.LoadAll(token);
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(backupDirectory))
|
||||
TryDeleteDirectory(backupDirectory, "plugin backup", this.logger);
|
||||
|
||||
this.logger.LogInformation("Installed plugin '{PluginName}' ({PluginId}, {PluginType}) to '{PluginDirectory}'.", plugin.Name, plugin.Id, pluginType, finalDirectory);
|
||||
return new(true, plugin.Id, plugin.Name, finalDirectory, replacedExisting, string.Empty);
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
this.logger.LogError(e, "Failed to install plugin.");
|
||||
|
||||
// Only remove the target directory when this installation actually moved the plugin
|
||||
// there. Otherwise, when moving the previous plugin into the backup directory failed,
|
||||
// we would delete the still intact previous plugin:
|
||||
if (movedIntoPlace && !string.IsNullOrWhiteSpace(finalDirectory) && Directory.Exists(finalDirectory))
|
||||
TryDeleteDirectory(finalDirectory, "failed assistant plugin installation", this.logger);
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(backupDirectory) && Directory.Exists(backupDirectory) && !string.IsNullOrWhiteSpace(finalDirectory) && !Directory.Exists(finalDirectory))
|
||||
{
|
||||
try
|
||||
{
|
||||
Directory.Move(backupDirectory, finalDirectory);
|
||||
await PluginFactory.LoadAll(CancellationToken.None);
|
||||
}
|
||||
catch (Exception restoreException)
|
||||
{
|
||||
this.logger.LogError(restoreException, "Failed to restore the previous assistant plugin after a failed installation.");
|
||||
}
|
||||
}
|
||||
|
||||
return Error(string.Format(TB("Unexpected error: {0}"), e.Message));
|
||||
}
|
||||
finally
|
||||
{
|
||||
this.TryDeleteStagingDirectory(stagingDirectory);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Loads and validates plugin code that is not installed yet.
|
||||
/// </summary>
|
||||
/// <param name="pluginDirectory">The staging directory the plugin currently lives in.</param>
|
||||
/// <param name="pluginCode">The <c>plugin.lua</c> content to validate.</param>
|
||||
/// <param name="acceptedTypes">The plugin types the caller accepts.</param>
|
||||
/// <param name="wrongTypeIssue">Issue when the plugin has another type. Gets the plugin issues as {0}.</param>
|
||||
/// <param name="invalidPluginIssue">Issue when the plugin is of an accepted type, but invalid. Gets the plugin issues as {0}.</param>
|
||||
/// <param name="conflictingPluginIdIssue">Issue when another plugin already uses this plugin ID.</param>
|
||||
/// <param name="token">Cancellation token for running the Lua code.</param>
|
||||
/// <returns>The validation result, including the loaded plugin when it passed.</returns>
|
||||
private static async Task<PluginValidationResult> ValidatePluginCodeAsync(string pluginDirectory, string pluginCode, IReadOnlyCollection<PluginType> acceptedTypes,
|
||||
string wrongTypeIssue, string invalidPluginIssue, string conflictingPluginIdIssue, CancellationToken token)
|
||||
{
|
||||
// The plugin is not installed yet: it sits in a staging directory outside the installed
|
||||
// plugins directory. We allow that directory as the module base, so the plugin can load its
|
||||
// own Lua modules, e.g., an icon.lua, while we validate it:
|
||||
var plugin = await PluginFactory.Load(pluginDirectory, pluginCode, token, pluginDirectory);
|
||||
if (!acceptedTypes.Contains(plugin.Type))
|
||||
return PluginValidationResult.Failure(string.Format(wrongTypeIssue, string.Join("; ", plugin.Issues)));
|
||||
|
||||
if (!plugin.IsValid)
|
||||
return PluginValidationResult.Failure(string.Format(invalidPluginIssue, string.Join("; ", plugin.Issues)));
|
||||
|
||||
// Plugin IDs must be unique across all plugin types: several lookups resolve a plugin by its
|
||||
// ID alone, e.g., the base language plugin in PluginFactory.Starting. A plugin carrying the
|
||||
// ID of a plugin of another type would break those lookups. Reusing the ID of another local
|
||||
// plugin of the same type stays allowed: that is how updating one works.
|
||||
if (PluginFactory.AvailablePlugins.Any(availablePlugin => availablePlugin.Id == plugin.Id && (availablePlugin.IsInternal || availablePlugin.Type != plugin.Type)))
|
||||
return PluginValidationResult.Failure(conflictingPluginIdIssue);
|
||||
|
||||
return new(true, string.Empty, plugin, string.Empty);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Determines the directory local plugins of the given type are installed into.
|
||||
/// </summary>
|
||||
private static bool TryGetPluginRoot(PluginType pluginType, out string pluginRoot, out string issue)
|
||||
{
|
||||
pluginRoot = string.Empty;
|
||||
issue = string.Empty;
|
||||
|
||||
var dataDirectory = SettingsManager.DataDirectory;
|
||||
if (string.IsNullOrWhiteSpace(dataDirectory))
|
||||
{
|
||||
issue = TB("The AI Studio data directory is not initialized yet.");
|
||||
return false;
|
||||
}
|
||||
|
||||
pluginRoot = Path.Join(dataDirectory, "plugins", pluginType.GetDirectory());
|
||||
return true;
|
||||
}
|
||||
|
||||
private static string DetermineFinalDirectory(string pluginRoot, IPluginMetadata plugin, PluginType pluginType)
|
||||
{
|
||||
var existingPlugin = FindReplaceablePlugin(plugin.Id, pluginType);
|
||||
return existingPlugin is not null
|
||||
? existingPlugin.LocalPath
|
||||
: Path.Join(pluginRoot, CreatePluginDirectoryName(plugin));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Finds the local plugin that an installation with the given ID and type would replace.
|
||||
/// </summary>
|
||||
/// <param name="pluginId">The ID of the plugin about to be installed.</param>
|
||||
/// <param name="pluginType">The type of the plugin about to be installed.</param>
|
||||
/// <returns>The plugin that would be replaced, or null when the installation adds a new plugin.</returns>
|
||||
private static IAvailablePlugin? FindReplaceablePlugin(Guid pluginId, PluginType pluginType) => PluginFactory.AvailablePlugins
|
||||
.OfType<IAvailablePlugin>()
|
||||
.FirstOrDefault(plugin => plugin.Type == pluginType && plugin.Id == pluginId && !plugin.IsInternal);
|
||||
|
||||
/// <summary>
|
||||
/// Collects the metadata an archive declares about itself, together with the information about
|
||||
/// the installed plugin it would replace.
|
||||
/// </summary>
|
||||
/// <param name="plugin">The validated plugin from the archive.</param>
|
||||
/// <returns>The preview shown to the user before the installation starts.</returns>
|
||||
private static PluginImportPreview CreateImportPreview(PluginBase plugin) => new(
|
||||
plugin,
|
||||
FindReplaceablePlugin(plugin.Id, plugin.Type),
|
||||
plugin is PluginConfiguration configurationPlugin ? CreateConfigurationImportSummary(configurationPlugin) : null);
|
||||
|
||||
/// <summary>
|
||||
/// Collects what a configuration plugin would set up once it is installed.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// The plugin was loaded as a dry run, so nothing of this is stored yet. The destinations come
|
||||
/// from the parsed configuration objects, which is why the preview can name the host a provider
|
||||
/// would talk to.
|
||||
/// </remarks>
|
||||
private static ConfigurationPluginImportSummary CreateConfigurationImportSummary(PluginConfiguration configurationPlugin)
|
||||
{
|
||||
var configObjects = configurationPlugin.ConfigObjects.ToList();
|
||||
var destinations = configObjects
|
||||
.Where(configObject => configObject.Type is PluginConfigurationObjectType.LLM_PROVIDER
|
||||
or PluginConfigurationObjectType.EMBEDDING_PROVIDER
|
||||
or PluginConfigurationObjectType.TRANSCRIPTION_PROVIDER
|
||||
or PluginConfigurationObjectType.DATA_SOURCE)
|
||||
.Select(configObject => new ConfigurationPluginDestination(configObject.Type, configObject.Name, configObject.Endpoint))
|
||||
.ToList();
|
||||
|
||||
return new(
|
||||
Destinations: destinations,
|
||||
ChatTemplates: CountObjects(PluginConfigurationObjectType.CHAT_TEMPLATE),
|
||||
Profiles: CountObjects(PluginConfigurationObjectType.PROFILE),
|
||||
DocumentAnalysisPolicies: CountObjects(PluginConfigurationObjectType.DOCUMENT_ANALYSIS_POLICY),
|
||||
DeclaredSettings: configurationPlugin.DeclaredSettingsCount,
|
||||
MandatoryInfos: configurationPlugin.MandatoryInfos.Count,
|
||||
Introductions: configurationPlugin.Introductions.Count);
|
||||
|
||||
int CountObjects(PluginConfigurationObjectType type) => configObjects.Count(configObject => configObject.Type == type);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Checks whether an installation may replace the plugin that currently uses the given ID.
|
||||
/// Plugins deployed by a Config Server belong to the organization's IT, so neither an import nor
|
||||
/// the Assistant Builder may overwrite them.
|
||||
/// </summary>
|
||||
/// <param name="pluginId">The ID of the plugin about to be installed.</param>
|
||||
/// <param name="pluginType">The type of the plugin about to be installed.</param>
|
||||
/// <returns>A user-facing issue when the existing plugin must not be replaced, an empty string otherwise.</returns>
|
||||
private static string GetReplacementIssue(Guid pluginId, PluginType pluginType)
|
||||
{
|
||||
var existingPlugin = FindReplaceablePlugin(pluginId, pluginType);
|
||||
if (existingPlugin is null)
|
||||
return string.Empty;
|
||||
|
||||
if (existingPlugin.IsManagedByConfigServer)
|
||||
return TB("Plugins deployed by your organization cannot be replaced.");
|
||||
|
||||
if (string.IsNullOrWhiteSpace(existingPlugin.LocalPath))
|
||||
return string.Empty;
|
||||
|
||||
// The metadata above and the running plugin read the same Lua field. We check both, though,
|
||||
// just like the deletion path does:
|
||||
var runningPlugin = PluginFactory.RunningPlugins
|
||||
.FirstOrDefault(candidate => candidate.Id == pluginId && IsSameDirectory(candidate.PluginPath, existingPlugin.LocalPath));
|
||||
|
||||
var isManagedByConfigServer = runningPlugin switch
|
||||
{
|
||||
PluginAssistants assistantPlugin => assistantPlugin.IsManagedByConfigServer,
|
||||
PluginConfiguration configurationPlugin => configurationPlugin.DeployedUsingConfigServer ?? false,
|
||||
|
||||
_ => false,
|
||||
};
|
||||
|
||||
return isManagedByConfigServer
|
||||
? TB("Plugins deployed by your organization cannot be replaced.")
|
||||
: string.Empty;
|
||||
}
|
||||
|
||||
private static string CreateInstallBackupDirectory(IPluginMetadata plugin)
|
||||
{
|
||||
var backupRoot = Path.Join(SettingsManager.DataDirectory, INSTALL_BACKUP_DIRECTORY);
|
||||
return Path.Join(backupRoot, $"assistant-{plugin.Id:N}-{Guid.NewGuid():N}");
|
||||
}
|
||||
|
||||
private static string CreatePluginDirectoryName(IPluginMetadata plugin)
|
||||
{
|
||||
var safeName = CreateSafeDirectoryNamePart(plugin.Name);
|
||||
return $"{safeName}-{plugin.Id:N}";
|
||||
}
|
||||
|
||||
private static string CreateSafeDirectoryNamePart(string name)
|
||||
{
|
||||
var sb = new StringBuilder();
|
||||
var invalidChars = Path.GetInvalidFileNameChars().ToHashSet();
|
||||
|
||||
foreach (var character in name.Trim())
|
||||
{
|
||||
if (char.IsLetterOrDigit(character))
|
||||
{
|
||||
sb.Append(char.ToLowerInvariant(character));
|
||||
continue;
|
||||
}
|
||||
|
||||
if (character is '-' or '_' or '.' && !invalidChars.Contains(character))
|
||||
{
|
||||
sb.Append(character);
|
||||
continue;
|
||||
}
|
||||
|
||||
AppendSeparator();
|
||||
}
|
||||
|
||||
var safeName = sb.ToString().Trim('-', '.');
|
||||
if (safeName.Length > DIRECTORY_PREFIX_MAX_LEN)
|
||||
safeName = safeName[..DIRECTORY_PREFIX_MAX_LEN].Trim('-', '.');
|
||||
|
||||
// Fallback for a plugin name without any usable character. The plugin ID is appended by the
|
||||
// caller, so the directory stays unique either way:
|
||||
return string.IsNullOrWhiteSpace(safeName)
|
||||
? "plugin"
|
||||
: safeName;
|
||||
|
||||
void AppendSeparator()
|
||||
{
|
||||
if (sb.Length == 0 || sb[^1] == '-')
|
||||
return;
|
||||
|
||||
sb.Append('-');
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
using AIStudio.Settings;
|
||||
using AIStudio.Tools.AssistantSessions;
|
||||
using AIStudio.Tools.PluginSystem;
|
||||
using AIStudio.Tools.PluginSystem.Assistants;
|
||||
|
||||
namespace AIStudio.Tools.Services;
|
||||
|
||||
/// <summary>
|
||||
/// Installs, updates, and removes the plugins AI Studio manages locally.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// The implementation is split across several files:<br/>
|
||||
/// - <c>PluginInstallService.AssistantBuilder.cs</c>: installing generated assistant plugin code<br/>
|
||||
/// - <c>PluginInstallService.Editing.cs</c>: editing an installed assistant plugin<br/>
|
||||
/// - <c>PluginInstallService.Import.cs</c>: importing plugin archives<br/>
|
||||
/// - <c>PluginInstallService.Delete.cs</c>: removing installed plugins<br/>
|
||||
/// - <c>PluginInstallService.Installation.cs</c>: the shared validation and installation steps<br/>
|
||||
/// - <c>PluginInstallService.FileSystem.cs</c>: the shared path and directory helpers
|
||||
/// </remarks>
|
||||
public sealed partial class PluginInstallService
|
||||
{
|
||||
private static string TB(string fallbackEN) => I18N.I.T(fallbackEN, typeof(PluginInstallService).Namespace, nameof(PluginInstallService));
|
||||
|
||||
private const string PLUGIN_FILE_NAME = "plugin.lua";
|
||||
private const string ASSISTANT_BUILDER_DIRECTORY_PREFIX = "assistant-builder";
|
||||
private const string DELETE_BACKUP_DIRECTORY = ".plugin-delete-backups";
|
||||
private const string INSTALL_BACKUP_DIRECTORY = ".plugin-install-backups";
|
||||
private const int DIRECTORY_PREFIX_MAX_LEN = 80;
|
||||
|
||||
private readonly ILogger<PluginInstallService> logger;
|
||||
private readonly SettingsManager settingsManager;
|
||||
private readonly AssistantSessionService assistantSessionService;
|
||||
private readonly MediaTranscriptionService mediaTranscriptionService;
|
||||
private readonly SemaphoreSlim installSemaphore = new(1, 1);
|
||||
|
||||
private static AssistantPluginInstallResult Error(string issue) => new(false, Guid.Empty, string.Empty, string.Empty, false, issue);
|
||||
|
||||
private static AssistantPluginInstallResult CancelledByUser() => new(false, Guid.Empty, string.Empty, string.Empty, false, string.Empty, true);
|
||||
|
||||
private static AssistantPluginCheckResult CheckError(string issue) => new(false, Guid.Empty, string.Empty, issue);
|
||||
|
||||
private static PluginDeleteResult DeleteError(IPluginMetadata plugin, string pluginDirectory, string issue) => new(false, plugin.Id, plugin.Name, pluginDirectory, issue);
|
||||
|
||||
private static AssistantPluginUpdateResult UpdateError(IPluginMetadata plugin, string pluginDirectory, string issue) => new(false, plugin.Id, plugin.Name, pluginDirectory, issue);
|
||||
|
||||
public PluginInstallService(ILogger<PluginInstallService> logger, SettingsManager settingsManager, AssistantSessionService assistantSessionService, MediaTranscriptionService mediaTranscriptionService)
|
||||
{
|
||||
this.logger = logger;
|
||||
this.settingsManager = settingsManager;
|
||||
this.assistantSessionService = assistantSessionService;
|
||||
this.mediaTranscriptionService = mediaTranscriptionService;
|
||||
this.logger.LogInformation("The plugin install service has been initialized.");
|
||||
}
|
||||
|
||||
private sealed record PluginValidationResult(bool Success, string StagingDirectory, PluginBase? Plugin, string Issue)
|
||||
{
|
||||
public static PluginValidationResult Failure(string issue) => new(false, string.Empty, null, issue);
|
||||
|
||||
/// <summary>
|
||||
/// The validated plugin as an assistant plugin, or null when it has another type.
|
||||
/// </summary>
|
||||
public PluginAssistants? AssistantPlugin => this.Plugin as PluginAssistants;
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user