Part 20: Manager Approvals and Checkpoints
Some requests need a person to say yes. A paid app costs a licence, so before the service desk assigns one, the employee's manager has to approve it, and the manager may answer in five minutes or in three days. In this part the agent sends such a request to the manager, and a workflow waits for the answer: a request port pauses the run, checkpoints in Azure Cosmos DB keep it waiting through restarts, and a new endpoint continues it when the manager answers.
This is Part 20 of a 23-part series.
- Part 1: Overview, Architecture and Azure Setup
- Part 2: Create a Production-Grade .NET Solution
- Part 3: Your First Agent API with Microsoft Foundry
- Part 4: Multi-Turn Conversations with Sessions
- Part 5: Create a Next.js Chat App for Your Agent
- Part 6: Stream the Agent Through a Trusted Next.js Route Handler
- Part 7: Build a Streaming Chat Page with the AG-UI Client
- Part 8: Secure the Agent API with Microsoft Entra ID
- Part 9: Add Microsoft Entra ID Sign-In to the Next.js Chat App
- Part 10: Give the Agent Enterprise Tools
- Part 11: Let the Agent Create Tickets
- Part 12: Connect an MCP Server
- Part 13: Human Approval for Sensitive Actions
- Part 14: Approval Cards in the Chat UI
- Part 15: Persistent Conversations
- Part 16: Memory That Knows the Employee
- Part 17: Guardrails — Keep Secrets Out of the Model
- Part 18: Audit Logs and Observability
- Part 19: Ticket Triage Workflow
- Part 20: Manager Approvals and Checkpoints (you are here)
- Part 21: Agent Harness — Weekly Problem Report (coming soon)
- Part 22: Deploy to Azure Container Apps (coming soon)
- Part 23: Bring It to Microsoft Teams (coming soon)
What You Will Build
An employee asks the agent for Microsoft Visio. The agent sends the request to their manager and tells them so:

Behind that answer, a workflow run started, saved the request, asked the manager and stopped. Nothing of it stays in memory: the run waits in Azure Cosmos DB. The API can restart, or another copy of it can take the manager's answer, minutes or days later. When the answer comes, the run continues where it stopped, assigns the licence and writes an audit entry.
By the end of this part, the solution has:
- A company directory and a software catalog: who each employee's manager is, and three paid apps an employee can ask for. Like the ticket system, they're sample versions you can swap for the real systems.
- Two new tools:
request_software, which sends a request to the employee's manager, andget_my_software_requests, which tells the employee where their requests stand. - The software approval workflow: a step that saves the request, a request port that asks the manager and waits, and a step that carries out the answer.
- Checkpoints in Cosmos DB, through a checkpoint store of its own, so a waiting run survives restarts.
- An
approvalscontainer with one item per request, kept in the manager's own partition. - Two endpoints for managers:
GET /api/approvalslists the requests waiting for them, andPOST /api/approvals/{number}approves or rejects one. - Three new audit entries: a request sent, approved and rejected.
The chat app doesn't change. Managers answer through the API, here from the .http file.
How a Workflow Waits for a Person
Part 19's workflow ran from start to finish in about a second and a half. This one stops in the middle, for as long as the manager takes. Two features of Agent Framework workflows make that possible.
A request port asks and waits
A request port is a step that asks the outside world a question. Microsoft's guide to human-in-the-loop workflows describes it: When an executor sends a message to a RequestPort, the request port emits a RequestInfoEvent that contains the details of the request. The run then has nothing left to do, so it stops with the status PendingRequests. Whoever holds the answer creates a response from that event, and the run continues with it.
Here is the software approval workflow, drawn by the workflow itself:
- SubmitRequest saves the employee's request in the workflow's state and sends the manager a question.
- ManagerApproval is the request port. It turns the question into a
RequestInfoEventand waits for an answer. - ApplyDecision gets the manager's answer. If it's yes, it assigns the app's licence to the employee. Either way, it writes the audit entry and returns the outcome, the workflow's output.
How to Pause a Microsoft Agent Framework Workflow Until a Person Answers in C# shows a request port on its own, in a small console app.
A checkpoint keeps the run waiting
A run that stops in memory dies with the process. A checkpoint keeps it. Microsoft's guide to checkpoints says when they're made: Checkpoints are created at the end of each superstep, after all executors in that superstep have completed their execution. A superstep is one round of the run, in which every step that has a message waiting runs. Each checkpoint saves the steps' state, the messages on their way, the questions still waiting for an answer and the shared state.
The software approval run has two rounds before it stops: SubmitRequest, then the request port. So each request leaves two checkpoints, and the second one holds the manager's question. When the answer comes, maybe after a restart and in another copy of the API, the code loads that checkpoint into a new run. The guide promises what happens next: When you restore from a checkpoint, any pending requests will be re-emitted as RequestInfoEvent objects. The code answers that event, and the run continues to ApplyDecision.
How to Resume a Microsoft Agent Framework Workflow from a Checkpoint After a Restart in C# shows that on its own: one process starts a run and stops, a second process continues it.
The whole journey of one request
What This Part Costs
- Azure Cosmos DB: from the request charges in the traces, sending one request cost 27 request units (RU): two checkpoints and the approval item. Answering it cost 74 RU: reading and claiming the request, loading the checkpoint, two more checkpoints, and deleting all four at the end. At the serverless price from Part 15, $0.25 per million RU, that's about $25 for a million requests. A waiting request takes a few kilobytes of storage: its item, and two checkpoints of about 6 KB each.
- The model: the three chat requests in Steps 15 and 16 used 16,982 input tokens, 16,320 of them from Foundry's prompt cache, and 258 output tokens: less than half a cent at the prices from Part 1.
- The manager's account: a user in Microsoft Entra ID without a licence costs nothing.
Prerequisites
- The solution and the chat app from Part 19: Ticket Triage Workflow, with the Aspire Dashboard running as in Part 18.
- The right to create users in your Microsoft Entra tenant, such as the User Administrator role. The manager in this part is a second, real account that signs in.
Step 1: Create the Approvals and Checkpoints Containers
This part keeps two new kinds of data in the servicedesk database from Part 15, each in a container of its own: approvals, with one item per software request, and checkpoints, with the saved state of the workflow runs that wait for an answer.
The approvals container
The Azure CLI creates it in one command, the way Part 16 created memories. How to Create a Database and Container in Azure Cosmos DB Data Explorer shows the same in the portal.
- bash / zsh
- PowerShell
az cosmosdb sql container create \
--account-name cosmos-maf-servicedesk-4224 \
--resource-group rg-maf-servicedesk \
--database-name servicedesk \
--name approvals \
--partition-key-path /approverId \
--ttl 31536000 \
--query "{container:name, partitionKey:resource.partitionKey.paths, defaultTtl:resource.defaultTtl}"
az cosmosdb sql container create `
--account-name cosmos-maf-servicedesk-4224 `
--resource-group rg-maf-servicedesk `
--database-name servicedesk `
--name approvals `
--partition-key-path /approverId `
--ttl 31536000 `
--query "{container:name, partitionKey:resource.partitionKey.paths, defaultTtl:resource.defaultTtl}"
Replace the account name with yours.
--partition-key-path /approverId: every request has anapproverId, the manager who answers it, and all the requests sent to one manager share a partition. A manager's list and every answer stay inside that one partition.--ttl 31536000: 365 days, in seconds, counted from an item's last change. A request nobody answers for a year disappears, and an answered request stays for a year after its answer, so the employee can still ask about it. How to Set a Time to Live on an Azure Cosmos DB Container explains how Cosmos DB counts it.
It took 37 seconds:
{
"container": "approvals",
"defaultTtl": 31536000,
"partitionKey": [
"/approverId"
]
}
The checkpoints container
By default, Azure Cosmos DB indexes everything. Microsoft's page on indexing policies says it: The default indexing policy for newly created containers indexes every property of every item and enforces range indexes for any string or number. A checkpoint keeps the whole state of a run in one property, value, about 6 KB of JSON that nothing ever searches: the code reads a checkpoint by its ID and lists a run's checkpoint IDs, and that's all. So the checkpoints container gets an indexing policy that leaves value out.
Save this as checkpoints-indexing.json in the folder where you run the next command:
{
"indexingMode": "consistent",
"includedPaths": [
{ "path": "/*" }
],
"excludedPaths": [
{ "path": "/value/*" }
]
}
"includedPaths": [{ "path": "/*" }]indexes every property, as the default does, so queries onsessionId,parentIdandcommittedAtstay cheap."excludedPaths": [{ "path": "/value/*" }]takesvalueout of the index, with everything inside it./*at the end of a path means the property and everything below it."indexingMode": "consistent"updates the index with every write. A time to live needs it: Microsoft's page says it isn't possible to activate TTL on a container where the indexing mode is set tonone.
Then create the container with the policy:
- bash / zsh
- PowerShell
az cosmosdb sql container create \
--account-name cosmos-maf-servicedesk-4224 \
--resource-group rg-maf-servicedesk \
--database-name servicedesk \
--name checkpoints \
--partition-key-path /sessionId \
--ttl 31536000 \
--idx @checkpoints-indexing.json \
--query "{container:name, partitionKey:resource.partitionKey.paths, defaultTtl:resource.defaultTtl, indexing:resource.indexingPolicy}"
az cosmosdb sql container create `
--account-name cosmos-maf-servicedesk-4224 `
--resource-group rg-maf-servicedesk `
--database-name servicedesk `
--name checkpoints `
--partition-key-path /sessionId `
--ttl 31536000 `
--idx '@checkpoints-indexing.json' `
--query "{container:name, partitionKey:resource.partitionKey.paths, defaultTtl:resource.defaultTtl, indexing:resource.indexingPolicy}"
--partition-key-path /sessionId: every checkpoint belongs to one workflow run, its session, and one run's checkpoints are read and deleted together.--idx @checkpoints-indexing.json: the indexing policy. An@before a file name tells the Azure CLI to read the value from that file. In PowerShell,@starts a splatting expression, so the value is in quotes: Microsoft's page on running the Azure CLI in PowerShell says to enclose the value in single (') or double (") quotes.--queryadds the indexing policy to the output, so you can check it.
It took 35 seconds:
{
"container": "checkpoints",
"defaultTtl": 31536000,
"indexing": {
"automatic": true,
"compositeIndexes": null,
"excludedPaths": [
{
"path": "/value/*"
},
{
"path": "/\"_etag\"/?"
}
],
"fullTextIndexes": [],
"includedPaths": [
{
"indexes": null,
"path": "/*"
}
],
"indexingMode": "consistent",
"spatialIndexes": null,
"vectorIndexes": null
},
"partitionKey": [
"/sessionId"
]
}
Cosmos DB added one excluded path of its own, /"_etag"/?, which every default policy has too. Once the container exists, the policy is part of it, and you can delete checkpoints-indexing.json. How to Exclude a Property from Indexing in Azure Cosmos DB with the Azure CLI shows this on its own, with a small example.
My first checkpoints container had the default policy. The request charges in the traces (Step 17 shows where to find them) gave it away: every checkpoint write cost 38 to 45 request units, and deleting one cost the same, because Cosmos DB updated an index entry for every property inside value. One request and its answer cost 367 RU together. With value left out of the index, a checkpoint write costs 8 or 9 RU, and the same request and answer cost 101 RU. Microsoft's page explains why: By optimizing the number of paths that are indexed, you can substantially reduce the latency and RU charge of write operations. My container was still empty, so I deleted it and created it again with the command above.
Step 2: Give Yourself Access to Both Containers
Your account has the Cosmos DB Built-in Data Contributor role on sessions and memories only, since Parts 15 and 16. Give it the role on the two new containers, one assignment each:
- bash / zsh
- PowerShell
az cosmosdb sql role assignment create \
--resource-group rg-maf-servicedesk \
--account-name cosmos-maf-servicedesk-4224 \
--role-definition-id 00000000-0000-0000-0000-000000000002 \
--principal-id "$(az ad signed-in-user show --query id --output tsv)" \
--scope "/dbs/servicedesk/colls/approvals"
az cosmosdb sql role assignment create \
--resource-group rg-maf-servicedesk \
--account-name cosmos-maf-servicedesk-4224 \
--role-definition-id 00000000-0000-0000-0000-000000000002 \
--principal-id "$(az ad signed-in-user show --query id --output tsv)" \
--scope "/dbs/servicedesk/colls/checkpoints"
az cosmosdb sql role assignment create `
--resource-group rg-maf-servicedesk `
--account-name cosmos-maf-servicedesk-4224 `
--role-definition-id 00000000-0000-0000-0000-000000000002 `
--principal-id "$(az ad signed-in-user show --query id --output tsv)" `
--scope "/dbs/servicedesk/colls/approvals"
az cosmosdb sql role assignment create `
--resource-group rg-maf-servicedesk `
--account-name cosmos-maf-servicedesk-4224 `
--role-definition-id 00000000-0000-0000-0000-000000000002 `
--principal-id "$(az ad signed-in-user show --query id --output tsv)" `
--scope "/dbs/servicedesk/colls/checkpoints"
They're the commands from Part 16, with the new containers' names in --scope. How to Give Your Account Access to Azure Cosmos DB Data with the Azure CLI explains every option. The first took 37 seconds and the second 36:
{
"id": "…/databaseAccounts/cosmos-maf-servicedesk-4224/sqlRoleAssignments/00000000-0000-0000-0000-000000000000",
"name": "00000000-0000-0000-0000-000000000000",
"principalId": "00000000-0000-0000-0000-000000000000",
"resourceGroup": "rg-maf-servicedesk",
"roleDefinitionId": "…/databaseAccounts/cosmos-maf-servicedesk-4224/sqlRoleDefinitions/00000000-0000-0000-0000-000000000002",
"scope": "…/databaseAccounts/cosmos-maf-servicedesk-4224/dbs/servicedesk/colls/approvals",
"systemData": null,
"type": "Microsoft.DocumentDB/databaseAccounts/sqlRoleAssignments"
}
{
"id": "…/databaseAccounts/cosmos-maf-servicedesk-4224/sqlRoleAssignments/00000000-0000-0000-0000-000000000000",
"name": "00000000-0000-0000-0000-000000000000",
"principalId": "00000000-0000-0000-0000-000000000000",
"resourceGroup": "rg-maf-servicedesk",
"roleDefinitionId": "…/databaseAccounts/cosmos-maf-servicedesk-4224/sqlRoleDefinitions/00000000-0000-0000-0000-000000000002",
"scope": "…/databaseAccounts/cosmos-maf-servicedesk-4224/dbs/servicedesk/colls/checkpoints",
"systemData": null,
"type": "Microsoft.DocumentDB/databaseAccounts/sqlRoleAssignments"
}
The role is still only on the containers the API uses. The manager's account, which you create next, gets no role at all: managers only ever reach Cosmos DB through the API, which signs in as you.
Step 3: Add a Manager Who Can Sign In
A manager answers requests through the API, so the manager has to be a real account that can sign in and get a token. In your tenant, add a user named Test Manager, as How to Add a User and Assign a License in the Microsoft 365 Admin Center shows, with one difference: on Product licenses, choose Create user without product license. The manager only signs in, so it needs no licence, no group and no role.
The company directory you add in Step 6 needs two object IDs: yours, the employee who asks, and the manager's. The Azure CLI looks them up. Yours:
az ad signed-in-user show --query id --output tsv
00000000-0000-0000-0000-000000000000
And the manager's, by the user name you gave the new user:
az ad user show --id test.manager@contoso.onmicrosoft.com --query "{id:id, displayName:displayName, userPrincipalName:userPrincipalName}"
{
"displayName": "Test Manager",
"id": "44444444-4444-4444-4444-444444444444",
"userPrincipalName": "test.manager@contoso.onmicrosoft.com"
}
Replace test.manager@contoso.onmicrosoft.com with the user name of your manager. Keep both IDs for Step 6.
Step 4: Sign In as the Manager in the Azure CLI
The .http file gets its token from the Azure CLI, which is signed in as you. The manager needs a sign-in of their own, kept apart from yours. Microsoft's guide to subscriptions in the Azure CLI says to Use az login to change the active tenant and update the subscription list to which you belong, and a command that names no subscription uses your current, active subscription. So signing the manager in where you're signed in would make the manager's sign-in the active one, for your own commands too. Microsoft's tips for the Azure CLI describe the setting that keeps the two apart: with the environment variable AZURE_CONFIG_DIR set, Azure CLI commands in that script save the configuration and token cache to the configured location instead of the default ~/.azure folder. So a second folder gives the manager a sign-in beside yours:
- bash / zsh
- PowerShell
AZURE_CONFIG_DIR=~/.azure-test-manager az login --tenant contoso.onmicrosoft.com --allow-no-subscriptions
$env:AZURE_CONFIG_DIR = Join-Path $HOME ".azure-test-manager"
az login --tenant contoso.onmicrosoft.com --allow-no-subscriptions
Remove-Item Env:AZURE_CONFIG_DIR
AZURE_CONFIG_DIR=~/.azure-test-managersets the folder for this one command in bash and zsh. In PowerShell, the first line sets it for the window and the last line removes it, so the nextazcommand is you again.--tenant contoso.onmicrosoft.com: your tenant's domain, where the manager's account lives.--allow-no-subscriptions: the manager has no Azure subscription, and needs none. The Azure CLI reference describes the option: Support accessing tenants without subscriptions.
Your browser opens Microsoft's sign-in page. Sign in as the manager, not as yourself. The first sign-in asks for a new password in place of the temporary one; How to Sign In to Microsoft 365 for the First Time with a Temporary Password shows those screens. Once you're in, the browser shows a page of the Azure CLI documentation, and the terminal lists what the manager can use:
A web browser has been opened at https://login.microsoftonline.com/11111111-1111-1111-1111-111111111111/oauth2/v2.0/authorize. Please continue the login in the web browser. If no web browser is available or if the web browser fails to open, use device code flow with `az login --use-device-code`.
Retrieving subscriptions for the selection...
[Tenant and subscription selection]
No Subscription name Subscription ID Tenant
----- ------------------------- ------------------------------------ ------------------------------------
[1] * N/A(tenant level account) 11111111-1111-1111-1111-111111111111 11111111-1111-1111-1111-111111111111
The default is marked with an *; the default tenant is '11111111-1111-1111-1111-111111111111' and subscription is 'N/A(tenant level account)' (11111111-1111-1111-1111-111111111111).
Select a subscription and tenant (Type a number or Enter for no changes):
N/A(tenant level account) is a sign-in to the tenant without a subscription, the one --allow-no-subscriptions allows. Press Enter to keep it.
My first try was az login --use-device-code, which shows a code to type on another device. The manager's password worked, and then the page said You don't have access to this, with error code 53003: my tenant blocks the device code flow. Fixed: "You don't have access to this" (Error Code 53003) When You Sign In to the Azure CLI with a Device Code explains why and what to do. The browser sign-in above isn't affected.
How to Sign In to Two Accounts at Once in the Azure CLI shows this on its own.
Step 5: Save Both Tokens for the .http File
In Part 8, the .env file next to the .http file got one line, AGENT_API_TOKEN, with your token. Now it gets the manager's token too, as MANAGER_API_TOKEN. Run these commands from the solution root:
- bash / zsh
- PowerShell
API_CLIENT_ID=$(az ad app list --display-name "Dewiride Service Desk API" --query "[0].appId" --output tsv)
TOKEN=$(az account get-access-token --scope "api://$API_CLIENT_ID/access_as_user" --query accessToken --output tsv)
MANAGER_TOKEN=$(AZURE_CONFIG_DIR=~/.azure-test-manager az account get-access-token --scope "api://$API_CLIENT_ID/access_as_user" --query accessToken --output tsv)
printf 'AGENT_API_TOKEN=%s\nMANAGER_API_TOKEN=%s\n' "$TOKEN" "$MANAGER_TOKEN" > src/Dewiride.ServiceDesk.Api/.env
$apiClientId = az ad app list --display-name "Dewiride Service Desk API" --query "[0].appId" --output tsv
$token = az account get-access-token --scope "api://$apiClientId/access_as_user" --query accessToken --output tsv
$env:AZURE_CONFIG_DIR = Join-Path $HOME ".azure-test-manager"
$managerToken = az account get-access-token --scope "api://$apiClientId/access_as_user" --query accessToken --output tsv
Remove-Item Env:AZURE_CONFIG_DIR
"AGENT_API_TOKEN=$token", "MANAGER_API_TOKEN=$managerToken" | Set-Content src/Dewiride.ServiceDesk.Api/.env
The commands print nothing when they succeed: the tokens go straight into the file, never onto your screen.
| Line | What it does |
|---|---|
| The first | Looks up the API's client ID by the registration's name, as in Part 8 |
| The second | Gets your token for the API's access_as_user scope |
| The third | Gets the manager's token for the same scope, from the manager's sign-in folder |
| The last | Writes both tokens into .env, one per line, in place of the file from Part 8 |
In PowerShell, the manager's token takes three lines: the first sets AZURE_CONFIG_DIR to the manager's folder for the commands after it, and Remove-Item Env:AZURE_CONFIG_DIR removes the variable again, so your next az command runs as you.
The manager never had to agree to anything: Part 8 pre-authorized the Azure CLI for the access_as_user scope, for every user of your tenant. Both tokens last about an hour; when the API starts answering 401, run the commands again.
Step 6: Add the Company Directory and the Software Catalog
Before the agent can send a request anywhere, the service desk has to know two things: who the employee's manager is, and which apps an employee can ask for. A real company keeps the first in its directory, such as Microsoft Entra ID, and the second in a software catalog. Like the ticket system from Part 10, both come in as interfaces with sample versions behind them, so a real company swaps the samples for its own systems without touching anything else.
The company directory
An employee is their object ID, their name and their manager's object ID:
namespace Dewiride.ServiceDesk.Agent.Systems;
/// <summary>
/// An employee in the company directory: their object ID in Microsoft Entra ID, the name colleagues see,
/// and their manager's object ID, or null when they have no manager.
/// </summary>
public sealed record Employee(string Id, string DisplayName, string? ManagerId);
The directory finds an employee by their object ID:
namespace Dewiride.ServiceDesk.Agent.Systems;
/// <summary>The company directory: who works here and who their manager is.</summary>
public interface IEmployeeDirectory
{
/// <summary>Finds an employee by their object ID, or returns null when the directory has no such employee.</summary>
Task<Employee?> FindEmployeeAsync(string employeeId, CancellationToken cancellationToken);
}
The sample directory can't invent its employees, the way the ticket system invents tickets: the manager has to be a real account that signs in, the one from Step 3. So its employees come from the app's settings, through an options class:
namespace Dewiride.ServiceDesk.Agent.Systems;
/// <summary>
/// The employees of the sample directory. Filled from the "EmployeeDirectory" section of the app's settings.
/// </summary>
public sealed class EmployeeDirectoryOptions
{
public const string SectionName = "EmployeeDirectory";
/// <summary>Every employee the directory knows, managers included.</summary>
public List<EmployeeEntry> Employees { get; set; } = [];
/// <summary>One employee: their object ID, their name and their manager's object ID, if they have a manager.</summary>
public sealed class EmployeeEntry
{
public string Id { get; set; } = string.Empty;
public string DisplayName { get; set; } = string.Empty;
public string? ManagerId { get; set; }
}
}
using Microsoft.Extensions.Options;
namespace Dewiride.ServiceDesk.Agent.Systems;
/// <summary>
/// A stand-in for the company directory, read from the app's settings. The manager has to be a real
/// account that can sign in, so the employees come from settings instead of sample data in code.
/// A real directory, such as Microsoft Entra ID through Microsoft Graph, replaces it.
/// </summary>
public sealed class SampleEmployeeDirectory(IOptions<EmployeeDirectoryOptions> options) : IEmployeeDirectory
{
// Object IDs are GUIDs, and access tokens carry them in lowercase. Settings may not, so every ID is
// kept in lowercase: then an employee's ID is always the same text, wherever it comes from.
private readonly Dictionary<string, Employee> _employees = options.Value.Employees.ToDictionary(
entry => entry.Id.ToLowerInvariant(),
entry => new Employee(
entry.Id.ToLowerInvariant(),
entry.DisplayName,
string.IsNullOrWhiteSpace(entry.ManagerId) ? null : entry.ManagerId.ToLowerInvariant()));
public Task<Employee?> FindEmployeeAsync(string employeeId, CancellationToken cancellationToken) =>
Task.FromResult(_employees.GetValueOrDefault(employeeId.ToLowerInvariant()));
}
ToDictionaryturns the list from the settings into a dictionary keyed by object ID, once, when the directory is created. Every lookup after that is a dictionary lookup.ToLowerInvariant()keeps every ID in lowercase. The ID of the signed-in employee comes from their token, in lowercase; an ID pasted into the settings may have capitals. Without this, the same person would have two different IDs.GetValueOrDefaultreturnsnullfor an ID the directory doesn't know, and the code that asks decides what that means.
The software catalog
An app in the catalog is an ID and a name:
namespace Dewiride.ServiceDesk.Agent.Systems;
/// <summary>An app in the software catalog that employees can ask for: its ID and its name.</summary>
public sealed record SoftwareTitle(string Id, string Name);
The catalog lists its apps and assigns an app's licence to an employee:
namespace Dewiride.ServiceDesk.Agent.Systems;
/// <summary>
/// The company's software catalog: the paid apps employees can ask for, and the licences assigned to them.
/// Every app in it costs a licence, so it needs the employee's manager to approve it first.
/// </summary>
public interface ISoftwareCatalog
{
/// <summary>Gets every app in the catalog.</summary>
Task<IReadOnlyList<SoftwareTitle>> GetTitlesAsync(CancellationToken cancellationToken);
/// <summary>
/// Assigns an app's licence to an employee, so the app installs on their devices. Assigning a licence
/// the employee already has changes nothing, so it's safe to call again.
/// </summary>
Task AssignLicenceAsync(string employeeId, string softwareId, CancellationToken cancellationToken);
}
AssignLicenceAsync promises that assigning a licence twice changes nothing. That matters later: if the API stops in the middle of an answer, the manager can send the answer again, and the second assignment does no harm.
The sample catalog has three paid apps and keeps the licences it assigned in memory:
namespace Dewiride.ServiceDesk.Agent.Systems;
/// <summary>
/// A stand-in for a real software catalog, kept in memory: three paid apps, and the licences assigned since the app started.
/// </summary>
public sealed class SampleSoftwareCatalog : ISoftwareCatalog
{
private static readonly IReadOnlyList<SoftwareTitle> Titles =
[
new("visio", "Microsoft Visio Plan 2"),
new("project", "Microsoft Project Plan 3"),
new("acrobat-pro", "Adobe Acrobat Pro"),
];
// Requests can arrive at the same moment, so one lock guards the licences.
private readonly Lock _lock = new();
private readonly Dictionary<string, HashSet<string>> _licencesByEmployee = [];
public Task<IReadOnlyList<SoftwareTitle>> GetTitlesAsync(CancellationToken cancellationToken) => Task.FromResult(Titles);
public Task AssignLicenceAsync(string employeeId, string softwareId, CancellationToken cancellationToken)
{
if (!Titles.Any(title => title.Id == softwareId))
{
throw new ArgumentException($"The software catalog has no app with the ID {softwareId}.", nameof(softwareId));
}
lock (_lock)
{
if (!_licencesByEmployee.TryGetValue(employeeId, out HashSet<string>? licences))
{
licences = [];
_licencesByEmployee.Add(employeeId, licences);
}
// A set: adding a licence the employee already has changes nothing.
licences.Add(softwareId);
}
return Task.CompletedTask;
}
}
Lockis the lock type of .NET 9 and later. The catalog is one instance for the whole app, so two answers can assign licences at the same moment, andlock (_lock)lets only one of them change the dictionary at a time.HashSet<string>holds each employee's licences. Adding a value a set already has does nothing, which keeps the promise of the interface.
The settings
Add the two container names to the CosmosDb section of appsettings.json, and a new EmployeeDirectory section with two employees: you, with the manager as your manager, and the manager, with no manager. Use the object IDs from Step 3. The whole file now looks like this:
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning",
"Microsoft.Identity": "Warning",
"Dewiride.ServiceDesk.Audit": "Information"
}
},
"AllowedHosts": "*",
"AzureAd": {
"Instance": "https://login.microsoftonline.com/",
"TenantId": "11111111-1111-1111-1111-111111111111",
"ClientId": "22222222-2222-2222-2222-222222222222"
},
"Foundry": {
"ProjectEndpoint": "https://foundry-devblogs-exp.services.ai.azure.com/api/projects/proj-devblogs-exp",
"ModelDeployment": "gpt-5.6-luna"
},
"MicrosoftLearn": {
"McpEndpoint": "https://learn.microsoft.com/api/mcp?maxTokenBudget=2000",
"ProtocolVersion": "2025-06-18"
},
"CosmosDb": {
"AccountEndpoint": "https://cosmos-maf-servicedesk-4224.documents.azure.com:443/",
"DatabaseName": "servicedesk",
"SessionsContainerName": "sessions",
"MemoriesContainerName": "memories",
"ApprovalsContainerName": "approvals",
"CheckpointsContainerName": "checkpoints"
},
"EmployeeDirectory": {
"Employees": [
{
"Id": "00000000-0000-0000-0000-000000000000",
"DisplayName": "Azure User",
"ManagerId": "44444444-4444-4444-4444-444444444444"
},
{
"Id": "44444444-4444-4444-4444-444444444444",
"DisplayName": "Test Manager"
}
]
}
}
Your object ID goes in the first Id, and the manager's object ID in both the first ManagerId and the second Id. The DisplayName values are the names the requests show: put your own name in place of Azure User.
Step 7: Describe a Software Request
A request travels through several pieces of code, and each one needs a type for it. They all go in a new Approvals folder of the Agent project.
The status of a request is one of three values:
using System.Text.Json.Serialization;
namespace Dewiride.ServiceDesk.Agent.Approvals;
/// <summary>Where a request for approval stands. Stored and sent as its name, such as "Pending".</summary>
[JsonConverter(typeof(JsonStringEnumConverter<ApprovalStatus>))]
public enum ApprovalStatus
{
Pending,
Approved,
Rejected,
}
[JsonConverter(typeof(JsonStringEnumConverter<ApprovalStatus>))] writes the status as its name everywhere it turns into JSON: in Cosmos DB, in the tool results the model reads and in the API's answers. "Pending" means something to a person reading the item and to the model; 0 doesn't.
What the employee and the manager see about a request:
namespace Dewiride.ServiceDesk.Agent.Approvals;
/// <summary>
/// An employee's request for an app, and the manager's answer: what the employee sees about their requests,
/// and what the manager sees about the requests waiting for them.
/// </summary>
public sealed record SoftwareApproval(
string Number,
string Software,
string RequestedBy,
string Approver,
string Reason,
ApprovalStatus Status,
DateTimeOffset RequestedAt,
DateTimeOffset? DecidedAt = null,
string? Comment = null);
What the request_software tool returns, the request or the problem:
namespace Dewiride.ServiceDesk.Agent.Approvals;
/// <summary>
/// What asking for an app returns: the request sent to the manager, or, when it wasn't sent,
/// the problem to fix, in words the AI model can act on.
/// </summary>
public sealed record SoftwareRequestResult(bool Sent, SoftwareApproval? Request = null, string? Problem = null);
What a manager's answer can lead to:
namespace Dewiride.ServiceDesk.Agent.Approvals;
/// <summary>What happened to a manager's answer.</summary>
public enum ApprovalAnswerOutcome
{
/// <summary>The answer was recorded and carried out.</summary>
Answered,
/// <summary>No request with that number is waiting for this manager.</summary>
NotFound,
/// <summary>The request was already answered.</summary>
AlreadyAnswered,
/// <summary>The answer can't be accepted as it is, such as a comment that's too long.</summary>
Invalid,
}
/// <summary>What answering a request returns: the outcome, the request as it is now, and the problem when there is one.</summary>
public sealed record ApprovalAnswerResult(
ApprovalAnswerOutcome Outcome, SoftwareApproval? Approval = null, string? Problem = null);
The store needs two more types. A new request carries the checkpoint where its workflow run waits, and a stored request carries that checkpoint back, plus the ETag of the item: a version stamp that Cosmos DB changes every time the item changes. Step 8 explains what the ETag is for.
using Dewiride.ServiceDesk.Agent.Systems;
using Microsoft.Agents.AI.Workflows;
namespace Dewiride.ServiceDesk.Agent.Approvals;
/// <summary>
/// A new request for approval: who asks, who approves, for which app and why, and the checkpoint where its
/// workflow run waits for the answer.
/// </summary>
public sealed record NewSoftwareApproval(
Employee Requester,
Employee Approver,
SoftwareTitle Software,
string Reason,
CheckpointInfo Checkpoint);
using Microsoft.Agents.AI.Workflows;
namespace Dewiride.ServiceDesk.Agent.Approvals;
/// <summary>
/// A request for approval as the store keeps it: the request, the checkpoint where its workflow run waits for
/// the answer, and the version of the item the store read, so an answer only changes the version it was given (the ETag).
/// </summary>
public sealed record StoredApproval(SoftwareApproval Approval, CheckpointInfo Checkpoint, string ETag);
CheckpointInfo is Agent Framework's own type for a checkpoint's address: the run's session ID and the checkpoint's ID.
Last, the store itself, as an interface:
namespace Dewiride.ServiceDesk.Agent.Approvals;
/// <summary>
/// Where requests for approval are kept: one record per request, found by the manager who approves it.
/// </summary>
public interface IApprovalStore
{
/// <summary>Saves a new request, waiting for the manager's answer, and returns it with the number the store gave it.</summary>
Task<StoredApproval> CreateAsync(NewSoftwareApproval approval, CancellationToken cancellationToken);
/// <summary>Finds one request sent to a manager, or returns null when that manager has no request with that number.</summary>
Task<StoredApproval?> FindAsync(string approverId, string number, CancellationToken cancellationToken);
/// <summary>Gets the requests waiting for a manager's answer, oldest first.</summary>
Task<IReadOnlyList<SoftwareApproval>> GetPendingAsync(string approverId, CancellationToken cancellationToken);
/// <summary>Gets the requests one employee sent to their manager, newest first.</summary>
Task<IReadOnlyList<SoftwareApproval>> GetRequestsAsync(string approverId, string requesterId, CancellationToken cancellationToken);
/// <summary>
/// Records the manager's answer, but only if the request hasn't changed since it was read: returns the answered
/// request, or null when someone answered it first.
/// </summary>
Task<StoredApproval?> TryDecideAsync(string approverId, StoredApproval approval, bool approved, string? comment,
CancellationToken cancellationToken);
/// <summary>Puts an answered request back to waiting, when the answer couldn't be carried out.</summary>
Task ReopenAsync(string approverId, StoredApproval decided, CancellationToken cancellationToken);
}
Every method takes the manager's ID, the partition the request lives in. TryDecideAsync returns null instead of throwing when someone answered first, because that isn't an error: it's an answer the API has to give.
Step 8: Keep the Requests in Cosmos DB
CosmosApprovalStore keeps one item per request in the approvals container. Here it is piece by piece, then the whole file.
The item
private sealed record ApprovalDocument(
[property: JsonPropertyName("id")] string Id,
[property: JsonPropertyName("approverId")] string ApproverId,
[property: JsonPropertyName("requesterId")] string RequesterId,
[property: JsonPropertyName("requesterName")] string RequesterName,
[property: JsonPropertyName("approverName")] string ApproverName,
[property: JsonPropertyName("software")] string Software,
[property: JsonPropertyName("reason")] string Reason,
[property: JsonPropertyName("status")] ApprovalStatus Status,
[property: JsonPropertyName("requestedAt")] DateTimeOffset RequestedAt,
[property: JsonPropertyName("decidedAt")] DateTimeOffset? DecidedAt,
[property: JsonPropertyName("comment")] string? Comment,
[property: JsonPropertyName("sessionId")] string SessionId,
[property: JsonPropertyName("checkpointId")] string CheckpointId);
The request number is the item's id, and the manager's ID is the partition key, approverId. The last two properties are the address of the checkpoint where the request's workflow run waits.
The IDs of the employee and the manager don't go into the item as they are:
// Object IDs never go into the items: SHA-256 hashes of them do, and the same ID always gives the same hash.
private static string EmployeeKey(string employeeId) =>
Convert.ToHexStringLower(SHA256.HashData(Encoding.UTF8.GetBytes(employeeId)));
It's the same rule as the memories in Part 16: the store can still find everything that belongs to one person, because the same ID always gives the same hash, but the items don't carry the object IDs themselves.
A new request
for (int attempt = 1; ; attempt++)
{
ApprovalDocument document = new(
NewNumber(), approverKey, EmployeeKey(approval.Requester.Id),
approval.Requester.DisplayName, approval.Approver.DisplayName,
approval.Software.Name, approval.Reason, ApprovalStatus.Pending,
RequestedAt: timeProvider.GetUtcNow(), DecidedAt: null, Comment: null,
approval.Checkpoint.SessionId, approval.Checkpoint.CheckpointId);
try
{
ItemResponse<ApprovalDocument> response = await container.CreateItemAsync(
document, new PartitionKey(approverKey), cancellationToken: cancellationToken);
return ToStored(response.Resource, response.ETag);
}
catch (CosmosException exception) when (exception.StatusCode == HttpStatusCode.Conflict && attempt < 3)
{
}
}
NewNumber() makes a number like APR-3F9A01BC from four random bytes. Two requests of the same manager could, very rarely, get the same number. CreateItemAsync never overwrites an item: it fails with 409 Conflict when the ID is taken, and the loop tries a new number, up to three times. How to Create an Item Only If Its ID Is New in Azure Cosmos DB with C# shows that behavior on its own.
Finding requests
A manager's answer names a request by its number, and the store reads it with a point read, in the manager's own partition:
ItemResponse<ApprovalDocument> response = await container.ReadItemAsync<ApprovalDocument>(
number, new PartitionKey(EmployeeKey(approverId)), cancellationToken: cancellationToken);
A request sent to another manager is in another partition, so it's never found: for this manager, it doesn't exist. The two lists, a manager's waiting requests and an employee's own requests, are queries that also stay in one partition, through QueryRequestOptions.PartitionKey. How to Query the Items of One Partition in Azure Cosmos DB with C# explains that option.
Recording an answer, only once
Two answers can arrive at the same moment, from two browser tabs or two managers' assistants. Both read the request as Pending. If both then simply wrote their answer, the request would end up with whichever wrote last, after both had been carried out. Cosmos DB has an answer for this, the ETag. Microsoft's page on transactions and optimistic concurrency describes it: the _etag value is automatically generated and updated by the server every time the item is updated, and if the value of the if-match request header is no longer current, the server rejects the operation with an "HTTP 412 Precondition failure" response message.
So the store sends the ETag it read with the change:
ItemResponse<ApprovalDocument> response = await container.PatchItemAsync<ApprovalDocument>(
approval.Approval.Number, new PartitionKey(EmployeeKey(approverId)),
[
PatchOperation.Set("/status", approved ? ApprovalStatus.Approved : ApprovalStatus.Rejected),
PatchOperation.Set("/decidedAt", timeProvider.GetUtcNow()),
PatchOperation.Set("/comment", comment),
],
new PatchItemRequestOptions { IfMatchEtag = approval.ETag },
cancellationToken);
PatchItemAsyncchanges only the three properties of the answer, without sending the whole item back. How to Change Only Some Properties of an Azure Cosmos DB Item with PatchItemAsync in C# shows it with a small example.IfMatchEtag = approval.ETagmakes the change conditional: Cosmos DB applies it only if the item still has the ETag the store read. The first answer changes the item, and with it the ETag. The second answer still sends the old ETag, gets412 Precondition Failed, and the store returnsnull: someone answered first. How to Update an Azure Cosmos DB Item Only If It Hasn't Changed with an ETag in C# shows two saves of the same item, first without the ETag and then with it.
ReopenAsync is the same kind of patch, back to Pending, for an answer that couldn't be carried out. Step 11 explains when that happens.
The whole file
using System.Net;
using System.Security.Cryptography;
using System.Text;
using System.Text.Json.Serialization;
using Microsoft.Agents.AI.Workflows;
using Microsoft.Azure.Cosmos;
namespace Dewiride.ServiceDesk.Agent.Approvals;
/// <summary>
/// Keeps requests for approval in an Azure Cosmos DB container whose partition key path is /approverId:
/// one item per request, and all the requests sent to one manager in one partition. A manager's list,
/// and every answer, stays inside their own partition.
/// </summary>
public sealed class CosmosApprovalStore(Container container, TimeProvider timeProvider) : IApprovalStore
{
public async Task<StoredApproval> CreateAsync(NewSoftwareApproval approval, CancellationToken cancellationToken)
{
string approverKey = EmployeeKey(approval.Approver.Id);
// A short random number is enough among one manager's requests. If it's already taken (409 Conflict),
// try another one.
for (int attempt = 1; ; attempt++)
{
ApprovalDocument document = new(
NewNumber(), approverKey, EmployeeKey(approval.Requester.Id),
approval.Requester.DisplayName, approval.Approver.DisplayName,
approval.Software.Name, approval.Reason, ApprovalStatus.Pending,
RequestedAt: timeProvider.GetUtcNow(), DecidedAt: null, Comment: null,
approval.Checkpoint.SessionId, approval.Checkpoint.CheckpointId);
try
{
ItemResponse<ApprovalDocument> response = await container.CreateItemAsync(
document, new PartitionKey(approverKey), cancellationToken: cancellationToken);
return ToStored(response.Resource, response.ETag);
}
catch (CosmosException exception) when (exception.StatusCode == HttpStatusCode.Conflict && attempt < 3)
{
}
}
}
public async Task<StoredApproval?> FindAsync(string approverId, string number, CancellationToken cancellationToken)
{
try
{
// A point read in the manager's own partition: a request sent to another manager is never found.
ItemResponse<ApprovalDocument> response = await container.ReadItemAsync<ApprovalDocument>(
number, new PartitionKey(EmployeeKey(approverId)), cancellationToken: cancellationToken);
return ToStored(response.Resource, response.ETag);
}
catch (CosmosException exception) when (exception.StatusCode == HttpStatusCode.NotFound)
{
return null;
}
}
public Task<IReadOnlyList<SoftwareApproval>> GetPendingAsync(string approverId, CancellationToken cancellationToken) =>
QueryAsync(approverId,
new QueryDefinition("SELECT * FROM c WHERE c.status = @status ORDER BY c.requestedAt")
.WithParameter("@status", ApprovalStatus.Pending),
cancellationToken);
public Task<IReadOnlyList<SoftwareApproval>> GetRequestsAsync(
string approverId, string requesterId, CancellationToken cancellationToken) =>
QueryAsync(approverId,
new QueryDefinition("SELECT * FROM c WHERE c.requesterId = @requesterId ORDER BY c.requestedAt DESC")
.WithParameter("@requesterId", EmployeeKey(requesterId)),
cancellationToken);
public async Task<StoredApproval?> TryDecideAsync(
string approverId, StoredApproval approval, bool approved, string? comment, CancellationToken cancellationToken)
{
try
{
// Change only the answer's fields, and only if the item is still the version that was read:
// IfMatchEtag sends its ETag, and Cosmos DB refuses the change if the item has changed since.
ItemResponse<ApprovalDocument> response = await container.PatchItemAsync<ApprovalDocument>(
approval.Approval.Number, new PartitionKey(EmployeeKey(approverId)),
[
PatchOperation.Set("/status", approved ? ApprovalStatus.Approved : ApprovalStatus.Rejected),
PatchOperation.Set("/decidedAt", timeProvider.GetUtcNow()),
PatchOperation.Set("/comment", comment),
],
new PatchItemRequestOptions { IfMatchEtag = approval.ETag },
cancellationToken);
return ToStored(response.Resource, response.ETag);
}
catch (CosmosException exception) when (exception.StatusCode == HttpStatusCode.PreconditionFailed)
{
// 412 Precondition Failed: the item changed after it was read, so someone answered first.
return null;
}
}
public async Task ReopenAsync(string approverId, StoredApproval decided, CancellationToken cancellationToken) =>
await container.PatchItemAsync<ApprovalDocument>(
decided.Approval.Number, new PartitionKey(EmployeeKey(approverId)),
[
PatchOperation.Set("/status", ApprovalStatus.Pending),
PatchOperation.Set<DateTimeOffset?>("/decidedAt", null),
PatchOperation.Set<string?>("/comment", null),
],
new PatchItemRequestOptions { IfMatchEtag = decided.ETag },
cancellationToken);
// Reads the manager's partition only. Without the partition key, the query would look through every partition.
private async Task<IReadOnlyList<SoftwareApproval>> QueryAsync(
string approverId, QueryDefinition query, CancellationToken cancellationToken)
{
using FeedIterator<ApprovalDocument> feed = container.GetItemQueryIterator<ApprovalDocument>(
query, requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey(EmployeeKey(approverId)) });
List<SoftwareApproval> approvals = [];
while (feed.HasMoreResults)
{
foreach (ApprovalDocument document in await feed.ReadNextAsync(cancellationToken))
{
approvals.Add(ToApproval(document));
}
}
return approvals;
}
// Object IDs never go into the items: SHA-256 hashes of them do, and the same ID always gives the same hash.
private static string EmployeeKey(string employeeId) =>
Convert.ToHexStringLower(SHA256.HashData(Encoding.UTF8.GetBytes(employeeId)));
// APR- and eight random hexadecimal characters, such as APR-3F9A01BC.
private static string NewNumber() => $"APR-{Convert.ToHexString(RandomNumberGenerator.GetBytes(4))}";
private static StoredApproval ToStored(ApprovalDocument document, string etag) =>
new(ToApproval(document), new CheckpointInfo(document.SessionId, document.CheckpointId), etag);
private static SoftwareApproval ToApproval(ApprovalDocument document) =>
new(document.Id, document.Software, document.RequesterName, document.ApproverName, document.Reason,
document.Status, document.RequestedAt, document.DecidedAt, document.Comment);
private sealed record ApprovalDocument(
[property: JsonPropertyName("id")] string Id,
[property: JsonPropertyName("approverId")] string ApproverId,
[property: JsonPropertyName("requesterId")] string RequesterId,
[property: JsonPropertyName("requesterName")] string RequesterName,
[property: JsonPropertyName("approverName")] string ApproverName,
[property: JsonPropertyName("software")] string Software,
[property: JsonPropertyName("reason")] string Reason,
[property: JsonPropertyName("status")] ApprovalStatus Status,
[property: JsonPropertyName("requestedAt")] DateTimeOffset RequestedAt,
[property: JsonPropertyName("decidedAt")] DateTimeOffset? DecidedAt,
[property: JsonPropertyName("comment")] string? Comment,
[property: JsonPropertyName("sessionId")] string SessionId,
[property: JsonPropertyName("checkpointId")] string CheckpointId);
}
Step 9: Build the Approval Workflow
The workflow has three parts: two executors written as classes, as in Part 19, and the request port between them. How to Write a Class-Based Workflow Executor in Microsoft Agent Framework in C# shows the executor pattern on its own.
The messages
namespace Dewiride.ServiceDesk.Agent.Approvals;
// The messages of the software approval workflow. Every checkpoint saves the ones still on their way,
// so each of them must turn into JSON and back: they're listed in ApprovalJsonContext.
/// <summary>What starts the workflow: one employee's request for an app, which their manager has to approve.</summary>
internal sealed record SoftwareRequest(string RequesterId, string RequestedBy, string SoftwareId, string Software, string Reason);
/// <summary>What the workflow asks the manager, through the ManagerApproval request port.</summary>
internal sealed record ApprovalRequest(string RequestedBy, string Software, string Reason);
/// <summary>The manager's answer to one request, by its number, which comes back through the same port.</summary>
internal sealed record ApprovalDecision(string ApprovalNumber, bool Approved, string? Comment);
/// <summary>The workflow's output: what was done with the manager's answer.</summary>
internal sealed record ApprovalOutcome(string ApprovalNumber, bool Approved);
SoftwareRequeststarts a run. It carries the employee's object ID, which the licence needs, their name, and the app's ID and name.ApprovalRequestis the question to the manager: who asks, for what and why. It carries no IDs, because the manager doesn't need them.ApprovalDecisionis the manager's answer, with the request's number. The run doesn't know the number on its own: Step 11 explains why the run starts before the request gets one.ApprovalOutcomeis what the workflow returns once it has carried out the answer.
They're internal: nothing outside the Agent project ever sees the workflow's messages.
SubmitRequest: keep the request and ask
using Microsoft.Agents.AI.Workflows;
namespace Dewiride.ServiceDesk.Agent.Approvals;
/// <summary>
/// Step 1: keeps the employee's request in the workflow's state, where every checkpoint saves it, and asks the
/// manager. The question goes to the ManagerApproval request port, and the workflow waits there for the answer.
/// </summary>
internal sealed partial class SubmitRequestExecutor() : Executor("SubmitRequest", declareCrossRunShareable: true)
{
[MessageHandler]
private async ValueTask<ApprovalRequest> HandleAsync(
SoftwareRequest request, IWorkflowContext context, CancellationToken cancellationToken)
{
// A shared scope: other steps of the same run can read it. Each run has its own state.
await context.QueueStateUpdateAsync(
SoftwareApprovalWorkflow.RequestStateKey, request, SoftwareApprovalWorkflow.StateScope, cancellationToken);
return new ApprovalRequest(request.RequestedBy, request.Software, request.Reason);
}
}
The answer may come days later, so the executor that carries it out, ApplyDecision, can't take the request from a variable. It reads it from the workflow's state, which every checkpoint saves. Microsoft's page on workflow state explains the scope: when scopeName is set, the value is written to a shared scope that any executor can read when using the same scope name. Without a scope, the value would be private to SubmitRequest. A value written with QueueStateUpdateAsync reaches the other executors at the next superstep, which is the earliest any of them could run anyway.
The handler returns an ApprovalRequest, and an edge you add below carries it to the request port. How to Share Data Between the Steps of a Microsoft Agent Framework Workflow in C# shows state with a small example.
ApplyDecision: carry out the answer
using Dewiride.ServiceDesk.Agent.Auditing;
using Dewiride.ServiceDesk.Agent.Systems;
using Microsoft.Agents.AI.Workflows;
namespace Dewiride.ServiceDesk.Agent.Approvals;
/// <summary>
/// Step 2, when the manager answers: assigns the app's licence to the employee if the manager approved,
/// records the answer in the audit trail and returns the outcome: the workflow's output.
/// </summary>
internal sealed partial class ApplyDecisionExecutor(ISoftwareCatalog softwareCatalog, ServiceDeskAudit audit)
: Executor("ApplyDecision", declareCrossRunShareable: true)
{
[MessageHandler]
private async ValueTask<ApprovalOutcome> HandleAsync(
ApprovalDecision decision, IWorkflowContext context, CancellationToken cancellationToken)
{
// The request that SubmitRequest saved, maybe days ago and in another process: it comes from the checkpoint.
SoftwareRequest request = await context.ReadStateAsync<SoftwareRequest>(
SoftwareApprovalWorkflow.RequestStateKey, SoftwareApprovalWorkflow.StateScope, cancellationToken)
?? throw new InvalidOperationException("The workflow's state has no software request.");
if (!decision.Approved)
{
audit.SoftwareRequestRejected(decision.ApprovalNumber, request.Software);
return new ApprovalOutcome(decision.ApprovalNumber, Approved: false);
}
await softwareCatalog.AssignLicenceAsync(request.RequesterId, request.SoftwareId, cancellationToken);
audit.SoftwareRequestApproved(decision.ApprovalNumber, request.Software);
return new ApprovalOutcome(decision.ApprovalNumber, Approved: true);
}
}
ReadStateAsync<SoftwareRequest>reads the request back, with the same key and scope. By the time this runs, the run may have been restored from a checkpoint in another process: the request came back with it.- A rejected request only gets its audit entry.
- An approved request gets the app's licence, then its audit entry.
- The return value goes out as the workflow's output, which tells the code that runs the workflow that the answer was carried out.
The audit entries
ApplyDecision writes two of three new audit entries; the third is for the request itself. Add them to ServiceDeskAudit, the audit trail from Part 18. The public methods:
public void SoftwareRequested(string approvalNumber, string software) =>
LogSoftwareRequested(EmployeeId, software, approvalNumber);
// The manager's answer comes from the manager's own sign-in, so EmployeeId is the manager here.
public void SoftwareRequestApproved(string approvalNumber, string software) =>
LogSoftwareRequestApproved(EmployeeId, approvalNumber, software);
public void SoftwareRequestRejected(string approvalNumber, string software) =>
LogSoftwareRequestRejected(EmployeeId, approvalNumber, software);
And their log messages, with the next event IDs, 11 to 13:
[LoggerMessage(EventId = 11, EventName = "SoftwareRequested", Level = LogLevel.Information,
Message = "Employee {EmployeeId} asked for {Software} in request {ApprovalNumber}. It waits for their manager's answer.")]
private partial void LogSoftwareRequested(string employeeId, string software, string approvalNumber);
[LoggerMessage(EventId = 12, EventName = "SoftwareRequestApproved", Level = LogLevel.Information,
Message = "Employee {EmployeeId} approved request {ApprovalNumber}, and the {Software} licence was assigned to the employee who asked for it.")]
private partial void LogSoftwareRequestApproved(string employeeId, string approvalNumber, string software);
[LoggerMessage(EventId = 13, EventName = "SoftwareRequestRejected", Level = LogLevel.Information,
Message = "Employee {EmployeeId} rejected request {ApprovalNumber} for {Software}.")]
private partial void LogSoftwareRequestRejected(string employeeId, string approvalNumber, string software);
EmployeeId is always the signed-in person, so the entries record who did what: the employee asked, the manager approved or rejected. The whole file, with the class summary updated:
using Dewiride.ServiceDesk.Agent.Memory;
using Dewiride.ServiceDesk.Agent.Systems;
using Microsoft.Agents.AI;
using Microsoft.Extensions.AI;
using Microsoft.Extensions.Logging;
namespace Dewiride.ServiceDesk.Agent.Auditing;
/// <summary>
/// The audit trail: one log entry for every change the agent makes for an employee, every answer an employee
/// gives to an approval request, every secret the guard removes, every ticket triage assigns, and every software
/// request and its manager's answer. Each entry says who (the signed-in employee's object ID, never a name or
/// an email address), what happened and the outcome. The log itself records when, and which trace the entry
/// belongs to. Every entry goes to its own category, so the audit trail can be kept, searched and protected
/// apart from the other logs.
/// </summary>
public sealed partial class ServiceDeskAudit(ILoggerFactory loggerFactory, ICurrentEmployee currentEmployee)
{
/// <summary>The category every audit entry is logged under.</summary>
public const string CategoryName = "Dewiride.ServiceDesk.Audit";
private readonly ILogger logger = loggerFactory.CreateLogger(CategoryName);
// Who did it always comes from the sign-in, never from the AI model.
private string EmployeeId => currentEmployee.Id ?? "(no one signed in)";
public void TicketRaised(Ticket ticket, TicketType type) => LogTicketRaised(EmployeeId, ticket.Number, type);
public void PasswordResetSent(PasswordReset reset) => LogPasswordResetSent(EmployeeId, reset.SentTo, reset.LinkExpiresAt);
public void MemorySaved(MemoryItem memory) => LogMemorySaved(EmployeeId, memory.Id);
public void MemoryForgotten(string memoryId) => LogMemoryForgotten(EmployeeId, memoryId);
public void SecretsRemoved(int count, string source) => LogSecretsRemoved(EmployeeId, count, source);
public void TicketTriaged(Ticket ticket) =>
LogTicketTriaged(EmployeeId, ticket.Number, ticket.Category, ticket.Priority, ticket.AssignedTo);
public void MajorIncidentDeclared(string ticketNumber) => LogMajorIncidentDeclared(EmployeeId, ticketNumber);
public void SecurityIncidentReported(string ticketNumber) => LogSecurityIncidentReported(EmployeeId, ticketNumber);
public void SoftwareRequested(string approvalNumber, string software) =>
LogSoftwareRequested(EmployeeId, software, approvalNumber);
// The manager's answer comes from the manager's own sign-in, so EmployeeId is the manager here.
public void SoftwareRequestApproved(string approvalNumber, string software) =>
LogSoftwareRequestApproved(EmployeeId, approvalNumber, software);
public void SoftwareRequestRejected(string approvalNumber, string software) =>
LogSoftwareRequestRejected(EmployeeId, approvalNumber, software);
/// <summary>
/// Agent run middleware: before a run starts, records the employee's answer to every approval
/// request the run carries, approved or rejected.
/// </summary>
public Task RecordApprovalAnswersAsync(
IEnumerable<ChatMessage> messages,
AgentSession? session,
AgentRunOptions? options,
Func<IEnumerable<ChatMessage>, AgentSession?, AgentRunOptions?, CancellationToken, Task> next,
CancellationToken cancellationToken)
{
foreach (ToolApprovalResponseContent answer in messages
.SelectMany(message => message.Contents)
.OfType<ToolApprovalResponseContent>())
{
string toolName = answer.ToolCall is FunctionCallContent call ? call.Name : "(unknown tool)";
if (answer.Approved)
{
LogToolCallApproved(EmployeeId, toolName, answer.ToolCall.CallId);
}
else
{
LogToolCallRejected(EmployeeId, toolName, answer.ToolCall.CallId);
}
}
return next(messages, session, options, cancellationToken);
}
[LoggerMessage(EventId = 1, EventName = "TicketRaised", Level = LogLevel.Information,
Message = "Raised ticket {TicketNumber} ({TicketType}) for employee {EmployeeId}.")]
private partial void LogTicketRaised(string employeeId, string ticketNumber, TicketType ticketType);
[LoggerMessage(EventId = 2, EventName = "ToolCallApproved", Level = LogLevel.Information,
Message = "Employee {EmployeeId} approved {ToolName} ({ToolCallId}).")]
private partial void LogToolCallApproved(string employeeId, string toolName, string toolCallId);
[LoggerMessage(EventId = 3, EventName = "ToolCallRejected", Level = LogLevel.Information,
Message = "Employee {EmployeeId} rejected {ToolName} ({ToolCallId}).")]
private partial void LogToolCallRejected(string employeeId, string toolName, string toolCallId);
[LoggerMessage(EventId = 4, EventName = "PasswordResetSent", Level = LogLevel.Information,
Message = "Sent a password reset link for employee {EmployeeId} to {SentTo}. It expires at {ExpiresAt:O}.")]
private partial void LogPasswordResetSent(string employeeId, string sentTo, DateTimeOffset expiresAt);
[LoggerMessage(EventId = 5, EventName = "MemorySaved", Level = LogLevel.Information,
Message = "Saved memory {MemoryId} about employee {EmployeeId}.")]
private partial void LogMemorySaved(string employeeId, string memoryId);
[LoggerMessage(EventId = 6, EventName = "MemoryForgotten", Level = LogLevel.Information,
Message = "Forgot memory {MemoryId} about employee {EmployeeId}.")]
private partial void LogMemoryForgotten(string employeeId, string memoryId);
[LoggerMessage(EventId = 7, EventName = "SecretsRemoved", Level = LogLevel.Warning,
Message = "Removed {Count} secret(s) from {Source} before the AI model saw it, for employee {EmployeeId}.")]
private partial void LogSecretsRemoved(string employeeId, int count, string source);
[LoggerMessage(EventId = 8, EventName = "TicketTriaged", Level = LogLevel.Information,
Message = "Triaged ticket {TicketNumber} for employee {EmployeeId}: {Category}, priority {Priority}, assigned to {Team}.")]
private partial void LogTicketTriaged(string employeeId, string ticketNumber, TicketCategory? category, TicketPriority? priority, string team);
[LoggerMessage(EventId = 9, EventName = "MajorIncidentDeclared", Level = LogLevel.Warning,
Message = "Declared ticket {TicketNumber} a major incident. It was raised by employee {EmployeeId}.")]
private partial void LogMajorIncidentDeclared(string employeeId, string ticketNumber);
[LoggerMessage(EventId = 10, EventName = "SecurityIncidentReported", Level = LogLevel.Warning,
Message = "Sent ticket {TicketNumber} to the security team. It was raised by employee {EmployeeId}.")]
private partial void LogSecurityIncidentReported(string employeeId, string ticketNumber);
[LoggerMessage(EventId = 11, EventName = "SoftwareRequested", Level = LogLevel.Information,
Message = "Employee {EmployeeId} asked for {Software} in request {ApprovalNumber}. It waits for their manager's answer.")]
private partial void LogSoftwareRequested(string employeeId, string software, string approvalNumber);
[LoggerMessage(EventId = 12, EventName = "SoftwareRequestApproved", Level = LogLevel.Information,
Message = "Employee {EmployeeId} approved request {ApprovalNumber}, and the {Software} licence was assigned to the employee who asked for it.")]
private partial void LogSoftwareRequestApproved(string employeeId, string approvalNumber, string software);
[LoggerMessage(EventId = 13, EventName = "SoftwareRequestRejected", Level = LogLevel.Information,
Message = "Employee {EmployeeId} rejected request {ApprovalNumber} for {Software}.")]
private partial void LogSoftwareRequestRejected(string employeeId, string approvalNumber, string software);
}
The workflow
using Dewiride.ServiceDesk.Agent.Auditing;
using Dewiride.ServiceDesk.Agent.Systems;
using Microsoft.Agents.AI.Workflows;
namespace Dewiride.ServiceDesk.Agent.Approvals;
/// <summary>
/// The software approval workflow: it saves the employee's request, asks their manager through a request port,
/// waits as long as the manager takes, and then carries out the answer.
/// </summary>
internal static class SoftwareApprovalWorkflow
{
/// <summary>The ID of the request port that asks the manager. It's part of every checkpoint: never change it.</summary>
public const string ManagerApprovalPortId = "ManagerApproval";
/// <summary>The shared state scope that keeps the request for the steps after the port.</summary>
public const string StateScope = "software-request";
/// <summary>The key of the request in that scope.</summary>
public const string RequestStateKey = "request";
public static Workflow Build(ISoftwareCatalog softwareCatalog, ServiceDeskAudit audit)
{
SubmitRequestExecutor submit = new();
ApplyDecisionExecutor apply = new(softwareCatalog, audit);
// A request port: the workflow sends it an ApprovalRequest, and it waits for an ApprovalDecision from outside.
RequestPort managerApproval = RequestPort.Create<ApprovalRequest, ApprovalDecision>(ManagerApprovalPortId);
return new WorkflowBuilder(submit)
.WithName(SoftwareApprovals.WorkflowName)
.AddEdge(submit, managerApproval)
.AddEdge(managerApproval, apply)
.WithOutputFrom(apply)
.WithOpenTelemetry()
.Build();
}
}

RequestPort.Create<ApprovalRequest, ApprovalDecision>(ManagerApprovalPortId)makes the request port, with its two types: it takesApprovalRequestmessages and waits for anApprovalDecisionfrom outside the workflow. Like an executor, it has an ID.AddEdge(submit, managerApproval)carries the question fromSubmitRequestto the port, andAddEdge(managerApproval, apply)carries the answer from the port toApplyDecision.WithOutputFrom(apply)makesApplyDecision's return value the workflow's output.WithNameandWithOpenTelemetryname the workflow and trace its runs, as in Part 19.
The IDs, SubmitRequest, ManagerApproval and ApplyDecision, matter more here than in Part 19: every checkpoint records them, and a waiting run can only continue in a workflow with the same ones. Microsoft's guide to checkpoints says it: the workflow you resume must have the same structure and executor identities as the workflow that created the checkpoint. Rename a step while requests are waiting, and those requests can't continue. How to Pause a Microsoft Agent Framework Workflow Until a Person Answers in C# shows a request port with a small example.
Both executors keep nothing in their fields, so they're declared shareable across runs, and one workflow serves every request at once, as in Part 19. The request lives in each run's own state, never in an executor.
Step 10: Keep Checkpoints in Cosmos DB
A checkpoint has to outlive the process that saved it, and it has to be readable by every copy of the API, because the manager's answer can reach any of them. The Workflows package comes with checkpoints in memory, which die with the process, and in files, which stay on one machine. There is a Cosmos DB checkpoint store, CosmosCheckpointStore, but only in the Microsoft.Agents.AI.CosmosNoSql package, whose newest release is a preview, 1.28.0-preview.261106.1. Its code also saves each checkpoint's time in whole seconds and lists a run's checkpoints in that order, while a run saves its checkpoints a fraction of a second apart: 0.28 seconds for the request in Step 16. Two checkpoints saved in the same second get the same time, and then nothing decides which of them is listed last. So the API gets a store of its own, on the Microsoft.Azure.Cosmos package it already uses.
The store's contract
Agent Framework stores checkpoints through ICheckpointStore<T>. The API's store adds one method, to delete a finished run's checkpoints:
using System.Text.Json;
using Microsoft.Agents.AI.Workflows.Checkpointing;
namespace Dewiride.ServiceDesk.Agent.Approvals;
/// <summary>
/// Where workflow runs keep their checkpoints, as JSON, and how to delete the checkpoints of a run that's finished.
/// </summary>
public interface IWorkflowCheckpointStore : ICheckpointStore<JsonElement>
{
/// <summary>Deletes every checkpoint of one run: its session.</summary>
Task DeleteSessionAsync(string sessionId, CancellationToken cancellationToken);
}
JsonElement is the checkpoint's value: Agent Framework turns the whole state of the run into one JSON document, and the store only keeps it. The abstract class JsonCheckpointStore implements ICheckpointStore<JsonElement> and leaves three methods to write: save a checkpoint, read one, and list a run's checkpoints.
Save a checkpoint
CheckpointInfo checkpoint = new(sessionId, Guid.NewGuid().ToString("N"));
CheckpointDocument document = new(checkpoint.CheckpointId, sessionId, parent?.CheckpointId, CommittedAt(), value);
await container.CreateItemAsync(document, new PartitionKey(sessionId));
return checkpoint;
The store makes the checkpoint's ID, a new GUID, and returns its address. Each checkpoint also records its parent, the checkpoint before it in the same run, and when it was saved.
Read a checkpoint
ItemResponse<CheckpointDocument> response = await container.ReadItemAsync<CheckpointDocument>(
key.CheckpointId, new PartitionKey(sessionId));
return response.Resource.Value;
A point read by ID, in the run's partition. A checkpoint that doesn't exist throws KeyNotFoundException, the same exception Agent Framework's file store throws.
List a run's checkpoints, in order
QueryDefinition query = withParent is null
? new QueryDefinition("SELECT c.id FROM c ORDER BY c.committedAt")
: new QueryDefinition("SELECT c.id FROM c WHERE c.parentId = @parentId ORDER BY c.committedAt")
.WithParameter("@parentId", withParent.CheckpointId);
The order isn't a detail. The documentation of ICheckpointStore says: Implementations must return checkpoints in the order they were committed, with the most recently committed checkpoint last. And it says why: callers rely on it to identify the latest checkpoint for a session, so a store that returns checkpoints unordered (or newest-first) will cause the wrong checkpoint to be resumed.
When a checkpoint was saved
Every Cosmos DB item has a _ts, the time of its last change, but it counts whole seconds: both checkpoints of the Visio request in Step 15 have the same _ts. So the store writes its own time:
private string CommittedAt() =>
timeProvider.GetUtcNow().UtcDateTime.ToString("yyyy-MM-ddTHH:mm:ss.fffffffZ", CultureInfo.InvariantCulture);
The format is the one Microsoft recommends for dates in Cosmos DB: The recommended format for date and time strings is yyyy-MM-ddTHH:mm:ss.fffffffZ, which follows the ISO 8601 UTC standard. Every value has the same length, down to the ten-millionth of a second, so ORDER BY on the text sorts the times. How to Store Dates and Times That Sort Correctly in Azure Cosmos DB with C# shows why the format matters.
The whole file
using System.Globalization;
using System.Net;
using System.Text.Json;
using System.Text.Json.Serialization;
using Microsoft.Agents.AI.Workflows;
using Microsoft.Agents.AI.Workflows.Checkpointing;
using Microsoft.Azure.Cosmos;
namespace Dewiride.ServiceDesk.Agent.Approvals;
/// <summary>
/// Keeps workflow checkpoints in an Azure Cosmos DB container whose partition key path is /sessionId:
/// one item per checkpoint, and all the checkpoints of one run in one partition.
/// </summary>
public sealed class CosmosDbCheckpointStore(Container container, TimeProvider timeProvider)
: JsonCheckpointStore, IWorkflowCheckpointStore
{
public override async ValueTask<CheckpointInfo> CreateCheckpointAsync(
string sessionId, JsonElement value, CheckpointInfo? parent = null)
{
CheckpointInfo checkpoint = new(sessionId, Guid.NewGuid().ToString("N"));
CheckpointDocument document = new(checkpoint.CheckpointId, sessionId, parent?.CheckpointId, CommittedAt(), value);
await container.CreateItemAsync(document, new PartitionKey(sessionId));
return checkpoint;
}
public override async ValueTask<JsonElement> RetrieveCheckpointAsync(string sessionId, CheckpointInfo key)
{
try
{
ItemResponse<CheckpointDocument> response = await container.ReadItemAsync<CheckpointDocument>(
key.CheckpointId, new PartitionKey(sessionId));
return response.Resource.Value;
}
catch (CosmosException exception) when (exception.StatusCode == HttpStatusCode.NotFound)
{
throw new KeyNotFoundException($"Session {sessionId} has no checkpoint {key.CheckpointId}.", exception);
}
}
public override async ValueTask<IEnumerable<CheckpointInfo>> RetrieveIndexAsync(
string sessionId, CheckpointInfo? withParent = null)
{
// The list must be in the order the checkpoints were saved, oldest first: that's the store's contract, and
// CheckpointManager.GetLatestCheckpointAsync takes the last checkpoint of the list as the latest one.
QueryDefinition query = withParent is null
? new QueryDefinition("SELECT c.id FROM c ORDER BY c.committedAt")
: new QueryDefinition("SELECT c.id FROM c WHERE c.parentId = @parentId ORDER BY c.committedAt")
.WithParameter("@parentId", withParent.CheckpointId);
List<CheckpointInfo> checkpoints = [];
foreach (string id in await ReadIdsAsync(sessionId, query))
{
checkpoints.Add(new CheckpointInfo(sessionId, id));
}
return checkpoints;
}
public async Task DeleteSessionAsync(string sessionId, CancellationToken cancellationToken)
{
foreach (string id in await ReadIdsAsync(sessionId, new QueryDefinition("SELECT c.id FROM c"), cancellationToken))
{
try
{
await container.DeleteItemAsync<CheckpointDocument>(id, new PartitionKey(sessionId),
cancellationToken: cancellationToken);
}
catch (CosmosException exception) when (exception.StatusCode == HttpStatusCode.NotFound)
{
}
}
}
// Reads the run's own partition only.
private async Task<List<string>> ReadIdsAsync(
string sessionId, QueryDefinition query, CancellationToken cancellationToken = default)
{
using FeedIterator<IdOnly> feed = container.GetItemQueryIterator<IdOnly>(
query, requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey(sessionId) });
List<string> ids = [];
while (feed.HasMoreResults)
{
foreach (IdOnly item in await feed.ReadNextAsync(cancellationToken))
{
ids.Add(item.Id);
}
}
return ids;
}
// When the checkpoint was saved, in UTC, to the ten-millionth of a second, written the way Azure Cosmos DB
// recommends for dates: always the same length, so sorting the text sorts the times. The item's own _ts
// counts whole seconds, which can't tell apart the checkpoints of one run.
private string CommittedAt() =>
timeProvider.GetUtcNow().UtcDateTime.ToString("yyyy-MM-ddTHH:mm:ss.fffffffZ", CultureInfo.InvariantCulture);
private sealed record CheckpointDocument(
[property: JsonPropertyName("id")] string Id,
[property: JsonPropertyName("sessionId")] string SessionId,
[property: JsonPropertyName("parentId")] string? ParentId,
[property: JsonPropertyName("committedAt")] string CommittedAt,
[property: JsonPropertyName("value")] JsonElement Value);
private sealed record IdOnly([property: JsonPropertyName("id")] string Id);
}
DeleteSessionAsync lists the run's checkpoint IDs and deletes each one. A checkpoint that's already gone counts as deleted. How to Write a Custom Checkpoint Store for Microsoft Agent Framework Workflows in C# builds a smaller store with a small example.
Your own types in a checkpoint
A checkpoint turns everything in the run into JSON: the request in the state, the question waiting at the port and any message on its way. Agent Framework brings the JSON settings for its own types. CheckpointManager.CreateJson takes serializer options for the app's types; its documentation says they Must be provided if using custom types in messages or state. A source-generated serializer context provides them:
using System.Text.Json.Serialization;
namespace Dewiride.ServiceDesk.Agent.Approvals;
/// <summary>
/// How the workflow's own types turn into JSON and back, for its checkpoints. The checkpoint manager knows
/// only the workflow framework's types; these are the ones it needs from this app. The source generator
/// writes the code when you build, so nothing has to inspect the types while the app runs.
/// </summary>
[JsonSerializable(typeof(SoftwareRequest))]
[JsonSerializable(typeof(ApprovalRequest))]
[JsonSerializable(typeof(ApprovalDecision))]
[JsonSerializable(typeof(ApprovalOutcome))]
internal sealed partial class ApprovalJsonContext : JsonSerializerContext;
[JsonSerializable] names each type, and the source generator writes the code that turns them into JSON and back when you build. In an app like this one, where .NET's reflection-based serialization is on, as it is by default, a checkpoint still saves a type you leave out, so a missing line goes unnoticed. In a trimmed or native AOT app, where it's off, the same run fails at its first checkpoint with No JSON type info is available for type …. How to Save Your Own Types in Microsoft Agent Framework Workflow Checkpoints in C# shows both with a small example.
Step 11: Start a Run for Every Request and Continue It When the Manager Answers
The workflow and both stores are ready. One class puts them together: SoftwareApprovals. The agent's tools call it to send a request and to list the employee's requests, and the manager's endpoints call it to list and answer them. Create src/Dewiride.ServiceDesk.Agent/Approvals/SoftwareApprovals.cs. This step goes through it piece by piece, and the whole file is at the end.
Runs that save checkpoints
// Turns checkpoints into JSON and back. It knows the workflow framework's types; ApprovalJsonContext adds this app's.
private readonly CheckpointManager _checkpointManager =
CheckpointManager.CreateJson(checkpointStore, ApprovalJsonContext.Default.Options);
// Concurrent: one workflow serves every request at the same time. WithCheckpointing: each run saves
// a checkpoint at the end of every superstep, through the checkpoint manager.
private InProcessExecutionEnvironment Execution => InProcessExecution.Concurrent.WithCheckpointing(_checkpointManager);
CheckpointManager.CreateJsonmakes a checkpoint manager. It turns each checkpoint into JSON, with the options from Step 10 for this app's own types, and hands the JSON to the store.InProcessExecution.Concurrentruns workflows inside the API, as in Part 19, so one workflow serves every request at the same time.WithCheckpointingadds checkpoints to that: every run started or continued throughExecutionsaves one at the end of each superstep.
Send a request
RequestAsync starts with checks. The app and the reason come from the AI model, so a problem comes back as a sentence that tells the model what to do, as with create_ticket in Part 11, never as an exception. The reason can't be empty or longer than 500 characters. Then come the app and the manager:
IReadOnlyList<SoftwareTitle> titles = await softwareCatalog.GetTitlesAsync(cancellationToken);
if (FindTitle(titles, software) is not SoftwareTitle title)
{
return NotSent($"The software catalog has no single app called '{software}'. " +
$"The apps in it are: {string.Join(", ", titles.Select(t => t.Name))}.");
}
// Who approves comes from the company directory, never from the AI model.
if (await employeeDirectory.FindEmployeeAsync(employeeId, cancellationToken) is not Employee requester)
{
return NotSent("The company directory has no record of this employee, so the request can't go to a manager. Offer to raise a ticket instead.");
}
Employee? approver = requester.ManagerId is string managerId
? await employeeDirectory.FindEmployeeAsync(managerId, cancellationToken)
: null;
if (approver is null || approver.Id == requester.Id)
{
return NotSent("The company directory has no manager for this employee who can approve the request. Offer to raise a ticket instead.");
}
FindTitle, at the end of the file, takes an app's exact name, or a word that only one app's name contains, so Visio finds Microsoft Visio Plan 2. When nothing matches, the answer lists the catalog's apps, so the model can ask the employee which one they mean.- The approver comes from the directory. The employee's ID is the signed-in user's, and their manager is whoever the directory says. The model never names the approver, so it can't send a request to someone else.
- Nobody approves their own request, even if the directory says they're their own manager.
Then the run starts, and the request is saved:
// Each run gets an ID of its own: the session ID that its checkpoints are kept under.
string sessionId = Guid.NewGuid().ToString("N");
StoredApproval stored;
try
{
// 1. The run: it saves the request in its state, asks the manager and stops there, waiting.
CheckpointInfo waiting = await StartRunAsync(
new SoftwareRequest(requester.Id, requester.DisplayName, title.Id, title.Name, reason.Trim()),
sessionId, cancellationToken);
// 2. The request, saved where the manager's list finds it, with the checkpoint where its run waits.
// It's saved last, so a manager never sees a request that nothing is waiting to carry out.
stored = await approvalStore.CreateAsync(
new NewSoftwareApproval(requester, approver, title, reason.Trim(), waiting), cancellationToken);
}
catch
{
// The request never reached the manager: remove what the run saved, so nothing is left waiting.
await checkpointStore.DeleteSessionAsync(sessionId, CancellationToken.None);
throw;
}
audit.SoftwareRequested(stored.Approval.Number, title.Name);
return new SoftwareRequestResult(Sent: true, Request: stored.Approval);
- A session ID for each run. A run's checkpoints are kept under its session ID, the partition key of the
checkpointscontainer, so every request gets a new one. - The run comes first. It stops at the manager's question and returns the checkpoint where it waits.
- The request comes last, with that checkpoint in it. If anything fails on the way, the manager never sees a request, and
catchdeletes whatever checkpoints the run saved.CancellationToken.Nonelets that cleanup finish even when the employee's request was the thing that got cancelled. - The audit entry from Step 9 records the request.
StartRunAsync starts the run:
private async Task<CheckpointInfo> StartRunAsync(SoftwareRequest request, string sessionId, CancellationToken cancellationToken)
{
await using Run run = await Execution.RunAsync(workflow, request, sessionId, cancellationToken);
// PendingRequests: the run waits for an answer at the request port. The last checkpoint it saved holds
// the question, and that's where the run continues when the answer comes.
RunStatus status = await run.GetStatusAsync(cancellationToken);
if (status != RunStatus.PendingRequests || run.LastCheckpoint is not CheckpointInfo waiting)
{
LogRunProblems(run.OutgoingEvents, sessionId);
throw new InvalidOperationException(
$"The approval workflow stopped with the status {status} instead of waiting for the manager.");
}
return waiting;
}
RunAsyncstarts a run with the request as its input and the session ID for its checkpoints. It returns when the run has nothing left to do, which here is when the manager's question is waiting.PendingRequestsis the status of a run that waits for an answer. Any other status means a step failed:LogRunProblemswrites each failed step's exception to the log, and the exception stops the request.run.LastCheckpointis the last checkpoint the run saved, the one that holds the question.await usingdisposes of the run. From here on, the run waits in Cosmos DB, not in memory.
Answer a request
// Only the requests sent to this manager: anyone else's number isn't found.
if (await approvalStore.FindAsync(managerId, number, cancellationToken) is not StoredApproval stored)
{
return new ApprovalAnswerResult(ApprovalAnswerOutcome.NotFound,
Problem: $"No request {number} is waiting for your answer.");
}
if (stored.Approval.Status != ApprovalStatus.Pending)
{
return AlreadyAnswered(stored.Approval);
}
// 1. Record the answer, unless someone answered first. Two answers sent at the same moment can't both win.
if (await approvalStore.TryDecideAsync(managerId, stored, approved, comment, cancellationToken) is not StoredApproval decided)
{
StoredApproval? current = await approvalStore.FindAsync(managerId, number, cancellationToken);
return AlreadyAnswered((current ?? stored).Approval);
}
// 2. Continue the run from the checkpoint where it waits, and give the waiting question its answer.
try
{
await ContinueRunAsync(decided, new ApprovalDecision(decided.Approval.Number, approved, comment), cancellationToken);
}
catch
{
// The answer couldn't be carried out: the request waits again, so the manager can answer it again.
await approvalStore.ReopenAsync(managerId, decided, CancellationToken.None);
throw;
}
// 3. The run is finished, and its checkpoints are no longer needed.
await checkpointStore.DeleteSessionAsync(decided.Checkpoint.SessionId, cancellationToken);
return new ApprovalAnswerResult(ApprovalAnswerOutcome.Answered, decided.Approval);
FindAsyncreads from the manager's own partition only (Step 8). A request sent to someone else gets the same answer as a number that doesn't exist, so nobody learns which numbers are real.TryDecideAsyncrecords the answer only if the request hasn't changed since it was read, with the ETag check from Step 8. When two answers arrive at the same moment, one wins, and the other gets the request's status as it now stands.ContinueRunAsynccontinues the run with the answer. If that fails,ReopenAsyncsets the request back to Pending, so the manager can answer again, and the exception goes on to the endpoint.- The checkpoints are deleted once the run has finished. Nothing waits on them any more.
ContinueRunAsync does the part this step is about:
private async Task ContinueRunAsync(StoredApproval approval, ApprovalDecision decision, CancellationToken cancellationToken)
{
string number = approval.Approval.Number;
// The checkpoint comes from our own record, never from the request: a checkpoint is trusted data, so the API
// only ever loads one that the run it started for this request saved. And it's always the one where the run
// waits, not the latest: an attempt that fails saves checkpoints after it, which no longer hold the question.
await using Run run = await Execution.ResumeAsync(workflow, approval.Checkpoint, cancellationToken);
// The run starts again where the checkpoint left it. Its question to the manager comes back as a RequestInfoEvent.
RequestInfoEvent question = run.OutgoingEvents.OfType<RequestInfoEvent>()
.SingleOrDefault(waiting => waiting.Request.TryGetDataAs(out ApprovalRequest? _))
?? throw new InvalidOperationException($"The workflow run of {number} isn't waiting for the manager.");
// The answer goes back through the request port, and the run carries on to ApplyDecision.
await run.ResumeAsync([question.Request.CreateResponse(decision)], cancellationToken);
IReadOnlyList<WorkflowEvent> events = [.. run.NewEvents];
if (!events.OfType<WorkflowOutputEvent>().Any(output => output.Is(out ApprovalOutcome? outcome) && outcome.ApprovalNumber == number))
{
LogRunProblems(events, approval.Checkpoint.SessionId);
throw new InvalidOperationException($"The workflow run of {number} didn't finish.");
}
}
Execution.ResumeAsyncmakes a new run from the checkpoint saved with the request. Loading a checkpoint is a matter of trust: Microsoft's checkpoint guide calls checkpoint storage a trust boundary and warns: Never load checkpoints from untrusted or potentially tampered sources. The checkpoint's ID comes from the approval item the API wrote itself, never from the manager's request, and only the accounts you gave the data role in Step 2 can write to the container.- The question comes back. The restored run puts it in
OutgoingEventsas aRequestInfoEvent, andTryGetDataAs(out ApprovalRequest? _)picks the one that asks for an approval. question.Request.CreateResponse(decision)makes the answer to exactly that question, andrun.ResumeAsyncsends it in. The run carries on to ApplyDecision.run.NewEventsholds what happened since the answer went in. The run must have output anApprovalOutcomewith this request's number. If it didn't, a step failed: its error goes to the log, and the exception tellsAnswerAsync.
The mistake I made first
My first version didn't keep the checkpoint with the request. To continue a run, it asked the checkpoint manager for the session's latest checkpoint. That looked right: once a request is sent, its latest checkpoint is the one where the run waits.
Then I wrote the catch that reopens a request when its answer can't be carried out, say because the licence service is down, and asked myself what the manager's second answer would continue from. The failed attempt had saved checkpoints too, after the waiting one. To see what a run restored from one of them looks like, I built a small console app: the same three steps, a decision step that fails on the first answer, and checkpoints in files. Each attempt continued from the latest checkpoint, as my code did:
start: status PendingRequests, checkpoints 2
attempt 1: 2 checkpoints, resuming from #2
after restore: status PendingRequests, pending question: Microsoft.Agents.AI.Workflows.PortableValue
after answer: status Ended
event: RequestInfoEvent
event: WorkflowStartedEvent
event: SuperStepStartedEvent
event: ExecutorInvokedEvent
event: ExecutorCompletedEvent
event: SuperStepCompletedEvent
event: SuperStepStartedEvent
event: ExecutorInvokedEvent
event: ExecutorFailedEvent The licence service is down.
event: WorkflowErrorEvent Error invoking handler for System.Boolean
checkpoints now: 3
attempt 2: 3 checkpoints, resuming from #3
after restore: status Idle, pending question:
The first attempt continued from checkpoint 2, where the run waits, and the failing step left a third checkpoint behind. The second attempt continued from that one, the latest, and the run came back Idle, with no question waiting. A reopened request would have stayed Pending forever, and every answer the manager sent would fail.
So the request keeps the checkpoint where its run waits from the start: StartRunAsync returns run.LastCheckpoint, and RequestAsync saves it with the request. Every answer continues from that checkpoint, however many attempts came before. That's also why the request is saved after the run, not before: the checkpoint doesn't exist until the run stops.
To check the fix in the API, I changed ApplyDecision for one run so it failed whenever the manager's comment was simulate-a-failure, and changed it back afterwards. The first answer failed with status 500, and the API logged it (stack traces left out):
fail: Dewiride.ServiceDesk.Agent.Approvals.SoftwareApprovals[1933060374]
Step ApplyDecision of approval workflow run 9eadb890d49e48a4ac283eed51716c39 failed.
System.InvalidOperationException: Simulated failure for verification.
fail: Dewiride.ServiceDesk.Agent.Approvals.SoftwareApprovals[1851032607]
Approval workflow run 9eadb890d49e48a4ac283eed51716c39 failed.
System.Reflection.TargetInvocationException: Error invoking handler for Dewiride.ServiceDesk.Agent.Approvals.ApprovalDecision
---> System.InvalidOperationException: Simulated failure for verification.
fail: Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware[1]
An unhandled exception has occurred while executing the request.
System.InvalidOperationException: The workflow run of APR-FF92AAA7 didn't finish.
The request was Pending again, and its run now had three checkpoints. The second answer continued from the waiting checkpoint, and the request was approved:
info: Dewiride.ServiceDesk.Audit[12]
Employee 44444444-4444-4444-4444-444444444444 approved request APR-FF92AAA7, and the Microsoft Project Plan 3 licence was assigned to the employee who asked for it.
How to Resume a Microsoft Agent Framework Workflow from the Checkpoint Where It Waits for an Answer in C# shows the problem and the fix with a small example.
The whole file
using Dewiride.ServiceDesk.Agent.Auditing;
using Dewiride.ServiceDesk.Agent.Systems;
using Microsoft.Agents.AI.Workflows;
using Microsoft.Agents.AI.Workflows.InProc;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
namespace Dewiride.ServiceDesk.Agent.Approvals;
/// <summary>
/// Software requests that the employee's manager has to approve. Each request starts a run of the software
/// approval workflow, which stops at the manager's question. Its checkpoint keeps it waiting, for minutes or days
/// and through restarts, until the manager's answer continues it.
/// </summary>
public sealed partial class SoftwareApprovals(
[FromKeyedServices(SoftwareApprovals.WorkflowName)] Workflow workflow,
IWorkflowCheckpointStore checkpointStore,
IApprovalStore approvalStore,
IEmployeeDirectory employeeDirectory,
ISoftwareCatalog softwareCatalog,
ServiceDeskAudit audit,
ILogger<SoftwareApprovals> logger)
{
/// <summary>The name the workflow is registered and traced under.</summary>
public const string WorkflowName = "software-approval";
/// <summary>The longest reason an employee can give.</summary>
public const int MaxReasonLength = 500;
/// <summary>The longest comment a manager can add to an answer.</summary>
public const int MaxCommentLength = 500;
// Turns checkpoints into JSON and back. It knows the workflow framework's types; ApprovalJsonContext adds this app's.
private readonly CheckpointManager _checkpointManager =
CheckpointManager.CreateJson(checkpointStore, ApprovalJsonContext.Default.Options);
// Concurrent: one workflow serves every request at the same time. WithCheckpointing: each run saves
// a checkpoint at the end of every superstep, through the checkpoint manager.
private InProcessExecutionEnvironment Execution => InProcessExecution.Concurrent.WithCheckpointing(_checkpointManager);
/// <summary>
/// Sends an employee's request for an app to their manager, and starts the workflow run that waits for the answer.
/// Returns the request, or the problem to fix first.
/// </summary>
public async Task<SoftwareRequestResult> RequestAsync(
string employeeId, string software, string reason, CancellationToken cancellationToken)
{
// The app and the reason come from the AI model: check them, and say what to fix instead of failing.
if (string.IsNullOrWhiteSpace(reason))
{
return NotSent("The reason is empty. Ask the employee what they need the app for.");
}
if (reason.Trim().Length > MaxReasonLength)
{
return NotSent($"The reason has {reason.Trim().Length} characters. Shorten it to {MaxReasonLength} characters or fewer.");
}
IReadOnlyList<SoftwareTitle> titles = await softwareCatalog.GetTitlesAsync(cancellationToken);
if (FindTitle(titles, software) is not SoftwareTitle title)
{
return NotSent($"The software catalog has no single app called '{software}'. " +
$"The apps in it are: {string.Join(", ", titles.Select(t => t.Name))}.");
}
// Who approves comes from the company directory, never from the AI model.
if (await employeeDirectory.FindEmployeeAsync(employeeId, cancellationToken) is not Employee requester)
{
return NotSent("The company directory has no record of this employee, so the request can't go to a manager. Offer to raise a ticket instead.");
}
Employee? approver = requester.ManagerId is string managerId
? await employeeDirectory.FindEmployeeAsync(managerId, cancellationToken)
: null;
if (approver is null || approver.Id == requester.Id)
{
return NotSent("The company directory has no manager for this employee who can approve the request. Offer to raise a ticket instead.");
}
// Each run gets an ID of its own: the session ID that its checkpoints are kept under.
string sessionId = Guid.NewGuid().ToString("N");
StoredApproval stored;
try
{
// 1. The run: it saves the request in its state, asks the manager and stops there, waiting.
CheckpointInfo waiting = await StartRunAsync(
new SoftwareRequest(requester.Id, requester.DisplayName, title.Id, title.Name, reason.Trim()),
sessionId, cancellationToken);
// 2. The request, saved where the manager's list finds it, with the checkpoint where its run waits.
// It's saved last, so a manager never sees a request that nothing is waiting to carry out.
stored = await approvalStore.CreateAsync(
new NewSoftwareApproval(requester, approver, title, reason.Trim(), waiting), cancellationToken);
}
catch
{
// The request never reached the manager: remove what the run saved, so nothing is left waiting.
await checkpointStore.DeleteSessionAsync(sessionId, CancellationToken.None);
throw;
}
audit.SoftwareRequested(stored.Approval.Number, title.Name);
return new SoftwareRequestResult(Sent: true, Request: stored.Approval);
}
/// <summary>Gets the requests one employee sent to their manager, newest first.</summary>
public async Task<IReadOnlyList<SoftwareApproval>> GetMyRequestsAsync(string employeeId, CancellationToken cancellationToken)
{
Employee? employee = await employeeDirectory.FindEmployeeAsync(employeeId, cancellationToken);
return employee?.ManagerId is string managerId
? await approvalStore.GetRequestsAsync(managerId, employeeId, cancellationToken)
: [];
}
/// <summary>Gets the requests waiting for a manager's answer, oldest first.</summary>
public Task<IReadOnlyList<SoftwareApproval>> GetWaitingForAsync(string managerId, CancellationToken cancellationToken) =>
approvalStore.GetPendingAsync(managerId, cancellationToken);
/// <summary>
/// Records a manager's answer to one of their requests and continues its workflow run from the checkpoint where it waits.
/// </summary>
public async Task<ApprovalAnswerResult> AnswerAsync(
string managerId, string number, bool approved, string? comment, CancellationToken cancellationToken)
{
comment = string.IsNullOrWhiteSpace(comment) ? null : comment.Trim();
if (comment?.Length > MaxCommentLength)
{
return new ApprovalAnswerResult(ApprovalAnswerOutcome.Invalid,
Problem: $"The comment has {comment.Length} characters. Shorten it to {MaxCommentLength} characters or fewer.");
}
// Only the requests sent to this manager: anyone else's number isn't found.
if (await approvalStore.FindAsync(managerId, number, cancellationToken) is not StoredApproval stored)
{
return new ApprovalAnswerResult(ApprovalAnswerOutcome.NotFound,
Problem: $"No request {number} is waiting for your answer.");
}
if (stored.Approval.Status != ApprovalStatus.Pending)
{
return AlreadyAnswered(stored.Approval);
}
// 1. Record the answer, unless someone answered first. Two answers sent at the same moment can't both win.
if (await approvalStore.TryDecideAsync(managerId, stored, approved, comment, cancellationToken) is not StoredApproval decided)
{
StoredApproval? current = await approvalStore.FindAsync(managerId, number, cancellationToken);
return AlreadyAnswered((current ?? stored).Approval);
}
// 2. Continue the run from the checkpoint where it waits, and give the waiting question its answer.
try
{
await ContinueRunAsync(decided, new ApprovalDecision(decided.Approval.Number, approved, comment), cancellationToken);
}
catch
{
// The answer couldn't be carried out: the request waits again, so the manager can answer it again.
await approvalStore.ReopenAsync(managerId, decided, CancellationToken.None);
throw;
}
// 3. The run is finished, and its checkpoints are no longer needed.
await checkpointStore.DeleteSessionAsync(decided.Checkpoint.SessionId, cancellationToken);
return new ApprovalAnswerResult(ApprovalAnswerOutcome.Answered, decided.Approval);
}
// Starts the run of one request. It stops at the manager's question: returns the checkpoint where it waits.
private async Task<CheckpointInfo> StartRunAsync(SoftwareRequest request, string sessionId, CancellationToken cancellationToken)
{
await using Run run = await Execution.RunAsync(workflow, request, sessionId, cancellationToken);
// PendingRequests: the run waits for an answer at the request port. The last checkpoint it saved holds
// the question, and that's where the run continues when the answer comes.
RunStatus status = await run.GetStatusAsync(cancellationToken);
if (status != RunStatus.PendingRequests || run.LastCheckpoint is not CheckpointInfo waiting)
{
LogRunProblems(run.OutgoingEvents, sessionId);
throw new InvalidOperationException(
$"The approval workflow stopped with the status {status} instead of waiting for the manager.");
}
return waiting;
}
// Continues the run of one request from the checkpoint where it waits, and gives its question the manager's answer.
private async Task ContinueRunAsync(StoredApproval approval, ApprovalDecision decision, CancellationToken cancellationToken)
{
string number = approval.Approval.Number;
// The checkpoint comes from our own record, never from the request: a checkpoint is trusted data, so the API
// only ever loads one that the run it started for this request saved. And it's always the one where the run
// waits, not the latest: an attempt that fails saves checkpoints after it, which no longer hold the question.
await using Run run = await Execution.ResumeAsync(workflow, approval.Checkpoint, cancellationToken);
// The run starts again where the checkpoint left it. Its question to the manager comes back as a RequestInfoEvent.
RequestInfoEvent question = run.OutgoingEvents.OfType<RequestInfoEvent>()
.SingleOrDefault(waiting => waiting.Request.TryGetDataAs(out ApprovalRequest? _))
?? throw new InvalidOperationException($"The workflow run of {number} isn't waiting for the manager.");
// The answer goes back through the request port, and the run carries on to ApplyDecision.
await run.ResumeAsync([question.Request.CreateResponse(decision)], cancellationToken);
IReadOnlyList<WorkflowEvent> events = [.. run.NewEvents];
if (!events.OfType<WorkflowOutputEvent>().Any(output => output.Is(out ApprovalOutcome? outcome) && outcome.ApprovalNumber == number))
{
LogRunProblems(events, approval.Checkpoint.SessionId);
throw new InvalidOperationException($"The workflow run of {number} didn't finish.");
}
}
// A single app whose name is the text, or else the one app whose name contains it, such as Visio.
private static SoftwareTitle? FindTitle(IReadOnlyList<SoftwareTitle> titles, string software)
{
string text = software.Trim();
if (text.Length == 0)
{
return null;
}
SoftwareTitle? exact = titles.FirstOrDefault(title => string.Equals(title.Name, text, StringComparison.OrdinalIgnoreCase));
if (exact is not null)
{
return exact;
}
List<SoftwareTitle> partial = [.. titles.Where(title => title.Name.Contains(text, StringComparison.OrdinalIgnoreCase))];
return partial.Count == 1 ? partial[0] : null;
}
private static SoftwareRequestResult NotSent(string problem) => new(Sent: false, Problem: problem);
private static ApprovalAnswerResult AlreadyAnswered(SoftwareApproval approval) =>
new(ApprovalAnswerOutcome.AlreadyAnswered, approval,
$"Request {approval.Number} was already {approval.Status.ToString().ToLowerInvariant()}.");
private void LogRunProblems(IEnumerable<WorkflowEvent> events, string sessionId)
{
foreach (WorkflowEvent workflowEvent in events)
{
switch (workflowEvent)
{
case ExecutorFailedEvent failed:
LogStepFailed(failed.Data, failed.ExecutorId, sessionId);
break;
case WorkflowErrorEvent error:
LogRunFailed(error.Exception, sessionId);
break;
}
}
}
[LoggerMessage(Level = LogLevel.Error, Message = "Step {ExecutorId} of approval workflow run {SessionId} failed.")]
private partial void LogStepFailed(Exception? exception, string executorId, string sessionId);
[LoggerMessage(Level = LogLevel.Error, Message = "Approval workflow run {SessionId} failed.")]
private partial void LogRunFailed(Exception? exception, string sessionId);
}
AlreadyAnswered puts the request's status into the problem, such as Request APR-01723B70 was already rejected. LogRunProblems writes each ExecutorFailedEvent (a step that failed) and WorkflowErrorEvent (the run that failed) to the log with its exception, through two [LoggerMessage] methods.
Step 12: Register the Software Requests
Registration comes in two parts, like the memories in Part 16. The agent's library registers the directory, the catalog, the workflow and SoftwareApprovals. The host chooses where requests and checkpoints are kept.
What the agent needs
Create src/Dewiride.ServiceDesk.Agent/Approvals/SoftwareApprovalExtensions.cs:
using Dewiride.ServiceDesk.Agent.Auditing;
using Dewiride.ServiceDesk.Agent.Systems;
using Microsoft.Agents.AI.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.Extensions.Hosting;
namespace Dewiride.ServiceDesk.Agent.Approvals;
/// <summary>Adds software requests and the workflow that waits for the manager's approval.</summary>
internal static class SoftwareApprovalExtensions
{
public static IHostApplicationBuilder AddSoftwareApprovals(this IHostApplicationBuilder builder)
{
// 1. The company directory, read from the "EmployeeDirectory" settings, and the software catalog.
// A host that has the real systems registers its own versions first, and those win.
builder.Services.AddOptions<EmployeeDirectoryOptions>()
.BindConfiguration(EmployeeDirectoryOptions.SectionName)
.Validate(directory => directory.Employees.All(employee =>
!string.IsNullOrWhiteSpace(employee.Id) && !string.IsNullOrWhiteSpace(employee.DisplayName)),
"Give every employee in EmployeeDirectory:Employees an Id (their object ID) and a DisplayName.")
.Validate(directory => directory.Employees
.Select(employee => employee.Id.ToLowerInvariant()).Distinct().Count() == directory.Employees.Count,
"Each employee in EmployeeDirectory:Employees needs an Id of their own.")
.ValidateOnStart();
builder.Services.TryAddSingleton<IEmployeeDirectory, SampleEmployeeDirectory>();
builder.Services.TryAddSingleton<ISoftwareCatalog, SampleSoftwareCatalog>();
// 2. The workflow, built once and registered under its name.
builder.AddWorkflow(SoftwareApprovals.WorkflowName, (services, name) => SoftwareApprovalWorkflow.Build(
services.GetRequiredService<ISoftwareCatalog>(),
services.GetRequiredService<ServiceDeskAudit>()));
// 3. What starts a run for every request and continues it when the manager answers.
builder.Services.AddSingleton<SoftwareApprovals>();
return builder;
}
}
- The directory and the catalog.
BindConfigurationfillsEmployeeDirectoryOptionsfrom theEmployeeDirectorysection of Step 6, and the twoValidatecalls check it: every employee needs an ID and a name, and no ID can appear twice.ValidateOnStartruns the checks when the API starts, so a mistake in the settings stops the API straight away instead of failing someone's request later.TryAddSingletonregisters the sample versions only if the host hasn't registered its own, so a company with a real directory registers it first and it wins. - The workflow.
AddWorkflowregisters it under its name,software-approval, as Part 19 did for the triage workflow. The function builds it once, with the catalog and the audit it needs, andSoftwareApprovalsgets it with[FromKeyedServices(SoftwareApprovals.WorkflowName)]. SoftwareApprovalsis a singleton: one for the whole app. It keeps nothing about a request in memory, so every request can share it.
Then call it in ServiceDeskAgentExtensions, in step 5 of AddServiceDeskAgent, before the tools that need it:
// 5. The ticket triage workflow, which classifies every new ticket, sets its priority and assigns it,
// and the intake that raises tickets from the chat or any other app and triages each one.
builder.AddTicketTriage();
builder.Services.AddSingleton<TicketIntake>();
// Software requests, and the workflow that waits for the manager's approval of each one.
builder.AddSoftwareApprovals();
builder.Services.AddSingleton<ServiceDeskTools>();
Add using Dewiride.ServiceDesk.Agent.Approvals; at the top. The summary above the class now names the two stores the host provides. The complete file:
using Azure.AI.Projects;
using Azure.Core;
using Azure.Identity;
using Dewiride.ServiceDesk.Agent.Approvals;
using Dewiride.ServiceDesk.Agent.Auditing;
using Dewiride.ServiceDesk.Agent.Guardrails;
using Dewiride.ServiceDesk.Agent.Memory;
using Dewiride.ServiceDesk.Agent.Systems;
using Dewiride.ServiceDesk.Agent.Triage;
using Microsoft.Agents.AI;
using Microsoft.Agents.AI.Hosting;
using Microsoft.Extensions.AI;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Options;
namespace Dewiride.ServiceDesk.Agent;
/// <summary>
/// Adds the Dewiride Service Desk agent to any .NET host: the API today, a background job and a Teams bot later.
/// The host also registers <see cref="ICurrentEmployee"/>, so the agent's tools know who is signed in,
/// an <see cref="IEmployeeMemoryStore"/>, where the agent keeps what it remembers about each employee,
/// and an <see cref="IApprovalStore"/> and an <see cref="IWorkflowCheckpointStore"/>, where software requests wait
/// for their manager's answer.
/// </summary>
public static class ServiceDeskAgentExtensions
{
/// <summary>The name the agent is registered under.</summary>
public const string AgentName = "service-desk";
/// <summary>
/// The name the agent's traces and metrics are sent under: every run, every model call and every tool call.
/// A host that collects telemetry subscribes to it with AddSource and AddMeter.
/// </summary>
public const string TelemetrySourceName = "Dewiride.ServiceDesk.Agent";
public static IHostedAgentBuilder AddServiceDeskAgent(this IHostApplicationBuilder builder)
{
// 1. Read the "Foundry" settings, and refuse to start if one is missing.
builder.Services.AddOptions<FoundryOptions>()
.Bind(builder.Configuration.GetSection(FoundryOptions.SectionName))
.Validate(foundry => Uri.TryCreate(foundry.ProjectEndpoint, UriKind.Absolute, out _),
"Set Foundry:ProjectEndpoint to your Foundry project endpoint.")
.Validate(foundry => !string.IsNullOrWhiteSpace(foundry.ModelDeployment),
"Set Foundry:ModelDeployment to your model deployment name.")
.ValidateOnStart();
// 2. Read the "MicrosoftLearn" settings the same way. Wrong settings stop the API here;
// a server that can't be reached doesn't (see MicrosoftLearnTools).
builder.Services.AddOptions<MicrosoftLearnOptions>()
.Bind(builder.Configuration.GetSection(MicrosoftLearnOptions.SectionName))
.Validate(learn => Uri.TryCreate(learn.McpEndpoint, UriKind.Absolute, out Uri? endpoint)
&& endpoint.Scheme == Uri.UriSchemeHttps,
"Set MicrosoftLearn:McpEndpoint to the https address of the Microsoft Learn MCP server.")
.Validate(learn => !string.IsNullOrWhiteSpace(learn.ProtocolVersion),
"Set MicrosoftLearn:ProtocolVersion to the MCP protocol version the server supports, such as 2025-06-18.")
.ValidateOnStart();
// 3. Sign in with Microsoft Entra ID - no API keys. The AZURE_TOKEN_CREDENTIALS
// environment variable decides how: your Azure CLI sign-in on your machine,
// a managed identity in Azure.
builder.Services.AddSingleton<TokenCredential>(_ =>
new DefaultAzureCredential(DefaultAzureCredential.DefaultEnvironmentVariableName));
// 4. The company's IT systems that the tools read from. These are in-memory samples;
// a host that has the real systems registers its own versions first, and those win.
builder.Services.TryAddSingleton(TimeProvider.System);
builder.Services.TryAddSingleton<IDeviceInventory, SampleDeviceInventory>();
builder.Services.TryAddSingleton<ITicketSystem, SampleTicketSystem>();
builder.Services.TryAddSingleton<IKnowledgeBase, SampleKnowledgeBase>();
builder.Services.TryAddSingleton<IAccountSystem, SampleAccountSystem>();
// 5. The ticket triage workflow, which classifies every new ticket, sets its priority and assigns it,
// and the intake that raises tickets from the chat or any other app and triages each one.
builder.AddTicketTriage();
builder.Services.AddSingleton<TicketIntake>();
// Software requests, and the workflow that waits for the manager's approval of each one.
builder.AddSoftwareApprovals();
builder.Services.AddSingleton<ServiceDeskTools>();
// 6. The tools of the Microsoft Learn MCP server. One instance for the whole app, so every
// run shares one connection; the app disposes it when it stops.
builder.Services.AddSingleton<MicrosoftLearnTools>();
// 7. What the agent remembers about the signed-in employee, from one conversation to the next.
// One instance for the whole app: it keeps nothing about any employee itself, only in the store.
builder.Services.AddSingleton<EmployeeMemory>();
// 8. The audit trail: one log entry for every change the agent makes for an employee,
// every approval answer and every secret the guard removes.
builder.Services.AddSingleton<ServiceDeskAudit>();
// 9. The secret guard, which keeps passwords and recovery keys away from the AI model.
builder.Services.AddSingleton<SecretGuard>();
// 10. Register the agent with its tools. It talks to your model through the Foundry project,
// gets the Microsoft Learn tools and the employee's memories at the start of every run,
// takes secrets out of messages and tool results, records approval answers in the audit
// trail, traces every run, and logs every run that fails, so the API's console shows you why.
return builder.AddAIAgent(AgentName, (services, name) =>
{
FoundryOptions foundry = services.GetRequiredService<IOptions<FoundryOptions>>().Value;
TokenCredential credential = services.GetRequiredService<TokenCredential>();
ServiceDeskTools tools = services.GetRequiredService<ServiceDeskTools>();
MicrosoftLearnTools microsoftLearnTools = services.GetRequiredService<MicrosoftLearnTools>();
EmployeeMemory employeeMemory = services.GetRequiredService<EmployeeMemory>();
SecretGuard secretGuard = services.GetRequiredService<SecretGuard>();
ServiceDeskAudit audit = services.GetRequiredService<ServiceDeskAudit>();
AIProjectClient projectClient = new(new Uri(foundry.ProjectEndpoint), credential);
return projectClient
.AsAIAgent(new ChatClientAgentOptions
{
// A fixed ID. Without one, every start gets a new random ID, and the session store,
// which keeps each conversation under the agent's ID, can't find yesterday's conversations.
Id = name,
Name = name,
ChatOptions = new ChatOptions
{
ModelId = foundry.ModelDeployment,
Instructions = ServiceDeskInstructions.Text,
Tools = tools.AsAITools(),
},
AIContextProviders = [microsoftLearnTools, employeeMemory],
})
.AsBuilder()
// The secret guard comes first, so it's the outermost layer: everything after it,
// including the logging below, only ever sees messages without their secrets.
.Use(sharedFunc: secretGuard.RemoveSecretsFromMessagesAsync)
.Use(secretGuard.RemoveSecretsFromToolResultAsync)
// Records every answer the employee gives to an approval request, approved or rejected.
.Use(sharedFunc: audit.RecordApprovalAnswersAsync)
// Traces and metrics for every run, model call and tool call: durations and token counts,
// never the messages themselves. After the guard, so even those could never hold a secret.
.UseOpenTelemetry(sourceName: TelemetrySourceName)
.UseLogging()
.Build(services);
});
}
}
Where requests and checkpoints are kept
CosmosDbOptions gets the names of the two new containers:
namespace Dewiride.ServiceDesk.Agent;
/// <summary>
/// Where conversations, memories and approvals are kept. Filled from the "CosmosDb" section of the app's settings.
/// </summary>
public sealed class CosmosDbOptions
{
public const string SectionName = "CosmosDb";
/// <summary>The account's URI, for example https://your-account.documents.azure.com:443/.</summary>
public string AccountEndpoint { get; set; } = string.Empty;
/// <summary>The database that holds the containers, for example servicedesk.</summary>
public string DatabaseName { get; set; } = string.Empty;
/// <summary>The container that holds one item per conversation, for example sessions.</summary>
public string SessionsContainerName { get; set; } = string.Empty;
/// <summary>The container that holds what the agent remembers about each employee, for example memories.</summary>
public string MemoriesContainerName { get; set; } = string.Empty;
/// <summary>The container that holds one item per request for approval, for example approvals.</summary>
public string ApprovalsContainerName { get; set; } = string.Empty;
/// <summary>The container that holds the checkpoints of the workflow runs, for example checkpoints.</summary>
public string CheckpointsContainerName { get; set; } = string.Empty;
}
Create src/Dewiride.ServiceDesk.Agent/Approvals/CosmosApprovalExtensions.cs:
using Microsoft.Agents.AI.Hosting;
using Microsoft.Azure.Cosmos;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
namespace Dewiride.ServiceDesk.Agent.Approvals;
/// <summary>
/// Keeps software requests and the checkpoints of their workflow runs in Azure Cosmos DB, for any host that runs the agent.
/// </summary>
public static class CosmosApprovalExtensions
{
public static IHostedAgentBuilder WithCosmosDbApprovals(this IHostedAgentBuilder agent)
{
// 1. The Cosmos DB account and its client, shared with the session store and the memories.
// The approvals need the names of their two containers.
agent.ServiceCollection.AddServiceDeskCosmosDb()
.Validate(cosmos => !string.IsNullOrWhiteSpace(cosmos.ApprovalsContainerName),
"Set CosmosDb:ApprovalsContainerName to the name of the container that keeps the requests for approval.")
.Validate(cosmos => !string.IsNullOrWhiteSpace(cosmos.CheckpointsContainerName),
"Set CosmosDb:CheckpointsContainerName to the name of the container that keeps the workflow checkpoints.");
// 2. The requests, which the managers' lists read.
agent.ServiceCollection.AddSingleton<IApprovalStore>(services => new CosmosApprovalStore(
Container(services, cosmos => cosmos.ApprovalsContainerName), services.GetRequiredService<TimeProvider>()));
// 3. The checkpoints, which keep each run waiting until its manager answers.
agent.ServiceCollection.AddSingleton<IWorkflowCheckpointStore>(services => new CosmosDbCheckpointStore(
Container(services, cosmos => cosmos.CheckpointsContainerName), services.GetRequiredService<TimeProvider>()));
return agent;
}
private static Container Container(IServiceProvider services, Func<CosmosDbOptions, string> containerName)
{
CosmosDbOptions cosmos = services.GetRequiredService<IOptions<CosmosDbOptions>>().Value;
return services.GetRequiredService<CosmosClient>().GetContainer(cosmos.DatabaseName, containerName(cosmos));
}
}
- The account.
AddServiceDeskCosmosDbis the method from Part 16 that the session store and the memories share: oneCosmosClientfor the whole app. The twoValidatecalls add the approvals' own settings, so the API won't start without the container names. - The requests, in the
approvalscontainer. - The checkpoints, in the
checkpointscontainer. Both stores get the app'sTimeProvider, which gives them the current time.
Last, in Program.cs, add .WithCosmosDbApprovals() to the agent, next to the session store and the memories:
var serviceDeskAgent = builder.AddServiceDeskAgent()
.WithCosmosDbSessionStore()
.WithCosmosDbEmployeeMemory()
.WithCosmosDbApprovals();
Add using Dewiride.ServiceDesk.Agent.Approvals; at the top. Step 14 adds one more line to Program.cs, so the complete file comes there.
Step 13: Give the Agent Two Tools for Software Requests
In ServiceDeskTools, add SoftwareApprovals to the constructor, and two tools:
[Description("Asks for an app from the company's software catalog for the employee in this chat. Every app in the catalog costs a licence, so the request goes to the employee's manager to approve. Returns the request with its number, the app, the manager who answers it and its status, or the problem to fix before it can be sent, such as the names of the apps in the catalog.")]
public Task<SoftwareRequestResult> RequestSoftwareAsync(
[Description("The app's name, such as 'Microsoft Visio Plan 2', or a word only that app's name has, such as 'Visio'.")] string software,
[Description("Why the employee needs the app, from what they told you, such as 'to draw the network diagrams for the office move'. At most 500 characters.")] string reason,
CancellationToken cancellationToken) =>
softwareApprovals.RequestAsync(SignedInEmployeeId(), software, reason, cancellationToken);
[Description("Gets the software requests of the employee in this chat, newest first: number, app, the manager who answers it, status (Pending, Approved or Rejected), when it was answered and the manager's comment.")]
public Task<IReadOnlyList<SoftwareApproval>> GetMySoftwareRequestsAsync(CancellationToken cancellationToken) =>
softwareApprovals.GetMyRequestsAsync(SignedInEmployeeId(), cancellationToken);
- The descriptions are for the model. It reads them to decide when to call a tool and what to put in each parameter. The description of
request_softwaresays the request goes to the manager and what comes back, including a problem to fix. - The employee comes from the sign-in, as in every other tool. The model fills in only the app and the reason.
- No approval card this time.
reset_my_passwordwaits for the employee's approval in the chat because it changes their account at once.request_softwarechanges nothing yet: the approval it needs is the manager's, and the workflow waits for it.
Add both to AsAITools, after create_ticket:
AIFunctionFactory.Create(RequestSoftwareAsync, name: "request_software"),
AIFunctionFactory.Create(GetMySoftwareRequestsAsync, name: "get_my_software_requests"),
Add using Dewiride.ServiceDesk.Agent.Approvals; at the top. The complete file:
using System.ComponentModel;
using Dewiride.ServiceDesk.Agent.Approvals;
using Dewiride.ServiceDesk.Agent.Auditing;
using Dewiride.ServiceDesk.Agent.Systems;
using Microsoft.Extensions.AI;
namespace Dewiride.ServiceDesk.Agent;
/// <summary>
/// The agent's tools: what it may look up in the company's IT systems, the tickets it may raise,
/// the apps it may ask the employee's manager for, and the password reset it may ask for. The tools
/// about "my" records always use the signed-in employee, never an ID that the AI model chose.
/// </summary>
public sealed class ServiceDeskTools(
ICurrentEmployee currentEmployee,
IDeviceInventory deviceInventory,
ITicketSystem ticketSystem,
IKnowledgeBase knowledgeBase,
IAccountSystem accountSystem,
TicketIntake ticketIntake,
SoftwareApprovals softwareApprovals,
ServiceDeskAudit audit)
{
[Description("Gets the laptops and phones that IT gave to the employee in this chat: model, operating system, last check-in, compliance and free storage.")]
public Task<IReadOnlyList<Device>> GetMyDevicesAsync(CancellationToken cancellationToken) =>
deviceInventory.GetDevicesAsync(SignedInEmployeeId(), cancellationToken);
[Description("Gets the open IT tickets of the employee in this chat: number, title, description, status, team and latest update.")]
public Task<IReadOnlyList<Ticket>> GetMyTicketsAsync(CancellationToken cancellationToken) =>
ticketSystem.GetOpenTicketsAsync(SignedInEmployeeId(), cancellationToken);
[Description("Searches the IT knowledge base for articles with known fixes. Returns up to three articles.")]
public Task<IReadOnlyList<KnowledgeArticle>> SearchKnowledgeBaseAsync(
[Description("A few words about the problem, such as 'slow laptop' or 'VPN disconnects'.")] string query,
CancellationToken cancellationToken) =>
knowledgeBase.SearchAsync(query, cancellationToken);
[Description("Raises a new IT ticket for the employee in this chat, and triages it. Returns the new ticket with its number, category, priority, team and latest update, or the problem to fix before it can be raised.")]
public Task<CreateTicketResult> CreateTicketAsync(
[Description("Incident when something is broken or not working. Request when the employee needs something, such as new hardware, software or access.")] TicketType type,
[Description("A one-line summary of at most 100 characters, such as 'Laptop very slow, only 6% free storage'.")] string title,
[Description("The details the IT team needs: what happened or what is needed, the device, and what the employee already tried. At most 1,000 characters.")] string description,
CancellationToken cancellationToken) =>
// The intake checks the ticket the AI model wrote, raises it and triages it.
ticketIntake.RaiseAsync(SignedInEmployeeId(), new NewTicket(type, title, description), cancellationToken);
[Description("Asks for an app from the company's software catalog for the employee in this chat. Every app in the catalog costs a licence, so the request goes to the employee's manager to approve. Returns the request with its number, the app, the manager who answers it and its status, or the problem to fix before it can be sent, such as the names of the apps in the catalog.")]
public Task<SoftwareRequestResult> RequestSoftwareAsync(
[Description("The app's name, such as 'Microsoft Visio Plan 2', or a word only that app's name has, such as 'Visio'.")] string software,
[Description("Why the employee needs the app, from what they told you, such as 'to draw the network diagrams for the office move'. At most 500 characters.")] string reason,
CancellationToken cancellationToken) =>
softwareApprovals.RequestAsync(SignedInEmployeeId(), software, reason, cancellationToken);
[Description("Gets the software requests of the employee in this chat, newest first: number, app, the manager who answers it, status (Pending, Approved or Rejected), when it was answered and the manager's comment.")]
public Task<IReadOnlyList<SoftwareApproval>> GetMySoftwareRequestsAsync(CancellationToken cancellationToken) =>
softwareApprovals.GetMyRequestsAsync(SignedInEmployeeId(), cancellationToken);
[Description("Resets the password of the employee in this chat: texts a one-time link to their registered mobile phone, where they choose a new password. Returns where the link went and when it expires.")]
public async Task<PasswordReset> ResetMyPasswordAsync(CancellationToken cancellationToken)
{
PasswordReset reset = await accountSystem.ResetPasswordAsync(SignedInEmployeeId(), cancellationToken);
audit.PasswordResetSent(reset);
return reset;
}
/// <summary>The tools as the agent sees them: a name, a description and the parameters the AI model fills in.</summary>
public IList<AITool> AsAITools() =>
[
AIFunctionFactory.Create(GetMyDevicesAsync, name: "get_my_devices"),
AIFunctionFactory.Create(GetMyTicketsAsync, name: "get_my_tickets"),
AIFunctionFactory.Create(SearchKnowledgeBaseAsync, name: "search_knowledge_base"),
AIFunctionFactory.Create(CreateTicketAsync, name: "create_ticket"),
AIFunctionFactory.Create(RequestSoftwareAsync, name: "request_software"),
AIFunctionFactory.Create(GetMySoftwareRequestsAsync, name: "get_my_software_requests"),
// A password reset changes the employee's account, so it waits for a person: the agent
// can ask for it, but it runs only after the employee approves that exact call.
new ApprovalRequiredAIFunction(AIFunctionFactory.Create(ResetMyPasswordAsync, name: "reset_my_password")),
];
// Who is asking comes from the host's sign-in. With no one signed in, the tool fails
// instead of guessing.
private string SignedInEmployeeId() =>
currentEmployee.Id ?? throw new InvalidOperationException("No employee is signed in.");
}
In ServiceDeskInstructions, add a section about software requests, before What you remember:
Software requests:
- Employees can ask for the paid apps in the company's software catalog, such as Microsoft Visio. Each one needs
their manager's approval. When an employee asks for one, find out why they need it if they haven't said, then
call request_software. If it returns a problem, follow what it says.
- After sending a request, give the employee its number, the app's full name and the manager who answers it, and
tell them the app's licence is assigned as soon as the manager approves. Never promise that the manager will
approve it.
- When they ask about their requests, call get_my_software_requests and tell them the status, and the manager's
comment if there is one.
- You can't approve requests. Managers answer them outside this chat.
And in the rules at the end, the agent can now ask for software, but never approve a request:
- You can look things up, raise tickets, ask for software and reset the employee's own password, but you cannot
change, close or reassign tickets, approve requests, or change anything else. When a problem needs hands-on
help, offer to raise a ticket.
The complete file:
namespace Dewiride.ServiceDesk.Agent;
/// <summary>
/// The agent's instructions: who it is, what it helps with and the rules it always follows.
/// The model receives them with every request.
/// </summary>
internal static class ServiceDeskInstructions
{
public const string Text = """
You are the Dewiride IT Service Desk assistant. You help Dewiride employees with IT questions:
laptops and phones, software, sign-in and passwords, email and Microsoft Teams, Wi-Fi and VPN,
printers, and security.
How you answer:
- Be friendly, clear and brief.
- Give fixes as short numbered steps.
- If a request is unclear, ask one clarifying question first, such as which device or operating system.
- If you are not sure, say so. Never invent Dewiride policies, ticket numbers or contact details.
- Write plain text. Do not use Markdown formatting such as ** or #.
What you can look up and do:
- Use your tools to look up the employee's own devices and open tickets, and to search the IT knowledge base.
Look things up instead of guessing, and base your answers on what the tools return.
- You can only see the records of the employee you are chatting with. If someone asks about another
person's devices or tickets, explain that you can only see their own.
- When a knowledge base article fits the problem, follow its steps and mention its number, such as KB0001.
- For questions about Microsoft products, such as Windows, Microsoft 365, Outlook, Teams, OneDrive and
Microsoft Authenticator, that the knowledge base doesn't answer, search Microsoft Learn with your
Microsoft Learn tools. Base your answer on what you find, and give the link to the page you used.
- Searches of Microsoft Learn leave Dewiride. Describe the problem in general words only: never put names,
email addresses, device names, ticket numbers or other details about the employee in them.
- You can raise tickets for the employee you are chatting with. Raise one only when they ask for it or agree
when you offer it. First check their open tickets: if one already covers the problem, give them its number
instead of raising another.
- Write the ticket's title and description from what the employee told you, what you remember about them
and what your tools found. Never invent details. After raising it, give the employee the new ticket's number,
its priority, the team that has it and its latest update.
- You can reset the password of the employee you are chatting with, and only theirs. Call reset_my_password
when they ask for a reset, or agree when you offer one because they forgot their password, are locked out or
wrote it down.
Don't ask them to confirm it in your own words first: they approve the reset in the chat before it runs.
- After a reset, tell them where the one-time link went and when it expires, and that they choose their new
password with that link. If the reset is rejected, the employee declined it: say that their password
wasn't reset and nothing changed. Don't call it a failure or ask them to try again.
Software requests:
- Employees can ask for the paid apps in the company's software catalog, such as Microsoft Visio. Each one needs
their manager's approval. When an employee asks for one, find out why they need it if they haven't said, then
call request_software. If it returns a problem, follow what it says.
- After sending a request, give the employee its number, the app's full name and the manager who answers it, and
tell them the app's licence is assigned as soon as the manager approves. Never promise that the manager will
approve it.
- When they ask about their requests, call get_my_software_requests and tell them the status, and the manager's
comment if there is one.
- You can't approve requests. Managers answer them outside this chat.
What you remember:
- You remember things about the employee from earlier conversations, and each request tells you what they are.
Use them when they help, so the employee doesn't have to repeat themselves. When you raise a ticket, include
what you remember that helps the IT team, such as where the employee works or how they like to be contacted.
- A preference you remember says what the employee would like, not what Dewiride will do. When you add one to
a ticket, say that you added it, and don't promise how or when the IT team will contact them.
- When the employee tells you something lasting about themselves that will help with later IT requests, such as
where they work, which devices they use or how they like to be contacted, save it with remember_about_me as
one short sentence, and tell them what you remembered.
- Never remember passwords, codes or other secrets, health or money matters, or anything about other people.
- When the employee asks what you remember, tell them. When they ask you to forget something, call forget_memory
for each memory it covers, and tell them what you forgot. Never show the memories' IDs.
Secrets:
- Never ask for passwords, MFA codes or other secrets.
- Dewiride removes passwords and BitLocker recovery keys from messages and tool results before you see them, and
writes [password removed] or [recovery key removed] where they were. You never see the secret itself.
- When the employee's message has one, tell them it was removed before it reached you and that they should never
share secrets in the chat. If it was a password, tell them to change it, because they wrote it down, and offer
to reset it.
- When a tool result has one, such as a password in a ticket, tell them that a secret in it was removed. If it was
a password, tell them to change it and offer to reset it.
Rules you always follow:
- Help only with IT topics. Politely decline anything else and say what you can help with.
- You can look things up, raise tickets, ask for software and reset the employee's own password, but you cannot
change, close or reassign tickets, approve requests, or change anything else. When a problem needs hands-on
help, offer to raise a ticket.
""";
}
Step 14: Add the Managers' Endpoints
Managers answer through two endpoints. Create src/Dewiride.ServiceDesk.Api/ApprovalEndpoints.cs:
using Dewiride.ServiceDesk.Agent;
using Dewiride.ServiceDesk.Agent.Approvals;
using Microsoft.AspNetCore.Http.HttpResults;
namespace Dewiride.ServiceDesk.Api;
/// <summary>
/// The approvals API, for managers: the software requests waiting for their answer, and the answer itself.
/// A manager only ever sees and answers the requests sent to them.
/// </summary>
internal static class ApprovalEndpoints
{
public static IEndpointRouteBuilder MapApprovalEndpoints(this IEndpointRouteBuilder app)
{
RouteGroupBuilder approvals = app.MapGroup("/api/approvals")
.RequireAuthorization("ServiceDeskUser");
approvals.MapGet("/", GetWaitingAsync);
approvals.MapPost("/{number}", AnswerAsync);
return app;
}
// GET /api/approvals: the requests waiting for the signed-in manager's answer, oldest first.
private static async Task<Ok<IReadOnlyList<SoftwareApproval>>> GetWaitingAsync(
SoftwareApprovals softwareApprovals,
ICurrentEmployee currentEmployee,
CancellationToken cancellationToken) =>
TypedResults.Ok(await softwareApprovals.GetWaitingForAsync(SignedInId(currentEmployee), cancellationToken));
// POST /api/approvals/{number}: the signed-in manager approves or rejects one of their requests.
private static async Task<Results<Ok<SoftwareApproval>, ProblemHttpResult>> AnswerAsync(
string number,
AnswerApprovalRequest request,
SoftwareApprovals softwareApprovals,
ICurrentEmployee currentEmployee,
CancellationToken cancellationToken)
{
if (request.Approved is not bool approved)
{
return TypedResults.Problem("Set approved to true or false.",
statusCode: StatusCodes.Status400BadRequest, title: "The answer wasn't recorded.");
}
ApprovalAnswerResult result = await softwareApprovals.AnswerAsync(
SignedInId(currentEmployee), number, approved, request.Comment, cancellationToken);
return result.Outcome switch
{
ApprovalAnswerOutcome.Answered => TypedResults.Ok(result.Approval!),
// The same answer for a number that doesn't exist and one sent to another manager:
// the API never says whether someone else's request exists.
ApprovalAnswerOutcome.NotFound => TypedResults.Problem(result.Problem,
statusCode: StatusCodes.Status404NotFound, title: "No such request."),
ApprovalAnswerOutcome.AlreadyAnswered => TypedResults.Problem(result.Problem,
statusCode: StatusCodes.Status409Conflict, title: "The request was already answered."),
_ => TypedResults.Problem(result.Problem,
statusCode: StatusCodes.Status400BadRequest, title: "The answer wasn't recorded."),
};
}
// The policy above lets only signed-in users in, so there is always one here.
private static string SignedInId(ICurrentEmployee currentEmployee) =>
currentEmployee.Id ?? throw new InvalidOperationException("No one is signed in.");
}
/// <summary>A manager's answer: approved, true or false, and an optional comment for the employee.</summary>
internal sealed record AnswerApprovalRequest(bool? Approved, string? Comment);
MapGroup("/api/approvals")puts both endpoints under one path, with one rule:RequireAuthorization("ServiceDeskUser"), the policy from Part 8. Every caller needs a token for the API.- The manager is the signed-in user. Both endpoints take the manager's ID from
ICurrentEmployee, never from the request, so a manager only ever sees and answers the requests sent to them. GET /api/approvalsreturns the requests waiting for the signed-in manager's answer, oldest first.POST /api/approvals/{number}takes the answer as JSON:approvedand an optionalcomment.Approvedis abool?, not abool. A plainboolwould turn a body withoutapprovedintofalse, and a forgotten field would reject a request. Withbool?it'snull, and the API answers Set approved to true or false.- Each outcome has its own status code:
200 OKwith the request,404 Not Foundfor a number the manager doesn't have,409 Conflictfor a request that was already answered, and400 Bad Requestfor an answer that can't be recorded, such as a comment that's too long. The errors are problem details, the standard JSON for API errors, as in Part 19's tickets endpoint (How to Return Problem Details Errors in ASP.NET Core).Results<Ok<SoftwareApproval>, ProblemHttpResult>lists the possible responses in the method's type.
In Program.cs, map the endpoints after the tickets':
app.MapTicketEndpoints();
app.MapApprovalEndpoints();
The comment about enums now covers the whole API, because the requests' status is an enum too, so the JSON says "Pending" rather than 0. The complete file:
using System.Text.Json.Serialization;
using Dewiride.ServiceDesk.Agent;
using Dewiride.ServiceDesk.Agent.Approvals;
using Dewiride.ServiceDesk.Agent.Memory;
using Dewiride.ServiceDesk.Agent.Sessions;
using Dewiride.ServiceDesk.Api;
using Microsoft.Agents.AI.Hosting;
using Microsoft.Agents.AI.Hosting.AGUI.AspNetCore;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.Identity.Web;
var builder = WebApplication.CreateBuilder(args);
// Logs, traces and metrics, sent with OpenTelemetry wherever the OTLP settings point.
builder.AddServiceDeskObservability();
// Health checks answer one question: "is this API up and running?"
builder.Services.AddHealthChecks();
// Sign-in: accept only access tokens that Microsoft Entra ID issued for this API.
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddMicrosoftIdentityWebApi(builder.Configuration.GetSection("AzureAd"));
// Permission: the token must also carry the access_as_user scope.
builder.Services.AddAuthorization(options =>
options.AddPolicy("ServiceDeskUser", policy => policy.RequireScope("access_as_user")));
// Every conversation belongs to the person who signed in: their object ID (the oid claim)
// becomes part of each conversation's key in the session store.
builder.Services.AddHttpContextAccessor();
builder.Services.UseClaimsBasedAgentIsolation(new ClaimsIdentityAgentIsolationKeyProviderOptions
{
ClaimType = ClaimConstants.ObjectId,
});
// The agent's tools look up the signed-in employee's own records, by the same object ID.
builder.Services.AddSingleton<ICurrentEmployee, SignedInEmployee>();
// The Dewiride Service Desk agent, and AG-UI: the protocol that streams its answers.
// Every conversation is kept in Azure Cosmos DB, separately for each user, so it
// survives restarts and every copy of the API sees it. What the agent remembers about
// each employee is kept there too, and lasts from one conversation to the next, and so are
// software requests and the checkpoints of the workflow runs that wait for their managers.
var serviceDeskAgent = builder.AddServiceDeskAgent()
.WithCosmosDbSessionStore()
.WithCosmosDbEmployeeMemory()
.WithCosmosDbApprovals();
builder.Services.AddAGUIServer();
// The API's JSON uses names for enums, such as "Incident" and "Medium", not numbers.
builder.Services.ConfigureHttpJsonOptions(options =>
options.SerializerOptions.Converters.Add(new JsonStringEnumConverter()));
var app = builder.Build();
app.MapHealthChecks("/health");
app.MapAGUIServer(serviceDeskAgent, "/api/agents/service-desk")
.RequireAuthorization("ServiceDeskUser");
app.MapTicketEndpoints();
app.MapApprovalEndpoints();
app.Run();
The requests in the .http file
Add these requests at the end of src/Dewiride.ServiceDesk.Api/Dewiride.ServiceDesk.Api.http:
# Ask for an app that needs your manager's approval: the agent sends the request to your manager
# and gives you its number.
POST {{baseUrl}}/api/agents/service-desk
Authorization: Bearer {{$dotenv AGENT_API_TOKEN}}
Content-Type: application/json
Accept: text/event-stream
{
"threadId": "thread-24",
"runId": "run-1",
"messages": [
{
"id": "message-1",
"role": "user",
"content": "I need Microsoft Visio to draw the network diagrams for the new office. Can I get it?"
}
]
}
###
# As the manager, with the manager's token: the requests waiting for your answer, oldest first.
GET {{baseUrl}}/api/approvals
Authorization: Bearer {{$dotenv MANAGER_API_TOKEN}}
###
# As the manager: approve a request. Paste its number from the list in place of PASTE-THE-APPROVAL-NUMBER.
POST {{baseUrl}}/api/approvals/PASTE-THE-APPROVAL-NUMBER
Authorization: Bearer {{$dotenv MANAGER_API_TOKEN}}
Content-Type: application/json
{
"approved": true,
"comment": "Approved for the office move."
}
###
# Back as the employee, in the same conversation: ask what happened to the request.
POST {{baseUrl}}/api/agents/service-desk
Authorization: Bearer {{$dotenv AGENT_API_TOKEN}}
Content-Type: application/json
Accept: text/event-stream
{
"threadId": "thread-24",
"runId": "run-2",
"parentRunId": "run-1",
"messages": [
{
"id": "message-2",
"role": "user",
"content": "Has my Visio request been answered yet?"
}
]
}
###
# Ask for another app, in a new conversation.
POST {{baseUrl}}/api/agents/service-desk
Authorization: Bearer {{$dotenv AGENT_API_TOKEN}}
Content-Type: application/json
Accept: text/event-stream
{
"threadId": "thread-25",
"runId": "run-1",
"messages": [
{
"id": "message-1",
"role": "user",
"content": "Can I get Adobe Acrobat Pro? I need to fill in and sign PDF contracts from our suppliers."
}
]
}
###
# As the manager: reject it, with a comment for the employee. Paste the new request's number.
POST {{baseUrl}}/api/approvals/PASTE-THE-APPROVAL-NUMBER
Authorization: Bearer {{$dotenv MANAGER_API_TOKEN}}
Content-Type: application/json
{
"approved": false,
"comment": "Microsoft Edge can fill in and sign PDF forms. Please try it first."
}
###
# As the manager: answer the same request again. The API answers 409 Conflict: a request is answered only once.
POST {{baseUrl}}/api/approvals/PASTE-THE-APPROVAL-NUMBER
Authorization: Bearer {{$dotenv MANAGER_API_TOKEN}}
Content-Type: application/json
{
"approved": true
}
###
# As the employee, with your own token: try to approve your own request. The API answers 404 Not Found:
# a request is found only by the manager it was sent to.
POST {{baseUrl}}/api/approvals/PASTE-THE-APPROVAL-NUMBER
Authorization: Bearer {{$dotenv AGENT_API_TOKEN}}
Content-Type: application/json
{
"approved": true
}
- Two tokens. The employee's requests use
AGENT_API_TOKEN, your own account, and the manager's useMANAGER_API_TOKEN, Test Manager's. Both come from the.envfile of Step 5. PASTE-THE-APPROVAL-NUMBERis where you paste a request's number, such asAPR-7ACD7BD9, before you send that request.- The last request uses your own token to answer your own request, which the API mustn't allow.
Step 15: Ask for Visio, Restart the API and Approve
Build the solution from the DewirideServiceDesk folder:
dotnet build
Restore complete (0.7s)
Dewiride.ServiceDesk.Agent net10.0 succeeded (1.9s) → src/Dewiride.ServiceDesk.Agent/bin/Debug/net10.0/Dewiride.ServiceDesk.Agent.dll
Dewiride.ServiceDesk.Api net10.0 succeeded (0.4s) → src/Dewiride.ServiceDesk.Api/bin/Debug/net10.0/Dewiride.ServiceDesk.Api.dll
Build succeeded in 3.1s
If more than an hour has passed since Step 5, run its commands again: both tokens last about an hour. Then start the API as in Part 18:
- VS Code
- Visual Studio
In a terminal, in the src/Dewiride.ServiceDesk.Api folder, run:
dotnet run
Make sure http is selected in the drop-down list next to the green Start button (▶), with Dewiride.ServiceDesk.Api as the startup project, and press Ctrl+F5 (Debug → Start Without Debugging).
Ask for Visio
In the .http file, send the request under Ask for an app that needs your manager's approval. The stream shows the agent calling request_software with these arguments:
{"software":"Microsoft Visio","reason":"To draw network diagrams for the new office."}
The model wrote Microsoft Visio, not the catalog's full name. No app is called exactly that, but only one app's name contains it, so FindTitle found Microsoft Visio Plan 2. The agent's answer, at the end of the stream:
Your request was sent.
Request: APR-7ACD7BD9
App: Microsoft Visio Plan 2
Approver: Test Manager
Status: Pending
The licence will be assigned if your manager approves the request.
The API's terminal shows the audit entry:
info: Dewiride.ServiceDesk.Audit[11]
Employee 00000000-0000-0000-0000-000000000000 asked for Microsoft Visio Plan 2 in request APR-7ACD7BD9. It waits for their manager's answer.
See what's waiting in Cosmos DB
Open your Cosmos DB account in the Azure portal, select Data Explorer, expand servicedesk, then approvals, and select Items. How to View, Edit and Delete Items in Azure Cosmos DB Data Explorer shows the way around Data Explorer. Select the request to see it:

approverIdandrequesterIdare SHA-256 hashes of the two object IDs, like the employee IDs in the memories of Part 16. The manager's hash is the partition key, so the manager's list is a read of one partition.statusisPending, with no answer, time or comment yet.sessionIdandcheckpointIdsay where the run waits: the session its checkpoints are kept under, and the checkpoint that holds the question.
Now open checkpoints and select Items. The run saved two checkpoints, both under the request's sessionId. Select the one whose id is the request's checkpointId:

parentIdis the first checkpoint, saved after SubmitRequest. Each checkpoint names the one before it.committedAtis the time the store wrote, with ten-millionths of a second.valueis the checkpoint itself, as Agent Framework saved it. It starts withworkflow, the shape of the workflow: its steps and edges. A run can only continue in a workflow with the same shape, which is why a checkpoint carries it.
Select the arrow next to "workflow" to fold it, and the rest of the checkpoint comes into view:

outstandingRequestsis the manager's question: the request port it waits at,ManagerApproval, the types of its question and answer, and the question itself. This is what comes back as aRequestInfoEventwhen the run is restored.stateDatais the workflow's shared state. SubmitRequest saved the employee's request there, under the scopesoftware-request, for ApplyDecision to read.
A checkpoint holds everything the run holds, here the employee's object ID and why they need the app. Microsoft's checkpoint guide is clear about who may see it: Only authorized services and users should have read or write access to checkpoint data. In this solution that's the data role from Step 2, scoped to the one container.
Restart the API
Restart the API: press Ctrl+C in its terminal and run dotnet run again (in Visual Studio, stop it and press Ctrl+F5). Nothing of the run is left in memory now. Only the two Cosmos DB containers know that APR-7ACD7BD9 is waiting.
Approve the request as the manager
Send the request under As the manager, with the manager's token. It lists what waits for Test Manager:
[
{
"number": "APR-7ACD7BD9",
"software": "Microsoft Visio Plan 2",
"requestedBy": "Azure User",
"approver": "Test Manager",
"reason": "To draw network diagrams for the new office.",
"status": "Pending",
"requestedAt": "2026-12-03T10:28:33.916988+00:00",
"decidedAt": null,
"comment": null
}
]
Paste the request's number in place of PASTE-THE-APPROVAL-NUMBER in the request under As the manager: approve a request, and send it:
{
"number": "APR-7ACD7BD9",
"software": "Microsoft Visio Plan 2",
"requestedBy": "Azure User",
"approver": "Test Manager",
"reason": "To draw network diagrams for the new office.",
"status": "Approved",
"requestedAt": "2026-12-03T10:28:33.916988+00:00",
"decidedAt": "2026-12-03T10:35:24.484401+00:00",
"comment": "Approved for the office move."
}
The answer was carried out by a run that started in another process: the API loaded the waiting checkpoint, gave the question its answer, and ApplyDecision assigned the licence. The API's terminal shows the audit entry:
info: Dewiride.ServiceDesk.Audit[12]
Employee 44444444-4444-4444-4444-444444444444 approved request APR-7ACD7BD9, and the Microsoft Visio Plan 2 licence was assigned to the employee who asked for it.
In Data Explorer, close the checkpoints tab and open checkpoints › Items again. The run has finished, so its checkpoints are gone:

On the approvals tab, select Refresh above the list and then the request. It's Approved, with the time of the answer and the manager's comment:

The request keeps sessionId and checkpointId after the answer. They point to nothing now, but they record which run carried the answer out.
Ask the agent
Back as the employee, send the request under Back as the employee, in the same conversation. The agent calls get_my_software_requests and answers:
Yes. Your Microsoft Visio Plan 2 request APR-7ACD7BD9 was approved by Test Manager.
Comment: “Approved for the office move.”
Step 16: Reject a Request, Answer It Twice and Answer Your Own
Send the request under Ask for another app, in a new conversation. It's for Adobe Acrobat Pro:
Your request for Adobe Acrobat Pro has been sent.
Request number: APR-01723B70
Approver: Test Manager
Status: Pending
The licence will be assigned if your manager approves it.
The API was warm this time, and the run's two checkpoints were saved 0.28 seconds apart: their committedAt values are 2026-12-03T10:38:11.8008030Z and 2026-12-03T10:38:12.0776400Z.
Paste the new number into the next three requests. The first rejects it, with a comment for the employee:
{
"number": "APR-01723B70",
"software": "Adobe Acrobat Pro",
"requestedBy": "Azure User",
"approver": "Test Manager",
"reason": "To fill in and sign PDF contracts from suppliers.",
"status": "Rejected",
"requestedAt": "2026-12-03T10:38:12.34856+00:00",
"decidedAt": "2026-12-03T10:38:25.558466+00:00",
"comment": "Microsoft Edge can fill in and sign PDF forms. Please try it first."
}
info: Dewiride.ServiceDesk.Audit[13]
Employee 44444444-4444-4444-4444-444444444444 rejected request APR-01723B70 for Adobe Acrobat Pro.
A rejection goes through the same workflow: ApplyDecision gets approved: false, assigns nothing and writes the audit entry. The second request answers the same request again:
{
"type": "https://tools.ietf.org/html/rfc9110#section-15.5.10",
"title": "The request was already answered.",
"status": 409,
"detail": "Request APR-01723B70 was already rejected."
}
A request is answered once. The status check in AnswerAsync stopped this one, and if two answers ever arrive at the same moment, the ETag check from Step 8 stops the second. The last request sends an answer with your own token, the employee's:
{
"type": "https://tools.ietf.org/html/rfc9110#section-15.5.5",
"title": "No such request.",
"status": 404,
"detail": "No request APR-01723B70 is waiting for your answer."
}
Your own request isn't in your partition: it's in your manager's. So the API can't find it for you, and it answers as it would for a number that doesn't exist. Nobody can approve their own request, or learn whether someone else's request number exists.
Step 17: Watch a Request Wait in the Aspire Dashboard
In the Aspire Dashboard, open Traces. A request to the agent is a POST /api/agents/service-desk trace, and a manager's answer is a POST /api/approvals/{number} trace. Open the trace of a request in which the agent called request_software:

execute_tool request_softwareis the tool call, and the run sits inside it:workflow.session, theninvoke_workflow software-approval.executor.process SubmitRequesttook under a millisecond. Thecreate_item checkpointsafter it is the first checkpoint, saved at the end of the first superstep.executor.process ManagerApprovalis the request port. It took 0.1 milliseconds to send the question out, and the secondcreate_item checkpointssaved the checkpoint that holds the question.- There's no
ApplyDecision. The run stopped at the question, with nothing left to do until the manager answers. create_item approvalscomes after the run, becauseRequestAsyncsaves the request last. Then the model writes its answer to the employee, andupsert_item sessionssaves the conversation, as in Part 15.
The red mark on the first HTTP POST under query_items memories is the Cosmos DB SDK giving up on a slow call after one second and trying again, as in Part 18. The second try succeeded.
Now open the trace of a manager's answer:

read_item approvalsandpatch_item approvals:AnswerAsyncfinds the request and records the answer, with the ETag check from Step 8.read_item checkpointsloads the checkpoint where the run waits. In thequery_items checkpointsafter it, Agent Framework reads the list of the session's checkpoints, through the store'sRetrieveIndexAsyncfrom Step 10.- Two
invoke_workflow software-approvalspans. The first, 5 microseconds long, has nothing under it: the restored run had no message to deliver, only a question without an answer. The second starts whenResumeAsyncgives the question its answer. executor.process ManagerApprovalpasses the answer on, and acreate_item checkpointsends that superstep.executor.process ApplyDecisionassigns the licence and writes the audit entry in about 2 milliseconds, and anothercreate_item checkpointsends the last superstep.query_items checkpointsand fourdelete_item checkpoints:DeleteSessionAsynclists the run's checkpoints and deletes them, two from the request and two from the answer.
The workflow's steps took under 3 milliseconds together. The rest of the 6.75 seconds is calls to Cosmos DB, so the cost of a request that waits is in where it waits, not in the workflow.
Every Cosmos DB span also says what its call cost. Select one, such as the second create_item checkpoints of a request:

azure.cosmosdb.request.request_charge is the request units the call used: 9 for this checkpoint, with value left out of the index. db.response.status_code 201 means the item was created. The figures in What This Part Costs are these charges added up.
Step 18: Ask from the Chat App
The chat app needs no change: the new tools work there as they do in the .http file. With the API running, run npm run dev in the web/agent-chat-ui folder in a second terminal, sign in and ask for an app. I asked for Visio again. The sample catalog doesn't check which licences an employee already has, so a second request goes to the manager like the first, and the agent's answer is the one at the top of this page.
Approve it as in Step 15: paste its number into the request under As the manager: approve a request and send it. Then ask about it in the same chat:

The manager's comment was nowhere in the conversation, so the agent looked the request up before it answered. The employee never left the chat, and the manager never opened it.
Your Solution Now Looks Like This
DewirideServiceDesk/
├── src/
│ ├── Dewiride.ServiceDesk.Agent/
│ │ ├── Approvals/ ← new
│ │ │ ├── ApplyDecisionExecutor.cs ← carries out the answer
│ │ │ ├── ApprovalAnswerResult.cs
│ │ │ ├── ApprovalJsonContext.cs ← this app's types in checkpoints
│ │ │ ├── ApprovalMessages.cs ← the messages between the steps
│ │ │ ├── ApprovalStatus.cs
│ │ │ ├── CosmosApprovalExtensions.cs ← the two containers
│ │ │ ├── CosmosApprovalStore.cs ← the requests in Cosmos DB
│ │ │ ├── CosmosDbCheckpointStore.cs ← the checkpoints in Cosmos DB
│ │ │ ├── IApprovalStore.cs
│ │ │ ├── IWorkflowCheckpointStore.cs
│ │ │ ├── NewSoftwareApproval.cs
│ │ │ ├── SoftwareApproval.cs ← a request, as the API returns it
│ │ │ ├── SoftwareApprovalExtensions.cs ← registers the workflow and SoftwareApprovals
│ │ │ ├── SoftwareApprovalWorkflow.cs ← the graph
│ │ │ ├── SoftwareApprovals.cs ← starts the runs and continues them
│ │ │ ├── SoftwareRequestResult.cs
│ │ │ ├── StoredApproval.cs
│ │ │ └── SubmitRequestExecutor.cs ← keeps the request and asks
│ │ ├── Auditing/
│ │ │ └── ServiceDeskAudit.cs ← requested, approved and rejected entries
│ │ ├── Systems/
│ │ │ ├── Employee.cs ← new
│ │ │ ├── EmployeeDirectoryOptions.cs ← new
│ │ │ ├── IEmployeeDirectory.cs ← new
│ │ │ ├── ISoftwareCatalog.cs ← new
│ │ │ ├── SampleEmployeeDirectory.cs ← new: the employees from the settings
│ │ │ ├── SampleSoftwareCatalog.cs ← new: three paid apps
│ │ │ └── SoftwareTitle.cs ← new
│ │ ├── CosmosDbOptions.cs ← the two container names
│ │ ├── ServiceDeskAgentExtensions.cs ← step 5: software requests
│ │ ├── ServiceDeskInstructions.cs ← software requests
│ │ └── ServiceDeskTools.cs ← request_software, get_my_software_requests
│ └── Dewiride.ServiceDesk.Api/
│ ├── .env ← the manager's token too
│ ├── ApprovalEndpoints.cs ← new: GET and POST /api/approvals
│ ├── appsettings.json ← the containers and the directory
│ ├── Dewiride.ServiceDesk.Api.http ← eight new requests
│ └── Program.cs ← WithCosmosDbApprovals, MapApprovalEndpoints
└── web/
└── agent-chat-ui/ ← unchanged
Cleanup (Only If You Stop Here)
Later parts keep using the software requests. If you are stopping here, delete the account as described in Part 15: the approvals and checkpoints containers and their role assignments go with it.
To keep the account and remove only this part's containers, delete them:
az cosmosdb sql container delete --account-name cosmos-maf-servicedesk-4224 --resource-group rg-maf-servicedesk --database-name servicedesk --name approvals --yes
az cosmosdb sql container delete --account-name cosmos-maf-servicedesk-4224 --resource-group rg-maf-servicedesk --database-name servicedesk --name checkpoints --yes
--yes skips the confirmation. The commands work the same in bash, zsh and PowerShell.
Delete the Test Manager user, as How to Delete a User in Microsoft 365 shows, and the manager's sign-in folder:
- bash / zsh
- PowerShell
rm -rf ~/.azure-test-manager
Remove-Item -Recurse -Force (Join-Path $HOME ".azure-test-manager")
The chat requests saved their conversations in Cosmos DB and Foundry, as in Part 18; clean them up as described in Part 16.
Common Mistakes
| Mistake | What happens | Do this instead |
|---|---|---|
| Continuing a run from its session's latest checkpoint | After a failed answer, the latest checkpoint holds no question, and every later answer fails with The workflow run of APR-… isn't waiting for the manager. | Keep the checkpoint where the run waits with the request, and always continue from it (Step 11) |
| Saving the request before its run starts | A manager can answer a request that no run is waiting to carry out | Start the run first, and save the request with its waiting checkpoint last (Step 11) |
| Taking the checkpoint to load from the caller | A caller chooses which saved state the API loads, and a checkpoint is trusted data | Load only the checkpoint stored with the request (Step 11) |
Leaving one of the app's types out of ApprovalJsonContext | Nothing shows while reflection-based serialization is on; in a trimmed or native AOT app, the run fails at its first checkpoint with No JSON type info is available for type … | Add a [JsonSerializable] line for every type in the messages and the state (Step 10) |
Keeping the default indexing policy on checkpoints | Every checkpoint write and delete costs 38 to 45 RU instead of 8 or 9 | Leave /value/* out of the index (Step 1) |
Ordering checkpoints by _ts | Two checkpoints saved in the same second come back in any order, and the wrong one can be resumed | Save the time to the ten-millionth of a second and order by it (Step 10) |
| Letting the model say who approves | The model could send a request to anyone | Take the manager from the company directory (Step 11) |
| Taking the manager from the request | Anyone with a token could answer anyone's requests | Take the manager from the signed-in user (Step 14) |
Signing the manager in without AZURE_CONFIG_DIR | The manager's sign-in becomes the active one, and your own Azure CLI commands use it too | Give the manager a configuration folder of their own (Step 4) |
Troubleshooting
| Symptom | Likely cause | Fix |
|---|---|---|
| The agent says the directory has no record of you | Your object ID isn't the first Id in EmployeeDirectory | Check it against az ad signed-in-user show (Steps 3 and 6) |
| The agent says there's no manager who can approve the request | Your ManagerId is empty, or isn't the Id of another employee | Put the manager's object ID in both places (Step 6) |
| The agent says the catalog has no single app with that name | The name matches no app, or more than one | Name the app as the catalog does (Step 6) |
401 Unauthorized from any request in the .http file | A token has expired | Run Step 5's commands again |
404 No request APR-… is waiting for your answer. when you answer | The number is wrong, or the answer went out with your own token | Copy the number from GET /api/approvals, and answer with MANAGER_API_TOKEN (Step 14) |
409 Request APR-… was already approved. | The request was answered before | Nothing to fix: a request is answered once (Step 16) |
500 and The workflow run of APR-… didn't finish. in the API's terminal | A step of the run failed | Read the Step … of approval workflow run … failed entry above it; the request is Pending again, so answer it again once it's fixed (Step 11) |
Request blocked by Auth in the API's terminal, for approvals or checkpoints | The data role is missing on that container (Fixed) | Give your account the role on it (Step 2) |
| You don't have access to this, error code 53003, when the manager signs in | Your tenant blocks the device code flow | Sign in with the browser (Step 4) |
Frequently Asked Questions
Why not use the tool approval from Part 13?
Tool approval asks the person in the chat, while the agent's run waits for the answer inside the conversation. A manager's approval comes from someone else, outside the chat, maybe days later, after the employee has closed the page and the API has restarted. A workflow with a request port and checkpoints doesn't need anyone to stay connected: the run waits in Cosmos DB, and whoever answers continues it.
How long can a request wait?
Up to a year. Both containers have a time to live of 365 days, so a request that nobody answers disappears after a year, with its checkpoints. Until then, the manager can answer it at any time, from any copy of the API.
Can a manager answer from Teams or by email?
The API doesn't care where the answer comes from: anything that can call POST /api/approvals/{number} with the manager's token can answer. Part 23 brings the agent to Microsoft Teams.
Why are the checkpoints deleted after the answer?
A finished run never continues again, and its checkpoints hold the employee's request, including their object ID. Deleting them keeps nothing longer than it's needed. The request itself stays in approvals, so the employee can still ask about it.
Does a waiting request cost anything?
Only its storage: the item and two checkpoints of about 6 KB each. Nothing reads or writes them while the request waits, so it uses no request units until the manager lists or answers it.
Conclusion
The service desk can now ask a person and wait. request_software checks the request, finds the employee's manager in the company directory and starts a run of the software approval workflow: SubmitRequest keeps the request in the workflow's state, and the ManagerApproval request port asks the question and stops the run. The run's checkpoints, in a Cosmos DB store of its own with value left out of the index, keep it waiting for days and through restarts, and the request itself waits in the manager's partition of approvals, with the checkpoint where its run stopped. When the manager answers, the API records the answer once, loads that checkpoint, gives the question its answer, and ApplyDecision assigns the licence and writes the audit entry. The employee asks the agent, and the agent knows.
Next: Part 21: Agent Harness — Weekly Problem Report (coming soon). The service desk answers one employee at a time. Part 21 adds an agent that works on its own: once a week it reads the tickets, finds the problems behind them and writes a report.
Additional Resources
- Human-in-the-loop workflows — request ports,
RequestInfoEventand responses. - Checkpoints — when checkpoints are saved, restoring and resuming, and who may read them.
- Indexing policies in Azure Cosmos DB — included and excluded paths.
- Transactions and optimistic concurrency control — ETags and conditional updates in Azure Cosmos DB.
- Partial document update — patching single properties of an item.
- Tips for using the Azure CLI successfully —
AZURE_CONFIG_DIRand other settings.