mirror of
https://github.com/microsoft/agent-framework.git
synced 2026-06-16 21:04:09 +08:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3d41c0ad63 | ||
|
|
1e743b332b | ||
|
|
6daa941cbd | ||
|
|
c3522ac8c6 | ||
|
|
708c0a4ab8 | ||
|
|
2bb7ab5c44 | ||
|
|
c187cccf78 | ||
|
|
ecc90bcf78 | ||
|
|
cfd3dfe40b | ||
|
|
3b6a4574eb | ||
|
|
4409b00b86 | ||
|
|
818ae65b77 | ||
|
|
d8619b93ad | ||
|
|
ae57616b32 | ||
|
|
41d6c61f81 | ||
|
|
dfc3079d68 | ||
|
|
939d4d0153 | ||
|
|
fe09f13adb | ||
|
|
4ad96b64e7 | ||
|
|
e3875f2c91 | ||
|
|
9199c84d42 | ||
|
|
0bbedc4fa2 | ||
|
|
18d7a46a54 | ||
|
|
9d8c3f8cb7 | ||
|
|
9faf52de4f | ||
|
|
d2ce0e9087 | ||
|
|
0557b5782b | ||
|
|
eb709d8fc9 | ||
|
|
226c004b53 | ||
|
|
3aae3cb9de |
@@ -38,6 +38,8 @@ jobs:
|
||||
dotnetChanges: ${{ steps.filter.outputs.dotnet }}
|
||||
cosmosDbChanges: ${{ steps.filter.outputs.cosmosdb }}
|
||||
foundryHostingChanges: ${{ steps.filter.outputs.foundryHosting }}
|
||||
functionsChanged: ${{ steps.filter.outputs.functions }}
|
||||
coreChanged: ${{ steps.filter.outputs.core }}
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
- uses: dorny/paths-filter@v3
|
||||
@@ -60,9 +62,28 @@ jobs:
|
||||
- 'dotnet/src/Microsoft.Agents.AI.Workflows/**'
|
||||
- 'dotnet/tests/Foundry.Hosting.IntegrationTests/**'
|
||||
- 'dotnet/tests/Foundry.Hosting.IntegrationTests.TestContainer/**'
|
||||
- 'dotnet/samples/04-hosting/FoundryHostedAgents/responses/Hosted-AzureSearchRag/**'
|
||||
- 'dotnet/Directory.Packages.props'
|
||||
- 'dotnet/tests/Foundry.Hosting.IntegrationTests/scripts/it-build-image.ps1'
|
||||
- '.github/workflows/dotnet-build-and-test.yml'
|
||||
functions:
|
||||
- 'dotnet/src/Microsoft.Agents.AI.DurableTask/**'
|
||||
- 'dotnet/src/Microsoft.Agents.AI.Hosting.AzureFunctions/**'
|
||||
- 'dotnet/tests/Microsoft.Agents.AI.DurableTask.IntegrationTests/**'
|
||||
- 'dotnet/tests/Microsoft.Agents.AI.Hosting.AzureFunctions.IntegrationTests/**'
|
||||
- '.github/actions/azure-functions-integration-setup/**'
|
||||
- '.github/workflows/dotnet-build-and-test.yml'
|
||||
core:
|
||||
- 'dotnet/src/Microsoft.Agents.AI/**'
|
||||
- 'dotnet/src/Microsoft.Agents.AI.Abstractions/**'
|
||||
- 'dotnet/src/Microsoft.Agents.AI.OpenAI/**'
|
||||
- 'dotnet/src/Microsoft.Agents.AI.Workflows/**'
|
||||
- 'dotnet/src/Microsoft.Agents.AI.Workflows.Generators/**'
|
||||
- 'dotnet/eng/scripts/New-FilteredSolution.ps1'
|
||||
- 'dotnet/tests/Directory.Build.props'
|
||||
- 'dotnet/Directory.Packages.props'
|
||||
- 'dotnet/global.json'
|
||||
- '.github/workflows/dotnet-build-and-test.yml'
|
||||
# run only if 'dotnet' files were changed
|
||||
- name: dotnet tests
|
||||
if: steps.filter.outputs.dotnet == 'true'
|
||||
@@ -210,10 +231,11 @@ jobs:
|
||||
Verbose = $true
|
||||
}
|
||||
./dotnet/eng/scripts/New-FilteredSolution.ps1 @commonArgs `
|
||||
-TestProjectNameFilter "*UnitTests*" `
|
||||
-TestProjectNameIncludeFilter "*UnitTests*" `
|
||||
-OutputPath dotnet/filtered-unit.slnx
|
||||
./dotnet/eng/scripts/New-FilteredSolution.ps1 @commonArgs `
|
||||
-TestProjectNameFilter "*IntegrationTests*" `
|
||||
-TestProjectNameIncludeFilter "*IntegrationTests*" `
|
||||
-TestProjectNameExcludeFilter "*DurableTask.IntegrationTests*","*AzureFunctions.IntegrationTests*" `
|
||||
-OutputPath dotnet/filtered-integration.slnx
|
||||
|
||||
- name: Run Unit Tests
|
||||
@@ -255,14 +277,6 @@ jobs:
|
||||
tenant-id: ${{ secrets.AZURE_TENANT_ID }}
|
||||
subscription-id: ${{ secrets.AZURE_SUBSCRIPTION_ID }}
|
||||
|
||||
# This setup action is required for both Durable Task and Azure Functions integration tests.
|
||||
# We only run it on Ubuntu since the Durable Task and Azure Functions features are not available
|
||||
# on .NET Framework (net472) which is what we use the Windows runner for.
|
||||
- name: Set up Durable Task and Azure Functions Integration Test Emulators
|
||||
if: github.event_name != 'pull_request' && matrix.integration-tests && matrix.os == 'ubuntu-latest'
|
||||
uses: ./.github/actions/azure-functions-integration-setup
|
||||
id: azure-functions-setup
|
||||
|
||||
- name: Run Integration Tests
|
||||
shell: pwsh
|
||||
working-directory: dotnet
|
||||
@@ -340,7 +354,6 @@ jobs:
|
||||
runs-on: ubuntu-latest
|
||||
environment: integration
|
||||
env:
|
||||
targetFramework: net10.0
|
||||
configuration: Release
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
@@ -357,31 +370,15 @@ jobs:
|
||||
with:
|
||||
global-json-file: ${{ github.workspace }}/dotnet/global.json
|
||||
|
||||
- name: Generate test solution (no samples)
|
||||
shell: pwsh
|
||||
run: |
|
||||
./dotnet/eng/scripts/New-FilteredSolution.ps1 `
|
||||
-Solution dotnet/agent-framework-dotnet.slnx `
|
||||
-TargetFramework $env:targetFramework `
|
||||
-Configuration $env:configuration `
|
||||
-ExcludeSamples `
|
||||
-OutputPath dotnet/filtered.slnx `
|
||||
-Verbose
|
||||
|
||||
- name: Generate Foundry hosted IT filtered solution
|
||||
shell: pwsh
|
||||
run: |
|
||||
./dotnet/eng/scripts/New-FilteredSolution.ps1 `
|
||||
-Solution dotnet/filtered.slnx `
|
||||
-TargetFramework $env:targetFramework `
|
||||
-Configuration $env:configuration `
|
||||
-TestProjectNameFilter "Foundry.Hosting.IntegrationTests*" `
|
||||
-OutputPath dotnet/filtered-foundry-hosted.slnx `
|
||||
-Verbose
|
||||
|
||||
# Build the test csproj directly instead of a filtered slnx + -f override.
|
||||
# The test project pins TargetFrameworks=net10.0 and its ProjectReference closure
|
||||
# gives MSBuild a single-rooted graph, so each multi-targeted dependency is invoked
|
||||
# exactly once for net10.0. This avoids the MSB3026/MSB3491/MSB4018/MSB3883 file-lock
|
||||
# collisions caused by parallel inner-builds racing on shared bin/obj output paths
|
||||
# under the previous slnx + global TFM override approach.
|
||||
- name: Build Foundry hosted IT (and its deps)
|
||||
shell: bash
|
||||
run: dotnet build dotnet/filtered-foundry-hosted.slnx -c "$configuration" -f "$targetFramework" --warnaserror
|
||||
run: dotnet build dotnet/tests/Foundry.Hosting.IntegrationTests/Foundry.Hosting.IntegrationTests.csproj -c "$configuration" --warnaserror
|
||||
|
||||
- name: Azure CLI Login
|
||||
uses: azure/login@v2
|
||||
@@ -394,13 +391,12 @@ jobs:
|
||||
# are picked up; the image tag is content-hashed across the test container source AND its
|
||||
# framework project references, so identical content is a no-op push.
|
||||
#
|
||||
# `-UsePrebuiltProjectReferences` opts into the no-rebuild fast path: publish skips
|
||||
# rebuilding ProjectReferences and consumes the DLLs the prior "Build Foundry hosted IT
|
||||
# (and its deps)" step already produced. This avoids MSB3026 ("file is being used by
|
||||
# another process") collisions caused by the previous build's shared-compilation server
|
||||
# still holding file handles to those DLLs. Safe in CI because the prebuild step ran in
|
||||
# the same job against the same source. Do not remove the prebuild step (the subsequent
|
||||
# `dotnet test --no-build` step depends on it too).
|
||||
# The script always passes --no-dependencies to dotnet publish so publish never re-touches
|
||||
# the framework lib DLLs the prior "Build Foundry hosted IT (and its deps)" step produced.
|
||||
# This structurally eliminates the MSB3026 collision that VBCSCompiler from the prebuild
|
||||
# would otherwise cause by holding file handles to those DLLs. Do not remove the prebuild
|
||||
# step: the subsequent `dotnet test --no-build` step and the publish's ProjectReference
|
||||
# resolution both depend on the prebuilt outputs being present.
|
||||
- name: Build and push Foundry Hosted Agents test container
|
||||
id: build-foundry-hosted-image
|
||||
shell: pwsh
|
||||
@@ -410,14 +406,13 @@ jobs:
|
||||
if ([string]::IsNullOrWhiteSpace($registry)) {
|
||||
throw "IT_HOSTED_AGENT_REGISTRY not set in the integration environment."
|
||||
}
|
||||
& "${{ github.workspace }}/dotnet/tests/Foundry.Hosting.IntegrationTests/scripts/it-build-image.ps1" -Registry $registry -UsePrebuiltProjectReferences | Tee-Object -FilePath $env:GITHUB_ENV -Append
|
||||
& "${{ github.workspace }}/dotnet/tests/Foundry.Hosting.IntegrationTests/scripts/it-build-image.ps1" -Registry $registry | Tee-Object -FilePath $env:GITHUB_ENV -Append
|
||||
|
||||
- name: Run Foundry Hosted Agents Integration Tests
|
||||
shell: pwsh
|
||||
working-directory: dotnet
|
||||
run: |
|
||||
dotnet test --solution ./filtered-foundry-hosted.slnx `
|
||||
-f $env:targetFramework `
|
||||
dotnet test --project tests/Foundry.Hosting.IntegrationTests/Foundry.Hosting.IntegrationTests.csproj `
|
||||
-c $env:configuration `
|
||||
--no-build -v Normal `
|
||||
--report-xunit-trx `
|
||||
@@ -426,13 +421,118 @@ jobs:
|
||||
env:
|
||||
AZURE_AI_PROJECT_ENDPOINT: ${{ vars.IT_HOSTED_AGENT_PROJECT_ENDPOINT }}
|
||||
AZURE_AI_MODEL_DEPLOYMENT_NAME: ${{ vars.IT_HOSTED_AGENT_MODEL_DEPLOYMENT_NAME }}
|
||||
# Azure AI Search (for the azure-search-rag scenario). Reuses the integration
|
||||
# environment secrets shared with python-sample-validation.yml. The index is
|
||||
# provisioned out of band; see dotnet/tests/Foundry.Hosting.IntegrationTests/README.md
|
||||
# for the required schema and seed content.
|
||||
AZURE_SEARCH_ENDPOINT: ${{ secrets.AZURE_SEARCH_ENDPOINT }}
|
||||
AZURE_SEARCH_INDEX_NAME: ${{ secrets.AZURE_SEARCH_INDEX_NAME }}
|
||||
# IT_HOSTED_AGENT_IMAGE was exported into $GITHUB_ENV by the previous step.
|
||||
|
||||
# DurableTask and AzureFunctions integration tests (ubuntu/net10.0 only).
|
||||
# Split from main dotnet-test job for path-based filtering and parallelism.
|
||||
dotnet-test-functions:
|
||||
needs: [paths-filter]
|
||||
if: >
|
||||
github.event_name != 'pull_request' &&
|
||||
(needs.paths-filter.outputs.functionsChanged == 'true' ||
|
||||
needs.paths-filter.outputs.coreChanged == 'true' ||
|
||||
github.event_name == 'schedule' ||
|
||||
github.event_name == 'workflow_dispatch')
|
||||
runs-on: ubuntu-latest
|
||||
environment: integration
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
with:
|
||||
persist-credentials: false
|
||||
sparse-checkout: |
|
||||
.
|
||||
.github
|
||||
dotnet
|
||||
python
|
||||
declarative-agents
|
||||
|
||||
- name: Setup dotnet
|
||||
uses: actions/setup-dotnet@v5.2.0
|
||||
with:
|
||||
global-json-file: ${{ github.workspace }}/dotnet/global.json
|
||||
|
||||
- name: Build functions integration test projects
|
||||
shell: bash
|
||||
working-directory: dotnet
|
||||
run: |
|
||||
dotnet build ./tests/Microsoft.Agents.AI.DurableTask.IntegrationTests -c Release -f net10.0 --warnaserror
|
||||
dotnet build ./tests/Microsoft.Agents.AI.Hosting.AzureFunctions.IntegrationTests -c Release -f net10.0 --warnaserror
|
||||
|
||||
- name: Azure CLI Login
|
||||
uses: azure/login@v2
|
||||
with:
|
||||
client-id: ${{ secrets.AZURE_CLIENT_ID }}
|
||||
tenant-id: ${{ secrets.AZURE_TENANT_ID }}
|
||||
subscription-id: ${{ secrets.AZURE_SUBSCRIPTION_ID }}
|
||||
|
||||
- name: Set up Durable Task and Azure Functions Integration Test Emulators
|
||||
uses: ./.github/actions/azure-functions-integration-setup
|
||||
id: azure-functions-setup
|
||||
|
||||
- name: Run Functions Integration Tests
|
||||
shell: pwsh
|
||||
working-directory: dotnet
|
||||
run: |
|
||||
# Run DurableTask integration tests
|
||||
dotnet test `
|
||||
--project ./tests/Microsoft.Agents.AI.DurableTask.IntegrationTests `
|
||||
-f net10.0 `
|
||||
-c Release `
|
||||
--no-build -v Normal `
|
||||
--report-xunit-trx `
|
||||
--report-junit `
|
||||
--results-directory ../IntegrationTestResults/ `
|
||||
--ignore-exit-code 8 `
|
||||
--filter-not-trait "Category=IntegrationDisabled" `
|
||||
--parallel-algorithm aggressive `
|
||||
--max-threads 2.0x
|
||||
|
||||
# Run AzureFunctions integration tests
|
||||
dotnet test `
|
||||
--project ./tests/Microsoft.Agents.AI.Hosting.AzureFunctions.IntegrationTests `
|
||||
-f net10.0 `
|
||||
-c Release `
|
||||
--no-build -v Normal `
|
||||
--report-xunit-trx `
|
||||
--report-junit `
|
||||
--results-directory ../IntegrationTestResults/ `
|
||||
--ignore-exit-code 8 `
|
||||
--filter-not-trait "Category=IntegrationDisabled" `
|
||||
--parallel-algorithm aggressive `
|
||||
--max-threads 2.0x
|
||||
env:
|
||||
# OpenAI Models
|
||||
OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
|
||||
OPENAI_CHAT_MODEL_NAME: ${{ vars.OPENAI_CHAT_MODEL_NAME }}
|
||||
OPENAI_REASONING_MODEL_NAME: ${{ vars.OPENAI_REASONING_MODEL_NAME }}
|
||||
# Azure OpenAI Models
|
||||
AZURE_OPENAI_DEPLOYMENT_NAME: ${{ vars.AZURE_OPENAI_DEPLOYMENT_NAME }}
|
||||
AZURE_OPENAI_CHAT_DEPLOYMENT_NAME: ${{ vars.AZURE_OPENAI_DEPLOYMENT_NAME }}
|
||||
AZURE_OPENAI_ENDPOINT: ${{ vars.AZURE_OPENAI_ENDPOINT }}
|
||||
# Azure AI Foundry
|
||||
AZURE_AI_PROJECT_ENDPOINT: ${{ vars.AZURE_AI_PROJECT_ENDPOINT }}
|
||||
AZURE_AI_MODEL_DEPLOYMENT_NAME: ${{ vars.AZURE_AI_MODEL_DEPLOYMENT_NAME }}
|
||||
AZURE_AI_BING_CONNECTION_ID: ${{ vars.AZURE_AI_BING_CONNECTION_ID }}
|
||||
|
||||
- name: Upload functions test results
|
||||
if: always()
|
||||
uses: actions/upload-artifact@v7
|
||||
with:
|
||||
name: dotnet-test-results-functions-net10.0-ubuntu-latest
|
||||
path: IntegrationTestResults/**/*.junit
|
||||
if-no-files-found: ignore
|
||||
|
||||
# This final job is required to satisfy the merge queue. It must only run (or succeed) if no tests failed
|
||||
dotnet-build-and-test-check:
|
||||
if: always()
|
||||
runs-on: ubuntu-latest
|
||||
needs: [dotnet-build, dotnet-test, dotnet-foundry-hosted-it]
|
||||
needs: [dotnet-build, dotnet-test, dotnet-foundry-hosted-it, dotnet-test-functions]
|
||||
steps:
|
||||
- name: Get Date
|
||||
shell: bash
|
||||
@@ -479,7 +579,7 @@ jobs:
|
||||
github.event_name != 'pull_request' &&
|
||||
(contains(join(needs.*.result, ','), 'success') ||
|
||||
contains(join(needs.*.result, ','), 'failure'))
|
||||
needs: [dotnet-test]
|
||||
needs: [dotnet-test, dotnet-test-functions]
|
||||
runs-on: ubuntu-latest
|
||||
defaults:
|
||||
run:
|
||||
|
||||
@@ -1,12 +1,8 @@
|
||||
name: Issue Triage
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
issue_number:
|
||||
description: Issue number to triage
|
||||
required: true
|
||||
type: string
|
||||
issues:
|
||||
types: [opened, labeled]
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
@@ -14,7 +10,13 @@ permissions:
|
||||
id-token: write
|
||||
|
||||
concurrency:
|
||||
group: issue-triage-${{ github.repository }}-${{ github.event.issue.number || inputs.issue_number || github.run_id }}
|
||||
group: >-
|
||||
issue-triage-${{ github.repository }}-${{
|
||||
((github.event.action == 'opened' && contains(github.event.issue.labels.*.name, 'bug'))
|
||||
|| (github.event.action == 'labeled' && github.event.label.name == 'bug'))
|
||||
&& github.event.issue.number
|
||||
|| github.run_id
|
||||
}}
|
||||
cancel-in-progress: true
|
||||
|
||||
env:
|
||||
@@ -26,6 +28,7 @@ env:
|
||||
jobs:
|
||||
team_check:
|
||||
runs-on: ubuntu-latest
|
||||
if: ${{ (github.event.action == 'opened' && contains(github.event.issue.labels.*.name, 'bug')) || (github.event.action == 'labeled' && github.event.label.name == 'bug') }}
|
||||
outputs:
|
||||
is_team_member: ${{ steps.check.outputs.is_team_member }}
|
||||
issue_number: ${{ steps.issue.outputs.issue_number }}
|
||||
@@ -36,18 +39,13 @@ jobs:
|
||||
shell: bash
|
||||
env:
|
||||
ISSUE_NUMBER_EVENT: ${{ github.event.issue.number }}
|
||||
ISSUE_NUMBER_INPUT: ${{ inputs.issue_number }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
|
||||
if [[ "${GITHUB_EVENT_NAME}" == "issues" ]]; then
|
||||
issue_number="${ISSUE_NUMBER_EVENT}"
|
||||
else
|
||||
issue_number="${ISSUE_NUMBER_INPUT}"
|
||||
fi
|
||||
issue_number="${ISSUE_NUMBER_EVENT}"
|
||||
|
||||
if [[ ! "$issue_number" =~ ^[1-9][0-9]*$ ]]; then
|
||||
echo "Could not determine issue number; for workflow_dispatch runs, the 'issue_number' input is required." >&2
|
||||
echo "Could not determine issue number from event payload." >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
@@ -166,6 +164,9 @@ jobs:
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
GH_COPILOT_TOKEN: ${{ secrets.GH_COPILOT_TOKEN }}
|
||||
# Not seen by the agent prompt; used only to push a paper-trail
|
||||
# branch back to maf-dashboard at run end.
|
||||
DEVFLOW_TOKEN: ${{ secrets.DEVFLOW_TOKEN }}
|
||||
SK_REPO_PATH: ${{ env.TARGET_REPO_PATH }}
|
||||
AGENT_REPO_PATH: ${{ env.TARGET_REPO_PATH }}
|
||||
ISSUE_REPO: ${{ needs.team_check.outputs.repo }}
|
||||
|
||||
@@ -11,7 +11,7 @@
|
||||
</PropertyGroup>
|
||||
<ItemGroup>
|
||||
<!-- Aspire.* -->
|
||||
<PackageVersion Include="Anthropic" Version="12.13.0" />
|
||||
<PackageVersion Include="Anthropic" Version="12.20.0" />
|
||||
<PackageVersion Include="Anthropic.Foundry" Version="0.5.0" />
|
||||
<PackageVersion Include="Aspire.Hosting" Version="$(AspireAppHostSdkVersion)" />
|
||||
<PackageVersion Include="Aspire.Azure.AI.OpenAI" Version="13.0.0-preview.1.25560.3" />
|
||||
@@ -25,7 +25,8 @@
|
||||
<PackageVersion Include="Azure.AI.AgentServer.Core" Version="1.0.0-beta.23" />
|
||||
<PackageVersion Include="Azure.AI.AgentServer.Invocations" Version="1.0.0-beta.3" />
|
||||
<PackageVersion Include="Azure.AI.AgentServer.Responses" Version="1.0.0-beta.4" />
|
||||
<PackageVersion Include="Azure.AI.Projects" Version="2.0.0" />
|
||||
<PackageVersion Include="Azure.Search.Documents" Version="12.0.0" />
|
||||
<PackageVersion Include="Azure.AI.Projects" Version="2.1.0-beta.1" />
|
||||
<PackageVersion Include="Azure.AI.Agents.Persistent" Version="1.2.0-beta.10" />
|
||||
<PackageVersion Include="Azure.AI.OpenAI" Version="2.9.0-beta.1" />
|
||||
<PackageVersion Include="Azure.Core" Version="1.53.0" />
|
||||
@@ -193,4 +194,4 @@
|
||||
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
|
||||
</PackageReference>
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
</Project>
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
<Solution>
|
||||
<Solution>
|
||||
<Configurations>
|
||||
<BuildType Name="Debug" />
|
||||
<BuildType Name="Publish" />
|
||||
@@ -65,6 +65,7 @@
|
||||
<Project Path="samples/02-agents/Agents/Agent_Step18_CompactionPipeline/Agent_Step18_CompactionPipeline.csproj" />
|
||||
<Project Path="samples/02-agents/Agents/Agent_Step19_InFunctionLoopCheckpointing/Agent_Step19_InFunctionLoopCheckpointing.csproj" />
|
||||
<Project Path="samples/02-agents/Agents/Agent_Step20_DynamicFunctionTools/Agent_Step20_DynamicFunctionTools.csproj" />
|
||||
<Project Path="samples/02-agents/Agents/Agent_Step21_ShellWithEnvironment/Agent_Step21_ShellWithEnvironment.csproj" />
|
||||
</Folder>
|
||||
<Folder Name="/Samples/02-agents/DeclarativeAgents/">
|
||||
<Project Path="samples/02-agents/DeclarativeAgents/ChatClient/DeclarativeChatClientAgents.csproj" />
|
||||
@@ -123,6 +124,8 @@
|
||||
<Project Path="samples/02-agents/Harness/Harness_Step01_Research/Harness_Step01_Research.csproj" />
|
||||
<Project Path="samples/02-agents/Harness/Harness_Step02_Research_WithSubAgents/Harness_Step02_Research_WithSubAgents.csproj" />
|
||||
<Project Path="samples/02-agents/Harness/Harness_Step03_DataProcessing/Harness_Step03_DataProcessing.csproj" />
|
||||
<Project Path="samples/02-agents/Harness/ConsoleReactiveFramework/ConsoleReactiveFramework.csproj" />
|
||||
<Project Path="samples/02-agents/Harness/ConsoleReactiveComponents/ConsoleReactiveComponents.csproj" />
|
||||
</Folder>
|
||||
<Folder Name="/Samples/02-agents/AGUI/Step05_StateManagement/">
|
||||
<Project Path="samples/02-agents/AGUI/Step05_StateManagement/Client/Client.csproj" />
|
||||
@@ -167,7 +170,7 @@
|
||||
<Project Path="samples/02-agents/AgentsWithFoundry/Agent_Step22_MemorySearch/Agent_Step22_MemorySearch.csproj" />
|
||||
<Project Path="samples/02-agents/AgentsWithFoundry/Agent_Step23_LocalMCP/Agent_Step23_LocalMCP.csproj" />
|
||||
<Project Path="samples/02-agents/AgentsWithFoundry/Agent_Step24_CodeInterpreterFileDownload/Agent_Step24_CodeInterpreterFileDownload.csproj" />
|
||||
<Project Path="samples/02-agents/AgentsWithFoundry/Agent_Step25_ToolboxServerSideTools/Agent_Step25_ToolboxServerSideTools.csproj" />
|
||||
<Project Path="samples/02-agents/AgentsWithFoundry/Agent_Step25_FoundryToolboxMcp/Agent_Step25_FoundryToolboxMcp.csproj" />
|
||||
</Folder>
|
||||
<Folder Name="/Samples/02-agents/Evaluation/">
|
||||
<Project Path="samples/02-agents/Evaluation/Evaluation_CustomEvals/Evaluation_CustomEvals.csproj" />
|
||||
@@ -313,6 +316,9 @@
|
||||
<Folder Name="/Samples/04-hosting/FoundryHostedAgents/responses/Hosted-FoundryAgent/">
|
||||
<Project Path="samples/04-hosting/FoundryHostedAgents/responses/Hosted-FoundryAgent/HostedFoundryAgent.csproj" />
|
||||
</Folder>
|
||||
<Folder Name="/Samples/04-hosting/FoundryHostedAgents/responses/Hosted-Files/">
|
||||
<Project Path="samples/04-hosting/FoundryHostedAgents/responses/Hosted-Files/HostedFiles.csproj" />
|
||||
</Folder>
|
||||
<Folder Name="/Samples/04-hosting/FoundryHostedAgents/responses/Hosted-LocalTools/">
|
||||
<Project Path="samples/04-hosting/FoundryHostedAgents/responses/Hosted-LocalTools/HostedLocalTools.csproj" />
|
||||
</Folder>
|
||||
@@ -325,6 +331,9 @@
|
||||
<Folder Name="/Samples/04-hosting/FoundryHostedAgents/responses/Hosted-Toolbox/">
|
||||
<Project Path="samples/04-hosting/FoundryHostedAgents/responses/Hosted-Toolbox/HostedToolbox.csproj" />
|
||||
</Folder>
|
||||
<Folder Name="/Samples/04-hosting/FoundryHostedAgents/responses/Hosted-AzureSearchRag/">
|
||||
<Project Path="samples/04-hosting/FoundryHostedAgents/responses/Hosted-AzureSearchRag/HostedAzureSearchRag.csproj" />
|
||||
</Folder>
|
||||
<Folder Name="/Samples/04-hosting/FoundryHostedAgents/responses/Hosted-TextRag/">
|
||||
<Project Path="samples/04-hosting/FoundryHostedAgents/responses/Hosted-TextRag/HostedTextRag.csproj" />
|
||||
</Folder>
|
||||
@@ -332,6 +341,7 @@
|
||||
<Project Path="samples/04-hosting/FoundryHostedAgents/responses/Hosted-Workflow-Simple/HostedWorkflowSimple.csproj" />
|
||||
</Folder>
|
||||
<Folder Name="/Samples/04-hosting/FoundryHostedAgents/responses/Using-Samples/">
|
||||
<Project Path="samples/04-hosting/FoundryHostedAgents/responses/Using-Samples/SessionFilesClient/SessionFilesClient.csproj" />
|
||||
<Project Path="samples/04-hosting/FoundryHostedAgents/responses/Using-Samples/SimpleAgent/SimpleAgent.csproj" />
|
||||
</Folder>
|
||||
<Folder Name="/Samples/04-hosting/FoundryHostedAgents/responses/Hosted-Workflow-Handoff/">
|
||||
@@ -366,7 +376,7 @@
|
||||
<Project Path="samples/02-agents/A2A/A2AAgent_PollingForTaskCompletion/A2AAgent_PollingForTaskCompletion.csproj" />
|
||||
<Project Path="samples/02-agents/A2A/A2AAgent_ProtocolSelection/A2AAgent_ProtocolSelection.csproj" />
|
||||
<Project Path="samples/02-agents/A2A/A2AAgent_StreamReconnection/A2AAgent_StreamReconnection.csproj" />
|
||||
</Folder>
|
||||
</Folder>
|
||||
<Folder Name="/Samples/05-end-to-end/">
|
||||
<Project Path="samples/05-end-to-end/AgentWithPurview/AgentWithPurview.csproj" />
|
||||
<Project Path="samples/05-end-to-end/M365Agent/M365Agent.csproj" />
|
||||
@@ -583,6 +593,7 @@
|
||||
<Project Path="src/Microsoft.Agents.AI.Mem0/Microsoft.Agents.AI.Mem0.csproj" />
|
||||
<Project Path="src/Microsoft.Agents.AI.OpenAI/Microsoft.Agents.AI.OpenAI.csproj" />
|
||||
<Project Path="src/Microsoft.Agents.AI.Purview/Microsoft.Agents.AI.Purview.csproj" />
|
||||
<Project Path="src/Microsoft.Agents.AI.Tools.Shell/Microsoft.Agents.AI.Tools.Shell.csproj" />
|
||||
<Project Path="src/Microsoft.Agents.AI.Workflows.Declarative.Foundry/Microsoft.Agents.AI.Workflows.Declarative.Foundry.csproj" />
|
||||
<Project Path="src/Microsoft.Agents.AI.Workflows.Declarative.Mcp/Microsoft.Agents.AI.Workflows.Declarative.Mcp.csproj" />
|
||||
<Project Path="src/Microsoft.Agents.AI.Workflows.Declarative/Microsoft.Agents.AI.Workflows.Declarative.csproj" />
|
||||
@@ -605,6 +616,7 @@
|
||||
<Project Path="tests/Microsoft.Agents.AI.Hosting.AzureFunctions.IntegrationTests/Microsoft.Agents.AI.Hosting.AzureFunctions.IntegrationTests.csproj" />
|
||||
<Project Path="tests/Microsoft.Agents.AI.Hyperlight.IntegrationTests/Microsoft.Agents.AI.Hyperlight.IntegrationTests.csproj" />
|
||||
<Project Path="tests/Microsoft.Agents.AI.Mem0.IntegrationTests/Microsoft.Agents.AI.Mem0.IntegrationTests.csproj" />
|
||||
<Project Path="tests/Microsoft.Agents.AI.Tools.Shell.IntegrationTests/Microsoft.Agents.AI.Tools.Shell.IntegrationTests.csproj" />
|
||||
<Project Path="tests/Microsoft.Agents.AI.Workflows.Declarative.IntegrationTests/Microsoft.Agents.AI.Workflows.Declarative.IntegrationTests.csproj" />
|
||||
<Project Path="tests/OpenAIAssistant.IntegrationTests/OpenAIAssistant.IntegrationTests.csproj" />
|
||||
<Project Path="tests/OpenAIChatCompletion.IntegrationTests/OpenAIChatCompletion.IntegrationTests.csproj" />
|
||||
@@ -633,6 +645,7 @@
|
||||
<Project Path="tests/Microsoft.Agents.AI.Mem0.UnitTests/Microsoft.Agents.AI.Mem0.UnitTests.csproj" />
|
||||
<Project Path="tests/Microsoft.Agents.AI.OpenAI.UnitTests/Microsoft.Agents.AI.OpenAI.UnitTests.csproj" />
|
||||
<Project Path="tests/Microsoft.Agents.AI.Purview.UnitTests/Microsoft.Agents.AI.Purview.UnitTests.csproj" />
|
||||
<Project Path="tests/Microsoft.Agents.AI.Tools.Shell.UnitTests/Microsoft.Agents.AI.Tools.Shell.UnitTests.csproj" />
|
||||
<Project Path="tests/Microsoft.Agents.AI.UnitTests/Microsoft.Agents.AI.UnitTests.csproj" />
|
||||
<Project Path="tests/Microsoft.Agents.AI.Workflows.Declarative.Mcp.UnitTests/Microsoft.Agents.AI.Workflows.Declarative.Mcp.UnitTests.csproj" />
|
||||
<Project Path="tests/Microsoft.Agents.AI.Workflows.Declarative.UnitTests/Microsoft.Agents.AI.Workflows.Declarative.UnitTests.csproj" />
|
||||
|
||||
@@ -30,7 +30,8 @@
|
||||
"src\\Microsoft.Agents.AI.Workflows.Generators\\Microsoft.Agents.AI.Workflows.Generators.csproj",
|
||||
"src\\Microsoft.Agents.AI.Workflows\\Microsoft.Agents.AI.Workflows.csproj",
|
||||
"src\\Microsoft.Agents.AI\\Microsoft.Agents.AI.csproj",
|
||||
"src\\Aspire.Hosting.AgentFramework.DevUI\\Aspire.Hosting.AgentFramework.DevUI.csproj"
|
||||
"src\\Aspire.Hosting.AgentFramework.DevUI\\Aspire.Hosting.AgentFramework.DevUI.csproj",
|
||||
"src\\Microsoft.Agents.AI.Hyperlight\\Microsoft.Agents.AI.Hyperlight.csproj"
|
||||
]
|
||||
}
|
||||
}
|
||||
|
||||
@@ -21,10 +21,15 @@
|
||||
.PARAMETER Configuration
|
||||
Optional MSBuild configuration used when querying TargetFrameworks. Defaults to Debug.
|
||||
|
||||
.PARAMETER TestProjectNameFilter
|
||||
.PARAMETER TestProjectNameIncludeFilter
|
||||
Optional wildcard pattern to filter test project names (e.g., *UnitTests*, *IntegrationTests*).
|
||||
When specified, only test projects whose filename matches this pattern are kept.
|
||||
|
||||
.PARAMETER TestProjectNameExcludeFilter
|
||||
Optional wildcard pattern(s) to exclude test projects by name (e.g., *DurableTask.IntegrationTests*).
|
||||
When specified, test projects whose filename matches any of these patterns are removed.
|
||||
Applied after TestProjectNameIncludeFilter. Can be a single string or an array of strings.
|
||||
|
||||
.PARAMETER ExcludeSamples
|
||||
When specified, removes all projects under the samples/ directory from the solution.
|
||||
|
||||
@@ -38,11 +43,15 @@
|
||||
|
||||
.EXAMPLE
|
||||
# Generate a solution with only unit test projects
|
||||
./dotnet/eng/scripts/New-FilteredSolution.ps1 -Solution dotnet/agent-framework-dotnet.slnx -TargetFramework net10.0 -TestProjectNameFilter "*UnitTests*" -OutputPath filtered-unit.slnx
|
||||
./dotnet/eng/scripts/New-FilteredSolution.ps1 -Solution dotnet/agent-framework-dotnet.slnx -TargetFramework net10.0 -TestProjectNameIncludeFilter "*UnitTests*" -OutputPath filtered-unit.slnx
|
||||
|
||||
.EXAMPLE
|
||||
# Inline usage with dotnet test (PowerShell)
|
||||
dotnet test --solution (./dotnet/eng/scripts/New-FilteredSolution.ps1 -Solution dotnet/agent-framework-dotnet.slnx -TargetFramework net472) --no-build -f net472
|
||||
|
||||
.EXAMPLE
|
||||
# Generate integration tests excluding DurableTask and AzureFunctions
|
||||
./dotnet/eng/scripts/New-FilteredSolution.ps1 -Solution dotnet/agent-framework-dotnet.slnx -TargetFramework net10.0 -TestProjectNameIncludeFilter "*IntegrationTests*" -TestProjectNameExcludeFilter "*DurableTask.IntegrationTests*","*AzureFunctions.IntegrationTests*" -OutputPath filtered-other-integration.slnx
|
||||
#>
|
||||
|
||||
[CmdletBinding()]
|
||||
@@ -55,7 +64,9 @@ param(
|
||||
|
||||
[string]$Configuration = "Debug",
|
||||
|
||||
[string]$TestProjectNameFilter,
|
||||
[string]$TestProjectNameIncludeFilter,
|
||||
|
||||
[string[]]$TestProjectNameExcludeFilter,
|
||||
|
||||
[switch]$ExcludeSamples,
|
||||
|
||||
@@ -100,13 +111,30 @@ foreach ($proj in $allProjects) {
|
||||
$isTestProject = $projRelPath -like "*tests/*"
|
||||
|
||||
# Filter test projects by name pattern if specified
|
||||
if ($isTestProject -and $TestProjectNameFilter -and ($projFileName -notlike $TestProjectNameFilter)) {
|
||||
if ($isTestProject -and $TestProjectNameIncludeFilter -and ($projFileName -notlike $TestProjectNameIncludeFilter)) {
|
||||
Write-Verbose "Removing (name filter): $projRelPath"
|
||||
$removed += $projRelPath
|
||||
$proj.ParentNode.RemoveChild($proj) | Out-Null
|
||||
continue
|
||||
}
|
||||
|
||||
# Exclude test projects matching any exclusion pattern
|
||||
if ($isTestProject -and $TestProjectNameExcludeFilter) {
|
||||
$excluded = $false
|
||||
foreach ($pattern in $TestProjectNameExcludeFilter) {
|
||||
if ($projFileName -like $pattern) {
|
||||
$excluded = $true
|
||||
break
|
||||
}
|
||||
}
|
||||
if ($excluded) {
|
||||
Write-Verbose "Removing (exclude filter): $projRelPath"
|
||||
$removed += $projRelPath
|
||||
$proj.ParentNode.RemoveChild($proj) | Out-Null
|
||||
continue
|
||||
}
|
||||
}
|
||||
|
||||
if (-not (Test-Path $projFullPath)) {
|
||||
Write-Verbose "Project not found, keeping in solution: $projRelPath"
|
||||
$kept += $projRelPath
|
||||
|
||||
@@ -1,14 +1,14 @@
|
||||
<Project>
|
||||
<PropertyGroup>
|
||||
<!-- Central version prefix - applies to all nuget packages. -->
|
||||
<VersionPrefix>1.4.0</VersionPrefix>
|
||||
<VersionPrefix>1.5.0</VersionPrefix>
|
||||
<RCNumber>1</RCNumber>
|
||||
<DateSuffix>260505</DateSuffix>
|
||||
<DateSuffix>260507</DateSuffix>
|
||||
<PackageVersion Condition="'$(IsReleaseCandidate)' == 'true'">$(VersionPrefix)-rc$(RCNumber)</PackageVersion>
|
||||
<PackageVersion Condition="'$(IsReleaseCandidate)' != 'true' AND '$(VersionSuffix)' != ''">$(VersionPrefix)-$(VersionSuffix).$(DateSuffix).1</PackageVersion>
|
||||
<PackageVersion Condition="'$(IsReleaseCandidate)' != 'true' AND '$(VersionSuffix)' == ''">$(VersionPrefix)-preview.$(DateSuffix).1</PackageVersion>
|
||||
<PackageVersion Condition="'$(IsReleased)' == 'true'">$(VersionPrefix)</PackageVersion>
|
||||
<GitTag>1.4.0</GitTag>
|
||||
<GitTag>1.5.0</GitTag>
|
||||
|
||||
<Configurations>Debug;Release;Publish</Configurations>
|
||||
<IsPackable>true</IsPackable>
|
||||
|
||||
+75
-2
@@ -8,6 +8,11 @@
|
||||
// even if the process is interrupted mid-loop, but may also result in chat history that is not
|
||||
// yet finalized (e.g., tool calls without results) being persisted, which may be undesirable in some cases.
|
||||
//
|
||||
// Additionally, this sample demonstrates the MessageInjectingChatClient feature, which allows tool
|
||||
// code to inject new user messages during the function execution loop. When a tool or anything else enqueues
|
||||
// a message via MessageInjectingChatClient.EnqueueMessages during the tool execution loop, the PerServiceCallChatHistoryPersistingChatClient
|
||||
// detects the pending message before the next service call and includes the injected message in the request.
|
||||
//
|
||||
// To use end-of-run persistence instead (atomic run semantics), remove the
|
||||
// RequirePerServiceCallChatHistoryPersistence = true setting (or set it to false). End-of-run
|
||||
// persistence is the default behavior.
|
||||
@@ -54,6 +59,37 @@ static string GetTime([Description("The city name.")] string city) =>
|
||||
_ => $"{city}: time data not available."
|
||||
};
|
||||
|
||||
// This tool demonstrates message injection during the function execution loop.
|
||||
// When called, it checks travel advisories for a city. If an advisory is active, it uses
|
||||
// the ambient run context to resolve MessageInjectingChatClient and injects a follow-up user message
|
||||
// asking for alternative destinations. The model will process this injected message on the next
|
||||
// service call — even though the parent FunctionInvokingChatClient loop would otherwise stop.
|
||||
[Description("Check current travel advisories for a city.")]
|
||||
static string CheckTravelAdvisory([Description("The city name.")] string city)
|
||||
{
|
||||
// Simulated travel advisory data.
|
||||
var advisory = city.ToUpperInvariant() switch
|
||||
{
|
||||
"LONDON" => "Travel advisory: Severe fog warnings in London. Flights may be delayed or cancelled.",
|
||||
"SEATTLE" => "Travel advisory: Heavy rainfall expected. Flooding possible in low-lying areas.",
|
||||
_ => null
|
||||
};
|
||||
|
||||
if (advisory is null)
|
||||
{
|
||||
return $"{city}: No active travel advisories.";
|
||||
}
|
||||
|
||||
// When an advisory is found, inject a follow-up question so the model automatically
|
||||
// suggests alternatives without the user needing to ask.
|
||||
var runContext = AIAgent.CurrentRunContext!;
|
||||
runContext.Agent.GetService<MessageInjectingChatClient>()?.EnqueueMessages(
|
||||
runContext.Session!,
|
||||
[new ChatMessage(ChatRole.User, $"Given the travel advisory for {city}, what alternative cities would you recommend instead?")]);
|
||||
|
||||
return advisory;
|
||||
}
|
||||
|
||||
// Create the agent — per-service-call persistence is enabled via RequirePerServiceCallChatHistoryPersistence.
|
||||
// The in-memory ChatHistoryProvider is used by default when the service does not require service stored chat
|
||||
// history, so for those cases, we can inspect the chat history via session.TryGetInMemoryChatHistory().
|
||||
@@ -65,10 +101,11 @@ AIAgent agent = chatClient.AsAIAgent(
|
||||
{
|
||||
Name = "WeatherAssistant",
|
||||
RequirePerServiceCallChatHistoryPersistence = true,
|
||||
EnableMessageInjection = true,
|
||||
ChatOptions = new()
|
||||
{
|
||||
Instructions = "You are a helpful assistant. When asked about multiple cities, call the appropriate tool for each city.",
|
||||
Tools = [AIFunctionFactory.Create(GetWeather), AIFunctionFactory.Create(GetTime)]
|
||||
Instructions = "You are a helpful travel assistant. When asked about cities, call the appropriate tools for each city.",
|
||||
Tools = [AIFunctionFactory.Create(GetWeather), AIFunctionFactory.Create(GetTime), AIFunctionFactory.Create(CheckTravelAdvisory)]
|
||||
},
|
||||
});
|
||||
|
||||
@@ -109,6 +146,18 @@ async Task RunNonStreamingAsync()
|
||||
response = await agent.RunAsync(FollowUp2, session);
|
||||
PrintAgentResponse(response.Text);
|
||||
PrintChatHistory(session, "After third run", ref lastChatHistorySize, ref lastConversationId);
|
||||
|
||||
// Fourth turn — demonstrates message injection during the function loop.
|
||||
// The CheckTravelAdvisory tool detects an advisory for London and injects a follow-up
|
||||
// user message asking for alternative cities. After the tool completes, the internal loop
|
||||
// in PerServiceCallChatHistoryPersistingChatClient detects the pending injected message
|
||||
// and calls the service again, so the model answers the follow-up automatically.
|
||||
const string TravelPrompt = "I'm planning to travel to London next week. Check if there are any travel advisories.";
|
||||
PrintUserMessage(TravelPrompt);
|
||||
|
||||
response = await agent.RunAsync(TravelPrompt, session);
|
||||
PrintAgentResponse(response.Text);
|
||||
PrintChatHistory(session, "After travel advisory run", ref lastChatHistorySize, ref lastConversationId);
|
||||
}
|
||||
|
||||
async Task RunStreamingAsync()
|
||||
@@ -181,6 +230,30 @@ async Task RunStreamingAsync()
|
||||
|
||||
Console.WriteLine();
|
||||
PrintChatHistory(session, "After third run", ref lastChatHistorySize, ref lastConversationId);
|
||||
|
||||
// Fourth turn — demonstrates message injection during the function loop (streaming).
|
||||
// The CheckTravelAdvisory tool detects an advisory for London and injects a follow-up
|
||||
// user message asking for alternative cities. After the tool completes, the internal loop
|
||||
// in PerServiceCallChatHistoryPersistingChatClient detects the pending injected message
|
||||
// and calls the service again, so the model answers the follow-up automatically.
|
||||
const string TravelPrompt = "I'm planning to travel to London next week. Check if there are any travel advisories.";
|
||||
PrintUserMessage(TravelPrompt);
|
||||
|
||||
Console.ForegroundColor = ConsoleColor.Cyan;
|
||||
Console.Write("\n[Agent] ");
|
||||
Console.ResetColor();
|
||||
|
||||
await foreach (var update in agent.RunStreamingAsync(TravelPrompt, session))
|
||||
{
|
||||
Console.Write(update);
|
||||
|
||||
// During streaming we should be able to see updates to the chat history
|
||||
// before the full run completes, as each service call is made and persisted.
|
||||
PrintChatHistory(session, "During travel advisory run", ref lastChatHistorySize, ref lastConversationId);
|
||||
}
|
||||
|
||||
Console.WriteLine();
|
||||
PrintChatHistory(session, "After travel advisory run", ref lastChatHistorySize, ref lastConversationId);
|
||||
}
|
||||
|
||||
void PrintUserMessage(string message)
|
||||
|
||||
+22
@@ -0,0 +1,22 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<OutputType>Exe</OutputType>
|
||||
<TargetFrameworks>net10.0</TargetFrameworks>
|
||||
|
||||
<Nullable>enable</Nullable>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Azure.AI.OpenAI" />
|
||||
<PackageReference Include="Azure.Identity" />
|
||||
<PackageReference Include="Microsoft.Extensions.AI.OpenAI" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\..\..\..\src\Microsoft.Agents.AI.OpenAI\Microsoft.Agents.AI.OpenAI.csproj" />
|
||||
<ProjectReference Include="..\..\..\..\src\Microsoft.Agents.AI.Tools.Shell\Microsoft.Agents.AI.Tools.Shell.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
@@ -0,0 +1,130 @@
|
||||
// Copyright (c) Microsoft. All rights reserved.
|
||||
|
||||
// Shell tool with environment-aware system prompt
|
||||
//
|
||||
// WARNING: This sample uses LocalShellExecutor, which executes real commands
|
||||
// against the shell on this machine. Approval gating is disabled here so
|
||||
// the demo runs unattended; in any real application keep approval on
|
||||
// (the default), or use DockerShellExecutor for container isolation. The
|
||||
// commands the model emits below are read-only or scoped (echo, cd into
|
||||
// a temp folder, set a process-local env var) but a different model or
|
||||
// prompt could choose to do something destructive. Run this only in an
|
||||
// environment where you are comfortable with the agent typing into your
|
||||
// terminal.
|
||||
//
|
||||
// Demonstrates LocalShellExecutor in both modes paired with
|
||||
// ShellEnvironmentProvider, an AIContextProvider that probes the live
|
||||
// shell (OS, family, version, CWD, common CLIs) and injects authoritative
|
||||
// system-prompt instructions so the agent emits commands in the right
|
||||
// idiom (PowerShell vs POSIX).
|
||||
//
|
||||
// Two runs:
|
||||
// 1) Stateless mode: each tool call runs in a fresh shell. Useful when
|
||||
// commands are independent (read-only scripts, version checks, file
|
||||
// listings) and you want strong isolation between calls. Side
|
||||
// effects in one call (cd, exported variables) do NOT carry to the
|
||||
// next.
|
||||
// 2) Persistent mode: a single long-lived shell is reused across calls,
|
||||
// so working directory and exported environment variables are
|
||||
// preserved. Useful for multi-step workflows that build state
|
||||
// (cd into a folder and run a sequence of commands there; set a
|
||||
// token in one step and read it in the next).
|
||||
|
||||
using Azure.AI.OpenAI;
|
||||
using Azure.Identity;
|
||||
using Microsoft.Agents.AI;
|
||||
using Microsoft.Agents.AI.Tools.Shell;
|
||||
using Microsoft.Extensions.AI;
|
||||
using OpenAI.Chat;
|
||||
|
||||
var endpoint = Environment.GetEnvironmentVariable("AZURE_OPENAI_ENDPOINT") ?? throw new InvalidOperationException("AZURE_OPENAI_ENDPOINT is not set.");
|
||||
var deploymentName = Environment.GetEnvironmentVariable("AZURE_OPENAI_DEPLOYMENT_NAME") ?? "gpt-5.4-mini";
|
||||
|
||||
var chatClient = new AzureOpenAIClient(new Uri(endpoint), new DefaultAzureCredential())
|
||||
.GetChatClient(deploymentName);
|
||||
|
||||
const string Instructions = """
|
||||
You are an agent with a single tool: run_shell. Use it to satisfy the
|
||||
user's request. Do not describe what you would do — actually run the
|
||||
commands. Reply with the final answer derived from real output.
|
||||
""";
|
||||
|
||||
// --------------------------------------------------------------------
|
||||
// 1. Stateless mode — each call gets a fresh shell.
|
||||
// --------------------------------------------------------------------
|
||||
Console.WriteLine("### Stateless mode\n");
|
||||
await using (var statelessShell = new LocalShellExecutor(new() { Mode = ShellMode.Stateless, AcknowledgeUnsafe = true }))
|
||||
{
|
||||
var envProvider = new ShellEnvironmentProvider(statelessShell);
|
||||
var statelessAgent = chatClient.AsAIAgent(new ChatClientAgentOptions
|
||||
{
|
||||
ChatOptions = new()
|
||||
{
|
||||
Instructions = Instructions,
|
||||
Tools = [statelessShell.AsAIFunction(requireApproval: false)],
|
||||
},
|
||||
AIContextProviders = [envProvider],
|
||||
});
|
||||
|
||||
var statelessSession = await statelessAgent.CreateSessionAsync();
|
||||
Console.WriteLine(await statelessAgent.RunAsync("Print the current working directory.", statelessSession));
|
||||
Console.WriteLine();
|
||||
|
||||
// Show that side effects do NOT carry between stateless calls: ask the
|
||||
// agent to cd into the system temp directory in one call, then ask
|
||||
// for the CWD in a second call. Stateless mode means the cd is gone.
|
||||
Console.WriteLine(await statelessAgent.RunAsync("Change directory into the system temp folder, then print the current working directory.", statelessSession));
|
||||
Console.WriteLine();
|
||||
Console.WriteLine(await statelessAgent.RunAsync("In a NEW shell call, print the current working directory again. Tell me whether it matches the temp folder from the previous call.", statelessSession));
|
||||
Console.WriteLine();
|
||||
|
||||
PrintSnapshot(envProvider.CurrentSnapshot!);
|
||||
}
|
||||
|
||||
// --------------------------------------------------------------------
|
||||
// 2. Persistent mode — one shell, reused across calls. State carries.
|
||||
// --------------------------------------------------------------------
|
||||
Console.WriteLine("\n### Persistent mode\n");
|
||||
await using (var persistentShell = new LocalShellExecutor(new() { Mode = ShellMode.Persistent, AcknowledgeUnsafe = true }))
|
||||
{
|
||||
var envProvider = new ShellEnvironmentProvider(persistentShell);
|
||||
var persistentAgent = chatClient.AsAIAgent(new ChatClientAgentOptions
|
||||
{
|
||||
ChatOptions = new()
|
||||
{
|
||||
Instructions = Instructions,
|
||||
Tools = [persistentShell.AsAIFunction(requireApproval: false)],
|
||||
},
|
||||
AIContextProviders = [envProvider],
|
||||
});
|
||||
|
||||
var persistentSession = await persistentAgent.CreateSessionAsync();
|
||||
|
||||
// State carries across calls in persistent mode: cd into temp, then
|
||||
// verify the next call sees the new CWD.
|
||||
Console.WriteLine(await persistentAgent.RunAsync("Change directory into the system temp folder, then print the current working directory.", persistentSession));
|
||||
Console.WriteLine();
|
||||
Console.WriteLine(await persistentAgent.RunAsync("In a NEW shell call, print the current working directory again. Tell me whether it still matches the temp folder.", persistentSession));
|
||||
Console.WriteLine();
|
||||
|
||||
// Same idea with an exported variable: set in one call, read in the next.
|
||||
Console.WriteLine(await persistentAgent.RunAsync("Set the environment variable DEMO_TOKEN to the value 'hello-world'.", persistentSession));
|
||||
Console.WriteLine();
|
||||
Console.WriteLine(await persistentAgent.RunAsync("Print the current value of DEMO_TOKEN. Tell me exactly what value the shell reports.", persistentSession));
|
||||
Console.WriteLine();
|
||||
|
||||
PrintSnapshot(envProvider.CurrentSnapshot!);
|
||||
}
|
||||
|
||||
static void PrintSnapshot(ShellEnvironmentSnapshot snap)
|
||||
{
|
||||
Console.WriteLine("--- Captured environment snapshot ---");
|
||||
Console.WriteLine($" Family: {snap.Family}");
|
||||
Console.WriteLine($" OS: {snap.OSDescription}");
|
||||
Console.WriteLine($" Shell: {snap.ShellVersion ?? "(unknown)"}");
|
||||
Console.WriteLine($" CWD: {snap.WorkingDirectory}");
|
||||
foreach (var (tool, version) in snap.ToolVersions)
|
||||
{
|
||||
Console.WriteLine($" {tool,-8} {version ?? "(not installed)"}");
|
||||
}
|
||||
}
|
||||
+7
-3
@@ -6,12 +6,16 @@
|
||||
|
||||
<Nullable>enable</Nullable>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\..\..\..\src\Microsoft.Agents.AI.Foundry.Hosting\Microsoft.Agents.AI.Foundry.Hosting.csproj" />
|
||||
<PackageReference Include="Azure.AI.Projects" VersionOverride="2.1.0-beta.1" />
|
||||
<PackageReference Include="Azure.AI.Projects" />
|
||||
<PackageReference Include="Azure.Identity" />
|
||||
<PackageReference Include="ModelContextProtocol" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\..\..\..\src\Microsoft.Agents.AI.Foundry\Microsoft.Agents.AI.Foundry.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
+70
-71
@@ -1,93 +1,80 @@
|
||||
// Copyright (c) Microsoft. All rights reserved.
|
||||
|
||||
// This sample shows how to load a Foundry toolbox and pass its tools as server-side
|
||||
// tools when creating an agent. The Foundry platform handles tool execution — the agent
|
||||
// process does not invoke tools locally.
|
||||
// Foundry Toolbox via MCP (Streamable HTTP).
|
||||
//
|
||||
// Point an `McpClient` at a Foundry Toolbox's MCP endpoint. The agent
|
||||
// discovers the toolbox's tools at runtime and invokes them locally.
|
||||
|
||||
using System.ClientModel;
|
||||
using System.ClientModel.Primitives;
|
||||
using System.Net.Http.Headers;
|
||||
using Azure.AI.Projects;
|
||||
using Azure.AI.Projects.Agents;
|
||||
using Azure.Core;
|
||||
using Azure.Identity;
|
||||
using Microsoft.Agents.AI;
|
||||
using Microsoft.Extensions.AI;
|
||||
using ModelContextProtocol.Client;
|
||||
using OpenAI.Responses;
|
||||
|
||||
#pragma warning disable OPENAI001 // Experimental API
|
||||
#pragma warning disable AAIP001 // AgentToolboxes is experimental
|
||||
#pragma warning disable CS8321 // Local functions may be commented-out alternatives
|
||||
|
||||
// Replace with your own Foundry toolbox name.
|
||||
// Must match the `<name>` segment of FOUNDRY_TOOLBOX_ENDPOINT.
|
||||
const string ToolboxName = "research_toolbox";
|
||||
// Used only by CombineToolboxes — swap in a second toolbox you own.
|
||||
const string SecondToolboxName = "analysis_toolbox";
|
||||
// Replace with any question that exercises the tools configured in your toolbox.
|
||||
const string Query = "Introduce yourself and briefly describe the tools you can use to help me.";
|
||||
const string Query = "What tools do you have access to?";
|
||||
|
||||
string endpoint = Environment.GetEnvironmentVariable("FOUNDRY_PROJECT_ENDPOINT")
|
||||
?? throw new InvalidOperationException("Set FOUNDRY_PROJECT_ENDPOINT to your Foundry project endpoint.");
|
||||
string model = Environment.GetEnvironmentVariable("FOUNDRY_MODEL") ?? "gpt-5.4-mini";
|
||||
string endpoint = Environment.GetEnvironmentVariable("AZURE_AI_PROJECT_ENDPOINT")
|
||||
?? throw new InvalidOperationException("AZURE_AI_PROJECT_ENDPOINT is not set.");
|
||||
string deploymentName = Environment.GetEnvironmentVariable("AZURE_AI_MODEL_DEPLOYMENT_NAME") ?? "gpt-5.4-mini";
|
||||
string toolboxEndpoint = Environment.GetEnvironmentVariable("FOUNDRY_TOOLBOX_ENDPOINT")
|
||||
?? throw new InvalidOperationException(
|
||||
"FOUNDRY_TOOLBOX_ENDPOINT is not set. Example: " +
|
||||
"https://<account>.services.ai.azure.com/api/projects/<project>/toolsets/<name>/mcp?api-version=2025-05-01-preview");
|
||||
|
||||
TokenCredential credential = new DefaultAzureCredential();
|
||||
|
||||
// Comment out if the toolbox already exists in your Foundry project.
|
||||
await CreateSampleToolboxAsync(ToolboxName, endpoint, credential);
|
||||
|
||||
// Inject a fresh Azure AI bearer token on every MCP request.
|
||||
using var httpClient = new HttpClient(new BearerTokenHandler(credential, "https://ai.azure.com/.default")
|
||||
{
|
||||
InnerHandler = new HttpClientHandler(),
|
||||
});
|
||||
|
||||
Console.WriteLine($"Connecting to toolbox MCP endpoint: {toolboxEndpoint}");
|
||||
|
||||
await using McpClient mcpClient = await McpClient.CreateAsync(
|
||||
new HttpClientTransport(
|
||||
new HttpClientTransportOptions
|
||||
{
|
||||
Endpoint = new Uri(toolboxEndpoint),
|
||||
Name = "foundry_toolbox",
|
||||
},
|
||||
httpClient));
|
||||
|
||||
IList<McpClientTool> mcpTools = await mcpClient.ListToolsAsync();
|
||||
Console.WriteLine($"Toolbox MCP tools available: {string.Join(", ", mcpTools.Select(t => t.Name))}");
|
||||
|
||||
// WARNING: DefaultAzureCredential is convenient for development but requires careful consideration in production.
|
||||
// In production, consider using a specific credential (e.g., ManagedIdentityCredential) to avoid
|
||||
// latency issues, unintended credential probing, and potential security risks from fallback mechanisms.
|
||||
var projectClient = new AIProjectClient(new Uri(endpoint), new DefaultAzureCredential());
|
||||
AIProjectClient aiProjectClient = new(new Uri(endpoint), credential);
|
||||
|
||||
await Main(projectClient, model, endpoint);
|
||||
// await CombineToolboxes(projectClient, model, endpoint);
|
||||
AIAgent agent = aiProjectClient.AsAIAgent(
|
||||
model: deploymentName,
|
||||
instructions: "You are a helpful assistant. Use the available toolbox tools to answer the user.",
|
||||
name: "ToolboxMcpAgent",
|
||||
tools: [.. mcpTools.Cast<AITool>()]);
|
||||
|
||||
Console.WriteLine($"\nUser: {Query}\n");
|
||||
Console.WriteLine($"Assistant: {await agent.RunAsync(Query)}");
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Main: single toolbox
|
||||
// Helper: create (or replace) a sample toolbox so the sample runs end-to-end
|
||||
// ---------------------------------------------------------------------------
|
||||
static async Task Main(AIProjectClient projectClient, string model, string endpoint)
|
||||
{
|
||||
Console.WriteLine("=== Foundry Toolbox Server-Side Tools Example ===");
|
||||
|
||||
// Comment out if the toolbox already exists in your Foundry project.
|
||||
await CreateSampleToolboxAsync(ToolboxName, endpoint);
|
||||
|
||||
// Omit the version to resolve the toolbox's current default version at runtime.
|
||||
var tools = await projectClient.GetToolboxToolsAsync(ToolboxName);
|
||||
|
||||
AIAgent agent = projectClient
|
||||
.AsAIAgent(
|
||||
model: model,
|
||||
instructions: "You are a research assistant. Use the available tools to answer questions.",
|
||||
tools: tools.ToList());
|
||||
|
||||
Console.WriteLine($"User: {Query}");
|
||||
Console.WriteLine($"Result: {await agent.RunAsync(Query)}\n");
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Alternative: combine tools from multiple toolboxes
|
||||
// ---------------------------------------------------------------------------
|
||||
static async Task CombineToolboxes(AIProjectClient projectClient, string model, string endpoint)
|
||||
{
|
||||
Console.WriteLine("=== Combine Toolboxes Example ===");
|
||||
|
||||
// Comment out if the toolboxes already exist in your Foundry project.
|
||||
await CreateSampleToolboxAsync(ToolboxName, endpoint);
|
||||
await CreateSampleToolboxAsync(SecondToolboxName, endpoint);
|
||||
|
||||
var toolboxA = await projectClient.GetToolboxToolsAsync(ToolboxName);
|
||||
var toolboxB = await projectClient.GetToolboxToolsAsync(SecondToolboxName);
|
||||
|
||||
var allTools = toolboxA.Concat(toolboxB).ToList();
|
||||
|
||||
AIAgent agent = projectClient
|
||||
.AsAIAgent(
|
||||
model: model,
|
||||
instructions: "You are a research assistant. Use all available tools to answer questions.",
|
||||
tools: allTools);
|
||||
|
||||
Console.WriteLine($"User: {Query}");
|
||||
Console.WriteLine($"Combined-toolbox result: {await agent.RunAsync(Query)}\n");
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Helper: create (or replace) a sample toolbox so the sample works out-of-the-box
|
||||
// ---------------------------------------------------------------------------
|
||||
static async Task CreateSampleToolboxAsync(string name, string endpoint)
|
||||
static async Task CreateSampleToolboxAsync(string name, string endpoint, TokenCredential credential)
|
||||
{
|
||||
// Toolboxes are normally configured in the Foundry portal or a deployment
|
||||
// script, not the application itself. This helper exists so the sample can
|
||||
@@ -96,10 +83,7 @@ static async Task CreateSampleToolboxAsync(string name, string endpoint)
|
||||
// The Foundry-Features header is currently required for toolbox CRUD operations.
|
||||
var options = new AgentAdministrationClientOptions();
|
||||
options.AddPolicy(new FoundryFeaturesPolicy("Toolboxes=V1Preview"), PipelinePosition.PerCall);
|
||||
var adminClient = new AgentAdministrationClient(
|
||||
new Uri(endpoint),
|
||||
new DefaultAzureCredential(),
|
||||
options);
|
||||
var adminClient = new AgentAdministrationClient(new Uri(endpoint), credential, options);
|
||||
var toolboxClient = adminClient.GetAgentToolboxes();
|
||||
|
||||
// Delete existing toolbox if present (ignore 404).
|
||||
@@ -128,7 +112,7 @@ static async Task CreateSampleToolboxAsync(string name, string endpoint)
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Pipeline policy that adds the Foundry-Features header for toolbox CRUD
|
||||
// Pipeline policy: adds the Foundry-Features header for toolbox CRUD calls
|
||||
// ---------------------------------------------------------------------------
|
||||
internal sealed class FoundryFeaturesPolicy(string feature) : PipelinePolicy
|
||||
{
|
||||
@@ -146,3 +130,18 @@ internal sealed class FoundryFeaturesPolicy(string feature) : PipelinePolicy
|
||||
return ProcessNextAsync(message, pipeline, currentIndex);
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// DelegatingHandler: attaches a fresh Azure AI bearer token to every request
|
||||
// ---------------------------------------------------------------------------
|
||||
internal sealed class BearerTokenHandler(TokenCredential credential, string scope) : DelegatingHandler
|
||||
{
|
||||
private readonly TokenRequestContext _tokenContext = new([scope]);
|
||||
|
||||
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
|
||||
{
|
||||
AccessToken token = await credential.GetTokenAsync(this._tokenContext, cancellationToken).ConfigureAwait(false);
|
||||
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token.Token);
|
||||
return await base.SendAsync(request, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
# Foundry Toolbox via MCP
|
||||
|
||||
This sample shows how to use a Foundry Toolbox by pointing an `McpClient` at the toolbox's MCP endpoint. The agent discovers the toolbox's tools at runtime and invokes them locally over MCP.
|
||||
|
||||
## What this sample demonstrates
|
||||
|
||||
- Connecting to a Foundry toolbox's MCP endpoint via Streamable HTTP transport
|
||||
- Injecting a fresh Azure AI bearer token (`https://ai.azure.com/.default`) on every MCP request
|
||||
- Passing the discovered MCP tools to `AIProjectClient.AsAIAgent(...)`
|
||||
- Optional helper to create (or replace) a sample toolbox in the project so the sample is runnable end-to-end
|
||||
|
||||
## Prerequisites
|
||||
|
||||
- A Microsoft Foundry project with a toolbox configured (or let the sample create one for you)
|
||||
- Azure CLI installed and authenticated (`az login`)
|
||||
|
||||
Set the following environment variables:
|
||||
|
||||
```powershell
|
||||
$env:AZURE_AI_PROJECT_ENDPOINT="https://your-foundry-service.services.ai.azure.com/api/projects/your-foundry-project"
|
||||
$env:AZURE_AI_MODEL_DEPLOYMENT_NAME="gpt-5.4-mini"
|
||||
$env:FOUNDRY_TOOLBOX_ENDPOINT="https://your-foundry-service.services.ai.azure.com/api/projects/your-foundry-project/toolsets/research_toolbox/mcp?api-version=2025-05-01-preview"
|
||||
```
|
||||
|
||||
The `<name>` segment of `FOUNDRY_TOOLBOX_ENDPOINT` must match the `ToolboxName` constant in `Program.cs`.
|
||||
|
||||
## Run the sample
|
||||
|
||||
```powershell
|
||||
dotnet run
|
||||
```
|
||||
-46
@@ -1,46 +0,0 @@
|
||||
# Agent_Step25_ToolboxServerSideTools
|
||||
|
||||
This sample demonstrates loading a named Foundry toolbox and passing its tools as
|
||||
**server-side tools** when creating an agent via `AsAIAgent()`.
|
||||
|
||||
When tools from a toolbox are passed this way, they are sent as tool definitions in
|
||||
the Responses API request. The Foundry platform handles tool execution — the agent
|
||||
process does not invoke tools locally.
|
||||
|
||||
This is the dotnet equivalent of the Python sample:
|
||||
`python/samples/02-agents/providers/foundry/foundry_chat_client_with_toolbox.py`
|
||||
|
||||
## Prerequisites
|
||||
|
||||
- A Microsoft Foundry project
|
||||
- `AZURE_AI_PROJECT_ENDPOINT` environment variable set to your Foundry project endpoint
|
||||
- `AZURE_AI_MODEL_DEPLOYMENT_NAME` environment variable set (defaults to `gpt-5.4-mini`)
|
||||
|
||||
The sample recreates the toolbox on each run, replacing any existing toolbox with
|
||||
the same name. Comment out the `CreateSampleToolboxAsync` call if you want to keep
|
||||
an existing toolbox unchanged.
|
||||
|
||||
## How it works
|
||||
|
||||
1. `projectClient.GetToolboxVersionAsync(name)` fetches the toolbox definition from the
|
||||
Foundry project API (resolving the default version if none is specified)
|
||||
2. `ToolboxVersion.ToAITools()` converts each tool definition to an `AITool` instance
|
||||
3. The tools are passed to `AsAIAgent(tools: ...)` which includes them in the Responses
|
||||
API request as server-side tool definitions
|
||||
|
||||
For a one-liner, use `projectClient.GetToolboxToolsAsync(name)` to fetch and convert in one call.
|
||||
|
||||
## Sample flows
|
||||
|
||||
| Flow | Description |
|
||||
|------|-------------|
|
||||
| `Main` (default) | Loads a single toolbox and runs an agent with its tools |
|
||||
| `CombineToolboxes` | Loads two toolboxes and merges their tools into one agent |
|
||||
|
||||
Uncomment the desired flow in the top-level statements to try each one.
|
||||
|
||||
## Running the sample
|
||||
|
||||
```bash
|
||||
dotnet run
|
||||
```
|
||||
@@ -73,6 +73,7 @@ Some samples require extra tool-specific environment variables. See each sample
|
||||
| [Memory search](./Agent_Step22_MemorySearch/) | Memory search tool |
|
||||
| [Local MCP](./Agent_Step23_LocalMCP/) | Local MCP client with HTTP transport |
|
||||
| [Code interpreter file download](./Agent_Step24_CodeInterpreterFileDownload/) | Download container files generated by code interpreter |
|
||||
| [Foundry toolbox via MCP](./Agent_Step25_FoundryToolboxMcp/) | Use a Foundry Toolbox from a non-hosted agent via its MCP endpoint |
|
||||
|
||||
## Running the samples
|
||||
|
||||
|
||||
@@ -0,0 +1,90 @@
|
||||
// Copyright (c) Microsoft. All rights reserved.
|
||||
|
||||
namespace Harness.ConsoleReactiveComponents;
|
||||
|
||||
/// <summary>
|
||||
/// Provides descriptive helpers for common ANSI/VT100 escape sequences used
|
||||
/// in the split-console layout (DECSTBM scroll regions, cursor movement, line erasure).
|
||||
/// </summary>
|
||||
public static class AnsiEscapes
|
||||
{
|
||||
/// <summary>
|
||||
/// Sets the scrollable region to rows 1 through <paramref name="bottom"/> (DECSTBM).
|
||||
/// Content outside this region will not scroll.
|
||||
/// </summary>
|
||||
public static string SetScrollRegion(int bottom) => $"\x1b[1;{bottom}r";
|
||||
|
||||
/// <summary>
|
||||
/// Resets the scroll region to the full terminal height (DECSTBM reset).
|
||||
/// </summary>
|
||||
public static string ResetScrollRegion => "\x1b[r";
|
||||
|
||||
/// <summary>
|
||||
/// Moves the cursor to the specified 1-based <paramref name="row"/> and <paramref name="column"/> (CUP).
|
||||
/// </summary>
|
||||
public static string MoveCursor(int row, int column) => $"\x1b[{row};{column}H";
|
||||
|
||||
/// <summary>
|
||||
/// Erases the entire current line (EL 2).
|
||||
/// </summary>
|
||||
public static string EraseEntireLine => "\x1b[2K";
|
||||
|
||||
/// <summary>
|
||||
/// Erases the entire screen.
|
||||
/// </summary>
|
||||
public static string EraseEntireScreen => "\x1b[2J";
|
||||
|
||||
/// <summary>
|
||||
/// Erases the scrollback buffer (ESC[3J). Use alongside <see cref="EraseEntireScreen"/>
|
||||
/// to fully clear both the visible screen and the scroll history.
|
||||
/// </summary>
|
||||
public static string EraseScrollbackBuffer => "\x1b[3J";
|
||||
|
||||
/// <summary>
|
||||
/// Saves the current cursor position (DECSC / SCP).
|
||||
/// Note: most terminals have a single save slot — nested saves are not supported.
|
||||
/// </summary>
|
||||
public static string SaveCursor => "\x1b[s";
|
||||
|
||||
/// <summary>
|
||||
/// Restores the previously saved cursor position (DECRC / RCP).
|
||||
/// </summary>
|
||||
public static string RestoreCursor => "\x1b[u";
|
||||
|
||||
/// <summary>
|
||||
/// Moves the cursor to the specified 1-based <paramref name="row"/> at column 1, then erases the entire line.
|
||||
/// Convenience combination of <see cref="MoveCursor"/> and <see cref="EraseEntireLine"/>.
|
||||
/// </summary>
|
||||
public static string MoveAndEraseLine(int row) => $"\x1b[{row};1H\x1b[2K";
|
||||
|
||||
/// <summary>
|
||||
/// Sets the foreground text color using a <see cref="ConsoleColor"/> value.
|
||||
/// </summary>
|
||||
public static string SetForegroundColor(ConsoleColor color) => $"\x1b[{ConsoleColorToAnsi(color)}m";
|
||||
|
||||
/// <summary>
|
||||
/// Resets all text attributes (color, bold, etc.) to their defaults.
|
||||
/// </summary>
|
||||
public static string ResetAttributes => "\x1b[0m";
|
||||
|
||||
private static int ConsoleColorToAnsi(ConsoleColor color) => color switch
|
||||
{
|
||||
ConsoleColor.Black => 30,
|
||||
ConsoleColor.DarkRed => 31,
|
||||
ConsoleColor.DarkGreen => 32,
|
||||
ConsoleColor.DarkYellow => 33,
|
||||
ConsoleColor.DarkBlue => 34,
|
||||
ConsoleColor.DarkMagenta => 35,
|
||||
ConsoleColor.DarkCyan => 36,
|
||||
ConsoleColor.Gray => 37,
|
||||
ConsoleColor.DarkGray => 90,
|
||||
ConsoleColor.Red => 91,
|
||||
ConsoleColor.Green => 92,
|
||||
ConsoleColor.Yellow => 93,
|
||||
ConsoleColor.Blue => 94,
|
||||
ConsoleColor.Magenta => 95,
|
||||
ConsoleColor.Cyan => 96,
|
||||
ConsoleColor.White => 97,
|
||||
_ => 37
|
||||
};
|
||||
}
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFrameworks>net10.0</TargetFrameworks>
|
||||
|
||||
<Nullable>enable</Nullable>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="../ConsoleReactiveFramework/ConsoleReactiveFramework.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
@@ -0,0 +1,151 @@
|
||||
// Copyright (c) Microsoft. All rights reserved.
|
||||
|
||||
using Harness.ConsoleReactiveFramework;
|
||||
|
||||
namespace Harness.ConsoleReactiveComponents;
|
||||
|
||||
/// <summary>
|
||||
/// A component that renders a selectable list of items with a cursor indicator.
|
||||
/// The selected item is indicated with a ">" prefix and rendered in the highlight color.
|
||||
/// Optionally includes a title above the list and a custom text input option at the bottom.
|
||||
/// </summary>
|
||||
public class ListSelection : ConsoleReactiveComponent<ListSelectionProps, ConsoleReactiveState>
|
||||
{
|
||||
/// <summary>
|
||||
/// Calculates the height (in rows) required to render the list,
|
||||
/// including the optional title and custom text input row.
|
||||
/// </summary>
|
||||
/// <param name="props">The list selection props.</param>
|
||||
/// <returns>The number of rows needed.</returns>
|
||||
public static int CalculateHeight(ListSelectionProps props)
|
||||
{
|
||||
int height = props.Items.Count;
|
||||
if (props.CustomTextPlaceholder != null)
|
||||
{
|
||||
height++;
|
||||
}
|
||||
|
||||
height += GetTitleLineCount(props.Title);
|
||||
return height;
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public override void RenderCore(ListSelectionProps props, ConsoleReactiveState state)
|
||||
{
|
||||
int row = 0;
|
||||
|
||||
// Render the title lines (if any)
|
||||
if (props.Title is not null)
|
||||
{
|
||||
foreach (string line in props.Title.Split('\n'))
|
||||
{
|
||||
Console.Write(AnsiEscapes.MoveCursor(this.Y + row, this.X));
|
||||
Console.Write(AnsiEscapes.EraseEntireLine);
|
||||
Console.Write(line);
|
||||
row++;
|
||||
}
|
||||
}
|
||||
|
||||
// Render the list items + optional custom text row
|
||||
int totalItems = props.Items.Count + (props.CustomTextPlaceholder != null ? 1 : 0);
|
||||
|
||||
for (int i = 0; i < totalItems; i++)
|
||||
{
|
||||
Console.Write(AnsiEscapes.MoveCursor(this.Y + row, this.X));
|
||||
Console.Write(AnsiEscapes.EraseEntireLine);
|
||||
|
||||
bool isSelected = i == props.SelectedIndex;
|
||||
bool isCustomTextOption = props.CustomTextPlaceholder != null && i == props.Items.Count;
|
||||
|
||||
// Cursor indicator
|
||||
Console.Write(isSelected ? "> " : " ");
|
||||
|
||||
if (isCustomTextOption)
|
||||
{
|
||||
this.RenderCustomTextOption(props, isSelected);
|
||||
}
|
||||
else
|
||||
{
|
||||
if (isSelected)
|
||||
{
|
||||
Console.Write(AnsiEscapes.SetForegroundColor(props.HighlightColor));
|
||||
}
|
||||
|
||||
Console.Write(props.Items[i]);
|
||||
|
||||
if (isSelected)
|
||||
{
|
||||
Console.Write(AnsiEscapes.ResetAttributes);
|
||||
}
|
||||
}
|
||||
|
||||
Console.WriteLine();
|
||||
row++;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the number of lines the title occupies, or 0 if no title is set.
|
||||
/// </summary>
|
||||
private static int GetTitleLineCount(string? title) =>
|
||||
title is null ? 0 : title.Split('\n').Length;
|
||||
|
||||
private void RenderCustomTextOption(ListSelectionProps props, bool isSelected)
|
||||
{
|
||||
if (props.CustomText.Length > 0)
|
||||
{
|
||||
// User has typed text — render in highlight color if selected
|
||||
if (isSelected)
|
||||
{
|
||||
Console.Write(AnsiEscapes.SetForegroundColor(props.HighlightColor));
|
||||
}
|
||||
|
||||
Console.Write(props.CustomText);
|
||||
|
||||
if (isSelected)
|
||||
{
|
||||
Console.Write(AnsiEscapes.ResetAttributes);
|
||||
}
|
||||
}
|
||||
else if (!string.IsNullOrWhiteSpace(props.CustomTextPlaceholder))
|
||||
{
|
||||
// No text — show placeholder in dark grey (or highlight color if selected)
|
||||
if (isSelected)
|
||||
{
|
||||
Console.Write(AnsiEscapes.SetForegroundColor(props.HighlightColor));
|
||||
}
|
||||
else
|
||||
{
|
||||
Console.Write(AnsiEscapes.SetForegroundColor(ConsoleColor.DarkGray));
|
||||
}
|
||||
|
||||
Console.Write(" ");
|
||||
Console.Write(props.CustomTextPlaceholder);
|
||||
Console.Write(AnsiEscapes.ResetAttributes);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Props for <see cref="ListSelection"/>.
|
||||
/// </summary>
|
||||
public record ListSelectionProps : ConsoleReactiveProps
|
||||
{
|
||||
/// <summary>Gets the title text displayed above the list items. May contain newlines for multi-line titles.</summary>
|
||||
public string? Title { get; init; }
|
||||
|
||||
/// <summary>Gets the items to display in the list.</summary>
|
||||
public IReadOnlyList<string> Items { get; init; } = Array.Empty<string>();
|
||||
|
||||
/// <summary>Gets the zero-based index of the currently selected item.</summary>
|
||||
public int SelectedIndex { get; init; }
|
||||
|
||||
/// <summary>Gets the highlight color for the active item. Defaults to <see cref="ConsoleColor.Cyan"/>.</summary>
|
||||
public ConsoleColor HighlightColor { get; init; } = ConsoleColor.Cyan;
|
||||
|
||||
/// <summary>Gets the placeholder text for the custom text input option. If <c>null</c>, no custom option is shown.</summary>
|
||||
public string? CustomTextPlaceholder { get; init; }
|
||||
|
||||
/// <summary>Gets the text being typed into the custom text input option.</summary>
|
||||
public string CustomText { get; init; } = "";
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
// Copyright (c) Microsoft. All rights reserved.
|
||||
|
||||
using Harness.ConsoleReactiveFramework;
|
||||
|
||||
namespace Harness.ConsoleReactiveComponents;
|
||||
|
||||
/// <summary>
|
||||
/// Props for <see cref="TextInput"/>.
|
||||
/// </summary>
|
||||
public record TextInputProps : ConsoleReactiveProps
|
||||
{
|
||||
/// <summary>Gets the prompt string displayed on the left (e.g. "> " or "user > ").</summary>
|
||||
public string Prompt { get; init; } = "> ";
|
||||
|
||||
/// <summary>Gets the text content to render to the right of the prompt.</summary>
|
||||
public string Text { get; init; } = "";
|
||||
|
||||
/// <summary>Gets the placeholder text shown in dark grey when <see cref="Text"/> is empty.</summary>
|
||||
public string Placeholder { get; init; } = "";
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A component that renders a prompt with text input. Supports multi-line text
|
||||
/// where continuation lines are indented to align with the text start position
|
||||
/// (i.e. the column after the prompt).
|
||||
/// </summary>
|
||||
public class TextInput : ConsoleReactiveComponent<TextInputProps, ConsoleReactiveState>
|
||||
{
|
||||
/// <summary>
|
||||
/// Calculates the height (in rows) required to render the prompt and text
|
||||
/// given the available width.
|
||||
/// </summary>
|
||||
/// <param name="props">The text input props.</param>
|
||||
/// <param name="availableWidth">The total available width in columns.</param>
|
||||
/// <returns>The number of rows needed.</returns>
|
||||
public static int CalculateHeight(TextInputProps props, int availableWidth)
|
||||
{
|
||||
int promptLength = props.Prompt.Length;
|
||||
int textWidth = availableWidth - promptLength;
|
||||
|
||||
if (textWidth <= 0 || props.Text.Length == 0)
|
||||
{
|
||||
return 1;
|
||||
}
|
||||
|
||||
int lines = 1;
|
||||
int remaining = props.Text.Length - textWidth;
|
||||
while (remaining > 0)
|
||||
{
|
||||
lines++;
|
||||
remaining -= textWidth;
|
||||
}
|
||||
|
||||
return lines;
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public override void RenderCore(TextInputProps props, ConsoleReactiveState state)
|
||||
{
|
||||
int promptLength = props.Prompt.Length;
|
||||
int textWidth = this.Width - promptLength;
|
||||
string indent = new(' ', promptLength);
|
||||
|
||||
// First line: prompt + start of text
|
||||
Console.Write(AnsiEscapes.MoveCursor(this.Y, this.X));
|
||||
Console.Write(AnsiEscapes.EraseEntireLine);
|
||||
Console.Write(props.Prompt);
|
||||
|
||||
if (textWidth <= 0 || props.Text.Length == 0)
|
||||
{
|
||||
// Show placeholder if text is empty
|
||||
if (props.Text.Length == 0 && props.Placeholder.Length > 0 && textWidth > 0)
|
||||
{
|
||||
Console.Write(AnsiEscapes.SetForegroundColor(ConsoleColor.DarkGray));
|
||||
Console.Write(" ");
|
||||
Console.Write(props.Placeholder[..Math.Min(props.Placeholder.Length, textWidth - 1)]);
|
||||
Console.Write(AnsiEscapes.ResetAttributes);
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
int offset = 0;
|
||||
int firstChunk = Math.Min(textWidth, props.Text.Length);
|
||||
Console.Write(props.Text[offset..firstChunk]);
|
||||
offset = firstChunk;
|
||||
|
||||
// Continuation lines: indented to align with text start
|
||||
int row = 1;
|
||||
while (offset < props.Text.Length)
|
||||
{
|
||||
int chunk = Math.Min(textWidth, props.Text.Length - offset);
|
||||
Console.Write(AnsiEscapes.MoveCursor(this.Y + row, this.X));
|
||||
Console.Write(AnsiEscapes.EraseEntireLine);
|
||||
Console.Write(indent);
|
||||
Console.Write(props.Text[offset..(offset + chunk)]);
|
||||
offset += chunk;
|
||||
row++;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
// Copyright (c) Microsoft. All rights reserved.
|
||||
|
||||
using Harness.ConsoleReactiveFramework;
|
||||
|
||||
namespace Harness.ConsoleReactiveComponents;
|
||||
|
||||
/// <summary>
|
||||
/// Props for <see cref="TextPanel"/>.
|
||||
/// </summary>
|
||||
public record TextPanelProps : ConsoleReactiveProps
|
||||
{
|
||||
/// <summary>Gets the items to render in the panel.</summary>
|
||||
public IReadOnlyList<object> Items { get; init; } = [];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A component that renders a list of items vertically using a custom render delegate.
|
||||
/// Designed for rendering dynamic items in a non-scroll region that may be
|
||||
/// re-rendered on each update. If the component's <see cref="ConsoleReactiveComponent.Height"/>
|
||||
/// exceeds the number of output lines, leftover lines are erased.
|
||||
/// </summary>
|
||||
public class TextPanel : ConsoleReactiveComponent<TextPanelProps, ConsoleReactiveState>
|
||||
{
|
||||
private readonly Func<object, string> _renderItem;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="TextPanel"/> class.
|
||||
/// </summary>
|
||||
/// <param name="renderItem">A delegate that renders an item and returns the text to display (may contain newlines).</param>
|
||||
public TextPanel(Func<object, string> renderItem)
|
||||
{
|
||||
this._renderItem = renderItem;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Calculates the height (in lines) needed to render all items.
|
||||
/// </summary>
|
||||
/// <param name="items">The items to measure.</param>
|
||||
/// <param name="renderItem">The render delegate to use for measuring.</param>
|
||||
/// <returns>The total number of lines all items will occupy.</returns>
|
||||
public static int CalculateHeight(IReadOnlyList<object> items, Func<object, string> renderItem)
|
||||
{
|
||||
int total = 0;
|
||||
for (int i = 0; i < items.Count; i++)
|
||||
{
|
||||
string text = renderItem(items[i]);
|
||||
total += CountLines(text);
|
||||
}
|
||||
|
||||
return total;
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public override void RenderCore(TextPanelProps props, ConsoleReactiveState state)
|
||||
{
|
||||
int currentRow = 0;
|
||||
|
||||
for (int i = 0; i < props.Items.Count; i++)
|
||||
{
|
||||
string text = this._renderItem(props.Items[i]);
|
||||
string[] lines = text.Split('\n');
|
||||
int lineCount = CountLines(text);
|
||||
|
||||
for (int j = 0; j < lineCount; j++)
|
||||
{
|
||||
Console.Write(AnsiEscapes.MoveAndEraseLine(this.Y + currentRow));
|
||||
Console.Write(lines[j]);
|
||||
currentRow++;
|
||||
}
|
||||
}
|
||||
|
||||
// If the component height exceeds the output, erase leftover lines
|
||||
if (this.Height > currentRow)
|
||||
{
|
||||
for (int i = currentRow; i < this.Height; i++)
|
||||
{
|
||||
Console.Write(AnsiEscapes.MoveAndEraseLine(this.Y + i));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static int CountLines(string text)
|
||||
{
|
||||
if (string.IsNullOrEmpty(text))
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
|
||||
int count = 1;
|
||||
for (int i = 0; i < text.Length; i++)
|
||||
{
|
||||
if (text[i] == '\n')
|
||||
{
|
||||
count++;
|
||||
}
|
||||
}
|
||||
|
||||
// If text ends with a newline, don't count the trailing empty line
|
||||
if (text[text.Length - 1] == '\n')
|
||||
{
|
||||
count--;
|
||||
}
|
||||
|
||||
return count;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
// Copyright (c) Microsoft. All rights reserved.
|
||||
|
||||
using Harness.ConsoleReactiveFramework;
|
||||
|
||||
namespace Harness.ConsoleReactiveComponents;
|
||||
|
||||
/// <summary>
|
||||
/// Props for <see cref="TextScrollPanel"/>.
|
||||
/// </summary>
|
||||
public record TextScrollPanelProps : ConsoleReactiveProps
|
||||
{
|
||||
/// <summary>Gets the items to render in the scroll panel.</summary>
|
||||
public IReadOnlyList<object> Items { get; init; } = [];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// State for <see cref="TextScrollPanel"/>.
|
||||
/// </summary>
|
||||
/// <param name="RenderedCount">The number of items already rendered.</param>
|
||||
public record TextScrollPanelState(int RenderedCount = 0) : ConsoleReactiveState;
|
||||
|
||||
/// <summary>
|
||||
/// A component that renders items within a scroll area using a custom render delegate.
|
||||
/// All items are considered finalized — only new items since the last render are output.
|
||||
/// Use <see cref="Reset"/> to force a full re-render.
|
||||
/// </summary>
|
||||
public class TextScrollPanel : ConsoleReactiveComponent<TextScrollPanelProps, TextScrollPanelState>
|
||||
{
|
||||
private readonly Func<object, string> _renderItem;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="TextScrollPanel"/> class.
|
||||
/// </summary>
|
||||
/// <param name="renderItem">A delegate that renders a single item and returns the text to display (may contain newlines).</param>
|
||||
public TextScrollPanel(Func<object, string> renderItem)
|
||||
{
|
||||
this._renderItem = renderItem;
|
||||
this.State = new TextScrollPanelState();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Resets the panel so all items will be re-rendered on the next Render call.
|
||||
/// </summary>
|
||||
public void Reset()
|
||||
{
|
||||
this.State = new TextScrollPanelState();
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public override void RenderCore(TextScrollPanelProps props, TextScrollPanelState state)
|
||||
{
|
||||
if (props.Items.Count == 0)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// Move cursor to the bottom of the scroll area
|
||||
Console.Write(AnsiEscapes.MoveCursor(this.Y + this.Height - 1, this.X));
|
||||
|
||||
// Output only new items since last rendered
|
||||
for (int i = state.RenderedCount; i < props.Items.Count; i++)
|
||||
{
|
||||
string text = this._renderItem(props.Items[i]);
|
||||
Console.Write(text);
|
||||
}
|
||||
|
||||
// Update state to track what we've rendered
|
||||
this.State = new TextScrollPanelState(props.Items.Count);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
// Copyright (c) Microsoft. All rights reserved.
|
||||
|
||||
using Harness.ConsoleReactiveFramework;
|
||||
|
||||
namespace Harness.ConsoleReactiveComponents;
|
||||
|
||||
/// <summary>
|
||||
/// Props for <see cref="TopBottomRule"/>.
|
||||
/// </summary>
|
||||
public record TopBottomRuleProps : ConsoleReactiveProps
|
||||
{
|
||||
/// <summary>Gets the width of the horizontal rules in characters.</summary>
|
||||
public int Width { get; init; }
|
||||
|
||||
/// <summary>Gets the foreground color of the horizontal rules. If <c>null</c>, the default terminal color is used.</summary>
|
||||
public ConsoleColor? Color { get; init; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A component that renders a top and bottom horizontal rule (─) with children
|
||||
/// stacked vertically between them.
|
||||
/// </summary>
|
||||
public class TopBottomRule : ConsoleReactiveComponent<TopBottomRuleProps, ConsoleReactiveState>
|
||||
{
|
||||
/// <summary>
|
||||
/// Calculates the total height including the top rule, children, and bottom rule.
|
||||
/// </summary>
|
||||
/// <param name="props">The component props containing children.</param>
|
||||
/// <returns>2 (for the rules) plus the sum of all children heights.</returns>
|
||||
public static int CalculateHeight(TopBottomRuleProps props)
|
||||
{
|
||||
int childrenHeight = 0;
|
||||
foreach (var child in props.Children)
|
||||
{
|
||||
childrenHeight += child.Height;
|
||||
}
|
||||
|
||||
// Top rule + children + bottom rule
|
||||
return 2 + childrenHeight;
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public override void RenderCore(TopBottomRuleProps props, ConsoleReactiveState state)
|
||||
{
|
||||
int ruleWidth = props.Width;
|
||||
string rule = new('─', ruleWidth);
|
||||
|
||||
if (props.Color.HasValue)
|
||||
{
|
||||
Console.Write(AnsiEscapes.SetForegroundColor(props.Color.Value));
|
||||
}
|
||||
|
||||
// Top rule
|
||||
Console.Write(AnsiEscapes.MoveCursor(this.Y, this.X));
|
||||
Console.Write(rule);
|
||||
|
||||
// Render children stacked below the top rule
|
||||
int currentY = this.Y + 1;
|
||||
|
||||
if (props.Color.HasValue)
|
||||
{
|
||||
Console.Write(AnsiEscapes.ResetAttributes);
|
||||
}
|
||||
|
||||
foreach (var child in props.Children)
|
||||
{
|
||||
child.X = this.X;
|
||||
child.Y = currentY;
|
||||
child.Render();
|
||||
currentY += child.Height;
|
||||
}
|
||||
|
||||
if (props.Color.HasValue)
|
||||
{
|
||||
Console.Write(AnsiEscapes.SetForegroundColor(props.Color.Value));
|
||||
}
|
||||
|
||||
// Bottom rule
|
||||
Console.Write(AnsiEscapes.MoveCursor(currentY, this.X));
|
||||
Console.Write(rule);
|
||||
|
||||
if (props.Color.HasValue)
|
||||
{
|
||||
Console.Write(AnsiEscapes.ResetAttributes);
|
||||
}
|
||||
}
|
||||
}
|
||||
+110
@@ -0,0 +1,110 @@
|
||||
// Copyright (c) Microsoft. All rights reserved.
|
||||
|
||||
namespace Harness.ConsoleReactiveFramework;
|
||||
|
||||
/// <summary>
|
||||
/// Abstract base class for all console UI components. Provides layout properties
|
||||
/// (position and size) and a <see cref="Render"/> method for drawing to the console.
|
||||
/// Derive from <see cref="ConsoleReactiveComponent{TProps, TState}"/> instead of this class directly.
|
||||
/// </summary>
|
||||
public abstract class ConsoleReactiveComponent
|
||||
{
|
||||
internal ConsoleReactiveComponent()
|
||||
{
|
||||
}
|
||||
|
||||
/// <summary>Gets or sets the 1-based column position of the component.</summary>
|
||||
public int X { get; set; }
|
||||
|
||||
/// <summary>Gets or sets the 1-based row position of the component.</summary>
|
||||
public int Y { get; set; }
|
||||
|
||||
/// <summary>Gets or sets the width of the component in columns.</summary>
|
||||
public int Width { get; set; }
|
||||
|
||||
/// <summary>Gets or sets the height of the component in rows.</summary>
|
||||
public int Height { get; set; }
|
||||
|
||||
/// <summary>Renders the component to the console at its current position.</summary>
|
||||
public abstract void Render();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Generic base class for console UI components with typed props and state.
|
||||
/// Props represent externally supplied configuration; state represents internal mutable data.
|
||||
/// </summary>
|
||||
/// <typeparam name="TProps">The type of the component's props (external configuration).</typeparam>
|
||||
/// <typeparam name="TState">The type of the component's internal state.</typeparam>
|
||||
public abstract class ConsoleReactiveComponent<TProps, TState> : ConsoleReactiveComponent
|
||||
where TProps : ConsoleReactiveProps
|
||||
where TState : ConsoleReactiveState
|
||||
{
|
||||
private readonly object _renderLock = new();
|
||||
private TProps? _lastRenderedProps;
|
||||
private TState? _lastRenderedState;
|
||||
|
||||
/// <summary>Gets or sets the component's props (external configuration).</summary>
|
||||
public TProps? Props { get; set; }
|
||||
|
||||
/// <summary>Gets or sets the component's internal state.</summary>
|
||||
protected TState? State { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Updates the component's state and triggers a re-render.
|
||||
/// </summary>
|
||||
/// <param name="newState">The new state value.</param>
|
||||
public void SetState(TState newState)
|
||||
{
|
||||
this.State = newState;
|
||||
this.Render();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Renders the component using the current props and state.
|
||||
/// Uses a lock to prevent concurrent renders from multiple sources.
|
||||
/// Skips rendering if neither props nor state have changed since the last render.
|
||||
/// </summary>
|
||||
public override void Render()
|
||||
{
|
||||
lock (this._renderLock)
|
||||
{
|
||||
if (this.Props is null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (ReferenceEquals(this.Props, this._lastRenderedProps)
|
||||
&& ReferenceEquals(this.State, this._lastRenderedState))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
this.RenderCore(this.Props, this.State!);
|
||||
|
||||
this._lastRenderedProps = this.Props;
|
||||
this._lastRenderedState = this.State;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Called by <see cref="Render"/> to perform the actual rendering. Override this in derived classes.
|
||||
/// </summary>
|
||||
/// <param name="props">The current props.</param>
|
||||
/// <param name="state">The current state.</param>
|
||||
public abstract void RenderCore(TProps props, TState state);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Base record for component props. Provides an optional <see cref="Children"/> collection
|
||||
/// for composing child components.
|
||||
/// </summary>
|
||||
public record ConsoleReactiveProps
|
||||
{
|
||||
/// <summary>Gets the child components to render within this component.</summary>
|
||||
public IReadOnlyList<ConsoleReactiveComponent> Children { get; init; } = [];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Base record for component state.
|
||||
/// </summary>
|
||||
public record ConsoleReactiveState;
|
||||
+10
@@ -0,0 +1,10 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFrameworks>net10.0</TargetFrameworks>
|
||||
|
||||
<Nullable>enable</Nullable>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
</PropertyGroup>
|
||||
|
||||
</Project>
|
||||
@@ -0,0 +1,83 @@
|
||||
// Copyright (c) Microsoft. All rights reserved.
|
||||
|
||||
namespace Harness.ConsoleReactiveFramework;
|
||||
|
||||
/// <summary>
|
||||
/// Event args for console resize events, containing the old and new dimensions.
|
||||
/// </summary>
|
||||
public class ConsoleResizeEventArgs : EventArgs
|
||||
{
|
||||
/// <summary>Gets the previous console width.</summary>
|
||||
public int OldWidth { get; }
|
||||
|
||||
/// <summary>Gets the previous console height.</summary>
|
||||
public int OldHeight { get; }
|
||||
|
||||
/// <summary>Gets the new console width.</summary>
|
||||
public int NewWidth { get; }
|
||||
|
||||
/// <summary>Gets the new console height.</summary>
|
||||
public int NewHeight { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="ConsoleResizeEventArgs"/> class.
|
||||
/// </summary>
|
||||
/// <param name="oldWidth">The previous width.</param>
|
||||
/// <param name="oldHeight">The previous height.</param>
|
||||
/// <param name="newWidth">The new width.</param>
|
||||
/// <param name="newHeight">The new height.</param>
|
||||
public ConsoleResizeEventArgs(int oldWidth, int oldHeight, int newWidth, int newHeight)
|
||||
{
|
||||
this.OldWidth = oldWidth;
|
||||
this.OldHeight = oldHeight;
|
||||
this.NewWidth = newWidth;
|
||||
this.NewHeight = newHeight;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Singleton that polls console dimensions every 16ms and raises the
|
||||
/// <see cref="ConsoleResized"/> event when the window size changes.
|
||||
/// </summary>
|
||||
public sealed class ConsoleResizeListener
|
||||
{
|
||||
#pragma warning disable IDE0052 // Remove unread private members
|
||||
private readonly Task _task;
|
||||
#pragma warning restore IDE0052 // Remove unread private members
|
||||
|
||||
private int _lastWidth;
|
||||
private int _lastHeight;
|
||||
|
||||
private ConsoleResizeListener()
|
||||
{
|
||||
this._lastWidth = Console.WindowWidth;
|
||||
this._lastHeight = Console.WindowHeight;
|
||||
this._task = this.ListenForResizeAsync();
|
||||
}
|
||||
|
||||
/// <summary>Gets the singleton instance of <see cref="ConsoleResizeListener"/>.</summary>
|
||||
public static ConsoleResizeListener Instance { get; } = new ConsoleResizeListener();
|
||||
|
||||
/// <summary>Raised when the console window is resized.</summary>
|
||||
public event EventHandler<ConsoleResizeEventArgs>? ConsoleResized;
|
||||
|
||||
private async Task ListenForResizeAsync()
|
||||
{
|
||||
while (true)
|
||||
{
|
||||
int currentWidth = Console.WindowWidth;
|
||||
int currentHeight = Console.WindowHeight;
|
||||
|
||||
if (currentWidth != this._lastWidth || currentHeight != this._lastHeight)
|
||||
{
|
||||
int oldWidth = this._lastWidth;
|
||||
int oldHeight = this._lastHeight;
|
||||
this._lastWidth = currentWidth;
|
||||
this._lastHeight = currentHeight;
|
||||
this.ConsoleResized?.Invoke(this, new ConsoleResizeEventArgs(oldWidth, oldHeight, currentWidth, currentHeight));
|
||||
}
|
||||
|
||||
await Task.Delay(16);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
// Copyright (c) Microsoft. All rights reserved.
|
||||
|
||||
namespace Harness.ConsoleReactiveFramework;
|
||||
|
||||
/// <summary>
|
||||
/// Event args for key press events, wrapping a <see cref="ConsoleKeyInfo"/>.
|
||||
/// </summary>
|
||||
public class KeyPressEventArgs : EventArgs
|
||||
{
|
||||
/// <summary>Gets the key information for the pressed key.</summary>
|
||||
public ConsoleKeyInfo KeyInfo { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="KeyPressEventArgs"/> class.
|
||||
/// </summary>
|
||||
/// <param name="keyInfo">The key information.</param>
|
||||
public KeyPressEventArgs(ConsoleKeyInfo keyInfo)
|
||||
{
|
||||
this.KeyInfo = keyInfo;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Singleton that polls for console key presses every 16ms and raises the
|
||||
/// <see cref="KeyPressed"/> event when a key is detected.
|
||||
/// </summary>
|
||||
public sealed class KeyEventListener
|
||||
{
|
||||
#pragma warning disable IDE0052 // Remove unread private members
|
||||
private readonly Task _task;
|
||||
#pragma warning restore IDE0052 // Remove unread private members
|
||||
|
||||
private KeyEventListener()
|
||||
{
|
||||
this._task = this.ListenForKeyPressesAsync();
|
||||
}
|
||||
|
||||
/// <summary>Gets the singleton instance of <see cref="KeyEventListener"/>.</summary>
|
||||
public static KeyEventListener Instance { get; } = new KeyEventListener();
|
||||
|
||||
/// <summary>Raised when a key is pressed in the console.</summary>
|
||||
public event EventHandler<KeyPressEventArgs>? KeyPressed;
|
||||
|
||||
private async Task ListenForKeyPressesAsync()
|
||||
{
|
||||
while (true)
|
||||
{
|
||||
while (Console.KeyAvailable)
|
||||
{
|
||||
var keyInfo = Console.ReadKey(intercept: true);
|
||||
this.KeyPressed?.Invoke(this, new KeyPressEventArgs(keyInfo));
|
||||
}
|
||||
|
||||
await Task.Delay(16);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,315 @@
|
||||
// Copyright (c) Microsoft. All rights reserved.
|
||||
|
||||
using Harness.ConsoleReactiveComponents;
|
||||
using Harness.ConsoleReactiveFramework;
|
||||
|
||||
namespace Harness.ConsoleSandbox;
|
||||
|
||||
/// <summary>
|
||||
/// Determines which component is shown in the bottom panel.
|
||||
/// </summary>
|
||||
public enum BottomPanelMode
|
||||
{
|
||||
/// <summary>Show the list selection component.</summary>
|
||||
ListSelection,
|
||||
|
||||
/// <summary>Show the text input component.</summary>
|
||||
TextInput
|
||||
}
|
||||
|
||||
public record AppComponentProps : ConsoleReactiveProps
|
||||
{
|
||||
public IReadOnlyList<string> Items { get; init; } = Array.Empty<string>();
|
||||
public IReadOnlyList<object> ScrollItems { get; init; } = [];
|
||||
|
||||
/// <summary>Gets the bottom panel mode.</summary>
|
||||
public BottomPanelMode Mode { get; init; } = BottomPanelMode.ListSelection;
|
||||
|
||||
/// <summary>Gets the prompt string for text input mode.</summary>
|
||||
public string Prompt { get; init; } = "> ";
|
||||
|
||||
/// <summary>Gets the placeholder text shown when the input is empty.</summary>
|
||||
public string Placeholder { get; init; } = "";
|
||||
|
||||
/// <summary>Gets the highlight color for the active list item. Defaults to <see cref="ConsoleColor.Cyan"/>.</summary>
|
||||
public ConsoleColor ListHighlightColor { get; init; } = ConsoleColor.Cyan;
|
||||
|
||||
/// <summary>Gets the placeholder text for the custom text input option in the list. If <c>null</c>, no custom option is shown.</summary>
|
||||
public string? ListCustomTextPlaceholder { get; init; }
|
||||
|
||||
/// <summary>Gets the foreground color for the rule borders. If <c>null</c>, uses the default terminal color.</summary>
|
||||
public ConsoleColor? RuleColor { get; init; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Internal state for the <see cref="AppComponent"/>.
|
||||
/// </summary>
|
||||
public record AppComponentState : ConsoleReactiveState
|
||||
{
|
||||
/// <summary>Gets the selected index in list selection mode.</summary>
|
||||
public int SelectedIndex { get; init; }
|
||||
|
||||
/// <summary>Gets the current input text being typed in text input mode.</summary>
|
||||
public string InputText { get; init; } = "";
|
||||
|
||||
/// <summary>Gets the current text being typed into the list's custom text option.</summary>
|
||||
public string ListInputText { get; init; } = "";
|
||||
}
|
||||
|
||||
public class AppComponent : ConsoleReactiveComponent<AppComponentProps, AppComponentState>
|
||||
{
|
||||
private readonly TopBottomRule _rule = new();
|
||||
private readonly ListSelection _listSelection = new();
|
||||
private readonly TextInput _textInput = new();
|
||||
private readonly TextScrollPanel _textScrollPanel;
|
||||
private readonly TextPanel _textPanel;
|
||||
private readonly Func<object, string> _renderItem;
|
||||
private readonly Action<string> _onTextInputSubmit;
|
||||
private readonly Action<string> _onListInputSubmit;
|
||||
private bool _resizedSinceLastRender;
|
||||
private int _lastScrollBottom;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="AppComponent"/> class.
|
||||
/// </summary>
|
||||
/// <param name="renderScrollItem">A delegate that renders a single scroll panel item and returns the text to display.</param>
|
||||
/// <param name="onTextInputSubmit">A callback invoked with the input text when the user presses Enter in text input mode.</param>
|
||||
/// <param name="onListInputSubmit">A callback invoked with the selected or typed text when the user presses Enter in list selection mode.</param>
|
||||
public AppComponent(Func<object, string> renderScrollItem, Action<string> onTextInputSubmit, Action<string> onListInputSubmit)
|
||||
{
|
||||
this._renderItem = renderScrollItem;
|
||||
this._onTextInputSubmit = onTextInputSubmit;
|
||||
this._onListInputSubmit = onListInputSubmit;
|
||||
this._textScrollPanel = new TextScrollPanel(renderScrollItem);
|
||||
this._textPanel = new TextPanel(renderScrollItem);
|
||||
this.State = new AppComponentState();
|
||||
KeyEventListener.Instance.KeyPressed += this.OnKeyPressed;
|
||||
ConsoleResizeListener.Instance.ConsoleResized += this.OnConsoleResized;
|
||||
}
|
||||
|
||||
private void OnKeyPressed(object? sender, KeyPressEventArgs e)
|
||||
{
|
||||
if (this.Props!.Mode == BottomPanelMode.TextInput)
|
||||
{
|
||||
this.HandleTextInputKey(e);
|
||||
}
|
||||
else
|
||||
{
|
||||
this.HandleListSelectionKey(e);
|
||||
}
|
||||
}
|
||||
|
||||
private void HandleTextInputKey(KeyPressEventArgs e)
|
||||
{
|
||||
if (e.KeyInfo.Key == ConsoleKey.Enter)
|
||||
{
|
||||
string text = this.State!.InputText;
|
||||
this.SetState(this.State with { InputText = "" });
|
||||
this._onTextInputSubmit(text);
|
||||
}
|
||||
else if (e.KeyInfo.Key == ConsoleKey.Backspace)
|
||||
{
|
||||
if (this.State!.InputText.Length > 0)
|
||||
{
|
||||
this.SetState(this.State with { InputText = this.State.InputText[..^1] });
|
||||
}
|
||||
}
|
||||
else if (e.KeyInfo.KeyChar != '\0' && !char.IsControl(e.KeyInfo.KeyChar))
|
||||
{
|
||||
this.SetState(this.State! with { InputText = this.State.InputText + e.KeyInfo.KeyChar });
|
||||
}
|
||||
}
|
||||
|
||||
private void HandleListSelectionKey(KeyPressEventArgs e)
|
||||
{
|
||||
int maxIndex = this.Props!.Items.Count - 1;
|
||||
if (this.Props.ListCustomTextPlaceholder != null)
|
||||
{
|
||||
maxIndex = this.Props.Items.Count; // extra option at the end
|
||||
}
|
||||
|
||||
bool isOnCustomTextOption = this.Props.ListCustomTextPlaceholder != null
|
||||
&& this.State!.SelectedIndex == this.Props.Items.Count;
|
||||
|
||||
if (e.KeyInfo.Key == ConsoleKey.UpArrow)
|
||||
{
|
||||
this.SetState(this.State! with { SelectedIndex = Math.Max(0, this.State.SelectedIndex - 1) });
|
||||
}
|
||||
else if (e.KeyInfo.Key == ConsoleKey.DownArrow)
|
||||
{
|
||||
this.SetState(this.State! with { SelectedIndex = Math.Min(maxIndex, this.State.SelectedIndex + 1) });
|
||||
}
|
||||
else if (e.KeyInfo.Key == ConsoleKey.Enter)
|
||||
{
|
||||
if (isOnCustomTextOption)
|
||||
{
|
||||
string text = this.State!.ListInputText;
|
||||
this.SetState(this.State with { ListInputText = "" });
|
||||
this._onListInputSubmit(text);
|
||||
}
|
||||
else
|
||||
{
|
||||
this._onListInputSubmit(this.Props.Items[this.State!.SelectedIndex]);
|
||||
}
|
||||
}
|
||||
else if (isOnCustomTextOption)
|
||||
{
|
||||
// Typing only works when on the custom text option
|
||||
if (e.KeyInfo.Key == ConsoleKey.Backspace)
|
||||
{
|
||||
if (this.State!.ListInputText.Length > 0)
|
||||
{
|
||||
this.SetState(this.State with { ListInputText = this.State.ListInputText[..^1] });
|
||||
}
|
||||
}
|
||||
else if (e.KeyInfo.KeyChar != '\0' && !char.IsControl(e.KeyInfo.KeyChar))
|
||||
{
|
||||
this.SetState(this.State! with { ListInputText = this.State.ListInputText + e.KeyInfo.KeyChar });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void OnConsoleResized(object? sender, ConsoleResizeEventArgs e)
|
||||
{
|
||||
this._resizedSinceLastRender = true;
|
||||
this.Render();
|
||||
}
|
||||
|
||||
public override void RenderCore(AppComponentProps props, AppComponentState state)
|
||||
{
|
||||
// Determine the text panel height for the last scroll item
|
||||
object? lastItem = props.ScrollItems.Count > 0 ? props.ScrollItems[^1] : null;
|
||||
IReadOnlyList<object> lastItems = lastItem != null ? [lastItem] : [];
|
||||
int textPanelHeight = TextPanel.CalculateHeight(lastItems, this._renderItem);
|
||||
if (textPanelHeight > 0)
|
||||
{
|
||||
textPanelHeight++; // Extra line for spacing between text panel and rule
|
||||
}
|
||||
|
||||
// Build the bottom panel child based on mode
|
||||
ConsoleReactiveComponent bottomChild;
|
||||
int bottomChildHeight;
|
||||
|
||||
if (props.Mode == BottomPanelMode.TextInput)
|
||||
{
|
||||
var textInputProps = new TextInputProps
|
||||
{
|
||||
Prompt = props.Prompt,
|
||||
Text = state.InputText,
|
||||
Placeholder = props.Placeholder
|
||||
};
|
||||
|
||||
bottomChildHeight = TextInput.CalculateHeight(textInputProps, Console.WindowWidth);
|
||||
this._textInput.Width = Console.WindowWidth;
|
||||
this._textInput.Height = bottomChildHeight;
|
||||
this._textInput.Props = textInputProps;
|
||||
bottomChild = this._textInput;
|
||||
}
|
||||
else
|
||||
{
|
||||
var listProps = new ListSelectionProps
|
||||
{
|
||||
Items = props.Items,
|
||||
SelectedIndex = state.SelectedIndex,
|
||||
HighlightColor = props.ListHighlightColor,
|
||||
CustomTextPlaceholder = props.ListCustomTextPlaceholder,
|
||||
CustomText = state.ListInputText
|
||||
};
|
||||
|
||||
bottomChildHeight = ListSelection.CalculateHeight(listProps);
|
||||
this._listSelection.Height = bottomChildHeight;
|
||||
this._listSelection.Props = listProps;
|
||||
bottomChild = this._listSelection;
|
||||
}
|
||||
|
||||
var ruleProps = new TopBottomRuleProps
|
||||
{
|
||||
Width = Console.WindowWidth,
|
||||
Color = props.RuleColor,
|
||||
Children = [bottomChild]
|
||||
};
|
||||
|
||||
int ruleHeight = TopBottomRule.CalculateHeight(ruleProps);
|
||||
int scrollBottom = Console.WindowHeight - ruleHeight - textPanelHeight;
|
||||
|
||||
// If scroll region changed or a clear is needed, reset everything
|
||||
if (this._resizedSinceLastRender || (this._lastScrollBottom != 0 && scrollBottom != this._lastScrollBottom))
|
||||
{
|
||||
Console.Write(AnsiEscapes.EraseEntireScreen);
|
||||
Console.Write(AnsiEscapes.EraseScrollbackBuffer);
|
||||
this._textScrollPanel.Reset();
|
||||
this._resizedSinceLastRender = false;
|
||||
}
|
||||
|
||||
this._lastScrollBottom = scrollBottom;
|
||||
|
||||
Console.Write(AnsiEscapes.SetScrollRegion(scrollBottom));
|
||||
|
||||
// Render text scroll panel in the scroll area (all items except the last)
|
||||
IReadOnlyList<object> scrollItems = props.ScrollItems.Count > 1
|
||||
? props.ScrollItems.Take(props.ScrollItems.Count - 1).ToList()
|
||||
: [];
|
||||
|
||||
this._textScrollPanel.X = 1;
|
||||
this._textScrollPanel.Y = 1;
|
||||
this._textScrollPanel.Width = Console.WindowWidth;
|
||||
this._textScrollPanel.Height = scrollBottom;
|
||||
this._textScrollPanel.Props = new TextScrollPanelProps
|
||||
{
|
||||
Items = scrollItems
|
||||
};
|
||||
this._textScrollPanel.Render();
|
||||
|
||||
// Render the text panel for the last (dynamic) item just below the scroll region
|
||||
this._textPanel.X = 1;
|
||||
this._textPanel.Y = scrollBottom + 1;
|
||||
this._textPanel.Width = Console.WindowWidth;
|
||||
this._textPanel.Height = textPanelHeight;
|
||||
this._textPanel.Props = new TextPanelProps
|
||||
{
|
||||
Items = lastItems,
|
||||
};
|
||||
this._textPanel.Render();
|
||||
|
||||
// Render the bottom rule + child below the text panel
|
||||
this._rule.X = 1;
|
||||
this._rule.Y = scrollBottom + textPanelHeight + 1;
|
||||
this._rule.Props = ruleProps;
|
||||
this._rule.Render();
|
||||
|
||||
// Position cursor for natural typing appearance
|
||||
if (props.Mode == BottomPanelMode.TextInput)
|
||||
{
|
||||
int promptLength = props.Prompt.Length;
|
||||
int textWidth = Console.WindowWidth - promptLength;
|
||||
int textLength = state.InputText.Length;
|
||||
|
||||
// The TextInput starts at rule.Y + 1 (first row inside the rule)
|
||||
int textInputY = this._rule.Y + 1;
|
||||
|
||||
if (textWidth <= 0 || textLength == 0)
|
||||
{
|
||||
// Cursor right after the prompt
|
||||
Console.Write(AnsiEscapes.MoveCursor(textInputY, promptLength + 1));
|
||||
}
|
||||
else
|
||||
{
|
||||
// Calculate which row and column the cursor lands on
|
||||
int cursorRow = textLength < textWidth ? 0 : 1 + ((textLength - textWidth) / textWidth);
|
||||
int cursorCol = textLength < textWidth ? textLength : (textLength - textWidth) % textWidth;
|
||||
Console.Write(AnsiEscapes.MoveCursor(textInputY + cursorRow, promptLength + cursorCol + 1));
|
||||
}
|
||||
}
|
||||
else if (props.Mode == BottomPanelMode.ListSelection
|
||||
&& props.ListCustomTextPlaceholder != null
|
||||
&& state.SelectedIndex == props.Items.Count)
|
||||
{
|
||||
// Cursor after the typed text in the custom text option
|
||||
// The custom text option is at rule.Y + 1 + Items.Count (0-based row inside rule)
|
||||
int customOptionY = this._rule.Y + 1 + props.Items.Count;
|
||||
// "> " prefix is 2 chars, then the typed text
|
||||
int cursorCol = 2 + state.ListInputText.Length + 1;
|
||||
Console.Write(AnsiEscapes.MoveCursor(customOptionY, cursorCol));
|
||||
}
|
||||
}
|
||||
}
|
||||
+8
-7
@@ -5,24 +5,25 @@ using Microsoft.Agents.AI;
|
||||
namespace Harness.Shared.Console.Commands;
|
||||
|
||||
/// <summary>
|
||||
/// Handles a console command (e.g., /todos, /mode). Command handlers are checked
|
||||
/// in order before user input is sent to the agent. The first handler that
|
||||
/// accepts the input prevents further handlers from being checked.
|
||||
/// Base class for console command handlers (e.g., /todos, /mode). Command handlers
|
||||
/// are checked in order before user input is sent to the agent. The first handler
|
||||
/// that accepts the input prevents further handlers from being checked.
|
||||
/// </summary>
|
||||
public interface ICommandHandler
|
||||
public abstract class CommandHandler
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets the help text for this command, displayed in the console header.
|
||||
/// Gets the help text for this command, displayed in the mode-and-help bar.
|
||||
/// Returns <see langword="null"/> if the command is not currently available.
|
||||
/// </summary>
|
||||
/// <returns>Help text like <c>"/todos (show todo list)"</c>, or <see langword="null"/>.</returns>
|
||||
string? GetHelpText();
|
||||
public abstract string? GetHelpText();
|
||||
|
||||
/// <summary>
|
||||
/// Attempts to handle the given user input.
|
||||
/// </summary>
|
||||
/// <param name="input">The raw user input string.</param>
|
||||
/// <param name="session">The current agent session.</param>
|
||||
/// <param name="ux">The UX container for rendering output.</param>
|
||||
/// <returns><see langword="true"/> if this handler handled the input; <see langword="false"/> otherwise.</returns>
|
||||
ValueTask<bool> TryHandleAsync(string input, AgentSession session);
|
||||
public abstract ValueTask<bool> TryHandleAsync(string input, AgentSession session, HarnessUXContainer ux);
|
||||
}
|
||||
+12
-15
@@ -7,7 +7,7 @@ namespace Harness.Shared.Console.Commands;
|
||||
/// <summary>
|
||||
/// Handles the <c>/mode</c> command to display or switch the current agent mode.
|
||||
/// </summary>
|
||||
internal sealed class ModeCommandHandler : ICommandHandler
|
||||
internal sealed class ModeCommandHandler : CommandHandler
|
||||
{
|
||||
private readonly AgentModeProvider? _modeProvider;
|
||||
private readonly IReadOnlyDictionary<string, ConsoleColor>? _modeColors;
|
||||
@@ -24,28 +24,28 @@ internal sealed class ModeCommandHandler : ICommandHandler
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
public string? GetHelpText() => this._modeProvider is not null ? "/mode [plan|execute] (show or switch mode)" : null;
|
||||
public override string? GetHelpText() => this._modeProvider is not null ? "/mode [plan|execute] (show or switch mode)" : null;
|
||||
|
||||
/// <inheritdoc/>
|
||||
public ValueTask<bool> TryHandleAsync(string input, AgentSession session)
|
||||
public override async ValueTask<bool> TryHandleAsync(string input, AgentSession session, HarnessUXContainer ux)
|
||||
{
|
||||
if (!input.StartsWith("/mode ", StringComparison.OrdinalIgnoreCase) && !input.Equals("/mode", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
return ValueTask.FromResult(false);
|
||||
return false;
|
||||
}
|
||||
|
||||
if (this._modeProvider is null)
|
||||
{
|
||||
System.Console.WriteLine("AgentModeProvider is not available.");
|
||||
return ValueTask.FromResult(true);
|
||||
await ux.WriteInfoLineAsync("AgentModeProvider is not available.").ConfigureAwait(false);
|
||||
return true;
|
||||
}
|
||||
|
||||
string[] parts = input.Split(' ', 2, StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
|
||||
if (parts.Length < 2)
|
||||
{
|
||||
string current = this._modeProvider.GetMode(session);
|
||||
System.Console.WriteLine($"\n Current mode: {current}\n");
|
||||
return ValueTask.FromResult(true);
|
||||
await ux.WriteInfoLineAsync($"Current mode: {current}").ConfigureAwait(false);
|
||||
return true;
|
||||
}
|
||||
|
||||
string newMode = parts[1];
|
||||
@@ -53,17 +53,14 @@ internal sealed class ModeCommandHandler : ICommandHandler
|
||||
try
|
||||
{
|
||||
this._modeProvider.SetMode(session, newMode);
|
||||
System.Console.ForegroundColor = ConsoleWriter.GetModeColor(newMode, this._modeColors);
|
||||
System.Console.WriteLine($"\n Switched to {newMode} mode.\n");
|
||||
System.Console.ResetColor();
|
||||
ux.CurrentMode = newMode;
|
||||
await ux.WriteInfoLineAsync($"Switched to {newMode} mode.", ModeColors.Get(newMode, this._modeColors)).ConfigureAwait(false);
|
||||
}
|
||||
catch (ArgumentException ex)
|
||||
{
|
||||
System.Console.ForegroundColor = ConsoleColor.Red;
|
||||
System.Console.WriteLine($"\n {ex}\n");
|
||||
System.Console.ResetColor();
|
||||
await ux.WriteInfoLineAsync(ex.Message, ConsoleColor.Red).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
return ValueTask.FromResult(true);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
+11
-17
@@ -7,7 +7,7 @@ namespace Harness.Shared.Console.Commands;
|
||||
/// <summary>
|
||||
/// Handles the <c>/todos</c> command to display the current todo list.
|
||||
/// </summary>
|
||||
internal sealed class TodoCommandHandler : ICommandHandler
|
||||
internal sealed class TodoCommandHandler : CommandHandler
|
||||
{
|
||||
private readonly TodoProvider? _todoProvider;
|
||||
|
||||
@@ -21,10 +21,10 @@ internal sealed class TodoCommandHandler : ICommandHandler
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
public string? GetHelpText() => this._todoProvider is not null ? "/todos (show todo list)" : null;
|
||||
public override string? GetHelpText() => this._todoProvider is not null ? "/todos (show todo list)" : null;
|
||||
|
||||
/// <inheritdoc/>
|
||||
public async ValueTask<bool> TryHandleAsync(string input, AgentSession session)
|
||||
public override async ValueTask<bool> TryHandleAsync(string input, AgentSession session, HarnessUXContainer ux)
|
||||
{
|
||||
if (!input.Equals("/todos", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
@@ -33,34 +33,28 @@ internal sealed class TodoCommandHandler : ICommandHandler
|
||||
|
||||
if (this._todoProvider is null)
|
||||
{
|
||||
System.Console.WriteLine("TodoProvider is not available.");
|
||||
await ux.WriteInfoLineAsync("TodoProvider is not available.").ConfigureAwait(false);
|
||||
return true;
|
||||
}
|
||||
|
||||
var todos = await this._todoProvider.GetAllTodosAsync(session).ConfigureAwait(false);
|
||||
if (todos.Count == 0)
|
||||
{
|
||||
System.Console.WriteLine("\n No todos yet.\n");
|
||||
await ux.WriteInfoLineAsync("No todos yet.").ConfigureAwait(false);
|
||||
return true;
|
||||
}
|
||||
|
||||
System.Console.WriteLine();
|
||||
System.Console.WriteLine(" ── Todo List ──");
|
||||
await ux.WriteInfoLineAsync("── Todo List ──").ConfigureAwait(false);
|
||||
foreach (var item in todos)
|
||||
{
|
||||
string status = item.IsComplete ? "✓" : "○";
|
||||
System.Console.ForegroundColor = item.IsComplete ? ConsoleColor.DarkGray : ConsoleColor.White;
|
||||
System.Console.Write($" [{status}] #{item.Id} {item.Title}");
|
||||
if (!string.IsNullOrWhiteSpace(item.Description))
|
||||
{
|
||||
System.Console.Write($" — {item.Description}");
|
||||
}
|
||||
|
||||
System.Console.WriteLine();
|
||||
ConsoleColor color = item.IsComplete ? ConsoleColor.DarkGray : ConsoleColor.White;
|
||||
string description = string.IsNullOrWhiteSpace(item.Description)
|
||||
? string.Empty
|
||||
: $" — {item.Description}";
|
||||
await ux.WriteInfoLineAsync($"[{status}] #{item.Id} {item.Title}{description}", color).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
System.Console.ResetColor();
|
||||
System.Console.WriteLine();
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
+71
@@ -0,0 +1,71 @@
|
||||
// Copyright (c) Microsoft. All rights reserved.
|
||||
|
||||
using Harness.ConsoleReactiveComponents;
|
||||
using Harness.ConsoleReactiveFramework;
|
||||
|
||||
namespace Harness.Shared.Console.Components;
|
||||
|
||||
/// <summary>
|
||||
/// Props for <see cref="AgentModeAndHelp"/>.
|
||||
/// </summary>
|
||||
public record AgentModeAndHelpProps : ConsoleReactiveProps
|
||||
{
|
||||
/// <summary>Gets or sets the current mode name (e.g. "plan", "execute"), or <see langword="null"/> if no mode is active.</summary>
|
||||
public string? Mode { get; set; }
|
||||
|
||||
/// <summary>Gets or sets the foreground color for the mode label.</summary>
|
||||
public ConsoleColor? ModeColor { get; set; }
|
||||
|
||||
/// <summary>Gets or sets the help text to display (e.g. available commands and exit info).</summary>
|
||||
public string? HelpText { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A component that renders a single fixed line below the bottom rule showing
|
||||
/// the current agent mode (in the mode colour) and available commands (in dark grey).
|
||||
/// </summary>
|
||||
public class AgentModeAndHelp : ConsoleReactiveComponent<AgentModeAndHelpProps, ConsoleReactiveState>
|
||||
{
|
||||
/// <summary>
|
||||
/// Calculates the height of the component.
|
||||
/// </summary>
|
||||
/// <param name="props">The component props.</param>
|
||||
/// <returns>1 if there is content to display; otherwise 0.</returns>
|
||||
public static int CalculateHeight(AgentModeAndHelpProps props) =>
|
||||
(props.Mode is not null || !string.IsNullOrEmpty(props.HelpText)) ? 1 : 0;
|
||||
|
||||
/// <inheritdoc />
|
||||
public override void RenderCore(AgentModeAndHelpProps props, ConsoleReactiveState state)
|
||||
{
|
||||
if (props.Mode is null && string.IsNullOrEmpty(props.HelpText))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
System.Console.Write(AnsiEscapes.SaveCursor);
|
||||
System.Console.Write(AnsiEscapes.MoveAndEraseLine(this.Y));
|
||||
|
||||
bool hasMode = props.Mode is not null;
|
||||
|
||||
if (hasMode)
|
||||
{
|
||||
if (props.ModeColor.HasValue)
|
||||
{
|
||||
System.Console.Write(AnsiEscapes.SetForegroundColor(props.ModeColor.Value));
|
||||
}
|
||||
|
||||
System.Console.Write($" [{props.Mode}]");
|
||||
System.Console.Write(AnsiEscapes.ResetAttributes);
|
||||
}
|
||||
|
||||
if (!string.IsNullOrEmpty(props.HelpText))
|
||||
{
|
||||
string prefix = hasMode ? " " : " ";
|
||||
System.Console.Write(AnsiEscapes.SetForegroundColor(ConsoleColor.DarkGray));
|
||||
System.Console.Write($"{prefix}{props.HelpText}");
|
||||
System.Console.Write(AnsiEscapes.ResetAttributes);
|
||||
}
|
||||
|
||||
System.Console.Write(AnsiEscapes.RestoreCursor);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,120 @@
|
||||
// Copyright (c) Microsoft. All rights reserved.
|
||||
|
||||
using Harness.ConsoleReactiveComponents;
|
||||
using Harness.ConsoleReactiveFramework;
|
||||
|
||||
namespace Harness.Shared.Console.Components;
|
||||
|
||||
/// <summary>
|
||||
/// Props for <see cref="AgentStatus"/>.
|
||||
/// </summary>
|
||||
public record AgentStatusProps : ConsoleReactiveProps
|
||||
{
|
||||
/// <summary>Gets or sets a value indicating whether the spinner is visible.</summary>
|
||||
public bool ShowSpinner { get; set; }
|
||||
|
||||
/// <summary>Gets or sets the formatted token usage text to display.</summary>
|
||||
public string? UsageText { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// State for <see cref="AgentStatus"/>.
|
||||
/// </summary>
|
||||
/// <param name="SpinnerIndex">The current spinner animation frame index.</param>
|
||||
public record AgentStatusState(int SpinnerIndex = 0) : ConsoleReactiveState;
|
||||
|
||||
/// <summary>
|
||||
/// A component that renders a single-line agent status bar with an animated spinner
|
||||
/// and token usage statistics. Positioned above the rule in the non-scrolling area.
|
||||
/// </summary>
|
||||
public class AgentStatus : ConsoleReactiveComponent<AgentStatusProps, AgentStatusState>, IDisposable
|
||||
{
|
||||
private static readonly string[] s_spinnerFrames =
|
||||
[
|
||||
"⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏",
|
||||
];
|
||||
|
||||
private readonly Timer _timer;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="AgentStatus"/> class.
|
||||
/// </summary>
|
||||
public AgentStatus()
|
||||
{
|
||||
this.State = new AgentStatusState();
|
||||
this._timer = new Timer(this.OnTimerTick, null, TimeSpan.Zero, TimeSpan.FromMilliseconds(100));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Calculates the height of the agent status component.
|
||||
/// </summary>
|
||||
/// <param name="props">The component props.</param>
|
||||
/// <returns>1 if the spinner or usage text is visible; otherwise 0.</returns>
|
||||
public static int CalculateHeight(AgentStatusProps props)
|
||||
{
|
||||
return (props.ShowSpinner || !string.IsNullOrEmpty(props.UsageText)) ? 1 : 0;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Disposes the internal spinner timer.
|
||||
/// </summary>
|
||||
public void Dispose()
|
||||
{
|
||||
this.Dispose(true);
|
||||
GC.SuppressFinalize(this);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Releases managed resources.
|
||||
/// </summary>
|
||||
/// <param name="disposing"><c>true</c> to release managed resources.</param>
|
||||
protected virtual void Dispose(bool disposing)
|
||||
{
|
||||
if (disposing)
|
||||
{
|
||||
this._timer.Dispose();
|
||||
}
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public override void RenderCore(AgentStatusProps props, AgentStatusState state)
|
||||
{
|
||||
if (!props.ShowSpinner && string.IsNullOrEmpty(props.UsageText))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
System.Console.Write(AnsiEscapes.SaveCursor);
|
||||
System.Console.Write(AnsiEscapes.MoveAndEraseLine(this.Y));
|
||||
|
||||
if (props.ShowSpinner)
|
||||
{
|
||||
string frame = s_spinnerFrames[state.SpinnerIndex];
|
||||
System.Console.Write(AnsiEscapes.SetForegroundColor(ConsoleColor.Cyan));
|
||||
System.Console.Write($" {frame} ");
|
||||
System.Console.Write(AnsiEscapes.ResetAttributes);
|
||||
}
|
||||
else
|
||||
{
|
||||
System.Console.Write(" ");
|
||||
}
|
||||
|
||||
if (!string.IsNullOrEmpty(props.UsageText))
|
||||
{
|
||||
System.Console.Write(AnsiEscapes.SetForegroundColor(ConsoleColor.DarkGray));
|
||||
System.Console.Write(props.UsageText);
|
||||
System.Console.Write(AnsiEscapes.ResetAttributes);
|
||||
}
|
||||
|
||||
System.Console.Write(AnsiEscapes.RestoreCursor);
|
||||
}
|
||||
|
||||
private void OnTimerTick(object? timerState)
|
||||
{
|
||||
if (this.Props is { ShowSpinner: true })
|
||||
{
|
||||
int nextIndex = ((this.State?.SpinnerIndex ?? 0) + 1) % s_spinnerFrames.Length;
|
||||
this.SetState(new AgentStatusState(nextIndex));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,278 +0,0 @@
|
||||
// Copyright (c) Microsoft. All rights reserved.
|
||||
|
||||
using Spectre.Console;
|
||||
|
||||
namespace Harness.Shared.Console;
|
||||
|
||||
/// <summary>
|
||||
/// Centralizes all console output and spinner management for the harness console.
|
||||
/// Observers write through this class so the spinner is automatically paused before output.
|
||||
/// </summary>
|
||||
public sealed class ConsoleWriter : IDisposable
|
||||
{
|
||||
private readonly Spinner _spinner = new();
|
||||
private readonly IReadOnlyDictionary<string, ConsoleColor>? _modeColors;
|
||||
|
||||
private bool _lastWasText;
|
||||
private bool _hasReceivedAnyText;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="ConsoleWriter"/> class.
|
||||
/// </summary>
|
||||
/// <param name="modeColors">Optional mapping of mode names to console colors.</param>
|
||||
public ConsoleWriter(IReadOnlyDictionary<string, ConsoleColor>? modeColors = null)
|
||||
{
|
||||
this._modeColors = modeColors;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the current agent mode (e.g., "plan", "execute").
|
||||
/// Used to determine the console color for mode-prefixed output.
|
||||
/// </summary>
|
||||
public string? CurrentMode { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Writes the agent response header (e.g., "[plan] Agent: ") and starts the spinner.
|
||||
/// </summary>
|
||||
public void WriteResponseHeader()
|
||||
{
|
||||
if (this.CurrentMode is not null)
|
||||
{
|
||||
System.Console.ForegroundColor = GetModeColor(this.CurrentMode, this._modeColors);
|
||||
System.Console.Write($"\n[{this.CurrentMode}] Agent: ");
|
||||
}
|
||||
else
|
||||
{
|
||||
System.Console.Write("\nAgent: ");
|
||||
}
|
||||
|
||||
this._lastWasText = true;
|
||||
this._hasReceivedAnyText = false;
|
||||
this._spinner.Start();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Writes informational output with automatic prefix spacing, without a trailing newline.
|
||||
/// Use when continuation content will be appended on the same line.
|
||||
/// </summary>
|
||||
/// <param name="text">The informational text to write (without leading newline/indent — added automatically).</param>
|
||||
/// <param name="color">Optional console color for the text.</param>
|
||||
public async Task WriteInfoAsync(string text, ConsoleColor? color = null)
|
||||
{
|
||||
await this.WriteInfoCoreAsync(text, color, newLine: false);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Writes informational output with automatic prefix spacing, followed by a newline.
|
||||
/// </summary>
|
||||
/// <param name="text">The informational text to write (without leading newline/indent — added automatically).</param>
|
||||
/// <param name="color">Optional console color for the text.</param>
|
||||
public async Task WriteInfoLineAsync(string text, ConsoleColor? color = null)
|
||||
{
|
||||
await this.WriteInfoCoreAsync(text, color, newLine: true);
|
||||
}
|
||||
|
||||
private async Task WriteInfoCoreAsync(string text, ConsoleColor? color, bool newLine)
|
||||
{
|
||||
await this._spinner.StopAsync();
|
||||
|
||||
string prefix = this._lastWasText ? "\n\n " : " ";
|
||||
this._lastWasText = false;
|
||||
|
||||
System.Console.ForegroundColor = color ?? GetModeColor(this.CurrentMode, this._modeColors);
|
||||
|
||||
if (newLine)
|
||||
{
|
||||
System.Console.WriteLine(prefix + text);
|
||||
}
|
||||
else
|
||||
{
|
||||
System.Console.Write(prefix + text);
|
||||
}
|
||||
|
||||
System.Console.ForegroundColor = GetModeColor(this.CurrentMode, this._modeColors);
|
||||
|
||||
this._spinner.Start();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Writes text output from the agent, managing line break state.
|
||||
/// Ensures a newline is written before the first text output.
|
||||
/// </summary>
|
||||
/// <param name="text">The text to write.</param>
|
||||
/// <param name="color">Optional console color override for this text.</param>
|
||||
public async Task WriteTextAsync(string text, ConsoleColor? color = null)
|
||||
{
|
||||
await this._spinner.StopAsync();
|
||||
|
||||
if (!this._lastWasText)
|
||||
{
|
||||
System.Console.Write("\n");
|
||||
this._lastWasText = true;
|
||||
}
|
||||
|
||||
this._hasReceivedAnyText = true;
|
||||
|
||||
if (color.HasValue)
|
||||
{
|
||||
System.Console.ForegroundColor = color.Value;
|
||||
}
|
||||
|
||||
System.Console.Write(text);
|
||||
|
||||
if (color.HasValue)
|
||||
{
|
||||
System.Console.ForegroundColor = GetModeColor(this.CurrentMode, this._modeColors);
|
||||
}
|
||||
|
||||
this._spinner.Start();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Reads a line of input from the console, pausing the spinner while waiting for input.
|
||||
/// Optionally displays a prompt before reading. The prompt is rendered between
|
||||
/// two horizontal rules for visual clarity.
|
||||
/// </summary>
|
||||
/// <param name="prompt">Optional prompt text to display before reading input.</param>
|
||||
/// <param name="promptColor">Optional console color for the prompt text.</param>
|
||||
/// <returns>The line read from the console, or <c>null</c> if no input is available.</returns>
|
||||
public async Task<string?> ReadLineAsync(string? prompt = null, ConsoleColor? promptColor = null)
|
||||
{
|
||||
await this._spinner.StopAsync();
|
||||
|
||||
if (prompt is not null)
|
||||
{
|
||||
System.Console.WriteLine();
|
||||
AnsiConsole.Write(this.CreateModeRule());
|
||||
|
||||
if (promptColor.HasValue)
|
||||
{
|
||||
System.Console.ForegroundColor = promptColor.Value;
|
||||
}
|
||||
|
||||
System.Console.Write($" {prompt}");
|
||||
|
||||
if (promptColor.HasValue)
|
||||
{
|
||||
System.Console.ForegroundColor = GetModeColor(this.CurrentMode, this._modeColors);
|
||||
}
|
||||
}
|
||||
|
||||
string? input = System.Console.ReadLine();
|
||||
|
||||
if (prompt is not null)
|
||||
{
|
||||
AnsiConsole.Write(this.CreateModeRule());
|
||||
}
|
||||
|
||||
this._lastWasText = false;
|
||||
return input;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Presents a selection prompt with the given choices, plus an option to type a custom response.
|
||||
/// Uses Spectre.Console <see cref="SelectionPrompt{T}"/> for interactive arrow-key selection.
|
||||
/// </summary>
|
||||
/// <param name="title">The title/question displayed above the selection list.</param>
|
||||
/// <param name="choices">The list of choices to present.</param>
|
||||
/// <returns>The selected choice text, or the custom-typed response.</returns>
|
||||
public async Task<string> ReadSelectionAsync(string title, IList<string> choices)
|
||||
{
|
||||
await this._spinner.StopAsync();
|
||||
|
||||
AnsiConsole.Write(this.CreateModeRule());
|
||||
|
||||
const string FreeformOption = "✏️ Type a custom response...";
|
||||
var allChoices = choices.Concat([FreeformOption]).ToList();
|
||||
|
||||
var prompt = new SelectionPrompt<string>()
|
||||
.Title($" [bold]{Markup.Escape(title)}[/]")
|
||||
.PageSize(10)
|
||||
.AddChoices(allChoices);
|
||||
|
||||
string selection = AnsiConsole.Prompt(prompt);
|
||||
|
||||
if (selection == FreeformOption)
|
||||
{
|
||||
var textPrompt = new TextPrompt<string>(" [grey]Response:[/]");
|
||||
selection = AnsiConsole.Prompt(textPrompt);
|
||||
}
|
||||
|
||||
AnsiConsole.MarkupLine($" [dim]→ {Markup.Escape(selection)}[/]");
|
||||
AnsiConsole.Write(this.CreateModeRule());
|
||||
|
||||
this._lastWasText = false;
|
||||
return selection;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Writes the stream-complete footer (handles "no text response" fallback, resets color).
|
||||
/// </summary>
|
||||
public async Task WriteStreamFooterAsync(bool hasFollowUpMessages)
|
||||
{
|
||||
await this._spinner.StopAsync();
|
||||
|
||||
if (!this._hasReceivedAnyText && !hasFollowUpMessages)
|
||||
{
|
||||
System.Console.ForegroundColor = ConsoleColor.DarkYellow;
|
||||
System.Console.Write("\n (no text response from agent)");
|
||||
}
|
||||
|
||||
System.Console.ResetColor();
|
||||
System.Console.WriteLine();
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
public void Dispose()
|
||||
{
|
||||
this._spinner.Dispose();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the console color associated with a mode name, using the provided color map.
|
||||
/// </summary>
|
||||
internal static ConsoleColor GetModeColor(string? mode, IReadOnlyDictionary<string, ConsoleColor>? modeColors = null)
|
||||
{
|
||||
if (mode is null)
|
||||
{
|
||||
return ConsoleColor.Gray;
|
||||
}
|
||||
|
||||
if (modeColors is not null && modeColors.TryGetValue(mode, out var color))
|
||||
{
|
||||
return color;
|
||||
}
|
||||
|
||||
return ConsoleColor.Gray;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a <see cref="Rule"/> styled with the current mode color.
|
||||
/// </summary>
|
||||
internal Rule CreateModeRule()
|
||||
{
|
||||
var spectreColor = ToSpectreColor(GetModeColor(this.CurrentMode, this._modeColors));
|
||||
return new Rule().RuleStyle(new Style(spectreColor));
|
||||
}
|
||||
|
||||
internal static Color ToSpectreColor(ConsoleColor consoleColor) => consoleColor switch
|
||||
{
|
||||
ConsoleColor.Black => Color.Black,
|
||||
ConsoleColor.DarkBlue => Color.Blue,
|
||||
ConsoleColor.DarkGreen => Color.Green,
|
||||
ConsoleColor.DarkCyan => Color.Teal,
|
||||
ConsoleColor.DarkRed => Color.Red,
|
||||
ConsoleColor.DarkMagenta => Color.Purple,
|
||||
ConsoleColor.DarkYellow => Color.Olive,
|
||||
ConsoleColor.Gray => Color.Silver,
|
||||
ConsoleColor.DarkGray => Color.Grey,
|
||||
ConsoleColor.Blue => Color.Blue1,
|
||||
ConsoleColor.Green => Color.Green1,
|
||||
ConsoleColor.Cyan => Color.Aqua,
|
||||
ConsoleColor.Red => Color.Red1,
|
||||
ConsoleColor.Magenta => Color.Fuchsia,
|
||||
ConsoleColor.Yellow => Color.Yellow,
|
||||
ConsoleColor.White => Color.White,
|
||||
_ => Color.Silver,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,553 @@
|
||||
// Copyright (c) Microsoft. All rights reserved.
|
||||
|
||||
using Harness.ConsoleReactiveComponents;
|
||||
using Harness.ConsoleReactiveFramework;
|
||||
using Harness.Shared.Console.Components;
|
||||
|
||||
namespace Harness.Shared.Console;
|
||||
|
||||
/// <summary>
|
||||
/// Determines which component is shown in the bottom panel.
|
||||
/// </summary>
|
||||
public enum BottomPanelMode
|
||||
{
|
||||
/// <summary>Show the text input component for user input.</summary>
|
||||
TextInput,
|
||||
|
||||
/// <summary>Show the list selection component for interactive prompts.</summary>
|
||||
ListSelection,
|
||||
|
||||
/// <summary>Show a disabled input indicator during agent streaming.</summary>
|
||||
Streaming,
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Event arguments for the <see cref="HarnessAppComponent.InputSubmitted"/> event.
|
||||
/// </summary>
|
||||
public sealed class InputSubmittedEventArgs : EventArgs
|
||||
{
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="InputSubmittedEventArgs"/> class.
|
||||
/// </summary>
|
||||
/// <param name="text">The submitted text.</param>
|
||||
/// <param name="mode">The bottom panel mode in which the input was submitted.</param>
|
||||
public InputSubmittedEventArgs(string text, BottomPanelMode mode)
|
||||
{
|
||||
this.Text = text;
|
||||
this.Mode = mode;
|
||||
}
|
||||
|
||||
/// <summary>Gets the submitted text.</summary>
|
||||
public string Text { get; }
|
||||
|
||||
/// <summary>Gets the bottom panel mode in which the input was submitted.</summary>
|
||||
public BottomPanelMode Mode { get; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Props for <see cref="HarnessAppComponent"/>.
|
||||
/// </summary>
|
||||
public record HarnessAppComponentProps : ConsoleReactiveProps
|
||||
{
|
||||
/// <summary>Gets or sets the list selection choices (for ListSelection mode).</summary>
|
||||
public IReadOnlyList<string> Items { get; set; } = Array.Empty<string>();
|
||||
|
||||
/// <summary>Gets or sets the scroll items (output entries) to render in the scroll panel.</summary>
|
||||
public IReadOnlyList<object> ScrollItems { get; set; } = [];
|
||||
|
||||
/// <summary>Gets or sets the bottom panel mode.</summary>
|
||||
public BottomPanelMode Mode { get; set; } = BottomPanelMode.TextInput;
|
||||
|
||||
/// <summary>Gets or sets the prompt string for text input mode.</summary>
|
||||
public string Prompt { get; set; } = "You: ";
|
||||
|
||||
/// <summary>Gets or sets the placeholder text shown when the input is empty.</summary>
|
||||
public string Placeholder { get; set; } = "";
|
||||
|
||||
/// <summary>Gets or sets the highlight color for the active list item.</summary>
|
||||
public ConsoleColor ListHighlightColor { get; set; } = ConsoleColor.Cyan;
|
||||
|
||||
/// <summary>Gets or sets the placeholder text for the custom text input option in the list.</summary>
|
||||
public string? ListCustomTextPlaceholder { get; set; }
|
||||
|
||||
/// <summary>Gets or sets the foreground color for the rule borders and mode label.</summary>
|
||||
public ConsoleColor? ModeColor { get; set; }
|
||||
|
||||
/// <summary>Gets or sets the current mode name displayed below the bottom rule (e.g. "plan").</summary>
|
||||
public string? ModeText { get; set; }
|
||||
|
||||
/// <summary>Gets or sets the help text displayed below the bottom rule (available commands).</summary>
|
||||
public string? HelpText { get; set; }
|
||||
|
||||
/// <summary>Gets or sets the title text displayed above the list selection (for interactive prompts).</summary>
|
||||
public string? ListTitle { get; set; }
|
||||
|
||||
/// <summary>Gets or sets a value indicating whether input is enabled during streaming.</summary>
|
||||
public bool InputEnabled { get; set; }
|
||||
|
||||
/// <summary>Gets or sets the prompt to show during streaming when input is disabled.</summary>
|
||||
public string StreamingPrompt { get; set; } = "(agent is running...)";
|
||||
|
||||
/// <summary>Gets or sets a value indicating whether the agent status spinner is visible.</summary>
|
||||
public bool ShowSpinner { get; set; }
|
||||
|
||||
/// <summary>Gets or sets the formatted token usage text to display in the status bar.</summary>
|
||||
public string? UsageText { get; set; }
|
||||
|
||||
/// <summary>Gets or sets the queued input items to display above the rule.</summary>
|
||||
public IReadOnlyList<object> QueuedItems { get; set; } = [];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Internal state for <see cref="HarnessAppComponent"/>.
|
||||
/// </summary>
|
||||
public record HarnessAppComponentState : ConsoleReactiveState
|
||||
{
|
||||
/// <summary>Gets the selected index in list selection mode.</summary>
|
||||
public int SelectedIndex { get; init; }
|
||||
|
||||
/// <summary>Gets the current input text being typed.</summary>
|
||||
public string InputText { get; init; } = "";
|
||||
|
||||
/// <summary>Gets the current text being typed into the list's custom text option.</summary>
|
||||
public string ListInputText { get; init; } = "";
|
||||
|
||||
/// <summary>Gets the current console width in columns.</summary>
|
||||
public int ConsoleWidth { get; init; }
|
||||
|
||||
/// <summary>Gets the current console height in rows.</summary>
|
||||
public int ConsoleHeight { get; init; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The main application component for the Harness console. Manages the scroll region
|
||||
/// and bottom panel (text input, list selection, or streaming indicator), and emits
|
||||
/// an <see cref="InputSubmitted"/> event when the user submits text in any mode.
|
||||
/// </summary>
|
||||
public class HarnessAppComponent : ConsoleReactiveComponent<HarnessAppComponentProps, HarnessAppComponentState>, IDisposable
|
||||
{
|
||||
private readonly TopBottomRule _rule = new();
|
||||
private readonly ListSelection _listSelection = new();
|
||||
private readonly TextInput _textInput = new();
|
||||
private readonly TextScrollPanel _textScrollPanel;
|
||||
private readonly TextPanel _textPanel;
|
||||
private readonly TextPanel _queuedPanel;
|
||||
private readonly AgentStatus _agentStatus = new();
|
||||
private readonly AgentModeAndHelp _modeAndHelp = new();
|
||||
private readonly Func<object, string> _renderItem;
|
||||
private bool _resizedSinceLastRender;
|
||||
private bool _deactivated;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="HarnessAppComponent"/> class.
|
||||
/// </summary>
|
||||
/// <param name="renderScrollItem">A delegate that renders a single output entry and returns the text to display.</param>
|
||||
public HarnessAppComponent(Func<object, string> renderScrollItem)
|
||||
{
|
||||
this._renderItem = renderScrollItem;
|
||||
this._textScrollPanel = new TextScrollPanel(renderScrollItem);
|
||||
this._textPanel = new TextPanel(renderScrollItem);
|
||||
this._queuedPanel = new TextPanel(renderScrollItem);
|
||||
this.State = new HarnessAppComponentState
|
||||
{
|
||||
ConsoleWidth = System.Console.WindowWidth,
|
||||
ConsoleHeight = System.Console.WindowHeight,
|
||||
};
|
||||
KeyEventListener.Instance.KeyPressed += this.OnKeyPressed;
|
||||
ConsoleResizeListener.Instance.ConsoleResized += this.OnConsoleResized;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the 1-based row number of the last row in the output scroll region.
|
||||
/// </summary>
|
||||
public int ScrollRegionBottom { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// Occurs when the user submits input via Enter, in any mode (text input, list selection,
|
||||
/// or streaming injection). Consumers inspect <see cref="InputSubmittedEventArgs.Mode"/>
|
||||
/// to decide how to handle the submission.
|
||||
/// </summary>
|
||||
public event EventHandler<InputSubmittedEventArgs>? InputSubmitted;
|
||||
|
||||
/// <summary>
|
||||
/// Deactivates the component, resetting the scroll region and unsubscribing from events.
|
||||
/// This method is idempotent and safe to call multiple times.
|
||||
/// </summary>
|
||||
public void Deactivate()
|
||||
{
|
||||
if (this._deactivated)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
this._deactivated = true;
|
||||
this._agentStatus.Dispose();
|
||||
KeyEventListener.Instance.KeyPressed -= this.OnKeyPressed;
|
||||
ConsoleResizeListener.Instance.ConsoleResized -= this.OnConsoleResized;
|
||||
System.Console.Write(AnsiEscapes.ResetScrollRegion);
|
||||
System.Console.Write(AnsiEscapes.MoveCursor(System.Console.WindowHeight, 1));
|
||||
System.Console.WriteLine();
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
public void Dispose()
|
||||
{
|
||||
this.Dispose(true);
|
||||
GC.SuppressFinalize(this);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Releases managed resources.
|
||||
/// </summary>
|
||||
/// <param name="disposing"><c>true</c> to release managed resources.</param>
|
||||
protected virtual void Dispose(bool disposing)
|
||||
{
|
||||
if (disposing)
|
||||
{
|
||||
this.Deactivate();
|
||||
}
|
||||
}
|
||||
|
||||
private void OnKeyPressed(object? sender, KeyPressEventArgs e)
|
||||
{
|
||||
if (this.Props!.Mode == BottomPanelMode.TextInput)
|
||||
{
|
||||
this.HandleTextInputKey(e);
|
||||
}
|
||||
else if (this.Props.Mode == BottomPanelMode.ListSelection)
|
||||
{
|
||||
this.HandleListSelectionKey(e);
|
||||
}
|
||||
else if (this.Props.Mode == BottomPanelMode.Streaming && this.Props.InputEnabled)
|
||||
{
|
||||
this.HandleStreamingInputKey(e);
|
||||
}
|
||||
}
|
||||
|
||||
private void HandleTextInputKey(KeyPressEventArgs e)
|
||||
{
|
||||
if (e.KeyInfo.Key == ConsoleKey.Enter)
|
||||
{
|
||||
string text = this.State!.InputText;
|
||||
if (string.IsNullOrWhiteSpace(text))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
this.SetState(this.State with { InputText = "" });
|
||||
this.InputSubmitted?.Invoke(this, new InputSubmittedEventArgs(text, BottomPanelMode.TextInput));
|
||||
}
|
||||
else if (e.KeyInfo.Key == ConsoleKey.Backspace)
|
||||
{
|
||||
if (this.State!.InputText.Length > 0)
|
||||
{
|
||||
this.SetState(this.State with { InputText = this.State.InputText[..^1] });
|
||||
}
|
||||
}
|
||||
else if (e.KeyInfo.KeyChar != '\0' && !char.IsControl(e.KeyInfo.KeyChar))
|
||||
{
|
||||
this.SetState(this.State! with { InputText = this.State.InputText + e.KeyInfo.KeyChar });
|
||||
}
|
||||
}
|
||||
|
||||
private void HandleListSelectionKey(KeyPressEventArgs e)
|
||||
{
|
||||
int maxIndex = this.Props!.Items.Count - 1;
|
||||
if (this.Props.ListCustomTextPlaceholder != null)
|
||||
{
|
||||
maxIndex = this.Props.Items.Count;
|
||||
}
|
||||
|
||||
bool isOnCustomTextOption = this.Props.ListCustomTextPlaceholder != null
|
||||
&& this.State!.SelectedIndex == this.Props.Items.Count;
|
||||
|
||||
if (e.KeyInfo.Key == ConsoleKey.UpArrow)
|
||||
{
|
||||
this.SetState(this.State! with { SelectedIndex = Math.Max(0, this.State.SelectedIndex - 1) });
|
||||
}
|
||||
else if (e.KeyInfo.Key == ConsoleKey.DownArrow)
|
||||
{
|
||||
this.SetState(this.State! with { SelectedIndex = Math.Min(maxIndex, this.State.SelectedIndex + 1) });
|
||||
}
|
||||
else if (e.KeyInfo.Key == ConsoleKey.Enter)
|
||||
{
|
||||
string result = isOnCustomTextOption
|
||||
? this.State!.ListInputText
|
||||
: this.Props.Items[this.State!.SelectedIndex];
|
||||
|
||||
this.SetState(this.State with { ListInputText = "", SelectedIndex = 0 });
|
||||
this.InputSubmitted?.Invoke(this, new InputSubmittedEventArgs(result, BottomPanelMode.ListSelection));
|
||||
}
|
||||
else if (isOnCustomTextOption)
|
||||
{
|
||||
if (e.KeyInfo.Key == ConsoleKey.Backspace)
|
||||
{
|
||||
if (this.State!.ListInputText.Length > 0)
|
||||
{
|
||||
this.SetState(this.State with { ListInputText = this.State.ListInputText[..^1] });
|
||||
}
|
||||
}
|
||||
else if (e.KeyInfo.KeyChar != '\0' && !char.IsControl(e.KeyInfo.KeyChar))
|
||||
{
|
||||
this.SetState(this.State! with { ListInputText = this.State.ListInputText + e.KeyInfo.KeyChar });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void HandleStreamingInputKey(KeyPressEventArgs e)
|
||||
{
|
||||
// During streaming with input enabled, capture text for message injection
|
||||
if (e.KeyInfo.Key == ConsoleKey.Enter)
|
||||
{
|
||||
string text = this.State!.InputText;
|
||||
if (string.IsNullOrWhiteSpace(text))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
this.SetState(this.State with { InputText = "" });
|
||||
this.InputSubmitted?.Invoke(this, new InputSubmittedEventArgs(text, BottomPanelMode.Streaming));
|
||||
}
|
||||
else if (e.KeyInfo.Key == ConsoleKey.Backspace)
|
||||
{
|
||||
if (this.State!.InputText.Length > 0)
|
||||
{
|
||||
this.SetState(this.State with { InputText = this.State.InputText[..^1] });
|
||||
}
|
||||
}
|
||||
else if (e.KeyInfo.KeyChar != '\0' && !char.IsControl(e.KeyInfo.KeyChar))
|
||||
{
|
||||
this.SetState(this.State! with { InputText = this.State.InputText + e.KeyInfo.KeyChar });
|
||||
}
|
||||
}
|
||||
|
||||
private void OnConsoleResized(object? sender, ConsoleResizeEventArgs e)
|
||||
{
|
||||
this._resizedSinceLastRender = true;
|
||||
this.SetState(this.State! with
|
||||
{
|
||||
ConsoleWidth = e.NewWidth,
|
||||
ConsoleHeight = e.NewHeight,
|
||||
});
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public override void RenderCore(HarnessAppComponentProps props, HarnessAppComponentState state)
|
||||
{
|
||||
// Determine the text panel height for the last scroll item
|
||||
IReadOnlyList<object> lastItems = props.ScrollItems.Count > 0
|
||||
? [props.ScrollItems[^1]]
|
||||
: [];
|
||||
int textPanelHeight = TextPanel.CalculateHeight(lastItems, this._renderItem);
|
||||
if (textPanelHeight > 0)
|
||||
{
|
||||
textPanelHeight++; // Extra line for spacing between text panel and rule
|
||||
}
|
||||
|
||||
// Calculate queued items panel height
|
||||
int queuedPanelHeight = TextPanel.CalculateHeight(props.QueuedItems, this._renderItem);
|
||||
|
||||
// Build the bottom panel child based on mode
|
||||
ConsoleReactiveComponent bottomChild;
|
||||
int bottomChildHeight;
|
||||
|
||||
if (props.Mode == BottomPanelMode.ListSelection)
|
||||
{
|
||||
var listProps = new ListSelectionProps
|
||||
{
|
||||
Title = props.ListTitle,
|
||||
Items = props.Items,
|
||||
SelectedIndex = state.SelectedIndex,
|
||||
HighlightColor = props.ListHighlightColor,
|
||||
CustomTextPlaceholder = props.ListCustomTextPlaceholder,
|
||||
CustomText = state.ListInputText,
|
||||
};
|
||||
|
||||
bottomChildHeight = ListSelection.CalculateHeight(listProps);
|
||||
this._listSelection.Height = bottomChildHeight;
|
||||
this._listSelection.Props = listProps;
|
||||
bottomChild = this._listSelection;
|
||||
}
|
||||
else if (props.Mode == BottomPanelMode.Streaming)
|
||||
{
|
||||
TextInputProps textInputProps;
|
||||
if (props.InputEnabled)
|
||||
{
|
||||
textInputProps = new TextInputProps
|
||||
{
|
||||
Prompt = props.Prompt,
|
||||
Text = state.InputText,
|
||||
Placeholder = props.Placeholder,
|
||||
};
|
||||
}
|
||||
else
|
||||
{
|
||||
textInputProps = new TextInputProps
|
||||
{
|
||||
Prompt = props.Prompt,
|
||||
Text = "",
|
||||
Placeholder = props.StreamingPrompt,
|
||||
};
|
||||
}
|
||||
|
||||
bottomChildHeight = TextInput.CalculateHeight(textInputProps, state.ConsoleWidth);
|
||||
this._textInput.Width = state.ConsoleWidth;
|
||||
this._textInput.Height = bottomChildHeight;
|
||||
this._textInput.Props = textInputProps;
|
||||
bottomChild = this._textInput;
|
||||
}
|
||||
else
|
||||
{
|
||||
var textInputProps = new TextInputProps
|
||||
{
|
||||
Prompt = props.Prompt,
|
||||
Text = state.InputText,
|
||||
Placeholder = props.Placeholder,
|
||||
};
|
||||
|
||||
bottomChildHeight = TextInput.CalculateHeight(textInputProps, state.ConsoleWidth);
|
||||
this._textInput.Width = state.ConsoleWidth;
|
||||
this._textInput.Height = bottomChildHeight;
|
||||
this._textInput.Props = textInputProps;
|
||||
bottomChild = this._textInput;
|
||||
}
|
||||
|
||||
var ruleProps = new TopBottomRuleProps
|
||||
{
|
||||
Width = state.ConsoleWidth,
|
||||
Color = props.ModeColor,
|
||||
Children = [bottomChild],
|
||||
};
|
||||
|
||||
// Calculate the agent status height
|
||||
var agentStatusProps = new AgentStatusProps
|
||||
{
|
||||
ShowSpinner = props.ShowSpinner,
|
||||
UsageText = props.UsageText,
|
||||
};
|
||||
int agentStatusHeight = AgentStatus.CalculateHeight(agentStatusProps);
|
||||
|
||||
// Calculate the mode-and-help height
|
||||
var modeAndHelpProps = new AgentModeAndHelpProps
|
||||
{
|
||||
Mode = props.ModeText,
|
||||
ModeColor = props.ModeColor,
|
||||
HelpText = props.HelpText,
|
||||
};
|
||||
int modeAndHelpHeight = AgentModeAndHelp.CalculateHeight(modeAndHelpProps);
|
||||
|
||||
int ruleHeight = TopBottomRule.CalculateHeight(ruleProps);
|
||||
int scrollBottom = Math.Max(1, state.ConsoleHeight - ruleHeight - textPanelHeight - agentStatusHeight - queuedPanelHeight - modeAndHelpHeight);
|
||||
|
||||
// If scroll region changed or a clear is needed, reset everything
|
||||
if (this._resizedSinceLastRender || (this.ScrollRegionBottom != 0 && scrollBottom != this.ScrollRegionBottom))
|
||||
{
|
||||
System.Console.Write(AnsiEscapes.EraseEntireScreen);
|
||||
System.Console.Write(AnsiEscapes.EraseScrollbackBuffer);
|
||||
this._textScrollPanel.Reset();
|
||||
this._resizedSinceLastRender = false;
|
||||
}
|
||||
|
||||
this.ScrollRegionBottom = scrollBottom;
|
||||
|
||||
System.Console.Write(AnsiEscapes.SetScrollRegion(scrollBottom));
|
||||
|
||||
// Render text scroll panel in the scroll area (all items except the last)
|
||||
IReadOnlyList<object> scrollItems = props.ScrollItems.Count > 1
|
||||
? props.ScrollItems.Take(props.ScrollItems.Count - 1).ToList()
|
||||
: [];
|
||||
|
||||
this._textScrollPanel.X = 1;
|
||||
this._textScrollPanel.Y = 1;
|
||||
this._textScrollPanel.Width = state.ConsoleWidth;
|
||||
this._textScrollPanel.Height = scrollBottom;
|
||||
this._textScrollPanel.Props = new TextScrollPanelProps
|
||||
{
|
||||
Items = scrollItems,
|
||||
};
|
||||
this._textScrollPanel.Render();
|
||||
|
||||
// Render the text panel for the last (dynamic) item just below the scroll region
|
||||
this._textPanel.X = 1;
|
||||
this._textPanel.Y = scrollBottom + 1;
|
||||
this._textPanel.Width = state.ConsoleWidth;
|
||||
this._textPanel.Height = textPanelHeight;
|
||||
this._textPanel.Props = new TextPanelProps
|
||||
{
|
||||
Items = lastItems,
|
||||
};
|
||||
this._textPanel.Render();
|
||||
|
||||
// Render queued input items between text panel and agent status
|
||||
int queuedPanelY = scrollBottom + textPanelHeight + 1;
|
||||
this._queuedPanel.X = 1;
|
||||
this._queuedPanel.Y = queuedPanelY;
|
||||
this._queuedPanel.Width = state.ConsoleWidth;
|
||||
this._queuedPanel.Height = queuedPanelHeight;
|
||||
this._queuedPanel.Props = new TextPanelProps
|
||||
{
|
||||
Items = props.QueuedItems,
|
||||
};
|
||||
this._queuedPanel.Render();
|
||||
|
||||
// Render the agent status line between queued items and rule
|
||||
int agentStatusY = queuedPanelY + queuedPanelHeight;
|
||||
this._agentStatus.X = 1;
|
||||
this._agentStatus.Y = agentStatusY;
|
||||
this._agentStatus.Width = state.ConsoleWidth;
|
||||
this._agentStatus.Height = agentStatusHeight;
|
||||
this._agentStatus.Props = agentStatusProps;
|
||||
this._agentStatus.Render();
|
||||
|
||||
// Render the bottom rule + child below the agent status
|
||||
this._rule.X = 1;
|
||||
this._rule.Y = agentStatusY + agentStatusHeight;
|
||||
this._rule.Props = ruleProps;
|
||||
this._rule.Render();
|
||||
|
||||
// Render the mode-and-help line below the bottom rule
|
||||
int modeAndHelpY = this._rule.Y + ruleHeight;
|
||||
this._modeAndHelp.X = 1;
|
||||
this._modeAndHelp.Y = modeAndHelpY;
|
||||
this._modeAndHelp.Width = state.ConsoleWidth;
|
||||
this._modeAndHelp.Height = modeAndHelpHeight;
|
||||
this._modeAndHelp.Props = modeAndHelpProps;
|
||||
this._modeAndHelp.Render();
|
||||
|
||||
// Position cursor for natural typing appearance
|
||||
this.PositionCursor(props, state);
|
||||
}
|
||||
|
||||
private void PositionCursor(HarnessAppComponentProps props, HarnessAppComponentState state)
|
||||
{
|
||||
if (props.Mode == BottomPanelMode.TextInput
|
||||
|| (props.Mode == BottomPanelMode.Streaming && props.InputEnabled))
|
||||
{
|
||||
int promptLength = props.Prompt.Length;
|
||||
int textWidth = state.ConsoleWidth - promptLength;
|
||||
int textLength = state.InputText.Length;
|
||||
|
||||
int textInputY = this._rule.Y + 1;
|
||||
|
||||
if (textWidth <= 0 || textLength == 0)
|
||||
{
|
||||
System.Console.Write(AnsiEscapes.MoveCursor(textInputY, promptLength + 1));
|
||||
}
|
||||
else
|
||||
{
|
||||
int cursorRow = textLength < textWidth ? 0 : 1 + ((textLength - textWidth) / textWidth);
|
||||
int cursorCol = textLength < textWidth ? textLength : (textLength - textWidth) % textWidth;
|
||||
System.Console.Write(AnsiEscapes.MoveCursor(textInputY + cursorRow, promptLength + cursorCol + 1));
|
||||
}
|
||||
}
|
||||
else if (props.Mode == BottomPanelMode.ListSelection
|
||||
&& props.ListCustomTextPlaceholder != null
|
||||
&& state.SelectedIndex == props.Items.Count)
|
||||
{
|
||||
int titleLines = props.ListTitle?.Split('\n').Length ?? 0;
|
||||
int customOptionY = this._rule.Y + 1 + titleLines + props.Items.Count;
|
||||
int cursorCol = 2 + state.ListInputText.Length + 1;
|
||||
System.Console.Write(AnsiEscapes.MoveCursor(customOptionY, cursorCol));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -34,42 +34,55 @@ public static class HarnessConsole
|
||||
nameof(options));
|
||||
}
|
||||
|
||||
System.Console.WriteLine($"=== {title} ===");
|
||||
System.Console.WriteLine(userPrompt);
|
||||
|
||||
var todoProvider = agent.GetService<TodoProvider>();
|
||||
var modeProvider = agent.GetService<AgentModeProvider>();
|
||||
var messageInjector = agent.GetService<MessageInjectingChatClient>();
|
||||
|
||||
// Build command handlers.
|
||||
var commandHandlers = new List<ICommandHandler>
|
||||
var commandHandlers = new List<CommandHandler>
|
||||
{
|
||||
new TodoCommandHandler(todoProvider),
|
||||
new ModeCommandHandler(modeProvider, options.ModeColors),
|
||||
};
|
||||
|
||||
var commands = commandHandlers
|
||||
AgentSession session = await agent.CreateSessionAsync();
|
||||
|
||||
using var ux = new HarnessUXContainer(
|
||||
placeholder: userPrompt,
|
||||
initialMode: modeProvider?.GetMode(session),
|
||||
inputEnabled: messageInjector is not null,
|
||||
modeColors: options.ModeColors);
|
||||
|
||||
// Streaming-mode submissions are enqueued for injection; the queued display
|
||||
// is then refreshed from the injector's current pending list.
|
||||
ux.StreamingInputReceived += (sender, e) =>
|
||||
{
|
||||
if (messageInjector is null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
messageInjector.EnqueueMessages(session, [new ChatMessage(ChatRole.User, e.Text)]);
|
||||
ux.ShowQueuedMessages(messageInjector.GetPendingMessages(session));
|
||||
};
|
||||
|
||||
var commandHelp = commandHandlers
|
||||
.Select(h => h.GetHelpText())
|
||||
.Where(t => t is not null)
|
||||
.Append("exit (quit)");
|
||||
.Append("exit (quit)")!;
|
||||
|
||||
System.Console.WriteLine($"Commands: {string.Join(", ", commands)}");
|
||||
System.Console.WriteLine();
|
||||
ux.Initialize(title, commandHelp!, messageInjector is not null);
|
||||
|
||||
AgentSession session = await agent.CreateSessionAsync();
|
||||
using var writer = new ConsoleWriter(options.ModeColors);
|
||||
writer.CurrentMode = modeProvider?.GetMode(session);
|
||||
string userInput = await ux.WaitForInputAsync();
|
||||
|
||||
string prompt = BuildUserPrompt(modeProvider, session);
|
||||
string? userInput = await writer.ReadLineAsync(prompt);
|
||||
|
||||
// Main loop to run a command or agent and get the next user command/input.
|
||||
while (!string.IsNullOrWhiteSpace(userInput) && !userInput.Equals("exit", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
ux.WriteUserInputEcho(userInput);
|
||||
|
||||
// Check command handlers first — first one to handle wins.
|
||||
bool handled = false;
|
||||
foreach (var handler in commandHandlers)
|
||||
{
|
||||
if (await handler.TryHandleAsync(userInput, session).ConfigureAwait(false))
|
||||
if (await handler.TryHandleAsync(userInput, session, ux).ConfigureAwait(false))
|
||||
{
|
||||
handled = true;
|
||||
break;
|
||||
@@ -78,14 +91,14 @@ public static class HarnessConsole
|
||||
|
||||
if (!handled)
|
||||
{
|
||||
await RunAgentTurnAsync(agent, session, modeProvider, options, writer, userInput);
|
||||
await RunAgentTurnAsync(agent, session, modeProvider, messageInjector, options, ux, userInput);
|
||||
}
|
||||
|
||||
writer.CurrentMode = modeProvider?.GetMode(session);
|
||||
prompt = BuildUserPrompt(modeProvider, session);
|
||||
userInput = await writer.ReadLineAsync(prompt);
|
||||
ux.CurrentMode = modeProvider?.GetMode(session);
|
||||
userInput = await ux.WaitForInputAsync();
|
||||
}
|
||||
|
||||
ux.Deactivate();
|
||||
System.Console.ResetColor();
|
||||
System.Console.WriteLine("Goodbye!");
|
||||
}
|
||||
@@ -99,27 +112,27 @@ public static class HarnessConsole
|
||||
AIAgent agent,
|
||||
AgentSession session,
|
||||
AgentModeProvider? modeProvider,
|
||||
MessageInjectingChatClient? messageInjector,
|
||||
HarnessConsoleOptions options,
|
||||
ConsoleWriter writer,
|
||||
HarnessUXContainer ux,
|
||||
string userInput)
|
||||
{
|
||||
IList<ChatMessage>? nextMessages = [new ChatMessage(ChatRole.User, userInput)];
|
||||
IReadOnlyList<ChatMessage> lastPendingMessages = messageInjector?.GetPendingMessages(session) ?? [];
|
||||
|
||||
while (nextMessages is not null)
|
||||
{
|
||||
// Build observers for this invocation (may change between iterations due to mode changes).
|
||||
var observers = CreateObservers(options, modeProvider, session);
|
||||
|
||||
// Build run options — observers may inject ResponseFormat, etc.
|
||||
var runOptions = new AgentRunOptions();
|
||||
foreach (var observer in observers)
|
||||
{
|
||||
observer.ConfigureRunOptions(runOptions);
|
||||
}
|
||||
|
||||
// Stream the response, fanning out to all observers.
|
||||
writer.CurrentMode = modeProvider?.GetMode(session);
|
||||
writer.WriteResponseHeader();
|
||||
ux.CurrentMode = modeProvider?.GetMode(session);
|
||||
ux.BeginStreaming();
|
||||
ux.BeginStreamingOutput();
|
||||
|
||||
try
|
||||
{
|
||||
@@ -129,9 +142,9 @@ public static class HarnessConsole
|
||||
if (modeProvider is not null)
|
||||
{
|
||||
string currentMode = modeProvider.GetMode(session);
|
||||
if (currentMode != writer.CurrentMode)
|
||||
if (currentMode != ux.CurrentMode)
|
||||
{
|
||||
writer.CurrentMode = currentMode;
|
||||
ux.CurrentMode = currentMode;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -139,7 +152,7 @@ public static class HarnessConsole
|
||||
{
|
||||
foreach (var observer in observers)
|
||||
{
|
||||
await observer.OnContentAsync(writer, content);
|
||||
await observer.OnContentAsync(ux, content);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -147,22 +160,32 @@ public static class HarnessConsole
|
||||
{
|
||||
foreach (var observer in observers)
|
||||
{
|
||||
await observer.OnTextAsync(writer, update.Text);
|
||||
await observer.OnTextAsync(ux, update.Text);
|
||||
}
|
||||
}
|
||||
|
||||
SyncQueuedMessageDisplay(messageInjector, session, ux, ref lastPendingMessages);
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
await writer.WriteInfoLineAsync($"❌ Stream error: {ex.GetType().Name}:\n{ex}", ConsoleColor.Red);
|
||||
await ux.WriteInfoLineAsync($"❌ Stream error: {ex.GetType().Name}:\n{ex}", ConsoleColor.Red);
|
||||
}
|
||||
|
||||
// Collect messages from all observers.
|
||||
// Final sync after streaming — messages may have been consumed during the last iteration.
|
||||
SyncQueuedMessageDisplay(messageInjector, session, ux, ref lastPendingMessages);
|
||||
|
||||
// Stop spinner before observer completions (which may prompt for input).
|
||||
ux.StopSpinner();
|
||||
|
||||
// Close the streaming output to provide visual separation from observer output.
|
||||
await ux.EndStreamingOutputAsync();
|
||||
|
||||
var combinedMessages = new List<ChatMessage>();
|
||||
bool hasObserverMessages = false;
|
||||
foreach (var observer in observers)
|
||||
{
|
||||
var messages = await observer.OnStreamCompleteAsync(writer, agent, session, options);
|
||||
var messages = await observer.OnStreamCompleteAsync(ux, agent, session, options);
|
||||
if (messages is { Count: > 0 })
|
||||
{
|
||||
combinedMessages.AddRange(messages);
|
||||
@@ -170,11 +193,44 @@ public static class HarnessConsole
|
||||
}
|
||||
}
|
||||
|
||||
await writer.WriteStreamFooterAsync(hasFollowUpMessages: hasObserverMessages);
|
||||
await ux.WriteNoTextWarningAsync(hasFollowUpMessages: hasObserverMessages);
|
||||
|
||||
ux.EndStreaming();
|
||||
|
||||
nextMessages = combinedMessages.Count > 0 ? combinedMessages : null;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Synchronizes the queued items display with the message injector's pending messages.
|
||||
/// Messages that have been consumed (drained by the service) are echoed to the output
|
||||
/// area as regular user-input entries.
|
||||
/// </summary>
|
||||
private static void SyncQueuedMessageDisplay(
|
||||
MessageInjectingChatClient? messageInjector,
|
||||
AgentSession session,
|
||||
HarnessUXContainer ux,
|
||||
ref IReadOnlyList<ChatMessage> lastPendingMessages)
|
||||
{
|
||||
if (messageInjector is null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var pending = messageInjector.GetPendingMessages(session);
|
||||
|
||||
// If previously pending messages exceed current pending count, some were consumed.
|
||||
int consumedCount = lastPendingMessages.Count - pending.Count;
|
||||
for (int i = 0; i < consumedCount && i < lastPendingMessages.Count; i++)
|
||||
{
|
||||
string text = lastPendingMessages[i].Text ?? string.Empty;
|
||||
ux.WriteUserInputEcho(text);
|
||||
}
|
||||
|
||||
lastPendingMessages = pending;
|
||||
ux.ShowQueuedMessages(pending);
|
||||
}
|
||||
|
||||
private static List<ConsoleObserver> CreateObservers(HarnessConsoleOptions options, AgentModeProvider? modeProvider, AgentSession session)
|
||||
{
|
||||
var observers = new List<ConsoleObserver>
|
||||
@@ -186,7 +242,6 @@ public static class HarnessConsole
|
||||
new UsageDisplayObserver(options.MaxContextWindowTokens, options.MaxOutputTokens),
|
||||
};
|
||||
|
||||
// Add the appropriate output observer based on the current mode.
|
||||
if (options.EnablePlanningUx
|
||||
&& modeProvider is not null
|
||||
&& string.Equals(modeProvider.GetMode(session), options.PlanningModeName, StringComparison.OrdinalIgnoreCase))
|
||||
@@ -200,15 +255,4 @@ public static class HarnessConsole
|
||||
|
||||
return observers;
|
||||
}
|
||||
|
||||
private static string BuildUserPrompt(AgentModeProvider? modeProvider, AgentSession session)
|
||||
{
|
||||
if (modeProvider is not null)
|
||||
{
|
||||
string mode = modeProvider.GetMode(session);
|
||||
return $"[{mode}] You: ";
|
||||
}
|
||||
|
||||
return "You: ";
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,478 @@
|
||||
// Copyright (c) Microsoft. All rights reserved.
|
||||
|
||||
using Harness.ConsoleReactiveComponents;
|
||||
using Microsoft.Extensions.AI;
|
||||
|
||||
namespace Harness.Shared.Console;
|
||||
|
||||
/// <summary>
|
||||
/// Event arguments raised when the user submits text while the bottom panel is in
|
||||
/// streaming mode (i.e. an agent turn is in progress).
|
||||
/// </summary>
|
||||
public sealed class StreamingInputReceivedEventArgs : EventArgs
|
||||
{
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="StreamingInputReceivedEventArgs"/> class.
|
||||
/// </summary>
|
||||
/// <param name="text">The submitted text.</param>
|
||||
public StreamingInputReceivedEventArgs(string text)
|
||||
{
|
||||
this.Text = text;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the submitted text.
|
||||
/// </summary>
|
||||
public string Text { get; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Façade over the harness UI: owns the <see cref="HarnessAppComponent"/>, manages
|
||||
/// its props, dispatches input submissions, and provides the high-level read/write
|
||||
/// operations used by observers, command handlers, and the harness loop.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// All callers interact with the UI exclusively through this class. The underlying
|
||||
/// <see cref="HarnessAppComponent"/> and its props are an implementation detail and
|
||||
/// must not be exposed.
|
||||
/// </remarks>
|
||||
public sealed class HarnessUXContainer : IDisposable
|
||||
{
|
||||
/// <summary>
|
||||
/// The prompt displayed in the bottom-panel input area.
|
||||
/// </summary>
|
||||
private const string UserPrompt = "> ";
|
||||
|
||||
private readonly IReadOnlyDictionary<string, ConsoleColor>? _modeColors;
|
||||
private readonly List<object> _outputItems = [];
|
||||
private readonly HarnessAppComponent _appComponent;
|
||||
private readonly object _outputLock = new();
|
||||
|
||||
private TaskCompletionSource<string>? _pendingInputTcs;
|
||||
private OutputEntryType? _lastEntryType;
|
||||
private bool _hasReceivedAnyText;
|
||||
private OutputEntry? _currentStreamingEntry;
|
||||
private string? _currentMode;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="HarnessUXContainer"/> class.
|
||||
/// </summary>
|
||||
/// <param name="placeholder">Placeholder text shown when the input is empty.</param>
|
||||
/// <param name="initialMode">The current agent mode, used to colour the rule and prompt.</param>
|
||||
/// <param name="inputEnabled">Whether the bottom-panel input accepts keystrokes during streaming.</param>
|
||||
/// <param name="modeColors">Optional mapping of mode names to console colors.</param>
|
||||
public HarnessUXContainer(
|
||||
string placeholder,
|
||||
string? initialMode,
|
||||
bool inputEnabled,
|
||||
IReadOnlyDictionary<string, ConsoleColor>? modeColors = null)
|
||||
{
|
||||
this._modeColors = modeColors;
|
||||
this._currentMode = initialMode;
|
||||
|
||||
this._appComponent = new HarnessAppComponent(RenderOutputEntry)
|
||||
{
|
||||
Props = new HarnessAppComponentProps
|
||||
{
|
||||
ScrollItems = this._outputItems,
|
||||
Mode = BottomPanelMode.TextInput,
|
||||
Prompt = UserPrompt,
|
||||
Placeholder = placeholder,
|
||||
ModeColor = ModeColors.Get(initialMode, modeColors),
|
||||
ModeText = initialMode,
|
||||
InputEnabled = inputEnabled,
|
||||
},
|
||||
};
|
||||
|
||||
this._appComponent.InputSubmitted += this.OnInputSubmitted;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Raised when the user submits text while the bottom panel is in streaming mode.
|
||||
/// Subscribers typically enqueue the text into a message-injecting chat client.
|
||||
/// </summary>
|
||||
public event EventHandler<StreamingInputReceivedEventArgs>? StreamingInputReceived;
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the current agent mode (e.g. "plan", "execute"). Updating this
|
||||
/// also refreshes the rule colour and bottom-panel prompt to match the new mode.
|
||||
/// </summary>
|
||||
public string? CurrentMode
|
||||
{
|
||||
get => this._currentMode;
|
||||
set
|
||||
{
|
||||
this._currentMode = value;
|
||||
this._appComponent.Props = this._appComponent.Props! with
|
||||
{
|
||||
ModeColor = ModeColors.Get(value, this._modeColors),
|
||||
ModeText = value,
|
||||
};
|
||||
this._appComponent.Render();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Performs the initial screen clear, sets the help text in the mode-and-help bar,
|
||||
/// and adds the title to the output area.
|
||||
/// </summary>
|
||||
/// <param name="title">The title displayed in the console header.</param>
|
||||
/// <param name="commandHelpTexts">The command help strings displayed in the mode-and-help bar.</param>
|
||||
/// <param name="messageInjectionActive">Whether streaming-time message injection is enabled.</param>
|
||||
public void Initialize(string title, IEnumerable<string> commandHelpTexts, bool messageInjectionActive)
|
||||
{
|
||||
// Set the help text on the mode-and-help bar (persists below the rule).
|
||||
this._appComponent.Props = this._appComponent.Props! with
|
||||
{
|
||||
HelpText = string.Join(", ", commandHelpTexts),
|
||||
ModeText = this._currentMode,
|
||||
};
|
||||
|
||||
System.Console.Write(AnsiEscapes.EraseEntireScreen);
|
||||
System.Console.Write(AnsiEscapes.EraseScrollbackBuffer);
|
||||
this._appComponent.Render();
|
||||
|
||||
this.AppendOutputEntries(
|
||||
new OutputEntry(OutputEntryType.InfoLine, $"=== {title} ===\n", ConsoleColor.White),
|
||||
new OutputEntry(OutputEntryType.InfoLine, "\n"));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Restores the cursor and exits the alternate screen, ending the interactive UI.
|
||||
/// </summary>
|
||||
public void Deactivate() => this._appComponent.Deactivate();
|
||||
|
||||
/// <summary>
|
||||
/// Switches the bottom panel to streaming mode and starts the spinner.
|
||||
/// </summary>
|
||||
public void BeginStreaming()
|
||||
{
|
||||
this._appComponent.Props = this._appComponent.Props! with
|
||||
{
|
||||
Mode = BottomPanelMode.Streaming,
|
||||
ShowSpinner = true,
|
||||
};
|
||||
this._appComponent.Render();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Stops the spinner without leaving streaming mode. Use between the end of the
|
||||
/// stream and any observer-driven prompts (e.g. tool approvals).
|
||||
/// </summary>
|
||||
public void StopSpinner()
|
||||
{
|
||||
this._appComponent.Props = this._appComponent.Props! with { ShowSpinner = false };
|
||||
this._appComponent.Render();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Switches the bottom panel back to text-input mode and stops the spinner.
|
||||
/// </summary>
|
||||
public void EndStreaming()
|
||||
{
|
||||
this._appComponent.Props = this._appComponent.Props! with
|
||||
{
|
||||
Mode = BottomPanelMode.TextInput,
|
||||
ShowSpinner = false,
|
||||
};
|
||||
this._appComponent.Render();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Resets per-turn streaming bookkeeping in preparation for a new agent turn.
|
||||
/// </summary>
|
||||
public void BeginStreamingOutput()
|
||||
{
|
||||
this._hasReceivedAnyText = false;
|
||||
this._currentStreamingEntry = null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sets the formatted usage text shown on the agent status bar.
|
||||
/// </summary>
|
||||
public void SetUsageText(string usageText)
|
||||
{
|
||||
this._appComponent.Props = this._appComponent.Props! with { UsageText = usageText };
|
||||
this._appComponent.Render();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Clears the usage text from the agent status bar.
|
||||
/// </summary>
|
||||
public void ClearUsageText()
|
||||
{
|
||||
this._appComponent.Props = this._appComponent.Props! with { UsageText = null };
|
||||
this._appComponent.Render();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Replaces the queued-message display with one entry per pending message.
|
||||
/// </summary>
|
||||
public void ShowQueuedMessages(IReadOnlyList<ChatMessage> pending)
|
||||
{
|
||||
var newQueued = new List<object>(pending.Count);
|
||||
foreach (var msg in pending)
|
||||
{
|
||||
string text = msg.Text ?? string.Empty;
|
||||
newQueued.Add(new OutputEntry(OutputEntryType.UserInput, $" 💬 {text}\n", ConsoleColor.DarkGray));
|
||||
}
|
||||
|
||||
this._appComponent.Props = this._appComponent.Props! with { QueuedItems = newQueued };
|
||||
this._appComponent.Render();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Echoes a submitted user input as a regular user-input entry in the output area,
|
||||
/// using the current mode-aware prompt prefix.
|
||||
/// </summary>
|
||||
/// <param name="text">The user-entered text.</param>
|
||||
public void WriteUserInputEcho(string text)
|
||||
{
|
||||
this.AppendOutputEntries(new OutputEntry(
|
||||
OutputEntryType.UserInput,
|
||||
$"\nYou: {text}\n",
|
||||
ConsoleColor.Green));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Writes informational output as an output entry, without a trailing newline.
|
||||
/// </summary>
|
||||
public Task WriteInfoAsync(string text, ConsoleColor? color = null) =>
|
||||
this.WriteInfoCoreAsync(text, color, newLine: false);
|
||||
|
||||
/// <summary>
|
||||
/// Writes informational output as an output entry, followed by a newline.
|
||||
/// </summary>
|
||||
public Task WriteInfoLineAsync(string text, ConsoleColor? color = null) =>
|
||||
this.WriteInfoCoreAsync(text, color, newLine: true);
|
||||
|
||||
private Task WriteInfoCoreAsync(string text, ConsoleColor? color, bool newLine)
|
||||
{
|
||||
// Add a blank line separator when transitioning from streaming text or user input.
|
||||
string prefix = this._lastEntryType is OutputEntryType.StreamingText or OutputEntryType.StreamFooter
|
||||
? "\n\n "
|
||||
: " ";
|
||||
|
||||
string fullText = newLine ? prefix + text + "\n" : prefix + text;
|
||||
this.AppendOutputEntries(new OutputEntry(
|
||||
OutputEntryType.InfoLine,
|
||||
fullText,
|
||||
color ?? ModeColors.Get(this.CurrentMode, this._modeColors)));
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Writes streaming text output from the agent. Successive calls accumulate into a
|
||||
/// single streaming entry that is re-rendered by the text panel.
|
||||
/// </summary>
|
||||
public Task WriteTextAsync(string text, ConsoleColor? color = null)
|
||||
{
|
||||
lock (this._outputLock)
|
||||
{
|
||||
this._lastEntryType = OutputEntryType.StreamingText;
|
||||
this._hasReceivedAnyText = true;
|
||||
|
||||
ConsoleColor effectiveColor = color ?? ModeColors.Get(this.CurrentMode, this._modeColors);
|
||||
|
||||
if (this._currentStreamingEntry is not null)
|
||||
{
|
||||
this._currentStreamingEntry = this._currentStreamingEntry with
|
||||
{
|
||||
Text = this._currentStreamingEntry.Text + text,
|
||||
};
|
||||
this._outputItems[^1] = this._currentStreamingEntry;
|
||||
}
|
||||
else
|
||||
{
|
||||
const string Prefix = "\n";
|
||||
this._currentStreamingEntry = new OutputEntry(OutputEntryType.StreamingText, Prefix + text, effectiveColor);
|
||||
this._outputItems.Add(this._currentStreamingEntry);
|
||||
}
|
||||
|
||||
this._appComponent.Props = this._appComponent.Props! with
|
||||
{
|
||||
ScrollItems = new List<object>(this._outputItems),
|
||||
};
|
||||
}
|
||||
|
||||
this._appComponent.Render();
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Writes a blank-line separator to visually close the streaming output section.
|
||||
/// Call before observer completions so their output is visually separated.
|
||||
/// </summary>
|
||||
public Task EndStreamingOutputAsync()
|
||||
{
|
||||
lock (this._outputLock)
|
||||
{
|
||||
this._outputItems.Add(new OutputEntry(OutputEntryType.StreamFooter, "\n"));
|
||||
this._currentStreamingEntry = null;
|
||||
this._lastEntryType = OutputEntryType.StreamFooter;
|
||||
this._appComponent.Props = this._appComponent.Props! with
|
||||
{
|
||||
ScrollItems = new List<object>(this._outputItems),
|
||||
};
|
||||
}
|
||||
|
||||
this._appComponent.Render();
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Shows a "(no text response from agent)" warning if no text was received
|
||||
/// and no observer produced follow-up messages. Call after observer completions.
|
||||
/// </summary>
|
||||
/// <param name="hasFollowUpMessages">Whether any observer produced follow-up messages.</param>
|
||||
public Task WriteNoTextWarningAsync(bool hasFollowUpMessages)
|
||||
{
|
||||
if (!this._hasReceivedAnyText && !hasFollowUpMessages)
|
||||
{
|
||||
this.AppendOutputEntries(new OutputEntry(
|
||||
OutputEntryType.StreamFooter,
|
||||
" (no text response from agent)\n",
|
||||
ConsoleColor.DarkYellow));
|
||||
}
|
||||
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Reads a line of input from the user. If <paramref name="prompt"/> is supplied
|
||||
/// it is rendered as an info line above the input row before reading.
|
||||
/// </summary>
|
||||
public async Task<string?> ReadLineAsync(string? prompt = null, ConsoleColor? promptColor = null)
|
||||
{
|
||||
if (prompt is not null)
|
||||
{
|
||||
ConsoleColor ruleColor = ModeColors.Get(this.CurrentMode, this._modeColors);
|
||||
this.AppendOutputEntries(
|
||||
new OutputEntry(OutputEntryType.InfoLine, "\n", ruleColor),
|
||||
new OutputEntry(OutputEntryType.InfoLine, $" {prompt}", promptColor ?? ruleColor));
|
||||
}
|
||||
|
||||
this._appComponent.Props = this._appComponent.Props! with { Mode = BottomPanelMode.TextInput };
|
||||
this._appComponent.Render();
|
||||
|
||||
string input = await this.WaitForInputAsync();
|
||||
|
||||
this.AppendOutputEntries(new OutputEntry(
|
||||
OutputEntryType.UserInput,
|
||||
$"\nYou: {input}\n",
|
||||
ConsoleColor.Green));
|
||||
|
||||
return input;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Presents a selection prompt with the given choices and waits for the user's
|
||||
/// selection. The title is displayed above the list in the bottom panel. After
|
||||
/// selection the bottom panel is restored to text-input mode and both the question
|
||||
/// and selection are echoed in the output area.
|
||||
/// </summary>
|
||||
public async Task<string> ReadSelectionAsync(string title, IList<string> choices)
|
||||
{
|
||||
this._appComponent.Props = this._appComponent.Props! with
|
||||
{
|
||||
Mode = BottomPanelMode.ListSelection,
|
||||
Items = choices.ToList(),
|
||||
ListTitle = title,
|
||||
ListCustomTextPlaceholder = "✏️ Type a custom response...",
|
||||
};
|
||||
this._appComponent.Render();
|
||||
|
||||
string selection = await this.WaitForInputAsync();
|
||||
|
||||
this._appComponent.Props = this._appComponent.Props with { Mode = BottomPanelMode.TextInput };
|
||||
|
||||
this.AppendOutputEntries(
|
||||
new OutputEntry(
|
||||
OutputEntryType.InfoLine,
|
||||
$"\n {title}\n",
|
||||
ModeColors.Get(this.CurrentMode, this._modeColors)),
|
||||
new OutputEntry(
|
||||
OutputEntryType.UserInput,
|
||||
$"\nYou: {selection}\n",
|
||||
ConsoleColor.Green));
|
||||
|
||||
return selection;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Awaits the next non-streaming user input submission.
|
||||
/// </summary>
|
||||
public Task<string> WaitForInputAsync()
|
||||
{
|
||||
this._pendingInputTcs = new TaskCompletionSource<string>(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
return this._pendingInputTcs.Task;
|
||||
}
|
||||
|
||||
private void OnInputSubmitted(object? sender, InputSubmittedEventArgs e)
|
||||
{
|
||||
if (e.Mode == BottomPanelMode.Streaming)
|
||||
{
|
||||
this.StreamingInputReceived?.Invoke(this, new StreamingInputReceivedEventArgs(e.Text));
|
||||
}
|
||||
else
|
||||
{
|
||||
var waiter = this._pendingInputTcs;
|
||||
this._pendingInputTcs = null;
|
||||
waiter?.TrySetResult(e.Text);
|
||||
}
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
public void Dispose()
|
||||
{
|
||||
this._appComponent.InputSubmitted -= this.OnInputSubmitted;
|
||||
this._appComponent.Deactivate();
|
||||
this._appComponent.Dispose();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Renders an <see cref="OutputEntry"/> to a string with ANSI color codes.
|
||||
/// Used as the render delegate for the <see cref="HarnessAppComponent"/>.
|
||||
/// </summary>
|
||||
private static string RenderOutputEntry(object item)
|
||||
{
|
||||
if (item is not OutputEntry entry)
|
||||
{
|
||||
return item?.ToString() ?? string.Empty;
|
||||
}
|
||||
|
||||
if (entry.Color.HasValue)
|
||||
{
|
||||
return $"{AnsiEscapes.SetForegroundColor(entry.Color.Value)}{entry.Text}{AnsiEscapes.ResetAttributes}";
|
||||
}
|
||||
|
||||
return entry.Text;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Appends one or more output entries to the output list under lock,
|
||||
/// updates <see cref="_lastEntryType"/> to the last entry's type, and renders.
|
||||
/// </summary>
|
||||
private void AppendOutputEntries(params OutputEntry[] entries)
|
||||
{
|
||||
lock (this._outputLock)
|
||||
{
|
||||
foreach (OutputEntry entry in entries)
|
||||
{
|
||||
this._outputItems.Add(entry);
|
||||
}
|
||||
|
||||
if (entries.Length > 0)
|
||||
{
|
||||
this._lastEntryType = entries[^1].Type;
|
||||
}
|
||||
|
||||
this._appComponent.Props = this._appComponent.Props! with
|
||||
{
|
||||
ScrollItems = new List<object>(this._outputItems),
|
||||
};
|
||||
}
|
||||
|
||||
this._appComponent.Render();
|
||||
}
|
||||
}
|
||||
+2
-4
@@ -7,12 +7,10 @@
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Spectre.Console" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\..\..\..\src\Microsoft.Agents.AI\Microsoft.Agents.AI.csproj" />
|
||||
<ProjectReference Include="..\ConsoleReactiveFramework\ConsoleReactiveFramework.csproj" />
|
||||
<ProjectReference Include="..\ConsoleReactiveComponents\ConsoleReactiveComponents.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
// Copyright (c) Microsoft. All rights reserved.
|
||||
|
||||
namespace Harness.Shared.Console;
|
||||
|
||||
/// <summary>
|
||||
/// Helpers for resolving console colours associated with agent modes.
|
||||
/// </summary>
|
||||
internal static class ModeColors
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets the console color associated with a mode name, using the provided color map.
|
||||
/// Falls back to <see cref="ConsoleColor.Gray"/> when the mode is <see langword="null"/>
|
||||
/// or not present in the map.
|
||||
/// </summary>
|
||||
/// <param name="mode">The mode name, or <see langword="null"/> if no mode is active.</param>
|
||||
/// <param name="modeColors">Optional mapping of mode names to console colors.</param>
|
||||
public static ConsoleColor Get(string? mode, IReadOnlyDictionary<string, ConsoleColor>? modeColors = null)
|
||||
{
|
||||
if (mode is null)
|
||||
{
|
||||
return ConsoleColor.Gray;
|
||||
}
|
||||
|
||||
if (modeColors is not null && modeColors.TryGetValue(mode, out var color))
|
||||
{
|
||||
return color;
|
||||
}
|
||||
|
||||
return ConsoleColor.Gray;
|
||||
}
|
||||
}
|
||||
+6
-6
@@ -25,28 +25,28 @@ public abstract class ConsoleObserver
|
||||
/// <summary>
|
||||
/// Called for each <see cref="AIContent"/> item in the response stream.
|
||||
/// </summary>
|
||||
/// <param name="writer">The console writer for rendering output.</param>
|
||||
/// <param name="ux">The harness UX container, used for rendering output and interacting with the user.</param>
|
||||
/// <param name="content">The content item from the stream.</param>
|
||||
public virtual Task OnContentAsync(ConsoleWriter writer, AIContent content) => Task.CompletedTask;
|
||||
public virtual Task OnContentAsync(HarnessUXContainer ux, AIContent content) => Task.CompletedTask;
|
||||
|
||||
/// <summary>
|
||||
/// Called for each text update in the response stream.
|
||||
/// </summary>
|
||||
/// <param name="writer">The console writer for rendering output.</param>
|
||||
/// <param name="ux">The harness UX container, used for rendering output and interacting with the user.</param>
|
||||
/// <param name="text">The text from the update.</param>
|
||||
public virtual Task OnTextAsync(ConsoleWriter writer, string text) => Task.CompletedTask;
|
||||
public virtual Task OnTextAsync(HarnessUXContainer ux, string text) => Task.CompletedTask;
|
||||
|
||||
/// <summary>
|
||||
/// Called after the response stream completes. Returns messages to include in the
|
||||
/// next agent invocation, or <see langword="null"/> if no re-invocation is needed.
|
||||
/// </summary>
|
||||
/// <param name="writer">The console writer for rendering output.</param>
|
||||
/// <param name="ux">The harness UX container, used for rendering output and interacting with the user.</param>
|
||||
/// <param name="agent">The agent being interacted with.</param>
|
||||
/// <param name="session">The current agent session.</param>
|
||||
/// <param name="options">The console options.</param>
|
||||
/// <returns>Messages to send to the agent, or <see langword="null"/> if no action is needed.</returns>
|
||||
public virtual Task<IList<ChatMessage>?> OnStreamCompleteAsync(
|
||||
ConsoleWriter writer,
|
||||
HarnessUXContainer ux,
|
||||
AIAgent agent,
|
||||
AgentSession session,
|
||||
HarnessConsoleOptions options) => Task.FromResult<IList<ChatMessage>?>(null);
|
||||
|
||||
+2
-2
@@ -10,7 +10,7 @@ namespace Harness.Shared.Console.Observers;
|
||||
internal sealed class ErrorDisplayObserver : ConsoleObserver
|
||||
{
|
||||
/// <inheritdoc/>
|
||||
public override async Task OnContentAsync(ConsoleWriter writer, AIContent content)
|
||||
public override async Task OnContentAsync(HarnessUXContainer ux, AIContent content)
|
||||
{
|
||||
if (content is ErrorContent errorContent)
|
||||
{
|
||||
@@ -25,7 +25,7 @@ internal sealed class ErrorDisplayObserver : ConsoleObserver
|
||||
errorText += $" details: {errorContent.Details}";
|
||||
}
|
||||
|
||||
await writer.WriteInfoLineAsync(errorText, ConsoleColor.Red);
|
||||
await ux.WriteInfoLineAsync(errorText, ConsoleColor.Red);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+17
-38
@@ -33,7 +33,7 @@ internal sealed class PlanningOutputObserver : ConsoleObserver
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
public override Task OnTextAsync(ConsoleWriter writer, string text)
|
||||
public override Task OnTextAsync(HarnessUXContainer ux, string text)
|
||||
{
|
||||
// Collect text silently instead of displaying it.
|
||||
this._textCollector.Append(text);
|
||||
@@ -42,7 +42,7 @@ internal sealed class PlanningOutputObserver : ConsoleObserver
|
||||
|
||||
/// <inheritdoc/>
|
||||
public override async Task<IList<ChatMessage>?> OnStreamCompleteAsync(
|
||||
ConsoleWriter writer,
|
||||
HarnessUXContainer ux,
|
||||
AIAgent agent,
|
||||
AgentSession session,
|
||||
HarnessConsoleOptions options)
|
||||
@@ -64,21 +64,21 @@ internal sealed class PlanningOutputObserver : ConsoleObserver
|
||||
}
|
||||
catch (JsonException ex)
|
||||
{
|
||||
await writer.WriteInfoLineAsync($"❌ Failed to parse planning response: {ex.Message}", ConsoleColor.Red);
|
||||
await writer.WriteInfoLineAsync($"(raw response) {collectedText}", ConsoleColor.DarkYellow);
|
||||
await ux.WriteInfoLineAsync($"❌ Failed to parse planning response: {ex.Message}", ConsoleColor.Red);
|
||||
await ux.WriteInfoLineAsync($"(raw response) {collectedText}", ConsoleColor.DarkYellow);
|
||||
return null;
|
||||
}
|
||||
|
||||
if (planningResponse is null)
|
||||
{
|
||||
await writer.WriteInfoLineAsync("(no structured response from agent)", ConsoleColor.DarkYellow);
|
||||
await ux.WriteInfoLineAsync("(no structured response from agent)", ConsoleColor.DarkYellow);
|
||||
return null;
|
||||
}
|
||||
|
||||
// Render based on response type.
|
||||
if (planningResponse.Type == PlanningResponseType.Clarification)
|
||||
{
|
||||
return AsUserMessages(await this.RenderClarificationsAndCollectResponsesAsync(writer, planningResponse));
|
||||
return AsUserMessages(await this.RenderClarificationsAndCollectResponsesAsync(ux, planningResponse));
|
||||
}
|
||||
|
||||
if (planningResponse.Type == PlanningResponseType.Approval)
|
||||
@@ -86,48 +86,45 @@ internal sealed class PlanningOutputObserver : ConsoleObserver
|
||||
var question = planningResponse.Questions.FirstOrDefault();
|
||||
if (question is null)
|
||||
{
|
||||
await writer.WriteInfoLineAsync("(approval response had no content)", ConsoleColor.DarkYellow);
|
||||
await ux.WriteInfoLineAsync("(approval response had no content)", ConsoleColor.DarkYellow);
|
||||
return null;
|
||||
}
|
||||
|
||||
string response = await this.RenderApprovalAndCollectResponseAsync(writer, question, options);
|
||||
string response = await this.RenderApprovalAndCollectResponseAsync(ux, question, options);
|
||||
if (response == "Approved")
|
||||
{
|
||||
this._modeProvider.SetMode(session, options.ExecutionModeName!);
|
||||
|
||||
await writer.WriteInfoLineAsync($"✅ Switched to {options.ExecutionModeName} mode.",
|
||||
ConsoleWriter.GetModeColor(options.ExecutionModeName, options.ModeColors));
|
||||
await ux.WriteInfoLineAsync($"✅ Switched to {options.ExecutionModeName} mode.",
|
||||
ModeColors.Get(options.ExecutionModeName, options.ModeColors));
|
||||
}
|
||||
|
||||
return AsUserMessages(response);
|
||||
}
|
||||
|
||||
await writer.WriteInfoLineAsync($"(unexpected response type: {planningResponse.Type})", ConsoleColor.DarkYellow);
|
||||
await ux.WriteInfoLineAsync($"(unexpected response type: {planningResponse.Type})", ConsoleColor.DarkYellow);
|
||||
return null;
|
||||
}
|
||||
|
||||
private static IList<ChatMessage>? AsUserMessages(string? text) =>
|
||||
text is not null ? [new ChatMessage(ChatRole.User, text)] : null;
|
||||
|
||||
private async Task<string?> RenderClarificationsAndCollectResponsesAsync(ConsoleWriter writer, PlanningResponse response)
|
||||
private async Task<string?> RenderClarificationsAndCollectResponsesAsync(HarnessUXContainer ux, PlanningResponse response)
|
||||
{
|
||||
var answers = new List<string>();
|
||||
|
||||
foreach (var question in response.Questions)
|
||||
{
|
||||
await writer.WriteInfoLineAsync(string.Empty);
|
||||
await writer.WriteInfoLineAsync(question.Message);
|
||||
|
||||
string? answer;
|
||||
if (question.Choices is { Count: > 0 })
|
||||
{
|
||||
answer = await writer.ReadSelectionAsync(
|
||||
"Choose an option:",
|
||||
answer = await ux.ReadSelectionAsync(
|
||||
question.Message,
|
||||
question.Choices);
|
||||
}
|
||||
else
|
||||
{
|
||||
answer = (await writer.ReadLineAsync("Response: "))?.Trim();
|
||||
answer = (await ux.ReadLineAsync(question.Message))?.Trim();
|
||||
}
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(answer))
|
||||
@@ -139,38 +136,20 @@ internal sealed class PlanningOutputObserver : ConsoleObserver
|
||||
return answers.Count > 0 ? string.Join("\n\n", answers) : null;
|
||||
}
|
||||
|
||||
private async Task<string> RenderApprovalAndCollectResponseAsync(ConsoleWriter writer, PlanningQuestion question, HarnessConsoleOptions options)
|
||||
private async Task<string> RenderApprovalAndCollectResponseAsync(HarnessUXContainer ux, PlanningQuestion question, HarnessConsoleOptions options)
|
||||
{
|
||||
await writer.WriteInfoLineAsync(question.Message);
|
||||
|
||||
var choices = new List<string>
|
||||
{
|
||||
"Approve and switch to execute mode",
|
||||
"Suggest changes",
|
||||
};
|
||||
|
||||
string selection = await writer.ReadSelectionAsync("What would you like to do?", choices);
|
||||
string selection = await ux.ReadSelectionAsync(question.Message, choices);
|
||||
|
||||
if (selection == choices[0])
|
||||
{
|
||||
return "Approved";
|
||||
}
|
||||
|
||||
if (selection == choices[1])
|
||||
{
|
||||
string? feedback = await writer.ReadLineAsync(
|
||||
"Your feedback: ",
|
||||
ConsoleWriter.GetModeColor(options.PlanningModeName, options.ModeColors));
|
||||
|
||||
if (string.IsNullOrWhiteSpace(feedback))
|
||||
{
|
||||
// Treat empty feedback as no changes — re-prompt the agent with the plan.
|
||||
return "No changes suggested. Please re-present the plan for approval.";
|
||||
}
|
||||
|
||||
return feedback;
|
||||
}
|
||||
|
||||
// Custom freeform input — treat as suggested changes.
|
||||
return selection;
|
||||
}
|
||||
|
||||
+2
-2
@@ -10,11 +10,11 @@ namespace Harness.Shared.Console.Observers;
|
||||
internal sealed class ReasoningDisplayObserver : ConsoleObserver
|
||||
{
|
||||
/// <inheritdoc/>
|
||||
public override async Task OnContentAsync(ConsoleWriter writer, AIContent content)
|
||||
public override async Task OnContentAsync(HarnessUXContainer ux, AIContent content)
|
||||
{
|
||||
if (content is TextReasoningContent reasoning && !string.IsNullOrEmpty(reasoning.Text))
|
||||
{
|
||||
await writer.WriteTextAsync(reasoning.Text, ConsoleColor.DarkMagenta);
|
||||
await ux.WriteTextAsync(reasoning.Text, ConsoleColor.DarkMagenta);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+2
-2
@@ -9,8 +9,8 @@ namespace Harness.Shared.Console.Observers;
|
||||
internal sealed class TextOutputObserver : ConsoleObserver
|
||||
{
|
||||
/// <inheritdoc/>
|
||||
public override async Task OnTextAsync(ConsoleWriter writer, string text)
|
||||
public override async Task OnTextAsync(HarnessUXContainer ux, string text)
|
||||
{
|
||||
await writer.WriteTextAsync(text);
|
||||
await ux.WriteTextAsync(text);
|
||||
}
|
||||
}
|
||||
|
||||
+7
-7
@@ -15,7 +15,7 @@ internal sealed class ToolApprovalObserver : ConsoleObserver
|
||||
private readonly List<ToolApprovalRequestContent> _approvalRequests = [];
|
||||
|
||||
/// <inheritdoc/>
|
||||
public override async Task OnContentAsync(ConsoleWriter writer, AIContent content)
|
||||
public override async Task OnContentAsync(HarnessUXContainer ux, AIContent content)
|
||||
{
|
||||
if (content is ToolApprovalRequestContent approvalRequest)
|
||||
{
|
||||
@@ -23,13 +23,13 @@ internal sealed class ToolApprovalObserver : ConsoleObserver
|
||||
string toolName = approvalRequest.ToolCall is FunctionCallContent fc
|
||||
? ToolCallFormatter.Format(fc)
|
||||
: approvalRequest.ToolCall?.ToString() ?? "unknown";
|
||||
await writer.WriteInfoLineAsync($"⚠️ Approval needed: {toolName}", ConsoleColor.Yellow);
|
||||
await ux.WriteInfoLineAsync($"⚠️ Approval needed: {toolName}", ConsoleColor.Yellow);
|
||||
}
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
public override async Task<IList<ChatMessage>?> OnStreamCompleteAsync(
|
||||
ConsoleWriter writer,
|
||||
HarnessUXContainer ux,
|
||||
AIAgent agent,
|
||||
AgentSession session,
|
||||
HarnessConsoleOptions options)
|
||||
@@ -39,12 +39,12 @@ internal sealed class ToolApprovalObserver : ConsoleObserver
|
||||
return null;
|
||||
}
|
||||
|
||||
var messages = await PromptForApprovalsAsync(writer, this._approvalRequests);
|
||||
var messages = await PromptForApprovalsAsync(ux, this._approvalRequests);
|
||||
this._approvalRequests.Clear();
|
||||
return messages;
|
||||
}
|
||||
|
||||
private static async Task<List<ChatMessage>?> PromptForApprovalsAsync(ConsoleWriter writer, List<ToolApprovalRequestContent> approvalRequests)
|
||||
private static async Task<List<ChatMessage>?> PromptForApprovalsAsync(HarnessUXContainer ux, List<ToolApprovalRequestContent> approvalRequests)
|
||||
{
|
||||
if (approvalRequests.Count == 0)
|
||||
{
|
||||
@@ -66,7 +66,7 @@ internal sealed class ToolApprovalObserver : ConsoleObserver
|
||||
"Deny",
|
||||
};
|
||||
|
||||
string selection = await writer.ReadSelectionAsync($"🔐 Tool approval: {toolName}", choices);
|
||||
string selection = await ux.ReadSelectionAsync($"🔐 Tool approval: {toolName}", choices);
|
||||
AIContent response = selection switch
|
||||
{
|
||||
"Always approve this tool (any arguments)" => request.CreateAlwaysApproveToolResponse("User chose to always approve this tool"),
|
||||
@@ -82,7 +82,7 @@ internal sealed class ToolApprovalObserver : ConsoleObserver
|
||||
"Deny" => "❌ Denied",
|
||||
_ => "✅ Approved",
|
||||
};
|
||||
await writer.WriteInfoLineAsync($" {action}", ConsoleColor.DarkGray);
|
||||
await ux.WriteInfoLineAsync($" {action}", ConsoleColor.DarkGray);
|
||||
|
||||
responses.Add(response);
|
||||
}
|
||||
|
||||
+3
-3
@@ -11,15 +11,15 @@ namespace Harness.Shared.Console.Observers;
|
||||
internal sealed class ToolCallDisplayObserver : ConsoleObserver
|
||||
{
|
||||
/// <inheritdoc/>
|
||||
public override async Task OnContentAsync(ConsoleWriter writer, AIContent content)
|
||||
public override async Task OnContentAsync(HarnessUXContainer ux, AIContent content)
|
||||
{
|
||||
if (content is FunctionCallContent functionCall)
|
||||
{
|
||||
await writer.WriteInfoLineAsync($"🔧 Calling tool: {ToolCallFormatter.Format(functionCall)}...", ConsoleColor.DarkYellow);
|
||||
await ux.WriteInfoLineAsync($"🔧 Calling tool: {ToolCallFormatter.Format(functionCall)}...", ConsoleColor.DarkYellow);
|
||||
}
|
||||
else if (content is ToolCallContent toolCall)
|
||||
{
|
||||
await writer.WriteInfoLineAsync($"🔧 Calling tool: {toolCall}...", ConsoleColor.DarkYellow);
|
||||
await ux.WriteInfoLineAsync($"🔧 Calling tool: {toolCall}...", ConsoleColor.DarkYellow);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+5
-3
@@ -24,19 +24,21 @@ internal sealed class UsageDisplayObserver : ConsoleObserver
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
public override async Task OnContentAsync(ConsoleWriter writer, AIContent content)
|
||||
public override Task OnContentAsync(HarnessUXContainer ux, AIContent content)
|
||||
{
|
||||
if (content is UsageContent usage)
|
||||
{
|
||||
if (usage.Details is not null)
|
||||
{
|
||||
await writer.WriteInfoLineAsync(this.FormatUsageBreakdown(usage.Details), ConsoleColor.DarkGray);
|
||||
ux.SetUsageText(this.FormatUsageBreakdown(usage.Details));
|
||||
}
|
||||
else
|
||||
{
|
||||
await writer.WriteInfoLineAsync("📊 Tokens —", ConsoleColor.DarkGray);
|
||||
ux.SetUsageText("📊 Tokens —");
|
||||
}
|
||||
}
|
||||
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
private string FormatUsageBreakdown(UsageDetails details)
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
// Copyright (c) Microsoft. All rights reserved.
|
||||
|
||||
namespace Harness.Shared.Console;
|
||||
|
||||
/// <summary>
|
||||
/// Represents the type of an output entry in the console conversation.
|
||||
/// </summary>
|
||||
public enum OutputEntryType
|
||||
{
|
||||
/// <summary>User input echo (e.g. "You: hello").</summary>
|
||||
UserInput,
|
||||
|
||||
/// <summary>In-progress streaming text from the agent (accumulated chunk by chunk).</summary>
|
||||
StreamingText,
|
||||
|
||||
/// <summary>Informational line (tool calls, errors, usage, approval requests, etc.).</summary>
|
||||
InfoLine,
|
||||
|
||||
/// <summary>Stream footer (e.g. "(no text response from agent)").</summary>
|
||||
StreamFooter,
|
||||
|
||||
/// <summary>Pending injected message notification.</summary>
|
||||
PendingMessage,
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Represents a single output entry in the console conversation history.
|
||||
/// These entries are rendered by the <see cref="HarnessAppComponent"/> via its render delegate.
|
||||
/// </summary>
|
||||
/// <param name="Type">The type of output entry.</param>
|
||||
/// <param name="Text">The text content of the entry.</param>
|
||||
/// <param name="Color">Optional foreground color for rendering.</param>
|
||||
public record OutputEntry(OutputEntryType Type, string Text, ConsoleColor? Color = null);
|
||||
@@ -1,77 +0,0 @@
|
||||
// Copyright (c) Microsoft. All rights reserved.
|
||||
|
||||
namespace Harness.Shared.Console;
|
||||
|
||||
/// <summary>
|
||||
/// A restartable spinner that can be started and stopped multiple times.
|
||||
/// </summary>
|
||||
internal sealed class Spinner : IDisposable
|
||||
{
|
||||
private static readonly string[] s_frames = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"];
|
||||
|
||||
private CancellationTokenSource? _cts;
|
||||
private Task? _task;
|
||||
|
||||
public void Start()
|
||||
{
|
||||
if (this._task is not null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
this._cts = new CancellationTokenSource();
|
||||
this._task = RunAsync(this._cts.Token);
|
||||
}
|
||||
|
||||
public async Task StopAsync()
|
||||
{
|
||||
if (this._cts is null || this._task is null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
this._cts.Cancel();
|
||||
await this._task;
|
||||
this._cts.Dispose();
|
||||
this._cts = null;
|
||||
this._task = null;
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
if (this._cts is not null && this._task is not null)
|
||||
{
|
||||
this._cts.Cancel();
|
||||
|
||||
// Block briefly to let the spinner task clean up.
|
||||
// This prevents the background task from writing to the console after disposal.
|
||||
#pragma warning disable VSTHRD002 // Synchronous wait in Dispose is acceptable here — the spinner task completes quickly on cancellation.
|
||||
this._task.Wait();
|
||||
#pragma warning restore VSTHRD002
|
||||
}
|
||||
|
||||
this._cts?.Dispose();
|
||||
this._cts = null;
|
||||
this._task = null;
|
||||
}
|
||||
|
||||
private static async Task RunAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
int i = 0;
|
||||
try
|
||||
{
|
||||
while (!cancellationToken.IsCancellationRequested)
|
||||
{
|
||||
System.Console.Write(s_frames[i % s_frames.Length]);
|
||||
await Task.Delay(80, cancellationToken);
|
||||
System.Console.Write("\b \b");
|
||||
i++;
|
||||
}
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
// Clear the last spinner frame left on screen.
|
||||
System.Console.Write("\b \b");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -135,6 +135,7 @@ AIAgent agent =
|
||||
// Build a ChatClient Pipeline
|
||||
.AsBuilder()
|
||||
.UseFunctionInvocation() // We are building our own stack from scratch so we need to include Function Invocation ourselves.
|
||||
.UseMessageInjection() // Allow message injection during the function call loop.
|
||||
.UsePerServiceCallChatHistoryPersistence() // Save chat history updates to the session after each service call, rather than only at the end of the run.
|
||||
.UseAIContextProviders(new CompactionProvider(compactionStrategy)) // Add Compaction before each service call to responses so that long function invocation loops don't overflow the context.
|
||||
|
||||
|
||||
+8
@@ -0,0 +1,8 @@
|
||||
AZURE_AI_PROJECT_ENDPOINT=<your-azure-ai-project-endpoint>
|
||||
AZURE_AI_MODEL_DEPLOYMENT_NAME=gpt-4o
|
||||
AZURE_SEARCH_ENDPOINT=<your-azure-search-endpoint>
|
||||
AZURE_SEARCH_INDEX_NAME=contoso-outdoors
|
||||
AZURE_BEARER_TOKEN_FOUNDRY=DefaultAzureCredential
|
||||
AZURE_BEARER_TOKEN_SEARCH=DefaultAzureCredential
|
||||
ASPNETCORE_URLS=http://+:8088
|
||||
ASPNETCORE_ENVIRONMENT=Development
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
# Use the official .NET 10.0 ASP.NET runtime as a parent image
|
||||
FROM mcr.microsoft.com/dotnet/aspnet:10.0 AS base
|
||||
WORKDIR /app
|
||||
|
||||
FROM mcr.microsoft.com/dotnet/sdk:10.0 AS build
|
||||
WORKDIR /src
|
||||
COPY . .
|
||||
RUN dotnet restore
|
||||
RUN dotnet publish -c Release -o /app/publish
|
||||
|
||||
# Final stage
|
||||
FROM base AS final
|
||||
WORKDIR /app
|
||||
COPY --from=build /app/publish .
|
||||
EXPOSE 8088
|
||||
ENV ASPNETCORE_URLS=http://+:8088
|
||||
ENTRYPOINT ["dotnet", "HostedAzureSearchRag.dll"]
|
||||
+23
@@ -0,0 +1,23 @@
|
||||
# Dockerfile for contributors building from the agent-framework repository source.
|
||||
#
|
||||
# This project uses ProjectReference to the local Microsoft.Agents.AI.Foundry source,
|
||||
# which means a standard multi-stage Docker build cannot resolve dependencies outside
|
||||
# this folder. Instead, pre-publish the app targeting the container runtime and copy
|
||||
# the output into the container:
|
||||
#
|
||||
# dotnet publish -c Debug -f net10.0 -r linux-musl-x64 --self-contained false -o out
|
||||
# docker build -f Dockerfile.contributor -t hosted-azure-search-rag .
|
||||
# docker run --rm -p 8088:8088 \
|
||||
# -e AGENT_NAME=hosted-azure-search-rag \
|
||||
# -e AZURE_BEARER_TOKEN_FOUNDRY=$AZURE_BEARER_TOKEN_FOUNDRY \
|
||||
# -e AZURE_BEARER_TOKEN_SEARCH=$AZURE_BEARER_TOKEN_SEARCH \
|
||||
# --env-file .env hosted-azure-search-rag
|
||||
#
|
||||
# For end-users consuming the NuGet package (not ProjectReference), use the standard
|
||||
# Dockerfile which performs a full dotnet restore + publish inside the container.
|
||||
FROM mcr.microsoft.com/dotnet/aspnet:10.0-alpine AS final
|
||||
WORKDIR /app
|
||||
COPY out/ .
|
||||
EXPOSE 8088
|
||||
ENV ASPNETCORE_URLS=http://+:8088
|
||||
ENTRYPOINT ["dotnet", "HostedAzureSearchRag.dll"]
|
||||
+35
@@ -0,0 +1,35 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk.Web">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFrameworks>net10.0</TargetFrameworks>
|
||||
<Nullable>enable</Nullable>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<CentralPackageTransitivePinningEnabled>false</CentralPackageTransitivePinningEnabled>
|
||||
<RootNamespace>HostedAzureSearchRag</RootNamespace>
|
||||
<AssemblyName>HostedAzureSearchRag</AssemblyName>
|
||||
<NoWarn>$(NoWarn);</NoWarn>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Azure.AI.Projects" VersionOverride="2.1.0-beta.1" />
|
||||
<PackageReference Include="Azure.Identity" />
|
||||
<PackageReference Include="Azure.Search.Documents" />
|
||||
<PackageReference Include="DotNetEnv" />
|
||||
</ItemGroup>
|
||||
|
||||
<!-- For contributors: uses ProjectReference to build against local source -->
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\..\..\..\..\src\Microsoft.Agents.AI.Foundry\Microsoft.Agents.AI.Foundry.csproj" />
|
||||
<ProjectReference Include="..\..\..\..\..\src\Microsoft.Agents.AI.Foundry.Hosting\Microsoft.Agents.AI.Foundry.Hosting.csproj" />
|
||||
<ProjectReference Include="..\..\..\..\..\src\Microsoft.Agents.AI.OpenAI\Microsoft.Agents.AI.OpenAI.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
<!-- For end-users: uncomment the PackageReference below and remove the ProjectReferences above
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.Agents.AI.Foundry" Version="1.0.0" />
|
||||
<PackageReference Include="Microsoft.Agents.AI.Foundry.Hosting" Version="1.0.0" />
|
||||
<PackageReference Include="Microsoft.Agents.AI.OpenAI" Version="1.0.0" />
|
||||
</ItemGroup>
|
||||
-->
|
||||
|
||||
</Project>
|
||||
+171
@@ -0,0 +1,171 @@
|
||||
// Copyright (c) Microsoft. All rights reserved.
|
||||
|
||||
// This sample shows how to add Retrieval Augmented Generation (RAG) capabilities to a hosted
|
||||
// agent using Azure AI Search. The sample assumes the search index has already been provisioned
|
||||
// and populated out of band (see README.md for the required schema and example seed content).
|
||||
// A SearchClient-backed adapter is plugged into TextSearchProvider, which runs a keyword search
|
||||
// against the index before each model invocation and injects the matching documents into the
|
||||
// model context.
|
||||
|
||||
using Azure;
|
||||
using Azure.AI.Projects;
|
||||
using Azure.Core;
|
||||
using Azure.Identity;
|
||||
using Azure.Search.Documents;
|
||||
using Azure.Search.Documents.Models;
|
||||
using DotNetEnv;
|
||||
using Microsoft.Agents.AI;
|
||||
using Microsoft.Agents.AI.Foundry.Hosting;
|
||||
using Microsoft.Extensions.AI;
|
||||
using OpenAI.Chat;
|
||||
|
||||
// Load .env file if present (for local development)
|
||||
Env.TraversePath().Load();
|
||||
|
||||
string projectEndpoint = Environment.GetEnvironmentVariable("AZURE_AI_PROJECT_ENDPOINT")
|
||||
?? throw new InvalidOperationException("AZURE_AI_PROJECT_ENDPOINT is not set.");
|
||||
string deploymentName = Environment.GetEnvironmentVariable("AZURE_AI_MODEL_DEPLOYMENT_NAME") ?? "gpt-4o";
|
||||
|
||||
string searchEndpoint = Environment.GetEnvironmentVariable("AZURE_SEARCH_ENDPOINT")
|
||||
?? throw new InvalidOperationException("AZURE_SEARCH_ENDPOINT is not set.");
|
||||
string searchIndexName = Environment.GetEnvironmentVariable("AZURE_SEARCH_INDEX_NAME")
|
||||
?? throw new InvalidOperationException("AZURE_SEARCH_INDEX_NAME is not set.");
|
||||
|
||||
// Use a chained credential. Try a temporary dev token first (for local Docker debugging),
|
||||
// then fall back to DefaultAzureCredential (for local dev via dotnet run / managed identity in
|
||||
// production). The dev credential is scope aware so a single instance serves both Foundry and
|
||||
// Azure AI Search clients (each Azure SDK client requests a token for its own audience).
|
||||
TokenCredential credential = new ChainedTokenCredential(
|
||||
new DevTemporaryTokenCredential(),
|
||||
new DefaultAzureCredential());
|
||||
|
||||
// Connect to the pre-provisioned search index. The caller is expected to have created the
|
||||
// index and populated it with documents matching the schema (id / content / sourceName /
|
||||
// sourceLink) before running this sample. See README.md for an example provisioning script.
|
||||
var searchClient = new SearchClient(new Uri(searchEndpoint), searchIndexName, credential);
|
||||
|
||||
TextSearchProviderOptions textSearchOptions = new()
|
||||
{
|
||||
SearchTime = TextSearchProviderOptions.TextSearchBehavior.BeforeAIInvoke,
|
||||
RecentMessageMemoryLimit = 6,
|
||||
};
|
||||
|
||||
AIAgent agent = new AIProjectClient(new Uri(projectEndpoint), credential)
|
||||
.AsAIAgent(new ChatClientAgentOptions
|
||||
{
|
||||
Name = Environment.GetEnvironmentVariable("AGENT_NAME") ?? "hosted-azure-search-rag",
|
||||
ChatOptions = new ChatOptions
|
||||
{
|
||||
ModelId = deploymentName,
|
||||
Instructions = "You are a helpful support specialist for Contoso Outdoors. " +
|
||||
"Answer questions using the provided context and cite the source document when available.",
|
||||
},
|
||||
AIContextProviders = [new TextSearchProvider(CreateSearchAdapter(searchClient), textSearchOptions)]
|
||||
});
|
||||
|
||||
// Host the agent as a Foundry Hosted Agent using the Responses API.
|
||||
var builder = WebApplication.CreateBuilder(args);
|
||||
builder.Services.AddFoundryResponses(agent);
|
||||
|
||||
var app = builder.Build();
|
||||
app.MapFoundryResponses();
|
||||
|
||||
if (app.Environment.IsDevelopment())
|
||||
{
|
||||
app.MapFoundryResponses("openai/v1");
|
||||
}
|
||||
|
||||
app.Run();
|
||||
|
||||
// ── Search adapter ───────────────────────────────────────────────────────────
|
||||
// Wraps a SearchClient as the delegate TextSearchProvider expects. Keyword/full-text only;
|
||||
// no embeddings. Returns the top results and projects them into TextSearchResult entries
|
||||
// the provider will inject into the model context.
|
||||
|
||||
static Func<string, CancellationToken, Task<IEnumerable<TextSearchProvider.TextSearchResult>>>
|
||||
CreateSearchAdapter(SearchClient client, int top = 3) =>
|
||||
async (query, cancellationToken) =>
|
||||
{
|
||||
var options = new SearchOptions { Size = top };
|
||||
Response<SearchResults<SearchDocument>> response =
|
||||
await client.SearchAsync<SearchDocument>(query, options, cancellationToken).ConfigureAwait(false);
|
||||
|
||||
var results = new List<TextSearchProvider.TextSearchResult>();
|
||||
await foreach (SearchResult<SearchDocument> hit in response.Value.GetResultsAsync().WithCancellation(cancellationToken).ConfigureAwait(false))
|
||||
{
|
||||
results.Add(new TextSearchProvider.TextSearchResult
|
||||
{
|
||||
SourceName = hit.Document.TryGetValue("sourceName", out var name) ? name?.ToString() ?? string.Empty : string.Empty,
|
||||
SourceLink = hit.Document.TryGetValue("sourceLink", out var link) ? link?.ToString() ?? string.Empty : string.Empty,
|
||||
Text = hit.Document.TryGetValue("content", out var content) ? content?.ToString() ?? string.Empty : string.Empty,
|
||||
RawRepresentation = hit
|
||||
});
|
||||
}
|
||||
|
||||
return results;
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// A scope aware <see cref="TokenCredential"/> for local Docker debugging only.
|
||||
/// Reads pre-fetched bearer tokens from environment variables, dispensing the right token
|
||||
/// based on the requested scope:
|
||||
/// <list type="bullet">
|
||||
/// <item><description><c>ai.azure.com</c> scopes -> <c>AZURE_BEARER_TOKEN_FOUNDRY</c></description></item>
|
||||
/// <item><description><c>search.azure.com</c> scopes -> <c>AZURE_BEARER_TOKEN_SEARCH</c></description></item>
|
||||
/// </list>
|
||||
/// For any other scope, throws <see cref="CredentialUnavailableException"/> so a chained
|
||||
/// credential will fall through. This should NOT be used in production: tokens expire (~1 hour)
|
||||
/// and cannot be refreshed.
|
||||
///
|
||||
/// Generate the tokens on your host and pass them to the container:
|
||||
/// <code>
|
||||
/// export AZURE_BEARER_TOKEN_FOUNDRY=$(az account get-access-token --resource https://ai.azure.com --query accessToken -o tsv)
|
||||
/// export AZURE_BEARER_TOKEN_SEARCH=$(az account get-access-token --resource https://search.azure.com --query accessToken -o tsv)
|
||||
/// docker run -e AZURE_BEARER_TOKEN_FOUNDRY -e AZURE_BEARER_TOKEN_SEARCH ...
|
||||
/// </code>
|
||||
/// </summary>
|
||||
internal sealed class DevTemporaryTokenCredential : TokenCredential
|
||||
{
|
||||
private const string FoundryEnvironmentVariable = "AZURE_BEARER_TOKEN_FOUNDRY";
|
||||
private const string SearchEnvironmentVariable = "AZURE_BEARER_TOKEN_SEARCH";
|
||||
|
||||
public override AccessToken GetToken(TokenRequestContext requestContext, CancellationToken cancellationToken)
|
||||
=> Resolve(requestContext.Scopes);
|
||||
|
||||
public override ValueTask<AccessToken> GetTokenAsync(TokenRequestContext requestContext, CancellationToken cancellationToken)
|
||||
=> new(Resolve(requestContext.Scopes));
|
||||
|
||||
private static AccessToken Resolve(IReadOnlyList<string> scopes)
|
||||
{
|
||||
string? envVar = null;
|
||||
foreach (var scope in scopes)
|
||||
{
|
||||
if (scope.Contains("search.azure.com", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
envVar = SearchEnvironmentVariable;
|
||||
break;
|
||||
}
|
||||
|
||||
if (scope.Contains("ai.azure.com", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
envVar = FoundryEnvironmentVariable;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (envVar is null)
|
||||
{
|
||||
throw new CredentialUnavailableException(
|
||||
$"DevTemporaryTokenCredential cannot serve scopes [{string.Join(", ", scopes)}]; falling through.");
|
||||
}
|
||||
|
||||
var token = Environment.GetEnvironmentVariable(envVar);
|
||||
if (string.IsNullOrEmpty(token) || string.Equals(token, "DefaultAzureCredential", StringComparison.Ordinal))
|
||||
{
|
||||
throw new CredentialUnavailableException(
|
||||
$"{envVar} environment variable is not set; falling through to next credential.");
|
||||
}
|
||||
|
||||
return new AccessToken(token, DateTimeOffset.UtcNow.AddHours(1));
|
||||
}
|
||||
}
|
||||
+179
@@ -0,0 +1,179 @@
|
||||
# Hosted-AzureSearchRag
|
||||
|
||||
A hosted agent with **Retrieval Augmented Generation (RAG)** capabilities backed by **Azure AI Search**. The agent grounds its answers in product documentation by running a keyword search against an Azure AI Search index before each model invocation, then citing the source in its response.
|
||||
|
||||
This sample is the Azure AI Search counterpart to `Hosted-TextRag`. Where `Hosted-TextRag` uses a mock in-process search function, this sample talks to a real Azure AI Search index that is provisioned out of band (see "Provisioning the search index" below).
|
||||
|
||||
## Prerequisites
|
||||
|
||||
- [.NET 10 SDK](https://dotnet.microsoft.com/download/dotnet/10.0)
|
||||
- An Azure AI Foundry project with a deployed model (e.g., `gpt-4o`)
|
||||
- An Azure AI Search service ([create one](https://learn.microsoft.com/azure/search/search-create-service-portal))
|
||||
- **A pre-provisioned search index** with the schema and content described in the next section
|
||||
- Azure CLI logged in (`az login`)
|
||||
|
||||
### Required RBAC
|
||||
|
||||
Your identity (or the Managed Identity running the container in production) needs:
|
||||
|
||||
- **Azure AI User** on the Foundry project scope
|
||||
- **Search Index Data Reader** on the Azure AI Search service (the sample only reads from the index)
|
||||
|
||||
## Provisioning the search index (one time)
|
||||
|
||||
The sample assumes the search index already exists and contains documents the agent can retrieve from. Provision it once via the Azure Portal, the [REST API](https://learn.microsoft.com/azure/search/search-how-to-create-search-index), or the snippet below.
|
||||
|
||||
### Index schema
|
||||
|
||||
| Field | Type | Attributes |
|
||||
|---|---|---|
|
||||
| `id` | `Edm.String` | key, filterable |
|
||||
| `content` | `Edm.String` | searchable (full-text) |
|
||||
| `sourceName` | `Edm.String` | retrievable, filterable |
|
||||
| `sourceLink` | `Edm.String` | retrievable |
|
||||
|
||||
### Example: provision and seed via Azure CLI + REST
|
||||
|
||||
```bash
|
||||
SEARCH_ENDPOINT="https://<your-search>.search.windows.net"
|
||||
INDEX_NAME="contoso-outdoors"
|
||||
TOKEN=$(az account get-access-token --resource https://search.azure.com --query accessToken -o tsv)
|
||||
|
||||
# 1. Create the index.
|
||||
curl -X PUT "$SEARCH_ENDPOINT/indexes/$INDEX_NAME?api-version=2024-07-01" \
|
||||
-H "Authorization: Bearer $TOKEN" -H "Content-Type: application/json" \
|
||||
-d '{
|
||||
"name": "contoso-outdoors",
|
||||
"fields": [
|
||||
{ "name": "id", "type": "Edm.String", "key": true, "filterable": true, "searchable": false, "retrievable": true },
|
||||
{ "name": "content", "type": "Edm.String", "key": false, "filterable": false, "searchable": true, "retrievable": true, "analyzer": "standard.lucene" },
|
||||
{ "name": "sourceName", "type": "Edm.String", "key": false, "filterable": true, "searchable": false, "retrievable": true },
|
||||
{ "name": "sourceLink", "type": "Edm.String", "key": false, "filterable": false, "searchable": false, "retrievable": true }
|
||||
]
|
||||
}'
|
||||
|
||||
# 2. Upload three Contoso Outdoors documents matching the queries below.
|
||||
curl -X POST "$SEARCH_ENDPOINT/indexes/$INDEX_NAME/docs/index?api-version=2024-07-01" \
|
||||
-H "Authorization: Bearer $TOKEN" -H "Content-Type: application/json" \
|
||||
-d '{
|
||||
"value": [
|
||||
{ "@search.action": "mergeOrUpload", "id": "return-policy", "sourceName": "Contoso Outdoors Return Policy", "sourceLink": "https://contoso.com/policies/returns", "content": "Customers may return any item within 30 days of delivery. Items should be unused and include original packaging. Refunds are issued to the original payment method within 5 business days of inspection. As a thank you, every accepted return ships back with a complimentary Contoso TrailRunner sticker pack, item code TR-CANARY-7821." },
|
||||
{ "@search.action": "mergeOrUpload", "id": "shipping-guide", "sourceName": "Contoso Outdoors Shipping Guide", "sourceLink": "https://contoso.com/help/shipping", "content": "Standard shipping is free on orders over $50 and typically arrives in 3-5 business days within the continental United States. Expedited options are available at checkout. Use promo code SHIP-CANARY-4493 at checkout for a one-time free overnight upgrade on your first order." },
|
||||
{ "@search.action": "mergeOrUpload", "id": "tent-care", "sourceName": "TrailRunner Tent Care Instructions", "sourceLink": "https://contoso.com/manuals/trailrunner-tent", "content": "Clean the tent fabric with lukewarm water and a non-detergent soap. Allow it to air dry completely before storage and avoid prolonged UV exposure to extend the lifespan of the waterproof coating. Replacement waterproofing kits are stocked under SKU TENT-CANARY-9067." }
|
||||
]
|
||||
}'
|
||||
```
|
||||
|
||||
You can also point the sample at any existing index that exposes the four fields above; the sample reads `content`, `sourceName`, and `sourceLink` as projected by the search results.
|
||||
|
||||
## Configuration
|
||||
|
||||
Copy the template and fill in your endpoints:
|
||||
|
||||
```bash
|
||||
cp .env.example .env
|
||||
```
|
||||
|
||||
Edit `.env`:
|
||||
|
||||
```env
|
||||
AZURE_AI_PROJECT_ENDPOINT=https://<your-account>.services.ai.azure.com/api/projects/<your-project>
|
||||
AZURE_AI_MODEL_DEPLOYMENT_NAME=gpt-4o
|
||||
AZURE_SEARCH_ENDPOINT=https://<your-search>.search.windows.net
|
||||
AZURE_SEARCH_INDEX_NAME=contoso-outdoors
|
||||
AZURE_BEARER_TOKEN_FOUNDRY=DefaultAzureCredential
|
||||
AZURE_BEARER_TOKEN_SEARCH=DefaultAzureCredential
|
||||
ASPNETCORE_URLS=http://+:8088
|
||||
ASPNETCORE_ENVIRONMENT=Development
|
||||
```
|
||||
|
||||
> **Note:** `.env` is gitignored. The `.env.example` template is checked in as a reference.
|
||||
|
||||
## Running directly (contributors)
|
||||
|
||||
This project uses `ProjectReference` to build against the local Agent Framework source.
|
||||
|
||||
```bash
|
||||
cd dotnet/samples/04-hosting/FoundryHostedAgents/responses/Hosted-AzureSearchRag
|
||||
AGENT_NAME=hosted-azure-search-rag dotnet run
|
||||
```
|
||||
|
||||
The agent will start on `http://localhost:8088`. The sample assumes the search index has already been provisioned and seeded (see "Provisioning the search index" above).
|
||||
|
||||
### Test it
|
||||
|
||||
Using the Azure Developer CLI:
|
||||
|
||||
```bash
|
||||
azd ai agent invoke --local "What is your return policy?"
|
||||
azd ai agent invoke --local "How long does shipping take?"
|
||||
azd ai agent invoke --local "How do I clean my tent?"
|
||||
```
|
||||
|
||||
Or with curl:
|
||||
|
||||
```bash
|
||||
curl -X POST http://localhost:8088/responses \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{"input": "What is your return policy?", "model": "hosted-azure-search-rag"}'
|
||||
```
|
||||
|
||||
## Running with Docker
|
||||
|
||||
Since this project uses `ProjectReference`, use `Dockerfile.contributor` which takes a pre-published output.
|
||||
|
||||
### 1. Publish for the container runtime (Linux Alpine)
|
||||
|
||||
```bash
|
||||
dotnet publish -c Debug -f net10.0 -r linux-musl-x64 --self-contained false -o out
|
||||
```
|
||||
|
||||
### 2. Build the Docker image
|
||||
|
||||
```bash
|
||||
docker build -f Dockerfile.contributor -t hosted-azure-search-rag .
|
||||
```
|
||||
|
||||
### 3. Run the container
|
||||
|
||||
Generate two bearer tokens on your host (one per audience) and pass them to the container. A single Azure AD token has only one `aud` claim, so Foundry and Azure AI Search require separate tokens.
|
||||
|
||||
```bash
|
||||
# Generate tokens (each expires in ~1 hour)
|
||||
export AZURE_BEARER_TOKEN_FOUNDRY=$(az account get-access-token --resource https://ai.azure.com --query accessToken -o tsv)
|
||||
export AZURE_BEARER_TOKEN_SEARCH=$(az account get-access-token --resource https://search.azure.com --query accessToken -o tsv)
|
||||
|
||||
# Run with both tokens
|
||||
docker run --rm -p 8088:8088 \
|
||||
-e AGENT_NAME=hosted-azure-search-rag \
|
||||
-e AZURE_BEARER_TOKEN_FOUNDRY=$AZURE_BEARER_TOKEN_FOUNDRY \
|
||||
-e AZURE_BEARER_TOKEN_SEARCH=$AZURE_BEARER_TOKEN_SEARCH \
|
||||
--env-file .env \
|
||||
hosted-azure-search-rag
|
||||
```
|
||||
|
||||
### 4. Test it
|
||||
|
||||
Using the Azure Developer CLI:
|
||||
|
||||
```bash
|
||||
azd ai agent invoke --local "What is your return policy?"
|
||||
```
|
||||
|
||||
## How RAG works in this sample
|
||||
|
||||
The `TextSearchProvider` runs a keyword search against the configured Azure AI Search index **before each model invocation**. When the index is seeded with the three Contoso Outdoors documents from the provisioning section above:
|
||||
|
||||
| User query mentions | Search result injected |
|
||||
|---|---|
|
||||
| "return", "refund" | Contoso Outdoors Return Policy (canary token: `TR-CANARY-7821`) |
|
||||
| "shipping", "promo" | Contoso Outdoors Shipping Guide (canary token: `SHIP-CANARY-4493`) |
|
||||
| "tent", "fabric" | TrailRunner Tent Care Instructions (canary token: `TENT-CANARY-9067`) |
|
||||
|
||||
The model receives the top three search results as additional context and cites the source in its response. Each seeded document includes a unique `*-CANARY-*` token that does not exist in any model training data, so the integration tests can prove an answer was grounded in retrieved content (not fabricated from training) by asking for the canary and asserting it appears in the response.
|
||||
|
||||
Replace the seed documents (or point the sample at an existing index with your own content) to ground the agent in your own knowledge base.
|
||||
|
||||
## NuGet package users
|
||||
|
||||
If you are consuming the Agent Framework as a NuGet package (not building from source), use the standard `Dockerfile` instead of `Dockerfile.contributor`. See the commented section in `HostedAzureSearchRag.csproj` for the `PackageReference` alternative.
|
||||
+31
@@ -0,0 +1,31 @@
|
||||
# yaml-language-server: $schema=https://raw.githubusercontent.com/microsoft/AgentSchema/refs/heads/main/schemas/v1.0/AgentManifest.yaml
|
||||
name: hosted-azure-search-rag
|
||||
displayName: "Hosted Azure AI Search RAG Agent"
|
||||
|
||||
description: >
|
||||
A support specialist agent for Contoso Outdoors with RAG capabilities backed by
|
||||
Azure AI Search. Uses TextSearchProvider with a SearchClient adapter to ground
|
||||
answers in product documentation indexed in Azure AI Search before each model
|
||||
invocation.
|
||||
|
||||
metadata:
|
||||
tags:
|
||||
- AI Agent Hosting
|
||||
- Azure AI AgentServer
|
||||
- Responses Protocol
|
||||
- RAG
|
||||
- Azure AI Search
|
||||
- Agent Framework
|
||||
|
||||
template:
|
||||
name: hosted-azure-search-rag
|
||||
kind: hosted
|
||||
protocols:
|
||||
- protocol: responses
|
||||
version: 1.0.0
|
||||
resources:
|
||||
cpu: "0.25"
|
||||
memory: 0.5Gi
|
||||
parameters:
|
||||
properties: []
|
||||
resources: []
|
||||
+9
@@ -0,0 +1,9 @@
|
||||
# yaml-language-server: $schema=https://raw.githubusercontent.com/microsoft/AgentSchema/refs/heads/main/schemas/v1.0/ContainerAgent.yaml
|
||||
kind: hosted
|
||||
name: hosted-azure-search-rag
|
||||
protocols:
|
||||
- protocol: responses
|
||||
version: 1.0.0
|
||||
resources:
|
||||
cpu: "0.25"
|
||||
memory: 0.5Gi
|
||||
@@ -0,0 +1,6 @@
|
||||
**/bin
|
||||
**/obj
|
||||
**/.vs
|
||||
**/.vscode
|
||||
.env
|
||||
*.user
|
||||
@@ -0,0 +1,5 @@
|
||||
AZURE_AI_PROJECT_ENDPOINT=<your-azure-ai-project-endpoint>
|
||||
ASPNETCORE_URLS=http://+:8088
|
||||
ASPNETCORE_ENVIRONMENT=Development
|
||||
AZURE_AI_MODEL_DEPLOYMENT_NAME=gpt-4o
|
||||
AZURE_BEARER_TOKEN=DefaultAzureCredential
|
||||
@@ -0,0 +1,17 @@
|
||||
# Use the official .NET 10.0 ASP.NET runtime as a parent image
|
||||
FROM mcr.microsoft.com/dotnet/aspnet:10.0 AS base
|
||||
WORKDIR /app
|
||||
|
||||
FROM mcr.microsoft.com/dotnet/sdk:10.0 AS build
|
||||
WORKDIR /src
|
||||
COPY . .
|
||||
RUN dotnet restore
|
||||
RUN dotnet publish -c Release -o /app/publish
|
||||
|
||||
# Final stage
|
||||
FROM base AS final
|
||||
WORKDIR /app
|
||||
COPY --from=build /app/publish .
|
||||
EXPOSE 8088
|
||||
ENV ASPNETCORE_URLS=http://+:8088
|
||||
ENTRYPOINT ["dotnet", "HostedFiles.dll"]
|
||||
+19
@@ -0,0 +1,19 @@
|
||||
# Dockerfile for contributors building from the agent-framework repository source.
|
||||
#
|
||||
# This project uses ProjectReference to the local Microsoft.Agents.AI.Foundry source,
|
||||
# which means a standard multi-stage Docker build cannot resolve dependencies outside
|
||||
# this folder. Instead, pre-publish the app targeting the container runtime and copy
|
||||
# the output into the container:
|
||||
#
|
||||
# dotnet publish -c Debug -f net10.0 -r linux-musl-x64 --self-contained false -o out
|
||||
# docker build -f Dockerfile.contributor -t hosted-files .
|
||||
# docker run --rm -p 8088:8088 -e AGENT_NAME=hosted-files -e AZURE_BEARER_TOKEN=$AZURE_BEARER_TOKEN --env-file .env hosted-files
|
||||
#
|
||||
# For end-users consuming the NuGet package (not ProjectReference), use the standard
|
||||
# Dockerfile which performs a full dotnet restore + publish inside the container.
|
||||
FROM mcr.microsoft.com/dotnet/aspnet:10.0-alpine AS final
|
||||
WORKDIR /app
|
||||
COPY out/ .
|
||||
EXPOSE 8088
|
||||
ENV ASPNETCORE_URLS=http://+:8088
|
||||
ENTRYPOINT ["dotnet", "HostedFiles.dll"]
|
||||
+40
@@ -0,0 +1,40 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk.Web">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFrameworks>net10.0</TargetFrameworks>
|
||||
<Nullable>enable</Nullable>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<CentralPackageTransitivePinningEnabled>false</CentralPackageTransitivePinningEnabled>
|
||||
<RootNamespace>HostedFiles</RootNamespace>
|
||||
<AssemblyName>HostedFiles</AssemblyName>
|
||||
<NoWarn>$(NoWarn);</NoWarn>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Azure.AI.Projects" VersionOverride="2.1.0-beta.1" />
|
||||
<PackageReference Include="Azure.Identity" />
|
||||
<PackageReference Include="DotNetEnv" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<!-- Bake demo resources into the published output so the deployed agent's
|
||||
tools can read them from /app/resources/ inside the container. -->
|
||||
<Content Include="resources\**\*">
|
||||
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
|
||||
</Content>
|
||||
</ItemGroup>
|
||||
|
||||
<!-- For contributors: uses ProjectReference to build against local source -->
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\..\..\..\..\src\Microsoft.Agents.AI.Foundry\Microsoft.Agents.AI.Foundry.csproj" />
|
||||
<ProjectReference Include="..\..\..\..\..\src\Microsoft.Agents.AI.Foundry.Hosting\Microsoft.Agents.AI.Foundry.Hosting.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
<!-- For end-users: uncomment the PackageReference below and remove the ProjectReference above
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.Agents.AI.Foundry" Version="1.0.0" />
|
||||
<PackageReference Include="Microsoft.Agents.AI.Foundry.Hosting" Version="1.0.0" />
|
||||
</ItemGroup>
|
||||
-->
|
||||
|
||||
</Project>
|
||||
@@ -0,0 +1,223 @@
|
||||
// Copyright (c) Microsoft. All rights reserved.
|
||||
|
||||
// Hosted Files Agent - A hosted agent that exposes two distinct file knowledge sources
|
||||
// through scoped, security-hardened tools:
|
||||
//
|
||||
// * Bundled files (image-baked) — files copied into the published output via the csproj
|
||||
// <Content Include="resources\**"> rule. Live at /app/resources/ inside the container.
|
||||
// Author-shipped knowledge that ships with every session.
|
||||
//
|
||||
// * Session files (per-session $HOME volume) — files uploaded at runtime via the alpha
|
||||
// Azure.AI.Projects.AgentSessionFiles SDK. Live at $HOME inside the per-session
|
||||
// container, which the platform sets to /home/session by default
|
||||
// (container-image-spec.md line 127, "If you use the session files API, $HOME is
|
||||
// also the base path for those operations").
|
||||
//
|
||||
// Each source is exposed via a separate tool pair, each rooted at its own directory.
|
||||
// Tools take a fileName, not a path: Path.GetFileName strips any directory components,
|
||||
// then a canonicalize + StartsWith(root) check enforces the boundary. The model cannot
|
||||
// be tricked into reading /etc/passwd or any path outside its tool's root, even via
|
||||
// indirect prompt injection in an uploaded file.
|
||||
//
|
||||
// Required environment variables:
|
||||
// AZURE_AI_PROJECT_ENDPOINT - Azure AI Foundry project endpoint
|
||||
// AZURE_AI_MODEL_DEPLOYMENT_NAME - Model deployment name (default: gpt-4o)
|
||||
//
|
||||
// Optional:
|
||||
// AGENT_NAME - Agent name (default: hosted-files)
|
||||
// BUNDLED_FILES_DIR - Override the bundled-files root
|
||||
// (default: <baseDir>/resources, i.e. /app/resources/)
|
||||
// HOME - Standard env var; the per-session sandbox volume
|
||||
// (default: /home/session in the platform-managed container)
|
||||
|
||||
using System.ComponentModel;
|
||||
using Azure.AI.Projects;
|
||||
using Azure.Core;
|
||||
using Azure.Identity;
|
||||
using DotNetEnv;
|
||||
using Microsoft.Agents.AI;
|
||||
using Microsoft.Agents.AI.Foundry.Hosting;
|
||||
using Microsoft.Extensions.AI;
|
||||
|
||||
// Load .env file if present (for local development)
|
||||
Env.TraversePath().Load();
|
||||
|
||||
// Bypass SampleEnvironment alias (which prompts on missing env vars) for optional values.
|
||||
string? GetOptionalEnv(string key) => System.Environment.GetEnvironmentVariable(key);
|
||||
|
||||
string endpoint = Environment.GetEnvironmentVariable("AZURE_AI_PROJECT_ENDPOINT")
|
||||
?? throw new InvalidOperationException("AZURE_AI_PROJECT_ENDPOINT is not set.");
|
||||
string deploymentName = GetOptionalEnv("AZURE_AI_MODEL_DEPLOYMENT_NAME") ?? "gpt-4o";
|
||||
|
||||
// Use a chained credential: try a temporary dev token first (for local Docker debugging),
|
||||
// then fall back to DefaultAzureCredential (for local dev via dotnet run / managed identity in production).
|
||||
TokenCredential credential = new ChainedTokenCredential(
|
||||
new DevTemporaryTokenCredential(),
|
||||
new DefaultAzureCredential());
|
||||
|
||||
// ── File roots (canonicalized once) ──────────────────────────────────────────
|
||||
|
||||
// Bundled root: where csproj <Content Include="resources\**"> lands at runtime.
|
||||
// In the container that resolves to /app/resources/.
|
||||
string bundledRoot = Path.GetFullPath(
|
||||
GetOptionalEnv("BUNDLED_FILES_DIR")
|
||||
?? Path.Combine(AppContext.BaseDirectory, "resources"));
|
||||
|
||||
// Session root: the per-session $HOME volume mounted by the Foundry platform.
|
||||
// Files uploaded via AgentSessionFiles.UploadSessionFileAsync(sessionStoragePath: "foo")
|
||||
// land at $HOME/foo per container-image-spec.md line 172.
|
||||
string sessionRoot = Path.GetFullPath(
|
||||
GetOptionalEnv("HOME")
|
||||
?? "/home/session");
|
||||
|
||||
// ── Tools: bundled files (image-baked, /app/resources/) ──────────────────────
|
||||
|
||||
[Description("List the names of files bundled with the agent (built-in knowledge that ships with the image).")]
|
||||
string ListBundledFiles() => SafeListNames(bundledRoot);
|
||||
|
||||
[Description("Read the full text contents of a bundled file by name. Bundled files are built-in knowledge shipped with the agent image.")]
|
||||
string ReadBundledFile(
|
||||
[Description("Name of the bundled file (no directory components). Must be one of the names returned by ListBundledFiles.")] string fileName)
|
||||
=> SafeRead(bundledRoot, fileName, scope: "bundled files");
|
||||
|
||||
// ── Tools: session files (per-session $HOME) ─────────────────────────────────
|
||||
|
||||
[Description("List the names of files uploaded into the current session sandbox by the user (e.g., via AgentSessionFiles.UploadSessionFileAsync).")]
|
||||
string ListSessionFiles() => SafeListNames(sessionRoot);
|
||||
|
||||
[Description("Read the full text contents of a file uploaded into the current session by name. Session files are user-supplied data that lives only for the lifetime of this session.")]
|
||||
string ReadSessionFile(
|
||||
[Description("Name of the session file (no directory components). Must be one of the names returned by ListSessionFiles.")] string fileName)
|
||||
=> SafeRead(sessionRoot, fileName, scope: "session files");
|
||||
|
||||
// ── Path-safe helpers (defense-in-depth: GetFileName + canonicalize + StartsWith(root)) ──
|
||||
|
||||
string SafeListNames(string root)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (!Directory.Exists(root))
|
||||
{
|
||||
return string.Empty;
|
||||
}
|
||||
|
||||
return string.Join(
|
||||
Environment.NewLine,
|
||||
Directory.EnumerateFiles(root).Select(Path.GetFileName));
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
return $"Error listing files: {ex.Message}";
|
||||
}
|
||||
}
|
||||
|
||||
string SafeRead(string root, string fileName, string scope)
|
||||
{
|
||||
try
|
||||
{
|
||||
// Step 1: strip any directory components the model might have included.
|
||||
string safeName = Path.GetFileName(fileName);
|
||||
if (string.IsNullOrEmpty(safeName))
|
||||
{
|
||||
return $"File '{fileName}' not found in {scope}.";
|
||||
}
|
||||
|
||||
// Step 2: combine with the root and canonicalize.
|
||||
string fullPath = Path.GetFullPath(Path.Combine(root, safeName));
|
||||
|
||||
// Step 3: enforce the prefix boundary so a crafted name still cannot escape.
|
||||
string rootPrefix = root.EndsWith(Path.DirectorySeparatorChar)
|
||||
? root
|
||||
: root + Path.DirectorySeparatorChar;
|
||||
if (!fullPath.StartsWith(rootPrefix, StringComparison.Ordinal))
|
||||
{
|
||||
return $"File '{fileName}' not found in {scope}.";
|
||||
}
|
||||
|
||||
return File.Exists(fullPath)
|
||||
? File.ReadAllText(fullPath)
|
||||
: $"File '{fileName}' not found in {scope}.";
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
return $"Error reading '{fileName}': {ex.Message}";
|
||||
}
|
||||
}
|
||||
|
||||
// ── Create and host the agent ────────────────────────────────────────────────
|
||||
|
||||
AIAgent agent = new AIProjectClient(new Uri(endpoint), credential)
|
||||
.AsAIAgent(
|
||||
model: deploymentName,
|
||||
instructions: """
|
||||
You are a friendly assistant that answers questions over two file sources:
|
||||
|
||||
- Bundled files: built-in knowledge that ships with the agent image
|
||||
(e.g., reference reports the author packaged with you). Tools:
|
||||
ListBundledFiles, ReadBundledFile.
|
||||
|
||||
- Session files: user-uploaded data for this session only (e.g., a CSV
|
||||
the user wants you to analyse). Tools: ListSessionFiles, ReadSessionFile.
|
||||
|
||||
Pick the tool pair by intent. If a name could match either source, list
|
||||
both first. Always read the file before answering; do not guess. Quote
|
||||
numbers and figures verbatim from the file.
|
||||
""",
|
||||
name: GetOptionalEnv("AGENT_NAME") ?? "hosted-files",
|
||||
description: "Hosted agent that answers questions over bundled (image-baked) and session-uploaded files via two scoped tool pairs.",
|
||||
tools:
|
||||
[
|
||||
AIFunctionFactory.Create(ListBundledFiles),
|
||||
AIFunctionFactory.Create(ReadBundledFile),
|
||||
AIFunctionFactory.Create(ListSessionFiles),
|
||||
AIFunctionFactory.Create(ReadSessionFile),
|
||||
]);
|
||||
|
||||
var builder = WebApplication.CreateBuilder(args);
|
||||
builder.Services.AddFoundryResponses(agent);
|
||||
|
||||
var app = builder.Build();
|
||||
app.MapFoundryResponses();
|
||||
|
||||
if (app.Environment.IsDevelopment())
|
||||
{
|
||||
app.MapFoundryResponses("openai/v1");
|
||||
}
|
||||
|
||||
app.Run();
|
||||
|
||||
/// <summary>
|
||||
/// A <see cref="TokenCredential"/> for local Docker debugging only.
|
||||
/// Reads a pre-fetched bearer token from the <c>AZURE_BEARER_TOKEN</c> environment variable
|
||||
/// once at startup. This should NOT be used in production.
|
||||
///
|
||||
/// Generate a token on your host and pass it to the container:
|
||||
/// export AZURE_BEARER_TOKEN=$(az account get-access-token --resource https://ai.azure.com --query accessToken -o tsv)
|
||||
/// docker run -e AZURE_BEARER_TOKEN=$AZURE_BEARER_TOKEN ...
|
||||
/// </summary>
|
||||
internal sealed class DevTemporaryTokenCredential : TokenCredential
|
||||
{
|
||||
private const string EnvironmentVariable = "AZURE_BEARER_TOKEN";
|
||||
private readonly string? _token;
|
||||
|
||||
public DevTemporaryTokenCredential()
|
||||
{
|
||||
this._token = System.Environment.GetEnvironmentVariable(EnvironmentVariable);
|
||||
}
|
||||
|
||||
public override AccessToken GetToken(TokenRequestContext requestContext, CancellationToken cancellationToken)
|
||||
=> this.GetAccessToken();
|
||||
|
||||
public override ValueTask<AccessToken> GetTokenAsync(TokenRequestContext requestContext, CancellationToken cancellationToken)
|
||||
=> new(this.GetAccessToken());
|
||||
|
||||
private AccessToken GetAccessToken()
|
||||
{
|
||||
if (string.IsNullOrEmpty(this._token) || this._token == "DefaultAzureCredential")
|
||||
{
|
||||
throw new CredentialUnavailableException($"{EnvironmentVariable} environment variable is not set.");
|
||||
}
|
||||
|
||||
return new AccessToken(this._token, DateTimeOffset.UtcNow.AddHours(1));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,128 @@
|
||||
# Hosted-Files
|
||||
|
||||
A hosted agent that demonstrates **two distinct file knowledge sources** through scoped, security-hardened tools:
|
||||
|
||||
- **Bundled files** (image-baked) — files the author packages with the agent at build time. Live at `/app/resources/` inside the container, copied from this project's [`resources/`](./resources/) folder via the csproj `<Content Include="resources\**\*" CopyToOutputDirectory="PreserveNewest" />` rule.
|
||||
- **Session files** (per-session `$HOME` volume) — files the user uploads at runtime via the alpha `Azure.AI.Projects.AgentSessionFiles` SDK. Live at `$HOME` inside the per-session container. The Foundry platform sets `HOME=/home/session` by default and roots the session-files API there per [`container-image-spec.md` line 172](https://github.com/microsoft/foundrysdk-specs/blob/main/specs/agents/hosted_agents/container-spec/docs/container-image-spec.md): *"If you use the session files API, `$HOME` is also the base path for those operations; any paths given in those API endpoints will be relative to `$HOME`."*
|
||||
|
||||
## Tool surface
|
||||
|
||||
Each source is exposed via its own tool pair, rooted at its own directory. The model picks by intent.
|
||||
|
||||
| Tool | Source | Root |
|
||||
|------|--------|------|
|
||||
| `ListBundledFiles` | Bundled (image-baked) | `/app/resources/` |
|
||||
| `ReadBundledFile` | Bundled (image-baked) | `/app/resources/` |
|
||||
| `ListSessionFiles` | Session-uploaded | `$HOME` (`/home/session`) |
|
||||
| `ReadSessionFile` | Session-uploaded | `$HOME` (`/home/session`) |
|
||||
|
||||
## Security model — distinct tools, distinct sandboxes
|
||||
|
||||
Each tool takes a `fileName` (no directory components allowed) and enforces three layers of defence inside the implementation:
|
||||
|
||||
1. **`Path.GetFileName(input)`** strips any directory parts from the model-supplied name. `"../../etc/passwd"` becomes `"passwd"`.
|
||||
2. **`Path.GetFullPath(Combine(root, name))`** canonicalises the path.
|
||||
3. **`fullPath.StartsWith(root + DirectorySeparatorChar)`** rejects anything that resolves outside the tool's root.
|
||||
|
||||
Failures return a controlled `"File '<input>' not found in <scope>."` rather than throwing or exposing the canonical path.
|
||||
|
||||
This is why the agent has four narrowly-scoped tools instead of a single `ReadFile(path)`:
|
||||
|
||||
- **Smaller per-tool attack surface.** Each tool has one purpose, one root, and no path-typed parameter. Even a buggy implementation can only leak its own directory.
|
||||
- **Cross-boundary access is impossible by schema.** A prompt-injection attempt to make the bundled tool read a session path (or vice versa) does not even compile in the tool schema the model sees.
|
||||
- **Read-only, non-recursive listing.** No write tools, no glob, no `..`.
|
||||
|
||||
## Companion
|
||||
|
||||
[`Using-Samples/SessionFilesClient`](../Using-Samples/SessionFilesClient/) — a thin chat REPL (same shape as [`SimpleAgent`](../Using-Samples/SimpleAgent/)) that points at the deployed Hosted-Files endpoint via `FoundryAgent` and lets you ask questions whose answers come from either file source.
|
||||
|
||||
## Live proof of the session-files contract
|
||||
|
||||
The end-to-end alpha-SDK round trip (client uploads via `AgentSessionFiles.UploadSessionFileAsync` → file arrives at `$HOME/<name>` inside the per-session container → agent's `ReadSessionFile` tool reads it → response quotes the verbatim contents) is exercised live by [`SessionFilesHostedAgentTests.UploadedFile_IsReadByHostedAgentAsync`](../../../../../tests/Foundry.Hosting.IntegrationTests/SessionFilesHostedAgentTests.cs) against the matching `session-files` scenario in the integration test container.
|
||||
|
||||
## Prerequisites
|
||||
|
||||
- [.NET 10 SDK](https://dotnet.microsoft.com/download/dotnet/10.0)
|
||||
- An Azure AI Foundry project with a deployed model (e.g., `gpt-4o`)
|
||||
- Azure CLI logged in (`az login`)
|
||||
|
||||
## Configuration
|
||||
|
||||
Copy the template and fill in your project endpoint:
|
||||
|
||||
```bash
|
||||
cp .env.example .env
|
||||
```
|
||||
|
||||
Edit `.env`:
|
||||
|
||||
```env
|
||||
AZURE_AI_PROJECT_ENDPOINT=https://<your-account>.services.ai.azure.com/api/projects/<your-project>
|
||||
ASPNETCORE_URLS=http://+:8088
|
||||
ASPNETCORE_ENVIRONMENT=Development
|
||||
AZURE_AI_MODEL_DEPLOYMENT_NAME=gpt-4o
|
||||
```
|
||||
|
||||
> `.env` is gitignored. The `.env.example` template is checked in as a reference.
|
||||
|
||||
## Running directly (contributors)
|
||||
|
||||
```bash
|
||||
cd dotnet/samples/04-hosting/FoundryHostedAgents/responses/Hosted-Files
|
||||
AGENT_NAME=hosted-files dotnet run
|
||||
```
|
||||
|
||||
The agent starts on `http://localhost:8088`.
|
||||
|
||||
## Try it from the SessionFilesClient REPL
|
||||
|
||||
### Bundled files (works against any deployment, including local)
|
||||
|
||||
```bash
|
||||
cd ../Using-Samples/SessionFilesClient
|
||||
$env:AGENT_ENDPOINT = "http://localhost:8088"
|
||||
$env:AGENT_NAME = "hosted-files"
|
||||
dotnet run
|
||||
|
||||
You> What is the total revenue in the contoso file?
|
||||
Agent> The contoso file reports total revenue of "$1,482.6M".
|
||||
```
|
||||
|
||||
The agent calls `ListBundledFiles`, sees `contoso_q1_2026_report.txt`, calls `ReadBundledFile("contoso_q1_2026_report.txt")` (which resolves under `/app/resources/`), and quotes the figure verbatim.
|
||||
|
||||
### Session files (against a deployed agent)
|
||||
|
||||
Upload a file to a specific session via `azd ai agent files upload` or via the alpha `AgentSessionFiles` SDK (see the integration test for the SDK call), then ask the agent about it. The agent's `ReadSessionFile` tool reads from `$HOME` and surfaces the content the same way.
|
||||
|
||||
## Running with Docker
|
||||
|
||||
This project uses `ProjectReference`, so use `Dockerfile.contributor` which takes a pre-published output:
|
||||
|
||||
```bash
|
||||
dotnet publish -c Debug -f net10.0 -r linux-musl-x64 --self-contained false -o out
|
||||
docker build -f Dockerfile.contributor -t hosted-files .
|
||||
|
||||
export AZURE_BEARER_TOKEN=$(az account get-access-token --resource https://ai.azure.com --query accessToken -o tsv)
|
||||
docker run --rm -p 8088:8088 \
|
||||
-e AGENT_NAME=hosted-files \
|
||||
-e AZURE_BEARER_TOKEN=$AZURE_BEARER_TOKEN \
|
||||
--env-file .env \
|
||||
hosted-files
|
||||
```
|
||||
|
||||
The bundled `resources/` folder is part of the published output and ships inside the image.
|
||||
|
||||
## NuGet package users
|
||||
|
||||
If consuming the Agent Framework as a NuGet package, use the standard `Dockerfile` instead of `Dockerfile.contributor` and switch the `ProjectReference` entries in `HostedFiles.csproj` to `PackageReference` (commented section in the csproj).
|
||||
|
||||
## Adding more bundled files
|
||||
|
||||
Drop additional text files into [`resources/`](./resources/). The csproj `<Content Include="resources\**\*" CopyToOutputDirectory="PreserveNewest" />` rule picks them up on the next `dotnet build` / `docker build`.
|
||||
|
||||
## Overrides
|
||||
|
||||
| Env var | Purpose | Default |
|
||||
|---------|---------|---------|
|
||||
| `BUNDLED_FILES_DIR` | Override the bundled-files root the tools read from. | `<process base dir>/resources` (`/app/resources/` in container) |
|
||||
| `HOME` | The per-session sandbox volume root the session-files tools read from. Set by the Foundry platform; can be overridden for local testing. | `/home/session` |
|
||||
+30
@@ -0,0 +1,30 @@
|
||||
# yaml-language-server: $schema=https://raw.githubusercontent.com/microsoft/AgentSchema/refs/heads/main/schemas/v1.0/AgentManifest.yaml
|
||||
name: hosted-files
|
||||
displayName: "Hosted Files Agent"
|
||||
|
||||
description: >
|
||||
A hosted agent that answers questions over a small set of files bundled
|
||||
with its container image (under /app/resources/). Two local C# function
|
||||
tools (ListFiles, ReadFile) surface the bundled file contents to the model.
|
||||
|
||||
metadata:
|
||||
tags:
|
||||
- AI Agent Hosting
|
||||
- Azure AI AgentServer
|
||||
- Responses Protocol
|
||||
- Bundled Files
|
||||
- Local Tools
|
||||
- Agent Framework
|
||||
|
||||
template:
|
||||
name: hosted-files
|
||||
kind: hosted
|
||||
protocols:
|
||||
- protocol: responses
|
||||
version: 1.0.0
|
||||
resources:
|
||||
cpu: "0.25"
|
||||
memory: 0.5Gi
|
||||
parameters:
|
||||
properties: []
|
||||
resources: []
|
||||
@@ -0,0 +1,9 @@
|
||||
# yaml-language-server: $schema=https://raw.githubusercontent.com/microsoft/AgentSchema/refs/heads/main/schemas/v1.0/ContainerAgent.yaml
|
||||
kind: hosted
|
||||
name: hosted-files
|
||||
protocols:
|
||||
- protocol: responses
|
||||
version: 1.0.0
|
||||
resources:
|
||||
cpu: "0.25"
|
||||
memory: 0.5Gi
|
||||
+121
@@ -0,0 +1,121 @@
|
||||
Contoso Corporation
|
||||
Quarterly Report — Q1 2026 (Three months ended March 31, 2026)
|
||||
|
||||
DISCLAIMER
|
||||
This document contains fictional data for sample/demo purposes only.
|
||||
Contoso is a fictional company; all figures below are fabricated.
|
||||
|
||||
------------------------------------------------------------
|
||||
1. EXECUTIVE SUMMARY
|
||||
------------------------------------------------------------
|
||||
Contoso delivered a solid first quarter, with total revenue of
|
||||
$1,482.6M, up 11.4% year-over-year. Growth was led by the Cloud
|
||||
Services segment (+22.7% YoY) and continued double-digit expansion
|
||||
in International markets. Operating margin expanded 140 basis points
|
||||
to 23.8% on disciplined cost management and improved gross margin.
|
||||
|
||||
Key highlights:
|
||||
- Revenue: $1,482.6M (YoY +11.4%)
|
||||
- Gross profit: $912.0M (gross margin 61.5%)
|
||||
- Operating income: $352.9M (operating margin 23.8%)
|
||||
- Net income: $268.4M (net margin 18.1%)
|
||||
- Diluted EPS: $1.27 (vs. $1.04 prior year)
|
||||
- Free cash flow: $311.5M
|
||||
- Cash & equivalents: $2,140.8M
|
||||
|
||||
------------------------------------------------------------
|
||||
2. INCOME STATEMENT (USD millions, unaudited)
|
||||
------------------------------------------------------------
|
||||
Q1 2026 Q1 2025 YoY %
|
||||
Revenue 1,482.6 1,330.7 +11.4%
|
||||
Cost of revenue 570.6 538.9 +5.9%
|
||||
Gross profit 912.0 791.8 +15.2%
|
||||
Gross margin 61.5% 59.5% +200 bps
|
||||
Operating expenses
|
||||
Research & development 241.4 220.5 +9.5%
|
||||
Sales & marketing 218.7 205.1 +6.6%
|
||||
General & administrative 99.0 88.6 +11.7%
|
||||
Total operating expenses 559.1 514.2 +8.7%
|
||||
Operating income 352.9 277.6 +27.1%
|
||||
Operating margin 23.8% 20.9% +290 bps
|
||||
Other income / (expense), net 8.4 5.1
|
||||
Income before taxes 361.3 282.7
|
||||
Provision for income taxes 92.9 72.6
|
||||
Net income 268.4 210.1 +27.7%
|
||||
Diluted EPS (USD) 1.27 1.04 +22.1%
|
||||
|
||||
------------------------------------------------------------
|
||||
3. REVENUE BY SEGMENT (USD millions)
|
||||
------------------------------------------------------------
|
||||
Segment Q1 2026 Q1 2025 YoY %
|
||||
Cloud Services 612.4 499.1 +22.7%
|
||||
Productivity Software 448.9 422.6 +6.2%
|
||||
Devices & Hardware 267.0 260.4 +2.5%
|
||||
Professional Services 154.3 148.6 +3.8%
|
||||
Total revenue 1,482.6 1,330.7 +11.4%
|
||||
|
||||
------------------------------------------------------------
|
||||
4. REVENUE BY GEOGRAPHY (USD millions)
|
||||
------------------------------------------------------------
|
||||
Region Q1 2026 Q1 2025 YoY %
|
||||
North America 812.1 756.0 +7.4%
|
||||
EMEA 388.5 340.2 +14.2%
|
||||
Asia-Pacific 221.7 183.4 +20.9%
|
||||
Latin America 60.3 51.1 +18.0%
|
||||
Total revenue 1,482.6 1,330.7 +11.4%
|
||||
|
||||
------------------------------------------------------------
|
||||
5. SELECTED BALANCE SHEET ITEMS (USD millions)
|
||||
------------------------------------------------------------
|
||||
Mar 31, Dec 31,
|
||||
2026 2025
|
||||
Cash & equivalents 2,140.8 1,902.3
|
||||
Short-term investments 845.6 820.4
|
||||
Accounts receivable, net 1,012.7 988.5
|
||||
Total current assets 4,510.2 4,190.6
|
||||
Goodwill & intangibles 2,330.1 2,338.9
|
||||
Total assets 9,884.5 9,512.0
|
||||
Total current liabilities 2,118.4 2,054.7
|
||||
Long-term debt 1,750.0 1,750.0
|
||||
Total liabilities 4,402.6 4,310.5
|
||||
Total stockholders' equity 5,481.9 5,201.5
|
||||
|
||||
------------------------------------------------------------
|
||||
6. CASH FLOW HIGHLIGHTS (USD millions)
|
||||
------------------------------------------------------------
|
||||
Q1 2026 Q1 2025
|
||||
Net cash from operating activities 382.0 298.7
|
||||
Capital expenditures (70.5) (62.1)
|
||||
Free cash flow 311.5 236.6
|
||||
Share repurchases (120.0) (90.0)
|
||||
Dividends paid (54.2) (48.6)
|
||||
|
||||
------------------------------------------------------------
|
||||
7. KEY OPERATING METRICS
|
||||
------------------------------------------------------------
|
||||
Cloud paid seats (millions) 48.6 39.7 +22.4%
|
||||
Cloud net revenue retention 118% 114%
|
||||
Active enterprise customers 18,420 16,905 +9.0%
|
||||
Headcount (end of period) 22,140 20,610 +7.4%
|
||||
|
||||
------------------------------------------------------------
|
||||
8. OUTLOOK — Q2 2026 GUIDANCE
|
||||
------------------------------------------------------------
|
||||
Revenue: $1,520M – $1,560M (YoY +10% to +13%)
|
||||
Operating margin: 23.5% – 24.5%
|
||||
Diluted EPS: $1.30 – $1.36
|
||||
Capital expenditures: ~$80M
|
||||
|
||||
Management remains confident in the full-year plan and reiterates
|
||||
fiscal-year 2026 revenue growth of 10–12% and operating-margin
|
||||
expansion of 100–150 basis points versus FY 2025.
|
||||
|
||||
------------------------------------------------------------
|
||||
9. NOTES
|
||||
------------------------------------------------------------
|
||||
- All figures are unaudited and rounded to one decimal place.
|
||||
- Year-over-year comparisons are versus the same period in 2025.
|
||||
- "Free cash flow" is defined as net cash from operating activities
|
||||
less capital expenditures, and is a non-GAAP measure.
|
||||
- This sample report is intended solely for demonstration of an
|
||||
agent-driven document analysis pipeline.
|
||||
+2
-2
@@ -1,4 +1,4 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk.Web">
|
||||
<Project Sdk="Microsoft.NET.Sdk.Web">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFrameworks>net10.0</TargetFrameworks>
|
||||
@@ -11,7 +11,7 @@
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Azure.AI.Projects" VersionOverride="2.1.0-beta.1" />
|
||||
<PackageReference Include="Azure.AI.Projects" />
|
||||
<PackageReference Include="Azure.Identity" />
|
||||
<PackageReference Include="DotNetEnv" />
|
||||
</ItemGroup>
|
||||
|
||||
+2
-2
@@ -1,4 +1,4 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk.Web">
|
||||
<Project Sdk="Microsoft.NET.Sdk.Web">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFrameworks>net10.0</TargetFrameworks>
|
||||
@@ -11,7 +11,7 @@
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Azure.AI.Projects" VersionOverride="2.1.0-beta.1" />
|
||||
<PackageReference Include="Azure.AI.Projects" />
|
||||
<PackageReference Include="Azure.Identity" />
|
||||
<PackageReference Include="ModelContextProtocol" VersionOverride="1.2.0" />
|
||||
<PackageReference Include="DotNetEnv" />
|
||||
|
||||
+2
-2
@@ -1,4 +1,4 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk.Web">
|
||||
<Project Sdk="Microsoft.NET.Sdk.Web">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFrameworks>net10.0</TargetFrameworks>
|
||||
@@ -11,7 +11,7 @@
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Azure.AI.Projects" VersionOverride="2.1.0-beta.1" />
|
||||
<PackageReference Include="Azure.AI.Projects" />
|
||||
<PackageReference Include="Azure.Identity" />
|
||||
<PackageReference Include="DotNetEnv" />
|
||||
</ItemGroup>
|
||||
|
||||
+2
-2
@@ -1,4 +1,4 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk.Web">
|
||||
<Project Sdk="Microsoft.NET.Sdk.Web">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFrameworks>net10.0</TargetFrameworks>
|
||||
@@ -11,7 +11,7 @@
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Azure.AI.Projects" VersionOverride="2.1.0-beta.1" />
|
||||
<PackageReference Include="Azure.AI.Projects" />
|
||||
<PackageReference Include="Azure.Identity" />
|
||||
<PackageReference Include="DotNetEnv" />
|
||||
</ItemGroup>
|
||||
|
||||
+1
-1
@@ -11,7 +11,7 @@
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Azure.AI.Projects" VersionOverride="2.1.0-beta.1" />
|
||||
<PackageReference Include="Azure.AI.Projects" />
|
||||
<PackageReference Include="Azure.Identity" />
|
||||
<PackageReference Include="DotNetEnv" />
|
||||
</ItemGroup>
|
||||
|
||||
+2
-2
@@ -1,4 +1,4 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk.Web">
|
||||
<Project Sdk="Microsoft.NET.Sdk.Web">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFrameworks>net10.0</TargetFrameworks>
|
||||
@@ -11,7 +11,7 @@
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Azure.AI.Projects" VersionOverride="2.1.0-beta.1" />
|
||||
<PackageReference Include="Azure.AI.Projects" />
|
||||
<PackageReference Include="Azure.Identity" />
|
||||
<PackageReference Include="DotNetEnv" />
|
||||
</ItemGroup>
|
||||
|
||||
+116
@@ -0,0 +1,116 @@
|
||||
// Copyright (c) Microsoft. All rights reserved.
|
||||
|
||||
using System.ClientModel.Primitives;
|
||||
using Azure.AI.Extensions.OpenAI;
|
||||
using Azure.AI.Projects;
|
||||
using Azure.Identity;
|
||||
using DotNetEnv;
|
||||
using Microsoft.Agents.AI;
|
||||
using Microsoft.Agents.AI.Foundry;
|
||||
|
||||
// Load .env file if present (for local development)
|
||||
Env.TraversePath().Load();
|
||||
|
||||
Uri agentEndpoint = new(Environment.GetEnvironmentVariable("AGENT_ENDPOINT")
|
||||
?? "http://localhost:8088");
|
||||
|
||||
var agentName = Environment.GetEnvironmentVariable("AGENT_NAME")
|
||||
?? throw new InvalidOperationException("AGENT_NAME is not set.");
|
||||
|
||||
// ── Create an agent-framework agent backed by the remote Hosted-Files agent ──
|
||||
|
||||
var options = new AIProjectClientOptions();
|
||||
|
||||
if (agentEndpoint.Scheme == "http")
|
||||
{
|
||||
// For local HTTP dev: tell AIProjectClient the endpoint is HTTPS (to satisfy
|
||||
// BearerTokenPolicy's TLS check), then swap the scheme back to HTTP right
|
||||
// before the request hits the wire.
|
||||
|
||||
agentEndpoint = new UriBuilder(agentEndpoint) { Scheme = "https" }.Uri;
|
||||
options.AddPolicy(new HttpSchemeRewritePolicy(), PipelinePosition.BeforeTransport);
|
||||
}
|
||||
|
||||
var aiProjectClient = new AIProjectClient(agentEndpoint, new AzureCliCredential(), options);
|
||||
FoundryAgent agent = aiProjectClient.AsAIAgent(new AgentReference(agentName));
|
||||
|
||||
AgentSession session = await agent.CreateSessionAsync();
|
||||
|
||||
// ── REPL ──────────────────────────────────────────────────────────────────────
|
||||
|
||||
Console.ForegroundColor = ConsoleColor.Cyan;
|
||||
Console.WriteLine($"""
|
||||
══════════════════════════════════════════════════════════
|
||||
Session Files Client
|
||||
Connected to: {agentEndpoint}
|
||||
Try: "Give me the total revenue in the contoso file."
|
||||
Type a message or 'quit' to exit
|
||||
══════════════════════════════════════════════════════════
|
||||
""");
|
||||
Console.ResetColor();
|
||||
Console.WriteLine();
|
||||
|
||||
while (true)
|
||||
{
|
||||
Console.ForegroundColor = ConsoleColor.Green;
|
||||
Console.Write("You> ");
|
||||
Console.ResetColor();
|
||||
|
||||
string? input = Console.ReadLine();
|
||||
|
||||
if (string.IsNullOrWhiteSpace(input)) { continue; }
|
||||
if (input.Equals("quit", StringComparison.OrdinalIgnoreCase)) { break; }
|
||||
|
||||
try
|
||||
{
|
||||
Console.ForegroundColor = ConsoleColor.Yellow;
|
||||
Console.Write("Agent> ");
|
||||
Console.ResetColor();
|
||||
|
||||
await foreach (var update in agent.RunStreamingAsync(input, session))
|
||||
{
|
||||
Console.Write(update);
|
||||
}
|
||||
|
||||
Console.WriteLine();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.ForegroundColor = ConsoleColor.Red;
|
||||
Console.WriteLine($"Error: {ex.Message}");
|
||||
Console.ResetColor();
|
||||
}
|
||||
|
||||
Console.WriteLine();
|
||||
}
|
||||
|
||||
Console.WriteLine("Goodbye!");
|
||||
|
||||
/// <summary>
|
||||
/// For Local Development Only
|
||||
/// Rewrites HTTPS URIs to HTTP right before transport, allowing AIProjectClient
|
||||
/// to target a local HTTP dev server while satisfying BearerTokenPolicy's TLS check.
|
||||
/// </summary>
|
||||
internal sealed class HttpSchemeRewritePolicy : PipelinePolicy
|
||||
{
|
||||
public override void Process(PipelineMessage message, IReadOnlyList<PipelinePolicy> pipeline, int currentIndex)
|
||||
{
|
||||
RewriteScheme(message);
|
||||
ProcessNext(message, pipeline, currentIndex);
|
||||
}
|
||||
|
||||
public override async ValueTask ProcessAsync(PipelineMessage message, IReadOnlyList<PipelinePolicy> pipeline, int currentIndex)
|
||||
{
|
||||
RewriteScheme(message);
|
||||
await ProcessNextAsync(message, pipeline, currentIndex).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
private static void RewriteScheme(PipelineMessage message)
|
||||
{
|
||||
var uri = message.Request.Uri!;
|
||||
if (uri.Scheme == Uri.UriSchemeHttps)
|
||||
{
|
||||
message.Request.Uri = new UriBuilder(uri) { Scheme = "http" }.Uri;
|
||||
}
|
||||
}
|
||||
}
|
||||
+50
@@ -0,0 +1,50 @@
|
||||
# SessionFilesClient
|
||||
|
||||
A thin chat REPL that connects to a deployed [`Hosted-Files`](../../Hosted-Files/) agent via `FoundryAgent` and lets you ask questions whose answers come from the files bundled with that agent. Same shape as [`SimpleAgent`](../SimpleAgent/) — point it at an `AGENT_ENDPOINT`, build a `FoundryAgent`, run.
|
||||
|
||||
The agent's container-side `ListFiles` and `ReadFile` tools surface the bundled file contents to the model. The client knows nothing about files; that is entirely the agent's concern.
|
||||
|
||||
## Prerequisites
|
||||
|
||||
- [.NET 10 SDK](https://dotnet.microsoft.com/download/dotnet/10.0)
|
||||
- A running [`Hosted-Files`](../../Hosted-Files/) agent (locally via `dotnet run` or deployed to Foundry)
|
||||
- Azure CLI logged in (`az login`)
|
||||
|
||||
## Configuration
|
||||
|
||||
```env
|
||||
AGENT_ENDPOINT=http://localhost:8088
|
||||
AGENT_NAME=hosted-files
|
||||
```
|
||||
|
||||
`AGENT_ENDPOINT` defaults to `http://localhost:8088`. Override with the deployed agent endpoint when chatting against Foundry.
|
||||
|
||||
## Run
|
||||
|
||||
```bash
|
||||
cd dotnet/samples/04-hosting/FoundryHostedAgents/responses/Using-Samples/SessionFilesClient
|
||||
$env:AGENT_ENDPOINT = "http://localhost:8088"
|
||||
$env:AGENT_NAME = "hosted-files"
|
||||
dotnet run
|
||||
```
|
||||
|
||||
## End-to-end demo
|
||||
|
||||
With the [`Hosted-Files`](../../Hosted-Files/) agent running:
|
||||
|
||||
```text
|
||||
══════════════════════════════════════════════════════════
|
||||
Session Files Client
|
||||
Connected to: http://localhost:8088/
|
||||
Try: "Give me the total revenue in the contoso file."
|
||||
Type a message or 'quit' to exit
|
||||
══════════════════════════════════════════════════════════
|
||||
|
||||
You> Give me the total revenue in the contoso file.
|
||||
Agent> The contoso file reports total revenue of "$1,482.6M".
|
||||
|
||||
You> quit
|
||||
Goodbye!
|
||||
```
|
||||
|
||||
The agent looked at its bundled files via `ListFiles`, picked `contoso_q1_2026_report.txt`, called `ReadFile`, and quoted the figure verbatim. The client only sent a chat prompt.
|
||||
+24
@@ -0,0 +1,24 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<OutputType>Exe</OutputType>
|
||||
<TargetFrameworks>net10.0</TargetFrameworks>
|
||||
<Nullable>enable</Nullable>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<CentralPackageTransitivePinningEnabled>false</CentralPackageTransitivePinningEnabled>
|
||||
<RootNamespace>SessionFilesClient</RootNamespace>
|
||||
<AssemblyName>session-files-client</AssemblyName>
|
||||
<NoWarn>$(NoWarn);NU1605;OPENAI001</NoWarn>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Azure.AI.Projects" />
|
||||
<PackageReference Include="Azure.Identity" />
|
||||
<PackageReference Include="DotNetEnv" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\..\..\..\..\..\src\Microsoft.Agents.AI.Foundry\Microsoft.Agents.AI.Foundry.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
@@ -163,10 +163,22 @@ app.MapA2AHttpJson(knightsKnavesAgentBuilder, path: "/a2a/knights-and-knaves");
|
||||
app.MapDevUI();
|
||||
|
||||
app.MapOpenAIResponses();
|
||||
app.MapOpenAIResponses(pirateAgentBuilder);
|
||||
app.MapOpenAIResponses(knightsKnavesAgentBuilder);
|
||||
app.MapOpenAIResponses(chemistryAgent);
|
||||
app.MapOpenAIResponses(mathsAgent);
|
||||
app.MapOpenAIResponses(literatureAgent);
|
||||
app.MapOpenAIResponses(scienceSequentialWorkflow);
|
||||
app.MapOpenAIResponses(scienceConcurrentWorkflow);
|
||||
app.MapOpenAIConversations();
|
||||
|
||||
app.MapOpenAIChatCompletions(pirateAgentBuilder);
|
||||
app.MapOpenAIChatCompletions(knightsKnavesAgentBuilder);
|
||||
app.MapOpenAIChatCompletions(chemistryAgent);
|
||||
app.MapOpenAIChatCompletions(mathsAgent);
|
||||
app.MapOpenAIChatCompletions(literatureAgent);
|
||||
app.MapOpenAIChatCompletions(scienceSequentialWorkflow);
|
||||
app.MapOpenAIChatCompletions(scienceConcurrentWorkflow);
|
||||
|
||||
// Map the agents HTTP endpoints
|
||||
app.MapAgentDiscovery("/agents");
|
||||
|
||||
+1
-1
@@ -24,7 +24,7 @@ internal sealed class OpenAIChatCompletionsAgentClient(HttpClient httpClient) :
|
||||
{
|
||||
OpenAIClientOptions options = new()
|
||||
{
|
||||
Endpoint = new Uri(httpClient.BaseAddress!, $"/{agentName}/v1/"),
|
||||
Endpoint = new Uri(httpClient.BaseAddress!, $"/{Uri.EscapeDataString(agentName)}/v1/"),
|
||||
Transport = new HttpClientPipelineTransport(httpClient)
|
||||
};
|
||||
|
||||
|
||||
+1
-1
@@ -23,7 +23,7 @@ internal sealed class OpenAIResponsesAgentClient(HttpClient httpClient) : AgentC
|
||||
{
|
||||
OpenAIClientOptions options = new()
|
||||
{
|
||||
Endpoint = new Uri(httpClient.BaseAddress!, "/v1/"),
|
||||
Endpoint = new Uri(httpClient.BaseAddress!, $"/{Uri.EscapeDataString(agentName)}/v1/"),
|
||||
Transport = new HttpClientPipelineTransport(httpClient)
|
||||
};
|
||||
|
||||
|
||||
@@ -93,26 +93,26 @@ public sealed class A2AAgent : AIAgent
|
||||
/// <inheritdoc/>
|
||||
protected override async Task<AgentResponse> RunCoreAsync(IEnumerable<ChatMessage> messages, AgentSession? session = null, AgentRunOptions? options = null, CancellationToken cancellationToken = default)
|
||||
{
|
||||
_ = Throw.IfNull(messages);
|
||||
var inputMessages = Throw.IfNull(messages) as IReadOnlyCollection<ChatMessage> ?? messages.ToList();
|
||||
|
||||
A2AAgentSession typedSession = await this.GetA2ASessionAsync(session, options, cancellationToken).ConfigureAwait(false);
|
||||
|
||||
this._logger.LogA2AAgentInvokingAgent(nameof(RunAsync), this.Id, this.Name);
|
||||
|
||||
if (GetContinuationToken(messages, options) is { } token)
|
||||
if (GetContinuationToken(inputMessages, options) is { } token)
|
||||
{
|
||||
AgentTask agentTask = await this._a2aClient.GetTaskAsync(new GetTaskRequest { Id = token.TaskId }, cancellationToken).ConfigureAwait(false);
|
||||
|
||||
this._logger.LogAgentChatClientInvokedAgent(nameof(RunAsync), this.Id, this.Name);
|
||||
|
||||
UpdateSession(typedSession, agentTask.ContextId, agentTask.Id);
|
||||
UpdateSession(typedSession, agentTask.ContextId, agentTask.Id, agentTask.Status.State);
|
||||
|
||||
return this.ConvertToAgentResponse(agentTask);
|
||||
}
|
||||
|
||||
SendMessageRequest sendParams = new()
|
||||
{
|
||||
Message = CreateA2AMessage(typedSession, messages),
|
||||
Message = CreateA2AMessage(typedSession, inputMessages),
|
||||
Metadata = options?.AdditionalProperties?.ToA2AMetadata(),
|
||||
Configuration = new SendMessageConfiguration { ReturnImmediately = options?.AllowBackgroundResponses is true }
|
||||
};
|
||||
@@ -134,7 +134,7 @@ public sealed class A2AAgent : AIAgent
|
||||
{
|
||||
var agentTask = a2aResponse.Task!;
|
||||
|
||||
UpdateSession(typedSession, agentTask.ContextId, agentTask.Id);
|
||||
UpdateSession(typedSession, agentTask.ContextId, agentTask.Id, agentTask.Status.State);
|
||||
|
||||
return this.ConvertToAgentResponse(agentTask);
|
||||
}
|
||||
@@ -145,7 +145,7 @@ public sealed class A2AAgent : AIAgent
|
||||
/// <inheritdoc/>
|
||||
protected override async IAsyncEnumerable<AgentResponseUpdate> RunCoreStreamingAsync(IEnumerable<ChatMessage> messages, AgentSession? session = null, AgentRunOptions? options = null, [EnumeratorCancellation] CancellationToken cancellationToken = default)
|
||||
{
|
||||
_ = Throw.IfNull(messages);
|
||||
var inputMessages = Throw.IfNull(messages) as IReadOnlyCollection<ChatMessage> ?? messages.ToList();
|
||||
|
||||
A2AAgentSession typedSession = await this.GetA2ASessionAsync(session, options, cancellationToken).ConfigureAwait(false);
|
||||
|
||||
@@ -153,7 +153,7 @@ public sealed class A2AAgent : AIAgent
|
||||
|
||||
ConfiguredCancelableAsyncEnumerable<StreamResponse> streamEvents;
|
||||
|
||||
if (GetContinuationToken(messages, options) is { } token)
|
||||
if (GetContinuationToken(inputMessages, options) is { } token)
|
||||
{
|
||||
streamEvents = this.SubscribeToTaskWithFallbackAsync(token.TaskId, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
@@ -161,7 +161,7 @@ public sealed class A2AAgent : AIAgent
|
||||
{
|
||||
SendMessageRequest sendParams = new()
|
||||
{
|
||||
Message = CreateA2AMessage(typedSession, messages),
|
||||
Message = CreateA2AMessage(typedSession, inputMessages),
|
||||
Metadata = options?.AdditionalProperties?.ToA2AMetadata()
|
||||
};
|
||||
|
||||
@@ -172,6 +172,7 @@ public sealed class A2AAgent : AIAgent
|
||||
|
||||
string? contextId = null;
|
||||
string? taskId = null;
|
||||
TaskState? taskState = null;
|
||||
|
||||
await foreach (var streamResponse in streamEvents)
|
||||
{
|
||||
@@ -187,6 +188,7 @@ public sealed class A2AAgent : AIAgent
|
||||
var task = streamResponse.Task!;
|
||||
contextId = task.ContextId;
|
||||
taskId = task.Id;
|
||||
taskState = task.Status.State;
|
||||
yield return this.ConvertToAgentResponseUpdate(task);
|
||||
break;
|
||||
|
||||
@@ -194,6 +196,7 @@ public sealed class A2AAgent : AIAgent
|
||||
var statusUpdate = streamResponse.StatusUpdate!;
|
||||
contextId = statusUpdate.ContextId;
|
||||
taskId = statusUpdate.TaskId;
|
||||
taskState = statusUpdate.Status.State;
|
||||
yield return this.ConvertToAgentResponseUpdate(statusUpdate);
|
||||
break;
|
||||
|
||||
@@ -209,7 +212,7 @@ public sealed class A2AAgent : AIAgent
|
||||
}
|
||||
}
|
||||
|
||||
UpdateSession(typedSession, contextId, taskId);
|
||||
UpdateSession(typedSession, contextId, taskId, taskState);
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
@@ -317,7 +320,7 @@ public sealed class A2AAgent : AIAgent
|
||||
}
|
||||
}
|
||||
|
||||
private static void UpdateSession(A2AAgentSession? session, string? contextId, string? taskId = null)
|
||||
private static void UpdateSession(A2AAgentSession? session, string? contextId, string? taskId = null, TaskState? taskState = null)
|
||||
{
|
||||
if (session is null)
|
||||
{
|
||||
@@ -335,9 +338,10 @@ public sealed class A2AAgent : AIAgent
|
||||
// Assign a server-generated context Id to the session if it's not already set.
|
||||
session.ContextId ??= contextId;
|
||||
session.TaskId = taskId;
|
||||
session.TaskState = taskState;
|
||||
}
|
||||
|
||||
private static Message CreateA2AMessage(A2AAgentSession typedSession, IEnumerable<ChatMessage> messages)
|
||||
private static Message CreateA2AMessage(A2AAgentSession typedSession, IReadOnlyCollection<ChatMessage> messages)
|
||||
{
|
||||
var a2aMessage = messages.ToA2AMessage();
|
||||
|
||||
@@ -345,9 +349,19 @@ public sealed class A2AAgent : AIAgent
|
||||
// See: https://github.com/a2aproject/A2A/blob/main/docs/topics/life-of-a-task.md#group-related-interactions
|
||||
a2aMessage.ContextId = typedSession.ContextId;
|
||||
|
||||
// Link the message as a follow-up to an existing task, if any.
|
||||
// See: https://github.com/a2aproject/A2A/blob/main/docs/topics/life-of-a-task.md#task-refinements
|
||||
a2aMessage.ReferenceTaskIds = typedSession.TaskId is null ? null : [typedSession.TaskId];
|
||||
if (typedSession.TaskState == TaskState.InputRequired)
|
||||
{
|
||||
// If the session indicates the task is waiting for user input,
|
||||
// link the response to the existing task so it is treated as input
|
||||
// for that task.
|
||||
a2aMessage.TaskId = typedSession.TaskId;
|
||||
}
|
||||
else
|
||||
{
|
||||
// Link the message as a follow-up to an existing task, if any.
|
||||
// See: https://github.com/a2aproject/A2A/blob/main/docs/topics/life-of-a-task.md#task-refinements
|
||||
a2aMessage.ReferenceTaskIds = typedSession.TaskId is not null ? [typedSession.TaskId] : null;
|
||||
}
|
||||
|
||||
return a2aMessage;
|
||||
}
|
||||
@@ -444,6 +458,7 @@ public sealed class A2AAgent : AIAgent
|
||||
Role = ChatRole.Assistant,
|
||||
FinishReason = MapTaskStateToFinishReason(statusUpdateEvent.Status.State),
|
||||
AdditionalProperties = statusUpdateEvent.Metadata?.ToAdditionalProperties() ?? [],
|
||||
Contents = statusUpdateEvent.Status.GetUserInputRequests(),
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -5,6 +5,8 @@ using System.Diagnostics;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
|
||||
using TaskState = A2A.TaskState;
|
||||
|
||||
namespace Microsoft.Agents.AI.A2A;
|
||||
|
||||
/// <summary>
|
||||
@@ -18,10 +20,11 @@ public sealed class A2AAgentSession : AgentSession
|
||||
}
|
||||
|
||||
[JsonConstructor]
|
||||
internal A2AAgentSession(string? contextId, string? taskId, AgentSessionStateBag? stateBag) : base(stateBag ?? new())
|
||||
internal A2AAgentSession(string? contextId, string? taskId, TaskState? taskState, AgentSessionStateBag? stateBag) : base(stateBag ?? new())
|
||||
{
|
||||
this.ContextId = contextId;
|
||||
this.TaskId = taskId;
|
||||
this.TaskState = taskState;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -36,6 +39,12 @@ public sealed class A2AAgentSession : AgentSession
|
||||
[JsonPropertyName("taskId")]
|
||||
public string? TaskId { get; internal set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the state of the task the agent is currently working on.
|
||||
/// </summary>
|
||||
[JsonPropertyName("taskState")]
|
||||
public TaskState? TaskState { get; internal set; }
|
||||
|
||||
/// <inheritdoc/>
|
||||
internal JsonElement Serialize(JsonSerializerOptions? jsonSerializerOptions = null)
|
||||
{
|
||||
@@ -57,5 +66,5 @@ public sealed class A2AAgentSession : AgentSession
|
||||
|
||||
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
|
||||
private string DebuggerDisplay =>
|
||||
$"ContextId = {this.ContextId}, TaskId = {this.TaskId}, StateBag Count = {this.StateBag.Count}";
|
||||
$"ContextId = {this.ContextId}, TaskId = {this.TaskId}, TaskState = {this.TaskState}, StateBag Count = {this.StateBag.Count}";
|
||||
}
|
||||
|
||||
@@ -13,7 +13,7 @@ internal static class A2AAIContentExtensions
|
||||
/// <summary>
|
||||
/// Converts a collection of <see cref="AIContent"/> to a list of <see cref="Part"/> objects.
|
||||
/// </summary>
|
||||
/// <param name="contents">The collection of AI contents to convert.</param>"
|
||||
/// <param name="contents">The collection of AI contents to convert.</param>
|
||||
/// <returns>The list of A2A <see cref="Part"/> objects.</returns>
|
||||
internal static List<Part>? ToParts(this IEnumerable<AIContent> contents)
|
||||
{
|
||||
@@ -21,8 +21,7 @@ internal static class A2AAIContentExtensions
|
||||
|
||||
foreach (var content in contents)
|
||||
{
|
||||
var part = content.ToPart();
|
||||
if (part is not null)
|
||||
if (content.ToPart() is { } part)
|
||||
{
|
||||
(parts ??= []).Add(part);
|
||||
}
|
||||
|
||||
@@ -17,7 +17,7 @@ internal static class A2AAgentTaskExtensions
|
||||
|
||||
List<ChatMessage>? messages = null;
|
||||
|
||||
if (agentTask?.Artifacts is { Count: > 0 })
|
||||
if (agentTask.Artifacts is { Count: > 0 })
|
||||
{
|
||||
foreach (var artifact in agentTask.Artifacts)
|
||||
{
|
||||
@@ -25,6 +25,14 @@ internal static class A2AAgentTaskExtensions
|
||||
}
|
||||
}
|
||||
|
||||
if (agentTask.Status?.GetUserInputRequests() is { } userInputRequests)
|
||||
{
|
||||
(messages ??= []).Add(new(ChatRole.Assistant, userInputRequests)
|
||||
{
|
||||
RawRepresentation = agentTask.Status,
|
||||
});
|
||||
}
|
||||
|
||||
return messages;
|
||||
}
|
||||
|
||||
@@ -42,6 +50,11 @@ internal static class A2AAgentTaskExtensions
|
||||
}
|
||||
}
|
||||
|
||||
if (agentTask.Status?.GetUserInputRequests() is { } userInputRequests)
|
||||
{
|
||||
(aiContents ??= []).AddRange(userInputRequests);
|
||||
}
|
||||
|
||||
return aiContents;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
// Copyright (c) Microsoft. All rights reserved.
|
||||
|
||||
using System.Collections.Generic;
|
||||
using Microsoft.Extensions.AI;
|
||||
using Microsoft.Shared.Diagnostics;
|
||||
|
||||
namespace A2A;
|
||||
|
||||
/// <summary>
|
||||
/// Extension methods for the <see cref="TaskStatus"/> class.
|
||||
/// </summary>
|
||||
internal static class AgentTaskStatusExtensions
|
||||
{
|
||||
internal static IList<AIContent>? GetUserInputRequests(this TaskStatus status)
|
||||
{
|
||||
_ = Throw.IfNull(status);
|
||||
|
||||
List<AIContent>? contents = null;
|
||||
|
||||
if (status.Message is null || status.State is not TaskState.InputRequired)
|
||||
{
|
||||
return contents;
|
||||
}
|
||||
|
||||
foreach (var part in status.Message.Parts)
|
||||
{
|
||||
var aiContent = part.ToAIContent();
|
||||
aiContent.RawRepresentation = part;
|
||||
aiContent.AdditionalProperties = part.Metadata.ToAdditionalProperties();
|
||||
(contents ??= []).Add(aiContent);
|
||||
}
|
||||
|
||||
return contents;
|
||||
}
|
||||
}
|
||||
@@ -105,7 +105,7 @@ public sealed class InMemoryChatHistoryProvider : ChatHistoryProvider
|
||||
State state = this._sessionState.GetOrInitializeState(context.Session);
|
||||
|
||||
// Add request and response messages to the provider
|
||||
var allNewMessages = context.RequestMessages.Concat(context.ResponseMessages ?? []);
|
||||
var allNewMessages = (context.RequestMessages ?? []).Concat(context.ResponseMessages ?? []);
|
||||
state.Messages.AddRange(allNewMessages);
|
||||
|
||||
if (this.ReducerTriggerEvent is InMemoryChatHistoryProviderOptions.ChatReducerTriggerEvent.AfterMessageAdded && this.ChatReducer is not null)
|
||||
|
||||
@@ -0,0 +1,106 @@
|
||||
// Copyright (c) Microsoft. All rights reserved.
|
||||
|
||||
using System.Net;
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
using Microsoft.Extensions.Options;
|
||||
using Microsoft.Net.Http.Headers;
|
||||
|
||||
namespace Microsoft.Agents.AI.DevUI;
|
||||
|
||||
/// <summary>
|
||||
/// Endpoint filter that enforces the DevUI security posture: loopback-only
|
||||
/// access by default, plus optional bearer-token authentication.
|
||||
/// </summary>
|
||||
internal sealed class DevUIAuthFilter : IEndpointFilter
|
||||
{
|
||||
private const string BearerScheme = "Bearer";
|
||||
|
||||
private readonly DevUIOptions _options;
|
||||
private readonly byte[]? _expectedTokenBytes;
|
||||
private readonly ILogger<DevUIAuthFilter> _logger;
|
||||
|
||||
/// <summary>
|
||||
/// Gets a value indicating whether a bearer token is required by this filter
|
||||
/// (either via <see cref="DevUIOptions.AuthToken"/> or the
|
||||
/// <c>DEVUI_AUTH_TOKEN</c> environment variable).
|
||||
/// </summary>
|
||||
public bool TokenRequired => this._expectedTokenBytes is { Length: > 0 };
|
||||
|
||||
public DevUIAuthFilter(IOptions<DevUIOptions> options, ILogger<DevUIAuthFilter> logger)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(options);
|
||||
ArgumentNullException.ThrowIfNull(logger);
|
||||
this._options = options.Value;
|
||||
this._logger = logger;
|
||||
|
||||
var configuredToken = !string.IsNullOrEmpty(this._options.AuthToken)
|
||||
? this._options.AuthToken
|
||||
: Environment.GetEnvironmentVariable(DevUIOptions.AuthTokenEnvironmentVariable);
|
||||
|
||||
this._expectedTokenBytes = !string.IsNullOrEmpty(configuredToken)
|
||||
? Encoding.UTF8.GetBytes(configuredToken)
|
||||
: null;
|
||||
}
|
||||
|
||||
public async ValueTask<object?> InvokeAsync(EndpointFilterInvocationContext context, EndpointFilterDelegate next)
|
||||
{
|
||||
var httpContext = context.HttpContext;
|
||||
var remoteIp = httpContext.Connection.RemoteIpAddress;
|
||||
var isLoopback = remoteIp is not null && IPAddress.IsLoopback(remoteIp);
|
||||
|
||||
if (!isLoopback && !this._options.AllowRemoteAccess)
|
||||
{
|
||||
this._logger.LogWarning(
|
||||
"Rejected non-loopback DevUI request from {RemoteIp}. Set DevUIOptions.AllowRemoteAccess to permit remote callers.",
|
||||
remoteIp);
|
||||
return Results.Problem(
|
||||
statusCode: StatusCodes.Status403Forbidden,
|
||||
title: "DevUI access denied",
|
||||
detail: "DevUI is restricted to loopback callers by default. Enable AllowRemoteAccess to permit remote access.");
|
||||
}
|
||||
|
||||
if (this._expectedTokenBytes is { Length: > 0 } expected && !TokenIsValid(httpContext.Request, expected))
|
||||
{
|
||||
httpContext.Response.Headers[HeaderNames.WWWAuthenticate] = BearerScheme;
|
||||
return Results.Problem(
|
||||
statusCode: StatusCodes.Status401Unauthorized,
|
||||
title: "DevUI authentication required",
|
||||
detail: "Provide a valid bearer token via the Authorization header.");
|
||||
}
|
||||
|
||||
return await next(context).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
private static bool TokenIsValid(HttpRequest request, byte[] expected)
|
||||
{
|
||||
if (!request.Headers.TryGetValue(HeaderNames.Authorization, out var headerValues))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
foreach (var header in headerValues)
|
||||
{
|
||||
if (string.IsNullOrEmpty(header))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
const int PrefixLength = 7; // "Bearer "
|
||||
if (header.Length <= PrefixLength ||
|
||||
!header.StartsWith(BearerScheme, StringComparison.OrdinalIgnoreCase) ||
|
||||
header[BearerScheme.Length] != ' ')
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
var presented = Encoding.UTF8.GetBytes(header.AsSpan(PrefixLength).Trim().ToString());
|
||||
if (CryptographicOperations.FixedTimeEquals(presented, expected))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
// Copyright (c) Microsoft. All rights reserved.
|
||||
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using Microsoft.Extensions.Options;
|
||||
|
||||
namespace Microsoft.Agents.AI.DevUI;
|
||||
|
||||
@@ -13,12 +14,19 @@ public static class DevUIExtensions
|
||||
/// Maps an endpoint that serves the DevUI from the '/devui' path.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// <para>
|
||||
/// DevUI requires the OpenAI Responses and Conversations services to be registered with
|
||||
/// <see cref="MicrosoftAgentAIHostingOpenAIServiceCollectionExtensions.AddOpenAIResponses(IServiceCollection)"/> and
|
||||
/// <see cref="MicrosoftAgentAIHostingOpenAIServiceCollectionExtensions.AddOpenAIConversations(IServiceCollection)"/>,
|
||||
/// and the corresponding endpoints to be mapped using
|
||||
/// <see cref="MicrosoftAgentAIHostingOpenAIEndpointRouteBuilderExtensions.MapOpenAIResponses(IEndpointRouteBuilder)"/> and
|
||||
/// <see cref="MicrosoftAgentAIHostingOpenAIEndpointRouteBuilderExtensions.MapOpenAIConversations(IEndpointRouteBuilder)"/>.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// DevUI is restricted to loopback callers unless
|
||||
/// <see cref="DevUIOptions.AllowRemoteAccess"/> is set. See <see cref="DevUIOptions"/>
|
||||
/// for the available authentication and authorization hooks.
|
||||
/// </para>
|
||||
/// </remarks>
|
||||
/// <param name="endpoints">The <see cref="IEndpointRouteBuilder"/> to add the endpoint to.</param>
|
||||
/// <returns>A <see cref="IEndpointConventionBuilder"/> that can be used to add authorization or other endpoint configuration.</returns>
|
||||
@@ -30,11 +38,29 @@ public static class DevUIExtensions
|
||||
public static IEndpointConventionBuilder MapDevUI(
|
||||
this IEndpointRouteBuilder endpoints)
|
||||
{
|
||||
var group = endpoints.MapGroup("");
|
||||
group.MapDevUI(pattern: "/devui");
|
||||
group.MapMeta();
|
||||
group.MapEntities();
|
||||
return group;
|
||||
ArgumentNullException.ThrowIfNull(endpoints);
|
||||
|
||||
var authFilter = endpoints.ServiceProvider.GetRequiredService<DevUIAuthFilter>();
|
||||
var options = endpoints.ServiceProvider.GetRequiredService<IOptions<DevUIOptions>>().Value;
|
||||
var startupLogger = endpoints.ServiceProvider.GetRequiredService<ILogger<DevUIAuthFilter>>();
|
||||
|
||||
WarnIfInsecurelyExposed(startupLogger, options);
|
||||
|
||||
// /meta must remain reachable without authentication so the frontend can
|
||||
// discover whether a bearer token is required before prompting for one.
|
||||
endpoints.MapMeta(authRequired: authFilter.TokenRequired);
|
||||
|
||||
var protectedGroup = endpoints.MapGroup("");
|
||||
|
||||
// Conventions must be applied before endpoints are added to the group so
|
||||
// they reliably attach to every protected DevUI endpoint.
|
||||
options.ConfigureEndpoints?.Invoke(protectedGroup);
|
||||
protectedGroup.AddEndpointFilter(authFilter);
|
||||
|
||||
protectedGroup.MapDevUI(pattern: "/devui");
|
||||
protectedGroup.MapEntities();
|
||||
|
||||
return protectedGroup;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -66,4 +92,18 @@ public static class DevUIExtensions
|
||||
.WithName($"DevUI at {cleanPattern}")
|
||||
.WithDescription("Interactive developer interface for Microsoft Agent Framework");
|
||||
}
|
||||
|
||||
private static void WarnIfInsecurelyExposed(ILogger logger, DevUIOptions options)
|
||||
{
|
||||
var tokenConfigured = !string.IsNullOrEmpty(options.AuthToken)
|
||||
|| !string.IsNullOrEmpty(Environment.GetEnvironmentVariable(DevUIOptions.AuthTokenEnvironmentVariable));
|
||||
|
||||
if (options.AllowRemoteAccess && !tokenConfigured && options.ConfigureEndpoints is null)
|
||||
{
|
||||
logger.LogWarning(
|
||||
"DevUI is configured with AllowRemoteAccess=true and no authentication. " +
|
||||
"Set DevUIOptions.AuthToken, the {EnvVar} environment variable, or attach an authorization policy via ConfigureEndpoints.",
|
||||
DevUIOptions.AuthTokenEnvironmentVariable);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,59 @@
|
||||
// Copyright (c) Microsoft. All rights reserved.
|
||||
|
||||
namespace Microsoft.Agents.AI.DevUI;
|
||||
|
||||
/// <summary>
|
||||
/// Options that control the security posture of the DevUI HTTP surface.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// DevUI exposes agent metadata that is sensitive in production contexts:
|
||||
/// system instructions, tool definitions, model identifiers, and workflow
|
||||
/// structure. By default, DevUI rejects any request whose remote endpoint
|
||||
/// is not a loopback address. Hosts that intentionally expose DevUI on a
|
||||
/// non-loopback interface must opt in via <see cref="AllowRemoteAccess"/>
|
||||
/// and should also configure <see cref="AuthToken"/> or
|
||||
/// <see cref="ConfigureEndpoints"/> to attach an authorization policy.
|
||||
/// </remarks>
|
||||
public sealed class DevUIOptions
|
||||
{
|
||||
/// <summary>
|
||||
/// Environment variable inspected for a default bearer token when
|
||||
/// <see cref="AuthToken"/> is not explicitly set.
|
||||
/// </summary>
|
||||
public const string AuthTokenEnvironmentVariable = "DEVUI_AUTH_TOKEN";
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets a value indicating whether DevUI may be served to
|
||||
/// non-loopback callers. Defaults to <see langword="false"/>.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// When <see langword="false"/>, any request whose
|
||||
/// <see cref="ConnectionInfo.RemoteIpAddress"/> is
|
||||
/// not a loopback address (or is missing) is rejected with HTTP 403 before
|
||||
/// reaching the DevUI handlers. Enable only when the host is responsible
|
||||
/// for fronting DevUI with its own authentication, network policy, or both.
|
||||
/// </remarks>
|
||||
public bool AllowRemoteAccess { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets a shared bearer token required on every DevUI request.
|
||||
/// When <see langword="null"/> or empty, the value of the
|
||||
/// <c>DEVUI_AUTH_TOKEN</c> environment variable is used instead.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// When a token is configured, requests must include the header
|
||||
/// <c>Authorization: Bearer <token></c>. Comparison is performed
|
||||
/// in constant time. This is a convenience for development scenarios.
|
||||
/// Production hosts should prefer a real ASP.NET Core authentication
|
||||
/// scheme attached via <see cref="ConfigureEndpoints"/>.
|
||||
/// </remarks>
|
||||
public string? AuthToken { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets a callback invoked with the DevUI endpoint group so the
|
||||
/// host can attach authorization, rate limiting, or other endpoint
|
||||
/// conventions (for example
|
||||
/// <c>group.RequireAuthorization("DevUIPolicy")</c>).
|
||||
/// </summary>
|
||||
public Action<IEndpointConventionBuilder>? ConfigureEndpoints { get; set; }
|
||||
}
|
||||
@@ -1,5 +1,7 @@
|
||||
// Copyright (c) Microsoft. All rights reserved.
|
||||
|
||||
using Microsoft.Agents.AI.DevUI;
|
||||
|
||||
namespace Microsoft.Extensions.Hosting;
|
||||
|
||||
/// <summary>
|
||||
@@ -13,10 +15,19 @@ public static class MicrosoftAgentAIDevUIHostApplicationBuilderExtensions
|
||||
/// <param name="builder">The <see cref="IHostApplicationBuilder"/> to configure.</param>
|
||||
/// <returns>The <see cref="IHostApplicationBuilder"/> for method chaining.</returns>
|
||||
public static IHostApplicationBuilder AddDevUI(this IHostApplicationBuilder builder)
|
||||
=> AddDevUI(builder, configure: null);
|
||||
|
||||
/// <summary>
|
||||
/// Adds DevUI services to the host application builder.
|
||||
/// </summary>
|
||||
/// <param name="builder">The <see cref="IHostApplicationBuilder"/> to configure.</param>
|
||||
/// <param name="configure">Optional callback used to configure <see cref="DevUIOptions"/>.</param>
|
||||
/// <returns>The <see cref="IHostApplicationBuilder"/> for method chaining.</returns>
|
||||
public static IHostApplicationBuilder AddDevUI(this IHostApplicationBuilder builder, Action<DevUIOptions>? configure)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(builder);
|
||||
|
||||
builder.Services.AddDevUI();
|
||||
builder.Services.AddDevUI(configure);
|
||||
|
||||
return builder;
|
||||
}
|
||||
|
||||
@@ -13,6 +13,7 @@ internal static class MetaApiExtensions
|
||||
/// Maps the HTTP API endpoint for retrieving server metadata.
|
||||
/// </summary>
|
||||
/// <param name="endpoints">The <see cref="IEndpointRouteBuilder"/> to add the route to.</param>
|
||||
/// <param name="authRequired">Value reported via <c>auth_required</c> in the meta response so the frontend can decide whether to prompt for a bearer token.</param>
|
||||
/// <returns>The <see cref="IEndpointConventionBuilder"/> for method chaining.</returns>
|
||||
/// <remarks>
|
||||
/// This extension method registers the following endpoint:
|
||||
@@ -22,16 +23,16 @@ internal static class MetaApiExtensions
|
||||
/// The endpoint is compatible with the Python DevUI frontend and provides essential
|
||||
/// configuration information needed for proper frontend initialization.
|
||||
/// </remarks>
|
||||
public static IEndpointConventionBuilder MapMeta(this IEndpointRouteBuilder endpoints)
|
||||
public static IEndpointConventionBuilder MapMeta(this IEndpointRouteBuilder endpoints, bool authRequired = false)
|
||||
{
|
||||
return endpoints.MapGet("/meta", GetMeta)
|
||||
return endpoints.MapGet("/meta", () => GetMeta(authRequired))
|
||||
.WithName("GetMeta")
|
||||
.WithSummary("Get server metadata and configuration")
|
||||
.WithDescription("Returns server metadata including UI mode, version, framework identifier, capabilities, and authentication requirements. Used by the frontend for initialization and feature detection.")
|
||||
.Produces<MetaResponse>(StatusCodes.Status200OK, contentType: "application/json");
|
||||
}
|
||||
|
||||
private static IResult GetMeta()
|
||||
private static IResult GetMeta(bool authRequired)
|
||||
{
|
||||
// TODO: Consider making these configurable via IOptions<DevUIOptions>
|
||||
// For now, using sensible defaults that match Python DevUI behavior
|
||||
@@ -53,7 +54,7 @@ internal static class MetaApiExtensions
|
||||
// Deployment capability - not currently supported in .NET DevUI
|
||||
["deployment"] = false
|
||||
},
|
||||
AuthRequired = false // Could be made configurable based on authentication middleware
|
||||
AuthRequired = authRequired
|
||||
};
|
||||
|
||||
return Results.Json(meta, EntitiesJsonContext.Default.MetaResponse);
|
||||
|
||||
@@ -2,6 +2,9 @@
|
||||
|
||||
This package provides a web interface for testing and debugging AI agents during development.
|
||||
|
||||
> [!WARNING]
|
||||
> DevUI is intended for development only. Its endpoints surface agent system instructions, tool definitions, model identifiers, and workflow structure. Do not expose DevUI to untrusted callers. By default, DevUI rejects any request whose remote endpoint is not a loopback address; see [Security](#security) below for the available options.
|
||||
|
||||
## Installation
|
||||
|
||||
```bash
|
||||
@@ -48,3 +51,30 @@ if (builder.Environment.IsDevelopment())
|
||||
|
||||
app.Run();
|
||||
```
|
||||
|
||||
## Security
|
||||
|
||||
DevUI exposes `/v1/entities` and `/v1/entities/{id}/info`, which return agent metadata including the system prompt (`ChatClientAgent.Instructions`). To prevent accidental disclosure, the DevUI route group is wrapped in a small endpoint filter that:
|
||||
|
||||
- Rejects requests from any non-loopback `RemoteIpAddress` with HTTP 403 by default.
|
||||
- Optionally requires a shared bearer token on every request.
|
||||
|
||||
Configure via `DevUIOptions`:
|
||||
|
||||
```csharp
|
||||
builder.AddDevUI(options =>
|
||||
{
|
||||
// Allow non-loopback callers. Set this only when the host fronts DevUI with
|
||||
// its own authentication or network policy.
|
||||
options.AllowRemoteAccess = true;
|
||||
|
||||
// Optional: require Authorization: Bearer <token> on every request.
|
||||
// Falls back to the DEVUI_AUTH_TOKEN environment variable when null.
|
||||
options.AuthToken = builder.Configuration["DevUI:AuthToken"];
|
||||
|
||||
// Optional: attach a real authorization policy or rate limiting.
|
||||
options.ConfigureEndpoints = group => group.RequireAuthorization("DevUIPolicy");
|
||||
});
|
||||
```
|
||||
|
||||
The bundled bearer-token check uses constant-time comparison and is intended as a convenience for development scenarios. Production hosts should prefer a real ASP.NET Core authentication scheme via `ConfigureEndpoints`.
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
// Copyright (c) Microsoft. All rights reserved.
|
||||
|
||||
using Microsoft.Agents.AI;
|
||||
using Microsoft.Agents.AI.DevUI;
|
||||
using Microsoft.Agents.AI.Workflows;
|
||||
using Microsoft.Shared.Diagnostics;
|
||||
|
||||
@@ -17,9 +18,26 @@ public static class MicrosoftAgentAIDevUIServiceCollectionsExtensions
|
||||
/// <param name="services">The <see cref="IServiceCollection"/> to configure.</param>
|
||||
/// <returns>The <see cref="IServiceCollection"/> for method chaining.</returns>
|
||||
public static IServiceCollection AddDevUI(this IServiceCollection services)
|
||||
=> AddDevUI(services, configure: null);
|
||||
|
||||
/// <summary>
|
||||
/// Adds services required for DevUI integration.
|
||||
/// </summary>
|
||||
/// <param name="services">The <see cref="IServiceCollection"/> to configure.</param>
|
||||
/// <param name="configure">Optional callback used to configure <see cref="DevUIOptions"/>.</param>
|
||||
/// <returns>The <see cref="IServiceCollection"/> for method chaining.</returns>
|
||||
public static IServiceCollection AddDevUI(this IServiceCollection services, Action<DevUIOptions>? configure)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(services);
|
||||
|
||||
var optionsBuilder = services.AddOptions<DevUIOptions>();
|
||||
if (configure is not null)
|
||||
{
|
||||
optionsBuilder.Configure(configure);
|
||||
}
|
||||
|
||||
services.AddSingleton<DevUIAuthFilter>();
|
||||
|
||||
// a factory that tries to construct an AIAgent from Workflow,
|
||||
// even if workflow was not explicitly registered as an AIAgent.
|
||||
|
||||
|
||||
@@ -1,56 +0,0 @@
|
||||
// Copyright (c) Microsoft. All rights reserved.
|
||||
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.Agents.AI.Foundry.Hosting;
|
||||
using Microsoft.Extensions.AI;
|
||||
using Microsoft.Shared.DiagnosticIds;
|
||||
using Microsoft.Shared.Diagnostics;
|
||||
|
||||
#pragma warning disable OPENAI001
|
||||
#pragma warning disable AAIP001 // AgentToolboxes is experimental in Azure.AI.Projects.Agents
|
||||
|
||||
namespace Azure.AI.Projects;
|
||||
|
||||
/// <summary>
|
||||
/// Provides extension methods on <see cref="AIProjectClient"/> for fetching
|
||||
/// Foundry toolbox definitions as server-side tools.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Provides a single call on the project client to retrieve tools ready for use
|
||||
/// with <c>AsAIAgent(model, instructions, tools: ...)</c>.
|
||||
/// </remarks>
|
||||
[Experimental(DiagnosticIds.Experiments.AIOpenAIResponses)]
|
||||
public static class AIProjectClientToolboxExtensions
|
||||
{
|
||||
/// <summary>
|
||||
/// Fetches a toolbox from the Foundry project and returns its tools as <see cref="AITool"/> instances
|
||||
/// ready for use as server-side tools in the Responses API.
|
||||
/// </summary>
|
||||
/// <param name="projectClient">The <see cref="AIProjectClient"/> to use. Cannot be <see langword="null"/>.</param>
|
||||
/// <param name="name">The name of the toolbox to fetch.</param>
|
||||
/// <param name="version">
|
||||
/// The specific toolbox version to fetch. When <see langword="null"/>, the toolbox's
|
||||
/// default version is resolved automatically.
|
||||
/// </param>
|
||||
/// <param name="cancellationToken">A token to monitor for cancellation requests.</param>
|
||||
/// <returns>A read-only list of <see cref="AITool"/> instances from the toolbox.</returns>
|
||||
/// <exception cref="System.ArgumentNullException">
|
||||
/// Thrown when <paramref name="projectClient"/> or <paramref name="name"/> is <see langword="null"/>.
|
||||
/// </exception>
|
||||
public static async Task<IReadOnlyList<AITool>> GetToolboxToolsAsync(
|
||||
this AIProjectClient projectClient,
|
||||
string name,
|
||||
string? version = null,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
Throw.IfNull(projectClient);
|
||||
Throw.IfNullOrWhitespace(name);
|
||||
|
||||
var toolboxClient = projectClient.AgentAdministrationClient.GetAgentToolboxes();
|
||||
var toolboxVersion = await FoundryToolbox.GetToolboxVersionCoreAsync(toolboxClient, name, version, cancellationToken).ConfigureAwait(false);
|
||||
return toolboxVersion.ToAITools();
|
||||
}
|
||||
}
|
||||
@@ -1,220 +0,0 @@
|
||||
// Copyright (c) Microsoft. All rights reserved.
|
||||
|
||||
using System;
|
||||
using System.ClientModel;
|
||||
using System.ClientModel.Primitives;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
using System.Text.Json.Nodes;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using Azure.AI.Projects.Agents;
|
||||
using Microsoft.Extensions.AI;
|
||||
using Microsoft.Shared.DiagnosticIds;
|
||||
using Microsoft.Shared.Diagnostics;
|
||||
using OpenAI.Responses;
|
||||
|
||||
#pragma warning disable OPENAI001
|
||||
#pragma warning disable AAIP001 // AgentToolboxes is experimental in Azure.AI.Projects.Agents
|
||||
#pragma warning disable IL2026 // ModelReaderWriter.Read<ResponseTool> uses reflection; suppressed for Azure SDK model types.
|
||||
#pragma warning disable IL3050 // ModelReaderWriter.Read<ResponseTool> requires dynamic code; suppressed for Azure SDK model types.
|
||||
|
||||
namespace Microsoft.Agents.AI.Foundry.Hosting;
|
||||
|
||||
/// <summary>
|
||||
/// Provides methods for fetching Foundry toolbox definitions and converting their tools
|
||||
/// to <see cref="AITool"/> instances for use as server-side tools in the Responses API.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// <para>
|
||||
/// When tools from a toolbox are passed to a Foundry agent (e.g. via <c>AsAIAgent(model, instructions, tools: ...)</c>),
|
||||
/// they are sent as server-side tool definitions in the Responses API request. The Foundry platform
|
||||
/// handles tool execution — the agent process does not invoke tools locally.
|
||||
/// </para>
|
||||
/// </remarks>
|
||||
[Experimental(DiagnosticIds.Experiments.AIOpenAIResponses)]
|
||||
public static class FoundryToolbox
|
||||
{
|
||||
/// <summary>
|
||||
/// Fetches a toolbox version from the Foundry project and returns the raw SDK <see cref="ToolboxVersion"/>.
|
||||
/// </summary>
|
||||
/// <param name="projectEndpoint">The Foundry project endpoint URI.</param>
|
||||
/// <param name="credential">The authentication credential used to access the Foundry project.</param>
|
||||
/// <param name="name">The name of the toolbox to fetch.</param>
|
||||
/// <param name="version">
|
||||
/// The specific toolbox version to fetch. When <see langword="null"/>, the toolbox's
|
||||
/// default version is resolved automatically (requires an additional API call).
|
||||
/// </param>
|
||||
/// <param name="cancellationToken">A token to monitor for cancellation requests.</param>
|
||||
/// <returns>The <see cref="ToolboxVersion"/> containing tool definitions.</returns>
|
||||
/// <exception cref="ArgumentNullException">
|
||||
/// Thrown when <paramref name="projectEndpoint"/>, <paramref name="credential"/>, or <paramref name="name"/> is <see langword="null"/>.
|
||||
/// </exception>
|
||||
/// <exception cref="ClientResultException">Thrown when the Foundry project API returns an error.</exception>
|
||||
public static async Task<ToolboxVersion> GetToolboxVersionAsync(
|
||||
Uri projectEndpoint,
|
||||
AuthenticationTokenProvider credential,
|
||||
string name,
|
||||
string? version = null,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
Throw.IfNull(projectEndpoint);
|
||||
Throw.IfNull(credential);
|
||||
Throw.IfNullOrWhitespace(name);
|
||||
|
||||
var toolboxClient = CreateToolboxClient(projectEndpoint, credential);
|
||||
return await GetToolboxVersionCoreAsync(toolboxClient, name, version, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Fetches a toolbox from the Foundry project and returns its tools as <see cref="AITool"/> instances
|
||||
/// ready for use as server-side tools in the Responses API.
|
||||
/// </summary>
|
||||
/// <param name="projectEndpoint">The Foundry project endpoint URI.</param>
|
||||
/// <param name="credential">The authentication credential used to access the Foundry project.</param>
|
||||
/// <param name="name">The name of the toolbox to fetch.</param>
|
||||
/// <param name="version">
|
||||
/// The specific toolbox version to fetch. When <see langword="null"/>, the toolbox's
|
||||
/// default version is resolved automatically.
|
||||
/// </param>
|
||||
/// <param name="cancellationToken">A token to monitor for cancellation requests.</param>
|
||||
/// <returns>A read-only list of <see cref="AITool"/> instances from the toolbox.</returns>
|
||||
/// <exception cref="ArgumentNullException">
|
||||
/// Thrown when <paramref name="projectEndpoint"/>, <paramref name="credential"/>, or <paramref name="name"/> is <see langword="null"/>.
|
||||
/// </exception>
|
||||
/// <exception cref="ClientResultException">Thrown when the Foundry project API returns an error.</exception>
|
||||
public static async Task<IReadOnlyList<AITool>> GetToolsAsync(
|
||||
Uri projectEndpoint,
|
||||
AuthenticationTokenProvider credential,
|
||||
string name,
|
||||
string? version = null,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
var toolboxVersion = await GetToolboxVersionAsync(projectEndpoint, credential, name, version, cancellationToken).ConfigureAwait(false);
|
||||
return toolboxVersion.ToAITools();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Converts the tools in a <see cref="ToolboxVersion"/> to <see cref="AITool"/> instances
|
||||
/// suitable for use as server-side tools in the Responses API.
|
||||
/// </summary>
|
||||
/// <param name="toolboxVersion">The toolbox version whose tools to convert.</param>
|
||||
/// <returns>A read-only list of <see cref="AITool"/> instances.</returns>
|
||||
/// <exception cref="ArgumentNullException">Thrown when <paramref name="toolboxVersion"/> is <see langword="null"/>.</exception>
|
||||
/// <remarks>
|
||||
/// <para>
|
||||
/// Each <see cref="ProjectsAgentTool"/> in the toolbox is cast to <see cref="ResponseTool"/>
|
||||
/// and converted via <c>AsAITool()</c>. Non-function hosted tools (MCP, web_search,
|
||||
/// code_interpreter, etc.) are included as server-side tool definitions — the Foundry
|
||||
/// platform handles their execution.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// Non-function tools are sanitized to remove decoration fields (<c>name</c>, <c>description</c>)
|
||||
/// that the toolbox API returns but the Responses API rejects.
|
||||
/// </para>
|
||||
/// </remarks>
|
||||
public static IReadOnlyList<AITool> ToAITools(this ToolboxVersion toolboxVersion)
|
||||
{
|
||||
Throw.IfNull(toolboxVersion);
|
||||
|
||||
if (toolboxVersion.Tools?.Any() != true)
|
||||
{
|
||||
return [];
|
||||
}
|
||||
|
||||
return toolboxVersion.Tools
|
||||
.Select(SanitizeAndConvert)
|
||||
.ToList();
|
||||
}
|
||||
|
||||
#region Internal helpers (visible to unit tests via InternalsVisibleTo)
|
||||
|
||||
/// <summary>
|
||||
/// Sanitizes a <see cref="ProjectsAgentTool"/> by removing decoration fields that the
|
||||
/// toolbox API returns but the Responses API rejects, then converts to <see cref="AITool"/>.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// The Azure AI Projects toolbox API may return <c>name</c> and <c>description</c> on
|
||||
/// hosted tool objects (MCP, code_interpreter, file_search, etc.). The Responses API
|
||||
/// rejects at least <c>name</c> with "Unknown parameter: 'tools[0].name'". We strip
|
||||
/// these decoration fields for non-function tools. Function tools keep them since
|
||||
/// <c>name</c> and <c>description</c> are expected parts of the function schema.
|
||||
/// </remarks>
|
||||
internal static AITool SanitizeAndConvert(ProjectsAgentTool tool)
|
||||
{
|
||||
var toolJson = ModelReaderWriter.Write(tool, new ModelReaderWriterOptions("J"));
|
||||
var node = JsonNode.Parse(toolJson.ToString());
|
||||
if (node is not JsonObject obj)
|
||||
{
|
||||
return ((ResponseTool)tool).AsAITool();
|
||||
}
|
||||
|
||||
var toolType = obj["type"]?.GetValue<string>();
|
||||
|
||||
// Function tools need name/description — don't strip
|
||||
if (toolType is "function" or "custom")
|
||||
{
|
||||
return ((ResponseTool)tool).AsAITool();
|
||||
}
|
||||
|
||||
// Strip decoration fields that the Responses API rejects
|
||||
bool modified = false;
|
||||
modified |= obj.Remove("name");
|
||||
modified |= obj.Remove("description");
|
||||
|
||||
if (!modified)
|
||||
{
|
||||
return ((ResponseTool)tool).AsAITool();
|
||||
}
|
||||
|
||||
var sanitizedJson = obj.ToJsonString();
|
||||
var sanitizedTool = ModelReaderWriter.Read<ResponseTool>(BinaryData.FromString(sanitizedJson))!;
|
||||
return sanitizedTool.AsAITool();
|
||||
}
|
||||
|
||||
internal static async Task<ToolboxVersion> GetToolboxVersionAsync(
|
||||
Uri projectEndpoint,
|
||||
AuthenticationTokenProvider credential,
|
||||
string name,
|
||||
string? version,
|
||||
AgentAdministrationClientOptions? clientOptions,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
Throw.IfNull(projectEndpoint);
|
||||
Throw.IfNull(credential);
|
||||
Throw.IfNullOrWhitespace(name);
|
||||
|
||||
var toolboxClient = CreateToolboxClient(projectEndpoint, credential, clientOptions);
|
||||
return await GetToolboxVersionCoreAsync(toolboxClient, name, version, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
internal static AgentToolboxes CreateToolboxClient(
|
||||
Uri projectEndpoint,
|
||||
AuthenticationTokenProvider credential,
|
||||
AgentAdministrationClientOptions? clientOptions = null)
|
||||
{
|
||||
clientOptions ??= new AgentAdministrationClientOptions();
|
||||
var adminClient = new AgentAdministrationClient(projectEndpoint, credential, clientOptions);
|
||||
return adminClient.GetAgentToolboxes();
|
||||
}
|
||||
|
||||
internal static async Task<ToolboxVersion> GetToolboxVersionCoreAsync(
|
||||
AgentToolboxes toolboxClient,
|
||||
string name,
|
||||
string? version,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
if (version is null)
|
||||
{
|
||||
var record = await toolboxClient.GetToolboxAsync(name, cancellationToken).ConfigureAwait(false);
|
||||
version = record.Value.DefaultVersion
|
||||
?? throw new InvalidOperationException($"Toolbox '{name}' does not have a default version. Specify an explicit version.");
|
||||
}
|
||||
|
||||
var result = await toolboxClient.GetToolboxVersionAsync(name, version, cancellationToken).ConfigureAwait(false);
|
||||
return result.Value;
|
||||
}
|
||||
|
||||
#endregion
|
||||
}
|
||||
+2
-2
@@ -1,4 +1,4 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFrameworks>$(TargetFrameworksCore)</TargetFrameworks>
|
||||
@@ -31,7 +31,7 @@
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Azure.AI.AgentServer.Responses" />
|
||||
<PackageReference Include="Azure.AI.Projects" VersionOverride="2.1.0-beta.1" />
|
||||
<PackageReference Include="Azure.AI.Projects" />
|
||||
<PackageReference Include="Azure.Identity" />
|
||||
<PackageReference Include="ModelContextProtocol" />
|
||||
<PackageReference Include="OpenTelemetry.Exporter.OpenTelemetryProtocol" />
|
||||
|
||||
@@ -42,23 +42,15 @@ internal sealed class ClientHeadersAgent : DelegatingAIAgent
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
var snapshot = TrySnapshot(options);
|
||||
if (snapshot is null)
|
||||
if (snapshot is not null)
|
||||
{
|
||||
return this.InnerAgent.RunAsync(messages, session, options, cancellationToken);
|
||||
// AsyncLocal mutations made inside an awaited async method do not leak back to the
|
||||
// caller after the method returns, so we do not need an explicit restore step here.
|
||||
// See ClientHeadersScope remarks.
|
||||
ClientHeadersScope.Current = snapshot;
|
||||
}
|
||||
|
||||
return RunAsyncCoreAsync(messages, session, options, snapshot, cancellationToken);
|
||||
|
||||
async Task<AgentResponse> RunAsyncCoreAsync(
|
||||
IEnumerable<ChatMessage> innerMessages,
|
||||
AgentSession? innerSession,
|
||||
AgentRunOptions? innerOptions,
|
||||
Dictionary<string, string> innerSnapshot,
|
||||
CancellationToken innerCt)
|
||||
{
|
||||
using var _ = ClientHeadersScope.Push(innerSnapshot);
|
||||
return await this.InnerAgent.RunAsync(innerMessages, innerSession, innerOptions, innerCt).ConfigureAwait(false);
|
||||
}
|
||||
return this.InnerAgent.RunAsync(messages, session, options, cancellationToken);
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
@@ -69,7 +61,10 @@ internal sealed class ClientHeadersAgent : DelegatingAIAgent
|
||||
[EnumeratorCancellation] CancellationToken cancellationToken = default)
|
||||
{
|
||||
var snapshot = TrySnapshot(options);
|
||||
using var _ = snapshot is null ? default : ClientHeadersScope.Push(snapshot);
|
||||
if (snapshot is not null)
|
||||
{
|
||||
ClientHeadersScope.Current = snapshot;
|
||||
}
|
||||
|
||||
await foreach (var update in this.InnerAgent.RunStreamingAsync(messages, session, options, cancellationToken).ConfigureAwait(false))
|
||||
{
|
||||
|
||||
@@ -11,39 +11,31 @@ namespace Microsoft.Agents.AI.Foundry;
|
||||
/// <see cref="ClientHeadersPolicy"/> running inside the SCM transport pipeline.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// AsyncLocal flows the value into downstream awaits but does not roll the value back when the
|
||||
/// setting method returns. This type pairs each <see cref="Push(IReadOnlyDictionary{string, string}?)"/>
|
||||
/// with a disposable that explicitly restores the prior value, giving stack-style LIFO semantics
|
||||
/// for nested or sequential per-call scopes on the same async flow.
|
||||
/// <para>
|
||||
/// <see cref="AsyncLocal{T}"/> propagates the value forward into every <c>await</c> on the same
|
||||
/// async flow, but mutations made inside an awaited <c>async</c> method do <em>not</em> leak back
|
||||
/// to the caller after the method returns. This means a method that assigns
|
||||
/// <see cref="Current"/> at the top and then awaits inner work does not need any explicit
|
||||
/// restoration step: the runtime restores the caller's view of the AsyncLocal automatically when
|
||||
/// the method's task completes.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// Setting <see cref="Current"/> from synchronous code, however, will leak to the caller because
|
||||
/// no async-method boundary is crossed. All Agent Framework call sites of this carrier are
|
||||
/// inside <c>async</c> methods (<see cref="ClientHeadersAgent"/>), so the natural restoration
|
||||
/// suffices for our needs.
|
||||
/// </para>
|
||||
/// </remarks>
|
||||
internal static class ClientHeadersScope
|
||||
{
|
||||
private static readonly AsyncLocal<IReadOnlyDictionary<string, string>?> s_current = new();
|
||||
|
||||
/// <summary>Gets the dictionary captured by the most recent <see cref="Push(IReadOnlyDictionary{string, string}?)"/> on this async flow.</summary>
|
||||
public static IReadOnlyDictionary<string, string>? Current => s_current.Value;
|
||||
|
||||
/// <summary>
|
||||
/// Pushes a new value as the current scope. Disposing the returned token restores the previous value.
|
||||
/// Gets or sets the per-async-flow client-header snapshot read by <see cref="ClientHeadersPolicy"/>.
|
||||
/// </summary>
|
||||
/// <param name="headers">The header dictionary to surface to the policy. May be <see langword="null"/>.</param>
|
||||
public static Scope Push(IReadOnlyDictionary<string, string>? headers)
|
||||
public static IReadOnlyDictionary<string, string>? Current
|
||||
{
|
||||
var previous = s_current.Value;
|
||||
s_current.Value = headers;
|
||||
return new Scope(previous);
|
||||
}
|
||||
|
||||
/// <summary>Disposable token that restores the previous scope on <see cref="Dispose"/>.</summary>
|
||||
internal readonly struct Scope : System.IDisposable
|
||||
{
|
||||
private readonly IReadOnlyDictionary<string, string>? _previous;
|
||||
|
||||
internal Scope(IReadOnlyDictionary<string, string>? previous)
|
||||
{
|
||||
this._previous = previous;
|
||||
}
|
||||
|
||||
public void Dispose() => s_current.Value = this._previous;
|
||||
get => s_current.Value;
|
||||
set => s_current.Value = value;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
using System;
|
||||
using System.ClientModel;
|
||||
using System.ClientModel.Primitives;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Threading;
|
||||
@@ -38,7 +39,28 @@ namespace Microsoft.Agents.AI.Foundry;
|
||||
[Experimental(DiagnosticIds.Experiments.AIOpenAIResponses)]
|
||||
public sealed class FoundryAgent : DelegatingAIAgent
|
||||
{
|
||||
private readonly AIProjectClient _aiProjectClient;
|
||||
/// <summary>
|
||||
/// Default OAuth scope for the Azure AI resource. Matches the scope used by
|
||||
/// <c>Azure.AI.Extensions.OpenAI</c>'s internal authentication helper so the bearer token is
|
||||
/// accepted by the Foundry control plane.
|
||||
/// </summary>
|
||||
private const string AzureAiResourceScope = "https://ai.azure.com/.default";
|
||||
|
||||
/// <summary>
|
||||
/// The cached <see cref="AIProjectClient"/> when one was supplied or constructed by the active
|
||||
/// constructor. Null when the agent was constructed via the agent-endpoint constructor, which
|
||||
/// does not build a full <see cref="AIProjectClient"/>.
|
||||
/// </summary>
|
||||
private readonly AIProjectClient? _aiProjectClient;
|
||||
|
||||
/// <summary>
|
||||
/// Project-scoped <see cref="ProjectOpenAIClient"/>. Always non-null. Used for project-level
|
||||
/// operations such as <see cref="CreateConversationSessionAsync(CancellationToken)"/>.
|
||||
/// In agent-endpoint mode this is built directly from the project root derived from the
|
||||
/// supplied agent endpoint; in project-endpoint mode it is the cached client returned by
|
||||
/// <see cref="AIProjectClient"/>.
|
||||
/// </summary>
|
||||
private readonly ProjectOpenAIClient _projectOpenAIClient;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="FoundryAgent"/> class using the direct Responses API path.
|
||||
@@ -72,30 +94,49 @@ public sealed class FoundryAgent : DelegatingAIAgent
|
||||
out var aiProjectClient))
|
||||
{
|
||||
this._aiProjectClient = aiProjectClient;
|
||||
this._projectOpenAIClient = aiProjectClient.GetProjectOpenAIClient();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="FoundryAgent"/> class from an agent-specific endpoint.
|
||||
/// </summary>
|
||||
/// <param name="agentEndpoint">The agent-specific endpoint URI (must contain the agent name in the path).</param>
|
||||
/// <param name="agentEndpoint">
|
||||
/// The agent-specific endpoint URI. Must be of the shape
|
||||
/// <c>https://<host>/.../projects/<project>/agents/<agentName>/endpoint/protocols/openai</c>.
|
||||
/// </param>
|
||||
/// <param name="credential">The authentication credential.</param>
|
||||
/// <param name="clientOptions">Optional configuration options for the <see cref="AIProjectClient"/>.</param>
|
||||
/// <param name="clientOptions">
|
||||
/// Optional configuration for the underlying <see cref="ProjectOpenAIClient"/>. When supplied:
|
||||
/// <list type="bullet">
|
||||
/// <item><description>The instance is passed through to the per-agent client; pipeline policies added via <c>AddPolicy(...)</c> on it execute on the per-agent traffic.</description></item>
|
||||
/// <item><description><c>Endpoint</c> and <see cref="ProjectOpenAIClientOptions.AgentName"/> are owned by this constructor and are overwritten with values derived from <paramref name="agentEndpoint"/>; any caller value is replaced.</description></item>
|
||||
/// <item><description>For the project-level conversations client a separate fresh options bag is built that copies only <see cref="ClientPipelineOptions.RetryPolicy"/>, <see cref="ClientPipelineOptions.NetworkTimeout"/>, <see cref="ClientPipelineOptions.Transport"/>, and <c>UserAgentApplicationId</c>; pipeline policies added via <c>AddPolicy(...)</c> do <strong>not</strong> propagate to the conversations pipeline.</description></item>
|
||||
/// </list>
|
||||
/// </param>
|
||||
/// <param name="tools">Optional tools to use when interacting with the agent.</param>
|
||||
/// <param name="clientFactory">Provides a way to customize the creation of the underlying <see cref="IChatClient"/>.</param>
|
||||
/// <param name="services">Optional service provider for resolving dependencies required by AI functions.</param>
|
||||
/// <exception cref="ArgumentNullException"><paramref name="agentEndpoint"/> or <paramref name="credential"/> is null.</exception>
|
||||
/// <exception cref="ArgumentException"><paramref name="agentEndpoint"/> does not match the expected agent-endpoint shape.</exception>
|
||||
/// <remarks>
|
||||
/// This is the lightweight constructor for invoking an existing Foundry hosted agent when the
|
||||
/// caller already has the per-agent endpoint URL. It populates <see cref="ChatClientAgentOptions.Id"/>
|
||||
/// and <see cref="ChatClientAgentOptions.Name"/> from the agent name parsed out of the endpoint
|
||||
/// path; <c>Description</c>, <c>Instructions</c>, <c>Temperature</c>, and <c>TopP</c> are not
|
||||
/// populated. Callers that need those fields hydrated from server-side state should use
|
||||
/// <c>AIProjectClient.AsAIAgent(ProjectsAgentVersion)</c> or
|
||||
/// <c>AIProjectClient.AsAIAgent(ProjectsAgentRecord)</c> instead.
|
||||
/// </remarks>
|
||||
public FoundryAgent(
|
||||
Uri agentEndpoint,
|
||||
AuthenticationTokenProvider credential,
|
||||
AIProjectClientOptions? clientOptions = null,
|
||||
ProjectOpenAIClientOptions? clientOptions = null,
|
||||
IList<AITool>? tools = null,
|
||||
Func<IChatClient, IChatClient>? clientFactory = null,
|
||||
IServiceProvider? services = null)
|
||||
: base(CreateInnerAgentFromEndpoint(
|
||||
CreateProjectClient(agentEndpoint, credential, clientOptions),
|
||||
agentEndpoint, tools, clientFactory, services,
|
||||
out var aiProjectClient))
|
||||
: base(CreateInnerAgentFromAgentEndpoint(agentEndpoint, credential, clientOptions, tools, clientFactory, services))
|
||||
{
|
||||
this._aiProjectClient = aiProjectClient;
|
||||
this._projectOpenAIClient = CreateProjectLevelOpenAIClientFromAgentEndpoint(agentEndpoint, credential, clientOptions);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -105,6 +146,7 @@ public sealed class FoundryAgent : DelegatingAIAgent
|
||||
: base(WireClientHeaders(Throw.IfNull(innerAgent)))
|
||||
{
|
||||
this._aiProjectClient = Throw.IfNull(aiProjectClient);
|
||||
this._projectOpenAIClient = aiProjectClient.GetProjectOpenAIClient();
|
||||
}
|
||||
|
||||
#region Convenience methods
|
||||
@@ -137,9 +179,7 @@ public sealed class FoundryAgent : DelegatingAIAgent
|
||||
/// <returns>A <see cref="ChatClientAgentSession"/> linked to the newly created server-side conversation.</returns>
|
||||
public async Task<ChatClientAgentSession> CreateConversationSessionAsync(CancellationToken cancellationToken = default)
|
||||
{
|
||||
var conversationsClient = this._aiProjectClient
|
||||
.GetProjectOpenAIClient()
|
||||
.GetProjectConversationsClient();
|
||||
var conversationsClient = this._projectOpenAIClient.GetProjectConversationsClient();
|
||||
|
||||
var conversation = (await conversationsClient.CreateProjectConversationAsync(options: null, cancellationToken).ConfigureAwait(false)).Value;
|
||||
|
||||
@@ -161,6 +201,11 @@ public sealed class FoundryAgent : DelegatingAIAgent
|
||||
return this._aiProjectClient;
|
||||
}
|
||||
|
||||
if (serviceKey is null && serviceType == typeof(ProjectOpenAIClient))
|
||||
{
|
||||
return this._projectOpenAIClient;
|
||||
}
|
||||
|
||||
return base.GetService(serviceType, serviceKey);
|
||||
}
|
||||
|
||||
@@ -238,47 +283,181 @@ public sealed class FoundryAgent : DelegatingAIAgent
|
||||
OpenAIRequestPoliciesReflection.AddPolicyIfMissing(
|
||||
policies,
|
||||
ClientHeadersPolicy.Instance,
|
||||
System.ClientModel.Primitives.PipelinePosition.PerCall);
|
||||
PipelinePosition.PerCall);
|
||||
}
|
||||
|
||||
return new ClientHeadersAgent(innerAgent);
|
||||
}
|
||||
|
||||
private static AIAgent CreateInnerAgentFromEndpoint(
|
||||
AIProjectClient aiProjectClient,
|
||||
/// <summary>
|
||||
/// Builds the inner <see cref="ChatClientAgent"/> for the agent-endpoint constructor by
|
||||
/// constructing a per-agent <see cref="ProjectOpenAIClient"/> via the
|
||||
/// <c>ProjectOpenAIClient(AuthenticationPolicy, ProjectOpenAIClientOptions)</c>
|
||||
/// constructor with <see cref="ProjectOpenAIClientOptions.AgentName"/> set. This routes the
|
||||
/// outbound URL through the per-agent endpoint shape that the Foundry service expects for
|
||||
/// hosted agents and lets the SDK auto-append the <c>api-version</c> query string.
|
||||
/// Caller-supplied <paramref name="clientOptions"/> are passed through to the per-agent
|
||||
/// client with <c>Endpoint</c> and
|
||||
/// <see cref="ProjectOpenAIClientOptions.AgentName"/> overridden by values derived from
|
||||
/// <paramref name="agentEndpoint"/>; any policies the caller added via <c>AddPolicy</c>
|
||||
/// remain in effect on the per-agent pipeline. The MEAI user-agent policy is appended last.
|
||||
/// </summary>
|
||||
private static AIAgent CreateInnerAgentFromAgentEndpoint(
|
||||
Uri agentEndpoint,
|
||||
AuthenticationTokenProvider credential,
|
||||
ProjectOpenAIClientOptions? clientOptions,
|
||||
IList<AITool>? tools,
|
||||
Func<IChatClient, IChatClient>? clientFactory,
|
||||
IServiceProvider? services,
|
||||
out AIProjectClient outClient)
|
||||
IServiceProvider? services)
|
||||
{
|
||||
outClient = aiProjectClient;
|
||||
Throw.IfNull(agentEndpoint);
|
||||
Throw.IfNull(credential);
|
||||
|
||||
AgentReference agentReference = agentEndpoint.Segments[^1].TrimEnd('/');
|
||||
var (agentName, _) = ParseAgentEndpoint(agentEndpoint);
|
||||
|
||||
ChatClientAgentOptions agentOptions = new()
|
||||
{
|
||||
Name = agentReference.Name,
|
||||
ChatOptions = new() { Tools = tools },
|
||||
};
|
||||
var perAgentOptions = clientOptions ?? new ProjectOpenAIClientOptions();
|
||||
perAgentOptions.Endpoint = agentEndpoint;
|
||||
perAgentOptions.AgentName = agentName;
|
||||
perAgentOptions.AddPolicy(RequestOptionsExtensions.UserAgentPolicy, PipelinePosition.PerCall);
|
||||
|
||||
IChatClient chatClient = new AzureAIProjectChatClient(aiProjectClient, agentReference, defaultModelId: null, agentOptions.ChatOptions);
|
||||
var authPolicy = new BearerTokenPolicy(credential, AzureAiResourceScope);
|
||||
var perAgentClient = new ProjectOpenAIClient(authPolicy, perAgentOptions);
|
||||
|
||||
IChatClient chatClient = perAgentClient.GetProjectResponsesClient().AsIChatClient();
|
||||
if (clientFactory is not null)
|
||||
{
|
||||
chatClient = clientFactory(chatClient);
|
||||
}
|
||||
|
||||
ChatClientAgentOptions agentOptions = new()
|
||||
{
|
||||
Id = agentName,
|
||||
Name = agentName,
|
||||
ChatOptions = new() { Tools = tools },
|
||||
};
|
||||
|
||||
return WireClientHeaders(new ChatClientAgent(chatClient, agentOptions, services: services));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds the project-scoped <see cref="ProjectOpenAIClient"/> for the agent-endpoint
|
||||
/// constructor by deriving the project root from the supplied agent endpoint and constructing
|
||||
/// a fresh client without <see cref="ProjectOpenAIClientOptions.AgentName"/> so the SDK
|
||||
/// appends the standard <c>/openai/v1</c> suffix expected for project-level surfaces such as
|
||||
/// conversations.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Only the four observable primitive properties (<see cref="ClientPipelineOptions.RetryPolicy"/>,
|
||||
/// <see cref="ClientPipelineOptions.NetworkTimeout"/>, <see cref="ClientPipelineOptions.Transport"/>,
|
||||
/// and <c>UserAgentApplicationId</c>) are copied from the caller's options bag. Pipeline
|
||||
/// policies added via <c>AddPolicy</c> on the caller bag do not propagate because
|
||||
/// <see cref="ClientPipelineOptions"/> does not publicly enumerate its policies. The MEAI
|
||||
/// user-agent policy is appended last.
|
||||
/// </remarks>
|
||||
private static ProjectOpenAIClient CreateProjectLevelOpenAIClientFromAgentEndpoint(
|
||||
Uri agentEndpoint,
|
||||
AuthenticationTokenProvider credential,
|
||||
ProjectOpenAIClientOptions? clientOptions)
|
||||
{
|
||||
var (_, projectRoot) = ParseAgentEndpoint(agentEndpoint);
|
||||
|
||||
var projectOptions = new ProjectOpenAIClientOptions();
|
||||
if (clientOptions is not null)
|
||||
{
|
||||
if (clientOptions.RetryPolicy is not null)
|
||||
{
|
||||
projectOptions.RetryPolicy = clientOptions.RetryPolicy;
|
||||
}
|
||||
|
||||
if (clientOptions.NetworkTimeout is not null)
|
||||
{
|
||||
projectOptions.NetworkTimeout = clientOptions.NetworkTimeout;
|
||||
}
|
||||
|
||||
if (clientOptions.Transport is not null)
|
||||
{
|
||||
projectOptions.Transport = clientOptions.Transport;
|
||||
}
|
||||
|
||||
if (!string.IsNullOrEmpty(clientOptions.UserAgentApplicationId))
|
||||
{
|
||||
projectOptions.UserAgentApplicationId = clientOptions.UserAgentApplicationId;
|
||||
}
|
||||
}
|
||||
|
||||
projectOptions.AddPolicy(RequestOptionsExtensions.UserAgentPolicy, PipelinePosition.PerCall);
|
||||
|
||||
return new ProjectOpenAIClient(projectRoot, credential, projectOptions);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Parses an agent endpoint URI of shape
|
||||
/// <c>https://<host>/.../projects/<project>/agents/<agentName>/endpoint/protocols/openai</c>
|
||||
/// and returns the agent name and the derived project-root URI.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Single source of truth for both agent-name extraction and project-root derivation.
|
||||
/// Tolerates trailing slash, casing variants on <c>/agents/</c> and the suffix segment, and
|
||||
/// strips query string and fragment. Throws <see cref="ArgumentException"/> for inputs that
|
||||
/// do not match the expected shape.
|
||||
/// </remarks>
|
||||
/// <exception cref="ArgumentException">
|
||||
/// The endpoint is missing the <c>/agents/</c> segment, has an empty agent name, or has a
|
||||
/// suffix other than <c>/endpoint/protocols/openai</c>.
|
||||
/// </exception>
|
||||
internal static (string AgentName, Uri ProjectRoot) ParseAgentEndpoint(Uri agentEndpoint)
|
||||
{
|
||||
Throw.IfNull(agentEndpoint);
|
||||
|
||||
const string AgentsSegment = "/agents/";
|
||||
const string ExpectedSuffix = "/endpoint/protocols/openai";
|
||||
|
||||
var path = agentEndpoint.AbsolutePath.TrimEnd('/');
|
||||
var idx = path.IndexOf(AgentsSegment, StringComparison.OrdinalIgnoreCase);
|
||||
if (idx < 0)
|
||||
{
|
||||
throw new ArgumentException(
|
||||
$"Expected an agent endpoint of shape 'https://<host>/.../projects/<project>/agents/<agentName>/endpoint/protocols/openai' but got '{agentEndpoint}'. " +
|
||||
"If you want to construct a FoundryAgent against a project endpoint, use the (Uri projectEndpoint, AuthenticationTokenProvider credential, string model, string instructions, ...) constructor instead.",
|
||||
nameof(agentEndpoint));
|
||||
}
|
||||
|
||||
var afterAgents = path.Substring(idx + AgentsSegment.Length);
|
||||
var nextSlash = afterAgents.IndexOf('/');
|
||||
if (nextSlash <= 0)
|
||||
{
|
||||
throw new ArgumentException(
|
||||
$"Agent endpoint '{agentEndpoint}' is missing the '<agentName>{ExpectedSuffix}' suffix.",
|
||||
nameof(agentEndpoint));
|
||||
}
|
||||
|
||||
var agentName = afterAgents.Substring(0, nextSlash);
|
||||
var suffix = afterAgents.Substring(nextSlash);
|
||||
if (!string.Equals(suffix, ExpectedSuffix, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
throw new ArgumentException(
|
||||
$"Agent endpoint '{agentEndpoint}' has an unexpected suffix '{suffix}'. Expected '{ExpectedSuffix}'.",
|
||||
nameof(agentEndpoint));
|
||||
}
|
||||
|
||||
var rootPath = path.Substring(0, idx);
|
||||
var projectRoot = new UriBuilder(agentEndpoint)
|
||||
{
|
||||
Path = rootPath,
|
||||
Query = string.Empty,
|
||||
Fragment = string.Empty,
|
||||
}.Uri;
|
||||
|
||||
return (agentName, projectRoot);
|
||||
}
|
||||
|
||||
private static AIProjectClient CreateProjectClient(Uri endpoint, AuthenticationTokenProvider credential, AIProjectClientOptions? clientOptions = null)
|
||||
{
|
||||
Throw.IfNull(endpoint);
|
||||
Throw.IfNull(credential);
|
||||
|
||||
clientOptions ??= new AIProjectClientOptions();
|
||||
clientOptions.AddPolicy(RequestOptionsExtensions.UserAgentPolicy, System.ClientModel.Primitives.PipelinePosition.PerCall);
|
||||
clientOptions.AddPolicy(RequestOptionsExtensions.UserAgentPolicy, PipelinePosition.PerCall);
|
||||
return new AIProjectClient(endpoint, credential, clientOptions);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,7 +1,10 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<IsReleased>true</IsReleased>
|
||||
<!-- Preview while we depend on Azure.AI.Projects 2.1.0-beta.1 for hosted-agent routing
|
||||
(ProjectOpenAIClientOptions.AgentName, the (AuthenticationPolicy, options) ctor, and
|
||||
related per-agent endpoint surface). Flip back to IsReleased=true once Azure.AI.Projects
|
||||
ships a stable 2.1.0. -->
|
||||
<InjectSharedThrow>true</InjectSharedThrow>
|
||||
<NoWarn>$(NoWarn);OPENAI001</NoWarn>
|
||||
</PropertyGroup>
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
// Copyright (c) Microsoft. All rights reserved.
|
||||
|
||||
using System;
|
||||
using System.Globalization;
|
||||
|
||||
namespace Microsoft.Agents.AI.Tools.Shell;
|
||||
|
||||
/// <summary>
|
||||
/// UID/GID pair passed to <c>docker run --user</c>.
|
||||
/// </summary>
|
||||
/// <param name="Uid">User ID (numeric string, e.g. <c>"65534"</c>; <c>"root"</c> or <c>"0"</c> selects the container's root user).</param>
|
||||
/// <param name="Gid">Group ID (numeric string).</param>
|
||||
public sealed record ContainerUser(string Uid, string Gid)
|
||||
{
|
||||
/// <summary>
|
||||
/// Default unprivileged user (<c>nobody:nogroup</c> on most distros, UID/GID 65534).
|
||||
/// </summary>
|
||||
public static ContainerUser Default { get; } = new("65534", "65534");
|
||||
|
||||
/// <summary>
|
||||
/// Container root (UID/GID 0). Avoid in production; use only for diagnostics.
|
||||
/// </summary>
|
||||
public static ContainerUser Root { get; } = new("0", "0");
|
||||
|
||||
/// <summary>Render as the <c>uid:gid</c> string Docker expects.</summary>
|
||||
public override string ToString() => $"{this.Uid}:{this.Gid}";
|
||||
|
||||
/// <summary>
|
||||
/// Returns <see langword="true"/> when this user maps to UID 0 (root).
|
||||
/// </summary>
|
||||
public bool IsRoot =>
|
||||
this.Uid.Equals("root", StringComparison.OrdinalIgnoreCase)
|
||||
|| (int.TryParse(this.Uid, NumberStyles.Integer, CultureInfo.InvariantCulture, out var uid) && uid == 0);
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user