Repository navigation
AI-tools and agents for everything the admin can do - #1334
Conversation
…min can do A plan, nothing built. For every feature of Orchard Core and of this repository it lists the AI tools to add so the admin assistant can do what the admin UI can do: name, description, kind, approval, permission, the agent that owns the tool, implementation notes and test prompts. - README.md: goal, numbers, existing tools, approach, order of work, decisions for the owner - 01-foundation.md: rules for every tool, framework work F1 to F14, existing tools to fix or replace - 02-agents.md: the roster of 57 agents with their tools, and which agents go on which assistant - 03-testing.md: how each tool is proven to be used and useful - 10 to 26: the catalog, one section per feature (807 tool entries) - 90-tool-index.md: every tool in one list
The same file, unchanged, as in pull request 1319, so the new tools check the caller's permission the same way and the two branches merge without a conflict.
…t, owner With OrchardCore.Contents on, the AI Agent module registers listContentItems, listContentItemVersions, restoreContentItemVersion, discardContentItemDraft and changeContentItemOwner in a new ContentsToolsStartup. listContentItems builds the filter text of the admin Content Items page (type, stereotype, status, sort, culture, then the search text) and runs it through that page's filter parser and query service. searchForContentItems stays as it is. The restore tool gives the content manager a copy of the stored version, as the audit trail gives it a snapshot, so the stored version stays in the history. Each tool checks the caller's Orchard Core permission, on the content item where the admin action checks one, and refuses a caller who is not signed in. AgentToolAuthorization and AgentToolResults hold the resource-based check and the result conventions for the tools that follow.
With OrchardCore.ContentTypes on, the AI Agent module registers saveContentTypePart, removeContentTypePart, saveContentPartField, removeContentPartField and reorderContentTypeElements in a new ContentTypesToolsStartup. The tools call IContentDefinitionService, the service the content type editor calls, so its events run and a system-defined part or field is refused. The service writes every value it is given, so a save sends back the values the caller did not change. Settings are merged as JSON keyed by settings class name, the shape a content definition recipe uses. A reorder is accepted only when it names every part or field once, because the service adds an empty field for a name it does not know. The tools need EditContentTypes; the two remove tools ask for approval.
With OrchardCore.ContentLocalization on, the AI Agent module registers listContentItemLocalizations and localizeContentItem in a new ContentLocalizationToolsStartup. The list tool returns one entry for each site culture: the translation's content item, or that it is missing. The localize tool makes the two checks of the admin Localize action (LocalizeContent on the item and EditContent for its type) and calls IContentLocalizationManager.LocalizeAsync.
With OrchardCore.Flows on, the AI Agent module registers listNestedContentItems, saveNestedContentItem and removeNestedContentItem in a new FlowsToolsStartup. createOrUpdateContentItem replaces a nested list whole. These tools change one nested item at any depth: they work on the JSON of the latest version, then merge only the changed part into a draft of the parent and save it through the content manager, with validation, as a draft or published. A new nested item is prepared with ContentItemPreparationService and checked with the payload validation of createOrUpdateContentItem, must be of a content type the part's settings allow, and gets the metadata part the editor welds to it. The tools check EditContent on the parent (PublishContent to publish) and, as the editor does, EditContent or DeleteContent on a nested item of a securable type. The remove tool asks for approval.
…ived With OrchardCore.PublishLater or OrchardCore.ArchiveLater on, the AI Agent module registers scheduleContentItem. The tool takes a local date and time, converts it with ILocalClock as the Publish Later and Archive Later editors do, refuses a time in the past, and saves the item the way those editors' buttons do: a scheduled publish is saved on the draft, a scheduled archive is published. It can also cancel a schedule. It needs PublishContent on the item.
…cument them OrchardContentToolCallerTests runs every new content tool with nobody signed in and with a caller who lacks the permission: each one refuses and changes nothing. It also checks that each JSON schema is closed and describes every argument. OrchardContentToolRegistrationTests checks that each tool is registered with a title, a description and a category, can be picked on a profile, and asks for approval where the tool coverage plan says so. The AI tools page lists the new tools in a table per Orchard Core feature, and the 3.0.0 change log has a line per feature.
… AI tools The AI Agent module references four more Orchard Core library packages, all at the Orchard Core version the solution already pins: OrchardCore.Autoroute.Core (AutoroutePart and the SetHomepage permission), OrchardCore.Taxonomies.Core (TaxonomyPart and TermPart), OrchardCore.Seo.Abstractions (IRobotsProvider and the SEO permission) and OrchardCore.Sitemaps.Abstractions (the sitemap manager, models and permission). Directory.Packages.props gets a version line for the last three. ContentItemListTree walks the tree of a menu or a taxonomy. Its lists are at the same place in the JSON whatever the content type of an item is, so they are found by name, where NestedContentItemTree finds the lists of Flow, Bag and widgets list parts from the content type. Both give the same entries, so the new tools find, move and save an item the way the nested item tools do. NestedContentItemTree.SaveAsync takes the version to load, because the menu and taxonomy editors change the latest version in place when the content type cannot have a draft. ContentItemLookup finds a menu or a taxonomy by content item ID, alias or title, through the parser and query service of the admin Content Items page. ContentItemPayloadCheck is the payload check of saveNestedContentItem moved out of that tool so the taxonomy tool can use it; the wording of the nested item tool is unchanged. AgentToolArguments reads a JSON array argument. OrchardCorePermissions mirrors ManageMenu, with the Menu edit permission that implies it, and ManageTaxonomy.
…e page With OrchardCore.Autoroute on, the AI Agent module registers findContentItemByHandle and setHomepage in a new AutorouteToolsStartup. findContentItemByHandle asks the content handle manager. A URL or a path is looked up as a slug, without the address of the site and the prefix of the tenant; a handle with a prefix is passed as it is; a bare word is tried as a slug, an alias and a content item ID. A path of / reads the home route of the site settings and says so when the home page is not a content item. It checks ViewContent on the content item it finds. setHomepage follows the only path the content editor has: it loads a draft of the content item, sets the SetHomepage flag of the Autoroute part and publishes, and the Autoroute feature writes the home route. The tool does not write the home route itself. It checks SetHomepage, and PublishContent on the content item. It refuses a content item whose latest version is a draft (the draft would go live), one without an Autoroute path and one whose route is disabled, and it reads the home route back before it says the home page changed. The result names the previous home page, which the site does not remember.
With OrchardCore.Menu on, the AI Agent module registers getMenuTree, saveMenuItem and deleteMenuItem in a new MenuToolsStartup. getMenuTree returns the items of a menu in outline order with their parent, depth and position, the URL or the linked content item, and the permissions an item asks for. The menu is given by content item ID, alias or title; without one the tool lists the menus the caller may view. It checks ViewContent on the menu. saveMenuItem adds, updates or moves one item and deleteMenuItem removes one with the items under it. Both check ManageMenu, the permission of the actions of the menu editor, and leave the rest of the menu as it was. Like that editor, they take a draft of the menu when the Menu content type can have drafts and its latest version otherwise. The menu is saved through the content manager with validation, and published only when publish is true, which also needs PublishContent on the menu. A new item must be of a content type with the MenuItem stereotype and starts from IContentManager.NewAsync. The menu parts are classes of the Menu module, so their JSON is written by name. A URL is checked the way the menu item editors check it, so a script URL is refused, and permission names must exist. deleteMenuItem asks for approval.
With OrchardCore.Taxonomies on, the AI Agent module registers getTaxonomyTerms, saveTaxonomyTerm and deleteTaxonomyTerm in a new TaxonomiesToolsStartup. getTaxonomyTerms returns the terms of a taxonomy in outline order with their ID, parent, depth, position and full path. The taxonomy is given by content item ID, alias or title; without one the tool lists the taxonomies the caller may view. It checks ViewContent on the taxonomy. saveTaxonomyTerm adds, updates or moves one term and deleteTaxonomyTerm removes one with the terms under it. Both check ManageTaxonomy, the permission of the actions of the taxonomy editor. Like that editor, they take a draft of the taxonomy when the Taxonomy content type can have drafts and its latest version otherwise. The taxonomy is saved through the content manager with validation, and published only when publish is true, which also needs PublishContent on the taxonomy. A new term starts from IContentManager.NewAsync with the term content type of the taxonomy and gets the welded TermPart, as in the editor. The title goes to the display text and to the title part. Other parts and fields are given as content item JSON and checked with the payload validation of createOrUpdateContentItem; the content cannot hold the ID, the title or child terms. deleteTaxonomyTerm asks for approval and says that content items keep the ID of a deleted term.
With OrchardCore.Seo on, the AI Agent module registers getRobotsTxt in a new SeoToolsStartup. The tool does what the robots middleware does: when the static files of the site have a robots.txt file, that file is the answer and the result says the robots settings have no effect; otherwise the content is what the registered IRobotsProvider services write, the provider registered last first. It checks ManageSeoSettings, the permission of the Robots settings page, and returns at most 20,000 characters with a truncated flag.
With OrchardCore.Sitemaps on, the AI Agent module registers listSitemaps, saveSitemap, deleteSitemap and purgeSitemapCache in a new SitemapsToolsStartup. All four check ManageSitemaps. listSitemaps returns the sitemaps and sitemap indexes with their path, enabled state and sources, and the cached files. saveSitemap creates a sitemap or updates one through ISitemapManager: name, path (made from the name when a new sitemap has none, and checked by ISitemapHelperService.ValidatePathAsync), enabled, and the content type and custom path sources. The source list replaces the stored one; a source listed with its ID is kept and updated, and new sources come from the registered ISitemapSourceFactory. Content types must be ones the routable content type coordinator lists, and a custom path gets the checks of its editor. Every argument is checked before anything is changed, so a refused call leaves the sitemap as it was. deleteSitemap asks for approval. purgeSitemapCache clears one cached file, which must be one the cache lists, or all of them, and reports when the cache provider says a file could not be removed. SitemapIndex and its source are classes of the Sitemaps module, which this module cannot reference. An index is therefore listed, renamed, enabled, disabled and deleted, but it cannot be created, and the sitemaps it contains are neither listed nor changed.
… and document them OrchardSiteStructureToolCallerTests runs each of the thirteen new tools with nobody signed in and with a caller who lacks the permission: each one refuses and changes nothing, and the first permission it checks is the one of the matching admin action. It also checks that each JSON schema is closed and describes every argument. OrchardSiteStructureToolRegistrationTests checks that each tool is registered with a title, a description and a category, can be picked on a profile, and asks for approval where the tool coverage plan says so. The AI tools page lists the new tools in a table per Orchard Core feature, and the 3.0.0 change log has a line per feature.
…copy and delete files With OrchardCore.Media on, the AI Agent module registers listMediaFiles, getMediaFile, getMediaOptions, importMediaFromUrl, saveMediaTextFile, moveMediaFile, copyMediaFile and deleteMediaFile in a new MediaToolsStartup. The module now references OrchardCore.Media.Core, which holds the media permissions and brings the media and file storage abstractions. The file tools go through IMediaFileStore, as the Media Library endpoints do, and check what those endpoints check: ManageMediaContent, then ManageMediaFolder with the path as the resource, so Orchard Core maps the path to the permission for normal folders, the attached media folder, the caller's own folder or the folders of other users. A new file needs an extension the site allows, and UploadRestrictedMedia for a restricted one. getMediaOptions checks ViewMediaOptions and adds the remaining storage only for a caller who may manage the media library. MediaToolSupport holds what the tools share. A path is refused when it has a drive, a '..' or empty segment, or when it names another folder or file after URL decoding: Orchard Core decodes a path before it checks the folder permission and the store does not, so such a path could be checked in one folder and used in another. A file name may still hold a percent sign, as an uploaded file can. The tools store, move and copy a file only into a folder that exists, and none creates or deletes a folder. The Media Library keeps its folder tree in MediaDirectoryTreeCache, a class of the Media module that this module cannot reference, so a folder made here would not show in the tree. createMediaFolder and deleteMediaFolder are not built for the same reason. importMediaFromUrl and saveMediaTextFile store the file through FileCreationService, the pipeline of an upload, so file event handlers can refuse it, and they replace a file only when overwrite is set. saveMediaTextFile writes text extensions only. Both ask for approval, as does deleteMediaFile. moveMediaFile and deleteMediaFile check every file before they change the first one. importMediaFromUrl fetches an address a model chose. RemoteMediaDownloader accepts only http and https without credentials, resolves the host and refuses the request when any address is loopback, private, link-local or otherwise internal, and follows at most five redirects itself, checking each one the same way. Its HTTP client uses the handler of the shared EgressNetwork guard with loopback refused, which follows no redirect and checks the address again when the connection opens. The download goes to a temporary file of ITempDirectoryProvider, stops at MediaOptions.MaxFileSize and after 100 seconds, and a web page returned in place of the file is not stored. getMediaFile returns the text of a file only when asked, at most 20,000 characters: from the text providers of the media indexing features when one is registered for the extension, otherwise from a plain-text file of up to 1 MB.
With OrchardCore.Media.Cache on, the AI Agent module registers purgeMediaCache in a new MediaCacheToolsStartup. OrchardCoreFeatureIds gets the ID of the feature. The tool does what the Purge button of the Media Cache settings page does: it checks ManageAssetCache and calls IMediaFileStoreCache.PurgeAsync. The cache is registered only when a remote media store is enabled and configured, so the tool says there is no cache when the service is missing, and it reports when the cache says some files could not be removed.
With OrchardCore.Shortcodes on, the AI Agent module registers listShortcodes in a new ShortcodesToolsStartup. The module now references OrchardCore.Shortcodes.Abstractions, and OrchardCoreFeatureIds gets the ID of the feature. The tool returns the catalog of IShortcodeDescriptorManager, which is what the shortcode picker of the HTML and Markdown editors shows: every shortcode with its hint, usage, default value and categories, with a search on the name, hint or category and paging. The picker checks no permission, so the tool asks only for a signed-in caller. The Liquid content of a shortcode template is not returned, and saveShortcodeTemplate and deleteShortcodeTemplate are not built: ShortcodeTemplatesManager and the template model are classes of the Shortcodes module, which this module cannot reference.
…ools, and document them OrchardMediaToolCallerTests runs each of the ten new tools with nobody signed in and with a caller who lacks the permission of the matching admin action: each one refuses and changes nothing. For the media file tools it also runs a caller who may use the media library but not the folder, and pins that the folder permission is checked with the path as the resource. It checks that each JSON schema is closed and describes every argument. OrchardMediaToolRegistrationTests checks that each tool is registered with a title, a description and a category, can be picked on a profile, and asks for approval where the tool coverage plan says so. MediaLibraryToolsTests and MediaFileCreationToolsTests run the tools against an in-memory media store that records every change: the main path of each tool, and that a refused call (a missing file or folder, an extension that is not allowed, an existing target, a path that reads differently when decoded, a file a file event handler refuses) changes nothing. RemoteMediaDownloaderTests covers the download of importMediaFromUrl: internal addresses in every notation, a host that resolves to an internal address, redirects to such addresses, the redirect limit, the size limit with and without an announced size, and that the registered HTTP client follows no redirect and refuses to connect to this machine. ListShortcodesToolTests covers the shortcode list. The AI tools page lists the new tools in a table per Orchard Core feature, and the 3.0.0 change log has a line per feature.
…, rebuild and delete With OrchardCore.Indexing on, the AI Agent module registers listIndexProfiles, getIndexProfile, saveIndexProfile, synchronizeIndexProfile, rebuildIndexProfile and deleteIndexProfile in a new IndexingToolsStartup. Each tool checks ManageIndexes for the signed-in caller, as the Indexes admin page does, and takes an index profile by its ID or its name. rebuildIndexProfile and deleteIndexProfile ask for approval. The tools call IIndexProfileManager and the keyed IIndexManager of the provider in the order the page does. Create is new, validate, store, create the physical index (the profile is removed again when the provider cannot), synchronize. Reset is reset, update, synchronize. Rebuild is reset, update, rebuild, synchronize, under the IndexingService lock of the index, as the rebuild recipe step takes it. Delete removes the physical index and then the profile, with the force option of the page. The tools that take a list do nothing when one of the indexes is unknown, and the ones that start indexing say that it was started, not that it is finished. saveIndexProfile updates the name and, for a Content index, the content types, the culture and latest or published. It sets them the way the editor of the page does and validates a copy with the manager first, so a refused change never stays on the profile the rest of the request reads. A content type must exist. The provider, the type and the index name cannot be changed, and the analyzer and the other provider settings are not arguments: they stay on the admin page. getIndexProfile returns the analyzer, the default search fields and the names of the indexed fields for Lucene and Elasticsearch indexes, read from the typed metadata of the two providers. The module now references OrchardCore.Indexing.Core, OrchardCore.Lucene.Core and OrchardCore.Elasticsearch.Core, and OrchardCore.Search.Abstractions and OrchardCore.Queries.Abstractions for the search and query tools that follow.
With OrchardCore.Search on, a new SearchToolsStartup registers searchIndex. It searches an index profile, or the default index of the site search settings, with the keyed ISearchService of the provider, pages the way the search page does, and loads the content items in the order of the results. It checks QuerySearchIndex with the index profile as the resource, so the permission of one index is enough. The search handlers the page calls afterwards are not called: a search by the tool is not a visitor's. With OrchardCore.Lucene or OrchardCore.Elasticsearch on, LuceneToolsStartup and ElasticsearchToolsStartup register runSearchQuery. It runs an ad-hoc JSON query as an unsaved query of the provider's query source through IQueryManager, which is how the query API of each provider runs one and uses the query service of the "Run query" admin page. It checks ManageLuceneIndexes for a Lucene index and ManageElasticIndexes for an Elasticsearch index, refuses a caller who holds neither before it looks up an index, and refuses an index of another provider, a missing physical index and an unconfigured Elasticsearch. QueryResultRows bounds the rows every query tool returns: a page of at most 50 rows, a page size limit, long values shortened, a content item as a summary, and values whose name says they are a credential replaced, also inside a JSON document in a text column.
With OrchardCore.Queries on, a new QueriesToolsStartup registers listQueries, saveQuery, deleteQuery and runQuery. The first three check ManageQueries; saveQuery and deleteQuery ask for approval. runQuery checks the permission of the query API for the query, and checks it for a name that matches no query too, so a caller who may not run queries does not learn which names exist. A failed saved query is logged and not relayed, because the caller may run it without being allowed to read it. saveQuery saves Lucene and Elasticsearch queries through IQueryManager with the checks of the Queries admin page: a safe and unique name, a template, an index profile of the source's provider and a JSON schema. An update removes the stored query and saves it again, as the Edit action does, which is also how a query is renamed. It does not save or change a SQL query: the page checks the SQL with SqlParser.Validate, which is internal to the Queries module, so the tool cannot make that check. With OrchardCore.Queries.Sql on, SqlQueriesToolsStartup registers runSqlQuery, which asks for approval and checks ManageSqlQueries. The permission is declared in OrchardCore.Queries.Core, which this repository does not reference, so OrchardCorePermissions mirrors it. The tool opens no connection: the SQL is the template of an unsaved query that the SQL query source runs, so it goes through Orchard Core's SQL parser (a SELECT only, with the tenant's table prefix). That source logs a query its parser refuses and returns no rows, so a result without rows says that both cases are possible.
…ry tools, and document them OrchardSearchToolCallerTests runs each of the thirteen new tools with nobody signed in and with a caller who lacks the permission of the matching admin action: each one refuses and changes and runs nothing. It pins the permission each tool checks, that searchIndex checks it on the index profile, that runSearchQuery refuses a caller who holds no "Run query" permission before it looks up an index and a caller who holds the one of another provider, and that runQuery checks the permission of a name that matches no query. It checks that each JSON schema is closed and describes every argument. OrchardSearchToolRegistrationTests checks that each tool is registered with a title, a description and a category, can be picked on a profile, and asks for approval where the tool coverage plan says so, and that runSearchQuery is registered the same way for Lucene and for Elasticsearch. IndexProfileToolsTests runs the index tools against an index profile manager and index managers that record every call: the order of create, reset, rebuild and delete, the indexing lock of a rebuild, the copy an update is validated on, and that a refused call changes nothing. SearchIndexToolTests covers the default index, the paging of the search page, the result order and a provider that cannot search. RunSearchQueryToolTests covers the unsaved query each provider runs and the cases that run nothing. QueryToolsTests covers list, save, rename, delete and run of saved queries, the refusal to save SQL, and runSqlQuery: the SQL only reaches the SQL query source, the rows are paged, credentials are left out, and a result without rows says a refused query looks the same. QueryResultRowsTests covers the limits of a result. The AI tools page lists the new tools in a table per Orchard Core feature, and the 3.0.0 change log has a line per feature.
…unlock, confirm email and delete With OrchardCore.Users on, listUsers, getUser, saveUser, enableUser, disableUser, unlockUser, confirmUserEmail and deleteUser check the permission the Users admin page checks on the user they act on and call the same services (the filter parser and query service of the page, the user manager and the user service). Results are built from a fixed list of fields and never hold a password hash, a security stamp, a token or the key of an external login. No tool takes a password: saveUser updates the user name, email and phone number and does not create a user. disableUser and deleteUser refuse the caller's own account, the site owner and the only enabled administrator. A caller who may act on no user gets the same refusal for an ID that exists and for one that does not.
With OrchardCore.Users and OrchardCore.Roles on, setUserRoles adds and removes roles with the checks of the role editor of a user: the permission to edit the user, and the permission to assign roles on each role it touches. It refuses the caller's own account, a role a user cannot hold, a role the caller may not assign, and removing the administrator role from the only enabled administrator. Everything is checked before anything is changed. A removed role changes the security stamp, as the role editor does.
With OrchardCore.Users.2FA on, disableUserTwoFactor does what the action of the Users admin page does, with the same permission, and refuses the account of the caller. The result says whether the site makes the user set two-factor authentication up again.
With OrchardCore.Users.CustomUserSettings on, saveUserCustomSettings merges the given parts and fields into the settings stored inside the user, validates them with the content manager and stores the user. It checks the permission to edit the user and the permission of the settings type, as the user editor does.
With OrchardCore.Roles on, listRoles, getRole and listPermissions read the roles, the assigned and effective permissions of a role and the permissions the enabled features provide; saveRole and deleteRole create, change and delete roles through the role manager. saveRole keeps the rules of the Roles admin page (a role name without a slash that no other role has; the permissions of the administrator role cannot be changed) and adds four: only permissions an enabled feature provides, no security-critical permission for Anonymous or Authenticated, no new permission on a role the caller holds, and every security-critical permission named again in the call so the approval shows it. deleteRole refuses system roles.
AIConstants.Feature.Area and AIConstants.Feature.OrchardCoreAIAgent repeated AIFeatureIds.Area and AIFeatureIds.Agent, and the startups used both. Every use now reads AIFeatureIds, which every module can reach; the two AIConstants names are obsolete aliases, listed under breaking changes.
Adds 25 test classes for the shared services that the group 1 admin pages now save, delete and validate through. They check main's messages, error fields, order of steps and permissions. Two pages behaved differently from main and now match it again: - Report subscriptions: a form that already has errors (from a field that did not bind or from an editor driver) is only checked. Nothing is copied onto the stored subscription. - Bookings Dates: when a field does not bind, the date and price errors show with it again. Nothing is saved (BookingDates.CheckAddAsync).
Await-style ValueTask results in the price list tests, and TryGet instead of the obsolete As in the phone verification tests.
|
The Core side of section 1 of the review is merged in CrestApps.Core: CrestApps/CrestApps.Core@15bcc89 (CrestApps/CrestApps.Core#359). It moves to Core:
|
…view-19250 CrestApps.Core 403 includes CrestApps/CrestApps.Core#359, so this pull request uses Core's code-defined agents, agent tool scope and card and bank number guard, and deletes its own copies: AIAgentDefinition, AIAgentOptions, AddAIAgent, FeatureAIAgentProvider, FeatureAIAgentToolScopeHandler and AIMoneyArguments. The AI module sets the agents' shared rules in this site's words. Core 403 also hashes visitor addresses with a random key instead of a salt (CrestApps/CrestApps.Core#357). The AI module keeps that key in the tenant's database and loads it when the tenant starts, the AI chat settings use RemoteAddressStorageMode and no longer show the ignored salt, and the changelog lists the change.
|
@MikeAlhayek thank you for the review. Everything in it is done; here is what changed, section by section. 1. Move to CrestApps.Core
2. No more tools in this pull request
3. CI
4. Tools that existed on
5. Smaller points
|
MikeAlhayek
left a comment
There was a problem hiding this comment.
Second review: nearly there
@JackTelford thank you, this round is very good. I checked each point against the code at cab0a085e:
- CrestApps.Core. The code-defined agents, the agent tool scope and
AIMoneyArgumentsare gone from this repository and come from CrestApps.Core 2.0.0-preview.403 (CrestApps/CrestApps.Core#359). Keeping an agent's tools in scope now works for every agent, not only code-defined ones. - No more tools. None were added. The plan marks what this pull request delivers, the description is rewritten, and #1412 tracks the rest.
- CI. Green. You're right about Validate Pull Request: its
pull_request_targetruns fail at startup on other branches too, so it isn't from this pull request. - Tools that existed on
main. The upgrade migrations and the breaking-change note are in. - Smaller points.
AIFeatureIdsis the only id,AILocalTimeArgumentsmoved to Calendars asLocalTimeArguments, AI.Core no longer references Calendars, and the moved rules have tests.
A few things are left. The first one has to be fixed before this merges. The others are small.
1. getStoreSetupGuide sends the bank-transfer instructions to the model
#1412 lists this under "Fix first" and asks to check whether this pull request fixed it. It didn't, and it's this pull request's own tool, so please fix it here.
GetStoreSetupGuideTool returns every quick-action field with its value (Commerce/AI/GetStoreSetupGuideTool.cs:77). For the offline payments step that field is bankTransfer.Instructions (PayLater/Services/OfflinePaymentsSetupStep.cs:85), the "How to pay you" text, which usually holds the store's bank account number. That breaks the rule this pull request sets for itself: no secrets pass through the model.
Fix: for that field, return whether it is set, not its text. A step should be able to mark a field as sensitive, so the tool leaves its value out. Then check getSiteSettings on the offline payments settings for the same leak. Its secret detection works by field name (EditorReplay.IsSecretName), and Instructions doesn't match. Add tests for both.
2. Other "Fix first" items that are this pull request's own code
These are small, and they belong to tools and agents this pull request adds, so please fix them here rather than in the follow-up:
ai-knowledge-agentis registered by AI File Sources (AI.FileSources/AIAgentStartup.cs), so it disappears when File Sources is off, along with the data source, web crawler and profile document tools it carries. Register it in the AI Agent or Data Sources module.resetUserSignInFactorssays this Orchard Core version has no passkeys (AI.Agent/Users/ResetUserSignInFactorsTool.cs:19and its description). It has them. Fix the text now, even ifremoveUserPasskeyswaits for the follow-up.updateProductPricingtells the model to "use the content tools for everything else on a product", butcatalog-agenthas no content tools. Point it at what the agent does have, or say that it isn't available here.
The course guard that silently undoes a content-agent change (item 4) can wait for the follow-up.
3. The upgrade migration also runs when a module is turned on later
Each module's AIAgentFeatureMigrations is a new migration, so it runs when the module is first enabled and the site is not being set up. On an upgraded site that is what we want. But it also runs on an existing site that turns on Payroll, Tickets or any of the other 12 modules next month, or that turns on AI later while those modules are on. AI Agent then gets turned on with force: true, even if the admin chose to leave it off.
Please limit it to sites that really used the tools before the upgrade. For example, run it only when the module was already enabled before this start (its other migration records already exist), or keep the one-time step in a single place that runs once per tenant at upgrade. If you'd rather keep it as it is, say so in the changelog: "turning on one of these modules on a site with AI turns on Orchard Core AI Agent too". Either way, add a test for the case where the module is turned on later.
4. Follow-ups as several pull requests
#1412 says the remaining ~540 tools and 41 agents "come in one follow-up PR". That would be this pull request's size again. Please plan them as several pull requests, one per area or agent group, in the order of the parts in #1412, each one updating the plan as its tools land.
5. The tests cover the rules, not the pages that call them
The 75 test classes test the new *Rules, *Editor and *Query services well. The two regressions they found were both in how a controller calls them, though: saving before checking ModelState, and copying input before the form's errors were known. The tests don't cover that order. Please do one UI pass of the moved pages' save and delete paths, with a deliberately invalid form on each, or add a few controller-level tests for the ones that save money or delete records (Purchase Orders, Customers, Work Order Settings, Webhooks, Phone Number Verifications, Call Recordings).
Summary
| Review round 1 | Done |
| Bank-transfer instructions sent to the model | Fix here (blocking) |
ai-knowledge-agent, passkeys text, updateProductPricing wording |
Fix here (small) |
| Upgrade migration on modules turned on later | Limit it, or document it |
| Follow-ups | Several pull requests, not one |
| Moved pages | One UI pass with invalid forms, or controller tests for the risky ones |
Once 1 and 2 are in, and 3 is limited or documented, I'm happy to approve.
|
@MikeAlhayek this PR has the KeyedHashKeyTenant Fix in it and must be merged before the mail newsletter PR |
…p, controller tests - Bank-transfer instructions are never sent to the model: store setup fields can be marked sensitive (StoreSetupField.IsSensitive, [SensitiveValue]); the setup guide only says whether they are set, runStoreSetupStep refuses them in chat, and the editor replay treats them as secrets. - ai-knowledge-agent moves to AI Agent; resetUserSignInFactors passkeys text and updateProductPricing wording fixed. - The 14 per-module AI Agent upgrade migrations are replaced by one check in AI (profiles, MCP and WebMCP tool lists) and one in Chat Interactions. They run after the index tables exist, so turning a module on later doesn't turn on AI Agent. Covered by tests. - Controller tests with invalid forms for Purchase Orders, Customers, Store Credit, Loyalty, Work Order Settings, Webhooks, Phone Number Verifications and Call Recordings. - Shared fail-closed keyed-hash key loader moves to CrestApps.OrchardCore.Core (AddTenantRemoteAddressProtector): loads after the request, never replaces a key it can't read. - Tool pickers post only the ticked tools, fixing the HTTP 400 when a form passed 1,024 values.
|
@MikeAlhayek thank you for the second review. Every point is answered in ✅ 1. The bank-transfer instructions no longer reach the model
✅ 2. The small fixes
✅ 3. The upgrade step no longer runs when a module is turned on laterI went with your second option, one step in one place:
4. Follow-upsNoted. #1412 is outside this pull request, and we'll plan how it lands there. ✅ 5. Controller tests with invalid forms8 new controller test classes. Each posts a deliberately invalid form, or one without the permission, and checks that the page shows the form again and nothing is saved, deleted or erased. Each also checks that a valid form saves exactly once:
All pass without changing the controllers. Also in this push
UI passI ran the app and went through the pages these changes touch. Nothing from these changes shows up in the log or the browser console.
The Release build passes with warnings as errors. 27,467 unit tests and 216 Learning integration tests pass.
|
MikeAlhayek
left a comment
There was a problem hiding this comment.
Third review
@JackTelford thank you. I checked a24814482 against each point of the second review, and they are all done:
- Bank-transfer instructions.
StoreSetupField.IsSensitiveand[SensitiveValue]keep the text out ofgetStoreSetupGuide,runStoreSetupStepandgetSiteSettings, and a value typed in the chat is refused. I found no other tool that returns those instructions. - Small fixes.
ai-knowledge-agentnow lives in AI Agent, the passkeys text is gone, andupdateProductPricingpoints atsaveProductVariants. - Upgrade step. The 14 per-module migrations are replaced by one step that runs once and only acts when the site already uses one of the moved tools. That's much better.
- Controller tests. The eight new controller test classes are what I asked for: an invalid form, or one without the permission, saves nothing, and a valid one saves once.
Two things in this push need a change, and there are a few nits.
1. FailClosedKeyedHashKeyStore reverses a CrestApps.Core decision for every tenant
CrestApps.Core replaces a key it can't decrypt on purpose. KeyedHasher.ReplaceUnreadableKeyAsync explains why: waiting for the lost Data Protection keys "would leave remote addresses unhashed, and the chat unusable in the default mode, until somebody deletes the key by hand". FailClosedKeyedHashKeyStore throws instead, and AddTenantRemoteAddressProtector registers it for the AI module. On a tenant that loses its Data Protection keys, a deployment without a persisted key ring for example, anonymous visitors can no longer use the AI chat until someone restores the keys.
I understand why mailing lists (#1369) wants it: there, a new key breaks lookups of stored hashes for good. But that's a choice per use, not one for the whole tenant, and it changes how a Core service behaves. As the first review said, a patch to Core behavior belongs in CrestApps.Core:
- Add an option to CrestApps.Core, such as a keyed-hash option that says whether an unreadable key is replaced or the hasher fails. Keep Core's default.
- In this pull request, keep AI chat on Core's default (replace). Drop the wrapper, or keep it only where a module explicitly asks for fail-closed.
- Mailing lists can then ask for fail-closed for its own hashes when #1369 lands.
Loading the key after the first request (KeyedHashKeyTenantEvents) to avoid "database is locked" on SQLite is fine and can stay.
2. The upgrade check misses workflows
AIAgentUpgradeMigrations.UsesTheToolsAsync reads AI profiles, the MCP server and WebMCP tool lists, and chat interactions. But the AI completion workflow task also keeps a list of tools (AICompletionWithConfigToolsDisplayDriver, activity.Interaction.ToolNames). A site that uses, for example, createTicket or findInvoices only in a workflow loses those tools on upgrade, and AI Agent stays off. Please also read the workflow types' AI tasks, and add a test for it.
3. Nits
AIAgentUpgradeTools.AnyIn(JsonSerializer.SerializeToNode(profile.Properties))matches any string value anywhere in a profile's properties. Some of the names are common words,askabove all, so any property whose value is exactlyaskturns AI Agent on. Read the tool lists themselves (FunctionInvocationMetadata.Names, and the post-session tools) instead of every value. The chat interaction step has the same issue withinteraction.Properties.chat-interaction.jsnow reads the tool checkboxes as a setting.getSettingInputs()leaves out names containing.Tools[, but the checkboxes are now namedChatInteraction.SelectedToolNames, so each one is also posted asselectedToolNames: true/false. The hub ignores the key, so nothing breaks, but please add.SelectedToolNamesto the selector's exclusions.- The order of #1334 and #1369. Your comment says #1369 must merge after this one because of the key loader. That's fine, but once point 1 moves the option to Core, #1369 only needs the Core version, not this pull request.
Summary
| Second review | All done |
| Fail-closed hash key for all of AI chat | Move the choice to Core, keep the default for AI chat |
| Upgrade check | Also read workflow AI tasks |
| Nits | Read tool lists, not every value; chat interaction script selector |
With 1 and 2 done, and CI green after the merge from main, I'll approve.
|
@MikeAlhayek thank you for the third review. On point 1, the key code is in this pull request because #1369 (mailing lists) needs a hash key that is never replaced, and #1369 merges after this one. We put the shared pieces in You're right that AI chat shouldn't pay for that, so we'll take your second option:
There's one thing to agree on for the Core option. A tenant has one hash key, and AI chat and mailing lists share it. On a tenant with both, fail-closed for mailing lists also means fail-closed for the chat, unless Core keeps a key per use. Should the Core option give each use its own key, or be one setting per tenant? |
|
This pull request has merge conflicts. Please resolve those before requesting a review. |
…does FailClosedKeyedHashKeyStore made hashing throw when the Data Protection keys that protected the tenant's hash key are lost. The AI chat hashes the visitor's address when it starts every session (signed-in users too) and in its rate limits, so in the default Hashed mode every new chat failed until someone deleted the key from the database by hand. AddTenantRemoteAddressProtector now uses CrestApps.Core's YesSqlKeyedHashKeyStore, which replaces a key it can't decrypt. The key still lives in the tenant's database and still loads after the first request. Only hashes stored before the loss stop matching; visitors find their sessions by their cookie, not by the hash. The test now proves that a lost key is replaced and hashing keeps working.
…e-plan # Conflicts: # src/Modules/CrestApps.OrchardCore.Staff/Drivers/StaffMemberDisplayDriver.cs
On the AI profile, AI profile template and chat interaction editors, each agent checkbox carries the names of the tools the agent has (not shown). Ticking an agent hides those tools in the Tools list and unticks them, so they aren't saved as tools of their own; a note says how many are hidden. Search and "Select All" skip the hidden tools, and unticking the agent shows them again, unticked. A tool ticked on its own works as before.
…for the admin, Plaid ACH, pull_request workflows) Conflicts: - AI Chat's remote address helper: main has the same CrestApps.Core helper, with the key loaded after the request that starts the tenant; main's side is kept (tenant events, docs, recipe schema, view, view model). - Campaign send moved into CampaignService.QueueSendAsync on main; it now checks the campaign's own e-mail address to send from, as this branch's page did, and the page keeps this branch's message. - Customers: main's CustomerEditorRules.Apply; the marketing choice still goes through the consent service on the page. - Coupons: main's CouponEditor.CheckCodeGeneration, using the shared CouponCodeGenerator.IsValidPrefix rule. - Help center: main's YesSql session type. Main's new Marketing AI test-send tool sends through CampaignService.SendTestAsync as the page does (from the campaign's e-mail address, through the Email Messaging Channel); its tests and CampaignServiceTests use this branch's CampaignService, and CustomersAdminControllerTests passes the consent service.
Lets an administrator do what the admin UI does by asking the AI assistant: AI tools for the Orchard Core features and the CrestApps modules, specialist agents that carry them, and the framework both need. The plan this follows, and what is still to come, are in
docs/engineering/ai/tool-coverage/(start with its README).What this pull request delivers
The framework
AIToolCallerAuthorization).AIActionPreviewTokens) protects the tools that move money.StoreSetupField.IsSensitive) or a settings property ([SensitiveValue]) can be marked sensitive, as the bank-transfer instructions are: tools only say whether it is set, and refuse a new value from the chat.AIRecordKindlets a module offer its records tolistRecords,getRecord,saveRecordanddeleteRecordthrough its own editors and permissions.Rules moved out of controllers and drivers
*Rules,*Editorand*Queryservices, so a page and its tool share one set of rules.main(75 new test classes). Writing them found two regressions, both fixed: the report subscription editor copied input onto the stored subscription when the form already had errors, and the bookings date page stopped showing its errors when a field didn't bind.Tools and agents
[Feature(...)]and[RequireFeatures(AIFeatureIds.Agent)]. The Orchard Core tools inAI.Agentalso require their Orchard Core feature.Breaking changes
The full text is in
changelog/3.0.0.md, under Breaking Changes.ask, and the Calendars, Dispatch, Invoicing, Learning AI, Payroll AI, Scheduling, SEO, Staff, Surveys AI, Tickets, Workforce and Workforce contact center tools.endCall,pressKeys,collectSecureDigits,transferToLiveAgent) still need only AI.AIFeatureIds.AreaandAIFeatureIds.Agent(inCrestApps.OrchardCore.Abstractions) are the only ids of these two features.AIConstants.Feature.AreaandAIConstants.Feature.OrchardCoreAIAgentare obsolete aliases.AIVisitorRemoteAddressModebecomesCrestApps.Core.Security.RemoteAddressStorageMode.AddTenantRemoteAddressProtector()inCrestApps.OrchardCore.Coresets this up for any module that hashes addresses (Add mailing lists: newsletter sign-up #1369 uses it too).SelectedToolNames). A view that overridesEditProfileTools_Edit,ChatInteractionTools_EditorAIProfilePostSession_Editstill works, but should post the names too.Uses CrestApps.Core 2.0.0-preview.403
Code-defined agents (
AIAgentDefinition,AIAgentOptions,AddAIAgentand the provider, nowCodeDefinedAIAgentProvider), keeping every agent's tools in scope while it runs (inAgentProxyTool), and the card and bank number guard (AIMoneyArguments) moved to CrestApps.Core in CrestApps/CrestApps.Core#359.This pull request uses CrestApps.Core 2.0.0-preview.403, which includes it, and its own copies are deleted. The AI module sets the agents' shared rules in this site's words. Orchard Core is 4.0.0-preview-19250.
What comes next
docs/engineering/ai/tool-coverage/marks what this pull request delivers and what is left. Each follow-up updates it.Testing
03-testing.mdare still to run against a live site.🤖 Generated with Claude Code