{"title":"Managing agent tasks programmatically (preview)","url":"https://jonas-paprotka.de/docs/dev-itpro/ai/ai-agent-sdk-tasks/","by":"JOP-AL","license":"Copyright (c) Microsoft Corporation. CC BY 4.0, https://creativecommons.org/licenses/by/4.0/; code samples MIT. From https://learn.microsoft.com/en-us/dynamics365/business-central/dev-itpro/ai/ai-agent-sdk-tasks, MicrosoftDocs/dynamics365smb-devitpro-pb at 828b6ee (2026-11-19). Changed: includes filled in, links to this site, and for agents shortened without dropping a fact.","credit":"Microsoft Corporation, CC BY 4.0","origin":"https://learn.microsoft.com/en-us/dynamics365/business-central/dev-itpro/ai/ai-agent-sdk-tasks","source":{"name":"Business Central developer and IT pro docs","repo":"https://github.com/MicrosoftDocs/dynamics365smb-devitpro-pb","commit":"828b6ee72fcd75755627cd6011f3d20899217ab2","date":"2026-11-19"},"checked":"2026-11-19","description":"Learn how to create and manage agent tasks, work with agent sessions, and handle cross-agent operations in Dynamics 365 Business Central.","date":"2026-10-02","meta":{"topic":"concept-article"},"outline":[{"level":1,"title":"Managing agent tasks programmatically (preview)","slug":"managing-agent-tasks-programmatically-preview","at":0,"chars":12645},{"level":2,"title":"Creating agent tasks","slug":"creating-agent-tasks","at":993,"chars":3552},{"level":3,"title":"Create tasks from page actions","slug":"create-tasks-from-page-actions","at":1176,"chars":590},{"level":3,"title":"Create tasks from business events","slug":"create-tasks-from-business-events","at":1766,"chars":847},{"level":3,"title":"Simulating email-based triggers","slug":"simulating-email-based-triggers","at":2613,"chars":815},{"level":3,"title":"Adding attachments to tasks","slug":"adding-attachments-to-tasks","at":3428,"chars":1117},{"level":2,"title":"Adding messages to existing tasks","slug":"adding-messages-to-existing-tasks","at":4545,"chars":1025},{"level":2,"title":"Skipping approval for incoming messages","slug":"skipping-approval-for-incoming-messages","at":5570,"chars":1586},{"level":2,"title":"Tracking tasks","slug":"tracking-tasks","at":7156,"chars":881},{"level":2,"title":"Managing the task lifecycle","slug":"managing-the-task-lifecycle","at":8037,"chars":621},{"level":2,"title":"Detecting and customizing agent sessions","slug":"detecting-and-customizing-agent-sessions","at":8658,"chars":3428},{"level":3,"title":"Detecting if running in an agent session","slug":"detecting-if-running-in-an-agent-session","at":9094,"chars":785},{"level":3,"title":"Binding events for agent task duration","slug":"binding-events-for-agent-task-duration","at":9879,"chars":2207},{"level":2,"title":"Related information","slug":"related-information","at":12086,"chars":559}],"text":"# Managing agent tasks programmatically (preview)\n[This article is prerelease documentation and is subject to change.]\n> IMPORTANT\n > This is a preview feature. Preview features might have restricted functionality and are subject to supplemental terms of use<https://www.microsoft.com/en-us/business-applications/legal/supp-powerplatform-preview/>.\n > The AI development toolkit is available in sandbox environments only. The Agent SDK for AL is available in sandbox environments and, starting from version 28.1, also in production environments.\n > This article is primarily intended for product owners, domain experts, consultants, and developers who want to experiment with AI capabilities in Business Central.\nYou can trigger agent tasks programmatically from AL code. This enables integration with UI actions, business events, and custom workflows. You can also simulate email-based triggers for testing scenarios from the UI. See Run an agent (preview)<ai-development-toolkit-run-agent>.\n## Creating agent tasks\nThe `Agent Task Builder` codeunit provides the primary interface for creating agent tasks. In the next sections, you can see some common integration patterns.\n### Create tasks from page actions\nAdd a page action that creates an agent task when clicked:\n```al\naction(CreateAgentTask)\n{\n    Caption = 'Send to Agent';\n    Image = Task;\n\n    trigger OnAction()\n    var\n        AgentTaskBuilder: Codeunit \"Agent Task Builder\";\n        AgentTask: Record \"Agent Task\";\n    begin\n        AgentTask := AgentTaskBuilder\n            .Initialize(AgentUserSecurityId, 'Review Sales Order')\n            .AddTaskMessage('Sales Team', 'Please review sales order ' + Rec.\"No.\" + ' for customer ' + Rec.\"Sell-to Customer Name\")\n            .Create();\n    end;\n}\n```\n### Create tasks from business events\nRespond to system events like document posting:\n```al\n[EventSubscriber(ObjectType::Codeunit, Codeunit::\"Sales-Post\", 'OnAfterSalesInvHeaderInsert', '', false, false)]\nlocal procedure OnAfterSalesInvoicePost(var SalesInvHeader: Record \"Sales Invoice Header\")\nvar\n    AgentTask: Record \"Agent Task\";\n    AgentTaskBuilder: Codeunit \"Agent Task Builder\";\n    AgentTaskMessageBuilder: Codeunit \"Agent Task Message Builder\";\nbegin\n    AgentTaskMessageBuilder\n        .Initialize('System', 'New invoice posted: ' + SalesInvHeader.\"No.\" + ' for customer ' + SalesInvHeader.\"Sell-to Customer Name\" + '. Amount: ' + Format(SalesInvHeader.Amount));\n\n    AgentTask := AgentTaskBuilder\n        .Initialize(AgentUserSecurityId, 'Review invoice')\n        .AddTaskMessage(AgentTaskMessageBuilder)\n        .Create();\nend;\n```\n### Simulating email-based triggers\nFor testing email integration scenarios, format the task message to include email metadata:\n```al\nlocal procedure CreateEmailSimulationTask(FromAddress: Text; Subject: Text; Body: Text; EmailThreadId: Text)\nvar\n    AgentTaskBuilder: Codeunit \"Agent Task Builder\";\n    AgentTaskMessageBuilder: Codeunit \"Agent Task Message Builder\";\n    MessageText: Text;\nbegin\n    MessageText := StrSubstNo('EMAIL FROM: %1\\nSUBJECT: %2\\n\\n%3', FromAddress, Subject, Body);\n\n    AgentTaskMessageBuilder\n        .Initialize(FromAddress, MessageText);\n\n    AgentTaskBuilder\n        .Initialize(AgentUserSecurityId, Subject)\n        .SetExternalId(EmailThreadId)\n        .AddTaskMessage(AgentTaskMessageBuilder)\n        .Create();\nend;\n```\nNotice how the external ID is used to track the thread ID.\n### Adding attachments to tasks\nWhen your task needs to include files for the agent to process, use the AddAttachment method:\n```al\nlocal procedure CreateTaskWithAttachment(AttachmentStream: InStream; FileName: Text; Sender: Text)\nvar\n    AgentTaskBuilder: Codeunit \"Agent Task Builder\";\n    AgentTaskMessageBuilder: Codeunit \"Agent Task Message Builder\";\n    TempBlob: Codeunit \"Temp Blob\";\n\nbegin\n    // Prepare your file content in AttachmentStream\n    TempBlob.CreateInStream(AttachmentStream);\n\n    AgentTaskMessageBuilder\n        .Initialize(Sender, 'Please process this document')\n        .AddAttachment(FileName, 'application/pdf', AttachmentStream);\n\n    AgentTaskBuilder\n        .Initialize(AgentUserSecurityId, 'Process Document')\n        .AddTaskMessage(AgentTaskMessageBuilder)\n        .Create();\nend;\n```\nAttachments enable agents to process documents like invoices, purchase orders, receipts, contracts, and other business documents. The agent can extract data from these files and use the information to complete tasks.\nSee Attachment capabilities and limitations<ai-development-toolkit-attachments>.\n## Adding messages to existing tasks\nContinue conversations by adding new messages to existing agent tasks:\n```al\nlocal procedure AddMessageToExistingTask(ExternalId: Text; MessageText: Text; Sender: Text)\nvar\n    AgentTaskRecord: Record \"Agent Task\";\n    AgentTask: Codeunit \"Agent Task\";\n    AgentTaskMessageBuilder: Codeunit \"Agent Task Message Builder\";\nbegin\n    // Get the existing task by its external ID\n    AgentTaskRecord := AgentTask.GetTaskByExternalId(AgentUserSecurityId, ExternalId);\n\n    // Add a new message to the task\n    AgentTaskMessageBuilder\n        .Initialize(Sender, MessageText)\n        .SetAgentTask(AgentTaskRecord)\n        .Create();\n\n    // Restart the task if it's completed or stopped\n    if AgentTask.CanSetStatusToReady(AgentTaskRecord) then\n        AgentTask.SetStatusToReady(AgentTaskRecord);\nend;\n```\nThis pattern is useful for:\n Providing additional information after the initial task creation\n Continuing multi-turn conversations with your agent\n Simulating email thread continuations\n## Skipping approval for incoming messages\nBy default, incoming task messages require user approval before the agent starts processing them. This safety mechanism ensures that users can review messages before they're passed to the agent, which is particularly important during initial evaluation of the agent, or for agents working with external inputs.\nStarting with version 28.1, you can skip this approval step for incoming messages by calling the SetRequiresReview method on the `Agent Task Message Builder` with the parameter value false. This allows the agent to start processing messages immediately without requiring manual user approval.\n```al\nlocal procedure CreateTaskWithoutApproval(AgentUserSecurityId: Guid; Sender: Text; MessageText: Text)\nvar\n    AgentTaskBuilder: Codeunit \"Agent Task Builder\";\n    AgentTaskMessageBuilder: Codeunit \"Agent Task Message Builder\";\nbegin\n    AgentTaskMessageBuilder\n        .Initialize(Sender, MessageText)\n        .SetRequiresReview(false);\n\n    AgentTaskBuilder\n        .Initialize(AgentUserSecurityId, 'Process Message')\n        .AddTaskMessage(AgentTaskMessageBuilder)\n        .Create();\nend;\n```\n> IMPORTANT\n> Only skip approval for messages from trusted, controlled sources where input has already been validated. For messages coming from external or untrusted sources, keep the default approval step in place to prevent unintended agent behavior.\n> NOTE\n> If the implementation of the method AnalyzeAgentTaskMessage in the interface IAgentTaskExecution returns some annotations with severity Warning, an approval will be required.\n## Tracking tasks\nThere are two strategies for correlating agent tasks with business entities. The external ID field provides a simple way to store an identifier from an external system (like an email thread ID), useful for one-to-one relationships with external events. For more complex scenarios, track the task ID in a table alongside your business entity records. This approach is recommended when you need to track multiple related entities per task, store extra metadata about the relationship, handle many-to-many relationships, or efficiently query tasks by business entity. By storing task IDs in your tables, you can find all agent tasks related to a specific record, track when multiple agents work on related tasks, and maintain audit trails. Choose external IDs for simple integrations and table-based tracking when you need robust tracking and querying capabilities.\n## Managing the task lifecycle\nMonitor and control running tasks:\n```al\nlocal procedure ManageAgentTask(var AgentTask: Record \"Agent Task\")\nvar\n    AgentTaskCU: Codeunit \"Agent Task\";\nbegin\n    // Check task status\n    if AgentTaskCU.IsTaskRunning(AgentTask) then\n        Message('Task is still running');\n\n    if AgentTaskCU.IsTaskCompleted(AgentTask) then\n        Message('Task completed successfully');\n\n    // Restart a stopped task\n    if AgentTaskCU.CanSetStatusToReady(AgentTask) then\n        AgentTaskCU.SetStatusToReady(AgentTask);\n\n    // Stop a running task\n    AgentTaskCU.StopTask(AgentTask, true);\nend;\n```\n## Detecting and customizing agent sessions\nIn some use cases, agent-specific AL code needs to be written. Examples of these are:\n Adding specific filtering on a page based on the agent task running, for example filter the sales orders only to the customer mentioned in the task message\n Hiding or showing parts of the UI dynamically to agents\n Showing dialogs with guidance for the agent\n Running validation events after agent actions\n### Detecting if running in an agent session\nThe `Agent Session` codeunit can be used to detect if the current session is an agent session and which metadata provider is running:\n```al\nlocal procedure DoAgentWork()\nvar\n    AgentSession: Codeunit \"Agent Session\";\n    AgentMetadataProvider: Enum \"Agent Metadata Provider\";\nbegin\n    // Check if running in any agent session and get the metadata provider\n    if not AgentSession.IsAgentSession(AgentMetadataProvider) then\n        exit;\n\n    // AgentMetadataProvider now contains the type of agent running\n    Message('Running in an agent session with provider: %1', AgentMetadataProvider);\nend;\n```\nIf the code needs to run only for a specific agent instance, the `UserID()` function can be used to retrieve the currently running agent.\n### Binding events for agent task duration\nA more performant pattern to subscribe multiple events only during a specific agent's tasks is to use the `Agent Session` codeunit to bind events during the sign in process of agent sessions.\n```al\ncodeunit 50102 \"Agent Session Events\"\n{\n    Access = Internal;\n    InherentEntitlements = X;\n    InherentPermissions = X;\n    SingleInstance = true;\n\n    [EventSubscriber(ObjectType::Codeunit, Codeunit::\"System Initialization\", OnAfterInitialization, '', false, false)]\n    local procedure RegisterSubscribersOnAfterInitialization()\n    begin\n        RegisterAgentEvents();\n    end;\n\n    local procedure RegisterAgentEvents()\n    var\n        AgentSession: Codeunit \"Agent Session\";\n        AgentMetadataProvider: Enum \"Agent Metadata Provider\";\n        AgentTaskID: BigInteger;\n    begin\n        if not AgentSession.IsAgentSession(AgentMetadataProvider) then\n            exit;\n\n        AgentTaskID := AgentSession.GetCurrentSessionAgentTaskId();\n        SetupCustomEvents(AgentTaskID);\n    end;\n\n    local procedure SetupCustomEvents(AgentTaskID: BigInteger)\n    begin\n        GlobalAgentEvents.SetAgentTaskID(AgentTaskID);\n        if BindSubscription(GlobalAgentEvents) then;\n    end;\n\n    var\n        GlobalAgentEvents: Codeunit \"Agent Events\";\n}\n```\nThen, a subscriber can be defined like the following to run code only for that specific agent task:\n```al\ncodeunit 50101 \"Agent Events\"\n{\n    Access = Internal;\n    InherentEntitlements = X;\n    InherentPermissions = X;\n    SingleInstance = true;\n\n    internal procedure SetAgentTaskID(NewAgentTaskID: BigInteger)\n    begin\n        AgentTaskID := NewAgentTaskID;\n    end;\n\n    [EventSubscriber(ObjectType::Table, Database::\"Sales Header\", OnAfterInsertEvent, '', false, false)]\n    local procedure OnAfterInsertSalesHeader(var Rec: Record \"Sales Header\")\n    begin\n        EncourageAgent();\n    end;\n\n    procedure EncourageAgent()\n    begin\n        Message('Keep up the great work, Agent!');\n    end;\n\n    var\n        AgentTaskID: BigInteger;\n}\n```\nLearn more about detecting if the current session is specifically an agent session in Integrate with the Tasks AL API (preview)<ai-development-toolkit-tasks-api>.\n## Related information\nCoding agents in AL (preview)<ai-agent-sdk-overview>\nDefine and register an agent programmatically (preview)<ai-agent-sdk-define-register>\nAgent setup and configuration (preview)<ai-agent-sdk-configuration>\nIntegrate with the Tasks AL API (preview)<ai-development-toolkit-tasks-api>\nOverview (preview)<https://learn.microsoft.com/dynamics365/business-central/dev-itpro/ai/ai-development-toolkit-landing-page>\nDesigning and coding agents (preview)<ai-development-toolkit-overview>\nRun an agent (preview)<ai-development-toolkit-run-agent>"}