Improved the assistants page with categories for assistant plugins (#1211)

This commit is contained in:
Thorsten Sommer authored and GitHub committed 2026-11-20 11:47:59 +01:00
1 parent ef059ffd15
commit 1db0f85898
74 files changed
+3392 -380

No files matched your search

@@ -1,15 +0,0 @@
namespace AIStudio.Tools;
public enum AssistantCategory
{
AS_IS,
GENERAL,
SCIENTIFIC,
PRODUCTIVITY,
BUSINESS,
LEARNING,
DEVELOPMENT,
AI_STUDIO,
OTHER,
}
@@ -1,39 +0,0 @@
using AIStudio.Tools.PluginSystem;
namespace AIStudio.Tools;
public static class AssistantCategoryExtensions
{
private static string TB(string fallbackEN) => I18N.I.T(fallbackEN, typeof(AssistantCategoryExtensions).Namespace, nameof(AssistantCategoryExtensions));
private static string TA(string fallbackEN) => I18N.I.TA(fallbackEN, typeof(AssistantCategoryExtensions).Namespace, nameof(AssistantCategoryExtensions));
extension(AssistantCategory category)
{
public string Name => category switch
{
AssistantCategory.AS_IS => TB("Select the assistant category"),
AssistantCategory.GENERAL => TB("General"),
AssistantCategory.SCIENTIFIC => TB("Scientific"),
AssistantCategory.BUSINESS => TB("Business"),
AssistantCategory.PRODUCTIVITY => TB("Productivity"),
AssistantCategory.DEVELOPMENT => TB("Software Development"),
AssistantCategory.LEARNING => TB("Learning & Reflecting"),
AssistantCategory.AI_STUDIO => TB("AI Studio Development"),
AssistantCategory.OTHER => TB("Other"),
_ => string.Empty,
};
public string NameSelecting
{
get
{
if(category is AssistantCategory.AS_IS)
return TA("Please select the assistant category");
return category.Name;
}
}
}
}
@@ -0,0 +1,187 @@
using AIStudio.Settings;
using AIStudio.Settings.DataModel;
using AIStudio.Tools.PluginSystem;
using AIStudio.Tools.PluginSystem.Assistants;
namespace AIStudio.Tools;
/// <summary>
/// Decides what the categories of an assistant allow, built-in assistants and plugins alike: whether your
/// organization disabled them, and whether the user collapsed or hid them on the assistants page.
/// </summary>
/// <remarks>
/// An organization disables categories through DataApp.DisabledAssistantCategories and
/// DataApp.DisabledCustomAssistantCategories, e.g., to keep entertainment plugins off its devices. An
/// assistant of a disabled category is gone everywhere: from the assistants page, from "Send to …", from
/// links, from direct chat launchers, and from the Assistant Builder. Ask these rules instead of reading the
/// settings: a check of your own would miss CORE, which counts as COMMON, or a custom category spelled
/// differently.<br/><br/>
/// Built-in assistants have exactly one category, see ComponentsExtensions.Category; IsAssistantVisible
/// checks it. A plugin may have several, and it stays available while one of them is not disabled. A plugin
/// your organization deployed itself is never disabled by its categories, see
/// PluginFactory.IsAssistantDeployedByOrganization.
/// </remarks>
public static class AssistantCategoryRules
{
/// <param name="app">The app settings which hold the categories your organization disabled.</param>
extension(DataApp app)
{
/// <summary>
/// Whether your organization disabled this category.
/// </summary>
/// <remarks>
/// CORE and COMMON are one category, because both share the heading "General". Disabling CUSTOM
/// disables every custom category.
/// </remarks>
/// <param name="category">The category in question.</param>
/// <returns>True when your organization disabled the category.</returns>
public bool IsAssistantCategoryDisabled(AssistantCategoryKey category)
{
if (category.Category is PluginCategory.CUSTOM)
return app.DisabledAssistantCategories.Contains(PluginCategory.CUSTOM)
|| app.DisabledCustomAssistantCategories.Any(name => category.Equals(new AssistantCategoryKey(PluginCategory.CUSTOM, name)));
return app.DisabledAssistantCategories.Any(disabledCategory => category.Equals(new AssistantCategoryKey(disabledCategory)));
}
/// <summary>
/// Whether your organization disabled an assistant plugin through its categories.
/// </summary>
/// <param name="plugin">The plugin in question.</param>
/// <param name="isDeployedByOrganization">Whether your organization deployed the plugin itself, see PluginFactory.IsAssistantDeployedByOrganization.</param>
/// <returns>True when every category of the plugin is disabled and your organization did not deploy it.</returns>
public bool DisablesAssistantPlugin(IPluginMetadata plugin, bool isDeployedByOrganization)
{
if (isDeployedByOrganization)
return false;
var categories = AssistantCategoryKey.AllOf(plugin);
return categories.Count > 0 && categories.All(category => app.IsAssistantCategoryDisabled(category));
}
}
/// <param name="page">The settings of the assistants page, which hold the categories the user collapsed or hid.</param>
extension(DataAssistantsPage page)
{
/// <summary>
/// Whether the user collapsed this category on the assistants page.
/// </summary>
/// <param name="category">The category in question.</param>
/// <returns>True when the category is collapsed.</returns>
public bool IsCategoryCollapsed(AssistantCategoryKey category) => Contains(page.CollapsedCategories, page.CollapsedCustomCategories, category);
/// <summary>
/// Whether the user hid this category on the assistants page.
/// </summary>
/// <param name="category">The category in question.</param>
/// <returns>True when the category is hidden.</returns>
public bool IsCategoryHidden(AssistantCategoryKey category) => Contains(page.HiddenCategories, page.HiddenCustomCategories, category);
/// <summary>
/// Collapses a category on the assistants page or expands it again.
/// </summary>
/// <param name="category">The category in question.</param>
/// <param name="isCollapsed">True to collapse the category, false to expand it.</param>
public void SetCategoryCollapsed(AssistantCategoryKey category, bool isCollapsed) => Set(page.CollapsedCategories, page.CollapsedCustomCategories, category, isCollapsed);
/// <summary>
/// Hides a category on the assistants page or shows it again.
/// </summary>
/// <param name="category">The category in question.</param>
/// <param name="isHidden">True to hide the category, false to show it.</param>
public void SetCategoryHidden(AssistantCategoryKey category, bool isHidden) => Set(page.HiddenCategories, page.HiddenCustomCategories, category, isHidden);
/// <summary>
/// Whether AI Studio offers the assistants of this category outside of the assistants page, e.g.,
/// in the "Send to ..." menu.
/// </summary>
/// <remarks>
/// A hidden category follows the option for hidden categories, also when it is collapsed as well;
/// a collapsed one follows the option for collapsed categories; any other category offers its
/// assistants. An assistant with several categories is offered as soon as one of them offers it.
/// Whether your organization disabled the category is a question of its own, see
/// IsAssistantCategoryDisabled.
/// </remarks>
/// <param name="category">The category in question.</param>
/// <returns>True when AI Studio offers the assistants of the category.</returns>
public bool IsCategoryOffering(AssistantCategoryKey category)
{
if (page.IsCategoryHidden(category))
return page.HiddenCategoryAssistants is AssistantOfferBehavior.KEEP_OFFERING;
if (page.IsCategoryCollapsed(category))
return page.CollapsedCategoryAssistants is AssistantOfferBehavior.KEEP_OFFERING;
return true;
}
/// <summary>
/// Whether AI Studio offers a built-in assistant outside of the assistants page, e.g., in the
/// "Send to ..." menu, as far as its category on the page is concerned.
/// </summary>
/// <remarks>
/// A component without a category, such as the chat, is always offered.
/// </remarks>
/// <param name="component">The assistant in question.</param>
/// <returns>True when the category of the assistant offers it.</returns>
public bool IsOfferingAssistant(Components component) => component.Category is PluginCategory.NONE || page.IsCategoryOffering(new AssistantCategoryKey(component.Category));
}
/// <summary>
/// Whether a category is among those stored in a pair of sets, one for the categories of AI Studio and
/// one for the names of custom categories.
/// </summary>
private static bool Contains(HashSet<PluginCategory> categories, HashSet<string> customNames, AssistantCategoryKey category) => category.Category is PluginCategory.CUSTOM
? customNames.Any(name => category.Equals(new AssistantCategoryKey(PluginCategory.CUSTOM, name)))
: categories.Any(storedCategory => category.Equals(new AssistantCategoryKey(storedCategory)));
/// <summary>
/// Adds a category to a pair of sets or removes it, see Contains.
/// </summary>
/// <remarks>
/// Removing a category removes every spelling of it, e.g., CORE together with COMMON, or a custom
/// name in another case. Adding it stores the spelling of the key, so a set never holds CORE.
/// </remarks>
private static void Set(HashSet<PluginCategory> categories, HashSet<string> customNames, AssistantCategoryKey category, bool isContained)
{
if (category.Category is PluginCategory.CUSTOM)
{
customNames.RemoveWhere(name => category.Equals(new AssistantCategoryKey(PluginCategory.CUSTOM, name)));
if (isContained)
customNames.Add(category.CustomName);
return;
}
categories.RemoveWhere(storedCategory => category.Equals(new AssistantCategoryKey(storedCategory)));
if (isContained)
categories.Add(category.Category);
}
/// <param name="settingsManager">The settings manager which holds the rules of your organization.</param>
extension(SettingsManager settingsManager)
{
/// <summary>
/// Whether your organization disabled an assistant plugin through its categories.
/// </summary>
/// <param name="plugin">The plugin in question.</param>
/// <returns>True when every category of the plugin is disabled and your organization did not deploy it.</returns>
public bool IsDisabledByItsCategories(PluginAssistants plugin)
{
var configuration = settingsManager.ConfigurationData;
var isDeployedByOrganization = PluginFactory.IsAssistantDeployedByOrganization(plugin, configuration.AssistantPluginAudit.EnterpriseApprovedPlugins);
return configuration.App.DisablesAssistantPlugin(plugin, isDeployedByOrganization);
}
/// <summary>
/// Whether an assistant plugin may be offered and started.
/// </summary>
/// <remarks>
/// Check this wherever an assistant plugin enters the app: on the assistants page, when a link
/// names it, and when a direct chat launcher starts its chat.
/// </remarks>
/// <param name="plugin">The plugin in question.</param>
/// <returns>True when the plugin is enabled and your organization did not disable it through its categories.</returns>
public bool IsAssistantPluginAvailable(PluginAssistants plugin) => settingsManager.IsPluginEnabled(plugin) && !settingsManager.IsDisabledByItsCategories(plugin);
}
}
@@ -152,5 +152,11 @@ public sealed class AssistantLaunchService(SettingsManager settingsManager, Assi
.OrderBy(destination => destination.Name.Length)
.ToArray();
private bool IsVisible(Components destination) => settingsManager.IsAssistantVisible(destination, withLogging: false, requiredPreviewFeature: destination.RequiredPreviewFeature);
/// <summary>
/// Whether the menu offers a destination: the user sees the assistant at all, and its category on the
/// assistants page, collapsed or hidden, still offers it.
/// </summary>
private bool IsVisible(Components destination) =>
settingsManager.IsAssistantVisible(destination, withLogging: false, requiredPreviewFeature: destination.RequiredPreviewFeature) &&
settingsManager.ConfigurationData.AssistantsPage.IsOfferingAssistant(destination);
}
@@ -1,5 +1,6 @@
using AIStudio.Settings;
using AIStudio.Settings.DataModel;
using AIStudio.Tools.PluginSystem;
namespace AIStudio.Tools;
@@ -43,6 +44,17 @@ public static class AssistantVisibilityExtensions
return true;
}
// Your organization may disable whole categories of assistants. Plugins bring their categories
// along, so AssistantCategoryRules.IsAssistantPluginAvailable checks them instead:
var category = component.Category;
if (category is not PluginCategory.NONE && settingsManager.ConfigurationData.App.IsAssistantCategoryDisabled(new AssistantCategoryKey(category)))
{
if(withLogging)
LOGGER.LogInformation("Assistant '{AssistantName}' is not visible because your organization disabled its category '{Category}'.", assistantName, category);
return false;
}
// Dynamic assistants are controlled through plugin activation and their security state.
// The Assistant Builder is controlled through its preview feature. Neither belongs to the
// built-in assistant visibility list, so both are expected to be visible at this point.
@@ -27,6 +27,51 @@ public static class ComponentsExtensions
_ => PreviewFeatures.NONE,
};
/// <summary>
/// Gets the category a built-in assistant belongs to, the same categories assistant plugins name.
/// </summary>
/// <remarks>
/// This is the single place that maps a built-in assistant to its category. The assistants page
/// shows the assistant in the section of this category, and whatever offers assistants elsewhere
/// asks it, too. Components which are no assistant of their own, such as the chat or the agents,
/// return PluginCategory.NONE.
/// </remarks>
/// <value>The category of the assistant.</value>
public PluginCategory Category => component switch
{
Components.TEXT_SUMMARIZER_ASSISTANT => PluginCategory.COMMON,
Components.TRANSLATION_ASSISTANT => PluginCategory.COMMON,
Components.GRAMMAR_SPELLING_ASSISTANT => PluginCategory.COMMON,
Components.REWRITE_ASSISTANT => PluginCategory.COMMON,
Components.PROMPT_OPTIMIZER_ASSISTANT => PluginCategory.COMMON,
Components.SYNONYMS_ASSISTANT => PluginCategory.COMMON,
Components.MODEL_COMPARISON_ASSISTANT => PluginCategory.COMMON,
Components.META_ASSISTANT => PluginCategory.COMMON,
Components.EMAIL_ASSISTANT => PluginCategory.BUSINESS,
Components.SWOT_ANALYSIS_ASSISTANT => PluginCategory.BUSINESS,
Components.DOCUMENT_ANALYSIS_ASSISTANT => PluginCategory.BUSINESS,
Components.BATCH_PROCESSING_ASSISTANT => PluginCategory.BUSINESS,
Components.MY_TASKS_ASSISTANT => PluginCategory.BUSINESS,
Components.AGENDA_ASSISTANT => PluginCategory.BUSINESS,
Components.JOB_POSTING_ASSISTANT => PluginCategory.BUSINESS,
Components.LEGAL_CHECK_ASSISTANT => PluginCategory.BUSINESS,
Components.ICON_FINDER_ASSISTANT => PluginCategory.BUSINESS,
Components.SLIDE_BUILDER_ASSISTANT => PluginCategory.BUSINESS,
Components.VISUAL_BRIEFING_ASSISTANT => PluginCategory.BUSINESS,
Components.BIAS_DAY_ASSISTANT => PluginCategory.EDUCATION,
Components.BEYOND_FACTS_LAB_ASSISTANT => PluginCategory.EDUCATION,
Components.CODING_ASSISTANT => PluginCategory.SOFTWARE_DEVELOPMENT,
Components.ERI_ASSISTANT => PluginCategory.SOFTWARE_DEVELOPMENT,
Components.I18N_ASSISTANT => PluginCategory.AI_STUDIO_DEVELOPMENT,
Components.LOG_VIEWER_ASSISTANT => PluginCategory.AI_STUDIO_DEVELOPMENT,
_ => PluginCategory.NONE,
};
/// <summary>
/// Gets whether a component owns exactly one assistant session slot, so that a running session
/// blocks starting another one and inactive sessions can be cleared as a group.
@@ -0,0 +1,71 @@
namespace AIStudio.Tools.PluginSystem;
/// <summary>
/// One category of assistants, as the assistants page groups them: a category of AI Studio, or a
/// custom category a plugin names itself.
/// </summary>
/// <remarks>
/// Two rules decide when two categories are the same. CORE belongs to configuration and language
/// plugins; an assistant plugin which names it nevertheless appears under "General", so CORE becomes
/// COMMON. Custom categories come in the language of their authors, so two plugins may well spell one
/// category differently: their names are compared without regard to case.
/// </remarks>
public sealed record AssistantCategoryKey
{
/// <param name="category">The category of AI Studio.</param>
/// <param name="customName">The name of the custom category, when the category is CUSTOM.</param>
public AssistantCategoryKey(PluginCategory category, string customName = "")
{
this.Category = category is PluginCategory.CORE ? PluginCategory.COMMON : category;
this.CustomName = this.Category is PluginCategory.CUSTOM ? customName.Trim() : string.Empty;
}
/// <summary>
/// The category of AI Studio, never CORE.
/// </summary>
public PluginCategory Category { get; }
/// <summary>
/// The name of the custom category, or an empty string for any other category.
/// </summary>
public string CustomName { get; }
/// <summary>
/// The name of the category as the user reads it: localized for a category of AI Studio, as the
/// plugin wrote it for a custom one.
/// </summary>
public string Name => this.Category is PluginCategory.CUSTOM ? this.CustomName : this.Category.Name;
/// <summary>
/// Gets the categories a plugin names, its custom ones included.
/// </summary>
/// <remarks>
/// CUSTOM stands for all names of CUSTOM_CATEGORIES. Each category appears once, also when a plugin
/// names CORE and COMMON at the same time.
/// </remarks>
/// <param name="plugin">The plugin in question.</param>
/// <returns>The categories of the plugin, in the order the plugin names them.</returns>
public static IReadOnlyList<AssistantCategoryKey> AllOf(IPluginMetadata plugin) => AllOf(plugin.Categories, plugin.CustomCategories);
/// <summary>
/// Gets the categories which CATEGORIES and CUSTOM_CATEGORIES name together.
/// </summary>
/// <remarks>
/// For categories which are not loaded yet, e.g., those of a model answer. See the overload for a plugin.
/// </remarks>
/// <param name="categories">The categories of AI Studio.</param>
/// <param name="customCategories">The names of the custom categories.</param>
/// <returns>The categories, each once, in the order they are named.</returns>
public static IReadOnlyList<AssistantCategoryKey> AllOf(IEnumerable<PluginCategory> categories, IEnumerable<string> customCategories) => categories
.SelectMany(category => category is PluginCategory.CUSTOM
? customCategories.Select(name => new AssistantCategoryKey(PluginCategory.CUSTOM, name))
: [new AssistantCategoryKey(category)])
.Distinct()
.ToList();
/// <inheritdoc />
public bool Equals(AssistantCategoryKey? other) => other is not null && this.Category == other.Category && string.Equals(this.CustomName, other.CustomName, StringComparison.OrdinalIgnoreCase);
/// <inheritdoc />
public override int GetHashCode() => HashCode.Combine(this.Category, StringComparer.OrdinalIgnoreCase.GetHashCode(this.CustomName));
}
@@ -0,0 +1,9 @@
namespace AIStudio.Tools.PluginSystem.Assistants;
/// <summary>
/// One section of the assistants page, with the assistant plugins it shows.
/// </summary>
/// <param name="Category">The category of the section.</param>
/// <param name="Assistants">The assistant plugins of this category, sorted by their title.</param>
/// <typeparam name="TPlugin">The type of the plugins.</typeparam>
public sealed record AssistantPageSection<TPlugin>(AssistantCategoryKey Category, IReadOnlyList<TPlugin> Assistants);
@@ -0,0 +1,163 @@
using AIStudio.Settings.DataModel;
namespace AIStudio.Tools.PluginSystem.Assistants;
/// <summary>
/// Decides which sections the assistants page shows and in which order.
/// </summary>
/// <remarks>
/// The built-in assistants and the assistant plugins share one set of categories, see
/// AssistantCategoryKey. The page shows the sections of its built-in assistants first, in
/// the order users know: "General", "Business", "Learning &amp; Reflecting", and "Software Development".
/// The categories which only plugins name follow, the ones of AI Studio before the custom ones, each
/// group sorted by its name. "AI Studio Development" comes last, since it concerns the development of
/// AI Studio itself.
/// </remarks>
public static class AssistantPageSections
{
/// <summary>
/// The groups of sections, in the order of the page.
/// </summary>
private enum PageGroup
{
LEADING,
OTHER,
CUSTOM,
TRAILING,
}
/// <summary>
/// A plugin in one of its categories.
/// </summary>
/// <param name="Category">One category of the plugin.</param>
/// <param name="Plugin">The plugin.</param>
/// <typeparam name="TPlugin">The type of the plugin.</typeparam>
private sealed record SectionMember<TPlugin>(AssistantCategoryKey Category, TPlugin Plugin);
/// <summary>
/// The categories of the built-in assistants, which lead the page, in their order.
/// </summary>
public static readonly IReadOnlyList<AssistantCategoryKey> LEADING_CATEGORIES =
[
new(PluginCategory.COMMON),
new(PluginCategory.BUSINESS),
new(PluginCategory.EDUCATION),
new(PluginCategory.SOFTWARE_DEVELOPMENT),
];
/// <summary>
/// The category of the built-in assistants which ends the page.
/// </summary>
public static readonly AssistantCategoryKey TRAILING_CATEGORY = new(PluginCategory.AI_STUDIO_DEVELOPMENT);
/// <summary>
/// Whether the page shows a section of this category for its built-in assistants anyway.
/// </summary>
/// <param name="category">The category in question.</param>
/// <returns>True for the categories of the built-in assistants.</returns>
public static bool IsBuiltIn(AssistantCategoryKey category) => LEADING_CATEGORIES.Contains(category) || category == TRAILING_CATEGORY;
/// <summary>
/// Compares two categories by their place on the assistants page.
/// </summary>
/// <param name="left">The first category.</param>
/// <param name="right">The second category.</param>
/// <returns>Less than zero when the first category comes first, zero when both are the same, otherwise more than zero.</returns>
public static int Compare(AssistantCategoryKey left, AssistantCategoryKey right)
{
var byGroup = Group(left).CompareTo(Group(right));
if (byGroup != 0)
return byGroup;
var leftIndex = IndexOfLeading(left);
if (leftIndex >= 0)
return leftIndex.CompareTo(IndexOfLeading(right));
return NameComparer.Compare(left.Name, right.Name);
}
/// <summary>
/// Selects the categories the settings dialog of the assistants page offers, in the order of the page.
/// </summary>
/// <remarks>
/// The dialog offers the categories the page shows right now, so that every switch changes something
/// the user sees, and every category the user hid, so that each one can come back. Categories your
/// organization disabled are missing: no switch of the user brings them back.
/// </remarks>
/// <param name="shownCategories">The categories which show at least one assistant right now.</param>
/// <param name="app">The app settings which hold the categories your organization disabled.</param>
/// <param name="page">The settings of the assistants page, which hold the categories the user hid.</param>
/// <returns>The categories for the dialog, each once.</returns>
public static IReadOnlyList<AssistantCategoryKey> SelectForSettings(IEnumerable<AssistantCategoryKey> shownCategories, DataApp app, DataAssistantsPage page)
{
var hiddenCategories = page.HiddenCategories
.Select(category => new AssistantCategoryKey(category))
.Concat(page.HiddenCustomCategories.Select(name => new AssistantCategoryKey(PluginCategory.CUSTOM, name)));
return shownCategories
.Concat(hiddenCategories)
.Distinct()
.Where(category => !app.IsAssistantCategoryDisabled(category))
.Order(Comparer<AssistantCategoryKey>.Create(Compare))
.ToList();
}
/// <summary>
/// Groups the assistant plugins into the sections of the assistants page.
/// </summary>
/// <remarks>
/// A plugin appears in each of its categories, but only once per section. The sections come in the
/// order of the page, and their plugins sorted by title.
/// </remarks>
/// <param name="plugins">The assistant plugins to show.</param>
/// <param name="titleOf">Gets the title under which a plugin appears.</param>
/// <typeparam name="TPlugin">The type of the plugins.</typeparam>
/// <returns>One section per category any of the plugins names.</returns>
public static IReadOnlyList<AssistantPageSection<TPlugin>> Build<TPlugin>(IEnumerable<TPlugin> plugins, Func<TPlugin, string> titleOf) where TPlugin : IPluginMetadata
{
var titleComparer = NameComparer;
return plugins
.SelectMany(plugin => AssistantCategoryKey.AllOf(plugin).Select(category => new SectionMember<TPlugin>(category, plugin)))
.GroupBy(member => member.Category)
.Order(Comparer<IGrouping<AssistantCategoryKey, SectionMember<TPlugin>>>.Create((left, right) => Compare(left.Key, right.Key)))
.Select(group => new AssistantPageSection<TPlugin>(group.Key, group.Select(member => member.Plugin).OrderBy(titleOf, titleComparer).ToList()))
.ToList();
}
/// <param name="sections">The sections of the assistants page.</param>
/// <typeparam name="TPlugin">The type of the plugins.</typeparam>
extension<TPlugin>(IReadOnlyList<AssistantPageSection<TPlugin>> sections)
{
/// <summary>
/// Gets the assistant plugins of one category.
/// </summary>
/// <param name="category">The category in question.</param>
/// <returns>The plugins of the category, or none when no plugin names it.</returns>
public IReadOnlyList<TPlugin> PluginsOf(AssistantCategoryKey category) => sections.FirstOrDefault(section => section.Category == category)?.Assistants ?? [];
}
/// <summary>
/// Compares names the way the user reads them: in the culture of the active language, without regard to case.
/// </summary>
private static StringComparer NameComparer => StringComparer.Create(I18N.I.Culture, ignoreCase: true);
private static int IndexOfLeading(AssistantCategoryKey category)
{
for (var index = 0; index < LEADING_CATEGORIES.Count; index++)
if (LEADING_CATEGORIES[index] == category)
return index;
return -1;
}
private static PageGroup Group(AssistantCategoryKey category)
{
if (IndexOfLeading(category) >= 0)
return PageGroup.LEADING;
if (category == TRAILING_CATEGORY)
return PageGroup.TRAILING;
return category.Category is PluginCategory.CUSTOM ? PageGroup.CUSTOM : PageGroup.OTHER;
}
}
@@ -35,7 +35,7 @@ public static class DirectChatLauncherLuaWriter
private const string FALLBACK_AUTHOR = "MindWork AI - Assistant Builder";
private const string FALLBACK_SUPPORT_CONTACT = "mailto:info@mindwork.ai";
private const string FALLBACK_SOURCE_URL = "https://github.com/MindWorkAI/AI-Studio";
private const string FALLBACK_CATEGORY = nameof(PluginCategory.CORE);
private const string FALLBACK_CATEGORY = nameof(PluginCategory.COMMON);
private const string FALLBACK_TARGET_GROUP = nameof(PluginTargetGroup.EVERYONE);
//
@@ -141,10 +141,23 @@ public static class DirectChatLauncherLuaWriter
builder.AppendLineLF($"SOURCE_URL = \"{Escape(ValueOrFallback(plugin.SourceURL, FALLBACK_SOURCE_URL))}\"");
builder.AppendLineLF();
//
// CUSTOM needs its names, and the loader refuses it without them. A defective launcher which
// lost its names thus keeps its other categories, or falls back like any other:
//
var customCategories = plugin.CustomCategories.Where(name => !string.IsNullOrWhiteSpace(name)).ToList();
var categories = customCategories.Count > 0 ? plugin.Categories : plugin.Categories.Where(category => category is not PluginCategory.CUSTOM).ToList();
builder.AppendLineLF("-- The categories for the plugin:");
builder.AppendLineLF($"CATEGORIES = {WriteEnumList(plugin.Categories, FALLBACK_CATEGORY)}");
builder.AppendLineLF($"CATEGORIES = {WriteEnumList(categories, FALLBACK_CATEGORY)}");
builder.AppendLineLF();
if (customCategories.Count > 0 && categories.Contains(PluginCategory.CUSTOM))
{
builder.AppendLineLF("-- The names of the custom categories for the plugin:");
builder.AppendLineLF($"CUSTOM_CATEGORIES = {WriteStringList(customCategories, string.Empty)}");
builder.AppendLineLF();
}
builder.AppendLineLF("-- The target groups for the plugin:");
builder.AppendLineLF($"TARGET_GROUPS = {WriteEnumList(plugin.TargetGroups, FALLBACK_TARGET_GROUP)}");
builder.AppendLineLF();
@@ -15,16 +15,17 @@ namespace AIStudio.Tools.PluginSystem.Assistants;
/// <param name="SupportContact">Where users turn with questions about this plugin.</param>
/// <param name="SourceURL">Where the plugin comes from.</param>
/// <param name="Categories">The categories this plugin belongs to.</param>
/// <param name="CustomCategories">The names of the custom categories, when the categories contain CUSTOM.</param>
/// <param name="TargetGroups">The target groups this plugin is meant for.</param>
/// <param name="IsMaintained">Whether the plugin is still maintained.</param>
/// <param name="DeprecationMessage">What users are told when the plugin is deprecated.</param>
/// <param name="IsAssistantBuilderGenerated">Whether the Assistant Builder created this plugin.</param>
public sealed record DirectChatLauncherPluginMetadata(Guid Id, string Version, DateTimeOffset? LastChanged, IReadOnlyList<string> Authors, string SupportContact, string SourceURL,
IReadOnlyList<PluginCategory> Categories, IReadOnlyList<PluginTargetGroup> TargetGroups, bool IsMaintained, string DeprecationMessage, bool IsAssistantBuilderGenerated)
IReadOnlyList<PluginCategory> Categories, IReadOnlyList<string> CustomCategories, IReadOnlyList<PluginTargetGroup> TargetGroups, bool IsMaintained, string DeprecationMessage, bool IsAssistantBuilderGenerated)
{
/// <summary>
/// Takes the metadata of an installed launcher for the case where one is edited.
/// </summary>
public static DirectChatLauncherPluginMetadata FromPlugin(PluginAssistants plugin) => new(plugin.Id, plugin.Version.ToString(), plugin.LastChanged, plugin.Authors,
plugin.SupportContact, plugin.SourceURL, plugin.Categories, plugin.TargetGroups, plugin.IsMaintained, plugin.DeprecationMessage, plugin.IsAssistantBuilderGenerated);
plugin.SupportContact, plugin.SourceURL, plugin.Categories, plugin.CustomCategories, plugin.TargetGroups, plugin.IsMaintained, plugin.DeprecationMessage, plugin.IsAssistantBuilderGenerated);
}
@@ -61,7 +61,15 @@ public interface IPluginMetadata
/// The categories of this plugin.
/// </summary>
public PluginCategory[] Categories { get; }
/// <summary>
/// The names of the categories this plugin names itself, when its categories contain CUSTOM.
/// </summary>
/// <remarks>
/// These names come in the language of the plugin's authors, so AI Studio shows them as they are.
/// </remarks>
public string[] CustomCategories { get; }
/// <summary>
/// The target groups of this plugin.
/// </summary>
@@ -1,5 +1,7 @@
using System.Globalization;
using AIStudio.Settings;
using Lua;
// ReSharper disable MemberCanBePrivate.Global
@@ -74,7 +76,10 @@ public abstract partial class PluginBase : IPluginMetadata, IDisposable
/// <inheritdoc />
public PluginCategory[] Categories { get; } = [];
/// <inheritdoc />
public string[] CustomCategories { get; } = [];
/// <inheritdoc />
public PluginTargetGroup[] TargetGroups { get; } = [];
@@ -168,10 +173,16 @@ public abstract partial class PluginBase : IPluginMetadata, IDisposable
issues.Add(issue);
if(this.TryInitCategories(out issue, out var categories))
{
this.Categories = categories;
if(this.TryInitCustomCategories(categories, out issue, out var customCategories))
this.CustomCategories = customCategories;
else
issues.Add(issue);
}
else if(this is not NoPlugin)
issues.Add(issue);
if(this.TryInitTargetGroups(out issue, out var targetGroups))
this.TargetGroups = targetGroups;
else if(this is not NoPlugin)
@@ -432,10 +443,14 @@ public abstract partial class PluginBase : IPluginMetadata, IDisposable
return false;
}
//
// Only the names of categories count. Enum.TryParse would also take a number such as "1", or
// "BUSINESS, SCIENCE" as a combination of both, and turn them into some category nobody named:
//
var categoryList = new List<PluginCategory>();
foreach(var luaCategory in categoriesTable.GetArraySpan())
if(luaCategory.TryRead<string>(out var categoryName))
if(Enum.TryParse<PluginCategory>(categoryName, out var category) && category != PluginCategory.NONE)
if(PluginCategory.TryParseName(categoryName, out var category) && category != PluginCategory.NONE)
categoryList.Add(category);
categories = categoryList.ToArray();
@@ -444,7 +459,79 @@ public abstract partial class PluginBase : IPluginMetadata, IDisposable
message = string.Format(TB("The table CATEGORIES is empty. At least one category is necessary. Valid categories are: {0}."), CommonTools.GetAllEnumValues(PluginCategory.NONE));
return false;
}
message = string.Empty;
return true;
}
/// <summary>
/// Tries to read the names of the categories the plugin names itself.
/// </summary>
/// <remarks>
/// The table CUSTOM_CATEGORIES belongs to the category CUSTOM, in both directions: CUSTOM without
/// a name could not be shown anywhere, and names without CUSTOM would be a category the plugin did
/// not declare. Either way, the plugin is invalid, so that its authors notice it right away.
/// Names are trimmed, and a name which differs from an earlier one only in its case is dropped,
/// because both would end up under the same heading anyway.
/// </remarks>
/// <param name="categories">The categories the plugin declared in CATEGORIES.</param>
/// <param name="message">The error message, when the names could not be read.</param>
/// <param name="customCategories">The read names, or an empty array without CUSTOM.</param>
/// <returns>True, when the names could be read successfully.</returns>
private bool TryInitCustomCategories(PluginCategory[] categories, out string message, out string[] customCategories)
{
customCategories = [];
var isCustomDeclared = categories.Contains(PluginCategory.CUSTOM);
var customCategoriesValue = this.State.Environment["CUSTOM_CATEGORIES"];
if (customCategoriesValue.Type is LuaValueType.Nil)
{
if (isCustomDeclared)
{
message = TB("The category CUSTOM requires the table CUSTOM_CATEGORIES with at least one name.");
return false;
}
message = string.Empty;
return true;
}
if (!customCategoriesValue.TryRead<LuaTable>(out var customCategoriesTable))
{
message = TB("The table CUSTOM_CATEGORIES is using an invalid syntax. It must be a table of names.");
return false;
}
//
// We read the table by its length rather than by GetArraySpan: the span may hold empty slots
// beyond the last entry, which would read as names which are no text:
//
var names = new List<string>();
for (var index = 1; index <= customCategoriesTable.ArrayLength; index++)
{
if (!customCategoriesTable[index].TryRead<string>(out var name) || string.IsNullOrWhiteSpace(name))
{
message = TB("The table CUSTOM_CATEGORIES contains an empty name or a value which is not a text.");
return false;
}
name = name.Trim();
if (!names.Contains(name, StringComparer.OrdinalIgnoreCase))
names.Add(name);
}
if (isCustomDeclared && names.Count == 0)
{
message = TB("The category CUSTOM requires the table CUSTOM_CATEGORIES with at least one name.");
return false;
}
if (!isCustomDeclared && names.Count > 0)
{
message = TB("The table CUSTOM_CATEGORIES requires the category CUSTOM in the table CATEGORIES.");
return false;
}
customCategories = names.ToArray();
message = string.Empty;
return true;
}
@@ -464,10 +551,11 @@ public abstract partial class PluginBase : IPluginMetadata, IDisposable
return false;
}
// Only the names of target groups count, as for the categories:
var targetGroupList = new List<PluginTargetGroup>();
foreach(var luaTargetGroup in targetGroupsTable.GetArraySpan())
if(luaTargetGroup.TryRead<string>(out var targetGroupName))
if(Enum.TryParse<PluginTargetGroup>(targetGroupName, out var targetGroup) && targetGroup != PluginTargetGroup.NONE)
if(PluginTargetGroup.TryParseName(targetGroupName, out var targetGroup) && targetGroup != PluginTargetGroup.NONE)
targetGroupList.Add(targetGroup);
targetGroups = targetGroupList.ToArray();
@@ -30,4 +30,26 @@ public enum PluginCategory
FICTION,
WRITING,
CONTENT_CREATION,
/// <summary>
/// Assistants for everyday tasks, which the assistants page shows under "General".
/// </summary>
/// <remarks>
/// CORE stays the category of configuration and language plugins. An assistant plugin which
/// names CORE nevertheless appears under "General" as well.
/// </remarks>
COMMON,
/// <summary>
/// Assistants which help to develop AI Studio itself, e.g., its localization.
/// </summary>
AI_STUDIO_DEVELOPMENT,
/// <summary>
/// A category the plugin names itself, see CUSTOM_CATEGORIES.
/// </summary>
/// <remarks>
/// Plugins name such categories in the language of their authors, so AI Studio cannot translate them.
/// </remarks>
CUSTOM,
}
@@ -16,7 +16,7 @@ public static class PluginCategoryExtensions
PluginCategory.UTILITY => TB("Utility"),
PluginCategory.SOFTWARE_DEVELOPMENT => TB("Software Development"),
PluginCategory.GAMING => TB("Gaming"),
PluginCategory.EDUCATION => TB("Education"),
PluginCategory.EDUCATION => TB("Learning & Reflecting"),
PluginCategory.ENTERTAINMENT => TB("Entertainment"),
PluginCategory.SOCIAL => TB("Social"),
PluginCategory.SHOPPING => TB("Shopping"),
@@ -36,6 +36,10 @@ public static class PluginCategoryExtensions
PluginCategory.FICTION => TB("Fiction"),
PluginCategory.WRITING => TB("Writing"),
PluginCategory.CONTENT_CREATION => TB("Content Creation"),
PluginCategory.COMMON => TB("General"),
PluginCategory.AI_STUDIO_DEVELOPMENT => TB("AI Studio Development"),
PluginCategory.CUSTOM => TB("Custom category"),
_ => TB("Unknown plugin category"),
};
@@ -334,6 +334,14 @@ public sealed class PluginConfiguration(bool isInternal, LuaState state, PluginT
// Config: hide some assistants?
ManagedConfiguration.TryProcessConfiguration(x => x.App, x => x.HiddenAssistants, this.Id, settingsTable, dryRun);
// Config: disable some categories of assistants, built-in ones and plugins alike?
ManagedConfiguration.TryProcessConfiguration(x => x.App, x => x.DisabledAssistantCategories, this.Id, settingsTable, dryRun);
ManagedConfiguration.TryProcessConfiguration(x => x.App, x => x.DisabledCustomAssistantCategories, this.Id, settingsTable, dryRun);
// Config: what happens to the assistants of categories users collapsed or hid?
ManagedConfiguration.TryProcessConfiguration(x => x.AssistantsPage, x => x.CollapsedCategoryAssistants, this.Id, settingsTable, dryRun);
ManagedConfiguration.TryProcessConfiguration(x => x.AssistantsPage, x => x.HiddenCategoryAssistants, this.Id, settingsTable, dryRun);
// Config: prohibit some providers?
ManagedConfiguration.TryProcessConfiguration(x => x.App, x => x.ProhibitedProviders, this.Id, settingsTable, dryRun);
@@ -131,6 +131,32 @@ public static partial class PluginFactory
return wasConfigurationChanged;
}
/// <summary>
/// Whether your organization deployed this assistant plugin itself.
/// </summary>
/// <remarks>
/// Rules of your organization which keep plugins of others away, e.g., disabled categories, never
/// apply to its own plugins. Two things prove that a plugin is one of them: it is stored below the
/// directory of a configuration plugin, or it declares DEPLOYED_USING_CONFIG_SERVER and your
/// organization approved exactly its code, e.g., when an MDM solution rolls it out. The declaration
/// alone proves nothing, because any plugin from the internet can make it. The approval alone does
/// not either: it states that a plugin is safe, not that the organization wants it.
/// </remarks>
/// <param name="plugin">The assistant plugin in question.</param>
/// <param name="approvals">The approvals of your organization, i.e., DataAssistantPluginAudit.EnterpriseApprovedPlugins.</param>
/// <returns>True when your organization deployed the plugin itself.</returns>
public static bool IsAssistantDeployedByOrganization(PluginAssistants plugin, IEnumerable<DataAssistantPluginEnterpriseApproval> approvals)
{
if (IsOrganizationConfigurationPath(plugin.PluginPath))
return true;
if (!plugin.IsManagedByConfigServer)
return false;
var pluginHash = NormalizeAssistantHash(plugin.ComputeAuditHash());
return pluginHash.Length > 0 && approvals.Any(approval => string.Equals(NormalizeAssistantHash(approval.PluginHash), pluginHash, StringComparison.Ordinal));
}
private static bool IsOrganizationDefaultActivation(Dictionary<string, DataAssistantPluginEnterpriseApproval> approvalsByHash, string pluginHash)
=> approvalsByHash.TryGetValue(pluginHash, out var approval) && approval is { Activate: true, AllowUserOverride: true };
@@ -37,6 +37,9 @@ public sealed class PluginMetadata(PluginBase plugin, string localPath, bool isM
/// <inheritdoc />
public PluginCategory[] Categories { get; } = plugin.Categories;
/// <inheritdoc />
public string[] CustomCategories { get; } = plugin.CustomCategories;
/// <inheritdoc />
public PluginTargetGroup[] TargetGroups { get; } = plugin.TargetGroups;
@@ -3,6 +3,8 @@ using System.Text.Json;
using AIStudio.Assistants.Builder;
using AIStudio.Chat;
using AIStudio.Provider;
using AIStudio.Settings;
using AIStudio.Settings.DataModel;
using AIStudio.Tools.PluginSystem;
using AIStudio.Tools.PluginSystem.Assistants;
using AIStudio.Tools.ToolCallingSystem;
@@ -10,7 +12,7 @@ using ProviderSettings = AIStudio.Settings.Provider;
namespace AIStudio.Tools.Services;
public sealed class AssistantPluginGenerationService(ToolRegistry toolRegistry, ILogger<AssistantPluginGenerationService> logger)
public sealed class AssistantPluginGenerationService(ToolRegistry toolRegistry, SettingsManager settingsManager, ILogger<AssistantPluginGenerationService> logger)
{
private static string TB(string fallbackEN) => I18N.I.T(fallbackEN, typeof(AssistantPluginGenerationService).Namespace, nameof(AssistantPluginGenerationService));
@@ -58,7 +60,7 @@ public sealed class AssistantPluginGenerationService(ToolRegistry toolRegistry,
if (string.IsNullOrWhiteSpace(context))
return DraftFailure(TA("The Assistant-Builder was not able to read the plugin manifest and therefore cannot safely generate your assistant right now."));
var prompt = BuildAssistantDraftPrompt(request, context);
var prompt = BuildAssistantDraftPrompt(request, context, settingsManager.ConfigurationData.App);
var markdown = await this.GenerateTextAsync(provider, prompt, TB("Assistant Draft"), BuildDraftSystemPrompt(), token);
if (string.IsNullOrWhiteSpace(markdown))
return DraftFailure(TB("The draft model did not return a usable answer."));
@@ -121,6 +123,12 @@ public sealed class AssistantPluginGenerationService(ToolRegistry toolRegistry,
if (!ResponseMetadataMatchesPlugin(parsedResponse.Assistant, generatedAssistant))
return InitialFailure(TB("The generated assistant metadata does not match the generated plugin."));
if (!ResponseCategoriesMatchPlugin(parsedResponse.Plugin, generatedAssistant))
return InitialFailure(TB("The categories of the generated assistant do not match the generated plugin."));
if (this.DescribeDisabledCategories(generatedAssistant.Categories, generatedAssistant.CustomCategories) is { Length: > 0 } disabledCategoriesIssue)
return InitialFailure(disabledCategoriesIssue);
if (this.FindUnknownToolIds(generatedAssistant) is { Count: > 0 } unknownToolIds)
return InitialFailure(string.Format(TA("The generated assistant plugin asks for tools this AI Studio does not have: '{0}'. Please try again."), string.Join(", ", unknownToolIds)));
@@ -151,6 +159,11 @@ public sealed class AssistantPluginGenerationService(ToolRegistry toolRegistry,
return InitialFailure(error.GetMessage(technicalDetails));
}
// The answer was checked while parsing, so reading it again cannot fail:
AssistantBuilderCategories.TryRead(texts.Categories, texts.CustomCategories, out var categories, out var customCategories);
if (this.DescribeDisabledCategories(categories, customCategories) is { Length: > 0 } disabledCategoriesIssue)
return InitialFailure(disabledCategoriesIssue);
var metadata = new DirectChatLauncherPluginMetadata(
request.PluginId,
DEFAULT_VERSION,
@@ -158,7 +171,8 @@ public sealed class AssistantPluginGenerationService(ToolRegistry toolRegistry,
[DEFAULT_AUTHOR],
DEFAULT_SUPPORT_CONTACT,
DEFAULT_SOURCE_URL,
[PluginCategory.CORE],
categories,
customCategories,
[PluginTargetGroup.EVERYONE],
IsMaintained: true,
DeprecationMessage: string.Empty,
@@ -241,6 +255,12 @@ public sealed class AssistantPluginGenerationService(ToolRegistry toolRegistry,
if (!ResponseMetadataMatchesPlugin(parsedResponse.Assistant, revisedAssistant))
return RevisionFailure(TB("The revised assistant metadata does not match the revised plugin."));
if (!ResponseCategoriesMatchPlugin(parsedResponse.Plugin, revisedAssistant))
return RevisionFailure(TB("The categories of the revised assistant do not match the revised plugin."));
if (this.DescribeDisabledCategories(revisedAssistant.Categories, revisedAssistant.CustomCategories) is { Length: > 0 } disabledCategoriesIssue)
return RevisionFailure(disabledCategoriesIssue);
if (this.FindUnknownToolIds(revisedAssistant, plugin) is { Count: > 0 } unknownToolIds)
return RevisionFailure(string.Format(TA("The revised assistant plugin asks for tools this AI Studio does not have: '{0}'. Please try again."), string.Join(", ", unknownToolIds)));
@@ -333,6 +353,26 @@ public sealed class AssistantPluginGenerationService(ToolRegistry toolRegistry,
Return exactly one JSON object. Do not wrap JSON in Markdown or code fences.
""";
/// <summary>
/// The rule which carries the category of the approved draft into the plugin.
/// </summary>
/// <remarks>
/// The draft names the category in a fixed form, see AssistantBuilderCategories. The
/// user may have edited that line, though, so a name which is no key counts as a custom category
/// rather than a reason to give up. AI Studio checks the answer strictly afterward.
/// </remarks>
/// <param name="writesLua">True when the model writes the plugin.lua, false when it only answers with JSON fields.</param>
/// <returns>The rule as a line of a bullet list.</returns>
private static string CategoryRule(bool writesLua)
{
var keys = string.Join(", ", AssistantBuilderCategories.Offered.Select(category => Enum.GetName(category)));
var target = writesLua
? $$"""A key such as BUSINESS becomes CATEGORIES = {"BUSINESS"}. "{{AssistantBuilderCategories.CUSTOM_PREFIX}} <name>" becomes CATEGORIES = {"CUSTOM"} together with CUSTOM_CATEGORIES = {"<name>"}; write CUSTOM_CATEGORIES only then. Repeat the keys as categories and the names as custom_categories in the JSON "plugin" object."""
: $$"""A key such as BUSINESS goes into categories as ["BUSINESS"]. "{{AssistantBuilderCategories.CUSTOM_PREFIX}} <name>" goes into categories as ["CUSTOM"] and its name into custom_categories. Leave custom_categories empty otherwise.""";
return $$"""- Take the category from the "## {{TB("Category")}}" section of the approved draft. {{target}} When the section names anything else than one of these keys, treat it as the name of a custom category. The keys are: {{keys}}.""";
}
private static string BuildLauncherTextsPrompt(AssistantPluginLuaGenerationRequest request, AssistantBuilderChatLaunchRequest chatLaunch) =>
$$"""
Name a direct chat launcher tile for AI Studio, based on the approved draft below.
@@ -355,11 +395,14 @@ public sealed class AssistantPluginGenerationService(ToolRegistry toolRegistry,
"schema_version": "{{LauncherTextsResponse.SCHEMA_VERSION_VALUE}}",
"plugin_name": "...",
"title": "...",
"description": "..."
"description": "...",
"categories": ["..."],
"custom_categories": []
}
Rules:
- Take plugin_name and title from the "## {{TB("Name")}}" section of the approved draft. Do not invent a different name and do not use placeholder text.
{{CategoryRule(writesLua: false)}}
- Keep title short enough to read on a tile: two to four words.
- Write description as one sentence that says which chat this tile opens and what it is for. Do not describe an input form, a prompt, or a submit button, because a launcher has none.
- Write all three texts in the language of the approved draft.
@@ -436,7 +479,6 @@ public sealed class AssistantPluginGenerationService(ToolRegistry toolRegistry,
AUTHORS = {"{{DEFAULT_AUTHOR}}"}
SUPPORT_CONTACT = "{{DEFAULT_SUPPORT_CONTACT}}"
SOURCE_URL = "{{DEFAULT_SOURCE_URL}}"
CATEGORIES = {"CORE"}
TARGET_GROUPS = {"EVERYONE"}
IS_MAINTAINED = true
DEPRECATION_MESSAGE = ""
@@ -457,6 +499,7 @@ public sealed class AssistantPluginGenerationService(ToolRegistry toolRegistry,
- Generate one self-contained plugin.lua only. Do not use require(...) or depend on icon.lua, assets, or any other companion file.
- The JSON "plugin" object describes the top-level Lua plugin metadata such as NAME, DESCRIPTION, and CATEGORIES.
- Take the plugin NAME and ASSISTANT.Title from the "## {{TB("Name")}}" section of the approved draft. Do not invent a different name and do not use placeholder text.
{{CategoryRule(writesLua: true)}}
- A null value in the request JSON means the user did not specify that detail. Never write the word "null" or a field name into the plugin.
- The JSON "assistant" object describes either a form assistant or a direct chat launcher.
- The plugin must include all required top-level metadata and the ASSISTANT table.
@@ -468,7 +511,7 @@ public sealed class AssistantPluginGenerationService(ToolRegistry toolRegistry,
""";
}
private static string BuildAssistantDraftPrompt(AssistantPluginDraftGenerationRequest request, string context)
private static string BuildAssistantDraftPrompt(AssistantPluginDraftGenerationRequest request, string context, DataApp app)
{
var draftSections = request.ChatLaunch is null
? $$"""
@@ -568,7 +611,11 @@ public sealed class AssistantPluginGenerationService(ToolRegistry toolRegistry,
- Treat filled optional guidance as explicit user intent.
- A null value means the user did not specify that detail. Derive it yourself from the assistant description. Never write the word "null", a field name, or placeholder text into the draft.
- The "## {{TB("Name")}}" section is mandatory and must always name the assistant. Use assistant_title verbatim when it is not null. When it is null, invent a short, specific name of two to four words that says what the assistant does.
- The "## {{TB("Category")}}" section is mandatory and consists of exactly one line and nothing else: either one key from the "Categories" list below, spelled exactly as listed, or "{{AssistantBuilderCategories.CUSTOM_PREFIX}} " followed by the name of a category of the user's own. Use category verbatim when it is not null. When it is null, choose the one key which fits the assistant best. Never invent a custom category yourself, and never use a key which is not in the list.
{{typeRequirements}}
Categories:
{{AssistantBuilderCategories.ListForPrompt(app)}}
""";
}
@@ -623,6 +670,7 @@ public sealed class AssistantPluginGenerationService(ToolRegistry toolRegistry,
- A null value in the request JSON means that detail is not available. Never write the word "null" or a field name into the plugin.
- Keep ID = "{{plugin.Id}}" exactly. Do not create a new plugin ID.
- Keep TYPE = "ASSISTANT".
- Keep CATEGORIES and CUSTOM_CATEGORIES unless the requested change asks for another category. CUSTOM_CATEGORIES lists the names of custom categories and belongs to the key CUSTOM in CATEGORIES only. Repeat the keys as categories and the names as custom_categories in the JSON "plugin" object.
- Set LAST_CHANGED = "{{NowAsLastChanged}}" right after VERSION, replacing any earlier value.
- Keep the assistant locally managed. DEPLOYED_USING_CONFIG_SERVER must not be true.
{{builderMetadataRule}}
@@ -809,6 +857,45 @@ public sealed class AssistantPluginGenerationService(ToolRegistry toolRegistry,
requested is not null && actual is not null &&
requested.ToHashSet(StringComparer.Ordinal).SetEquals(actual);
/// <summary>
/// Whether the categories of the answer are the ones the plugin states.
/// </summary>
/// <remarks>
/// The loader drops what it does not know from CATEGORIES, so a plugin.lua with a misspelled key may
/// still load with fewer categories than the model meant. Comparing it with the strictly checked
/// JSON catches that.
/// </remarks>
/// <param name="metadata">The plugin metadata of the answer.</param>
/// <param name="assistant">The plugin as AI Studio loaded it.</param>
/// <returns>True when both name the same categories.</returns>
private static bool ResponseCategoriesMatchPlugin(AssistantBuilderPluginMetadata? metadata, PluginAssistants assistant) =>
metadata is not null &&
AssistantBuilderCategories.TryRead(metadata.Categories, metadata.CustomCategories, out var categories, out var customCategories) &&
AssistantBuilderCategories.MatchPlugin(assistant, categories, customCategories);
/// <summary>
/// Describes the categories of a new or revised assistant which your organization disabled.
/// </summary>
/// <remarks>
/// The draft offers the model only the categories which are not disabled, but the user may edit the
/// draft, and a revision keeps the categories a plugin had before. See
/// AssistantBuilderCategories.FindDisabled.
/// </remarks>
/// <param name="categories">The categories of the assistant.</param>
/// <param name="customCategories">The names of its custom categories.</param>
/// <returns>The message for the user, or an empty string when your organization disabled none of the categories.</returns>
private string DescribeDisabledCategories(IEnumerable<PluginCategory> categories, IEnumerable<string> customCategories)
{
var disabledCategories = AssistantBuilderCategories.FindDisabled(settingsManager.ConfigurationData.App, categories, customCategories);
return disabledCategories.Count switch
{
0 => string.Empty,
1 => string.Format(TA("Your organization disabled the category '{0}'. Please choose another category for your assistant."), disabledCategories[0].Name),
_ => string.Format(TA("Your organization disabled these categories of your assistant: {0}. Please choose other categories."), string.Join(", ", disabledCategories.Select(category => category.Name))),
};
}
private static bool ResponseMetadataMatchesPlugin(AssistantBuilderAssistantMetadata? metadata, PluginAssistants assistant)
{
//
@@ -16,6 +16,10 @@ public sealed class DirectChatService(SettingsManager settingsManager, DataSourc
public async Task<DirectChatStartResult> TryCreateAssistantChatAsync(PluginAssistants assistantPlugin)
{
// Every way to a launcher leads through here, the one from the Assistant Builder included:
if (settingsManager.IsDisabledByItsCategories(assistantPlugin))
return new(null, TA("Your organization disabled the categories of this assistant."));
if (assistantPlugin.ChatLaunchConfiguration is not { } launchConfiguration)
return new(null, TB("The assistant plugin does not contain a valid chat launch configuration."));